python-PyPDF2复制后返回空白PDF
作者:互联网
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))))
我将跟随Python的“无聊的东西自动化”部分.在为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-3-x,pypdf2,python 来源: https://codeday.me/bug/20191111/2018898.html