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

修复PyPDF2报错:module 'PyPDF2' has no attribute 'pdf'

修复PyPDF2创建空白页时的"module 'PyPDF2' has no attribute 'pdf'"错误

错误原因

你遇到的错误是因为PyPDF2版本更新后调整了API结构,旧代码里的PyPDF2.pdf.PageObject路径已被废弃,新版本中PageObject直接放在PyPDF2顶级模块下,同时创建空白页的方法名也从驼峰式的createBlankPage改为了下划线命名的create_blank_page。

修复步骤

  • 替换空白页创建代码:将报错行的PyPDF2.pdf.PageObject.createBlankPage替换为PyPDF2.PageObject.create_blank_page,保持宽高参数不变。
  • 修复批注复制的潜在问题:原代码中如果目标页面没有/Annots字段,直接调用append()会触发KeyError,需要先初始化这个字段。
  • 同步更新其他方法名:PyPDF2新版本将mergeTranslatedPage改为merge_translated_page,同步替换避免后续报错。

修复后的完整代码

import PyPDF2

def copiar_anotaciones(pagina_fuente, pagina_destino):
    # 初始化目标页面的批注列表,避免KeyError
    if '/Annots' not in pagina_destino:
        pagina_destino['/Annots'] = PyPDF2.generic.ArrayObject()
    
    # 源页面无批注则直接返回
    if '/Annots' not in pagina_fuente:
        return
    
    for anotacion in pagina_fuente['/Annots']:
        anotacion_ref = anotacion.getObject()
        if '/Dest' in anotacion_ref:
            destino = anotacion_ref['/Dest']
            if isinstance(destino, PyPDF2.generic.ArrayObject) and len(destino) >= 2:
                pagina_referencia = destino[0]
                if isinstance(pagina_referencia, PyPDF2.generic.NumberObject):
                    destino[0] = pagina_destino
                    pagina_destino['/Annots'].append(anotacion_ref)

def alternar_paginas(pdf1_path, pdf2_path, output_path):
    pdf1 = PyPDF2.PdfReader(pdf1_path)
    pdf2 = PyPDF2.PdfReader(pdf2_path)

    pdf_writer = PyPDF2.PdfWriter()

    num_pages = min(len(pdf1.pages), len(pdf2.pages))

    for i in range(num_pages):
        pagina1 = pdf1.pages[i]
        pagina2 = pdf2.pages[i]

        # 新版API创建空白页
        nueva_pagina = PyPDF2.PageObject.create_blank_page(
            width=pagina1.mediaBox.getWidth() + pagina2.mediaBox.getWidth(),
            height=max(pagina1.mediaBox.getHeight(), pagina2.mediaBox.getHeight())
        )

        # 新版合并页面方法
        nueva_pagina.merge_translated_page(pagina1, 0, 0)
        nueva_pagina.merge_translated_page(pagina2, pagina1.mediaBox.getWidth(), 0)

        copiar_anotaciones(pagina1, nueva_pagina)
        copiar_anotaciones(pagina2, nueva_pagina)

        pdf_writer.add_page(nueva_pagina)

    with open(output_path, 'wb') as output_file:
        pdf_writer.write(output_file)

if __name__ == "__main__":
    pdf_ingles_path = "Learning_SQL_Generate,_Manipulate,_and_Retrieve_Data-bibis.ir.pdf"
    pdf_espanol_path = "ilovepdf_merged (1).pdf"
    pdf_resultante_path = "Learning_SQL_Espanol_Ingles5.pdf"

    alternar_paginas(pdf_ingles_path, pdf_espanol_path, pdf_resultante_path)

内容的提问来源于stack exchange,提问作者Enzo Piñeyro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 19:58:24