docling_pdf/pdfium_backend.rs
1//! pdfium-based text extraction and page rendering.
2//!
3//! Text is reconstructed the way docling's `docling-parse` does it, so the
4//! output spacing matches the groundtruth: the page's **character** stream is
5//! grouped into **words** (split at a horizontal gap wider than a fraction of
6//! the font height — font-relative, so letter-tracking in display titles does
7//! not split a word) and words into **lines** (by baseline). pdfium-render's
8//! safe API only exposes whole style runs / `GetBoundedText`, so the character
9//! loop is driven through the raw `PdfiumLibraryBindings` FFI on a second handle
10//! to the same bytes (no fork; stays publishable).
11
12#[cfg(feature = "ocr-prep")]
13use image::RgbImage;
14#[cfg(feature = "ml")]
15use pdfium_render::prelude::*;
16
17/// A run of text with its bounding box, in PDF points with a **top-left** origin
18/// (pdfium's native origin is bottom-left; we flip it to match docling's
19/// `BoundingBox(..., origin=TOPLEFT)`).
20#[derive(Debug, Clone)]
21pub struct TextCell {
22 pub text: String,
23 pub l: f32,
24 pub t: f32,
25 pub r: f32,
26 pub b: f32,
27}
28
29/// Pixels-per-point used to render page images. Layout is scale-invariant (it
30/// scales normalized boxes by the page point size), but OCR benefits from the
31/// extra resolution.
32pub const RENDER_SCALE: f32 = 2.0;
33
34/// One page's geometry, extracted text cells, and a rendered RGB image. The
35/// image is rendered at [`RENDER_SCALE`] pixels per PDF point; `image px =
36/// page point × scale`.
37#[derive(Clone)]
38pub struct PdfPage {
39 pub width: f32,
40 pub height: f32,
41 pub scale: f32,
42 pub cells: Vec<TextCell>,
43 /// Same text grouped for code regions: split only at pdfium space glyphs, so
44 /// monospace runs keep their source spacing instead of the prose heuristic's.
45 pub code_cells: Vec<TextCell>,
46 /// Per-word cells (one per word, not joined into lines) for TableFormer cell
47 /// matching.
48 pub word_cells: Vec<TextCell>,
49 /// The rendered page bitmap. Present whenever pixels are available at all
50 /// (`ocr-prep` ⊂ `ml`): the native pipeline renders it with pdfium, the
51 /// browser pipeline receives it from the host canvas. Picture regions are
52 /// cropped out of it.
53 #[cfg(feature = "ocr-prep")]
54 pub image: RgbImage,
55 /// The **scale-1.0** page image the layout model runs on (docling parity:
56 /// its layout stage calls `page.get_image(scale=1.0)` — pdfium at 1.5×,
57 /// PIL-BICUBIC down to point size — a *different* image from the 2×
58 /// OCR/crop bitmap above, and a different resampling regime than
59 /// stretching that bitmap). `None` on paths without a pdfium renderer
60 /// (browser, METS/TIFF), which fall back to stretching [`Self::image`].
61 #[cfg(feature = "ocr-prep")]
62 pub image_layout: Option<RgbImage>,
63 /// Hyperlink annotations on the page (rect in top-left page coords + target
64 /// URI), restricted to web/mail/tel schemes. Used only by strict Markdown.
65 pub links: Vec<LinkAnnot>,
66}
67
68impl PdfPage {
69 /// A page built from recognized cells alone — the browser pipeline's
70 /// shape (#157), where the bitmap lives on the JS side. Exists so callers
71 /// compile identically with and without the `ml` feature: under a
72 /// feature-unified workspace build the struct carries the `image` field,
73 /// which a plain literal in a non-`ml` consumer can't spell.
74 #[cfg(feature = "ocr-prep")]
75 pub fn from_cells(width: f32, height: f32, scale: f32, cells: Vec<TextCell>) -> Self {
76 Self {
77 width,
78 height,
79 scale,
80 cells,
81 code_cells: Vec::new(),
82 word_cells: Vec::new(),
83 #[cfg(feature = "ocr-prep")]
84 image: RgbImage::new(0, 0),
85 #[cfg(feature = "ocr-prep")]
86 image_layout: None,
87 links: Vec::new(),
88 }
89 }
90
91 /// Same as [`from_cells`](Self::from_cells) but carrying the rendered page
92 /// bitmap, so picture regions can be cropped out of it (#157: the browser
93 /// pipeline gets the same figure bytes the native one does).
94 #[cfg(feature = "ocr-prep")]
95 pub fn from_cells_with_image(
96 width: f32,
97 height: f32,
98 scale: f32,
99 cells: Vec<TextCell>,
100 image: RgbImage,
101 ) -> Self {
102 Self {
103 image,
104 ..Self::from_cells(width, height, scale, cells)
105 }
106 }
107}
108
109/// A PDF link annotation: its rectangle (top-left page coordinates, matching
110/// [`TextCell`]) and target URI.
111#[derive(Debug, Clone)]
112pub struct LinkAnnot {
113 pub l: f32,
114 pub t: f32,
115 pub r: f32,
116 pub b: f32,
117 pub uri: String,
118}
119
120#[cfg(feature = "ml")]
121/// A parsed PDF: per-page text cells and page images.
122pub struct PdfDocument {
123 pub pages: Vec<PdfPage>,
124}
125
126/// Whether to use the docling-parse line sanitizer ([`crate::dp_lines`]) for prose
127/// reconstruction — the default. Set `DOCLING_LEGACY_LINES` to fall back to the
128/// older gap-heuristic `lines_from_glyphs`.
129pub(crate) fn use_dp_lines() -> bool {
130 std::env::var("DOCLING_LEGACY_LINES").is_err()
131}
132
133/// Whether to source **word** cells from the pure-Rust parser (roadmap item 6),
134/// the default. The parser's `word_cells` reproduce docling-parse's word grouping
135/// byte-for-byte — the per-word tokens TableFormer matches table-grid cells
136/// against — which moves table extraction closer to docling on the heavy
137/// multi-column fixtures. Set `DOCLING_PDFIUM_WORDS` to keep pdfium's word cells,
138/// or `DOCLING_PDFIUM_TEXT` to fall back to pdfium for all text.
139pub(crate) fn use_parser_words() -> bool {
140 std::env::var("DOCLING_PDFIUM_WORDS").is_err() && std::env::var("DOCLING_PDFIUM_TEXT").is_err()
141}
142
143/// Whether to source **code** cells from the parser too (the default) — the last
144/// text layer to leave pdfium, fully retiring its text path. The parser's
145/// gap-based code grouping ([`code_cells_from_glyphs`]) reconstructs monospace
146/// spacing from positioning gaps (`function add(a, b) { … }`), so it no longer
147/// drops the inter-token spaces the old space-glyph-only grouping lost
148/// (`functionadd`). Reverts to pdfium with `DOCLING_PDFIUM_WORDS` (alongside word
149/// cells) or `DOCLING_PDFIUM_TEXT` (all text).
150pub(crate) fn use_parser_code() -> bool {
151 std::env::var("DOCLING_PDFIUM_WORDS").is_err() && std::env::var("DOCLING_PDFIUM_TEXT").is_err()
152}
153
154#[cfg(feature = "ml")]
155/// Try binding pdfium from a directory (or a literal library file path):
156/// `<dir>/<platform library name>` first, else `<dir>` itself as the file.
157fn try_bind_dir(path: &str) -> Option<Box<dyn pdfium_render::prelude::PdfiumLibraryBindings>> {
158 let name = Pdfium::pdfium_platform_library_name_at_path(path);
159 if let Ok(b) = Pdfium::bind_to_library(&name) {
160 return Some(b);
161 }
162 Pdfium::bind_to_library(path).ok()
163}
164
165#[cfg(feature = "ml")]
166/// Bind to the pdfium dynamic library. Honors `PDFIUM_DYNAMIC_LIB_PATH` (a
167/// directory or file) first; else falls back to `.pdfium/lib` relative to the
168/// current directory (the layout `scripts/install/download_dependencies.sh` and
169/// `scripts/install/pdf_setup.sh` both produce); else the system library.
170fn bind() -> Result<Pdfium, PdfiumError> {
171 if let Ok(path) = std::env::var("PDFIUM_DYNAMIC_LIB_PATH") {
172 if let Some(b) = try_bind_dir(&path) {
173 return Ok(Pdfium::new(b));
174 }
175 }
176 // No env var (or it didn't resolve): fall back to `.pdfium/lib` relative to
177 // the current directory — mirroring `layout.rs`/`ocr.rs`'s `models/…`
178 // defaults — the layout `scripts/install/download_dependencies.sh` (and
179 // `scripts/install/pdf_setup.sh`) produce, so a checkout with the dependencies
180 // downloaded next to it needs no env var at all.
181 if let Some(b) = try_bind_dir(&crate::resolve_asset(".pdfium/lib")) {
182 return Ok(Pdfium::new(b));
183 }
184 Pdfium::bind_to_system_library().map(Pdfium::new)
185}
186
187#[cfg(feature = "ml")]
188impl PdfDocument {
189 /// Parse a PDF from bytes, optionally decrypting with `password`.
190 ///
191 /// Note: this materialises **every** page's rendered bitmap in memory at
192 /// once. For large documents prefer [`for_each_page`], which streams.
193 pub fn open(bytes: &[u8], password: Option<&str>) -> Result<Self, PdfiumError> {
194 let pdfium = bind()?;
195 let ffi = FfiText::load(pdfium.bindings(), bytes, password);
196 let doc = pdfium.load_pdf_from_byte_slice(bytes, password)?;
197 let mut rust = rust_parser_cells(bytes);
198 let mut pages = Vec::new();
199 for (i, page) in doc.pages().iter().enumerate() {
200 let rc = rust.as_mut().and_then(|v| v.get_mut(i).map(std::mem::take));
201 pages.push(extract_page(&page, &ffi, i as i32, rc, true)?);
202 }
203 Ok(PdfDocument { pages })
204 }
205}
206
207#[cfg(feature = "ml")]
208/// Per-page prose line cells from the pure-Rust text parser. This is the
209/// **default** text layer (it matches docling-parse's char geometry and is a
210/// strict improvement on byte-conformance — e.g. it recovers the Arabic
211/// sentence-period attachment in `right_to_left_01`). Set `DOCLING_PDFIUM_TEXT`
212/// to fall back to pdfium's text layer. The parser returns an empty page when a
213/// PDF (or a page) has no parseable text layer; the caller keeps pdfium's cells
214/// in that case, so scanned/edge-case pages are unaffected.
215fn rust_parser_cells(bytes: &[u8]) -> Option<Vec<crate::textparse::PageParserCells>> {
216 if std::env::var("DOCLING_PDFIUM_TEXT").is_ok() {
217 return None;
218 }
219 Some(crate::timing::timed("textparse", || {
220 crate::textparse::pdf_all_cells(bytes)
221 }))
222}
223
224#[cfg(feature = "ml")]
225/// Number of pages in a PDF, without rendering any of them — used to decide
226/// whether a document is worth spinning up the parallel worker pool.
227pub fn page_count(bytes: &[u8], password: Option<&str>) -> Result<usize, PdfiumError> {
228 let pdfium = bind()?;
229 let doc = pdfium.load_pdf_from_byte_slice(bytes, password)?;
230 Ok(doc.pages().len() as usize)
231}
232
233#[cfg(feature = "ml")]
234/// Render + extract pages one at a time, handing each (owned) [`PdfPage`] to `f`.
235/// Only one page bitmap is resident at a time — a rendered page is ~5 MB, so a
236/// large PDF would otherwise hold gigabytes of bitmaps at once. `f` receives the
237/// zero-based page index and the total page count.
238///
239/// `render_image` controls whether the page bitmap is rasterized at all: layout,
240/// OCR, TableFormer, and picture cropping all need it, but a caller that skips
241/// every one of those (the `no_ocr` fast path) doesn't, and rasterizing +
242/// downsampling a page is by far the most expensive step per page — skipping it
243/// is most of `no_ocr`'s speedup. `PdfPage::image` is a 1×1 placeholder when
244/// `false`; do not read it.
245///
246/// `range` restricts the walk to a **0-based inclusive** page window (issue
247/// #80's `--pages`); out-of-window pages are skipped *before* text extraction
248/// and rasterization, so a 3-page window over a 500-page PDF costs three
249/// pages, not five hundred. `f` still receives the absolute page index, so
250/// downstream page numbering refers to the source document.
251///
252/// `E` is the caller's error type; pdfium errors convert into it via `From`.
253pub fn for_each_page<E, F>(
254 bytes: &[u8],
255 password: Option<&str>,
256 render_image: bool,
257 range: Option<(usize, usize)>,
258 mut f: F,
259) -> Result<(), E>
260where
261 E: From<PdfiumError>,
262 F: FnMut(usize, usize, PdfPage) -> Result<(), E>,
263{
264 let pdfium = bind()?;
265 let ffi = FfiText::load(pdfium.bindings(), bytes, password);
266 let doc = pdfium.load_pdf_from_byte_slice(bytes, password)?;
267 let mut rust = rust_parser_cells(bytes);
268 let pages = doc.pages();
269 let total = pages.len() as usize;
270 let (first, last) = range.unwrap_or((0, total.saturating_sub(1)));
271 for (i, page) in pages.iter().enumerate() {
272 if i < first || i > last {
273 continue;
274 }
275 let rc = rust.as_mut().and_then(|v| v.get_mut(i).map(std::mem::take));
276 let extracted = extract_page(&page, &ffi, i as i32, rc, render_image)?;
277 f(i, total, extracted)?;
278 }
279 Ok(())
280}
281
282#[cfg(feature = "ml")]
283fn extract_page(
284 page: &pdfium_render::prelude::PdfPage<'_>,
285 ffi: &FfiText<'_>,
286 index: i32,
287 rust_cells: Option<crate::textparse::PageParserCells>,
288 render_image: bool,
289) -> Result<PdfPage, PdfiumError> {
290 let width = page.width().value;
291 let height = page.height().value;
292
293 // Default: use the pure-Rust text parser instead of pdfium's text layer
294 // (override with `DOCLING_PDFIUM_TEXT`). Prose line cells always come from the
295 // parser; word and code cells do too unless `DOCLING_PDFIUM_WORDS` keeps them
296 // on pdfium (the parser's word grouping reproduces docling-parse's, which
297 // TableFormer matches against — roadmap item 6). A page the parser couldn't
298 // read (no text layer) keeps pdfium's cells.
299 let rc = rust_cells.unwrap_or_default();
300 let need_pdfium_prose = rc.prose.is_empty();
301 let need_pdfium_words = !use_parser_words() || rc.words.is_empty();
302 let need_pdfium_code = !use_parser_code() || rc.code.is_empty();
303
304 // The parser covers prose/words/code from one shared glyph pass, so on the
305 // common (parser-succeeded) page all three are already satisfied and this
306 // pdfium FFI call — otherwise fully discarded below — is skipped outright.
307 let (mut cells, mut code_cells, mut word_cells) =
308 if need_pdfium_prose || need_pdfium_words || need_pdfium_code {
309 let (mut cells, code_cells, word_cells) =
310 crate::timing::timed("ffi.page_cells", || ffi.page_cells(index, height));
311 if cells.is_empty() {
312 cells = segment_cells(&page.text()?, height);
313 }
314 (cells, code_cells, word_cells)
315 } else {
316 (Vec::new(), Vec::new(), Vec::new())
317 };
318 if !rc.prose.is_empty() {
319 cells = rc.prose;
320 }
321 if use_parser_words() && !rc.words.is_empty() {
322 word_cells = rc.words;
323 }
324 if use_parser_code() && !rc.code.is_empty() {
325 code_cells = rc.code;
326 }
327
328 let image = if render_image {
329 // docling renders at 1.5× the target scale and downsamples "to make it
330 // sharper" (pypdfium2 → PIL BICUBIC). Replicate exactly: the TableFormer
331 // model is pixel-sensitive, so the page bitmap must match byte-for-byte.
332 // `CatmullRom` is the same a=-0.5 cubic kernel as PIL's BICUBIC.
333 const SUPERSAMPLE: f32 = 1.5;
334 let tw = (width * RENDER_SCALE * SUPERSAMPLE).round().max(1.0) as i32;
335 let th = (height * RENDER_SCALE * SUPERSAMPLE).round().max(1.0) as i32;
336 let cfg = PdfRenderConfig::new()
337 .set_target_width(tw)
338 .set_target_height(th);
339 let big = crate::timing::timed("pdfium.render", || {
340 page.render_with_config(&cfg)
341 .map(|b| b.as_image().into_rgb8())
342 })?;
343 let dw = (width * RENDER_SCALE).round().max(1.0) as u32;
344 let dh = (height * RENDER_SCALE).round().max(1.0) as u32;
345 crate::timing::timed("image.resize", || fast_downscale(&big, dw, dh))
346 } else {
347 RgbImage::new(1, 1)
348 };
349 // The layout model's input image, built exactly like docling's
350 // `get_page_image(scale=1.0)`: a pdfium render at 1.5× (pypdfium2 sizes
351 // with `ceil`), PIL-BICUBIC down to the point-size image (PIL `resize`'s
352 // default kernel; Python `round` = ties-to-even). Distinct from the 2×
353 // bitmap above — resampling 1224→640 and 612→640 are different regimes,
354 // and the heron model's borderline scores follow the pixels.
355 let image_layout = if render_image {
356 let tw = f64::from(width * 1.5).ceil().max(1.0) as i32;
357 let th = f64::from(height * 1.5).ceil().max(1.0) as i32;
358 let cfg = PdfRenderConfig::new()
359 .set_target_width(tw)
360 .set_target_height(th);
361 let big = crate::timing::timed("pdfium.render_layout", || {
362 page.render_with_config(&cfg)
363 .map(|b| b.as_image().into_rgb8())
364 })?;
365 let dw = f64::from(width).round_ties_even().max(1.0) as u32;
366 let dh = f64::from(height).round_ties_even().max(1.0) as u32;
367 Some(crate::timing::timed("image.resize_layout", || {
368 crate::resample::pil_resize(&big, dw, dh, crate::resample::PilFilter::Bicubic)
369 }))
370 } else {
371 None
372 };
373
374 Ok(PdfPage {
375 width,
376 height,
377 scale: RENDER_SCALE,
378 image_layout,
379 cells,
380 code_cells,
381 word_cells,
382 image,
383 links: extract_links(page, height),
384 })
385}
386
387#[cfg(feature = "ml")]
388/// The supersample→target downscale via `fast_image_resize` (SIMD convolution;
389/// the same a=-0.5 Catmull-Rom kernel as `image::imageops::resize(...,
390/// CatmullRom)` and PIL BICUBIC — see the render comment above). Set
391/// `DOCLING_RS_SLOW_RESIZE=1` to fall back to the `image`-crate scalar resize
392/// (byte-parity with the pre-SIMD pipeline, several times slower).
393fn fast_downscale(big: &RgbImage, dw: u32, dh: u32) -> RgbImage {
394 use fast_image_resize as fir;
395 static SLOW: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
396 let slow = *SLOW.get_or_init(|| {
397 std::env::var("DOCLING_RS_SLOW_RESIZE")
398 .map(|v| v != "0")
399 .unwrap_or(false)
400 });
401 if !slow {
402 if let Some(out) = (|| {
403 let src = fir::images::ImageRef::new(
404 big.width(),
405 big.height(),
406 big.as_raw(),
407 fir::PixelType::U8x3,
408 )
409 .ok()?;
410 let mut dst = fir::images::Image::new(dw, dh, fir::PixelType::U8x3);
411 fir::Resizer::new()
412 .resize(
413 &src,
414 &mut dst,
415 &fir::ResizeOptions::new()
416 .resize_alg(fir::ResizeAlg::Convolution(fir::FilterType::CatmullRom)),
417 )
418 .ok()?;
419 RgbImage::from_raw(dw, dh, dst.into_vec())
420 })() {
421 return out;
422 }
423 // Unreachable in practice; fall through to the scalar path on any error.
424 }
425 image::imageops::resize(big, dw, dh, image::imageops::FilterType::CatmullRom)
426}
427
428#[cfg(feature = "ml")]
429/// Collect web/mail/tel hyperlink annotations on a page, mapping each link's
430/// rectangle into top-left page coordinates (like [`TextCell`]). `file://` and
431/// in-document destinations are skipped — only externally meaningful targets are
432/// rendered. pdfium occasionally lists a link twice; rects are kept as-is and the
433/// caller dedupes by resolved anchor text.
434fn extract_links(page: &pdfium_render::prelude::PdfPage<'_>, page_h: f32) -> Vec<LinkAnnot> {
435 let mut out = Vec::new();
436 for link in page.links().iter() {
437 let Some(uri) = link
438 .action()
439 .and_then(|a| a.as_uri_action().and_then(|u| u.uri().ok()))
440 else {
441 continue;
442 };
443 let scheme_ok = ["http://", "https://", "mailto:", "tel:"]
444 .iter()
445 .any(|s| uri.starts_with(s));
446 if !scheme_ok {
447 continue;
448 }
449 if let Ok(rect) = link.rect() {
450 out.push(LinkAnnot {
451 l: rect.left().value,
452 t: page_h - rect.top().value,
453 r: rect.right().value,
454 b: page_h - rect.bottom().value,
455 uri,
456 });
457 }
458 }
459 out
460}
461
462#[cfg(feature = "ml")]
463/// Fallback line cells from pdfium-render's style segments (one cell per
464/// segment). Used only when the raw-FFI text page can't be loaded.
465fn segment_cells(text: &PdfPageText, page_h: f32) -> Vec<TextCell> {
466 text.segments()
467 .iter()
468 .filter_map(|seg| {
469 let s = seg.text();
470 if s.trim().is_empty() {
471 return None;
472 }
473 let r = seg.bounds();
474 Some(TextCell {
475 text: s,
476 l: r.left().value,
477 t: page_h - r.top().value,
478 r: r.right().value,
479 b: page_h - r.bottom().value,
480 })
481 })
482 .collect()
483}
484
485#[cfg(feature = "ml")]
486/// A second, raw-FFI handle on the same PDF used to drive the character loop
487/// (`FPDFText_GetUnicode`/`GetCharBox`) that pdfium-render's safe API doesn't
488/// expose. Closes the document on drop.
489struct FfiText<'a> {
490 bindings: &'a dyn PdfiumLibraryBindings,
491 doc: FPDF_DOCUMENT,
492}
493
494/// One glyph: codepoint + native (y-up) box edges. `l/b/r/t` is pdfium's *tight*
495/// ink box (used by the legacy `lines_from_glyphs`); `ll/lb/lr/lt` is the *loose*
496/// box (font ascent/descent + advance — uniform per font/size), which the
497/// docling-parse-style sanitizer needs so adjacent glyphs share a top edge.
498pub(crate) struct Glyph {
499 pub(crate) ch: char,
500 pub(crate) l: f32,
501 pub(crate) b: f32,
502 pub(crate) r: f32,
503 pub(crate) t: f32,
504 pub(crate) ll: f32,
505 pub(crate) lb: f32,
506 pub(crate) lr: f32,
507 pub(crate) lt: f32,
508 /// Hash of the PDF font name + flags (0 when not fetched). The sanitizer uses
509 /// it for docling-parse's `enforce_same_font` (keeps a bold label and regular
510 /// value as separate line cells, e.g. `LABEL : value`).
511 pub(crate) font: u64,
512}
513
514#[cfg(feature = "ml")]
515impl<'a> FfiText<'a> {
516 fn load(bindings: &'a dyn PdfiumLibraryBindings, bytes: &[u8], password: Option<&str>) -> Self {
517 let doc = bindings.FPDF_LoadMemDocument(bytes, password);
518 FfiText { bindings, doc }
519 }
520
521 /// Reconstruct line cells for page `index` (zero-based) via the
522 /// chars→words→lines grouping. Returns `(prose_cells, code_cells)` — the same
523 /// glyphs grouped two ways (gap-heuristic for prose, space-glyph-only for
524 /// code). Both empty on any failure (caller falls back).
525 fn page_cells(&self, index: i32, page_h: f32) -> (Vec<TextCell>, Vec<TextCell>, Vec<TextCell>) {
526 let empty = || (Vec::new(), Vec::new(), Vec::new());
527 if self.doc.is_null() {
528 return empty();
529 }
530 let b = self.bindings;
531 let page = b.FPDF_LoadPage(self.doc, index);
532 if page.is_null() {
533 return empty();
534 }
535 let tp = b.FPDFText_LoadPage(page);
536 let out = if tp.is_null() {
537 empty()
538 } else {
539 let dp = use_dp_lines();
540 let g = glyphs(b, tp, dp);
541 b.FPDFText_ClosePage(tp);
542 // Prose line cells: the docling-parse-style sanitizer (behind a flag
543 // while it's validated) or the legacy gap-heuristic reconstruction.
544 let prose = if dp {
545 crate::dp_lines::line_cells(&g, page_h, false)
546 } else {
547 lines_from_glyphs(&g, page_h, Grouping::Prose)
548 };
549 (
550 prose,
551 lines_from_glyphs(&g, page_h, Grouping::CodeSpaceOnly),
552 words_from_glyphs(&g, page_h),
553 )
554 };
555 b.FPDF_ClosePage(page);
556 out
557 }
558}
559
560#[cfg(feature = "ml")]
561impl Drop for FfiText<'_> {
562 fn drop(&mut self) {
563 if !self.doc.is_null() {
564 self.bindings.FPDF_CloseDocument(self.doc);
565 }
566 }
567}
568
569#[cfg(feature = "ml")]
570/// Read every glyph (codepoint + native box) from the text page, in document
571/// order. A space glyph is kept as a word-boundary marker (NaN box, char `' '`);
572/// pdfium emits these on most lines and they pin word splits exactly. Hard line
573/// breaks are dropped (line structure comes from geometry); the gap heuristic in
574/// [`lines_from_glyphs`] is the fallback for the lines pdfium leaves space-less.
575/// Debug helper: the raw pdfium glyph stream (codepoint + native bottom-left
576/// box) for a page, in pdfium's character order. For comparing against
577/// docling-parse's char cells.
578pub fn debug_glyphs(bytes: &[u8], index: i32) -> Vec<(char, f32, f32)> {
579 let Ok(pdfium) = bind() else {
580 return Vec::new();
581 };
582 let ffi = FfiText::load(pdfium.bindings(), bytes, None);
583 if ffi.doc.is_null() {
584 return Vec::new();
585 }
586 let b = ffi.bindings;
587 let page = b.FPDF_LoadPage(ffi.doc, index);
588 if page.is_null() {
589 return Vec::new();
590 }
591 let tp = b.FPDFText_LoadPage(page);
592 let mut out = Vec::new();
593 if !tp.is_null() {
594 for g in glyphs(b, tp, true) {
595 out.push((g.ch, g.ll, g.lr));
596 }
597 b.FPDFText_ClosePage(tp);
598 }
599 b.FPDF_ClosePage(page);
600 out
601}
602
603#[cfg(feature = "ml")]
604/// One text object on a page, for the hidden-layer diagnostic.
605#[derive(Debug, Clone)]
606pub struct DebugTextObject {
607 /// True when the object is drawn invisibly (text render mode 3) — the marker of
608 /// a hidden duplicate text layer.
609 pub invisible: bool,
610 /// Bounding box in native PDF points (bottom-left origin).
611 pub l: f32,
612 pub b: f32,
613 pub r: f32,
614 pub t: f32,
615 /// The object's text (best-effort; empty if it could not be read).
616 pub text: String,
617}
618
619#[cfg(feature = "ml")]
620/// Diagnostic: every text object on page `index`, each tagged visible/invisible
621/// (via the object-level [`FPDFTextObj_GetTextRenderMode`], which — unlike the
622/// per-character render-mode API — is available on the default pdfium binding).
623/// A hidden duplicate text layer shows up as invisible objects repeating the
624/// visible text. Used by the `dump_render_modes` example.
625///
626/// [`FPDFTextObj_GetTextRenderMode`]: pdfium_render::prelude::PdfiumLibraryBindings::FPDFTextObj_GetTextRenderMode
627pub fn debug_text_objects(bytes: &[u8], index: i32) -> Vec<DebugTextObject> {
628 let Ok(pdfium) = bind() else {
629 return Vec::new();
630 };
631 let ffi = FfiText::load(pdfium.bindings(), bytes, None);
632 if ffi.doc.is_null() {
633 return Vec::new();
634 }
635 let b = ffi.bindings;
636 let page = b.FPDF_LoadPage(ffi.doc, index);
637 if page.is_null() {
638 return Vec::new();
639 }
640 let tp = b.FPDFText_LoadPage(page);
641 let mut out = Vec::new();
642 let n = b.FPDFPage_CountObjects(page);
643 for i in 0..n {
644 let obj = b.FPDFPage_GetObject(page, i);
645 if obj.is_null() || b.FPDFPageObj_GetType(obj) != FPDF_PAGEOBJ_TEXT as i32 {
646 continue;
647 }
648 let (mut l, mut bot, mut r, mut top) = (0f32, 0f32, 0f32, 0f32);
649 if b.FPDFPageObj_GetBounds(obj, &mut l, &mut bot, &mut r, &mut top) == 0 {
650 continue;
651 }
652 let invisible = b.FPDFTextObj_GetTextRenderMode(obj) == INVISIBLE_RENDER_MODE;
653 let text = if tp.is_null() {
654 String::new()
655 } else {
656 // FPDFTextObj_GetText returns the count of UTF-16 code units, including
657 // the trailing NUL; call once for the size, once to fill.
658 let need = b.FPDFTextObj_GetText(obj, tp, std::ptr::null_mut(), 0);
659 if need <= 1 {
660 String::new()
661 } else {
662 let mut buf = vec![0u16; need as usize];
663 b.FPDFTextObj_GetText(obj, tp, buf.as_mut_ptr(), need);
664 if let Some(&0) = buf.last() {
665 buf.pop();
666 }
667 String::from_utf16_lossy(&buf)
668 }
669 };
670 out.push(DebugTextObject {
671 invisible,
672 l,
673 b: bot,
674 r,
675 t: top,
676 text,
677 });
678 }
679 if !tp.is_null() {
680 b.FPDFText_ClosePage(tp);
681 }
682 b.FPDF_ClosePage(page);
683 out
684}
685
686#[cfg(feature = "ml")]
687/// Hash a glyph's PDF font name + flags, for `enforce_same_font`. 0 if unavailable.
688fn font_hash(b: &dyn PdfiumLibraryBindings, tp: FPDF_TEXTPAGE, i: i32) -> u64 {
689 use std::hash::{Hash, Hasher};
690 let mut flags: std::os::raw::c_int = 0;
691 let len = b.FPDFText_GetFontInfo(tp, i, std::ptr::null_mut(), 0, &mut flags);
692 if len == 0 {
693 return 0;
694 }
695 let mut buf = vec![0u8; len as usize];
696 b.FPDFText_GetFontInfo(
697 tp,
698 i,
699 buf.as_mut_ptr() as *mut std::os::raw::c_void,
700 len,
701 &mut flags,
702 );
703 let mut h = std::collections::hash_map::DefaultHasher::new();
704 buf.hash(&mut h);
705 flags.hash(&mut h);
706 h.finish()
707}
708
709#[cfg(feature = "ml")]
710/// pdfium text render mode 3: the glyph is drawn with neither fill nor stroke —
711/// an invisible glyph. Web-to-PDF exporters put a hidden plain-text copy of
712/// syntax-highlighted code (and other "copy"/accessibility layers) in this mode,
713/// which the char-level text API then extracts as a duplicate of the visible text.
714const INVISIBLE_RENDER_MODE: i32 = 3;
715
716#[cfg(feature = "ml")]
717fn glyphs(b: &dyn PdfiumLibraryBindings, tp: FPDF_TEXTPAGE, fetch_font: bool) -> Vec<Glyph> {
718 let n = b.FPDFText_CountChars(tp);
719 let mut out = Vec::with_capacity(n.max(0) as usize);
720 for i in 0..n {
721 let ch = match char::from_u32(b.FPDFText_GetUnicode(tp, i)) {
722 Some(c) => c,
723 None => continue,
724 };
725 if ch == '\r' || ch == '\n' {
726 continue;
727 }
728 // Spaces are font-neutral (0): pdfium's generated spaces carry a default
729 // font that would otherwise block every word↔space merge under
730 // enforce_same_font; docling-parse's spaces inherit the run's font.
731 let font = if fetch_font && !ch.is_whitespace() {
732 font_hash(b, tp, i)
733 } else {
734 0
735 };
736 let (mut l, mut r, mut bot, mut top) = (0f64, 0f64, 0f64, 0f64);
737 let has_box = b.FPDFText_GetCharBox(tp, i, &mut l, &mut r, &mut bot, &mut top) != 0;
738 // Loose box: font ascent/descent + glyph advance, uniform per font/size.
739 let mut lr = FS_RECTF {
740 left: 0.0,
741 top: 0.0,
742 right: 0.0,
743 bottom: 0.0,
744 };
745 let (ll, lb, lrt, ltop) = if b.FPDFText_GetLooseCharBox(tp, i, &mut lr) != 0 {
746 (lr.left, lr.bottom, lr.right, lr.top)
747 } else if has_box {
748 (l as f32, bot as f32, r as f32, top as f32)
749 } else {
750 (f32::NAN, 0.0, 0.0, 0.0)
751 };
752 if ch.is_whitespace() {
753 // Keep the space *with its box* (the docling-parse-style line sanitizer
754 // needs literal space glyphs); NaN `l` if pdfium reports no box (the
755 // legacy `lines_from_glyphs` ignores the box and only flags a space).
756 out.push(Glyph {
757 ch: ' ',
758 l: if has_box { l as f32 } else { f32::NAN },
759 b: if has_box { bot as f32 } else { 0.0 },
760 r: if has_box { r as f32 } else { 0.0 },
761 t: if has_box { top as f32 } else { 0.0 },
762 ll,
763 lb,
764 lr: lrt,
765 lt: ltop,
766 font,
767 });
768 continue;
769 }
770 if !has_box {
771 continue;
772 }
773 out.push(Glyph {
774 ch,
775 l: l as f32,
776 b: bot as f32,
777 r: r as f32,
778 t: top as f32,
779 ll,
780 lb,
781 lr: lrt,
782 lt: ltop,
783 font,
784 });
785 }
786 // pdfium splits the Arabic lam-alef ligature into two chars at the *same* x
787 // (it's one glyph) in visual order — `alef-variant, lam`. docling-parse and
788 // logical order are `lam, alef-variant`. Detect the ligature by the shared x
789 // and swap. The shared-x test reliably distinguishes a true ligature from a
790 // genuine `alef + lam` sequence (the article `ال`, or `فعالة`), whose two
791 // glyphs sit at different x and must NOT be reordered.
792 for i in 0..out.len().saturating_sub(1) {
793 let same_x = out[i].l.is_finite()
794 && out[i + 1].l.is_finite()
795 && (out[i].l - out[i + 1].l).abs() < 1.0;
796 if same_x
797 && matches!(out[i].ch, '\u{0622}' | '\u{0623}' | '\u{0625}' | '\u{0627}')
798 && out[i + 1].ch == '\u{0644}'
799 {
800 out.swap(i, i + 1);
801 }
802 }
803 // Reconstruct degenerate (zero-width) loose space boxes by spanning the gap to
804 // the next glyph on the same line, so the sanitizer keeps them as word
805 // separators rather than dropping them (which would merge `Information systems`
806 // → `Informationsystems`). pdfium gives generated spaces a zero-width box at a
807 // wrong baseline; a wrap (different baseline) or a touching gap is left alone.
808 for i in 0..out.len() {
809 if out[i].ch != ' ' || (out[i].lr - out[i].ll).abs() >= 0.5 {
810 continue;
811 }
812 let prev = out[..i]
813 .iter()
814 .rev()
815 .find(|g| g.ch != ' ' && g.ll.is_finite())
816 .map(|g| (g.lr, g.lb, g.lt));
817 let next = out[i + 1..]
818 .iter()
819 .find(|g| g.ch != ' ' && g.ll.is_finite())
820 .map(|g| (g.ll, g.lb));
821 if let (Some((plr, plb, plt)), Some((nll, nlb))) = (prev, next) {
822 let line_h = (plt - plb).abs().max(1.0);
823 if (plb - nlb).abs() < line_h * 0.5 && nll > plr + 0.5 {
824 out[i].ll = plr;
825 out[i].lr = nll;
826 out[i].lb = plb;
827 out[i].lt = plt;
828 }
829 }
830 }
831 out
832}
833
834/// How [`lines_from_glyphs`] splits a line into words.
835#[derive(Clone, Copy, PartialEq)]
836enum Grouping {
837 /// Gap heuristic + punctuation glue (`engines,`, `[37`, `98.5`) — prose.
838 Prose,
839 /// Split only at literal space glyphs, never glue — pdfium code cells.
840 /// pdfium's monospace listings carry a real space glyph at every source space,
841 /// and its overhanging loose boxes would make the gap heuristic over-split
842 /// (`f un c t i o n`), so honouring just the spaces reproduces the spacing.
843 CodeSpaceOnly,
844 /// Split on the inter-glyph **gap** (or a space glyph), but never glue — for
845 /// the parser's code cells: the parser emits no space glyphs (a source space
846 /// is a positioning gap), and its clean advance boxes make the gap reliable.
847 /// Unlike [`Grouping::Prose`] there is no punctuation glue, so a real gap
848 /// always splits (`et al. 2000`, not `et al.2000`) while genuinely touching
849 /// tokens stay joined (`add(a,` / `b)`).
850 CodeGap,
851}
852
853/// Group glyphs (document order) into words then lines, the way docling-parse
854/// does: a new **word** starts where the horizontal gap to the previous glyph
855/// exceeds ~0.2 × the font height (a real space is ~0.3 × height; letter
856/// tracking is smaller, so titles don't shatter); a new **line** starts where
857/// the baseline drops by ~half the font height (a superscript rises without
858/// dropping, so it stays on its line). Coordinates are flipped to top-left.
859/// See [`Grouping`] for how each mode decides word boundaries.
860fn lines_from_glyphs(gs: &[Glyph], page_h: f32, mode: Grouping) -> Vec<TextCell> {
861 let mut cells: Vec<TextCell> = Vec::new();
862 let mut words: Vec<String> = Vec::new(); // words on the current line
863 let mut word = String::new();
864 // current line bounding box, native
865 let (mut ll, mut lb, mut lr, mut lt) = (
866 f32::INFINITY,
867 f32::INFINITY,
868 f32::NEG_INFINITY,
869 f32::NEG_INFINITY,
870 );
871 // Tallest glyph seen on the current line: the word-gap threshold is relative
872 // to it, so a small-font run on the line (a superscript citation) isn't split
873 // at its tight digit gaps, while a big display title isn't split at its wider
874 // letter tracking. A real inter-word space is ~0.3× the font height.
875 let mut line_h: f32 = 0.0;
876 let mut prev: Option<&Glyph> = None;
877 // A space glyph between non-space glyphs pins a word split the gap heuristic
878 // can miss (tight justified spacing); it carries no geometry.
879 let mut pending_space = false;
880
881 for g in gs {
882 if g.ch == ' ' {
883 pending_space = true;
884 continue;
885 }
886 let h = (g.t - g.b).abs().max(1.0);
887 let (mut new_word, mut new_line) = (false, false);
888 if let Some(p) = prev {
889 // A new line drops the baseline *and* resets x leftward; requiring the
890 // x-reset avoids a descending comma/semicolon faking a line break. A
891 // *large* drop (≥1.5× the line height — a skipped line, e.g. a centered
892 // page-number footer below a short last word) is always a new line,
893 // even without the x-reset.
894 // LTR wraps reset x leftward (`g.l < p.r`); RTL (Arabic) wraps reset
895 // rightward (the new line begins at the far right). A large drop
896 // (≥1.5× line height) is a new line regardless of x.
897 let x_reset = if is_arabic(g.ch) || is_arabic(p.ch) {
898 g.l > p.r
899 } else {
900 g.l < p.r
901 };
902 new_line = (p.b - g.b > h * 0.5 && x_reset) || (p.b - g.b > line_h.max(h) * 1.5);
903 // Don't split before closing punctuation, after opening punctuation, or
904 // after a period that runs into a digit/lowercase letter — docling
905 // keeps `engines,` / `[37` / `i.e.` / `98.5` together even across a
906 // space or gap.
907 let glued = is_close_punct(g.ch)
908 || is_open_punct(p.ch)
909 || (p.ch.is_ascii_digit() && g.ch.is_ascii_digit())
910 || (p.ch == '.'
911 && !pending_space
912 && (g.ch.is_ascii_digit() || g.ch.is_ascii_lowercase()));
913 let word_gap = line_h.max(h) * 0.25;
914 new_word = if mode == Grouping::CodeSpaceOnly {
915 new_line || pending_space
916 } else if mode == Grouping::CodeGap {
917 // Gap-based, no glue: a real gap always splits, touching tokens join.
918 new_line || pending_space || g.l - p.r > word_gap
919 } else if is_arabic(g.ch) || is_arabic(p.ch) {
920 // RTL runs right-to-left, so the inter-word gap is `p.l - g.r`. A
921 // real word space has a gap; pdfium also emits spurious zero-gap
922 // space glyphs inside words (`التي`), so require the gap rather
923 // than trusting a bare space glyph.
924 new_line || (p.l - g.r > word_gap && !glued)
925 } else {
926 new_line || ((pending_space || g.l - p.r > word_gap) && !glued)
927 };
928 }
929 pending_space = false;
930 if new_line {
931 push_word(&mut word, &mut words);
932 push_line(&mut words, (ll, lb, lr, lt), page_h, &mut cells);
933 (ll, lb, lr, lt) = (
934 f32::INFINITY,
935 f32::INFINITY,
936 f32::NEG_INFINITY,
937 f32::NEG_INFINITY,
938 );
939 line_h = 0.0;
940 } else if new_word {
941 push_word(&mut word, &mut words);
942 }
943 word.push(g.ch);
944 ll = ll.min(g.l);
945 lb = lb.min(g.b);
946 lr = lr.max(g.r);
947 lt = lt.max(g.t);
948 line_h = line_h.max(h);
949 prev = Some(g);
950 }
951 push_word(&mut word, &mut words);
952 push_line(&mut words, (ll, lb, lr, lt), page_h, &mut cells);
953 cells
954}
955
956/// Code line cells from the **parser**'s glyph stream. Unlike pdfium — whose
957/// monospace listings carry explicit space glyphs (so [`Grouping::CodeSpaceOnly`]
958/// keeps their spacing) — the parser emits no space glyphs: a source space is a
959/// positioning gap. So code cells use [`Grouping::CodeGap`], which splits on the
960/// inter-glyph gap (a space wherever it exceeds ~0.25× the line height) but never
961/// glues punctuation, so `et al. 2000` keeps its space while `add(a,` / `b)` stay
962/// joined. The parser's clean advance boxes make the gap heuristic reliable here,
963/// where pdfium's overhanging loose boxes would over-split (`f un c t i o n`).
964pub(crate) fn code_cells_from_glyphs(gs: &[Glyph], page_h: f32) -> Vec<TextCell> {
965 lines_from_glyphs(gs, page_h, Grouping::CodeGap)
966}
967
968/// Per-word cells (each word's text + top-left bbox), using the same word/line
969/// splitting as [`lines_from_glyphs`] but emitting one cell per word instead of
970/// joining into lines — the legacy gap-heuristic word grouping, kept for the
971/// pdfium word path (`DOCLING_PDFIUM_WORDS`). The default parser path uses
972/// [`crate::dp_lines::word_cells`] instead.
973pub(crate) fn words_from_glyphs(gs: &[Glyph], page_h: f32) -> Vec<TextCell> {
974 let mut cells = Vec::new();
975 let mut word = String::new();
976 let inf = (
977 f32::INFINITY,
978 f32::INFINITY,
979 f32::NEG_INFINITY,
980 f32::NEG_INFINITY,
981 );
982 let (mut wl, mut wb, mut wr, mut wt) = inf;
983 let mut line_h: f32 = 0.0;
984 let mut prev: Option<&Glyph> = None;
985 let mut pending_space = false;
986 for g in gs {
987 if g.ch == ' ' {
988 pending_space = true;
989 continue;
990 }
991 let h = (g.t - g.b).abs().max(1.0);
992 let mut new_line = false;
993 let mut new_word = false;
994 if let Some(p) = prev {
995 // LTR wraps reset x leftward (`g.l < p.r`); RTL (Arabic) wraps reset
996 // rightward (the new line begins at the far right). A large drop
997 // (≥1.5× line height) is a new line regardless of x.
998 let x_reset = if is_arabic(g.ch) || is_arabic(p.ch) {
999 g.l > p.r
1000 } else {
1001 g.l < p.r
1002 };
1003 new_line = (p.b - g.b > h * 0.5 && x_reset) || (p.b - g.b > line_h.max(h) * 1.5);
1004 // No digit-digit glue here (unlike the prose grouping): table cells in
1005 // adjacent columns are numeric and a column gap must still split them
1006 // (`0.965` `0.934`, not `0.9650.934`). Intra-number digits have no gap
1007 // so they stay together regardless.
1008 let glued = is_close_punct(g.ch)
1009 || is_open_punct(p.ch)
1010 || (p.ch == '.'
1011 && !pending_space
1012 && (g.ch.is_ascii_digit() || g.ch.is_ascii_lowercase()));
1013 let word_gap = line_h.max(h) * 0.25;
1014 new_word = new_line || ((pending_space || g.l - p.r > word_gap) && !glued);
1015 }
1016 pending_space = false;
1017 if new_word && !word.is_empty() {
1018 cells.push(TextCell {
1019 text: std::mem::take(&mut word),
1020 l: wl,
1021 t: page_h - wt,
1022 r: wr,
1023 b: page_h - wb,
1024 });
1025 (wl, wb, wr, wt) = inf;
1026 }
1027 if new_line {
1028 line_h = 0.0;
1029 }
1030 word.push(g.ch);
1031 wl = wl.min(g.l);
1032 wb = wb.min(g.b);
1033 wr = wr.max(g.r);
1034 wt = wt.max(g.t);
1035 line_h = line_h.max(h);
1036 prev = Some(g);
1037 }
1038 if !word.is_empty() {
1039 cells.push(TextCell {
1040 text: word,
1041 l: wl,
1042 t: page_h - wt,
1043 r: wr,
1044 b: page_h - wb,
1045 });
1046 }
1047 cells
1048}
1049
1050fn is_arabic(c: char) -> bool {
1051 ('\u{0600}'..='\u{06FF}').contains(&c)
1052}
1053
1054fn is_close_punct(c: char) -> bool {
1055 matches!(
1056 c,
1057 ',' | '.' | ';' | '!' | '?' | ')' | ']' | '}' | '%' | '\'' | '\u{2019}' | '\u{2018}'
1058 )
1059}
1060
1061fn is_open_punct(c: char) -> bool {
1062 // `@` glues to what follows (`mAP @0.5`, `bpf@zurich`, `@decorator`).
1063 matches!(c, '(' | '[' | '{' | '@')
1064}
1065
1066fn push_word(word: &mut String, words: &mut Vec<String>) {
1067 if !word.is_empty() {
1068 words.push(std::mem::take(word));
1069 }
1070}
1071
1072fn push_line(
1073 words: &mut Vec<String>,
1074 bbox: (f32, f32, f32, f32),
1075 page_h: f32,
1076 cells: &mut Vec<TextCell>,
1077) {
1078 if words.is_empty() {
1079 return;
1080 }
1081 let text = std::mem::take(words).join(" ");
1082 let (l, b, r, t) = bbox;
1083 cells.push(TextCell {
1084 text,
1085 l,
1086 t: page_h - t,
1087 r,
1088 b: page_h - b,
1089 });
1090}