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