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