首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >PyPDF2错误“AES算法需要PyCryptodome”

PyPDF2错误“AES算法需要PyCryptodome”
EN

Stack Overflow用户
提问于 2022-09-13 09:59:00
回答 2查看 1.2K关注 0票数 2

我有数百个PDF,我需要设置密码。我试图使用pyPDF2来实现这一点,但是我得到了一个错误:"DependencyError: PyCryptodome是AES算法所必需的“。

我尝试过谷歌任何其他模块,如pikepdf,但我只找到了如何破解密码使用它,而不是实际设置密码。

有什么办法处理吗?在这一行中我得到了一个错误:"input_pdf = PdfFileReader(in_file)

代码语言:javascript
运行
复制
file = directory + '\\passwords.xlsx'  

df = pd.read_excel(file)
df['PDF'] = df.iloc[:,[0]] + '.pdf'

df = df.to_dict('records')
for i in df:
    filename = i['PDF']
    password = i['Password']

    with open(filename, "rb") as in_file:
        input_pdf = PdfFileReader(in_file)

    output_pdf = PdfFileWriter()
    output_pdf.appendPagesFromReader(input_pdf)
    output_pdf.encrypt(password)

    with open(filename, "wb") as out_file:
        output_pdf.write(out_file)
EN

回答 2

Stack Overflow用户

发布于 2022-09-13 10:44:50

A.)做这件事的好方法:

https://roytuts.com/how-to-encrypt-pdf-as-password-protected-file-in-python/

代码语言:javascript
运行
复制
import PyPDF2

#pdf_in_file = open("simple.pdf",'rb')
pdf_in_file = open("gre_research_validity_data.pdf",'rb')

inputpdf = PyPDF2.PdfFileReader(pdf_in_file)
pages_no = inputpdf.numPages
output = PyPDF2.PdfFileWriter()

for i in range(pages_no):
    inputpdf = PyPDF2.PdfFileReader(pdf_in_file)
    
    output.addPage(inputpdf.getPage(i))
    output.encrypt('password')

    #with open("simple_password_protected.pdf", "wb") as outputStream:
    with open("gre_research_validity_data_password_protected.pdf", "wb") as outputStream:
        output.write(outputStream)

pdf_in_file.close()

B.)如果您想修复自己的bug:

类似错误消息的解决方案,但在计算页面时- Not able to find number of pages of PDF using Python 3.X: DependencyError: PyCryptodome is required for AES algorithm

原码

代码语言:javascript
运行
复制
! pip install PyPDF2
! pip install pycryptodome
from PyPDF2 import PdfFileReader
from Crypto.Cipher import AES

if PdfFileReader('Media Downloaded Files/spk-10-3144 bro.pdf').isEncrypted:
    print('This file is encrypted.')
else:
    print(PdfFileReader('Media Downloaded Files/spk-10-3144-bro.pdf').numPages)

修复

代码语言:javascript
运行
复制
! pip install pikepdf 
from pikepdf import Pdf  
pdf = Pdf.open('Media Downloaded Files/spk-10-3144-bro.pdf') 
len(pdf.pages)
票数 0
EN

Stack Overflow用户

发布于 2022-10-31 19:42:59

我也有同样的问题。

您只需安装PyCryptodome包即可。

例如:

代码语言:javascript
运行
复制
pip install pycryptodome==3.15.0
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73701005

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档