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

如何用Python提取PDF中的批注及对应参考文本?

提取PDF批注及对应参考文本(基于PyMuPDF)

修改后的完整代码

import fitz  # PyMuPDF

def extract_comments_with_reference_text(file_path):
    document = fitz.open(file_path)
    comments = []

    for page_num in range(len(document)):
        page = document.load_page(page_num)
        annotations = page.annots()

        if annotations:
            for annot in annotations:
                # 覆盖常见批注类型:文本注释、高亮、下划线、删除线
                allowed_types = {8, 5, 6, 7}  # 8=文本注释, 5=高亮, 6=下划线, 7=删除线
                if annot.type[0] in allowed_types:
                    comment_content = annot.info.get("content", "")
                    reference_text = ""
                    
                    # 优先用QuadPoints提取精确选中的文本(针对高亮类批注)
                    if annot.quadpoints:
                        quads = fitz.Quad(annot.quadpoints).rects
                        for q in quads:
                            reference_text += page.get_text("text", clip=q).strip() + " "
                    else:
                        # 无精确区域时,用批注所在矩形提取文本
                        reference_text = page.get_text("text", clip=annot.rect).strip()
                    
                    comments.append({
                        "page": page_num + 1,
                        "comment": comment_content,
                        "reference_text": reference_text.strip()
                    })

    document.close()
    return comments

# 使用示例
if __name__ == "__main__":
    pdf_path = "your_file.pdf"
    result = extract_comments_with_reference_text(pdf_path)
    for item in result:
        print(f"页码: {item['page']}")
        print(f"参考文本: {item['reference_text']}")
        print(f"批注内容: {item['comment']}\n")

核心逻辑说明

  • 批注类型扩展:原代码仅筛选文本注释,这里新增了高亮、下划线等常见批注类型,适配更多使用场景。
  • 参考文本精准提取:
    • 对于高亮、下划线这类有精确选中区域的批注,通过quadpoints获取PDF记录的选中坐标,拆分后逐个提取对应区域的文本,保证内容准确性。
    • 普通文本注释无精确选中坐标时,通过批注所在的矩形区域annot.rect提取对应位置的文本。
  • 文本清洗:用strip()去除提取文本的首尾空格,避免冗余格式问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 16:00:12