在Python中,对多个pdf中的一个进行解密,以便组合成一个

2024-10-03 23:25:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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()

谢谢


Tags: 文件代码in文件夹密码forpdfos
1条回答
网友
1楼 · 发布于 2024-10-03 23:25:32

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

如果解密失败,^{}方法不会引发异常;它返回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。在

相关问题 更多 >