gpt4 book ai didi

python - PyPDF2 复制后返回空白 PDF

转载 作者:太空宇宙 更新时间:2023-11-03 15:54:32 26 4
gpt4 key购买 nike

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。

最佳答案

尝试将 pdfFile.close 移动到 for 循环的末尾。

for pdf in pdfFiles:
#
# {stuff}
#
if (canDecrypt):
print("%s successfully encrypted." % (pdf))
send2trash.send2trash(pdf)
success += 1

pdfFile.close()

想法是当 pdfWriter 最终写出时 pdfFile 需要可用并打开,否则它无法访问页面以写入新文件。

关于python - PyPDF2 复制后返回空白 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44375872/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com