You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PyPDF2批量为PDF设密码遇依赖错误,求解决方案

问题:批量给PDF设置密码时遇到PyPDF2依赖错误

我有数百份PDF文件需要设置密码,尝试使用PyPDF2实现该功能时,在执行代码行input_pdf = PdfFileReader(in_file)时触发错误:"DependencyError: PyCryptodome is required for AES algorithm"。我曾搜索pikepdf等其他模块,但仅找到其破解密码的方法,未发现设置密码的相关操作,请问该如何解决此问题?

以下是我的代码:

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)
解决方案

方法一:修复PyPDF2的依赖问题

  • 错误提示明确要求安装PyCryptodome库,执行以下命令安装:
    pip install pycryptodome
    
  • 若你的PyPDF2版本较旧,可能存在兼容性问题,建议同步升级到最新版:
    pip install --upgrade pypdf2
    
  • 安装完成后,原代码即可正常运行。

方法二:使用pikepdf批量加密PDF(更稳定)

pikepdf支持PDF加密功能,并非仅用于破解,以下是适配你需求的批量加密代码:

import pikepdf
import pandas as pd

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

for _, row in df.iterrows():
    filename = row['PDF']
    password = row['Password']
    
    # 打开PDF文件并设置加密参数
    with pikepdf.open(filename) as pdf:
        # 保存加密后的文件,user参数为打开PDF需要输入的密码
        pdf.save(filename, encryption=pikepdf.Encryption(user=password))
  • 先安装pikepdf依赖:
    pip install pikepdf
    
  • 优势:pikepdf对现代PDF格式兼容性更强,加密过程更稳定,还可额外设置所有者密码、打印/编辑权限等参数。

内容的提问来源于stack exchange,提问作者rammbb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 20:05:28