def EncryptPDFFiles(password, directory):
pdfFiles = []
success = 0
# Get all PDF files from a directory
for folderName, subFolders, fileNames in os.walk(directory):
for fileName in fileNames:
if (fileName.endswith(".pdf")):
pdfFiles.append(os.path.join(folderName, fileName))
print("%s PDF documents found." % str(len(pdfFiles)))
# Create an encrypted version for each document
for pdf in pdfFiles:
# Copy old PDF into a new PDF object
pdfFile = open(pdf,"rb")
pdfReader = PyPDF2.PdfFileReader(pdfFile)
pdfWriter = PyPDF2.PdfFileWriter()
for pageNum in range(pdfReader.numPages):
pdfWriter.addPage(pdfReader.getPage(pageNum))
pdfFile.close()
# Encrypt the new PDF and save it
saveName = pdf.replace(".pdf",ENCRYPTION_TAG)
pdfWriter.encrypt(password)
newFile = open(saveName, "wb")
pdfWriter.write(newFile)
newFile.close()
print("%s saved to: %s" % (pdf, saveName))
# Verify the the encrypted PDF encrypted properly
encryptedPdfFile = open(saveName,"rb")
encryptedPdfReader = PyPDF2.PdfFileReader(encryptedPdfFile)
canDecrypt = encryptedPdfReader.decrypt(password)
encryptedPdfFile.close()
if (canDecrypt):
print("%s successfully encrypted." % (pdf))
send2trash.send2trash(pdf)
success += 1
print("%s of %s successfully encrypted." % (str(success),str(len(pdfFiles))))
我正在跟随 Pythons Automate the Boring Stuff 部分。我在为 PDF 文档进行复制时遇到过问题,但到目前为止,每次我运行该程序时,我复制的 PDF 都是空白页。我新加密的 PDF 有正确数量的页面,但它们都是空白的(页面上没有内容)。我以前发生过这种情况,但无法重新创建。在关闭我的文件之前,我尝试过进入睡眠状态。我不确定在 Python 中打开和关闭文件的最佳做法是什么。作为参考,我使用的是 Python3。