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

使用PyInstaller打包含pypdfium2的Python脚本为exe时加载pdfium失败

解决pypdfium2新版(2024年5月后)PyInstaller打包exe加载pdfium失败的问题

问题重现

Python脚本直接运行正常,PyInstaller打包为exe后报错:

Traceback (most recent call last):
File "app.py", line 3, in
File "PyInstaller\loader\pyimod02_importers.py", line 419, in exec_module
File "pypdfium2_init_.py", line 7, in
File "PyInstaller\loader\pyimod02_importers.py", line 419, in exec_module
File "pypdfium2_helpers_init_.py", line 4, in
File "PyInstaller\loader\pyimod02_importers.py", line 419, in exec_module
File "pypdfium2_helpers\unsupported.py", line 8, in
File "PyInstaller\loader\pyimod02_importers.py", line 419, in exec_module
File "pypdfium2\raw.py", line 495, in
File "pypdfium2\raw.py", line 183, in call
ImportError: Could not load pdfium.
[10640] Failed to execute script 'app' due to unhandled exception!

原因是新版pypdfium2调整了内部结构,pdfium二进制库的存放路径变更,PyInstaller默认未打包相关文件。

可行解决方案

方法1:使用PyInstaller的--collect-all参数(推荐)

这个参数会自动收集pypdfium2包下的所有依赖文件(包括pdfium二进制库),无需手动指定路径:

pyinstaller --collect-all pypdfium2 your_script.py

方法2:手动添加二进制库路径

如果方法1失效,可手动指定pdfium二进制文件的打包路径:

  1. 找到你的Python环境中pypdfium2的安装目录,比如Windows下通常是Lib\site-packages\pypdfium2,其中_libs子目录下存放着pdfium.dll(Windows)、libpdfium.so(Linux)或libpdfium.dylib(macOS)。
  2. 使用--add-data参数打包:
    • Windows系统:
      pyinstaller --add-data "Lib\site-packages\pypdfium2\_libs\pdfium.dll;pypdfium2/_libs" your_script.py
      
    • Linux/macOS系统:
      pyinstaller --add-data "Lib/site-packages/pypdfium2/_libs/libpdfium.so:pypdfium2/_libs" your_script.py
      

方法3:通过.spec文件配置

若需自定义打包细节,可生成并修改.spec文件:

  1. 生成.spec文件:
    pyi-makespec your_script.py
    
  2. 打开生成的your_script.spec,在datas列表中添加pdfium库的路径映射:
    datas=[
        # Windows示例
        ('Lib\\site-packages\\pypdfium2\\_libs\\pdfium.dll', 'pypdfium2/_libs'),
        # Linux/macOS示例,替换为对应文件名
        # ('Lib/site-packages/pypdfium2/_libs/libpdfium.so', 'pypdfium2/_libs'),
    ],
    
  3. 用.spec文件打包:
    pyinstaller your_script.spec
    

验证

打包完成后,进入dist目录运行生成的exe文件,即可正常加载pdfium库执行脚本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 19:43:09