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

Python 3.X无法获取PDF页数:PyCryptodome依赖错误求助

问题:PDF页数校验时遇AES加密文件触发依赖错误

我在对从URL下载的文件做数据校验,其中一项是检查PDF页数。原本用PyPDF2的PdfFileReader模块可以正常实现,但遇到一个256-bit AES加密、仅有权限密码无文档打开密码的PDF时出了问题。因为文件来自厂商网站,拿不到密码,所以打算先判断PDF是否加密,加密就暂时跳过,但不管是获取页数还是检查加密状态,都会触发以下错误:

DependencyError: PyCryptodome is required for AES algorithm

错误出现在代码第6行的if语句处。

我已经安装了pycryptodome并导入了AES模块,使用的是Jupyter Notebook,但问题依然存在。原代码如下:

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

改用pikepdf库可以绕过这个问题,无需密码就能读取该类加密PDF的页数,代码如下:

! pip install pikepdf 
from pikepdf import Pdf  
pdf = Pdf.open('Media Downloaded Files/spk-10-3144-bro.pdf') 
len(pdf.pages)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 14:01:12