Skip to content

feat: extract AcroForm widget fields into FormItem key-value graphs - #4055

Closed
wittjeff wants to merge 1 commit into
docling-project:mainfrom
wittjeff:feat/acroform-widget-extraction
Closed

wittjeff wants to merge 1 commit into
docling-project:mainfrom
wittjeff:feat/acroform-widget-extraction

Conversation

@wittjeff

@wittjeff wittjeff commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to the offer in #301 (discussion): this makes the PDF pipeline read the interactive form layer of born-digital PDFs instead of dropping it.

What it does

  • docling/utils/form_utils.py — lossless widget-annotation extraction via PDFium's annotation API. Each field yields a FormFieldInfo: fully qualified name (/T), type (text/checkbox/radio/combobox/listbox/pushbutton/signature), current value (/V), tooltip (/TU — the PDF/UA accessible name), checkbox/radio state, required/read-only flags, and the widget rectangle.
  • PdfDocumentBackend.get_form_fields() — new backend surface with an empty default (mirroring get_document_outline()), implemented once in ManagedPdfiumDocumentBackend so both the docling-parse and pypdfium2 backends serve it from the pypdfium2 document handle they already hold.
  • PdfPipelineOptions.extract_form_fields (default False) — when enabled, StandardPdfPipeline attaches one FormItem per page-with-fields, carrying a key/value GraphData: the field name as a key cell (no page provenance — it's dictionary metadata, not page text), linked to_value to a value cell anchored at the widget rectangle. Checkable fields become checkbox cells with explicit checked/unchecked text, so state survives every export path. Metadata-only: no models run, negligible cost; scanned/flattened forms have no widget annotations and are unaffected.

What it deliberately does not do (yet)

  • Properties without a typed slot in today's docling-core schema — tooltip, field type, required/read-only, radio-group semantics, a source-widget reference — are preserved on FormFieldInfo for API users but not yet serialized into the document. We'll follow up with a docling-core schema proposal for those (flagged in Expose and add structured output for forms and key-value regions #301); this PR keeps the extraction layer and the schema discussion decoupled.
  • No visible-label ↔ field binding: linking the page text near a widget to the field is a semantics problem (and where scanned-form support would join); out of scope here.
  • VlmPipeline is untouched; the option lives on PdfPipelineOptions.

Tests

tests/test_form_extraction.py with a hand-crafted AcroForm fixture (tests/data/pdf/sources/acroform_sample.pdf: a filled required text field with /TU, a checked and an unchecked checkbox, a checkbox checked only via /AS with no /V — the viewer-filled pattern, resolved through the appearance state — and a Link annotation that field extraction must skip, plus visible text labels): backend extraction across both PDF backends, document representation (cells/links/provenance), the pipeline option gate in both positions, the no-form fallback on an existing fixture, plus degradation paths — get_form_fields() after unload(), a form environment that fails to initialize, and the empty default on non-PDFium backends (image input).

cc @cau-git — this is the "populate the existing model from widget annotations" PR from the discussion. @Ptark, your pypdfium2 approach is exactly the route taken (shared utility on the backends' existing handle); review from you would be very welcome, and if you'd like to build any of your richer extraction (JS actions, etc.) on top, happy to co-develop.

Checklist:

  • Documentation has been updated, if necessary.
  • Examples have been added, if necessary.
  • Tests have been added, if necessary.

🤖 Generated with Claude Code

@github-actions

Copy link
Copy Markdown
Contributor

✅ DCO Check Passed

Thanks @wittjeff, all your commits are properly signed off. 🎉

@mergify

mergify Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Merge Protections

🔴 1 of 2 protections blocking · waiting on 👀 reviews

Protection Waiting on
🔴 Require two reviewer for test updates 👀 reviews
🟢 Enforce conventional commit —

🔴 Require two reviewer for test updates

Waiting for

  • #approved-reviews-by >= 2
This rule is failing.

When test data is updated, we require two reviewers

  • #approved-reviews-by >= 2

Show 1 satisfied protection

🟢 Enforce conventional commit

Make sure that we follow https://www.conventionalcommits.org/en/v1.0.0/

  • title ~= ^(fix|feat|docs|style|refactor|perf|test|build|ci|chore|revert)(?:\(.+\))?(!)?:

@codecov

codecov Bot commented Aug 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.87500% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
docling/backend/pdf_backend.py 71.42% 2 Missing ⚠️
docling/utils/form_utils.py 98.14% 0 Missing and 2 partials ⚠️

📢 Thoughts on this report? Let us know!

Born-digital PDFs carry their interactive form layer machine-readable, but
the PDF pipeline dropped it: field names, types, values, checkbox states and
tooltips in widget annotations were never read (discussion docling-project#301).

- docling/utils/form_utils.py: lossless widget-annotation extraction via
  PDFium's annotation API (FormFieldInfo: name, type, value, /TU tooltip,
  checked state, required/readonly flags, widget rect), plus a builder that
  represents fields in a DoclingDocument as one FormItem per page with a
  key/value GraphData (checkable fields as checkbox cells with explicit
  checked/unchecked text).
- PdfDocumentBackend.get_form_fields() default (empty), implemented once in
  ManagedPdfiumDocumentBackend, so both the docling-parse and pypdfium2
  backends serve it from their existing pypdfium2 document handle.
- PdfPipelineOptions.extract_form_fields (default False) gates attachment in
  StandardPdfPipeline._assemble_document; metadata-only, no models involved.
- Hand-crafted AcroForm fixture: filled required text field with /TU, checked
  and unchecked checkboxes, a checkbox checked only via /AS (no /V), and a
  Link annotation that extraction must skip. Backend/document/pipeline tests
  incl. after-unload, malformed-form-env, and non-PDFium-backend fallbacks.

Properties without a typed schema slot yet (tooltip, field type, flags) stay
on FormFieldInfo; a docling-core schema proposal follows separately.

Signed-off-by: Jeff Witt <1848307+wittjeff@users.noreply.github.com>
@wittjeff
wittjeff force-pushed the feat/acroform-widget-extraction branch from 08e1204 to 52fabd4 Compare August 24, 2026 15:43
@cau-git

cau-git commented Aug 25, 2026

Copy link
Copy Markdown
Member

@wittjeff Many thanks for volunteering and taking the effort to push this further!

I have read the discussion in #301 and would like to give some input on the desired approach here.

1. Please use FieldRegionItem / FieldItem (not FormItem + GraphData).

The FormItem + GraphData model is being retired in the meantime. It stores form fields as a detached key/value graph at the document root, disconnected from the layout tree — which is why every serializer has to special-case it and why field text never reaches the reading order. docling-core already provides typed replacements: FieldRegionItem, FieldItem, FieldKeyItem, FieldValueItem (kind="fillable") — and matching add_field_* helpers on DoclingDocument. There's a migration in docling-core that rewrites legacy FormItems into these on load, but we don't want new code that relies on it.

Concretely, replace the current attach_form_fields core with something like:

from docling_core.types.doc import BoundingBox, CoordOrigin, ProvenanceItem

for page_no, page_fields in by_page.items():
    fri = doc.add_field_region(
        prov=ProvenanceItem(page_no=page_no, bbox=page_bbox, charspan=(0, 0)),
    )
    for f in page_fields:
        fi = doc.add_field_item(parent=fri)

        # /T is dictionary metadata, not page text — no prov
        doc.add_field_key(text=f.name, parent=fi)

        value_text = (
            ("checked" if f.checked else "unchecked")
            if f.checked is not None
            else f.value
        )
        doc.add_field_value(
            text=value_text,
            parent=fi,
            kind="fillable",
            prov=ProvenanceItem(
                page_no=page_no,
                bbox=BoundingBox(
                    l=f.rect[0], b=f.rect[1], r=f.rect[2], t=f.rect[3],
                    coord_origin=CoordOrigin.BOTTOMLEFT,
                ),
                charspan=(0, len(value_text)),
            ),
        )

Tooltip (/TU), field type, required/read-only, radio-group semantics don't have typed slots yet — better to leave those on FormFieldInfo for a docling-core follow-up than to smuggle them into free-form text.

2. Thread the fields through layout — don't attach them past it.

Right now attach_form_fields runs in _assemble_document after layout, layout-postprocessing, reading-order, and heading-hierarchy have all finished. The result is one form node per page bolted onto the document root with a page-level prov; even though each value cell carries the widget rectangle, the fields never participate in clustering or reading order, and page text overlapping a widget stays orphaned from the field. That's the same detachment problem the FormItem model had — it just moves from schema to pipeline placement.

Widgets should enter the pipeline at the layout stage, not after it. That means edits in three places:

  • Backend, per-page: expose widgets as page-level elements alongside text cells (not only as a document-level list at assembly time), so downstream stages see them at the same moment they see cells.
  • Layout / layout-postprocessing: inject each widget's /Rect as a pre-labeled FIELD_VALUE cluster — the geometry is authoritative, no model prediction needed — and make the postprocessor aware of these clusters so it doesn't fold them into an overlapping text or table cluster. A companion label-binding pass matches each widget rect to the nearest text cluster to its left/above (within a small margin) and promotes that cluster to FIELD_KEY: /T stays as machine metadata, the visible key comes from the page.
  • Page assembler: when it encounters FIELD_VALUE / FIELD_KEY cluster labels, emit FieldRegionItem / FieldItem / FieldKeyItem / FieldValueItem — not a floating form node. Reading order then naturally keeps a field's key and value adjacent, and the fields are part of the document's structural tree instead of a sidecar on it.

The docling-core primitives (FIELD_REGION, FIELD_ITEM, FIELD_KEY, FIELD_VALUE labels + add_field_* helpers) are in place; the missing piece is on the docling side — making layout aware of widgets. Happy to sketch the layout-injection hook if it helps.

3. We'll enable the docling-parse route so pypdfium2 isn't needed here.

Out of scope for this PR, only informational:
docling-parse already decodes AcroForm widgets in its C++ pipeline — every page carries a widgets list with /Rect, /T, /FT, and the current /V, reachable from Python as SegmentedPdfPage.widgets (and low-level as pdf_parser.get_page_decoder(...).get_page_widgets()). Today it's missing a few things the PR relies on (fully-qualified field names via the /Parent chain, /TU tooltips, /Ff flags, /AS appearance state for viewer-filled checkboxes, and the widget-kind enum on the Python binding) — none of them hard, and we'll close those gaps on the docling-parse side in the future, so the docling-parse backend can serve get_form_fields() directly from its own parser. Once that's in, the shared ManagedPdfiumDocumentBackend.get_form_fields() should move to the pypdfium2-only backend and the docling-parse backend should stop reaching for pypdfium2 for this. Worth structuring the code so that swap is a localized change rather than a rewrite — e.g. keep FormFieldInfo as the backend-agnostic contract and let each backend produce it from its own source.

@cau-git

cau-git commented Sep 2, 2026

Copy link
Copy Markdown
Member

@wittjeff FYI, I am doing an iteration on this. I found that it quickly gets messy in the details, so might need some time.

@wittjeff

wittjeff commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor Author

@cau-git
Your original point was well taken, I just have been on different tracks for the last two weeks. I'm swamped this week then will be traveling for most of September. Sorry for the radio silence.

@cau-git

cau-git commented Sep 2, 2026

Copy link
Copy Markdown
Member

@wittjeff I put up a PR with an effort to use the acroform widgets, which addresses the feedback above. It also uses docling-parse natively. There is still a lot of iterations to do but I would propose we start from there. Currently, only value fields are considered, and no binding from form labels/fieldnames yet.

See: #4140

@wittjeff

wittjeff commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

@cau-git Thanks for taking this over and for #4140. Agreed that it is the right shape: widgets entering at the layout stage, FieldRegionItem/FieldItem/FieldValueItem instead of the legacy graph, and docling-parse serving the widgets natively. I will close this PR once #4140 lands. Glad the fixture and the /AS-first checkbox resolution carried over; the docling-parse companion closes every gap you listed in your first comment.

I read #4140 against Well-Tagged PDF 1.0, which PDF/UA-2 is built on, and I think it is worth aligning the follow-on work with that spec now, while the contract is still fluid. Three things fall out of it:

  1. /TU is the label source, /T is not. WTPDF 8.10.2.1 lists the sources of context for a widget (Lbl in the structure tree, the field's TU, the widget's Contents) and then says explicitly that the field's name, its T entry, does not contribute. That matches your finding that /T leaks machine names, and it means /TU can be used as FieldKeyItem without inferring anything. feat(pdf): key form fields by their /TU description and skip artifact widgets #4144 is a small stacked PR on top of your branch that does exactly that, plus skipping zero-size widgets (artifacts per 8.9.2.4.13) and push buttons, which the feat: integrate native AcroForm widgets as typed fields #4140 description says are excluded but the code still emits as empty values.

  2. Two ingestion paths, one model. Interactive widgets get role and state from the field dictionary and their label from the structure tree. Non-interactive forms get role and state from PrintField attributes (8.10.4). docling-core's read_only/fillable split already mirrors that, so the schema follow-up is mostly a typed role/state/required slot and a source kind for the widget identity, not a new item type.

  3. Order by structure, not /Tabs. 8.9.3.3 notes that an annotation's logical position is defined by the structure tree regardless of Tabs. So the "form reading order" item in your future-work list resolves to reading Form/Lbl/OBJR from the structure tree in docling-parse, with the current geometry path as the untagged fallback.

The full proposal, with a phased plan across docling-parse, docling-core, and docling, is in #4143. Detailed review notes on #4140 itself (checkbox representation vs. the HTML backend, multi-select /Opt, signature widgets) I will post there so they stay with the code.

I am travelling most of September, so response times will be uneven, but I can keep moving the stacked pieces in the background.

@wittjeff

wittjeff commented Oct 4, 2026

Copy link
Copy Markdown
Contributor Author

Closing this as superseded by #4140.

@cau-git's point stands and I agreed with it at the time: FormItem + GraphData is the retired model, and the right shape is widgets entering at the layout stage with FieldRegionItem / FieldItem / FieldValueItem and docling-parse serving the widget data natively. #4140 does that, and the zero-size and push-button widget skips from this branch were absorbed into it along the way.

Rather than redesign this draft onto the typed items in parallel, the remaining pieces are better placed where that work already lives:

Nothing here is lost — #4143 remains the proposal of record for the PDF/UA-2 alignment, and the implementation now follows #4140. Thanks for picking it up.

🤖 Generated with Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants