我有一些正在对pdf进行加密的代码,由于某种原因,一旦我对pdf进行加密,文字就会挂起。如果我将pdf_writer.encrypt(password)
注释掉,就没有问题,并且一切编写正确。我曾尝试以最高权限运行脚本并修改文件夹选项,但也许我缺少一些简单的东西。
with open(filename, 'rb') as pdf_file:
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
pdf_writer = PyPDF2.PdfFileWriter()
for page_number in range(pdf_reader.numPages):
pdf_writer.addPage(pdf_reader.getPage(page_number))
pdf_writer.encrypt(password)
filename_encrypted = filename.parents[0] / f "{filename.stem}_encrypted.pdf"
with open(filename_encrypted, 'wb') as pdf_file_encrypted:
pdf_writer.write(pdf_file_encrypted)
任何帮助将不胜感激。
答案 0 :(得分:0)
我不知道为什么PyPDF2无法正常工作,所以我只是尝试了另一个名为pikepdf的模块,所以一切正常。无论如何,这实际上似乎比PyPDF2更好。
import pikepdf
filename = pathlib.Path(r"path\to\pdf\test.pdf")
password = 'password'
with Pdf.open(filename) as pdf:
filename_encrypted = filename.parents[0] / f"{filename.stem}_encrypted.pdf"
pdf.save(filename_encrypted, encryption=Encryption(user=password, owner=password))