Skip to content

fix(pypdfium2): render raster-only pages directly instead of supersampling - #3803

Open
wittjeff wants to merge 2 commits into
docling-project:mainfrom
wittjeff:fix/pypdfium-raster-supersample
Open

wittjeff wants to merge 2 commits into
docling-project:mainfrom
wittjeff:fix/pypdfium-raster-supersample

Conversation

@wittjeff

@wittjeff wittjeff commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

PyPdfiumPageBackend.get_page_image() renders every page at scale * 1.5 and then downsizes to the requested scale. Supersampling that way sharpens vector content, but on a raster-only page — a scanned page whose content is a single full-page image with no text or vector objects — there is no vector detail to sharpen. The round trip just resamples already-rasterised pixels twice, at 2.25× the pixel cost.

This renders raster-only pages directly at the requested scale. Pages with any text or vector content keep supersampling exactly as before.

Detection walks the page object list once (get_objects(max_depth=16)) and treats the page as raster-only only if it contains at least one image object and nothing but image and form objects. The result is cached per page, and any pdfium error falls back to the existing supersampling path.

Why

Render cost, unconditionally. Dropping a 2.25× oversized bitmap plus a full-page Lanczos resize is pure saving on every raster-only page, whatever happens to OCR quality:

old new
time (9 raster-only pages, scale=3.0, best of 5) 3.92 s (435 ms/page) 1.45 s (161 ms/page) 2.71× faster
peak bitmap 10 Mpx 5 Mpx 2.25× fewer pixels

@faithpricejp-source measured the same comparison independently on 21 raster-only pages from a corpus of scanned Chinese books (RapidOCR, Apple silicon) and saw 4.68× (92 → 20 ms/page) with the identical 2.25× pixel reduction. The pixel factor is structural — it is just 1.5² — while the time saving depends on machine and page content, so 2.7×–4.7× is the range to expect.

OCR recovery, conditionally. The round trip can destroy borderline text detections: #3587 reports an entire line lost, with CER 0.184 → 0.05 once the resample is skipped.

This benefit is not universal, and it is worth being precise about. @faithpricejp-source's 1,590-page corpus shows no measurable OCR difference from the change — a wash in both directions, at scale=3.0 and again at scale=1.0, which rules out "the render was already upsampling past native resolution" as the explanation. The honest summary of the two results together is that the round trip bites on scans that are already borderline for the engine, not on legible scans generally. A reviewer testing this on a clean scan should expect to see no OCR change at all.

So the case for the change is cost plus correctness-on-degraded-input, not a general OCR win.

Scope

Only the pypdfium2 backend. An earlier revision of this PR also carried the same fix for the docling-parse backend, but #4244 refactored that backend to remove pypdfium entirely, deleting the DoclingParsePageBackend class those commits modified. They are obsolete and have been dropped in the rebase onto current main; the pypdfium2 render path is the only pdfium-rendering path left.

supersample_factor is exposed on a new PyPdfiumBackendOptions (kind="pypdfium", a subclass of PdfBackendOptions in the same way ThreadedDoclingParseBackendOptions is) so the behaviour remains configurable, including setting it to 1.0 to disable supersampling entirely. It is scoped to the pypdfium2 backend on purpose: the docling-parse backends render through docling-parse's own renderer and never supersampled, so the option would be a no-op there. Passing a plain PdfBackendOptions to the pypdfium2 backend keeps the default factor.

Tests

tests/test_backend_pdfium.py covers the detector and the render path: a raster-only page renders byte-identically to a direct pdfium render at the requested scale, a page with text keeps the supersampled path, and the supersample_factor option is honoured end to end.

Known gap, follow-up offered

On @faithpricejp-source's corpus, 21 of 68 pages that the detector rejects are blocked by nothing but a full-page opaque blank fill drawn underneath the scan image — a 5-segment closed rect, RGBA (255,255,255,255), covering >98% of the page. Those pages are as raster-only as it gets and should take the fast path. The predicate has to respect draw order, though: across those pages the path precedes the image in 20 of 22 cases, but in 2 of 22 it is drawn over the image, where it could legitimately obscure content and must keep blocking the fast path. @faithpricejp-source has offered a follow-up PR for this, which is the right place for it.

@github-actions

Copy link
Copy Markdown
Contributor

✅ DCO Check Passed

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

@mergify

mergify Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Merge Protections

🟢 Merge protection satisfied — ready to merge.

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)(?:\(.+\))?(!)?:

@wittjeff wittjeff changed the title fix: avoid lossy supersample of raster-only pages in pypdfium2 backend fix: avoid lossy supersample of raster-only (scanned) pages in PDFium-rendering backends Jul 14, 2026
@wittjeff
wittjeff marked this pull request as ready for review July 14, 2026 15:47
@cau-git
cau-git requested a review from Copilot July 22, 2026 08:49

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adjusts Docling’s PDFium-based get_page_image() rendering to avoid a lossy supersample-then-downsample path on raster-only (scanned) PDF pages, while keeping the sharpening supersample behavior for vector/text pages by default. It also introduces a configurable supersample_factor backend option and consolidates rendering logic into the shared managed PDFium page backend.

Changes:

  • Detect raster-only pages (including form-wrapped scans) and render them directly at the requested scale to avoid degrading OCR quality.
  • Add PdfBackendOptions.supersample_factor (default 1.5; 1.0 disables supersampling globally) and propagate it through PDFium-rendering backends.
  • Add/extend tests and docs to validate behavior (including fractional page sizes and option honoring by the default backend).

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
docling/backend/managed_pdfium_backend.py Adds shared raster-only detection and unified get_page_image() with direct-render/cropping logic and configurable supersampling.
docling/backend/pypdfium2_backend.py Routes page rendering through the managed base and passes supersample_factor from backend options.
docling/backend/docling_parse_backend.py Routes page rendering through the managed base and passes supersample_factor into page backends.
docling/datamodel/backend_options.py Introduces PdfBackendOptions.supersample_factor with validation and documentation.
tests/test_backend_pdfium.py Adds deterministic raster-only and vector-page rendering tests plus option coverage.
tests/test_backend_docling_parse.py Adds a test asserting the default backend honors supersample_factor=1.0.
docs/usage/advanced_options.md Documents how to control PDF page image supersampling via backend options.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread tests/test_backend_docling_parse.py Resolved
@faithpricejp-source

Copy link
Copy Markdown

@wittjeff I ran this branch against the corpus behind my #3587 comment — 796 scanned Chinese book PDFs, 1,590 pages sampled, RapidOCR (ONNX) on Apple silicon. Three findings: the detector holds up, one gap worth closing, and one claim that does not reproduce on this corpus.

First, a validity check on my harness: on pages the detector rejects, get_page_image() output is byte-identical to the pre-PR path (3/3 in the A/B sample, comparing against a verbatim copy of main's render(scale*1.5) → resize). So the fallback really is a no-op, and my "old" arm is faithful.

1. Detection works well, but a blank background rect excludes genuine scans

Classification over 1,590 pages:

outcome pages share
raster-only (fast path taken) 1,473 92.6%
blocked by a PATH object 68 4.3%
blocked by TEXT objects (correctly) 21 1.3%
no image object 28 1.8%
blocked by annotations 0 0%

Of the 68 PATH-blocked pages, 21 (across 14 documents) are blocked by nothing but a full-page opaque blank fill: a 5-segment closed rect, RGBA (255,255,255,255), covering >98% of the page, drawn underneath the full-page scan image. Example (595.0×842.0 page):

PATH  bounds=(0.03, 0.17, 594.99, 841.97) segments=5 fill=(255,255,255,255)
IMAGE bounds=(0.00, 0.14, 595.02, 842.00)
text layer chars=0   annots=0

That page is as raster-only as it gets — no text layer, no annotations — but it takes the supersample round-trip. Some scanner/producer toolchains emit this background rect and some don't, so two otherwise identical scans get different render paths.

If you want to relax the detector, the z-order caveat matters: across those pages the draw order is PI/PPI in 20/22 cases (path first = background) but IP in 2/22 (path drawn over the image, where it could legitimately obscure content). So the safe predicate is narrower than "ignore blank paths" — something like opaque, single closed rect, ≥ page bounds, drawn before the first image object. Happy to send this as a follow-up PR against your branch rather than expanding scope here, if you'd prefer.

2. The OCR improvement does not reproduce on this corpus

This is the part that cuts against the PR's headline, so I want to be precise: I am not disputing the CER 0.184 vs 0.05 measurement in #3587. But on my scans the round-trip costs nothing measurable.

21 raster-only pages, old vs new arm, same OCR engine and settings:

render scale old chars new chars old lines new lines pages better / worse
3.0 6,917 6,902 589 579 6 / 4
1.0 6,805 6,807 562 553 7 / 7

A wash in both directions, well inside run-to-run noise.

I initially assumed this was because scale=3 already upsamples past the scan's native resolution (embedded image is 1.00×–4.17× page-points across the sample, so at 3× many pages are being upsampled and the round-trip has no real detail to discard). I tested that by re-running at scale=1.0, where the source has 1.0–4.2× more pixels than the render for every page — squarely in the regime where a double downsample should compound. It made no difference either. So that explanation is wrong, and the honest summary is: the round-trip only bites on scans that are already borderline for the OCR engine, not on legible scans generally.

I mention it because it affects how the fix should be argued — "recovers lost text" is true for degraded scans but overclaims for the common case, and a reviewer testing on a clean scan will see nothing and may conclude the PR does nothing.

3. There is a large unclaimed benefit: render cost

The stronger general argument may be the one the PR doesn't make. Same 21 raster-only pages, scale=3.0:

old  1.92 s  (92 ms/page)
new  0.41 s  (20 ms/page)     4.68x faster
peak bitmap: 183 Mpx -> 81 Mpx   (2.25x fewer pixels rendered)

That follows directly from dropping a 2.25× oversized bitmap plus a full-page Lanczos resize, and it holds regardless of whether OCR quality moves. For anyone processing scanned books in bulk it is the difference that shows up in wall-clock, and it makes the change worth taking on correctness-plus-cost grounds even where OCR is unaffected.

Happy to share the harness scripts if useful.

@wittjeff

wittjeff commented Sep 7, 2026

Copy link
Copy Markdown
Contributor Author

@faithpricejp-source — thank you for the thorough corpus analysis. The breakdown by classification outcome is exactly the kind of data needed to evaluate the detector, and the white-background-rect finding is actionable (I'll look at a follow-up that handles the PI z-order case you described).

Your point #2 is the more interesting finding for me. The round-trip degradation in #3587 was dramatic (entire line lost, CER 0.184 → 0.05), but your corpus shows no measurable OCR difference — which suggests the effect is conditional on scan quality, not universal. That's useful calibration for how to argue for the fix.

Your analysis also surfaced a question I've been circling: what's the right rendering strategy when we don't know the input characteristics?

The PR optimizes within a fixed-scale request (skip the 1.5× round-trip for raster-only pages), but it doesn't address the upstream question of what scale to request in the first place. For a scanned page, the embedded image has a fixed pixel resolution. Rendering at a scale that upsamples it invents pixels; rendering at a scale that downsamples it discards real data. The "optimal" scale depends on:

  1. The embedded image's native resolution (inspectable cheaply via pdfium without decoding)
  2. The OCR engine's preferred input characteristics (which vary — Tesseract historically wants ~300 DPI; some neural models prefer higher)
  3. Whether upsampling ever helps when native resolution is below the engine's minimum (I suspect this is model-dependent — an engine trained on degraded inputs might benefit differently than one trained on clean renders)

For my use case (yra-doc-pipeline, a multi-engine document processing pipeline where Docling is one adapter among many), this matters because different engines have different optimal inputs, and the intelligent choice would be per-page and per-engine. The cleanest path for raster-only pages might be to extract the embedded image directly and let each engine handle its own scaling — but that's a larger architectural question than this PR should carry.

I've reached out to Christoph Auer to discuss where Docling's scope ends and where orchestration-layer concerns begin. Depending on that conversation, the right home for "inspect embedded image metadata → choose rendering strategy" might be upstream in Docling, downstream in callers, or some combination. For now, the PATH-blocked-pages fix you identified seems like a clean follow-up to this PR regardless of how the bigger question resolves.

The scenarios you've surfaced also suggest there's value in a systematic factorial analysis across the input variables — embedded image resolution, effective pixels-per-stroke, noise/degradation level, contrast, presence of other page content — with generated test images under controlled conditions, measured against multiple OCR engines. The outcome would be empirical guidance on rendering strategy when we don't know the inputs up front: when does upsampling help vs. hurt, where are the engine-specific thresholds, what's the interaction between scan quality and model training. I haven't audited whether Docling's existing test corpus covers this parameter space, but if there are gaps, I'd be glad to contribute generated fixtures or run the matrix as part of work we're already doing on multi-engine benchmarking. Happy to coordinate with the Docling team on coverage if that's useful.

Happy to take your harness scripts if you want to share them — useful for validating the background-rect predicate.

@wittjeff wittjeff changed the title fix: avoid lossy supersample of raster-only (scanned) pages in PDFium-rendering backends fix(pypdfium2): render raster-only pages directly instead of supersampling Oct 4, 2026
@wittjeff
wittjeff force-pushed the fix/pypdfium-raster-supersample branch from 4759c96 to fd4148d Compare October 4, 2026 19:04
@wittjeff

wittjeff commented Oct 4, 2026

Copy link
Copy Markdown
Contributor Author

@faithpricejp-source Sorry for the long gap — and re-reading your review, I owe you a
correction on which part mattered.

You were right that the render-cost argument is the stronger one, and I didn't engage
with it at all.
My reply went off into the question of what scale to request in the
first place, and skipped your section 3 entirely:

old  1.92 s  (92 ms/page)
new  0.41 s  (20 ms/page)     4.68x faster
peak bitmap: 183 Mpx -> 81 Mpx   (2.25x fewer pixels rendered)

That is unconditional, it falls straight out of dropping a 2.25× oversized bitmap plus
a full-page Lanczos resize, and — as you put it — it holds regardless of whether OCR
quality moves. It also answers the review problem you identified in section 2: a
reviewer testing a clean scan sees no OCR difference and reasonably concludes the PR
does nothing. I'm rewriting the description around cost plus correctness, with the OCR
recovery as the conditional secondary claim it actually is, and re-measuring the timing
here rather than quoting your numbers, since it becomes the primary justification.

For the record, my A/B through the backend on 9 raster-only pages at scale=3.0
(best of 5 per page) gives 3.92 s → 1.45 s, 435 → 161 ms/page, 2.71× — lower than
your 4.68×, but with the identical 2.25× pixel reduction. That split makes sense:
the pixel factor is structural, just 1.5², while the time saving tracks machine and page
content. I've put both numbers in the description with that caveat, so a reviewer on
different hardware isn't surprised.

Your section 2 conclusion is the one I'd now put in the description verbatim in spirit:
the round-trip bites on scans that are already borderline for the engine, not on legible
scans generally. Thank you for killing your own scale=3 upsampling explanation by
re-running at scale=1.0 — that is the part that made the finding trustworthy rather
than just inconvenient.

On the background-rect gap: yes please, send the follow-up PR. 21 of 68 PATH-blocked
pages across 14 documents is worth recovering, and your predicate — opaque, single
closed rect, at least page bounds, drawn before the first image object — is the right
shape. The z-order caveat is the part I'd have got wrong without your data: the 2 of 22
IP cases, where the path is drawn over the image and could legitimately obscure
content, have to keep blocking the fast path.

Some API details I checked while confirming this is implementable, which may save you a
detour:

  • Draw order is already free. _is_raster_only() iterates
    page.get_objects(max_depth=16), and pdfium yields page objects in content-stream
    order, so "did a PATH appear before the first IMAGE" needs no extra call — just a flag
    in the existing loop.
  • The fill-colour accessor is FPDFPageObj_GetFillColor, not FPDFPath_GetFillColor.
    The latter does not exist in pypdfium2 5.13; I went looking for it first.
  • FPDFPath_CountSegments covers your 5-segment closed rect, FPDFPath_GetDrawMode
    separates fill from stroke, and PdfObject.get_bounds() gives the coverage test.

Two fixtures would make it reviewable on its own: one page with the blank fill under the
image (must take the fast path) and one with a fill over the image (must not).

One thing changed under the PR while it sat. #4244 refactored the docling-parse
backend to remove pypdfium entirely, which deleted the DoclingParsePageBackend class
that two of this PR's three commits modified. Those commits are obsolete, so the rebase
onto current main drops them and the PR is now a single commit scoped to the pypdfium2
backend — retitled accordingly. Your findings are unaffected: everything you measured
was on the pypdfium2 render path, which is the only pdfium-rendering path left.

And yes, I'd still like the harness scripts, mostly to validate the background-rect
predicate against something other than hand-made fixtures.

To be explicit about what I am not asking you to wait for: the optimal-scale question
from my last reply (inspect embedded image resolution, choose a render strategy
per-engine) is a larger architectural change than this PR should carry, and I don't want
it blocking yours.

🤖 Generated with Claude Code

@mergify

mergify Bot commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

Merge Protections

🟢 Merge protection satisfied — ready to merge.

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)(?:\(.+\))?(!)?:

@mergify

mergify Bot commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

Merge Protections

🟢 Merge protection satisfied — ready to merge.

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)(?:\(.+\))?(!)?:

@github-actions github-actions Bot added ai:ci-safe AI triage found no CI-safety concern (advisory) bug Something isn't working pdf PDF issue (except docling-parse) pdf parsing PDF issue related to docling-parse performance labels Nov 6, 2026
@github-actions

github-actions Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

AI triage (advisory)

Checked commit 1a04409b7b. The analysis read the diff only. It did not run code from this pull request.

The pypdfium2 backend now renders raster-only (scanned) pages directly at the requested scale. Pages with text or vector content still use 1.5x supersampling. The PR adds a PyPdfiumBackendOptions.supersample_factor option and tests.

CI safety: no concern found. A maintainer must still approve CI.

2 related pull request(s) in the same code
PR State Signal Assessment
#4781 open changes the same code related: Both PRs edit docling/backend/pypdfium2_backend.py, but in different places. This PR changes page image rendering. The other PR adds get_document_metadata() to the document backend.
#4244 merged referenced as #4244 related: This merged PR moved the docling-parse backend off pypdfium and kept PyPdfiumDocumentBackend. It shares no files with this PR and does not make the same change.

The ai:* labels are advisory. They do not approve CI and they do not add tests:full. A new push runs this check again.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI first review (advisory): no blocker found

This review covers the full diff at 12efbc1213. It read the code and did not run it.

The raster-only fast path in PyPdfiumPageBackend looks correct, and the raster-only test compares against a direct render. The risk is the new public option supersample_factor: the default PDF backend ignores it, and the description does not say so. Decide whether to add the option now or limit it to the pypdfium path.

A maintainer makes the merge decision. This review never approves the pull request.

Comment thread docling/datamodel/backend_options.py Resolved
@github-actions github-actions Bot added the ai:review-lgtm AI first review found no blocker or major issue (advisory) label Nov 6, 2026
MelvinAkothINGUBU and others added 2 commits November 6, 2026 04:46
PyPdfiumPageBackend.get_page_image() renders every page at 1.5x the
requested scale and PIL-resizes down. For vector content this sharpens
the output, but for image-only (scanned) pages it is a lossy resample
round-trip of already-rasterized pixels that can destroy borderline OCR
text detections (issue docling-project#3587).

- Render pages whose content is raster-only (image objects only, the
  common scanned-document case) directly at the requested scale.
- Add PdfBackendOptions.supersample_factor (default 1.5, preserving
  current behavior for pages with text/vector content); 1.0 disables
  supersampling entirely.
- Skip the PIL resize when the rendered bitmap already has the target
  pixel dimensions.

Resolves docling-project#3587

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: Jeff Witt <152964771+witt3rd@users.noreply.github.com>
The option lived on the shared PdfBackendOptions, but only the pypdfium2
backend reads it: the docling-parse backends render through their own
renderer and never supersampled. Move it to a PyPdfiumBackendOptions
subclass with kind "pypdfium", mirroring ThreadedDoclingParseBackendOptions,
and fall back to the default factor when a plain PdfBackendOptions is
passed. This keeps the shared options schema unchanged and makes the
backend scope explicit in the field description.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Jeff Witt <1848307+wittjeff@users.noreply.github.com>
@wittjeff
wittjeff force-pushed the fix/pypdfium-raster-supersample branch from 12efbc1 to 1a04409 Compare November 6, 2026 09:47
@github-actions github-actions Bot added ai:ci-safe AI triage found no CI-safety concern (advisory) and removed ai:ci-safe AI triage found no CI-safety concern (advisory) ai:review-lgtm AI first review found no blocker or major issue (advisory) labels Nov 6, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI first review (advisory): no blocker found

This review covers the full diff at 1a04409b7b. It read the code and did not run it.

No important defect found. The raster-only detection falls back to the old supersampling path on any non-image object or pdfium error. The new PyPdfiumBackendOptions is registered in the BackendOptions union, and the earlier question about a no-op option on the docling-parse backends is fixed by moving the field. I checked the get_objects recursion and render sizing in the installed pypdfium2, and I checked the test assertions against the old behavior. The raster-only test compares bytes with a direct render, so it fails on the old resample path.

Earlier findings

  • fixed (question): New supersample_factor option has no effect on the default PDF backend

A maintainer makes the merge decision. This review never approves the pull request.

@github-actions github-actions Bot added the ai:review-lgtm AI first review found no blocker or major issue (advisory) label Nov 6, 2026
@codecov

codecov Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Files with missing lines Patch % Lines
docling/backend/pypdfium2_backend.py 85.71% 3 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

This branch has not been deployed

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

Labels

ai:ci-safe AI triage found no CI-safety concern (advisory) ai:review-lgtm AI first review found no blocker or major issue (advisory) bug Something isn't working pdf parsing PDF issue related to docling-parse pdf PDF issue (except docling-parse) performance

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants