我正在尝试使用 python 对 pdf 文件进行密码保护。 我遇到过使用 PyPDF2 库的解决方案,但该解决方案不适用于 3.0.0 或更高版本。
下面是代码
# import PdfFileWriter and PdfFileReader
# class from PyPDF2 library
from PyPDF2 import PdfFileWriter, PdfFileReader
# create a PdfFileWriter object
out = PdfFileWriter()
# Open our PDF file with the PdfFileReader
file = PdfFileReader("myfile.pdf")
# Get number of pages in original file
num = file.numPages
# Iterate through every page of the original
# file and add it to our new file.
for idx in range(num):
# Get the page at index idx
page = file.getPage(idx)
# Add it to the output file
out.addPage(page)
# Create a variable password and store
# our password in it.
password = "pass"
# Encrypt the new file with the entered password
out.encrypt(password)
# Open a new file "myfile_encrypted.pdf"
with open("myfile_encrypted.pdf", "wb") as f:
# Write our encrypted PDF to this file
out.Write(f)
如果有人可以帮助我解决问题,那将会很有帮助。
谢谢你
他们已经弃用了很多东西。对于 PyPDF2 版本 3 及更高版本,请使用:
from PyPDF2 import PdfWriter, PdfReader
output = PdfWriter() # create a PdfWriter object
pdf_file = PdfReader("test.pdf") # test.pdf is the pdf you want to protect
numPages = len(pdf_file.pages)
# grab each page in pdf
for i in range(numPages):
page = pdf_file.pages[i]
output.add_page(page) # Add to the output object
output.encrypt("pass") # Encrypt output with password "pass"
# output actual encrypted binary pdf
with open("test_encrypted.pdf", "wb") as f:
output.write(f)
希望这有帮助!