|
| 1 | +//! Run **exactly** what a wasm build does with a PDF: `convert_text_layer` — |
| 2 | +//! the pure-Rust content-stream parser, no pdfium, no ONNX. Use it to tell a |
| 3 | +//! browser "this PDF needs OCR" apart from a genuine scan: the browser falls |
| 4 | +//! back to OCR precisely when this produces no nodes, so an empty result here |
| 5 | +//! reproduces that decision offline. |
| 6 | +//! |
| 7 | +//! Note this is *not* what the CLI's `--no-ocr` runs — that goes through |
| 8 | +//! pdfium's text extraction, which can read layers this parser cannot. When the |
| 9 | +//! two disagree, the breakdown below says which stage lost the text. |
| 10 | +//! |
| 11 | +//! ```bash |
| 12 | +//! cargo run -p docling-pdf --no-default-features --example text_layer -- <pdf> |
| 13 | +//! ``` |
| 14 | +//! (`--no-default-features` keeps pdfium/onnxruntime out of the build.) |
| 15 | +
|
| 16 | +fn main() { |
| 17 | + let path = match std::env::args().nth(1) { |
| 18 | + Some(p) => p, |
| 19 | + None => { |
| 20 | + eprintln!("usage: text_layer <pdf>"); |
| 21 | + std::process::exit(2); |
| 22 | + } |
| 23 | + }; |
| 24 | + let bytes = std::fs::read(&path).expect("read the pdf"); |
| 25 | + let name = std::path::Path::new(&path) |
| 26 | + .file_name() |
| 27 | + .map(|n| n.to_string_lossy().into_owned()) |
| 28 | + .unwrap_or_else(|| path.clone()); |
| 29 | + |
| 30 | + // Stage 1 — does lopdf load the document at all? `textparse` swallows this |
| 31 | + // failure (an unloadable PDF and a scan both come out empty), so ask |
| 32 | + // directly: encryption, a damaged xref or an unsupported filter all land |
| 33 | + // here, and they mean something very different from "no text layer". |
| 34 | + match lopdf::Document::load_mem(&bytes) { |
| 35 | + Err(e) => { |
| 36 | + eprintln!("1. lopdf load: FAILED — {e}"); |
| 37 | + eprintln!(" (the browser reports this as \"no embedded text layer\")"); |
| 38 | + eprintln!( |
| 39 | + " xref repair: {}", |
| 40 | + docling_pdf::textparse::xref_repair_status(&bytes) |
| 41 | + ); |
| 42 | + probe_tail(&bytes); |
| 43 | + } |
| 44 | + Ok(doc) => { |
| 45 | + eprintln!( |
| 46 | + "1. lopdf load: ok — {} page(s), version {}, encrypted: {}", |
| 47 | + doc.get_pages().len(), |
| 48 | + doc.version, |
| 49 | + doc.is_encrypted() |
| 50 | + ); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + // Stage 2 — raw line cells out of the content streams. Zero here with a |
| 55 | + // successful load means the text is there but we cannot decode it (font |
| 56 | + // encoding, an unhandled operator, a filter), not that the page is a scan. |
| 57 | + let pages = docling_pdf::textparse::pdf_textlines(&bytes); |
| 58 | + let cells: usize = pages.iter().map(|(_, _, c)| c.len()).sum(); |
| 59 | + eprintln!("2. text lines: {cells} across {} page(s)", pages.len()); |
| 60 | + if cells == 0 { |
| 61 | + eprintln!( |
| 62 | + " where it is lost:{}", |
| 63 | + docling_pdf::textparse::content_diagnosis(&bytes) |
| 64 | + ); |
| 65 | + } |
| 66 | + for (i, (_, _, c)) in pages.iter().enumerate().take(3) { |
| 67 | + if let Some(first) = c.iter().find(|c| !c.text.trim().is_empty()) { |
| 68 | + eprintln!(" page {}: first line {:?}", i + 1, first.text); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + // Stage 3 — the assembled document, i.e. what the browser actually gets. |
| 73 | + match docling_pdf::convert_text_layer(&bytes, &name) { |
| 74 | + Ok(doc) => { |
| 75 | + let md = doc.export_to_markdown(); |
| 76 | + eprintln!( |
| 77 | + "3. convert_text_layer: {} node(s), {} chars — {}", |
| 78 | + doc.nodes.len(), |
| 79 | + md.len(), |
| 80 | + if doc.nodes.is_empty() { |
| 81 | + "EMPTY: a browser build would fall back to OCR here" |
| 82 | + } else { |
| 83 | + "the browser would use this directly (no OCR)" |
| 84 | + } |
| 85 | + ); |
| 86 | + println!("{md}"); |
| 87 | + } |
| 88 | + Err(e) => { |
| 89 | + eprintln!("3. convert_text_layer: FAILED — {e}"); |
| 90 | + std::process::exit(1); |
| 91 | + } |
| 92 | + } |
| 93 | +} |
| 94 | + |
| 95 | +/// When the document will not load, show the cross-reference machinery the |
| 96 | +/// parser choked on: the last `startxref`, where it points, and what actually |
| 97 | +/// sits there. A classic `xref` table, an xref *stream* (`/Type /XRef`), bytes |
| 98 | +/// past the end of the file or plain garbage each point at a different repair, |
| 99 | +/// and this is enough to tell them apart without handing the PDF around. |
| 100 | +fn probe_tail(bytes: &[u8]) { |
| 101 | + let find_last = |needle: &[u8]| { |
| 102 | + bytes |
| 103 | + .windows(needle.len()) |
| 104 | + .rposition(|w| w == needle) |
| 105 | + .map(|i| (i, needle.len())) |
| 106 | + }; |
| 107 | + let printable = |b: &[u8]| -> String { |
| 108 | + b.iter() |
| 109 | + .map(|&c| { |
| 110 | + if (0x20..0x7f).contains(&c) { |
| 111 | + c as char |
| 112 | + } else if c == b'\n' || c == b'\r' { |
| 113 | + '\u{23ce}' |
| 114 | + } else { |
| 115 | + '.' |
| 116 | + } |
| 117 | + }) |
| 118 | + .collect() |
| 119 | + }; |
| 120 | + |
| 121 | + eprintln!(" file: {} bytes", bytes.len()); |
| 122 | + eprintln!( |
| 123 | + " markers: trailer={} startxref={} xref={} /XRef={} %%EOF={}", |
| 124 | + find_last(b"trailer").is_some(), |
| 125 | + find_last(b"startxref").is_some(), |
| 126 | + find_last(b"xref").is_some(), |
| 127 | + find_last(b"/XRef").is_some(), |
| 128 | + find_last(b"%%EOF").is_some(), |
| 129 | + ); |
| 130 | + |
| 131 | + // Trailing bytes after the final %%EOF confuse a strict tail scan. |
| 132 | + if let Some((i, len)) = find_last(b"%%EOF") { |
| 133 | + let after = bytes.len() - (i + len); |
| 134 | + eprintln!(" bytes after the last %%EOF: {after}"); |
| 135 | + } |
| 136 | + |
| 137 | + let Some((sx, _)) = find_last(b"startxref") else { |
| 138 | + eprintln!(" no startxref at all — the xref would have to be rebuilt by scanning objects"); |
| 139 | + return; |
| 140 | + }; |
| 141 | + let tail = &bytes[sx..bytes.len().min(sx + 60)]; |
| 142 | + eprintln!(" last startxref block: {:?}", printable(tail)); |
| 143 | + |
| 144 | + // The number after `startxref` is the byte offset of the xref section. |
| 145 | + let digits: String = tail |
| 146 | + .iter() |
| 147 | + .skip(b"startxref".len()) |
| 148 | + .skip_while(|c| c.is_ascii_whitespace()) |
| 149 | + .take_while(|c| c.is_ascii_digit()) |
| 150 | + .map(|&c| c as char) |
| 151 | + .collect(); |
| 152 | + match digits.parse::<usize>() { |
| 153 | + Ok(off) if off < bytes.len() => { |
| 154 | + let end = bytes.len().min(off + 120); |
| 155 | + eprintln!(" at offset {off} -> {:?}", printable(&bytes[off..end])); |
| 156 | + } |
| 157 | + Ok(off) => eprintln!(" startxref points to {off}, past the end of the file"), |
| 158 | + Err(_) => eprintln!(" startxref carries no parseable offset"), |
| 159 | + } |
| 160 | +} |
0 commit comments