你(就像我一样)一定想过——WTF"-3904"
来自凯文的answer https://stackoverflow.com/a/36016018/7797962.
请放心 - 我有答案)。
我在 PDF 1.6 参考中找到了它。你可以在这里得到它:https://www.adobe.com/content/dam/acom/en/devnet/pdf/pdf_reference_archive/PDFReference16.pdf https://www.adobe.com/content/dam/acom/en/devnet/pdf/pdf_reference_archive/PDFReference16.pdf
3.5节,第99页:
32 位整数,包含一组指定哪个访问的标志
当用户打开文档时应授予权限
使用权。表 3.20 显示了这些标志的含义。位位置
标志字内的编号从 1(低位)到 32
(高阶)。任意位置的 1 位启用相应的访问
允许。哪些位是有意义的,以及在某些情况下它们是如何有意义的
解释,取决于安全处理程序的修订号
(在加密字典的 R 条目中指定)。
*注意:PDF 整数对象在内部以带符号的二进制补码形式表示。由于所有保留的高阶标志位
加密字典的P值要求为1,该值
必须指定为负整数。例如,假设
安全处理程序的修订版 2,值 -44 允许打印和
复制但不允许修改内容和注释。
So, P
是许可!请检查该文件中的表格。-44
is 11010100
以位表示。
我是这样写的(允许打印和复制,但不允许修改内容和注释):
from hashlib import md5
from PyPDF4 import PdfFileReader, PdfFileWriter
from PyPDF4.generic import NameObject, DictionaryObject, ArrayObject, \
NumberObject, ByteStringObject
from PyPDF4.pdf import _alg33, _alg34, _alg35
from PyPDF4.utils import b_
def encrypt(writer_obj: PdfFileWriter, user_pwd, owner_pwd=None, use_128bit=True):
"""
Encrypt this PDF file with the PDF Standard encryption handler.
:param str user_pwd: The "user password", which allows for opening
and reading the PDF file with the restrictions provided.
:param str owner_pwd: The "owner password", which allows for
opening the PDF files without any restrictions. By default,
the owner password is the same as the user password.
:param bool use_128bit: flag as to whether to use 128bit
encryption. When false, 40bit encryption will be used. By default,
this flag is on.
"""
import time, random
if owner_pwd == None:
owner_pwd = user_pwd
if use_128bit:
V = 2
rev = 3
keylen = int(128 / 8)
else:
V = 1
rev = 2
keylen = int(40 / 8)
# permit copy and printing only:
P = -44
O = ByteStringObject(_alg33(owner_pwd, user_pwd, rev, keylen))
ID_1 = ByteStringObject(md5(b_(repr(time.time()))).digest())
ID_2 = ByteStringObject(md5(b_(repr(random.random()))).digest())
writer_obj._ID = ArrayObject((ID_1, ID_2))
if rev == 2:
U, key = _alg34(user_pwd, O, P, ID_1)
else:
assert rev == 3
U, key = _alg35(user_pwd, rev, keylen, O, P, ID_1, False)
encrypt = DictionaryObject()
encrypt[NameObject("/Filter")] = NameObject("/Standard")
encrypt[NameObject("/V")] = NumberObject(V)
if V == 2:
encrypt[NameObject("/Length")] = NumberObject(keylen * 8)
encrypt[NameObject("/R")] = NumberObject(rev)
encrypt[NameObject("/O")] = ByteStringObject(O)
encrypt[NameObject("/U")] = ByteStringObject(U)
encrypt[NameObject("/P")] = NumberObject(P)
writer_obj._encrypt = writer_obj._addObject(encrypt)
writer_obj._encrypt_key = key
unmeta = PdfFileReader('my_pdf.pdf')
writer = PdfFileWriter()
writer.appendPagesFromReader(unmeta)
encrypt(writer, '1', '123')
with open('my_pdf_encrypted.pdf', 'wb') as fp:
writer.write(fp)
如果您喜欢我的回答,请投票;)。