Skip to main content

docling_pdf/
pdfium_backend.rs

1//! The page walk of the PDF pipeline: per page, the geometry and links from
2//! the object model (`pdf_meta`), the text layer from the pure-Rust parser
3//! (`textparse`), the model-input bitmaps from the docling-parse renderer
4//! plugin, the Rust raster or the Rust page renderer — and, behind the
5//! `pdfium` feature, the pdfium library for `DOCLING_RS_RENDERER=pdfium`
6//! (docling's pypdfium2 chain) and for a file lopdf cannot read ([`native`]).
7//! The module keeps its historical name; every type in it is pdfium-free.
8
9#[cfg(feature = "render")]
10use crate::PdfError;
11#[cfg(feature = "ocr-prep")]
12use image::RgbImage;
13
14/// A run of text with its bounding box, in PDF points with a **top-left** origin
15/// (pdfium's native origin is bottom-left; we flip it to match docling's
16/// `BoundingBox(..., origin=TOPLEFT)`).
17#[derive(Debug, Clone)]
18pub struct TextCell {
19    pub text: String,
20    pub l: f32,
21    pub t: f32,
22    pub r: f32,
23    pub b: f32,
24}
25
26/// Pixels-per-point used to render page images. Layout is scale-invariant (it
27/// scales normalized boxes by the page point size), but OCR benefits from the
28/// extra resolution.
29pub const RENDER_SCALE: f32 = 2.0;
30
31/// One page's geometry, extracted text cells, and a rendered RGB image. The
32/// image is rendered at [`RENDER_SCALE`] pixels per PDF point; `image px =
33/// page point × scale`.
34#[derive(Clone)]
35pub struct PdfPage {
36    pub width: f32,
37    pub height: f32,
38    pub scale: f32,
39    pub cells: Vec<TextCell>,
40    /// Same text grouped for code regions: split only at pdfium space glyphs, so
41    /// monospace runs keep their source spacing instead of the prose heuristic's.
42    pub code_cells: Vec<TextCell>,
43    /// Per-word cells (one per word, not joined into lines) for TableFormer cell
44    /// matching.
45    pub word_cells: Vec<TextCell>,
46    /// Checkbox squares drawn on the page (#609): assembly gives each line
47    /// with one in front of it its own checkbox item. Empty without a text
48    /// layer (OCR pages) or vector paths.
49    pub checkboxes: Vec<crate::checkbox::CheckBox>,
50    /// The page's image placements (`[l, t, r, b]`, page points, the cells'
51    /// frame), as the text parser walks past them (#999) — what docling's
52    /// pdf-aware OCR calls the page's bitmaps: a layout region over one whose
53    /// text layer does not account for it is OCR'd even though it holds
54    /// programmatic text (a scan with a typed-in value). Empty without a text
55    /// layer (an OCR page is OCR'd whole anyway).
56    pub bitmaps: Vec<[f32; 4]>,
57    /// The page's vector shapes (`[l, t, r, b]`, page points, the cells'
58    /// frame) for the reading-order separators (#1092): stroked axis-aligned
59    /// segments and the boxes of connected painted paths, docling-parse's
60    /// `get_shape_lines` / `get_connected_shape_bounding_boxes`. Empty
61    /// without a text layer.
62    pub shapes: crate::textparse::PageShapes,
63    /// The rendered page bitmap. Present whenever pixels are available at all
64    /// (`ocr-prep` ⊂ `ml`): the native pipeline renders it with pdfium, the
65    /// browser pipeline receives it from the host canvas. Picture regions are
66    /// cropped out of it.
67    #[cfg(feature = "ocr-prep")]
68    pub image: RgbImage,
69    /// The **scale-1.0** page image the layout model runs on (parity with
70    /// docling's `PyPdfiumDocumentBackend`: the layout stage calls
71    /// `page.get_image(scale=1.0)`, which that backend serves as pdfium at
72    /// 1.5×, PIL-BICUBIC down to point size — a *different* image from the 2×
73    /// OCR/crop bitmap above, and a different resampling regime than
74    /// stretching that bitmap; docling 2.123+'s default docling-parse backend
75    /// renders the same request with its own Blend2D/FreeType renderer, whose
76    /// glyph anti-aliasing differs — #478). `None` on paths without a pdfium
77    /// renderer (browser, METS/TIFF), which fall back to stretching
78    /// [`Self::image`].
79    #[cfg(feature = "ocr-prep")]
80    pub image_layout: Option<RgbImage>,
81    /// The 2x bitmap of a page with a text layer, deferred to the page
82    /// walk's helper thread (#682): [`Self::image`] holds a 1×1 placeholder
83    /// until [`Self::resolve_image`] installs the render. The ML pipeline
84    /// resolves it after layout — the stage that reads
85    /// [`Self::image_layout`] instead — and only for a page whose detections
86    /// read the bitmap (tables, pictures, …; #897), so a text-only page never
87    /// draws it. `None` once resolved, and on every path that renders
88    /// synchronously (scanned pages, the plugin and pdfium renderers,
89    /// images, METS).
90    #[cfg(feature = "render")]
91    pub pending_image: Option<PendingImage>,
92    /// Hyperlink annotations on the page (rect in top-left page coords + target
93    /// URI), restricted to web/mail/tel schemes. Used only by strict Markdown.
94    pub links: Vec<LinkAnnot>,
95    /// The page's `/Rotate` value (0/90/180/270) when it was normalized away
96    /// before inference: a scanned page with `/Rotate` displays its raster
97    /// rotated, which turns OCR into garbage — so extraction un-rotates the
98    /// bitmaps (and swaps `width`/`height`) and records the display rotation
99    /// here. Assembly rotates the finished geometry *back* by this many
100    /// degrees clockwise, so emitted locations and the page size stay in
101    /// display space (matching docling and every PDF viewer). Always 0 for
102    /// text-layer pages (their cells live in display space already) and on
103    /// paths without a pdfium renderer.
104    pub rotation: u16,
105    /// Keep typographic punctuation as drawn — curly and low quotes, dashes,
106    /// `…`, `⁄`, `•` — instead of folding it to ASCII the way docling-parse's
107    /// sanitizer does (`pdf_keep_typography`, #921). Read by assembly.
108    pub keep_typography: bool,
109    /// The page's image placements (#1007, docling's
110    /// `use_embedded_picture_images`): a picture region matching exactly one
111    /// safe image gets that bitmap at native resolution instead of a render
112    /// crop. Empty unless the walk was asked for them
113    /// ([`TextOptions::embedded_pictures`]).
114    #[cfg(feature = "render")]
115    pub embedded_images: Vec<crate::embedded::EmbeddedImage>,
116}
117
118impl PdfPage {
119    /// A page built from recognized cells alone — the browser pipeline's
120    /// shape (#157), where the bitmap lives on the JS side. Exists so callers
121    /// compile identically with and without the `ml` feature: under a
122    /// feature-unified workspace build the struct carries the `image` field,
123    /// which a plain literal in a non-`ml` consumer can't spell.
124    #[cfg(feature = "ocr-prep")]
125    pub fn from_cells(width: f32, height: f32, scale: f32, cells: Vec<TextCell>) -> Self {
126        Self {
127            width,
128            height,
129            scale,
130            cells,
131            code_cells: Vec::new(),
132            word_cells: Vec::new(),
133            checkboxes: Vec::new(),
134            bitmaps: Vec::new(),
135            shapes: Default::default(),
136            #[cfg(feature = "ocr-prep")]
137            image: RgbImage::new(0, 0),
138            #[cfg(feature = "ocr-prep")]
139            image_layout: None,
140            #[cfg(feature = "render")]
141            pending_image: None,
142            links: Vec::new(),
143            rotation: 0,
144            keep_typography: false,
145            #[cfg(feature = "render")]
146            embedded_images: Vec::new(),
147        }
148    }
149
150    /// Wait for a deferred 2x render (#682) — starting it first when it was
151    /// left for on demand ([`BitmapRender::OnDemand`], #897) — and install it
152    /// as [`Self::image`]; a no-op when nothing is pending. The ML pipeline
153    /// calls it after layout for a page whose detections need the bitmap,
154    /// before anything reads it.
155    #[cfg(feature = "render")]
156    pub fn resolve_image(&mut self) -> Result<(), PdfError> {
157        if let Some(pending) = self.pending_image.take() {
158            self.image = crate::timing::timed("render.wait", || pending.wait())?;
159        }
160        Ok(())
161    }
162
163    /// Whether [`Self::image`] is still a placeholder for a deferred 2x
164    /// render ([`Self::resolve_image`] installs it).
165    #[cfg(feature = "render")]
166    pub fn image_pending(&self) -> bool {
167        self.pending_image.is_some()
168    }
169
170    /// Nothing is going to read this page's deferred 2x bitmap (#897): the
171    /// helper skips its render if it has not begun it. The page stays
172    /// pending — a later [`Self::resolve_image`] still gets the bitmap,
173    /// rendering it then if it was skipped.
174    #[cfg(feature = "render")]
175    pub fn decline_image(&self) {
176        if let Some(pending) = &self.pending_image {
177            pending.decline();
178        }
179    }
180
181    /// Same as [`from_cells`](Self::from_cells) but carrying the rendered page
182    /// bitmap, so picture regions can be cropped out of it (#157: the browser
183    /// pipeline gets the same figure bytes the native one does).
184    #[cfg(feature = "ocr-prep")]
185    pub fn from_cells_with_image(
186        width: f32,
187        height: f32,
188        scale: f32,
189        cells: Vec<TextCell>,
190        image: RgbImage,
191    ) -> Self {
192        Self {
193            image,
194            ..Self::from_cells(width, height, scale, cells)
195        }
196    }
197
198    /// Un-rotate the page's bitmaps by `deg` (clockwise 90° steps) and record
199    /// the compensating display rotation, composing with any rotation already
200    /// recorded: the raster becomes upright for inference while assembly
201    /// still maps the finished geometry back into display space. Handles both
202    /// `/Rotate` normalization (extraction) and content-detected orientation
203    /// (#225) — the two compose additively (axis-aligned 90° rotations
204    /// commute through the dimension swaps). Link rectangles follow the
205    /// raster; `width`/`height` swap on odd quarter-turns.
206    #[cfg(feature = "ocr-prep")]
207    pub(crate) fn unrotate(&mut self, deg: u16) {
208        if deg == 0 {
209            return;
210        }
211        use image::imageops::{rotate180, rotate270, rotate90};
212        // Display = upright rotated `deg`° clockwise, so upright = display
213        // rotated the complementary amount clockwise.
214        let un = |img: &RgbImage| match deg {
215            90 => rotate270(img),
216            180 => rotate180(img),
217            _ => rotate90(img),
218        };
219        if self.image.width() > 1 {
220            self.image = un(&self.image);
221        }
222        self.image_layout = self.image_layout.as_ref().map(&un);
223        let (width, height) = (self.width, self.height);
224        // Link rects follow the raster from display into upright space (the
225        // inverse of the geometry rotation assembly applies at the end).
226        for l in &mut self.links {
227            let (nl, nt, nr, nb) = match deg {
228                90 => (l.t, width - l.r, l.b, width - l.l),
229                180 => (width - l.r, height - l.b, width - l.l, height - l.t),
230                _ => (height - l.b, l.l, height - l.t, l.r),
231            };
232            (l.l, l.t, l.r, l.b) = (nl, nt, nr, nb);
233        }
234        // The text layer of a page with only a sparse one (a page number
235        // beside outlined text, #936) follows the raster the same way; a
236        // scan has none.
237        for c in self
238            .cells
239            .iter_mut()
240            .chain(&mut self.word_cells)
241            .chain(&mut self.code_cells)
242        {
243            let (nl, nt, nr, nb) = match deg {
244                90 => (c.t, width - c.r, c.b, width - c.l),
245                180 => (width - c.r, height - c.b, width - c.l, height - c.t),
246                _ => (height - c.b, c.l, height - c.t, c.r),
247            };
248            (c.l, c.t, c.r, c.b) = (nl, nt, nr, nb);
249        }
250        // Checkbox squares likewise (a scan has none; kept consistent).
251        for c in &mut self.checkboxes {
252            let (nl, nt, nr, nb) = match deg {
253                90 => (c.t, width - c.r, c.b, width - c.l),
254                180 => (width - c.r, height - c.b, width - c.l, height - c.t),
255                _ => (height - c.b, c.l, height - c.t, c.r),
256            };
257            (c.l, c.t, c.r, c.b) = (nl, nt, nr, nb);
258        }
259        if deg != 180 {
260            (self.width, self.height) = (height, width);
261        }
262        self.rotation = (self.rotation + deg) % 360;
263    }
264}
265
266/// A PDF link annotation: its rectangle (top-left page coordinates, matching
267/// [`TextCell`]) and target URI.
268#[derive(Debug, Clone)]
269pub struct LinkAnnot {
270    pub l: f32,
271    pub t: f32,
272    pub r: f32,
273    pub b: f32,
274    pub uri: String,
275}
276
277#[cfg(feature = "render")]
278/// A parsed PDF: per-page text cells and page images.
279pub struct PdfDocument {
280    pub pages: Vec<PdfPage>,
281}
282
283#[cfg(feature = "render")]
284impl PdfDocument {
285    /// Parse a PDF from bytes, optionally decrypting with `password`.
286    ///
287    /// Note: this materialises **every** page's rendered bitmap in memory at
288    /// once. For large documents prefer [`for_each_page`], which streams.
289    pub fn open(bytes: &[u8], password: Option<&str>) -> Result<Self, PdfError> {
290        let mut pages = Vec::new();
291        for_each_page::<PdfError, _>(bytes, password, true, true, None, |_, _, mut page| {
292            // Every page's bitmap, as documented — not the placeholder of a
293            // render still on the helper thread (#682).
294            page.resolve_image()?;
295            pages.push(page);
296            Ok(())
297        })?;
298        Ok(PdfDocument { pages })
299    }
300}
301
302#[cfg(feature = "render")]
303/// The document's text layer: the pure-Rust text parser (docling-parse's
304/// char geometry; the only text source since phase 4 of "Retiring pdfium" —
305/// on the whole corpus every page it reads no text from is one pdfium read
306/// no text from either, i.e. a scan for the OCR path). `None` for a file
307/// lopdf cannot open at all.
308fn rust_parser_cells(
309    bytes: &[u8],
310    password: Option<&str>,
311    word_gap: Option<crate::dp_lines::WordGap>,
312) -> Option<crate::textparse::PageTextParser> {
313    // Only the document load happens here; pages are parsed as the walk
314    // reaches them (`cells_timed`), so nothing is decoded for pages outside
315    // a `--pages` window and the parse overlaps the workers' inference.
316    crate::timing::timed("textparse.open", || {
317        let mut parser = crate::textparse::PageTextParser::open_with_password(bytes, password)?;
318        parser.set_word_gap(word_gap);
319        Some(parser)
320    })
321}
322
323impl crate::textparse::PageTextParser {
324    /// [`cells`](Self::cells) under the `textparse` timing stage (per page).
325    fn cells_timed(&mut self, index: usize) -> crate::textparse::PageParserCells {
326        crate::timing::timed("textparse", || self.cells(index))
327    }
328}
329
330#[cfg(feature = "render")]
331/// Number of pages in a PDF, without rendering any of them — used to decide
332/// whether a document is worth spinning up the parallel worker pool.
333pub fn page_count(bytes: &[u8], password: Option<&str>) -> Result<usize, PdfError> {
334    // The pure-Rust object model first, then the docling-parse plugin's
335    // count, then pdfium (the `pdfium` feature) — the order every entry point
336    // here follows.
337    if let Some(meta) = crate::timing::timed("meta.open", || {
338        crate::pdf_meta::PdfMeta::open_with_password(bytes, password)
339    })? {
340        return Ok(meta.page_count());
341    }
342    if let Some(dp) = crate::dparse_render::Doc::open_if_enabled(bytes, password) {
343        return Ok(dp.page_count());
344    }
345    crate::timing::timed("pdfium.page_count", || {
346        let lib = native::bind()?;
347        let n = lib.open(bytes, password)?.page_count();
348        Ok(n)
349    })
350}
351
352#[cfg(feature = "render")]
353/// Render + extract pages one at a time, handing each (owned) [`PdfPage`] to `f`.
354/// Only one page bitmap is resident at a time — a rendered page is ~5 MB, so a
355/// large PDF would otherwise hold gigabytes of bitmaps at once. `f` receives the
356/// zero-based page index and the total page count.
357///
358/// `render_image` controls whether the page bitmap is rasterized at all: layout,
359/// OCR, TableFormer, and picture cropping all need it, but a caller that skips
360/// every one of those (the `no_ocr` fast path) doesn't, and rasterizing +
361/// downsampling a page is by far the most expensive step per page — skipping it
362/// is most of `no_ocr`'s speedup. `PdfPage::image` is a 1×1 placeholder when
363/// `false`; do not read it.
364///
365/// `extract_text` decodes the page's text layer (parser or pdfium cells); pass
366/// `false` when full-page OCR is forced and the cells would be discarded
367/// unread (docling#4061).
368///
369/// `range` restricts the walk to a **0-based inclusive** page window (issue
370/// #80's `--pages`); out-of-window pages are skipped *before* text extraction
371/// and rasterization, so a 3-page window over a 500-page PDF costs three
372/// pages, not five hundred. `f` still receives the absolute page index, so
373/// downstream page numbering refers to the source document.
374///
375/// `E` is the caller's error type; [`PdfError`]s convert into it via `From`.
376///
377/// A page with a text layer may arrive with its 2x bitmap still rendering
378/// (#682): call [`PdfPage::resolve_image`] before reading [`PdfPage::image`].
379/// The render starts as the page leaves the walk; [`walk_pages`] with
380/// [`BitmapRender::OnDemand`] starts it only when resolved (#897).
381pub fn for_each_page<E, F>(
382    bytes: &[u8],
383    password: Option<&str>,
384    render_image: bool,
385    extract_text: bool,
386    range: Option<(usize, usize)>,
387    f: F,
388) -> Result<(), E>
389where
390    E: From<PdfError>,
391    F: FnMut(usize, usize, PdfPage) -> Result<(), E>,
392{
393    walk_pages(
394        bytes,
395        password,
396        render_image,
397        extract_text,
398        range,
399        BitmapRender::Eager,
400        TextOptions::from_env(),
401        f,
402    )
403}
404
405#[cfg(feature = "render")]
406/// When the 2x bitmap of a page with a text layer is rendered.
407#[derive(Clone, Copy, Debug, PartialEq, Eq)]
408pub enum BitmapRender {
409    /// As soon as the page leaves the walk, on the helper thread while
410    /// layout runs (#682) — for a caller that reads every page's bitmap.
411    Eager,
412    /// Started like [`Self::Eager`] while the document's recent pages mostly
413    /// read their bitmap, left [`Self::OnDemand`] while they mostly do not
414    /// (#897). Layout reads the separate 1x render, and a page whose
415    /// detections hold no table, picture or other bitmap consumer never
416    /// needs the 2x one: on a paper with a figure or table on most pages
417    /// the render overlaps layout as before; on prose the wasted renders go.
418    /// A started render the page then declines ([`PdfPage::decline_image`])
419    /// is still skipped if the helper has not begun it.
420    Adaptive,
421    /// Only once [`PdfPage::resolve_image`] asks for it (#897): no render is
422    /// ever wasted, but a page that needs one waits for it after layout
423    /// instead of having it drawn meanwhile.
424    OnDemand,
425}
426
427/// The text layer's settings a page walk applies (#921): the word-gap rule
428/// of the line and word cells, and whether assembly keeps typographic
429/// punctuation as drawn ([`PdfPage::keep_typography`]) — plus whether the
430/// walk lists each page's embedded images for the picture images (#1007).
431#[derive(Clone, Copy, Debug, Default, PartialEq)]
432pub struct TextOptions {
433    /// `None` = the process default (`DOCLING_RS_PDF_WORD_GAP`).
434    pub word_gap: Option<crate::dp_lines::WordGap>,
435    pub keep_typography: bool,
436    /// Collect [`PdfPage::embedded_images`] — docling's
437    /// `use_embedded_picture_images` (#1007). Off by default: the walk
438    /// then reads no image placements and decodes nothing.
439    pub embedded_pictures: bool,
440}
441
442impl TextOptions {
443    /// The process defaults: `DOCLING_RS_PDF_WORD_GAP` and
444    /// `DOCLING_RS_PDF_KEEP_TYPOGRAPHY`.
445    pub fn from_env() -> Self {
446        Self {
447            word_gap: None,
448            keep_typography: crate::assemble::keep_typography_from_env(),
449            embedded_pictures: false,
450        }
451    }
452}
453
454#[cfg(feature = "render")]
455/// [`for_each_page`] with the 2x bitmaps rendered as `bitmap` says, and the
456/// text layer's words split by `word_gap` (#921; `None` = the process
457/// default).
458#[allow(clippy::too_many_arguments)]
459pub fn walk_pages<E, F>(
460    bytes: &[u8],
461    password: Option<&str>,
462    render_image: bool,
463    extract_text: bool,
464    range: Option<(usize, usize)>,
465    bitmap: BitmapRender,
466    text: TextOptions,
467    mut f: F,
468) -> Result<(), E>
469where
470    E: From<PdfError>,
471    F: FnMut(usize, usize, PdfPage) -> Result<(), E>,
472{
473    // The pure-Rust object model: page count, geometry, `/Rotate`, links.
474    // `None` only for a file lopdf cannot read even after the parser's
475    // repairs; pdfium (the `pdfium` feature) then answers for it.
476    let meta = crate::timing::timed("meta.open", || {
477        crate::pdf_meta::PdfMeta::open_with_password(bytes, password)
478    })?;
479    // The docling-parse renderer (#478, `DOCLING_RS_RENDERER=docling-parse`):
480    // the page images the models see come from it when it is asked for.
481    let dparse = if render_image {
482        crate::dparse_render::Doc::open_if_enabled(bytes, password)
483    } else {
484        None
485    };
486    // pdfium, when it has a job (`bind_or_skip`).
487    let pdfium = bind_or_skip(meta.is_some())?;
488    let session = match &pdfium {
489        Some(p) => Some(p.open(bytes, password)?),
490        None => None,
491    };
492    // `extract_text = false` (full-page OCR forced, docling#4061 / 2.122):
493    // the text layer would be cleared unread, so neither the pure-Rust parser
494    // nor pdfium's text page is decoded at all — on vector-dense pages (CAD
495    // drawings as 100k+ path segments) that decode is most of the page cost.
496    let mut rust = if extract_text {
497        rust_parser_cells(bytes, password, text.word_gap)
498    } else {
499        None
500    };
501    // pdfium's count when it is loaded (a damaged file can make the two
502    // object models disagree, and pdfium's pages are the ones rendered), the
503    // object model's otherwise.
504    let total = match (&session, &meta) {
505        (Some(s), _) => s.page_count(),
506        (None, Some(m)) => m.page_count(),
507        (None, None) => 0,
508    };
509    // The object model's geometry and links are used whenever it read the same
510    // number of pages pdfium did (or pdfium is absent); a disagreeing file keeps
511    // pdfium's answers throughout.
512    //
513    // Shared, because the helper thread that renders the deferred 2x bitmaps
514    // (#682) outlives the walk: a page resolved on demand (#897) asks for its
515    // render after the walk has handed the last page over.
516    let meta = meta
517        .filter(|m| {
518            session
519                .as_ref()
520                .is_none_or(|s| s.page_count() == m.page_count())
521        })
522        .map(std::sync::Arc::new);
523    // The pure-Rust renderer (phase 3 of retiring pdfium): the model inputs
524    // of every page the plugin does not render and the Rust raster declines
525    // — the default renderer.
526    let renderer = match (&meta, render_image) {
527        (Some(m), true) => Some(crate::render::Renderer::new(m)),
528        _ => None,
529    };
530    let (first, last) = range.unwrap_or((0, total.saturating_sub(1)));
531    // The 2x bitmap of a page with a text layer renders on a helper thread
532    // (#682, `DeferredRender`) when the pure-Rust renderer is the only one
533    // drawing: the plugin and pdfium hold per-document handles the walk
534    // thread owns, so their pages render in place as before.
535    let defer = match (&meta, &renderer, &dparse, &session) {
536        (Some(m), Some(_), None, None) => DeferredRender::spawn(m.clone(), bitmap),
537        _ => None,
538    };
539    {
540        // Index the window directly: iterating pdfium's pages from page 0 and
541        // skipping to `first` would load (and close) every page before the
542        // window — ~0.7 ms each, 1.3 s of pure overhead for a one-page window
543        // over the 1913-page .NET reference.
544        for i in first..=last {
545            if i >= total {
546                break;
547            }
548            let page = match &session {
549                Some(s) => Some(s.page(i)?),
550                None => None,
551            };
552            let geom = match (&meta, &page) {
553                (Some(m), _) => m.geometry(i).ok_or_else(|| no_raster(i as i32))?,
554                (None, Some(p)) => p.geom(),
555                (None, None) => return Err(no_raster(i as i32).into()),
556            };
557            let links = match (&meta, &page) {
558                (Some(m), _) => m.links(i),
559                (None, Some(p)) => p.links(geom.unrotated().1),
560                (None, None) => Vec::new(),
561            };
562            let rc = rust.as_mut().map(|p| p.cells_timed(i));
563            let mut extracted = extract_page(
564                PageSources {
565                    page: page.as_ref(),
566                    dparse: dparse.as_ref(),
567                    meta: meta.as_deref(),
568                    renderer: renderer.as_ref(),
569                    defer: defer.as_ref(),
570                },
571                geom,
572                links,
573                i as i32,
574                rc,
575                render_image,
576            )?;
577            extracted.keep_typography = text.keep_typography;
578            if text.embedded_pictures && extracted.rotation == 0 {
579                if let Some(m) = meta.as_deref() {
580                    extracted.embedded_images = crate::timing::timed("embedded_images", || {
581                        crate::embedded::page_images(m, i)
582                    });
583                }
584            }
585            f(i, total, extracted)?;
586        }
587        // The helper ends once this sender and every page's handle are gone.
588        drop(defer);
589    }
590    // Tearing down the parsed document (hundreds of thousands of lopdf
591    // objects on a long PDF — 250 ms for the 1913-page .NET reference) is
592    // nobody's business but the allocator's: hand it to a detached thread so
593    // the last page's output isn't held up by it. `Arc`, not `Rc`, in the
594    // caches is what makes the parser `Send`.
595    if let Some(parser) = rust {
596        std::thread::spawn(move || crate::timing::timed("textparse.close", || drop(parser)));
597    }
598    Ok(())
599}
600
601/// One rasterized page from [`render_pages`] (#243): the absolute 1-based page
602/// number in the source document, the pixel dimensions, and the PNG bytes.
603#[cfg(feature = "render")]
604#[derive(Debug, Clone)]
605pub struct RenderedPage {
606    pub page_no: usize,
607    pub width: u32,
608    pub height: u32,
609    pub png: Vec<u8>,
610    /// The images the page's render drew as a placeholder block or left out,
611    /// each with the reason (#916) — empty when everything decoded. Only the
612    /// pure-Rust renderer reports; the docling-parse plugin and pdfium
613    /// renders leave it empty.
614    pub omissions: Vec<crate::render::Omission>,
615}
616
617/// Upper bound, in pixels, on a rendered page bitmap's side. A crafted PDF can
618/// declare an enormous `MediaBox` in a few hundred bytes; the page render then
619/// asks pdfium — and `into_rgb8` — to allocate `w * h * 4` bytes. At the
620/// pipeline's 3x supersample a 12000 pt box is 36000x36000 ~ 5 GB: pdfium
621/// returns an opaque internal error at the extreme, and just below it the
622/// `image` crate *panics* (a `TryReserveError`, not a recoverable error) when
623/// the allocation fails. Real pages, even large-format (A0 at 3x ~ 10110 px),
624/// stay well under this cap; it only rejects the implausible, turning an abort
625/// into a clean error. Mirrors `decode_image_limited`'s guard on the
626/// standalone-image path. `DOCLING_RS_MAX_RENDER_PIXELS` overrides it.
627#[cfg(feature = "render")]
628fn max_render_side() -> u32 {
629    static M: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
630    *M.get_or_init(|| docling_core::env::parse("DOCLING_RS_MAX_RENDER_PIXELS").unwrap_or(15_000))
631}
632
633/// Round float pixel dimensions to the `i32` pdfium wants, rejecting a page
634/// whose bitmap would exceed [`max_render_side`] on either side before either
635/// pdfium or `image` tries to allocate it.
636#[cfg(feature = "render")]
637fn checked_render_dims(
638    w_px: f64,
639    h_px: f64,
640    page_no: usize,
641) -> Result<(i32, i32), crate::PdfError> {
642    let cap = max_render_side();
643    let w = w_px.round().max(1.0);
644    let h = h_px.round().max(1.0);
645    if w > f64::from(cap) || h > f64::from(cap) {
646        return Err(crate::PdfError::Pdfium(format!(
647            "page {page_no}: render size {w:.0}x{h:.0} px exceeds the {cap}px per-side cap \
648             (raise DOCLING_RS_MAX_RENDER_PIXELS); the page's declared size is implausibly large"
649        )));
650    }
651    Ok((w as i32, h as i32))
652}
653
654#[cfg(feature = "render")]
655/// Rasterize a PDF's pages to PNG (#243) — the lean path behind serve's
656/// `to=images`: pdfium render only, no text extraction, no models, and only
657/// one page bitmap resident at a time (each is PNG-encoded and dropped before
658/// the next renders). `scale` is pixels per PDF point — 2.0 matches the
659/// pipeline's [`RENDER_SCALE`] (144 dpi). Unlike the pipeline's render there
660/// is no 1.5× supersample + downsample pass: that dance exists only because
661/// TableFormer is pixel-pinned to docling's bitmaps, and nothing downstream
662/// of this output is — a single render is nearly twice as fast.
663///
664/// `range` is a **1-based** inclusive page window (issue #80's `pages`
665/// semantics: the end clamps to the document, a start past the end errors).
666///
667/// pdfium is not thread-safe — callers must serialize this against any other
668/// pdfium use (docling-serve holds its pipeline mutex around this call for
669/// exactly that reason).
670pub fn render_pages(
671    bytes: &[u8],
672    password: Option<&str>,
673    range: Option<(usize, usize)>,
674    scale: f32,
675) -> Result<Vec<RenderedPage>, crate::PdfError> {
676    // The docling-parse renderer plugin renders the display bitmap when it is
677    // asked for (full-resolution bitmap decode: this is a viewer's render,
678    // not a model input); the Rust raster / renderer otherwise, pdfium under
679    // `DOCLING_RS_RENDERER=pdfium` or for a file lopdf cannot read.
680    let dparse = crate::dparse_render::Doc::open_if_enabled(bytes, password);
681    // The object model: the page count and the Rust raster / renderer.
682    let meta = crate::pdf_meta::PdfMeta::open_with_password(bytes, password)?;
683    let pdfium = match &dparse {
684        Some(_) => None,
685        None => bind_or_skip(meta.is_some())?,
686    };
687    let session = match &pdfium {
688        Some(p) => Some(p.open(bytes, password)?),
689        None => None,
690    };
691    let total = match (&session, &dparse, &meta) {
692        (Some(s), _, _) => s.page_count(),
693        (None, Some(dp), _) => dp.page_count(),
694        (None, None, Some(m)) => m.page_count(),
695        (None, None, None) => 0,
696    };
697    let (first, last) = match range {
698        None => (0, total.saturating_sub(1)),
699        Some((first, last)) => {
700            if first == 0 || last < first {
701                return Err(PdfError::Document(format!(
702                    "invalid page range {first}-{last} (pages are 1-based, first <= last)"
703                )));
704            }
705            if first > total {
706                return Err(PdfError::Document(format!(
707                    "page range {first}-{last} is outside the document ({total} page(s))"
708                )));
709            }
710            (first - 1, last.min(total) - 1)
711        }
712    };
713    let renderer = match (&dparse, &meta) {
714        // Page rasters a caller keeps decode every image at full size (the
715        // shim is asked with bitmap hint 0.0 below for the same reason).
716        (None, Some(m)) => Some(crate::render::Renderer::with_bitmap_hint(m, 0.0)),
717        _ => None,
718    };
719    let mut out = Vec::with_capacity(last.saturating_sub(first) + 1);
720    for i in first..=last {
721        if i >= total {
722            break;
723        }
724        // Both renderers apply /Rotate themselves, so the bitmap is the page as
725        // a viewer shows it — no orientation handling needed (the pipeline's
726        // scanned-page un-rotation is an OCR-conformance concern, not a display
727        // one).
728        // The plugin's canvas first (the renderer whenever it resolves), then
729        // the Rust raster of an image-only page (pdfium's bitmap byte for
730        // byte, no library needed) or the Rust page renderer, then pdfium
731        // (`DOCLING_RS_RENDERER=pdfium`, or a file lopdf cannot read).
732        // A page the per-side cap refuses is an error naming the cap (#916),
733        // not a missing renderer.
734        let rust = || -> Result<Option<RgbImage>, PdfError> {
735            let Some(g) = meta.as_ref().and_then(|m| m.geometry(i)) else {
736                return Ok(None);
737            };
738            let (tw, th) = checked_render_dims(
739                f64::from(g.width * scale),
740                f64::from(g.height * scale),
741                i + 1,
742            )?;
743            Ok(rust_bitmap(
744                meta.as_ref(),
745                renderer.as_ref(),
746                session.is_some(),
747                i as i32,
748                tw as u32,
749                th as u32,
750                0.0,
751            ))
752        };
753        let bitmap = match (&dparse, &session) {
754            (Some(dp), _) => {
755                crate::timing::timed("dparse.rasterize", || dp.render(i, f64::from(scale), 0.0))
756                    .map_err(PdfError::Document)?
757            }
758            (None, session) => match rust()? {
759                Some(img) => img,
760                None => {
761                    let Some(s) = session else {
762                        return Err(no_raster(i as i32));
763                    };
764                    let page = s.page(i)?;
765                    let (pw, ph) = page.size();
766                    let (tw, th) =
767                        checked_render_dims(f64::from(pw * scale), f64::from(ph * scale), i + 1)?;
768                    page.render(tw, th, "pdfium.rasterize")?
769                }
770            },
771        };
772        let mut png = Vec::new();
773        bitmap
774            .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
775            .map_err(|e| PdfError::Document(format!("PNG-encoding page {}: {e}", i + 1)))?;
776        out.push(RenderedPage {
777            page_no: i + 1,
778            width: bitmap.width(),
779            height: bitmap.height(),
780            png,
781            omissions: renderer
782                .as_ref()
783                .map(crate::render::Renderer::take_omissions)
784                .unwrap_or_default(),
785        });
786    }
787    Ok(out)
788}
789
790#[cfg(feature = "render")]
791/// The error for a page that needs a raster when the object model could not
792/// be read and neither the docling-parse renderer plugin nor pdfium is there.
793fn no_raster(index: i32) -> PdfError {
794    PdfError::Document(format!(
795        "page {}: no page renderer — the file's object model could not be read (lopdf), \
796         the docling-parse renderer plugin is not installed (.docling-parse/lib) and \
797         pdfium is not available (the `pdfium` feature + PDFIUM_DYNAMIC_LIB_PATH / \
798         .pdfium/lib)",
799        index + 1
800    ))
801}
802
803/// The pure-Rust bitmap of a page at `width` × `height`: the raster of an
804/// image-only page (`raster::render`, pdfium's bytes) when the page
805/// qualifies, the page renderer (`render`) otherwise — `None` only when the
806/// object model is not loaded, or when `DOCLING_RS_RENDERER=pdfium` asks for
807/// pdfium's render of a page the raster declines *and* pdfium's page is open
808/// (`pdfium_page`; a build or machine without the library degrades to the
809/// Rust renderer, as [`bind_or_skip`] warned).
810#[cfg(feature = "render")]
811fn rust_bitmap(
812    meta: Option<&crate::pdf_meta::PdfMeta>,
813    renderer: Option<&crate::render::Renderer<'_>>,
814    pdfium_page: bool,
815    index: i32,
816    width: u32,
817    height: u32,
818    bitmap_hint: f64,
819) -> Option<RgbImage> {
820    let meta = meta?;
821    if let Some(img) = crate::timing::timed("raster.render", || {
822        crate::raster::render(meta, index as usize, width, height)
823    }) {
824        return Some(img);
825    }
826    if pdfium_page && crate::dparse_render::choice() == crate::dparse_render::Choice::Pdfium {
827        return None;
828    }
829    let renderer = renderer?;
830    crate::timing::timed("render.page", || {
831        renderer.render_with_hint(index as usize, width, height, bitmap_hint)
832    })
833}
834
835#[cfg(feature = "render")]
836/// Bind pdfium for a conversion, or decide it can run without it. pdfium has
837/// a job in two cases only: its own render was asked for
838/// (`DOCLING_RS_RENDERER=pdfium`, which only the `pdfium` feature offers), or
839/// the pure-Rust object model could not read the file (`meta_ok` false) — then
840/// pdfium's page tree, geometry and render stand in, and a build without the
841/// feature (or without the library) fails the conversion with the hint.
842/// Otherwise the library is never loaded.
843fn bind_or_skip(meta_ok: bool) -> Result<Option<native::Lib>, PdfError> {
844    if meta_ok && crate::dparse_render::choice() != crate::dparse_render::Choice::Pdfium {
845        return Ok(None);
846    }
847    match native::bind() {
848        Ok(p) => Ok(Some(p)),
849        Err(e) if meta_ok => {
850            // The library was asked for by name and is not there: say so
851            // once, then degrade — the Rust renderer draws every page.
852            static WARNED: std::sync::Once = std::sync::Once::new();
853            WARNED.call_once(|| {
854                eprintln!(
855                    "docling-pdf: DOCLING_RS_RENDERER=pdfium but the pdfium library could not be \
856                     loaded ({e}); rendering with the Rust renderer"
857                );
858            });
859            Ok(None)
860        }
861        Err(e) => Err(e),
862    }
863}
864
865/// The native sources a page may draw on, each optional: pdfium's page handle
866/// (present only when [`bind_or_skip`] opened the library) and the
867/// docling-parse renderer (absent when the plugin is not asked for or no
868/// raster is wanted).
869#[cfg(feature = "render")]
870#[derive(Clone, Copy)]
871struct PageSources<'a> {
872    page: Option<&'a native::Page<'a>>,
873    dparse: Option<&'a crate::dparse_render::Doc>,
874    /// The object model, for the Rust raster of an image-only page.
875    meta: Option<&'a crate::pdf_meta::PdfMeta>,
876    /// The pure-Rust page renderer over the same object model (its
877    /// per-document caches live for the whole conversion).
878    renderer: Option<&'a crate::render::Renderer<'a>>,
879    /// The helper thread that renders the 2x bitmap of pages with a text
880    /// layer off the walk (#682); `None` when another renderer draws.
881    defer: Option<&'a DeferredRender>,
882}
883
884/// A page's 2x bitmap, rendered on the walk's helper thread (#682): queued
885/// until something asks for it ([`BitmapRender::OnDemand`]) or sent at once
886/// ([`BitmapRender::Eager`], [`BitmapRender::Adaptive`]), the result
887/// arriving through a one-shot channel. A sent job can be declined: the
888/// helper then skips it if it has not started it, and a later resolve sends
889/// it again (#897). Cloning a page clones the handle; whichever copy
890/// resolves first gets the bitmap. A handle dropped while still queued, or
891/// declined in time, costs nothing — the render never happens.
892#[cfg(feature = "render")]
893#[derive(Clone)]
894pub struct PendingImage(std::sync::Arc<std::sync::Mutex<Pending>>);
895
896/// The channel a sent job's bitmap comes back through.
897#[cfg(feature = "render")]
898type Reply = std::sync::mpsc::Receiver<Result<RgbImage, PdfError>>;
899
900/// Where a [`PendingImage`] stands: the job and the helper to send it to,
901/// plus — once sent — the reply channel and the flag that lets the helper
902/// skip it.
903#[cfg(feature = "render")]
904struct Pending {
905    spec: RenderSpec,
906    tx: std::sync::mpsc::Sender<RenderJob>,
907    sent: Option<(Reply, std::sync::Arc<std::sync::atomic::AtomicBool>)>,
908    taken: bool,
909    /// The document's recent verdicts, which [`BitmapRender::Adaptive`]
910    /// schedules by; this page's goes in once.
911    stats: std::sync::Arc<Verdicts>,
912    /// This page's verdict so far (`Some(true)` = read).
913    verdict: Option<bool>,
914}
915
916/// Whether the last [`Verdicts::WINDOW`] pages that reached a verdict read
917/// their 2x bitmap — what [`BitmapRender::Adaptive`] decides a new page's
918/// render by (#897).
919#[cfg(feature = "render")]
920#[derive(Default)]
921struct Verdicts(std::sync::Mutex<std::collections::VecDeque<bool>>);
922
923#[cfg(feature = "render")]
924impl Verdicts {
925    const WINDOW: usize = 8;
926
927    /// Record a page's verdict, or turn a declined page's into a read one.
928    fn record(&self, read: bool, replaces_decline: bool) {
929        let mut w = self.0.lock().unwrap_or_else(|p| p.into_inner());
930        if replaces_decline {
931            if let Some(v) = w.iter_mut().rev().find(|v| !**v) {
932                *v = true;
933            }
934            return;
935        }
936        if w.len() == Self::WINDOW {
937            w.pop_front();
938        }
939        w.push_back(read);
940    }
941
942    /// Start the next render now? Yes until a few verdicts are in (most
943    /// documents' first pages are not representative either way, and a
944    /// wrong "yes" costs one render, a wrong "no" one page's latency), then
945    /// while at least half of the window read theirs.
946    fn start_eagerly(&self) -> bool {
947        let w = self.0.lock().unwrap_or_else(|p| p.into_inner());
948        w.len() < 3 || 2 * w.iter().filter(|v| **v).count() >= w.len()
949    }
950}
951
952#[cfg(feature = "render")]
953impl Pending {
954    /// Send the job (again, after a skipped one) and keep its reply channel.
955    /// The helper runs while any job sender lives — this one included — so a
956    /// failed send means it died (a render panicked).
957    fn send(&mut self) -> Result<(), PdfError> {
958        let (reply, rx) = std::sync::mpsc::sync_channel(1);
959        let declined = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
960        self.tx
961            .send(RenderJob {
962                spec: self.spec,
963                declined: declined.clone(),
964                reply,
965            })
966            .map_err(|_| PdfError::Pdfium("page render thread ended early".into()))?;
967        self.sent = Some((rx, declined));
968        Ok(())
969    }
970}
971
972#[cfg(feature = "render")]
973impl PendingImage {
974    fn lock(&self) -> std::sync::MutexGuard<'_, Pending> {
975        self.0.lock().unwrap_or_else(|p| p.into_inner())
976    }
977
978    /// Hand the job to the helper, unless that happened already.
979    fn start(&self) {
980        let mut p = self.lock();
981        if p.sent.is_none() && !p.taken {
982            // A dead helper surfaces as the page's resolve error.
983            let _ = p.send();
984        }
985    }
986
987    /// Nothing will read this bitmap: let the helper skip the job if it has
988    /// not begun it (a job never sent stays unsent).
989    fn decline(&self) {
990        let mut p = self.lock();
991        if p.verdict.is_none() {
992            p.verdict = Some(false);
993            p.stats.record(false, false);
994        }
995        if let Some((_, declined)) = &p.sent {
996            declined.store(true, std::sync::atomic::Ordering::Relaxed);
997        }
998    }
999
1000    fn wait(self) -> Result<RgbImage, PdfError> {
1001        let mut p = self.lock();
1002        if p.taken {
1003            return Err(PdfError::Pdfium("page bitmap resolved twice".into()));
1004        }
1005        if p.verdict != Some(true) {
1006            p.stats.record(true, p.verdict == Some(false));
1007            p.verdict = Some(true);
1008        }
1009        loop {
1010            match &p.sent {
1011                None => p.send()?,
1012                Some((rx, declined)) => {
1013                    // Asked for after all: a job not yet begun renders.
1014                    declined.store(false, std::sync::atomic::Ordering::Relaxed);
1015                    match rx.recv() {
1016                        Ok(out) => {
1017                            p.taken = true;
1018                            p.sent = None;
1019                            return out;
1020                        }
1021                        // Skipped while declined (or the helper died, which
1022                        // the next send reports): send it again.
1023                        Err(_) => p.sent = None,
1024                    }
1025                }
1026            }
1027        }
1028    }
1029}
1030
1031#[cfg(feature = "render")]
1032impl std::fmt::Debug for PendingImage {
1033    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1034        f.write_str("PendingImage")
1035    }
1036}
1037
1038/// One deferred render: the 3x supersample of page `index` at `w` × `h`
1039/// with the decode `hint`, box-downscaled to `dw` × `dh` — exactly the
1040/// synchronous path's steps, on another thread.
1041#[cfg(feature = "render")]
1042#[derive(Clone, Copy)]
1043struct RenderSpec {
1044    index: i32,
1045    w: u32,
1046    h: u32,
1047    hint: f64,
1048    dw: u32,
1049    dh: u32,
1050}
1051
1052#[cfg(feature = "render")]
1053struct RenderJob {
1054    spec: RenderSpec,
1055    /// Set when the page turned out not to read the bitmap (#897): the
1056    /// helper skips the job if it gets to it after that — dropping `reply`,
1057    /// which tells a later resolve to send it again.
1058    declined: std::sync::Arc<std::sync::atomic::AtomicBool>,
1059    reply: std::sync::mpsc::SyncSender<Result<RgbImage, PdfError>>,
1060}
1061
1062/// The walk's render helper (#682): a second pure-Rust renderer, with its
1063/// own per-document caches, on its own thread, fed one [`RenderJob`] per
1064/// 2x bitmap asked for. Its bitmaps are the ones the walk thread would have
1065/// drawn — the same renderer code over the same object model — so the
1066/// output is byte-identical; what changes is that the page leaves the walk
1067/// as soon as its 1x layout image is drawn, and the 2x bitmap lands while
1068/// layout runs ([`BitmapRender::Eager`]) or when the page turns out to need
1069/// it ([`BitmapRender::OnDemand`], #897). Not scoped to the walk: a page
1070/// resolved on demand asks after the walk is over, so the thread holds the
1071/// object model and runs until the walk and every page's handle have let go
1072/// of the job sender.
1073#[cfg(feature = "render")]
1074struct DeferredRender {
1075    tx: std::sync::mpsc::Sender<RenderJob>,
1076    mode: BitmapRender,
1077    stats: std::sync::Arc<Verdicts>,
1078}
1079
1080#[cfg(feature = "render")]
1081impl DeferredRender {
1082    /// The helper for `meta`; `None` (render in place, as without one) when
1083    /// the thread cannot be spawned.
1084    fn spawn(meta: std::sync::Arc<crate::pdf_meta::PdfMeta>, mode: BitmapRender) -> Option<Self> {
1085        let (tx, rx) = std::sync::mpsc::channel();
1086        std::thread::Builder::new()
1087            .name("docling-pdf-render".into())
1088            .spawn(move || Self::serve(&meta, rx))
1089            .ok()?;
1090        Some(Self {
1091            tx,
1092            mode,
1093            stats: Default::default(),
1094        })
1095    }
1096
1097    fn submit(&self, index: i32, w: u32, h: u32, hint: f64, dw: u32, dh: u32) -> PendingImage {
1098        let spec = RenderSpec {
1099            index,
1100            w,
1101            h,
1102            hint,
1103            dw,
1104            dh,
1105        };
1106        let pending = PendingImage(std::sync::Arc::new(std::sync::Mutex::new(Pending {
1107            spec,
1108            tx: self.tx.clone(),
1109            sent: None,
1110            taken: false,
1111            stats: self.stats.clone(),
1112            verdict: None,
1113        })));
1114        let start = match self.mode {
1115            BitmapRender::Eager => true,
1116            BitmapRender::Adaptive => self.stats.start_eagerly(),
1117            BitmapRender::OnDemand => false,
1118        };
1119        if start {
1120            pending.start();
1121        }
1122        pending
1123    }
1124
1125    /// The helper's loop: runs until every job sender is dropped.
1126    fn serve(meta: &crate::pdf_meta::PdfMeta, jobs: std::sync::mpsc::Receiver<RenderJob>) {
1127        let renderer = crate::render::Renderer::new(meta);
1128        for RenderJob {
1129            spec,
1130            declined,
1131            reply,
1132        } in jobs
1133        {
1134            if declined.load(std::sync::atomic::Ordering::Relaxed) {
1135                if crate::timing::enabled() {
1136                    crate::timing::record("render.skipped", 0);
1137                }
1138                continue;
1139            }
1140            let out = rust_bitmap(
1141                Some(meta),
1142                Some(&renderer),
1143                false,
1144                spec.index,
1145                spec.w,
1146                spec.h,
1147                spec.hint,
1148            )
1149            .map(|big| {
1150                crate::timing::timed("image.resize", || fast_downscale(&big, spec.dw, spec.dh))
1151            })
1152            .ok_or_else(|| no_raster(spec.index));
1153            let _ = reply.send(out);
1154        }
1155    }
1156}
1157
1158#[cfg(feature = "render")]
1159fn extract_page(
1160    sources: PageSources<'_>,
1161    geom: crate::pdf_meta::PageGeom,
1162    links: Vec<LinkAnnot>,
1163    index: i32,
1164    rust_cells: Option<crate::textparse::PageParserCells>,
1165    render_image: bool,
1166) -> Result<PdfPage, PdfError> {
1167    let PageSources {
1168        page,
1169        dparse,
1170        meta,
1171        renderer,
1172        defer,
1173    } = sources;
1174    // The page size (and the render) is the *display* frame — `/Rotate`
1175    // applied — while every text coordinate (pdfium's own text page, the
1176    // pure-Rust parser's MediaBox-based glyphs, link annotation rects) lives
1177    // in the unrotated frame (docling#4008, 2.121). Keep the unrotated box
1178    // around for the y-flips and bring every rect into the display frame.
1179    let width = geom.width;
1180    let height = geom.height;
1181    let rotation = geom.rotation;
1182    let (unrot_w, unrot_h) = geom.unrotated();
1183
1184    // The text layer: the pure-Rust parser's prose, word and code cells (its
1185    // word grouping reproduces docling-parse's, which TableFormer matches
1186    // against). A page it reads nothing from is a scanned page for the OCR
1187    // path — pdfium's text page is gone (phase 4 of "Retiring pdfium").
1188    let rc = rust_cells.unwrap_or_default();
1189    let (mut cells, mut code_cells, mut word_cells) = (rc.prose, rc.code, rc.words);
1190    let mut checkboxes = rc.checkboxes;
1191    let mut bitmaps = rc.bitmaps;
1192    let mut shapes = rc.shapes;
1193    if rotation != 0 {
1194        for c in cells
1195            .iter_mut()
1196            .chain(word_cells.iter_mut())
1197            .chain(code_cells.iter_mut())
1198        {
1199            let (l, t, r, b) = to_display_frame((c.l, c.t, c.r, c.b), rotation, unrot_w, unrot_h);
1200            (c.l, c.t, c.r, c.b) = (l, t, r, b);
1201        }
1202        for c in &mut checkboxes {
1203            let (l, t, r, b) = to_display_frame((c.l, c.t, c.r, c.b), rotation, unrot_w, unrot_h);
1204            (c.l, c.t, c.r, c.b) = (l, t, r, b);
1205        }
1206        for [l, t, r, b] in bitmaps
1207            .iter_mut()
1208            .chain(shapes.lines.iter_mut())
1209            .chain(shapes.boxes.iter_mut())
1210        {
1211            let d = to_display_frame((*l, *t, *r, *b), rotation, unrot_w, unrot_h);
1212            (*l, *t, *r, *b) = d;
1213        }
1214    }
1215
1216    // The docling-parse renderer (#478, `dparse_render.rs`): the model inputs
1217    // come from docling-parse's Blend2D canvas, requested in docling's order
1218    // and with its decode hint — the scale-1.0 layout image (docling decodes
1219    // the page once, at its `render_scale` of 1.0), then the scale-2.0 bitmap
1220    // TableFormer crops from (`_render_image_at_scale` on the same decoder,
1221    // hence the same hint). One deliberate exception: a *scanned* page — no
1222    // text layer, the OCR path — keeps pdfium's bitmap. docling's 2.0/3.0
1223    // re-renders draw the raster its decoders reduced to 72 dpi, and Blend2D's
1224    // blit of a scan differs from pdfium's render + downscale in a way the
1225    // `ch` conformance recognizer feels (`scanned/ocr_test.pdf` read `JsON` for
1226    // `JSON` from either docling-parse raster, hint 1.0 or full resolution);
1227    // pdfium's raster is the one the scanned groundtruth was matched with, so
1228    // OCR keeps it (recorded in PDF_CONFORMANCE.md) — as long as pdfium is
1229    // loaded: a checkout with the plugin and no `libpdfium` OCRs the
1230    // docling-parse raster rather than failing the page (degradation over
1231    // failure). The canvases are `ceil`-sized where pdfium's are `round`ed;
1232    // every consumer maps points through `RENDER_SCALE`, not through the
1233    // image size, so the extra row/column is harmless.
1234    let scanned = cells.is_empty() && word_cells.is_empty() && code_cells.is_empty();
1235    let mut pending_image = None;
1236    let (mut dp_image, mut dp_layout) = (None, None);
1237    if let (true, Some(dp)) = (render_image, dparse) {
1238        let layout = crate::timing::timed("dparse.render_layout", || {
1239            dp.render(index as usize, 1.0, 1.0)
1240        })
1241        .map_err(PdfError::Document)?;
1242        if !scanned {
1243            let full = crate::timing::timed("dparse.render", || {
1244                dp.render(index as usize, f64::from(RENDER_SCALE), 1.0)
1245            })
1246            .map_err(PdfError::Document)?;
1247            dp_image = Some(full);
1248        }
1249        dp.release_page(index as usize);
1250        dp_layout = Some(layout);
1251    }
1252    // A scanned page's bitmap, in order: the pure-Rust raster (pdfium's bytes;
1253    // `raster`), pdfium itself, and — with neither — the plugin's scale-2.0
1254    // canvas rather than a failed page.
1255    let scanned_fallback = |page: Option<&native::Page<'_>>| match (page, dparse) {
1256        (None, Some(dp)) if scanned => {
1257            let full = crate::timing::timed("dparse.render", || {
1258                dp.render(index as usize, f64::from(RENDER_SCALE), 1.0)
1259            })
1260            .map_err(PdfError::Document)?;
1261            dp.release_page(index as usize);
1262            Ok(Some(full))
1263        }
1264        _ => Ok::<_, PdfError>(None),
1265    };
1266    let image = if let Some(img) = dp_image.take() {
1267        img
1268    } else if render_image {
1269        // docling's pypdfium2 backend renders at 1.5× the target scale and
1270        // downsamples "to make it sharper" (pypdfium2 → PIL BICUBIC). Replicate
1271        // exactly: the TableFormer model is pixel-sensitive, so the page bitmap
1272        // must match that backend's byte-for-byte (docling 2.123+'s default
1273        // docling-parse backend renders it itself — #478).
1274        // `CatmullRom` is the same a=-0.5 cubic kernel as PIL's BICUBIC.
1275        const SUPERSAMPLE: f32 = 1.5;
1276        // The 3x supersample is the largest bitmap the pipeline renders, so the
1277        // per-side cap is enforced here; the 1.5x layout render below is always
1278        // smaller and needs no separate guard.
1279        let (tw, th) = checked_render_dims(
1280            f64::from(width * RENDER_SCALE * SUPERSAMPLE),
1281            f64::from(height * RENDER_SCALE * SUPERSAMPLE),
1282            (index + 1) as usize,
1283        )?;
1284        // An image-only page (a scan) is rendered by the pure-Rust raster —
1285        // pdfium's bitmap byte for byte (`raster`, its oracle test) — and any
1286        // other page by the pure-Rust renderer (`render`), so the OCR path
1287        // needs no `libpdfium`; pdfium renders only when asked for
1288        // (`DOCLING_RS_RENDERER=pdfium`).
1289        let dw = (width * RENDER_SCALE).round().max(1.0) as u32;
1290        let dh = (height * RENDER_SCALE).round().max(1.0) as u32;
1291        // A page without a text layer takes this bitmap to OCR: decode its
1292        // images at full size (hint 0.0); a digital page's TableFormer input
1293        // follows docling's hint 1.0 like the layout image below.
1294        let hint = if cells.is_empty() { 0.0 } else { 1.0 };
1295        // A page with a text layer needs this bitmap only after layout
1296        // (TableFormer, crops): the helper thread draws it meanwhile (#682).
1297        // A scanned page reads it first (orientation, OCR) and renders here.
1298        if let (Some(defer), false) = (defer, scanned) {
1299            pending_image = Some(defer.submit(index, tw as u32, th as u32, hint, dw, dh));
1300            RgbImage::new(1, 1)
1301        } else {
1302            let big = match rust_bitmap(
1303                meta,
1304                renderer,
1305                page.is_some(),
1306                index,
1307                tw as u32,
1308                th as u32,
1309                hint,
1310            ) {
1311                Some(img) => Some(img),
1312                None if page.is_some() => {
1313                    let page = page.ok_or_else(|| no_raster(index))?;
1314                    Some(page.render(tw, th, "pdfium.render")?)
1315                }
1316                None => None,
1317            };
1318            match (big, scanned_fallback(page)?) {
1319                (Some(big), _) => {
1320                    crate::timing::timed("image.resize", || fast_downscale(&big, dw, dh))
1321                }
1322                (None, Some(canvas)) => canvas,
1323                (None, None) => return Err(no_raster(index)),
1324            }
1325        }
1326    } else {
1327        RgbImage::new(1, 1)
1328    };
1329    // The layout model's input image, built exactly like docling's pypdfium2
1330    // `get_page_image(scale=1.0)`: a pdfium render at 1.5× (pypdfium2 sizes
1331    // with `ceil`), PIL-BICUBIC down to the point-size image (PIL `resize`'s
1332    // default kernel; Python `round` = ties-to-even). Distinct from the 2×
1333    // bitmap above — resampling 1224→640 and 612→640 are different regimes,
1334    // and the heron model's borderline scores follow the pixels. "Exactly" is
1335    // against the pypdfium2 backend: docling 2.123+'s default docling-parse
1336    // backend renders this image with its own renderer (#478, see
1337    // docs/PDF_CONFORMANCE.md).
1338    let image_layout = if let Some(img) = dp_layout.take() {
1339        Some(img)
1340    } else if render_image {
1341        let tw = f64::from(width * 1.5).ceil().max(1.0) as i32;
1342        let th = f64::from(height * 1.5).ceil().max(1.0) as i32;
1343        let big = match rust_bitmap(
1344            meta,
1345            renderer,
1346            page.is_some(),
1347            index,
1348            tw as u32,
1349            th as u32,
1350            1.0,
1351        ) {
1352            Some(img) => img,
1353            None => {
1354                let page = page.ok_or_else(|| no_raster(index))?;
1355                page.render(tw, th, "pdfium.render_layout")?
1356            }
1357        };
1358        let dw = f64::from(width).round_ties_even().max(1.0) as u32;
1359        let dh = f64::from(height).round_ties_even().max(1.0) as u32;
1360        Some(crate::timing::timed("image.resize_layout", || {
1361            crate::resample::pil_resize(&big, dw, dh, crate::resample::PilFilter::Bicubic)
1362        }))
1363    } else {
1364        None
1365    };
1366
1367    let mut links = links;
1368    if rotation != 0 {
1369        for l in &mut links {
1370            let (a, t, r, b) = to_display_frame((l.l, l.t, l.r, l.b), rotation, unrot_w, unrot_h);
1371            (l.l, l.t, l.r, l.b) = (a, t, r, b);
1372        }
1373    }
1374
1375    // `/Rotate` normalization for scanned pages: pdfium renders the page as a
1376    // viewer displays it — `/Rotate` applied — so a rotated scan hands layout
1377    // and OCR a sideways/upside-down raster and the recognition output is
1378    // garbage. A page with a text layer needs none of this (its cells carry
1379    // the geometry; the models never see its pixels decide text), so the
1380    // normalization is gated to pages with no cells at all — exactly the set
1381    // the OCR path fires on. The bitmaps are un-rotated to upright (lossless
1382    // 90° steps), `width`/`height` swap to the upright box, and the display
1383    // rotation is recorded so assembly can rotate the finished geometry back
1384    // into display space (docling reports rotated pages in display coords).
1385    let mut page = PdfPage {
1386        width,
1387        height,
1388        scale: RENDER_SCALE,
1389        image_layout,
1390        pending_image,
1391        cells,
1392        code_cells,
1393        word_cells,
1394        checkboxes,
1395        bitmaps,
1396        shapes,
1397        image,
1398        links,
1399        rotation: 0,
1400        keep_typography: false,
1401        #[cfg(feature = "render")]
1402        embedded_images: Vec::new(),
1403    };
1404    if rotation != 0 && scanned && render_image {
1405        page.unrotate(rotation);
1406    }
1407    Ok(page)
1408}
1409
1410#[cfg(feature = "render")]
1411/// The supersample→target downscale via `fast_image_resize` (SIMD convolution;
1412/// the same a=-0.5 Catmull-Rom kernel as `image::imageops::resize(...,
1413/// CatmullRom)` and PIL BICUBIC — see the render comment above). Set
1414/// `DOCLING_RS_SLOW_RESIZE=1` to fall back to the `image`-crate scalar resize
1415/// (byte-parity with the pre-SIMD pipeline, several times slower).
1416fn fast_downscale(big: &RgbImage, dw: u32, dh: u32) -> RgbImage {
1417    use fast_image_resize as fir;
1418    static SLOW: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1419    let slow = *SLOW.get_or_init(|| docling_core::env::flag("DOCLING_RS_SLOW_RESIZE"));
1420    if !slow {
1421        if let Some(out) = (|| {
1422            let src = fir::images::ImageRef::new(
1423                big.width(),
1424                big.height(),
1425                big.as_raw(),
1426                fir::PixelType::U8x3,
1427            )
1428            .ok()?;
1429            let mut dst = fir::images::Image::new(dw, dh, fir::PixelType::U8x3);
1430            fir::Resizer::new()
1431                .resize(
1432                    &src,
1433                    &mut dst,
1434                    &fir::ResizeOptions::new()
1435                        .resize_alg(fir::ResizeAlg::Convolution(fir::FilterType::CatmullRom)),
1436                )
1437                .ok()?;
1438            RgbImage::from_raw(dw, dh, dst.into_vec())
1439        })() {
1440            return out;
1441        }
1442        // Unreachable in practice; fall through to the scalar path on any error.
1443    }
1444    image::imageops::resize(big, dw, dh, image::imageops::FilterType::CatmullRom)
1445}
1446
1447/// Map a top-left-origin rect from a page's unrotated (MediaBox) frame into its
1448/// `/Rotate`d display frame — the counterpart of docling's pypdfium2
1449/// `_rect_to_display_frame` (docling#4008) for our y-down coordinates.
1450/// `unrot_w`/`unrot_h` are the unrotated page box; the display box is the same
1451/// for 180° and swapped for 90°/270°.
1452pub(crate) fn to_display_frame(
1453    (l, t, r, b): (f32, f32, f32, f32),
1454    rotation: u16,
1455    unrot_w: f32,
1456    unrot_h: f32,
1457) -> (f32, f32, f32, f32) {
1458    match rotation {
1459        // Page turned 90° clockwise for display: the unrotated top edge becomes
1460        // the display right edge, so x' runs from the old bottom edge up.
1461        90 => (unrot_h - b, l, unrot_h - t, r),
1462        180 => (unrot_w - r, unrot_h - b, unrot_w - l, unrot_h - t),
1463        270 => (t, unrot_w - r, b, unrot_w - l),
1464        _ => (l, t, r, b),
1465    }
1466}
1467
1468/// One glyph: codepoint + native (y-up) box edges. `l/b/r/t` is pdfium's *tight*
1469/// ink box (used by the legacy `lines_from_glyphs`); `ll/lb/lr/lt` is the *loose*
1470/// box (font ascent/descent + advance — uniform per font/size), which the
1471/// docling-parse-style sanitizer needs so adjacent glyphs share a top edge.
1472pub(crate) struct Glyph {
1473    pub(crate) ch: char,
1474    pub(crate) l: f32,
1475    pub(crate) b: f32,
1476    pub(crate) r: f32,
1477    pub(crate) t: f32,
1478    pub(crate) ll: f32,
1479    pub(crate) lb: f32,
1480    pub(crate) lr: f32,
1481    pub(crate) lt: f32,
1482    /// Hash of the font's docling-parse name — `/FontDescriptor/FontName`,
1483    /// else `/Name`, else `/BaseFont` (#728: not the page's resource key, which
1484    /// binds one face under several keys) — 0 when not fetched. The sanitizer
1485    /// uses it for docling-parse's `enforce_same_font` (keeps a bold label and
1486    /// regular value as separate line cells, e.g. `LABEL : value`).
1487    pub(crate) font: u64,
1488    /// The loose box as the text matrix actually lays it — corners
1489    /// bottom-left, bottom-right, top-right, top-left as `[x0, y0, … x3, y3]`
1490    /// (docling-parse's `r_x0…r_y3`) — for a glyph whose baseline is **not**
1491    /// upright: rotated 90°/180°/270° or tilted (#528). `ll/lb/lr/lt` are then
1492    /// this quad's axis-aligned extent. `None` for upright text, whose quad is
1493    /// the `ll/lb/lr/lt` rectangle itself — that path stays exactly as it was.
1494    pub(crate) quad: Option<[f32; 8]>,
1495    /// Where the pen sets the glyph — the text origin on the baseline, rise
1496    /// included — and the font size in the same space, as `[x, y, size]`
1497    /// (docling-parse's `text_origin_x/y` and `nominal_text_height`). The
1498    /// word contraction tests a baseline shift on these (#921): the loose
1499    /// box's bottom sits a descent below the baseline, which differs between
1500    /// sizes, so a superscript read as shifted further than it is. `None`
1501    /// when unknown (a synthetic glyph); the box stands in then.
1502    pub(crate) pen: Option<[f32; 3]>,
1503    /// The glyph's font is a math face by its name (docling-parse's
1504    /// `has_math_positioning_semantics`): a sub- or superscript in it next to
1505    /// its base is attached, not a new word (#921).
1506    pub(crate) math_font: bool,
1507    /// Drawn in an invisible text rendering mode (`Tr` 3 or 7) — an OCR
1508    /// layer over a scan. Only the script-position stage reads it (#1005).
1509    pub(crate) invisible: bool,
1510}
1511
1512impl Glyph {
1513    /// The font's height on the glyph's own axis (ascent − descent): the
1514    /// loose box's height for upright text, the quad's left edge otherwise —
1515    /// a 90°-turned glyph's vertical extent is its advance, not its size.
1516    pub(crate) fn height(&self) -> f32 {
1517        match self.quad {
1518            Some(q) => (q[6] - q[0]).hypot(q[7] - q[1]),
1519            None => self.lt - self.lb,
1520        }
1521    }
1522}
1523
1524/// How [`lines_from_glyphs`] splits a line into words. Two more modes lived
1525/// here — the prose gap heuristic with punctuation glue and pdfium's
1526/// space-glyph-only code split — for pdfium's glyph stream; the parser's
1527/// prose goes through `dp_lines` and pdfium's text page is gone.
1528#[derive(Clone, Copy, PartialEq)]
1529enum Grouping {
1530    /// Split on the inter-glyph **gap** (or a space glyph), but never glue — for
1531    /// the parser's code cells: the parser emits no space glyphs (a source space
1532    /// is a positioning gap), and its clean advance boxes make the gap reliable.
1533    /// There is no punctuation glue, so a real gap always splits (`et al.
1534    /// 2000`, not `et al.2000`) while genuinely touching tokens stay joined
1535    /// (`add(a,` / `b)`).
1536    CodeGap,
1537}
1538
1539/// Group glyphs (document order) into words then lines, the way docling-parse
1540/// does: a new **word** starts where the horizontal gap to the previous glyph
1541/// exceeds ~0.2 × the font height (a real space is ~0.3 × height; letter
1542/// tracking is smaller, so titles don't shatter); a new **line** starts where
1543/// the baseline drops by ~half the font height (a superscript rises without
1544/// dropping, so it stays on its line). Coordinates are flipped to top-left.
1545/// See [`Grouping`] for how each mode decides word boundaries.
1546fn lines_from_glyphs(gs: &[Glyph], page_h: f32, mode: Grouping) -> Vec<TextCell> {
1547    let mut cells: Vec<TextCell> = Vec::new();
1548    let mut words: Vec<String> = Vec::new(); // words on the current line
1549    let mut word = String::new();
1550    // current line bounding box, native
1551    let (mut ll, mut lb, mut lr, mut lt) = (
1552        f32::INFINITY,
1553        f32::INFINITY,
1554        f32::NEG_INFINITY,
1555        f32::NEG_INFINITY,
1556    );
1557    // Tallest glyph seen on the current line: the word-gap threshold is relative
1558    // to it, so a small-font run on the line (a superscript citation) isn't split
1559    // at its tight digit gaps, while a big display title isn't split at its wider
1560    // letter tracking. A real inter-word space is ~0.3× the font height.
1561    let mut line_h: f32 = 0.0;
1562    let mut prev: Option<&Glyph> = None;
1563    // A space glyph between non-space glyphs pins a word split the gap heuristic
1564    // can miss (tight justified spacing); it carries no geometry.
1565    let mut pending_space = false;
1566
1567    for g in gs {
1568        if g.ch == ' ' {
1569            pending_space = true;
1570            continue;
1571        }
1572        let h = (g.t - g.b).abs().max(1.0);
1573        let (mut new_word, mut new_line) = (false, false);
1574        if let Some(p) = prev {
1575            // A new line drops the baseline *and* resets x leftward; requiring the
1576            // x-reset avoids a descending comma/semicolon faking a line break. A
1577            // *large* drop (≥1.5× the line height — a skipped line, e.g. a centered
1578            // page-number footer below a short last word) is always a new line,
1579            // even without the x-reset.
1580            // LTR wraps reset x leftward (`g.l < p.r`); RTL (Arabic) wraps reset
1581            // rightward (the new line begins at the far right). A large drop
1582            // (≥1.5× line height) is a new line regardless of x.
1583            let x_reset = if is_arabic(g.ch) || is_arabic(p.ch) {
1584                g.l > p.r
1585            } else {
1586                g.l < p.r
1587            };
1588            new_line = (p.b - g.b > h * 0.5 && x_reset) || (p.b - g.b > line_h.max(h) * 1.5);
1589            let word_gap = line_h.max(h) * 0.25;
1590            new_word = match mode {
1591                // Gap-based, no glue: a real gap always splits, touching tokens join.
1592                Grouping::CodeGap => new_line || pending_space || g.l - p.r > word_gap,
1593            };
1594        }
1595        pending_space = false;
1596        if new_line {
1597            push_word(&mut word, &mut words);
1598            push_line(&mut words, (ll, lb, lr, lt), page_h, &mut cells);
1599            (ll, lb, lr, lt) = (
1600                f32::INFINITY,
1601                f32::INFINITY,
1602                f32::NEG_INFINITY,
1603                f32::NEG_INFINITY,
1604            );
1605            line_h = 0.0;
1606        } else if new_word {
1607            push_word(&mut word, &mut words);
1608        }
1609        word.push(g.ch);
1610        ll = ll.min(g.l);
1611        lb = lb.min(g.b);
1612        lr = lr.max(g.r);
1613        lt = lt.max(g.t);
1614        line_h = line_h.max(h);
1615        prev = Some(g);
1616    }
1617    push_word(&mut word, &mut words);
1618    push_line(&mut words, (ll, lb, lr, lt), page_h, &mut cells);
1619    cells
1620}
1621
1622/// Code line cells from the parser's glyph stream. The parser emits no space
1623/// glyphs — a source space is a positioning gap — so code cells use
1624/// [`Grouping::CodeGap`], which splits on the inter-glyph gap (a space
1625/// wherever it exceeds ~0.25× the line height) but never glues punctuation,
1626/// so `et al. 2000` keeps its space while `add(a,` / `b)` stay joined. The
1627/// parser's clean advance boxes make the gap heuristic reliable here, where
1628/// pdfium's overhanging loose boxes used to over-split (`f un c t i o n`).
1629pub(crate) fn code_cells_from_glyphs(gs: &[Glyph], page_h: f32) -> Vec<TextCell> {
1630    lines_from_glyphs(gs, page_h, Grouping::CodeGap)
1631}
1632
1633fn is_arabic(c: char) -> bool {
1634    ('\u{0600}'..='\u{06FF}').contains(&c)
1635}
1636
1637fn push_word(word: &mut String, words: &mut Vec<String>) {
1638    if !word.is_empty() {
1639        words.push(std::mem::take(word));
1640    }
1641}
1642
1643fn push_line(
1644    words: &mut Vec<String>,
1645    bbox: (f32, f32, f32, f32),
1646    page_h: f32,
1647    cells: &mut Vec<TextCell>,
1648) {
1649    if words.is_empty() {
1650        return;
1651    }
1652    let text = std::mem::take(words).join(" ");
1653    let (l, b, r, t) = bbox;
1654    cells.push(TextCell {
1655        text,
1656        l,
1657        t: page_h - t,
1658        r,
1659        b: page_h - b,
1660    });
1661}
1662
1663/// The pdfium library, behind the `pdfium` feature (phase 5 of "Retiring
1664/// pdfium"): the render `DOCLING_RS_RENDERER=pdfium` asks for — docling's
1665/// pypdfium2 chain — the last resort for a file lopdf cannot read, and the
1666/// oracle of the raster and object-model tests. The default build has the
1667/// stub below and never links or loads pdfium.
1668#[cfg(feature = "pdfium")]
1669mod native {
1670    use super::LinkAnnot;
1671    use crate::PdfError;
1672    use image::RgbImage;
1673    use pdfium_render::prelude::*;
1674
1675    /// The bound library.
1676    pub(super) struct Lib(Pdfium);
1677    /// An open document.
1678    pub(super) struct Session<'a> {
1679        doc: PdfDocument<'a>,
1680    }
1681    /// A loaded page.
1682    pub(super) struct Page<'a>(PdfPage<'a>);
1683
1684    /// Try binding pdfium from a directory (or a literal library file path):
1685    /// `<dir>/<platform library name>` first, else `<dir>` itself as the file.
1686    fn try_bind_dir(path: &str) -> Option<Box<dyn PdfiumLibraryBindings>> {
1687        let name = Pdfium::pdfium_platform_library_name_at_path(path);
1688        if let Ok(b) = Pdfium::bind_to_library(&name) {
1689            return Some(b);
1690        }
1691        Pdfium::bind_to_library(path).ok()
1692    }
1693
1694    /// Bind to the pdfium dynamic library. Honors `PDFIUM_DYNAMIC_LIB_PATH` (a
1695    /// directory or file) first; else falls back to `.pdfium/lib` relative to
1696    /// the current directory (the layout `scripts/install/pdf_setup.sh`
1697    /// produces); else the system library.
1698    pub(super) fn bind() -> Result<Lib, PdfError> {
1699        if let Some(path) = docling_core::env::nonempty("PDFIUM_DYNAMIC_LIB_PATH") {
1700            if let Some(b) = try_bind_dir(&path) {
1701                return Ok(Lib(Pdfium::new(b)));
1702            }
1703        }
1704        if let Some(b) = try_bind_dir(&crate::resolve_asset(".pdfium/lib")) {
1705            return Ok(Lib(Pdfium::new(b)));
1706        }
1707        Pdfium::bind_to_system_library()
1708            .map(|b| Lib(Pdfium::new(b)))
1709            .map_err(Into::into)
1710    }
1711
1712    /// `bind()` for unit tests: point `PDFIUM_DYNAMIC_LIB_PATH` at the
1713    /// repo-root `.pdfium/lib` first (tests run with CWD = the crate dir,
1714    /// where the CWD-relative default cannot see it).
1715    #[cfg(test)]
1716    pub(crate) fn bind_for_tests() -> Result<Pdfium, PdfError> {
1717        if std::env::var_os("PDFIUM_DYNAMIC_LIB_PATH").is_none() {
1718            let lib = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.pdfium/lib");
1719            if lib.is_dir() {
1720                std::env::set_var("PDFIUM_DYNAMIC_LIB_PATH", &lib);
1721            }
1722        }
1723        bind().map(|l| l.0)
1724    }
1725
1726    impl Lib {
1727        pub(super) fn open<'a>(
1728            &'a self,
1729            bytes: &'a [u8],
1730            password: Option<&str>,
1731        ) -> Result<Session<'a>, PdfError> {
1732            crate::timing::timed("pdfium.open", || {
1733                self.0
1734                    .load_pdf_from_byte_slice(bytes, password)
1735                    .map(|doc| Session { doc })
1736                    .map_err(Into::into)
1737            })
1738        }
1739    }
1740
1741    impl Session<'_> {
1742        pub(super) fn page_count(&self) -> usize {
1743            self.doc.pages().len() as usize
1744        }
1745
1746        pub(super) fn page(&self, index: usize) -> Result<Page<'_>, PdfError> {
1747            self.doc
1748                .pages()
1749                .get(index as PdfPageIndex)
1750                .map(Page)
1751                .map_err(Into::into)
1752        }
1753    }
1754
1755    impl Page<'_> {
1756        /// The display size in points.
1757        pub(super) fn size(&self) -> (f32, f32) {
1758            (self.0.width().value, self.0.height().value)
1759        }
1760
1761        /// pdfium's view of the page's geometry, for the files lopdf cannot
1762        /// read — the same numbers `pdf_meta` computes from the object model.
1763        pub(super) fn geom(&self) -> crate::pdf_meta::PageGeom {
1764            crate::pdf_meta::PageGeom {
1765                width: self.0.width().value,
1766                height: self.0.height().value,
1767                rotation: match self.0.rotation() {
1768                    Ok(PdfPageRenderRotation::Degrees90) => 90u16,
1769                    Ok(PdfPageRenderRotation::Degrees180) => 180,
1770                    Ok(PdfPageRenderRotation::Degrees270) => 270,
1771                    _ => 0,
1772                },
1773            }
1774        }
1775
1776        /// Render the page into a `w` × `h` RGB bitmap under timing `stage`.
1777        pub(super) fn render(
1778            &self,
1779            w: i32,
1780            h: i32,
1781            stage: &'static str,
1782        ) -> Result<RgbImage, PdfError> {
1783            let cfg = PdfRenderConfig::new()
1784                .set_target_width(w)
1785                .set_target_height(h);
1786            crate::timing::timed(stage, || {
1787                self.0
1788                    .render_with_config(&cfg)
1789                    .map(|b| b.as_image().into_rgb8())
1790                    .map_err(Into::into)
1791            })
1792        }
1793
1794        /// Collect web/mail/tel hyperlink annotations on the page, mapping
1795        /// each link's rectangle into top-left page coordinates (like
1796        /// [`super::TextCell`]). `file://` and in-document destinations are
1797        /// skipped — only externally meaningful targets are rendered. pdfium
1798        /// occasionally lists a link twice; rects are kept as-is and the
1799        /// caller dedupes by resolved anchor text.
1800        pub(super) fn links(&self, page_h: f32) -> Vec<LinkAnnot> {
1801            let mut out = Vec::new();
1802            for link in self.0.links().iter() {
1803                let Some(uri) = link
1804                    .action()
1805                    .and_then(|a| a.as_uri_action().and_then(|u| u.uri().ok()))
1806                else {
1807                    continue;
1808                };
1809                let scheme_ok = ["http://", "https://", "mailto:", "tel:"]
1810                    .iter()
1811                    .any(|s| uri.starts_with(s));
1812                if !scheme_ok {
1813                    continue;
1814                }
1815                if let Ok(rect) = link.rect() {
1816                    out.push(LinkAnnot {
1817                        l: rect.left().value,
1818                        t: page_h - rect.top().value,
1819                        r: rect.right().value,
1820                        b: page_h - rect.bottom().value,
1821                        uri,
1822                    });
1823                }
1824            }
1825            out
1826        }
1827    }
1828}
1829
1830/// The `pdfium`-less build: pdfium never binds, so every entry point falls
1831/// through to the pure-Rust stack, and a file the object model cannot read
1832/// fails with [`no_raster`]'s hint.
1833#[cfg(all(feature = "render", not(feature = "pdfium")))]
1834mod native {
1835    use super::LinkAnnot;
1836    use crate::PdfError;
1837    use image::RgbImage;
1838    use std::convert::Infallible;
1839    use std::marker::PhantomData;
1840
1841    pub(super) struct Lib(Infallible);
1842    pub(super) struct Session<'a>(Infallible, PhantomData<&'a ()>);
1843    pub(super) struct Page<'a>(Infallible, PhantomData<&'a ()>);
1844
1845    /// Reached only for a file the pure-Rust object model could not read
1846    /// (every entry point tries it first), so the error is about the file:
1847    /// naming the missing library sent users of a corrupt or non-PDF upload
1848    /// looking for a pdfium install that would not have helped either.
1849    pub(super) fn bind() -> Result<Lib, PdfError> {
1850        Err(PdfError::Document(crate::UNREADABLE.into()))
1851    }
1852
1853    impl Lib {
1854        pub(super) fn open<'a>(
1855            &'a self,
1856            _bytes: &'a [u8],
1857            _password: Option<&str>,
1858        ) -> Result<Session<'a>, PdfError> {
1859            match self.0 {}
1860        }
1861    }
1862
1863    impl Session<'_> {
1864        pub(super) fn page_count(&self) -> usize {
1865            match self.0 {}
1866        }
1867
1868        pub(super) fn page(&self, _index: usize) -> Result<Page<'_>, PdfError> {
1869            match self.0 {}
1870        }
1871    }
1872
1873    impl Page<'_> {
1874        pub(super) fn size(&self) -> (f32, f32) {
1875            match self.0 {}
1876        }
1877
1878        pub(super) fn geom(&self) -> crate::pdf_meta::PageGeom {
1879            match self.0 {}
1880        }
1881
1882        pub(super) fn render(
1883            &self,
1884            _w: i32,
1885            _h: i32,
1886            _stage: &'static str,
1887        ) -> Result<RgbImage, PdfError> {
1888            match self.0 {}
1889        }
1890
1891        pub(super) fn links(&self, _page_h: f32) -> Vec<LinkAnnot> {
1892            match self.0 {}
1893        }
1894    }
1895}
1896
1897#[cfg(all(test, feature = "pdfium"))]
1898pub(crate) use native::bind_for_tests;
1899
1900#[cfg(test)]
1901mod tests {
1902    use super::{checked_render_dims, max_render_side, to_display_frame};
1903
1904    /// #897: the adaptive schedule starts renders eagerly for the first
1905    /// pages, then while at least half of the last 8 verdicts read the
1906    /// bitmap; a declined page that turns out to read it counts as read.
1907    #[cfg(feature = "render")]
1908    #[test]
1909    fn adaptive_verdicts() {
1910        let v = super::Verdicts::default();
1911        assert!(v.start_eagerly(), "no verdict yet");
1912        v.record(false, false);
1913        v.record(false, false);
1914        assert!(v.start_eagerly(), "still warming up");
1915        v.record(false, false);
1916        assert!(!v.start_eagerly(), "three text-only pages");
1917        v.record(true, true); // the last declined one was read after all
1918        v.record(true, false);
1919        assert!(v.start_eagerly(), "2 of 4 read");
1920        for _ in 0..8 {
1921            v.record(false, false);
1922        }
1923        assert!(!v.start_eagerly(), "the window forgets the read ones");
1924        for _ in 0..4 {
1925            v.record(true, false);
1926        }
1927        assert!(v.start_eagerly(), "4 of the last 8 read");
1928    }
1929
1930    /// The pure-Rust object model must answer exactly what pdfium answers —
1931    /// page count, display size, `/Rotate`, URI links — on every corpus PDF,
1932    /// or a checkout without pdfium would convert differently. Needs the
1933    /// library; skips cleanly without it (CI has no pdfium).
1934    #[test]
1935    #[cfg(feature = "pdfium")]
1936    fn pdf_meta_matches_pdfium_on_the_corpus() {
1937        let Ok(_) = super::bind_for_tests() else {
1938            eprintln!("skipping: pdfium not found");
1939            return;
1940        };
1941        let lib = super::native::bind().unwrap();
1942        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
1943        let mut files: Vec<std::path::PathBuf> = Vec::new();
1944        for dir in ["tests/data/pdf/sources", "tests/data/scanned/sources"] {
1945            let Ok(rd) = std::fs::read_dir(root.join(dir)) else {
1946                continue;
1947            };
1948            files.extend(
1949                rd.flatten()
1950                    .map(|e| e.path())
1951                    .filter(|p| p.extension().is_some_and(|e| e == "pdf")),
1952            );
1953        }
1954        files.sort();
1955        assert!(!files.is_empty(), "corpus not found");
1956        let mut checked = 0;
1957        for path in files {
1958            let bytes = std::fs::read(&path).unwrap();
1959            let Ok(doc) = lib.open(&bytes, None) else {
1960                continue; // password fixtures etc.
1961            };
1962            let Some(meta) = crate::pdf_meta::PdfMeta::open(&bytes) else {
1963                panic!(
1964                    "{}: lopdf could not read a file pdfium reads",
1965                    path.display()
1966                );
1967            };
1968            assert_eq!(meta.page_count(), doc.page_count(), "{}", path.display());
1969            for i in 0..meta.page_count() {
1970                let page = doc.page(i).unwrap();
1971                let want = page.geom();
1972                let got = meta.geometry(i).unwrap();
1973                assert!(
1974                    (got.width - want.width).abs() < 0.01
1975                        && (got.height - want.height).abs() < 0.01
1976                        && got.rotation == want.rotation,
1977                    "{} p{}: meta {got:?} vs pdfium {want:?}",
1978                    path.display(),
1979                    i + 1
1980                );
1981                let mut want_links = page.links(want.unrotated().1);
1982                let mut got_links = meta.links(i);
1983                let key = |l: &super::LinkAnnot| {
1984                    (
1985                        l.uri.clone(),
1986                        (l.l * 10.0) as i64,
1987                        (l.t * 10.0) as i64,
1988                        (l.r * 10.0) as i64,
1989                        (l.b * 10.0) as i64,
1990                    )
1991                };
1992                want_links.sort_by_key(key);
1993                got_links.sort_by_key(key);
1994                let want_keys: Vec<_> = want_links.iter().map(key).collect();
1995                let got_keys: Vec<_> = got_links.iter().map(key).collect();
1996                assert_eq!(got_keys, want_keys, "{} p{}: links", path.display(), i + 1);
1997                checked += 1;
1998            }
1999        }
2000        eprintln!("pdf_meta checked against pdfium on {checked} pages");
2001    }
2002
2003    /// A page whose declared size renders past the per-side cap is rejected
2004    /// with a recoverable error, before pdfium or `image` allocates the
2005    /// multi-gigabyte bitmap that would otherwise abort the process; a normal
2006    /// page passes through with its dimensions rounded to `i32`.
2007    #[test]
2008    fn oversized_render_is_rejected_not_allocated() {
2009        let cap = f64::from(max_render_side());
2010        // A 12000 pt box at the pipeline's 3x supersample is 36000 px/side.
2011        let huge = checked_render_dims(cap + 1.0, 10.0, 1);
2012        assert!(huge.is_err(), "over-cap width must be rejected");
2013        let tall = checked_render_dims(10.0, cap + 1.0, 7);
2014        assert!(tall.is_err(), "over-cap height must be rejected");
2015        assert!(
2016            tall.unwrap_err().to_string().contains("page 7"),
2017            "the error names the offending page"
2018        );
2019        // A Letter page at 2x supersample (612x792 pt -> 1836x2376 px) is fine.
2020        assert_eq!(
2021            checked_render_dims(1836.4, 2375.6, 1).unwrap(),
2022            (1836, 2376)
2023        );
2024        // Exactly at the cap is allowed; a zero-or-negative size floors to 1.
2025        assert_eq!(
2026            checked_render_dims(cap, cap, 1).unwrap(),
2027            (cap as i32, cap as i32)
2028        );
2029        assert_eq!(checked_render_dims(0.0, 0.0, 1).unwrap(), (1, 1));
2030    }
2031
2032    /// A 612×792 portrait page displayed under `/Rotate`: a rect near the
2033    /// unrotated top-left lands where a viewer shows it (docling#4008).
2034    #[test]
2035    fn display_frame_follows_the_page_rotation() {
2036        let r = (72.0, 63.0, 387.0, 74.0); // top-left origin, unrotated
2037        assert_eq!(to_display_frame(r, 0, 612.0, 792.0), r);
2038        // 90° clockwise: the page becomes 792×612; the old top edge is the
2039        // display right edge, old left edge the display top.
2040        assert_eq!(
2041            to_display_frame(r, 90, 612.0, 792.0),
2042            (718.0, 72.0, 729.0, 387.0)
2043        );
2044        // 180°: both axes mirror inside the same box.
2045        assert_eq!(
2046            to_display_frame(r, 180, 612.0, 792.0),
2047            (225.0, 718.0, 540.0, 729.0)
2048        );
2049        // 270°: the old top edge is the display left edge, old right edge the
2050        // display top.
2051        assert_eq!(
2052            to_display_frame(r, 270, 612.0, 792.0),
2053            (63.0, 225.0, 74.0, 540.0)
2054        );
2055    }
2056
2057    #[test]
2058    fn display_frame_rotations_compose_to_identity() {
2059        let r = (10.0, 20.0, 110.0, 40.0);
2060        // 90° then 270° from the intermediate (792×612) box round-trips.
2061        let once = to_display_frame(r, 90, 612.0, 792.0);
2062        assert_eq!(to_display_frame(once, 270, 792.0, 612.0), r);
2063        let twice = to_display_frame(to_display_frame(r, 180, 612.0, 792.0), 180, 612.0, 792.0);
2064        assert_eq!(twice, r);
2065    }
2066}