解密多个PDF中的一个,以便在Python中合并为一个PDF
我正在使用Python将一个文件夹下的许多PDF合并成一个PDF。但是我知道其中一个PDF有密码,所以我需要解密它,密码是:rosebud 我认为我的代码在循环遍历该文件夹中的所有PDF文件时确实解密了该文件,但我不断收到错误:PyPDF2.utils.PdfReadError:文件尚未解密 我的代码:解密多个PDF中的一个,以便在Python中合并为一个PDF,python,pypdf2,Python,Pypdf2,我正在使用Python将一个文件夹下的许多PDF合并成一个PDF。但是我知道其中一个PDF有密码,所以我需要解密它,密码是:rosebud 我认为我的代码在循环遍历该文件夹中的所有PDF文件时确实解密了该文件,但我不断收到错误:PyPDF2.utils.PdfReadError:文件尚未解密 我的代码: import PyPDF2, os pdfFiles=[] pdfFiles = [filename for filename in os.listdir('.') if filename.e
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:文件尚未解密
您应该更改代码以执行以下操作:
if pdfReader.isEncrypted:
decrypt = pdfReader.decrypt('rosebud')
if decrypt == 0:
# print a warning and skip the file? raise an exception?
当然,要真正解决这个问题,您需要使用正确的密码来解密PDF。很可能您的代码没有真正解密文件
如果解密失败,该方法不会引发异常;它返回0
。由于您忽略了该返回值,因此无法知道它是否实际成功
如果解密失败,当您稍后尝试读取该文件时,将得到一个PyPDF2.utils.PdfReadError:文件尚未解密
您应该更改代码以执行以下操作:
if pdfReader.isEncrypted:
decrypt = pdfReader.decrypt('rosebud')
if decrypt == 0:
# print a warning and skip the file? raise an exception?
当然,要真正解决这个问题,您需要使用正确的密码来解密PDF