如果与使用 AES 的 PDF 交互,请参阅安装指南中的说明以安装额外的依赖项。
加密
为 PDF 添加密码(加密):
from PyPDF2 import PdfReader, PdfWriter
reader = PdfReader("example.pdf")
writer = PdfWriter()
# Add all pages to the writer
for page in reader.pages:
writer.add_page(page)
# Add a password to the new PDF
writer.encrypt("my-secret-password")
# Save the new PDF to a file
with open("encrypted-pdf.pdf", "wb") as f:
writer.write(f)
解密
从 PDF 中删除密码(解密):
from PyPDF2 import PdfReader, PdfWriter
reader = PdfReader("encrypted-pdf.pdf")
writer = PdfWriter()
if reader.is_encrypted:
reader.decrypt("my-secret-password")
# Add all pages to the writer
for page in reader.pages:
writer.add_page(page)
# Save the new PDF to a file
with open("decrypted-pdf.pdf", "wb") as f:
writer.write(f)
更多建议: