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