解密许多PDF中的一个,以便在Python中合并为一个



我正在使用Python将一个文件夹下的许多PDF合并为一个PDF。但是我知道其中一个PDF有密码,所以我需要解密它,密码是:玫瑰花蕾。

我认为我的代码在循环浏览此文件夹中的所有PDF文件时确实解密了此文件,但是我不断收到错误:PyPDF2.utils.PdfReadError:文件尚未解密。

我的代码:

import PyPDF2, os
pdfFiles=[]
pdfFiles = [filename for filename in os.listdir('.') if filename.endswith('.pdf')]   
pdfFiles.sort(key=str.lower)
pdfwriter=PyPDF2.PdfFileWriter()

#loop through all the PDF file
for filename in pdfFiles:
pdfReader=PyPDF2.PdfFileReader(open(filename,'rb'))
if pdfReader.isEncrypted:
pdfReader.decrypt('rosebud')
#all page except first:0
for pagenum in range(1,pdfReader.numPages):
pageObj=pdfReader.getPage(pagenum)
pdfwriter.addPage(pageObj)
pdfoutput=open('allmyfile.pdf','wb')
pdfwriter.write(pdfoutput)
pdfoutput.close()

谢谢

很可能你的代码并没有真正解密文件。

如果解密失败,decrypt方法不会引发异常;它会返回0。由于您忽略了该返回值,因此您无法知道它是否真的成功了。

如果解密失败,稍后尝试读取文件时将获得PyPDF2.utils.PdfReadError: File has not been decrypted

您应该更改代码以执行以下操作:

if pdfReader.isEncrypted:
decrypt = pdfReader.decrypt('rosebud')
if decrypt == 0:
# print a warning and skip the file? raise an exception?

当然,要实际解决问题,您需要使用正确的密码来解密PDF。

相关内容

最新更新