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 = "ml")]
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 /// The rendered page bitmap. Present whenever pixels are available at all
47 /// (`ocr-prep` ⊂ `ml`): the native pipeline renders it with pdfium, the
48 /// browser pipeline receives it from the host canvas. Picture regions are
49 /// cropped out of it.
50 #[cfg(feature = "ocr-prep")]
51 pub image: RgbImage,
52 /// The **scale-1.0** page image the layout model runs on (parity with
53 /// docling's `PyPdfiumDocumentBackend`: the layout stage calls
54 /// `page.get_image(scale=1.0)`, which that backend serves as pdfium at
55 /// 1.5×, PIL-BICUBIC down to point size — a *different* image from the 2×
56 /// OCR/crop bitmap above, and a different resampling regime than
57 /// stretching that bitmap; docling 2.123+'s default docling-parse backend
58 /// renders the same request with its own Blend2D/FreeType renderer, whose
59 /// glyph anti-aliasing differs — #478). `None` on paths without a pdfium
60 /// renderer (browser, METS/TIFF), which fall back to stretching
61 /// [`Self::image`].
62 #[cfg(feature = "ocr-prep")]
63 pub image_layout: Option<RgbImage>,
64 /// Hyperlink annotations on the page (rect in top-left page coords + target
65 /// URI), restricted to web/mail/tel schemes. Used only by strict Markdown.
66 pub links: Vec<LinkAnnot>,
67 /// The page's `/Rotate` value (0/90/180/270) when it was normalized away
68 /// before inference: a scanned page with `/Rotate` displays its raster
69 /// rotated, which turns OCR into garbage — so extraction un-rotates the
70 /// bitmaps (and swaps `width`/`height`) and records the display rotation
71 /// here. Assembly rotates the finished geometry *back* by this many
72 /// degrees clockwise, so emitted locations and the page size stay in
73 /// display space (matching docling and every PDF viewer). Always 0 for
74 /// text-layer pages (their cells live in display space already) and on
75 /// paths without a pdfium renderer.
76 pub rotation: u16,
77}
78
79impl PdfPage {
80 /// A page built from recognized cells alone — the browser pipeline's
81 /// shape (#157), where the bitmap lives on the JS side. Exists so callers
82 /// compile identically with and without the `ml` feature: under a
83 /// feature-unified workspace build the struct carries the `image` field,
84 /// which a plain literal in a non-`ml` consumer can't spell.
85 #[cfg(feature = "ocr-prep")]
86 pub fn from_cells(width: f32, height: f32, scale: f32, cells: Vec<TextCell>) -> Self {
87 Self {
88 width,
89 height,
90 scale,
91 cells,
92 code_cells: Vec::new(),
93 word_cells: Vec::new(),
94 #[cfg(feature = "ocr-prep")]
95 image: RgbImage::new(0, 0),
96 #[cfg(feature = "ocr-prep")]
97 image_layout: None,
98 links: Vec::new(),
99 rotation: 0,
100 }
101 }
102
103 /// Same as [`from_cells`](Self::from_cells) but carrying the rendered page
104 /// bitmap, so picture regions can be cropped out of it (#157: the browser
105 /// pipeline gets the same figure bytes the native one does).
106 #[cfg(feature = "ocr-prep")]
107 pub fn from_cells_with_image(
108 width: f32,
109 height: f32,
110 scale: f32,
111 cells: Vec<TextCell>,
112 image: RgbImage,
113 ) -> Self {
114 Self {
115 image,
116 ..Self::from_cells(width, height, scale, cells)
117 }
118 }
119
120 /// Un-rotate the page's bitmaps by `deg` (clockwise 90° steps) and record
121 /// the compensating display rotation, composing with any rotation already
122 /// recorded: the raster becomes upright for inference while assembly
123 /// still maps the finished geometry back into display space. Handles both
124 /// `/Rotate` normalization (extraction) and content-detected orientation
125 /// (#225) — the two compose additively (axis-aligned 90° rotations
126 /// commute through the dimension swaps). Link rectangles follow the
127 /// raster; `width`/`height` swap on odd quarter-turns.
128 #[cfg(feature = "ocr-prep")]
129 pub(crate) fn unrotate(&mut self, deg: u16) {
130 if deg == 0 {
131 return;
132 }
133 use image::imageops::{rotate180, rotate270, rotate90};
134 // Display = upright rotated `deg`° clockwise, so upright = display
135 // rotated the complementary amount clockwise.
136 let un = |img: &RgbImage| match deg {
137 90 => rotate270(img),
138 180 => rotate180(img),
139 _ => rotate90(img),
140 };
141 if self.image.width() > 1 {
142 self.image = un(&self.image);
143 }
144 self.image_layout = self.image_layout.as_ref().map(&un);
145 let (width, height) = (self.width, self.height);
146 // Link rects follow the raster from display into upright space (the
147 // inverse of the geometry rotation assembly applies at the end).
148 for l in &mut self.links {
149 let (nl, nt, nr, nb) = match deg {
150 90 => (l.t, width - l.r, l.b, width - l.l),
151 180 => (width - l.r, height - l.b, width - l.l, height - l.t),
152 _ => (height - l.b, l.l, height - l.t, l.r),
153 };
154 (l.l, l.t, l.r, l.b) = (nl, nt, nr, nb);
155 }
156 if deg != 180 {
157 (self.width, self.height) = (height, width);
158 }
159 self.rotation = (self.rotation + deg) % 360;
160 }
161}
162
163/// A PDF link annotation: its rectangle (top-left page coordinates, matching
164/// [`TextCell`]) and target URI.
165#[derive(Debug, Clone)]
166pub struct LinkAnnot {
167 pub l: f32,
168 pub t: f32,
169 pub r: f32,
170 pub b: f32,
171 pub uri: String,
172}
173
174#[cfg(feature = "ml")]
175/// A parsed PDF: per-page text cells and page images.
176pub struct PdfDocument {
177 pub pages: Vec<PdfPage>,
178}
179
180#[cfg(feature = "ml")]
181impl PdfDocument {
182 /// Parse a PDF from bytes, optionally decrypting with `password`.
183 ///
184 /// Note: this materialises **every** page's rendered bitmap in memory at
185 /// once. For large documents prefer [`for_each_page`], which streams.
186 pub fn open(bytes: &[u8], password: Option<&str>) -> Result<Self, PdfError> {
187 let mut pages = Vec::new();
188 for_each_page::<PdfError, _>(bytes, password, true, true, None, |_, _, page| {
189 pages.push(page);
190 Ok(())
191 })?;
192 Ok(PdfDocument { pages })
193 }
194}
195
196#[cfg(feature = "ml")]
197/// The document's text layer: the pure-Rust text parser (docling-parse's
198/// char geometry; the only text source since phase 4 of "Retiring pdfium" —
199/// on the whole corpus every page it reads no text from is one pdfium read
200/// no text from either, i.e. a scan for the OCR path). `None` for a file
201/// lopdf cannot open at all.
202fn rust_parser_cells(
203 bytes: &[u8],
204 password: Option<&str>,
205) -> Option<crate::textparse::PageTextParser> {
206 // Only the document load happens here; pages are parsed as the walk
207 // reaches them (`cells_timed`), so nothing is decoded for pages outside
208 // a `--pages` window and the parse overlaps the workers' inference.
209 crate::timing::timed("textparse.open", || {
210 crate::textparse::PageTextParser::open_with_password(bytes, password)
211 })
212}
213
214impl crate::textparse::PageTextParser {
215 /// [`cells`](Self::cells) under the `textparse` timing stage (per page).
216 fn cells_timed(&mut self, index: usize) -> crate::textparse::PageParserCells {
217 crate::timing::timed("textparse", || self.cells(index))
218 }
219}
220
221#[cfg(feature = "ml")]
222/// Number of pages in a PDF, without rendering any of them — used to decide
223/// whether a document is worth spinning up the parallel worker pool.
224pub fn page_count(bytes: &[u8], password: Option<&str>) -> Result<usize, PdfError> {
225 // The pure-Rust object model first, then the docling-parse plugin's
226 // count, then pdfium (the `pdfium` feature) — the order every entry point
227 // here follows.
228 if let Some(meta) = crate::timing::timed("meta.open", || {
229 crate::pdf_meta::PdfMeta::open_with_password(bytes, password)
230 })? {
231 return Ok(meta.page_count());
232 }
233 if let Some(dp) = crate::dparse_render::Doc::open_if_enabled(bytes, password) {
234 return Ok(dp.page_count());
235 }
236 crate::timing::timed("pdfium.page_count", || {
237 let lib = native::bind()?;
238 let n = lib.open(bytes, password)?.page_count();
239 Ok(n)
240 })
241}
242
243#[cfg(feature = "ml")]
244/// Render + extract pages one at a time, handing each (owned) [`PdfPage`] to `f`.
245/// Only one page bitmap is resident at a time — a rendered page is ~5 MB, so a
246/// large PDF would otherwise hold gigabytes of bitmaps at once. `f` receives the
247/// zero-based page index and the total page count.
248///
249/// `render_image` controls whether the page bitmap is rasterized at all: layout,
250/// OCR, TableFormer, and picture cropping all need it, but a caller that skips
251/// every one of those (the `no_ocr` fast path) doesn't, and rasterizing +
252/// downsampling a page is by far the most expensive step per page — skipping it
253/// is most of `no_ocr`'s speedup. `PdfPage::image` is a 1×1 placeholder when
254/// `false`; do not read it.
255///
256/// `extract_text` decodes the page's text layer (parser or pdfium cells); pass
257/// `false` when full-page OCR is forced and the cells would be discarded
258/// unread (docling#4061).
259///
260/// `range` restricts the walk to a **0-based inclusive** page window (issue
261/// #80's `--pages`); out-of-window pages are skipped *before* text extraction
262/// and rasterization, so a 3-page window over a 500-page PDF costs three
263/// pages, not five hundred. `f` still receives the absolute page index, so
264/// downstream page numbering refers to the source document.
265///
266/// `E` is the caller's error type; [`PdfError`]s convert into it via `From`.
267pub fn for_each_page<E, F>(
268 bytes: &[u8],
269 password: Option<&str>,
270 render_image: bool,
271 extract_text: bool,
272 range: Option<(usize, usize)>,
273 mut f: F,
274) -> Result<(), E>
275where
276 E: From<PdfError>,
277 F: FnMut(usize, usize, PdfPage) -> Result<(), E>,
278{
279 // The pure-Rust object model: page count, geometry, `/Rotate`, links.
280 // `None` only for a file lopdf cannot read even after the parser's
281 // repairs; pdfium (the `pdfium` feature) then answers for it.
282 let meta = crate::timing::timed("meta.open", || {
283 crate::pdf_meta::PdfMeta::open_with_password(bytes, password)
284 })?;
285 // The docling-parse renderer (#478, `DOCLING_RS_RENDERER=docling-parse`):
286 // the page images the models see come from it when it is asked for.
287 let dparse = if render_image {
288 crate::dparse_render::Doc::open_if_enabled(bytes, password)
289 } else {
290 None
291 };
292 // pdfium, when it has a job (`bind_or_skip`).
293 let pdfium = bind_or_skip(meta.is_some())?;
294 let session = match &pdfium {
295 Some(p) => Some(p.open(bytes, password)?),
296 None => None,
297 };
298 // `extract_text = false` (full-page OCR forced, docling#4061 / 2.122):
299 // the text layer would be cleared unread, so neither the pure-Rust parser
300 // nor pdfium's text page is decoded at all — on vector-dense pages (CAD
301 // drawings as 100k+ path segments) that decode is most of the page cost.
302 let mut rust = if extract_text {
303 rust_parser_cells(bytes, password)
304 } else {
305 None
306 };
307 // pdfium's count when it is loaded (a damaged file can make the two
308 // object models disagree, and pdfium's pages are the ones rendered), the
309 // object model's otherwise.
310 let total = match (&session, &meta) {
311 (Some(s), _) => s.page_count(),
312 (None, Some(m)) => m.page_count(),
313 (None, None) => 0,
314 };
315 // The object model's geometry and links are used whenever it read the same
316 // number of pages pdfium did (or pdfium is absent); a disagreeing file keeps
317 // pdfium's answers throughout.
318 let meta = meta.filter(|m| {
319 session
320 .as_ref()
321 .is_none_or(|s| s.page_count() == m.page_count())
322 });
323 // The pure-Rust renderer (phase 3 of retiring pdfium): the model inputs
324 // of every page the plugin does not render and the Rust raster declines
325 // — the default renderer.
326 let renderer = match (&meta, render_image) {
327 (Some(m), true) => Some(crate::render::Renderer::new(m)),
328 _ => None,
329 };
330 let (first, last) = range.unwrap_or((0, total.saturating_sub(1)));
331 // Index the window directly: iterating pdfium's pages from page 0 and
332 // skipping to `first` would load (and close) every page before the
333 // window — ~0.7 ms each, 1.3 s of pure overhead for a one-page window
334 // over the 1913-page .NET reference.
335 for i in first..=last {
336 if i >= total {
337 break;
338 }
339 let page = match &session {
340 Some(s) => Some(s.page(i)?),
341 None => None,
342 };
343 let geom = match (&meta, &page) {
344 (Some(m), _) => m.geometry(i).ok_or_else(|| no_raster(i as i32))?,
345 (None, Some(p)) => p.geom(),
346 (None, None) => return Err(no_raster(i as i32).into()),
347 };
348 let links = match (&meta, &page) {
349 (Some(m), _) => m.links(i),
350 (None, Some(p)) => p.links(geom.unrotated().1),
351 (None, None) => Vec::new(),
352 };
353 let rc = rust.as_mut().map(|p| p.cells_timed(i));
354 let extracted = extract_page(
355 PageSources {
356 page: page.as_ref(),
357 dparse: dparse.as_ref(),
358 meta: meta.as_ref(),
359 renderer: renderer.as_ref(),
360 },
361 geom,
362 links,
363 i as i32,
364 rc,
365 render_image,
366 )?;
367 f(i, total, extracted)?;
368 }
369 // Tearing down the parsed document (hundreds of thousands of lopdf
370 // objects on a long PDF — 250 ms for the 1913-page .NET reference) is
371 // nobody's business but the allocator's: hand it to a detached thread so
372 // the last page's output isn't held up by it. `Arc`, not `Rc`, in the
373 // caches is what makes the parser `Send`.
374 if let Some(parser) = rust {
375 std::thread::spawn(move || crate::timing::timed("textparse.close", || drop(parser)));
376 }
377 Ok(())
378}
379
380/// One rasterized page from [`render_pages`] (#243): the absolute 1-based page
381/// number in the source document, the pixel dimensions, and the PNG bytes.
382#[cfg(feature = "ml")]
383#[derive(Debug, Clone)]
384pub struct RenderedPage {
385 pub page_no: usize,
386 pub width: u32,
387 pub height: u32,
388 pub png: Vec<u8>,
389}
390
391/// Upper bound, in pixels, on a rendered page bitmap's side. A crafted PDF can
392/// declare an enormous `MediaBox` in a few hundred bytes; the page render then
393/// asks pdfium — and `into_rgb8` — to allocate `w * h * 4` bytes. At the
394/// pipeline's 3x supersample a 12000 pt box is 36000x36000 ~ 5 GB: pdfium
395/// returns an opaque internal error at the extreme, and just below it the
396/// `image` crate *panics* (a `TryReserveError`, not a recoverable error) when
397/// the allocation fails. Real pages, even large-format (A0 at 3x ~ 10110 px),
398/// stay well under this cap; it only rejects the implausible, turning an abort
399/// into a clean error. Mirrors `decode_image_limited`'s guard on the
400/// standalone-image path. `DOCLING_RS_MAX_RENDER_PIXELS` overrides it.
401#[cfg(feature = "ml")]
402fn max_render_side() -> u32 {
403 static M: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
404 *M.get_or_init(|| docling_core::env::parse("DOCLING_RS_MAX_RENDER_PIXELS").unwrap_or(15_000))
405}
406
407/// Round float pixel dimensions to the `i32` pdfium wants, rejecting a page
408/// whose bitmap would exceed [`max_render_side`] on either side before either
409/// pdfium or `image` tries to allocate it.
410#[cfg(feature = "ml")]
411fn checked_render_dims(
412 w_px: f64,
413 h_px: f64,
414 page_no: usize,
415) -> Result<(i32, i32), crate::PdfError> {
416 let cap = max_render_side();
417 let w = w_px.round().max(1.0);
418 let h = h_px.round().max(1.0);
419 if w > f64::from(cap) || h > f64::from(cap) {
420 return Err(crate::PdfError::Pdfium(format!(
421 "page {page_no}: render size {w:.0}x{h:.0} px exceeds the {cap}px per-side cap \
422 (raise DOCLING_RS_MAX_RENDER_PIXELS); the page's declared size is implausibly large"
423 )));
424 }
425 Ok((w as i32, h as i32))
426}
427
428#[cfg(feature = "ml")]
429/// Rasterize a PDF's pages to PNG (#243) — the lean path behind serve's
430/// `to=images`: pdfium render only, no text extraction, no models, and only
431/// one page bitmap resident at a time (each is PNG-encoded and dropped before
432/// the next renders). `scale` is pixels per PDF point — 2.0 matches the
433/// pipeline's [`RENDER_SCALE`] (144 dpi). Unlike the pipeline's render there
434/// is no 1.5× supersample + downsample pass: that dance exists only because
435/// TableFormer is pixel-pinned to docling's bitmaps, and nothing downstream
436/// of this output is — a single render is nearly twice as fast.
437///
438/// `range` is a **1-based** inclusive page window (issue #80's `pages`
439/// semantics: the end clamps to the document, a start past the end errors).
440///
441/// pdfium is not thread-safe — callers must serialize this against any other
442/// pdfium use (docling-serve holds its pipeline mutex around this call for
443/// exactly that reason).
444pub fn render_pages(
445 bytes: &[u8],
446 password: Option<&str>,
447 range: Option<(usize, usize)>,
448 scale: f32,
449) -> Result<Vec<RenderedPage>, crate::PdfError> {
450 // The docling-parse renderer plugin renders the display bitmap when it is
451 // asked for (full-resolution bitmap decode: this is a viewer's render,
452 // not a model input); the Rust raster / renderer otherwise, pdfium under
453 // `DOCLING_RS_RENDERER=pdfium` or for a file lopdf cannot read.
454 let dparse = crate::dparse_render::Doc::open_if_enabled(bytes, password);
455 // The object model: the page count and the Rust raster / renderer.
456 let meta = crate::pdf_meta::PdfMeta::open_with_password(bytes, password)?;
457 let pdfium = match &dparse {
458 Some(_) => None,
459 None => bind_or_skip(meta.is_some())?,
460 };
461 let session = match &pdfium {
462 Some(p) => Some(p.open(bytes, password)?),
463 None => None,
464 };
465 let total = match (&session, &dparse, &meta) {
466 (Some(s), _, _) => s.page_count(),
467 (None, Some(dp), _) => dp.page_count(),
468 (None, None, Some(m)) => m.page_count(),
469 (None, None, None) => 0,
470 };
471 let (first, last) = match range {
472 None => (0, total.saturating_sub(1)),
473 Some((first, last)) => {
474 if first == 0 || last < first {
475 return Err(PdfError::Document(format!(
476 "invalid page range {first}-{last} (pages are 1-based, first <= last)"
477 )));
478 }
479 if first > total {
480 return Err(PdfError::Document(format!(
481 "page range {first}-{last} is outside the document ({total} page(s))"
482 )));
483 }
484 (first - 1, last.min(total) - 1)
485 }
486 };
487 let renderer = match (&dparse, &meta) {
488 // Page rasters a caller keeps decode every image at full size (the
489 // shim is asked with bitmap hint 0.0 below for the same reason).
490 (None, Some(m)) => Some(crate::render::Renderer::with_bitmap_hint(m, 0.0)),
491 _ => None,
492 };
493 let mut out = Vec::with_capacity(last.saturating_sub(first) + 1);
494 for i in first..=last {
495 if i >= total {
496 break;
497 }
498 // Both renderers apply /Rotate themselves, so the bitmap is the page as
499 // a viewer shows it — no orientation handling needed (the pipeline's
500 // scanned-page un-rotation is an OCR-conformance concern, not a display
501 // one).
502 // The plugin's canvas first (the renderer whenever it resolves), then
503 // the Rust raster of an image-only page (pdfium's bitmap byte for
504 // byte, no library needed) or the Rust page renderer, then pdfium
505 // (`DOCLING_RS_RENDERER=pdfium`, or a file lopdf cannot read).
506 let rust = || {
507 let m = meta.as_ref()?;
508 let g = m.geometry(i)?;
509 let (tw, th) = checked_render_dims(
510 f64::from(g.width * scale),
511 f64::from(g.height * scale),
512 i + 1,
513 )
514 .ok()?;
515 rust_bitmap(
516 Some(m),
517 renderer.as_ref(),
518 session.is_some(),
519 i as i32,
520 tw as u32,
521 th as u32,
522 0.0,
523 )
524 };
525 let bitmap = match (&dparse, &session) {
526 (Some(dp), _) => {
527 crate::timing::timed("dparse.rasterize", || dp.render(i, f64::from(scale), 0.0))
528 .map_err(PdfError::Document)?
529 }
530 (None, session) => match rust() {
531 Some(img) => img,
532 None => {
533 let Some(s) = session else {
534 return Err(no_raster(i as i32));
535 };
536 let page = s.page(i)?;
537 let (pw, ph) = page.size();
538 let (tw, th) =
539 checked_render_dims(f64::from(pw * scale), f64::from(ph * scale), i + 1)?;
540 page.render(tw, th, "pdfium.rasterize")?
541 }
542 },
543 };
544 let mut png = Vec::new();
545 bitmap
546 .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
547 .map_err(|e| PdfError::Document(format!("PNG-encoding page {}: {e}", i + 1)))?;
548 out.push(RenderedPage {
549 page_no: i + 1,
550 width: bitmap.width(),
551 height: bitmap.height(),
552 png,
553 });
554 }
555 Ok(out)
556}
557
558#[cfg(feature = "ml")]
559/// The error for a page that needs a raster when the object model could not
560/// be read and neither the docling-parse renderer plugin nor pdfium is there.
561fn no_raster(index: i32) -> PdfError {
562 PdfError::Document(format!(
563 "page {}: no page renderer — the file's object model could not be read (lopdf), \
564 the docling-parse renderer plugin is not installed (.docling-parse/lib) and \
565 pdfium is not available (the `pdfium` feature + PDFIUM_DYNAMIC_LIB_PATH / \
566 .pdfium/lib)",
567 index + 1
568 ))
569}
570
571/// The pure-Rust bitmap of a page at `width` × `height`: the raster of an
572/// image-only page (`raster::render`, pdfium's bytes) when the page
573/// qualifies, the page renderer (`render`) otherwise — `None` only when the
574/// object model is not loaded, or when `DOCLING_RS_RENDERER=pdfium` asks for
575/// pdfium's render of a page the raster declines *and* pdfium's page is open
576/// (`pdfium_page`; a build or machine without the library degrades to the
577/// Rust renderer, as [`bind_or_skip`] warned).
578#[cfg(feature = "ml")]
579fn rust_bitmap(
580 meta: Option<&crate::pdf_meta::PdfMeta>,
581 renderer: Option<&crate::render::Renderer<'_>>,
582 pdfium_page: bool,
583 index: i32,
584 width: u32,
585 height: u32,
586 bitmap_hint: f64,
587) -> Option<RgbImage> {
588 let meta = meta?;
589 if let Some(img) = crate::timing::timed("raster.render", || {
590 crate::raster::render(meta, index as usize, width, height)
591 }) {
592 return Some(img);
593 }
594 if pdfium_page && crate::dparse_render::choice() == crate::dparse_render::Choice::Pdfium {
595 return None;
596 }
597 let renderer = renderer?;
598 crate::timing::timed("render.page", || {
599 renderer.render_with_hint(index as usize, width, height, bitmap_hint)
600 })
601}
602
603#[cfg(feature = "ml")]
604/// Bind pdfium for a conversion, or decide it can run without it. pdfium has
605/// a job in two cases only: its own render was asked for
606/// (`DOCLING_RS_RENDERER=pdfium`, which only the `pdfium` feature offers), or
607/// the pure-Rust object model could not read the file (`meta_ok` false) — then
608/// pdfium's page tree, geometry and render stand in, and a build without the
609/// feature (or without the library) fails the conversion with the hint.
610/// Otherwise the library is never loaded.
611fn bind_or_skip(meta_ok: bool) -> Result<Option<native::Lib>, PdfError> {
612 if meta_ok && crate::dparse_render::choice() != crate::dparse_render::Choice::Pdfium {
613 return Ok(None);
614 }
615 match native::bind() {
616 Ok(p) => Ok(Some(p)),
617 Err(e) if meta_ok => {
618 // The library was asked for by name and is not there: say so
619 // once, then degrade — the Rust renderer draws every page.
620 static WARNED: std::sync::Once = std::sync::Once::new();
621 WARNED.call_once(|| {
622 eprintln!(
623 "docling-pdf: DOCLING_RS_RENDERER=pdfium but the pdfium library could not be \
624 loaded ({e}); rendering with the Rust renderer"
625 );
626 });
627 Ok(None)
628 }
629 Err(e) => Err(e),
630 }
631}
632
633/// The native sources a page may draw on, each optional: pdfium's page handle
634/// (present only when [`bind_or_skip`] opened the library) and the
635/// docling-parse renderer (absent when the plugin is not asked for or no
636/// raster is wanted).
637#[cfg(feature = "ml")]
638#[derive(Clone, Copy)]
639struct PageSources<'a> {
640 page: Option<&'a native::Page<'a>>,
641 dparse: Option<&'a crate::dparse_render::Doc>,
642 /// The object model, for the Rust raster of an image-only page.
643 meta: Option<&'a crate::pdf_meta::PdfMeta>,
644 /// The pure-Rust page renderer over the same object model (its
645 /// per-document caches live for the whole conversion).
646 renderer: Option<&'a crate::render::Renderer<'a>>,
647}
648
649#[cfg(feature = "ml")]
650fn extract_page(
651 sources: PageSources<'_>,
652 geom: crate::pdf_meta::PageGeom,
653 links: Vec<LinkAnnot>,
654 index: i32,
655 rust_cells: Option<crate::textparse::PageParserCells>,
656 render_image: bool,
657) -> Result<PdfPage, PdfError> {
658 let PageSources {
659 page,
660 dparse,
661 meta,
662 renderer,
663 } = sources;
664 // The page size (and the render) is the *display* frame — `/Rotate`
665 // applied — while every text coordinate (pdfium's own text page, the
666 // pure-Rust parser's MediaBox-based glyphs, link annotation rects) lives
667 // in the unrotated frame (docling#4008, 2.121). Keep the unrotated box
668 // around for the y-flips and bring every rect into the display frame.
669 let width = geom.width;
670 let height = geom.height;
671 let rotation = geom.rotation;
672 let (unrot_w, unrot_h) = geom.unrotated();
673
674 // The text layer: the pure-Rust parser's prose, word and code cells (its
675 // word grouping reproduces docling-parse's, which TableFormer matches
676 // against). A page it reads nothing from is a scanned page for the OCR
677 // path — pdfium's text page is gone (phase 4 of "Retiring pdfium").
678 let rc = rust_cells.unwrap_or_default();
679 let (mut cells, mut code_cells, mut word_cells) = (rc.prose, rc.code, rc.words);
680 if rotation != 0 {
681 for c in cells
682 .iter_mut()
683 .chain(word_cells.iter_mut())
684 .chain(code_cells.iter_mut())
685 {
686 let (l, t, r, b) = to_display_frame((c.l, c.t, c.r, c.b), rotation, unrot_w, unrot_h);
687 (c.l, c.t, c.r, c.b) = (l, t, r, b);
688 }
689 }
690
691 // The docling-parse renderer (#478, `dparse_render.rs`): the model inputs
692 // come from docling-parse's Blend2D canvas, requested in docling's order
693 // and with its decode hint — the scale-1.0 layout image (docling decodes
694 // the page once, at its `render_scale` of 1.0), then the scale-2.0 bitmap
695 // TableFormer crops from (`_render_image_at_scale` on the same decoder,
696 // hence the same hint). One deliberate exception: a *scanned* page — no
697 // text layer, the OCR path — keeps pdfium's bitmap. docling's 2.0/3.0
698 // re-renders draw the raster its decoders reduced to 72 dpi, and Blend2D's
699 // blit of a scan differs from pdfium's render + downscale in a way the
700 // `ch` conformance recognizer feels (`scanned/ocr_test.pdf` read `JsON` for
701 // `JSON` from either docling-parse raster, hint 1.0 or full resolution);
702 // pdfium's raster is the one the scanned groundtruth was matched with, so
703 // OCR keeps it (recorded in PDF_CONFORMANCE.md) — as long as pdfium is
704 // loaded: a checkout with the plugin and no `libpdfium` OCRs the
705 // docling-parse raster rather than failing the page (degradation over
706 // failure). The canvases are `ceil`-sized where pdfium's are `round`ed;
707 // every consumer maps points through `RENDER_SCALE`, not through the
708 // image size, so the extra row/column is harmless.
709 let scanned = cells.is_empty() && word_cells.is_empty() && code_cells.is_empty();
710 let (mut dp_image, mut dp_layout) = (None, None);
711 if let (true, Some(dp)) = (render_image, dparse) {
712 let layout = crate::timing::timed("dparse.render_layout", || {
713 dp.render(index as usize, 1.0, 1.0)
714 })
715 .map_err(PdfError::Document)?;
716 if !scanned {
717 let full = crate::timing::timed("dparse.render", || {
718 dp.render(index as usize, f64::from(RENDER_SCALE), 1.0)
719 })
720 .map_err(PdfError::Document)?;
721 dp_image = Some(full);
722 }
723 dp.release_page(index as usize);
724 dp_layout = Some(layout);
725 }
726 // A scanned page's bitmap, in order: the pure-Rust raster (pdfium's bytes;
727 // `raster`), pdfium itself, and — with neither — the plugin's scale-2.0
728 // canvas rather than a failed page.
729 let scanned_fallback = |page: Option<&native::Page<'_>>| match (page, dparse) {
730 (None, Some(dp)) if scanned => {
731 let full = crate::timing::timed("dparse.render", || {
732 dp.render(index as usize, f64::from(RENDER_SCALE), 1.0)
733 })
734 .map_err(PdfError::Document)?;
735 dp.release_page(index as usize);
736 Ok(Some(full))
737 }
738 _ => Ok::<_, PdfError>(None),
739 };
740 let image = if let Some(img) = dp_image.take() {
741 img
742 } else if render_image {
743 // docling's pypdfium2 backend renders at 1.5× the target scale and
744 // downsamples "to make it sharper" (pypdfium2 → PIL BICUBIC). Replicate
745 // exactly: the TableFormer model is pixel-sensitive, so the page bitmap
746 // must match that backend's byte-for-byte (docling 2.123+'s default
747 // docling-parse backend renders it itself — #478).
748 // `CatmullRom` is the same a=-0.5 cubic kernel as PIL's BICUBIC.
749 const SUPERSAMPLE: f32 = 1.5;
750 // The 3x supersample is the largest bitmap the pipeline renders, so the
751 // per-side cap is enforced here; the 1.5x layout render below is always
752 // smaller and needs no separate guard.
753 let (tw, th) = checked_render_dims(
754 f64::from(width * RENDER_SCALE * SUPERSAMPLE),
755 f64::from(height * RENDER_SCALE * SUPERSAMPLE),
756 (index + 1) as usize,
757 )?;
758 // An image-only page (a scan) is rendered by the pure-Rust raster —
759 // pdfium's bitmap byte for byte (`raster`, its oracle test) — and any
760 // other page by the pure-Rust renderer (`render`), so the OCR path
761 // needs no `libpdfium`; pdfium renders only when asked for
762 // (`DOCLING_RS_RENDERER=pdfium`).
763 let dw = (width * RENDER_SCALE).round().max(1.0) as u32;
764 let dh = (height * RENDER_SCALE).round().max(1.0) as u32;
765 // A page without a text layer takes this bitmap to OCR: decode its
766 // images at full size (hint 0.0); a digital page's TableFormer input
767 // follows docling's hint 1.0 like the layout image below.
768 let hint = if cells.is_empty() { 0.0 } else { 1.0 };
769 let big = match rust_bitmap(
770 meta,
771 renderer,
772 page.is_some(),
773 index,
774 tw as u32,
775 th as u32,
776 hint,
777 ) {
778 Some(img) => Some(img),
779 None if page.is_some() => {
780 let page = page.ok_or_else(|| no_raster(index))?;
781 Some(page.render(tw, th, "pdfium.render")?)
782 }
783 None => None,
784 };
785 match (big, scanned_fallback(page)?) {
786 (Some(big), _) => crate::timing::timed("image.resize", || fast_downscale(&big, dw, dh)),
787 (None, Some(canvas)) => canvas,
788 (None, None) => return Err(no_raster(index)),
789 }
790 } else {
791 RgbImage::new(1, 1)
792 };
793 // The layout model's input image, built exactly like docling's pypdfium2
794 // `get_page_image(scale=1.0)`: a pdfium render at 1.5× (pypdfium2 sizes
795 // with `ceil`), PIL-BICUBIC down to the point-size image (PIL `resize`'s
796 // default kernel; Python `round` = ties-to-even). Distinct from the 2×
797 // bitmap above — resampling 1224→640 and 612→640 are different regimes,
798 // and the heron model's borderline scores follow the pixels. "Exactly" is
799 // against the pypdfium2 backend: docling 2.123+'s default docling-parse
800 // backend renders this image with its own renderer (#478, see
801 // docs/PDF_CONFORMANCE.md).
802 let image_layout = if let Some(img) = dp_layout.take() {
803 Some(img)
804 } else if render_image {
805 let tw = f64::from(width * 1.5).ceil().max(1.0) as i32;
806 let th = f64::from(height * 1.5).ceil().max(1.0) as i32;
807 let big = match rust_bitmap(
808 meta,
809 renderer,
810 page.is_some(),
811 index,
812 tw as u32,
813 th as u32,
814 1.0,
815 ) {
816 Some(img) => img,
817 None => {
818 let page = page.ok_or_else(|| no_raster(index))?;
819 page.render(tw, th, "pdfium.render_layout")?
820 }
821 };
822 let dw = f64::from(width).round_ties_even().max(1.0) as u32;
823 let dh = f64::from(height).round_ties_even().max(1.0) as u32;
824 Some(crate::timing::timed("image.resize_layout", || {
825 crate::resample::pil_resize(&big, dw, dh, crate::resample::PilFilter::Bicubic)
826 }))
827 } else {
828 None
829 };
830
831 let mut links = links;
832 if rotation != 0 {
833 for l in &mut links {
834 let (a, t, r, b) = to_display_frame((l.l, l.t, l.r, l.b), rotation, unrot_w, unrot_h);
835 (l.l, l.t, l.r, l.b) = (a, t, r, b);
836 }
837 }
838
839 // `/Rotate` normalization for scanned pages: pdfium renders the page as a
840 // viewer displays it — `/Rotate` applied — so a rotated scan hands layout
841 // and OCR a sideways/upside-down raster and the recognition output is
842 // garbage. A page with a text layer needs none of this (its cells carry
843 // the geometry; the models never see its pixels decide text), so the
844 // normalization is gated to pages with no cells at all — exactly the set
845 // the OCR path fires on. The bitmaps are un-rotated to upright (lossless
846 // 90° steps), `width`/`height` swap to the upright box, and the display
847 // rotation is recorded so assembly can rotate the finished geometry back
848 // into display space (docling reports rotated pages in display coords).
849 let mut page = PdfPage {
850 width,
851 height,
852 scale: RENDER_SCALE,
853 image_layout,
854 cells,
855 code_cells,
856 word_cells,
857 image,
858 links,
859 rotation: 0,
860 };
861 if rotation != 0 && scanned && render_image {
862 page.unrotate(rotation);
863 }
864 Ok(page)
865}
866
867#[cfg(feature = "ml")]
868/// The supersample→target downscale via `fast_image_resize` (SIMD convolution;
869/// the same a=-0.5 Catmull-Rom kernel as `image::imageops::resize(...,
870/// CatmullRom)` and PIL BICUBIC — see the render comment above). Set
871/// `DOCLING_RS_SLOW_RESIZE=1` to fall back to the `image`-crate scalar resize
872/// (byte-parity with the pre-SIMD pipeline, several times slower).
873fn fast_downscale(big: &RgbImage, dw: u32, dh: u32) -> RgbImage {
874 use fast_image_resize as fir;
875 static SLOW: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
876 let slow = *SLOW.get_or_init(|| docling_core::env::flag("DOCLING_RS_SLOW_RESIZE"));
877 if !slow {
878 if let Some(out) = (|| {
879 let src = fir::images::ImageRef::new(
880 big.width(),
881 big.height(),
882 big.as_raw(),
883 fir::PixelType::U8x3,
884 )
885 .ok()?;
886 let mut dst = fir::images::Image::new(dw, dh, fir::PixelType::U8x3);
887 fir::Resizer::new()
888 .resize(
889 &src,
890 &mut dst,
891 &fir::ResizeOptions::new()
892 .resize_alg(fir::ResizeAlg::Convolution(fir::FilterType::CatmullRom)),
893 )
894 .ok()?;
895 RgbImage::from_raw(dw, dh, dst.into_vec())
896 })() {
897 return out;
898 }
899 // Unreachable in practice; fall through to the scalar path on any error.
900 }
901 image::imageops::resize(big, dw, dh, image::imageops::FilterType::CatmullRom)
902}
903
904/// Map a top-left-origin rect from a page's unrotated (MediaBox) frame into its
905/// `/Rotate`d display frame — the counterpart of docling's pypdfium2
906/// `_rect_to_display_frame` (docling#4008) for our y-down coordinates.
907/// `unrot_w`/`unrot_h` are the unrotated page box; the display box is the same
908/// for 180° and swapped for 90°/270°.
909pub(crate) fn to_display_frame(
910 (l, t, r, b): (f32, f32, f32, f32),
911 rotation: u16,
912 unrot_w: f32,
913 unrot_h: f32,
914) -> (f32, f32, f32, f32) {
915 match rotation {
916 // Page turned 90° clockwise for display: the unrotated top edge becomes
917 // the display right edge, so x' runs from the old bottom edge up.
918 90 => (unrot_h - b, l, unrot_h - t, r),
919 180 => (unrot_w - r, unrot_h - b, unrot_w - l, unrot_h - t),
920 270 => (t, unrot_w - r, b, unrot_w - l),
921 _ => (l, t, r, b),
922 }
923}
924
925/// One glyph: codepoint + native (y-up) box edges. `l/b/r/t` is pdfium's *tight*
926/// ink box (used by the legacy `lines_from_glyphs`); `ll/lb/lr/lt` is the *loose*
927/// box (font ascent/descent + advance — uniform per font/size), which the
928/// docling-parse-style sanitizer needs so adjacent glyphs share a top edge.
929pub(crate) struct Glyph {
930 pub(crate) ch: char,
931 pub(crate) l: f32,
932 pub(crate) b: f32,
933 pub(crate) r: f32,
934 pub(crate) t: f32,
935 pub(crate) ll: f32,
936 pub(crate) lb: f32,
937 pub(crate) lr: f32,
938 pub(crate) lt: f32,
939 /// Hash of the PDF font name + flags (0 when not fetched). The sanitizer uses
940 /// it for docling-parse's `enforce_same_font` (keeps a bold label and regular
941 /// value as separate line cells, e.g. `LABEL : value`).
942 pub(crate) font: u64,
943 /// The loose box as the text matrix actually lays it — corners
944 /// bottom-left, bottom-right, top-right, top-left as `[x0, y0, … x3, y3]`
945 /// (docling-parse's `r_x0…r_y3`) — for a glyph whose baseline is **not**
946 /// upright: rotated 90°/180°/270° or tilted (#528). `ll/lb/lr/lt` are then
947 /// this quad's axis-aligned extent. `None` for upright text, whose quad is
948 /// the `ll/lb/lr/lt` rectangle itself — that path stays exactly as it was.
949 pub(crate) quad: Option<[f32; 8]>,
950}
951
952impl Glyph {
953 /// The font's height on the glyph's own axis (ascent − descent): the
954 /// loose box's height for upright text, the quad's left edge otherwise —
955 /// a 90°-turned glyph's vertical extent is its advance, not its size.
956 pub(crate) fn height(&self) -> f32 {
957 match self.quad {
958 Some(q) => (q[6] - q[0]).hypot(q[7] - q[1]),
959 None => self.lt - self.lb,
960 }
961 }
962}
963
964/// How [`lines_from_glyphs`] splits a line into words. Two more modes lived
965/// here — the prose gap heuristic with punctuation glue and pdfium's
966/// space-glyph-only code split — for pdfium's glyph stream; the parser's
967/// prose goes through `dp_lines` and pdfium's text page is gone.
968#[derive(Clone, Copy, PartialEq)]
969enum Grouping {
970 /// Split on the inter-glyph **gap** (or a space glyph), but never glue — for
971 /// the parser's code cells: the parser emits no space glyphs (a source space
972 /// is a positioning gap), and its clean advance boxes make the gap reliable.
973 /// There is no punctuation glue, so a real gap always splits (`et al.
974 /// 2000`, not `et al.2000`) while genuinely touching tokens stay joined
975 /// (`add(a,` / `b)`).
976 CodeGap,
977}
978
979/// Group glyphs (document order) into words then lines, the way docling-parse
980/// does: a new **word** starts where the horizontal gap to the previous glyph
981/// exceeds ~0.2 × the font height (a real space is ~0.3 × height; letter
982/// tracking is smaller, so titles don't shatter); a new **line** starts where
983/// the baseline drops by ~half the font height (a superscript rises without
984/// dropping, so it stays on its line). Coordinates are flipped to top-left.
985/// See [`Grouping`] for how each mode decides word boundaries.
986fn lines_from_glyphs(gs: &[Glyph], page_h: f32, mode: Grouping) -> Vec<TextCell> {
987 let mut cells: Vec<TextCell> = Vec::new();
988 let mut words: Vec<String> = Vec::new(); // words on the current line
989 let mut word = String::new();
990 // current line bounding box, native
991 let (mut ll, mut lb, mut lr, mut lt) = (
992 f32::INFINITY,
993 f32::INFINITY,
994 f32::NEG_INFINITY,
995 f32::NEG_INFINITY,
996 );
997 // Tallest glyph seen on the current line: the word-gap threshold is relative
998 // to it, so a small-font run on the line (a superscript citation) isn't split
999 // at its tight digit gaps, while a big display title isn't split at its wider
1000 // letter tracking. A real inter-word space is ~0.3× the font height.
1001 let mut line_h: f32 = 0.0;
1002 let mut prev: Option<&Glyph> = None;
1003 // A space glyph between non-space glyphs pins a word split the gap heuristic
1004 // can miss (tight justified spacing); it carries no geometry.
1005 let mut pending_space = false;
1006
1007 for g in gs {
1008 if g.ch == ' ' {
1009 pending_space = true;
1010 continue;
1011 }
1012 let h = (g.t - g.b).abs().max(1.0);
1013 let (mut new_word, mut new_line) = (false, false);
1014 if let Some(p) = prev {
1015 // A new line drops the baseline *and* resets x leftward; requiring the
1016 // x-reset avoids a descending comma/semicolon faking a line break. A
1017 // *large* drop (≥1.5× the line height — a skipped line, e.g. a centered
1018 // page-number footer below a short last word) is always a new line,
1019 // even without the x-reset.
1020 // LTR wraps reset x leftward (`g.l < p.r`); RTL (Arabic) wraps reset
1021 // rightward (the new line begins at the far right). A large drop
1022 // (≥1.5× line height) is a new line regardless of x.
1023 let x_reset = if is_arabic(g.ch) || is_arabic(p.ch) {
1024 g.l > p.r
1025 } else {
1026 g.l < p.r
1027 };
1028 new_line = (p.b - g.b > h * 0.5 && x_reset) || (p.b - g.b > line_h.max(h) * 1.5);
1029 let word_gap = line_h.max(h) * 0.25;
1030 new_word = match mode {
1031 // Gap-based, no glue: a real gap always splits, touching tokens join.
1032 Grouping::CodeGap => new_line || pending_space || g.l - p.r > word_gap,
1033 };
1034 }
1035 pending_space = false;
1036 if new_line {
1037 push_word(&mut word, &mut words);
1038 push_line(&mut words, (ll, lb, lr, lt), page_h, &mut cells);
1039 (ll, lb, lr, lt) = (
1040 f32::INFINITY,
1041 f32::INFINITY,
1042 f32::NEG_INFINITY,
1043 f32::NEG_INFINITY,
1044 );
1045 line_h = 0.0;
1046 } else if new_word {
1047 push_word(&mut word, &mut words);
1048 }
1049 word.push(g.ch);
1050 ll = ll.min(g.l);
1051 lb = lb.min(g.b);
1052 lr = lr.max(g.r);
1053 lt = lt.max(g.t);
1054 line_h = line_h.max(h);
1055 prev = Some(g);
1056 }
1057 push_word(&mut word, &mut words);
1058 push_line(&mut words, (ll, lb, lr, lt), page_h, &mut cells);
1059 cells
1060}
1061
1062/// Code line cells from the parser's glyph stream. The parser emits no space
1063/// glyphs — a source space is a positioning gap — so code cells use
1064/// [`Grouping::CodeGap`], which splits on the inter-glyph gap (a space
1065/// wherever it exceeds ~0.25× the line height) but never glues punctuation,
1066/// so `et al. 2000` keeps its space while `add(a,` / `b)` stay joined. The
1067/// parser's clean advance boxes make the gap heuristic reliable here, where
1068/// pdfium's overhanging loose boxes used to over-split (`f un c t i o n`).
1069pub(crate) fn code_cells_from_glyphs(gs: &[Glyph], page_h: f32) -> Vec<TextCell> {
1070 lines_from_glyphs(gs, page_h, Grouping::CodeGap)
1071}
1072
1073fn is_arabic(c: char) -> bool {
1074 ('\u{0600}'..='\u{06FF}').contains(&c)
1075}
1076
1077fn push_word(word: &mut String, words: &mut Vec<String>) {
1078 if !word.is_empty() {
1079 words.push(std::mem::take(word));
1080 }
1081}
1082
1083fn push_line(
1084 words: &mut Vec<String>,
1085 bbox: (f32, f32, f32, f32),
1086 page_h: f32,
1087 cells: &mut Vec<TextCell>,
1088) {
1089 if words.is_empty() {
1090 return;
1091 }
1092 let text = std::mem::take(words).join(" ");
1093 let (l, b, r, t) = bbox;
1094 cells.push(TextCell {
1095 text,
1096 l,
1097 t: page_h - t,
1098 r,
1099 b: page_h - b,
1100 });
1101}
1102
1103/// The pdfium library, behind the `pdfium` feature (phase 5 of "Retiring
1104/// pdfium"): the render `DOCLING_RS_RENDERER=pdfium` asks for — docling's
1105/// pypdfium2 chain — the last resort for a file lopdf cannot read, and the
1106/// oracle of the raster and object-model tests. The default build has the
1107/// stub below and never links or loads pdfium.
1108#[cfg(feature = "pdfium")]
1109mod native {
1110 use super::LinkAnnot;
1111 use crate::PdfError;
1112 use image::RgbImage;
1113 use pdfium_render::prelude::*;
1114
1115 /// The bound library.
1116 pub(super) struct Lib(Pdfium);
1117 /// An open document.
1118 pub(super) struct Session<'a> {
1119 doc: PdfDocument<'a>,
1120 }
1121 /// A loaded page.
1122 pub(super) struct Page<'a>(PdfPage<'a>);
1123
1124 /// Try binding pdfium from a directory (or a literal library file path):
1125 /// `<dir>/<platform library name>` first, else `<dir>` itself as the file.
1126 fn try_bind_dir(path: &str) -> Option<Box<dyn PdfiumLibraryBindings>> {
1127 let name = Pdfium::pdfium_platform_library_name_at_path(path);
1128 if let Ok(b) = Pdfium::bind_to_library(&name) {
1129 return Some(b);
1130 }
1131 Pdfium::bind_to_library(path).ok()
1132 }
1133
1134 /// Bind to the pdfium dynamic library. Honors `PDFIUM_DYNAMIC_LIB_PATH` (a
1135 /// directory or file) first; else falls back to `.pdfium/lib` relative to
1136 /// the current directory (the layout `scripts/install/pdf_setup.sh`
1137 /// produces); else the system library.
1138 pub(super) fn bind() -> Result<Lib, PdfError> {
1139 if let Some(path) = docling_core::env::nonempty("PDFIUM_DYNAMIC_LIB_PATH") {
1140 if let Some(b) = try_bind_dir(&path) {
1141 return Ok(Lib(Pdfium::new(b)));
1142 }
1143 }
1144 if let Some(b) = try_bind_dir(&crate::resolve_asset(".pdfium/lib")) {
1145 return Ok(Lib(Pdfium::new(b)));
1146 }
1147 Pdfium::bind_to_system_library()
1148 .map(|b| Lib(Pdfium::new(b)))
1149 .map_err(Into::into)
1150 }
1151
1152 /// `bind()` for unit tests: point `PDFIUM_DYNAMIC_LIB_PATH` at the
1153 /// repo-root `.pdfium/lib` first (tests run with CWD = the crate dir,
1154 /// where the CWD-relative default cannot see it).
1155 #[cfg(test)]
1156 pub(crate) fn bind_for_tests() -> Result<Pdfium, PdfError> {
1157 if std::env::var_os("PDFIUM_DYNAMIC_LIB_PATH").is_none() {
1158 let lib = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.pdfium/lib");
1159 if lib.is_dir() {
1160 std::env::set_var("PDFIUM_DYNAMIC_LIB_PATH", &lib);
1161 }
1162 }
1163 bind().map(|l| l.0)
1164 }
1165
1166 impl Lib {
1167 pub(super) fn open<'a>(
1168 &'a self,
1169 bytes: &'a [u8],
1170 password: Option<&str>,
1171 ) -> Result<Session<'a>, PdfError> {
1172 crate::timing::timed("pdfium.open", || {
1173 self.0
1174 .load_pdf_from_byte_slice(bytes, password)
1175 .map(|doc| Session { doc })
1176 .map_err(Into::into)
1177 })
1178 }
1179 }
1180
1181 impl Session<'_> {
1182 pub(super) fn page_count(&self) -> usize {
1183 self.doc.pages().len() as usize
1184 }
1185
1186 pub(super) fn page(&self, index: usize) -> Result<Page<'_>, PdfError> {
1187 self.doc
1188 .pages()
1189 .get(index as PdfPageIndex)
1190 .map(Page)
1191 .map_err(Into::into)
1192 }
1193 }
1194
1195 impl Page<'_> {
1196 /// The display size in points.
1197 pub(super) fn size(&self) -> (f32, f32) {
1198 (self.0.width().value, self.0.height().value)
1199 }
1200
1201 /// pdfium's view of the page's geometry, for the files lopdf cannot
1202 /// read — the same numbers `pdf_meta` computes from the object model.
1203 pub(super) fn geom(&self) -> crate::pdf_meta::PageGeom {
1204 crate::pdf_meta::PageGeom {
1205 width: self.0.width().value,
1206 height: self.0.height().value,
1207 rotation: match self.0.rotation() {
1208 Ok(PdfPageRenderRotation::Degrees90) => 90u16,
1209 Ok(PdfPageRenderRotation::Degrees180) => 180,
1210 Ok(PdfPageRenderRotation::Degrees270) => 270,
1211 _ => 0,
1212 },
1213 }
1214 }
1215
1216 /// Render the page into a `w` × `h` RGB bitmap under timing `stage`.
1217 pub(super) fn render(
1218 &self,
1219 w: i32,
1220 h: i32,
1221 stage: &'static str,
1222 ) -> Result<RgbImage, PdfError> {
1223 let cfg = PdfRenderConfig::new()
1224 .set_target_width(w)
1225 .set_target_height(h);
1226 crate::timing::timed(stage, || {
1227 self.0
1228 .render_with_config(&cfg)
1229 .map(|b| b.as_image().into_rgb8())
1230 .map_err(Into::into)
1231 })
1232 }
1233
1234 /// Collect web/mail/tel hyperlink annotations on the page, mapping
1235 /// each link's rectangle into top-left page coordinates (like
1236 /// [`super::TextCell`]). `file://` and in-document destinations are
1237 /// skipped — only externally meaningful targets are rendered. pdfium
1238 /// occasionally lists a link twice; rects are kept as-is and the
1239 /// caller dedupes by resolved anchor text.
1240 pub(super) fn links(&self, page_h: f32) -> Vec<LinkAnnot> {
1241 let mut out = Vec::new();
1242 for link in self.0.links().iter() {
1243 let Some(uri) = link
1244 .action()
1245 .and_then(|a| a.as_uri_action().and_then(|u| u.uri().ok()))
1246 else {
1247 continue;
1248 };
1249 let scheme_ok = ["http://", "https://", "mailto:", "tel:"]
1250 .iter()
1251 .any(|s| uri.starts_with(s));
1252 if !scheme_ok {
1253 continue;
1254 }
1255 if let Ok(rect) = link.rect() {
1256 out.push(LinkAnnot {
1257 l: rect.left().value,
1258 t: page_h - rect.top().value,
1259 r: rect.right().value,
1260 b: page_h - rect.bottom().value,
1261 uri,
1262 });
1263 }
1264 }
1265 out
1266 }
1267 }
1268}
1269
1270/// The `pdfium`-less build: pdfium never binds, so every entry point falls
1271/// through to the pure-Rust stack, and a file the object model cannot read
1272/// fails with [`no_raster`]'s hint.
1273#[cfg(all(feature = "ml", not(feature = "pdfium")))]
1274mod native {
1275 use super::LinkAnnot;
1276 use crate::PdfError;
1277 use image::RgbImage;
1278 use std::convert::Infallible;
1279 use std::marker::PhantomData;
1280
1281 pub(super) struct Lib(Infallible);
1282 pub(super) struct Session<'a>(Infallible, PhantomData<&'a ()>);
1283 pub(super) struct Page<'a>(Infallible, PhantomData<&'a ()>);
1284
1285 pub(super) fn bind() -> Result<Lib, PdfError> {
1286 Err(PdfError::Document(
1287 "pdfium support is not compiled in (docling-pdf feature `pdfium`)".into(),
1288 ))
1289 }
1290
1291 impl Lib {
1292 pub(super) fn open<'a>(
1293 &'a self,
1294 _bytes: &'a [u8],
1295 _password: Option<&str>,
1296 ) -> Result<Session<'a>, PdfError> {
1297 match self.0 {}
1298 }
1299 }
1300
1301 impl Session<'_> {
1302 pub(super) fn page_count(&self) -> usize {
1303 match self.0 {}
1304 }
1305
1306 pub(super) fn page(&self, _index: usize) -> Result<Page<'_>, PdfError> {
1307 match self.0 {}
1308 }
1309 }
1310
1311 impl Page<'_> {
1312 pub(super) fn size(&self) -> (f32, f32) {
1313 match self.0 {}
1314 }
1315
1316 pub(super) fn geom(&self) -> crate::pdf_meta::PageGeom {
1317 match self.0 {}
1318 }
1319
1320 pub(super) fn render(
1321 &self,
1322 _w: i32,
1323 _h: i32,
1324 _stage: &'static str,
1325 ) -> Result<RgbImage, PdfError> {
1326 match self.0 {}
1327 }
1328
1329 pub(super) fn links(&self, _page_h: f32) -> Vec<LinkAnnot> {
1330 match self.0 {}
1331 }
1332 }
1333}
1334
1335#[cfg(all(test, feature = "pdfium"))]
1336pub(crate) use native::bind_for_tests;
1337
1338#[cfg(test)]
1339mod tests {
1340 use super::{checked_render_dims, max_render_side, to_display_frame};
1341
1342 /// The pure-Rust object model must answer exactly what pdfium answers —
1343 /// page count, display size, `/Rotate`, URI links — on every corpus PDF,
1344 /// or a checkout without pdfium would convert differently. Needs the
1345 /// library; skips cleanly without it (CI has no pdfium).
1346 #[test]
1347 #[cfg(feature = "pdfium")]
1348 fn pdf_meta_matches_pdfium_on_the_corpus() {
1349 let Ok(_) = super::bind_for_tests() else {
1350 eprintln!("skipping: pdfium not found");
1351 return;
1352 };
1353 let lib = super::native::bind().unwrap();
1354 let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
1355 let mut files: Vec<std::path::PathBuf> = Vec::new();
1356 for dir in ["tests/data/pdf/sources", "tests/data/scanned/sources"] {
1357 let Ok(rd) = std::fs::read_dir(root.join(dir)) else {
1358 continue;
1359 };
1360 files.extend(
1361 rd.flatten()
1362 .map(|e| e.path())
1363 .filter(|p| p.extension().is_some_and(|e| e == "pdf")),
1364 );
1365 }
1366 files.sort();
1367 assert!(!files.is_empty(), "corpus not found");
1368 let mut checked = 0;
1369 for path in files {
1370 let bytes = std::fs::read(&path).unwrap();
1371 let Ok(doc) = lib.open(&bytes, None) else {
1372 continue; // password fixtures etc.
1373 };
1374 let Some(meta) = crate::pdf_meta::PdfMeta::open(&bytes) else {
1375 panic!(
1376 "{}: lopdf could not read a file pdfium reads",
1377 path.display()
1378 );
1379 };
1380 assert_eq!(meta.page_count(), doc.page_count(), "{}", path.display());
1381 for i in 0..meta.page_count() {
1382 let page = doc.page(i).unwrap();
1383 let want = page.geom();
1384 let got = meta.geometry(i).unwrap();
1385 assert!(
1386 (got.width - want.width).abs() < 0.01
1387 && (got.height - want.height).abs() < 0.01
1388 && got.rotation == want.rotation,
1389 "{} p{}: meta {got:?} vs pdfium {want:?}",
1390 path.display(),
1391 i + 1
1392 );
1393 let mut want_links = page.links(want.unrotated().1);
1394 let mut got_links = meta.links(i);
1395 let key = |l: &super::LinkAnnot| {
1396 (
1397 l.uri.clone(),
1398 (l.l * 10.0) as i64,
1399 (l.t * 10.0) as i64,
1400 (l.r * 10.0) as i64,
1401 (l.b * 10.0) as i64,
1402 )
1403 };
1404 want_links.sort_by_key(key);
1405 got_links.sort_by_key(key);
1406 let want_keys: Vec<_> = want_links.iter().map(key).collect();
1407 let got_keys: Vec<_> = got_links.iter().map(key).collect();
1408 assert_eq!(got_keys, want_keys, "{} p{}: links", path.display(), i + 1);
1409 checked += 1;
1410 }
1411 }
1412 eprintln!("pdf_meta checked against pdfium on {checked} pages");
1413 }
1414
1415 /// A page whose declared size renders past the per-side cap is rejected
1416 /// with a recoverable error, before pdfium or `image` allocates the
1417 /// multi-gigabyte bitmap that would otherwise abort the process; a normal
1418 /// page passes through with its dimensions rounded to `i32`.
1419 #[test]
1420 fn oversized_render_is_rejected_not_allocated() {
1421 let cap = f64::from(max_render_side());
1422 // A 12000 pt box at the pipeline's 3x supersample is 36000 px/side.
1423 let huge = checked_render_dims(cap + 1.0, 10.0, 1);
1424 assert!(huge.is_err(), "over-cap width must be rejected");
1425 let tall = checked_render_dims(10.0, cap + 1.0, 7);
1426 assert!(tall.is_err(), "over-cap height must be rejected");
1427 assert!(
1428 tall.unwrap_err().to_string().contains("page 7"),
1429 "the error names the offending page"
1430 );
1431 // A Letter page at 2x supersample (612x792 pt -> 1836x2376 px) is fine.
1432 assert_eq!(
1433 checked_render_dims(1836.4, 2375.6, 1).unwrap(),
1434 (1836, 2376)
1435 );
1436 // Exactly at the cap is allowed; a zero-or-negative size floors to 1.
1437 assert_eq!(
1438 checked_render_dims(cap, cap, 1).unwrap(),
1439 (cap as i32, cap as i32)
1440 );
1441 assert_eq!(checked_render_dims(0.0, 0.0, 1).unwrap(), (1, 1));
1442 }
1443
1444 /// A 612×792 portrait page displayed under `/Rotate`: a rect near the
1445 /// unrotated top-left lands where a viewer shows it (docling#4008).
1446 #[test]
1447 fn display_frame_follows_the_page_rotation() {
1448 let r = (72.0, 63.0, 387.0, 74.0); // top-left origin, unrotated
1449 assert_eq!(to_display_frame(r, 0, 612.0, 792.0), r);
1450 // 90° clockwise: the page becomes 792×612; the old top edge is the
1451 // display right edge, old left edge the display top.
1452 assert_eq!(
1453 to_display_frame(r, 90, 612.0, 792.0),
1454 (718.0, 72.0, 729.0, 387.0)
1455 );
1456 // 180°: both axes mirror inside the same box.
1457 assert_eq!(
1458 to_display_frame(r, 180, 612.0, 792.0),
1459 (225.0, 718.0, 540.0, 729.0)
1460 );
1461 // 270°: the old top edge is the display left edge, old right edge the
1462 // display top.
1463 assert_eq!(
1464 to_display_frame(r, 270, 612.0, 792.0),
1465 (63.0, 225.0, 74.0, 540.0)
1466 );
1467 }
1468
1469 #[test]
1470 fn display_frame_rotations_compose_to_identity() {
1471 let r = (10.0, 20.0, 110.0, 40.0);
1472 // 90° then 270° from the intermediate (792×612) box round-trips.
1473 let once = to_display_frame(r, 90, 612.0, 792.0);
1474 assert_eq!(to_display_frame(once, 270, 792.0, 612.0), r);
1475 let twice = to_display_frame(to_display_frame(r, 180, 612.0, 792.0), 180, 612.0, 792.0);
1476 assert_eq!(twice, r);
1477 }
1478}