Annotated PDF Handoff: A Clean-Looking File Isn't Enough

directly addresses a high-frequency fault: when you use page.gettext() When extracting PDF content for translation or archiving, the default output typically do

Annotated PDFs often look finished, but their notes can be missing from your extracted text or mixed into it. If you translate or archive a PDF with a default text extraction call, reviewer comments may be left out, or they may land in the middle of the body text and break its meaning. Sensitive notes in the margins can also pass through unnoticed.

This guide is for developers, editors and document handlers who extract PDF content for translation, archiving or handover. It explains why annotations sit in a separate data layer, shows how to separate them from the main text, and sets out the checks to run before a file moves on. You will get a Python approach with defensive checks, an acceptance checklist, and the cases where manual review is still needed.

The examples use synthetic samples only. Keep your original files, and check the results against the boundaries in this guide before you process important documents.

How do you hand over annotated PDFs without losing or leaking notes? The short answer

Treat the main text and the annotations as two separate data streams, check annotations for sensitive content, and verify the output against the acceptance checklist before translation.

Your situationWhat to doWhy
You extract text with page.get_text()Read annotations separately with Page.annots()The default output typically does not include annotations
A highlight or underline has no visible text of its ownLook up the text by its coordinates in the main bodyMarkup annotations only record the regions (Quads/Rects)
A note or FreeText annotation has contentRead its own content string and check it for sensitive dataThese annotations carry their own text
The page is rotated by 90 degreesConvert coordinates with page.rotation_matrix or page.derotation_matrix firstAnnotation rectangles stay relative to the unrotated page
Annotation replies are nestedRebuild the dialogue tree from ParentIDPyMuPDF returns a flat list, and context is lost otherwise

Why are annotations a separate, hidden data layer?

In the PDF specification, the Content Stream and the Annots Array are separate structures:

  • The main text consists of text-display instructions.
  • Annotations are independent objects attached to the page. Each has its own coordinates, type and content attributes.

PyMuPDF's `Page.annots()` method returns a generator that iterates over this independent annotation list, not over the page's text stream. This means you cannot assume that all visible text can be extracted in the same way.

Annotation types also behave differently:

  • Markup annotations such as Highlight and Underline do not contain text. They record the regions they cover (Quads/Rects), and you must retrieve the actual text by matching those coordinates in the main body.
  • Text/Note and FreeText annotations carry their own content strings.

If you do not distinguish between types and read annot.info["content"] directly, you will lose the original text that markup annotations point to. You may also hit an exception when the content is empty.

Synthetic example: hierarchical extraction and sensitive information interception

To demonstrate the correct logic, the example builds a synthetic scenario with three typical annotations. None of the inputs come from real customer files. They exist only to illustrate the method.

What the correct output contains

The expected output has three structured fields:

  1. Main text fragment: only the page's original text, with no annotations.
  2. Annotation list: each record includes the type, location, author, time and content (if any).
  3. Security tag: if annotated content matches a predefined sensitive rule, such as an ID number or an internal code, the entry is marked redacted=True and its content is replaced with a placeholder.

Error and boundary cases

  • Empty content annotations: Some ink or graphic annotations made in readers have no text attribute. Reading .info["content"] may return an empty string or None. Your code must check for this and must not assume every annotation has readable text.
  • Rotated pages: If a page is rotated by 90 degrees, annotation rectangles remain relative to the unrotated page. Using them directly to crop or position text will place it incorrectly. Apply page.rotation_matrix or page.derotation_matrix first.
  • Orphan objects: If the document is closed or the page is reloaded during traversal, the current annotation object becomes invalid. Complete all read operations within a single page lifecycle.

Python implementation: secure annotation traversal and validation

The following example uses PyMuPDF to build a test PDF in memory. It demonstrates hierarchical extraction and basic de-identification. Install the PyMuPDF package (imported as pymupdf) in a locked dependency environment, using version 1.23.0 or later for full access to annotation attributes. The code makes no network calls and writes no files. It exists only to demonstrate the logic. For the method behind the annotation traversal, see the PyMuPDF Page.annots() documentation.

import fitz  # PyMuPDF
import re

# 合成示例:仅在内存中构造,无需外部文件
def create_sample_pdf():
    doc = fitz.open()
    page = doc.new_page()
    # 插入正文
    page.insert_text((72, 72), "Confidential Project Alpha Report", fontsize=12)
    # 添加便签批注(含敏感信息模拟)
    page.add_text_annot((200, 72), "Reviewer: SSN 123-45-6789 approved.")
    # 添加高亮批注(无自身文本,关联正文)
    highlight = page.add_highlight_annot(fitz.Rect(72, 60, 250, 80))
    # 必须调用update()使info变更生效
    highlight.set_info(title="Editor", content="Check this term")
    highlight.update()
    return doc

def extract_with_safety(page, sensitive_pattern=r"\d{3}-\d{2}-\d{4}"):
    body_text = page.get_text("text")
    annotations = []

    # 显式遍历批注生成器
    for annot in page.annots():
        info = annot.info
        # 防御性获取内容,处理None或空字符串
        content = info.get("content", "") or ""

        # 边界处理:敏感词检测与脱敏
        is_sensitive = bool(re.search(sensitive_pattern, content))
        safe_content = "[REDACTED]" if is_sensitive else content

        annotations.append({
            "type": annot.type[1],
            "author": info.get("title", "Unknown"),
            "content": safe_content,
            "is_redacted": is_sensitive,
            # 注意:此为未旋转坐标系,若页面有旋转需配合rotation_matrix使用
            "rect": list(annot.rect)
        })
    return body_text, annotations

# 执行校验
doc = create_sample_pdf()
page = doc[0]
text, annots = extract_with_safety(page)

assert "SSN 123-45-6789" not in str(annots), "敏感信息未被拦截"
assert any(a["type"] == "Highlight" for a in annots), "标记类批注丢失"
assert len(text.strip()) > 0, "正文提取失败"
print(f"Extracted {len(annots)} annotations safely.")

The core principle is defensive programming. Do not trust the content of annotations, and do not assume that every annotation type is complete. The assert statements check the logic's expectations. They are a demonstration only and do not guarantee results for every PDF variant.

Acceptance criteria and manual review boundary

Automated extraction cannot cover every edge case. The table below lists what to check during a real handover. It separates cases the code can handle from cases that need a person to decide.

Observed phenomenonCode-level processingManual review or decision
The annotation content is empty but an icon is presentRecord the type as "Ink" or "Stamp" and leave the content blankConfirm whether it is a signature or an approval seal, and decide whether to keep an image snapshot
The annotation position exceeds the CropBoxCoordinates stay valid, but rendering is invisibleDecide whether it is a legacy, discarded annotation. Such annotations can usually be ignored
A rich-text annotation contains HTML tagsExtract the original string, tags includedClean the tags or convert to plain text before translation, so the translated text contains no code
The annotator's name is garbledExtract it as is, with no encoding guessesCheck the source file's metadata to see whether the name uses a specific encoding
Nested reply threadsPyMuPDF returns a flat listRebuild the dialogue tree from ParentID, or the context is lost

Scope limits: This approach does not apply to password-protected encrypted PDFs, PDFs with corrupted structures, or annotation types that use non-standard proprietary extensions. In those cases the script may skip the file silently or raise an underlying C++ exception. Open the source file manually with specialised tools to check it.

Using this checklist for document translation

First check the page order, source location and textual integrity. Then submit the same sample to the translation process. After translation, check that titles, body text and figure captions still correspond correctly. Do not rely solely on how fluent the text reads.

OmniDoc translates PDF, Word, PowerPoint and Excel files: scanned pages are recognized first, table cells are translated one by one so tables keep their rows and columns, and a PDF comes back as both a bilingual and a translation-only file. Paid translation adds a glossary and context translation.

References and next steps

Next step: Select a historical project file that contains mixed annotation types, run the validation script above, and calculate the proportion of entries that need manual review. If that proportion is higher than you expected, add a preprocessing step to your handover process rather than relying on downstream tools to handle everything.

📊 At a glance

The main annotation types differ in where their text comes from:

Annotation typeWhere the text comes fromWhat to watch for
Highlight, UnderlineMain body, found by matching coordinates (Quads/Rects)The annotation holds no text of its own
Text/Note, FreeTextThe annotation's own content stringCheck the content for sensitive data
Ink, StampOften no text attributeContent may be empty or None; review the icon manually

🎯 Which approach fits you?

If you translate a PDF

Extract the main text and annotations separately, de-identify the sample, and then submit it for translation. Check that titles, body text and figure captions still line up after translation. Do not rely only on how fluent the text reads.

If you archive a PDF

Keep the annotation list as its own record, with type, location, author, time and content. Mark sensitive entries as redacted=True before the archive leaves your hands.

If your files contain nested review threads

Rebuild the dialogue tree from ParentID before you rely on the flat list PyMuPDF returns.

❓ FAQ

1. Why doesn't page.get_text() return my reviewers' comments?

The default output typically does not include annotations. Read them separately with Page.annots().

2. Why is the text for my highlights missing?

Highlight and Underline annotations store only the regions they cover. You need to find the matching text in the main body using the coordinates.

3. What should I do with sensitive notes in the margins?

Check each annotation against your sensitive rules, such as ID numbers or internal codes. Mark matches as redacted=True and replace their content with a placeholder.

4. Can I rely on the script for every PDF?

No. The approach does not cover encrypted files without a password, corrupted structures or proprietary extensions. Check your files against the acceptance table and review edge cases manually.

📝 Summary

Annotations are a separate data layer, so extract them on their own and treat their content as potentially sensitive. Validate the output against the checklist before it goes to translation or archive. Keep your original copies throughout.

Try it now: upload a document and get it translated with the layout intact

Updated 2026-11-29