2
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 Automating the Boring Stuffセクションに従っています。私は、PDF文書のコピーを行う際に問題を抱えていましたが、プログラムを実行するたびに、コピーされたPDFはすべて空のページです。新しく暗号化されたPDFの正しいページ数がありますが、それらはすべて空白です(ページにはコンテンツがありません)。私はこれを前に起こしたが、再現できなかった。私は私のファイルを閉じる前に眠りに投げてみました。ファイルを開いたり閉じたりするベストプラクティスがPythonでどういうものか分かりません。私はPython3を使っています。コピー後の空白PDFを返すPyPDF2
ありがとうございます。これは機能しているようです(特定の例ではゴミ箱に送信する前に閉じていなければなりません)。あなたは間違いなく、pdfWriterが書いて閉じてしまうまでpdfReaderを開いたままにする必要があるという点で正しいと思われます。私は、 "getPage"関数が作家に必要なすべての情報を作成したという誤った仮定をしていたと思います。あなたがそこからページオブジェクトを保存していても、ライターが依然としてオープンされているリーダーに依存している場合、それは直感的ではないようです。 もう一度おねがいします! – stryker14