A fast, helpful, and open-source document parser
Pin default text_width on a ligature and a fontless generated space
Sebas7672ddc54c0f
diff --git a/crates/liteparse/src/raw_text.rs b/crates/liteparse/src/raw_text.rsindex ad952cd..6be85ba 100644--- a/crates/liteparse/src/raw_text.rs+++ b/crates/liteparse/src/raw_text.rs@@ -385,7 +385,7 @@ fn build_item(bounds.right = bounds.right.max(glyph.loose.right);bounds.bottom = bounds.bottom.max(glyph.loose.bottom);}- // The first glyph is always read by char code, as `text_width` has always been.+ // Generated glyphs after the first are read by unicode; every other glyph by char code.let widths: Vec<f32> = glyphs.iter().enumerate()diff --git a/crates/liteparse/tests/integration_test.rs b/crates/liteparse/tests/integration_test.rsindex 9c8405f..d63b106 100644--- a/crates/liteparse/tests/integration_test.rs+++ b/crates/liteparse/tests/integration_test.rs@@ -989,6 +989,57 @@ async fn test_ocr_rounds_fill_across_sparse_pages() {/// items add up to the page's char count minus the generated line breaks it/// drops, items keep their trailing whitespace, and a generated glyph only/// ever closes an item.+#[test]+#[serial]+fn raw_text_items_account_for_every_glyph() {+ use liteparse::extract_raw_text_items;++ let lib = pdfium::Library::init();+ let document = lib+ .load_document("../../integration_tests_data/sample.pdf", None)+ .expect("sample.pdf loads");+ let page = document.page(0).expect("page 0 loads");+ let text_page = page.text().expect("text page loads");+ let view_box = page.view_box().expect("page has a bounding box");++ let items = extract_raw_text_items(&page, &text_page, &view_box, None);+ assert!(!items.is_empty(), "sample.pdf page 1 has text");++ let generated_breaks = text_page+ .chars()+ .filter(|c| c.is_generated() && matches!(c.unicode(), 0x0A | 0x0D))+ .count();+ let glyphs_in_items: usize = items.iter().map(|item| item.char_codes.len()).sum();+ assert_eq!(+ glyphs_in_items + generated_breaks,+ text_page.char_count() as usize,+ "every glyph lands in exactly one item"+ );++ for item in &items {+ assert!(!item.text.is_empty() || item.char_codes.iter().all(|&c| c == 0));+ assert!(item.width >= 0.0 && item.height >= 0.0);+ assert!((0.0..std::f32::consts::TAU).contains(&item.angle_radians));+ // A space glyph is always the last glyph of its item.+ let spaces: Vec<usize> = item+ .text+ .char_indices()+ .filter(|(_, c)| c.is_ascii_whitespace())+ .map(|(i, _)| i)+ .collect();+ assert!(+ spaces.iter().all(|&i| i == item.text.len() - 1),+ "whitespace closes an item: {:?}",+ item.text+ );+ }+ let text: String = items.iter().map(|item| item.text.as_str()).collect();+ assert!(+ text.chars().any(|c| c.is_alphabetic()),+ "sample text survives: {text:?}"+ );+}+/// The opt-in entry point returns the same items plus one advance per glyph, and/// those advances are the ones `text_width` sums.#[test]@@ -1028,55 +1079,92 @@ fn glyph_widths_are_opt_in_and_sum_to_text_width() {);}+/// One page that shows `(\002ce) Tj` in 12 pt Helvetica, where char code 2 is the+/// `fi` ligature and its ToUnicode entry maps it to "fi".+fn ligature_pdf() -> Vec<u8> {+ let content = "BT /F1 12 Tf 72 700 Td (\\002ce) Tj ET\n";+ let cmap = "/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /X def\n\+ 1 begincodespacerange <00> <FF> endcodespacerange\n\+ 1 beginbfchar <02> <00660069> endbfchar\n\+ 1 beginbfrange <20> <7E> <0020> endbfrange\n\+ endcmap CMapName currentdict /CMap defineresource pop end end\n";+ let objects = [+ "<< /Type /Catalog /Pages 2 0 R >>".to_string(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R \+ /Resources << /Font << /F1 5 0 R >> >> >>"+ .to_string(),+ format!(+ "<< /Length {} >>\nstream\n{content}endstream",+ content.len()+ ),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding << /Type /Encoding \+ /BaseEncoding /WinAnsiEncoding /Differences [2 /fi] >> /ToUnicode 6 0 R >>"+ .to_string(),+ format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len()),+ ];+ let mut pdf = b"%PDF-1.4\n".to_vec();+ let mut offsets = Vec::new();+ for (i, body) in objects.iter().enumerate() {+ offsets.push(pdf.len());+ pdf.extend(format!("{} 0 obj\n{body}\nendobj\n", i + 1).bytes());+ }+ let xref = pdf.len();+ pdf.extend(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).bytes());+ for offset in offsets {+ pdf.extend(format!("{offset:010} 00000 n \n").bytes());+ }+ pdf.extend(+ format!(+ "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n",+ objects.len() + 1+ )+ .bytes(),+ );+}++/// Without the opt-in, `text_width` is the Helvetica advances of the item's glyphs:+/// a ligature glyph is read by its char code and each of its two chars carries its+/// whole advance, and a generated space with no font adds 0.#[test]#[serial]-fn raw_text_items_account_for_every_glyph() {- use liteparse::extract_raw_text_items;+fn text_width_reads_char_codes_and_counts_a_missing_width_as_zero() {+ use liteparse::{extract_raw_text_items, extract_raw_text_items_with_glyph_widths};let lib = pdfium::Library::init();+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("ligature.pdf");+ std::fs::write(&path, ligature_pdf()).unwrap();let document = lib- .load_document("../../integration_tests_data/sample.pdf", None)- .expect("sample.pdf loads");+ .load_document(path.to_str().unwrap(), None)+ .expect("ligature.pdf loads");let page = document.page(0).expect("page 0 loads");let text_page = page.text().expect("text page loads");let view_box = page.view_box().expect("page has a bounding box");-let items = extract_raw_text_items(&page, &text_page, &view_box, None);- assert!(!items.is_empty(), "sample.pdf page 1 has text");-- let generated_breaks = text_page- .chars()- .filter(|c| c.is_generated() && matches!(c.unicode(), 0x0A | 0x0D))- .count();- let glyphs_in_items: usize = items.iter().map(|item| item.char_codes.len()).sum();+ assert_eq!(items.len(), 1);+ assert_eq!(items[0].text, "fice");+ // Helvetica advances per 1000 em: fi 500, c 500, e 556; at 12 pt.+ assert_eq!(items[0].text_width, 6.0 + 6.0 + 6.0 + 6.672);+ let with_widths = extract_raw_text_items_with_glyph_widths(&page, &text_page, &view_box, None);assert_eq!(- glyphs_in_items + generated_breaks,- text_page.char_count() as usize,- "every glyph lands in exactly one item"+ with_widths[0].glyph_widths,+ Some(vec![6.0, 6.0, 6.0, 6.672]));- for item in &items {- assert!(!item.text.is_empty() || item.char_codes.iter().all(|&c| c == 0));- assert!(item.width >= 0.0 && item.height >= 0.0);- assert!((0.0..std::f32::consts::TAU).contains(&item.angle_radians));- // A space glyph is always the last glyph of its item.- let spaces: Vec<usize> = item- .text- .char_indices()- .filter(|(_, c)| c.is_ascii_whitespace())- .map(|(i, _)| i)- .collect();- assert!(- spaces.iter().all(|&i| i == item.text.len() - 1),- "whitespace closes an item: {:?}",- item.text- );- }- let text: String = items.iter().map(|item| item.text.as_str()).collect();- assert!(- text.chars().any(|c| c.is_alphabetic()),- "sample text survives: {text:?}"- );+ let document = lib+ .load_document("../../integration_tests_data/diagonal_column.pdf", None)+ .expect("diagonal_column.pdf loads");+ let page = document.page(0).expect("page 0 loads");+ let text_page = page.text().expect("text page loads");+ let view_box = page.view_box().expect("page has a bounding box");+ let generated: Vec<_> = extract_raw_text_items(&page, &text_page, &view_box, None)+ .into_iter()+ .filter(|item| item.char_codes == [0])+ .collect();+ assert!(!generated.is_empty(), "the page has generated spaces");+ assert!(generated.iter().all(|item| item.text_width == 0.0));}/// A page whose content stream pairs a y-flipped CTM and `-100 Tz` with a