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

PyPDF2单PDF多注释添加问题求助:重复页面或索引越界报错

解决PDF批量添加注释的重复页面与索引错误问题

问题根源

  1. 重复页面:原代码每次循环调用writer.add_page(page),导致同一页面被多次写入输出PDF
  2. 索引错误:移除add_page后,writer内没有对应页码的页面,add_annotation找不到目标页面抛出IndexError

修正后的代码

def BatchAnnotate(myPDFPath, myPDFOutput, myAllNotes):
    pdf_path = myPDFPath
    reader = PdfReader(pdf_path)
    writer = PdfWriter()

    # 一次性导入所有页面到writer,避免重复添加
    for page in reader.pages:
        writer.add_page(page)

    for myNote in myAllNotes:
        myPageIndex = myNote[0]
        myText = myNote[1]
        myPosition = myNote[2]
        
        # 转换坐标单位
        myX = ConvertMM2Pixel(myPosition[0])
        myY = ConvertMM2Pixel(myPosition[1])
        
        # 获取当前注释页面的mediabox(原代码错误使用了第0页的尺寸)
        target_page = reader.pages[myPageIndex]
        box = target_page.mediabox

        # 注释矩形需要有实际宽高,原代码两点重合会导致注释无法显示
        rect_width = 100  # 可自定义宽度
        rect_height = 50  # 可自定义高度
        rect = (
            myX, 
            int(box[3] - myY - rect_height),  # 适配PDF左下角为原点的坐标体系
            myX + rect_width, 
            int(box[3] - myY)
        )

        annotation = AnnotationBuilder.text(
            text=myText,
            rect=rect,
            flags=15,
            open=False,
        )
        # 向已存在的页面添加注释
        writer.add_annotation(page_number=myPageIndex, annotation=annotation)

    # 写入最终PDF文件
    with open(myPDFOutput, "wb") as fp:
        writer.write(fp)

关键修改说明

  • 提前导入所有页面:在处理注释前,先把原PDF的所有页面一次性添加到writer,确保每个页码都存在,避免索引错误
  • 修正注释矩形:原代码的rect参数是两个相同的坐标点,导致注释无法正常显示,这里设置了默认宽高,你可以根据需求调整
  • 页面尺寸适配:每个注释对应页面的mediabox从当前页面获取,不再固定使用第0页的尺寸,适配多页面尺寸不同的PDF
  • 坐标修正:调整Y轴计算逻辑,适配PDF以左下角为坐标原点的特性,确保注释位置符合预期

内容的提问来源于stack exchange,提问作者Vinícius Amaral

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 09:43:22