#!/usr/bin/env python3
"""Remove pen marks (Ink annotations) from a PDF. Other annotations and the page itself are kept
(our test PDF had no links or form fields).

  python3 remove_ink.py marked.pdf clean.pdf

An Ink annotation is a pen stroke saved on top of the page. If the marks were flattened into
the page, this script finds 0: treat the page as an image instead.
Needs: pip install pypdf

From https://brasspage.com/erase-handwriting/ (MIT License, Brasspage, 2026).
"""

import sys

from pypdf import PdfWriter
from pypdf.generic import ArrayObject, NameObject

src, dst = sys.argv[1], sys.argv[2]
pdf = PdfWriter(clone_from=src)
removed = 0
for page in pdf.pages:
    annots = page.get("/Annots")
    if annots is None:
        continue
    keep = ArrayObject(
        a for a in annots.get_object() if a.get_object().get("/Subtype") != "/Ink"
    )
    removed += len(annots.get_object()) - len(keep)
    page[NameObject("/Annots")] = keep
pdf.write(dst)
print(f"removed {removed} pen marks from {len(pdf.pages)} pages")
