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

使用PyPDF2添加附件后PDF无法打开的问题求助

PyPDF2添加PDF附件后Adobe无法打开的问题解决

问题原因

  • PyPDF2版本bug:旧版本的PyPDF2在处理附件添加时,没有正确维护PDF的根字典结构,导致生成的PDF缺少Adobe Reader必需的根对象定义,触发"root object is missing or invalid"错误。
  • 错误的文件写入模式:第三版代码里用了ab(追加二进制)模式写输出文件,这种操作会把新PDF数据追加到原有文件后面,直接破坏了PDF的完整结构,必然导致读取报错。
  • 附件关联逻辑缺陷:部分PyPDF2版本在添加附件时,没有正确将附件信息关联到文档的结构字典中,导致Adobe Reader解析时找不到期望的字典对象,抛出"There was an error opening this document. There was a problem reading this document(14). Expected a dict object."错误。

解决方法

1. 升级PyPDF2到最新版

旧版本的PyPDF2存在大量PDF结构处理的bug,升级到最新稳定版能修复绝大多数已知问题:

pip install --upgrade PyPDF2

然后使用修正后的代码(注意用正确的写入模式):

from PyPDF2 import PdfReader, PdfWriter

# 读取源PDF文件
with open('Closeout.pdf', 'rb') as source_file:
    pdf_reader = PdfReader(source_file)
    pdf_writer = PdfWriter()
    
    # 复制源PDF的所有页面
    for page in pdf_reader.pages:
        pdf_writer.add_page(page)
    
    # 读取要添加的附件内容
    with open('input0.pdf', 'rb') as attachment_file:
        attachment_data = attachment_file.read()
    
    # 添加附件
    pdf_writer.add_attachment('input0.pdf', attachment_data)
    
    # 写入输出PDF(必须用wb模式,覆盖写入)
    with open('output_with_attachment.pdf', 'wb') as output_file:
        pdf_writer.write(output_file)

2. 换用PyMuPDF(fitz)处理

如果升级PyPDF2后问题依旧,推荐使用PyMuPDF,它对PDF结构的处理更稳定,兼容性更好:

pip install pymupdf

实现代码:

import fitz

# 打开源PDF
pdf_doc = fitz.open('Closeout.pdf')

# 读取附件文件的二进制内容
with open('input0.pdf', 'rb') as att_file:
    att_content = att_file.read()

# 添加附件,可自定义显示文件名和描述
pdf_doc.add_attachment('input0.pdf', att_content, description='附加的PDF文档')

# 保存带附件的PDF
pdf_doc.save('output_with_attachment.pdf')
pdf_doc.close()

关键注意事项

  • 保存输出PDF时必须用wb(写入二进制)模式,绝对不能用ab追加模式,否则会彻底破坏PDF的结构完整性。
  • 确保你的源PDF本身没有损坏,测试用的PDF尽量使用标准工具(如Adobe Acrobat、LibreOffice)生成的文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 03:30:46