我正在使用Python将一个文件夹下的许多PDF合并成一个PDF。但是我知道其中一个PDF有密码,所以我需要解密,密码是:rosebud。在
我想我的代码真的解密了这个文件,而我在这个文件夹中的所有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()
谢谢
很可能你的代码没有真正解密文件。在
如果解密失败,^{} 方法不会引发异常;它返回
0
。因为您忽略了返回值,所以您无法知道它是否实际成功。在如果解密失败,当您稍后尝试读取文件时,您将得到一个
PyPDF2.utils.PdfReadError: File has not been decrypted
。在您应该更改代码以执行以下操作:
当然,要真正解决这个问题,您需要使用正确的密码来解密pdf。在
相关问题 更多 >
编程相关推荐