diff --git a/crates/pdf/src/word.rs b/crates/pdf/src/word.rs index 8ffed9c..c101946 100644 --- a/crates/pdf/src/word.rs +++ b/crates/pdf/src/word.rs @@ -118,6 +118,17 @@ fn page_chars(page: &PdfPage) -> Result, PdfError> { Ok(out) } +/// The median gap between neighbouring visible characters of a line (sorted by x), not below 0; 0 for short lines. +fn median_gap(chars: &[Ch]) -> f32 { + let visible: Vec<&Ch> = chars.iter().filter(|c| !c.c.is_whitespace()).collect(); + let mut gaps: Vec = visible.windows(2).map(|w| w[1].x0 - w[0].x1).collect(); + if gaps.len() < 4 { + return 0.0; + } + gaps.sort_by(f32::total_cmp); + gaps[gaps.len() / 2].max(0.0) +} + /// Characters in pdfium's order → lines, top to bottom (PDF y grows upwards). fn lines(chars: Vec) -> Vec { let mut lines: Vec = Vec::new(); @@ -144,21 +155,30 @@ fn lines(chars: Vec) -> Vec { } for l in &mut lines { l.chars.sort_by(|a, b| a.x0.total_cmp(&b.x0)); - // pdfium adds spaces of its own between words; make sure words that touch get one too. + // Spaces come from the gaps between letters, not from pdfium's whitespace: many PDFs have no space glyphs, + // and pdfium then invents zero-width spaces, some of them inside a word where the producer split it into + // two text objects ("Dichotomou" + "s"). A whitespace character only lowers the gap a space needs. + // The gap is measured against the line's own letter spacing (its median gap: most neighbours are letters of + // one word), so justified text with narrow word gaps (0.14 em) is spaced and tracked-out headings are not + // split into letters. + let letter_gap = median_gap(&l.chars); let mut with_spaces: Vec = Vec::with_capacity(l.chars.len()); + let mut whitespace_seen = false; for ch in std::mem::take(&mut l.chars) { - if let Some(prev) = with_spaces.last() - && !prev.c.is_whitespace() - && !ch.c.is_whitespace() - && ch.x0 - prev.x1 > 0.18 * ch.size - { - let mut sp = prev.clone(); - sp.c = ' '; - with_spaces.push(sp); - } - if ch.c.is_whitespace() && with_spaces.last().is_some_and(|p| p.c.is_whitespace()) { + if ch.c.is_whitespace() { + whitespace_seen = true; continue; } + if let Some(prev) = with_spaces.last() { + let gap = ch.x0 - prev.x1 - letter_gap; + let size = ch.size.max(prev.size); + if gap > 0.1 * size || (whitespace_seen && gap > 0.05 * size) { + let mut sp = prev.clone(); + sp.c = ' '; + with_spaces.push(sp); + } + } + whitespace_seen = false; with_spaces.push(ch); } l.chars = with_spaces; @@ -401,3 +421,84 @@ pub fn to_word( docx.build().pack(&mut out).map_err(|e| PdfError::Write(e.to_string()))?; Ok(WordResult { bytes: out.into_inner(), pages: n, scanned_pages: scanned }) } + +#[cfg(test)] +mod tests { + use super::*; + + fn ch(c: char, x0: f32, x1: f32, size: f32) -> Ch { + Ch { c, x0, x1, y0: 700.0, y1: 700.0 + size, size, bold: false, italic: false } + } + + fn text(line: &Line) -> String { + line.chars.iter().map(|c| c.c).collect() + } + + /// The characters pdfium gave for a WPS Writer PDF (no space glyphs, words split over text objects): a + /// zero-width space of size 1 between the touching "u" and "s" of "Dichotomous", and a misplaced one in the + /// real 4 pt gap before "Segmentation". + #[test] + fn invented_spaces_inside_a_word_are_dropped_and_gaps_make_spaces() { + let s = 15.9; + let chars = vec![ + ch('o', 277.86, 285.83, s), + ch('u', 285.86, 294.72, s), + ch(' ', 292.53, 292.53, 1.0), + ch('s', 294.75, 300.96, s), + ch('I', 304.92, 311.12, s), + ch('m', 311.15, 324.43, s), + ch('e', 324.47, 332.45, s), + ch(' ', 326.0, 326.0, 1.0), + ch('S', 336.60, 345.47, s), + ]; + let l = lines(chars); + assert_eq!(l.len(), 1); + assert_eq!(text(&l[0]), "ous Ime S"); + } + + /// A PDF with real space glyphs keeps one space per gap, and a narrow space (a condensed font) still counts. + #[test] + fn real_space_glyphs_still_make_spaces() { + let s = 10.0; + let chars = vec![ + ch('a', 0.0, 5.0, s), + ch(' ', 5.0, 6.2, s), + ch('b', 6.2, 11.0, s), + ch(' ', 11.0, 11.5, s), + ch(' ', 11.5, 14.0, s), + ch('c', 14.0, 19.0, s), + ch('d', 19.02, 24.0, s), + ]; + assert_eq!(text(&lines(chars)[0]), "a b cd"); + } + + /// Lays a line out from words: letters `track` apart, words `space` apart (in points), no space glyphs. + fn laid_out(words: &[&str], size: f32, track: f32, space: f32) -> Vec { + let mut x = 0.0; + let mut out = Vec::new(); + for (i, w) in words.iter().enumerate() { + if i > 0 { + x += space - track; + } + for c in w.chars() { + out.push(ch(c, x, x + 0.5 * size, size)); + x += 0.5 * size + track; + } + } + out + } + + /// Justified text from the same WPS PDF: "of personal" is 1.55 pt apart at 11 pt (0.14 em). + #[test] + fn narrow_justified_word_gaps_are_spaces() { + let chars = laid_out(&["terms", "of", "personal", "data"], 11.05, 0.03, 1.55); + assert_eq!(text(&lines(chars)[0]), "terms of personal data"); + } + + /// A heading tracked out to 0.15 em between letters is not split into letters. + #[test] + fn tracked_out_letters_stay_one_word() { + let chars = laid_out(&["CHAPTER", "ONE"], 20.0, 3.0, 12.0); + assert_eq!(text(&lines(chars)[0]), "CHAPTER ONE"); + } +} diff --git a/crates/pdf/tests/word.rs b/crates/pdf/tests/word.rs index 9fcb0ab..b865803 100644 --- a/crates/pdf/tests/word.rs +++ b/crates/pdf/tests/word.rs @@ -215,3 +215,91 @@ fn libreoffice_reads_every_word_in_order() { let text = std::fs::read_to_string(&out).expect("LibreOffice converted the .docx"); assert_in_order(&text, ORDER); } + +/// A PDF written like many real ones (Word's own export among them): no space glyphs between words, only gaps, and +/// a word split over two text objects where the line was justified ("Dichotomou" | "s"). pdfium invents a +/// zero-width space at such a split; the .docx must not break the word there, and must still space the words. +fn no_space_glyphs_pdf() -> Vec { + let mut doc = Document::with_version("1.7"); + let pages_id = doc.new_object_id(); + let reg = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", "Encoding" => "WinAnsiEncoding"}); + // Helvetica advance widths (AFM, /1000 em) for the pieces, so each piece starts exactly where the last ended. + let w = |s: &str| -> f32 { + s.chars() + .map(|c| match c { + 'D' => 722.0, + 'I' | 'i' | 'l' | 'j' => 222.0, + 'c' | 'k' | 's' | 'v' | 'x' | 'y' | 'z' => 500.0, + 'f' | 't' => 278.0, + 'm' => 833.0, + 'r' => 333.0, + 'w' => 722.0, + 'S' | 'H' | 'A' | 'E' => 667.0, + _ => 556.0, + }) + .sum::() + * 16.0 + / 1000.0 + }; + let mut c = String::new(); + // Line 1: words as separate objects, a 4 pt gap between them, "Dichotomous" split in two touching objects. + let mut x = 72.0; + for (piece, gap_after) in [ + ("Highly", 4.0), + ("Accurate", 4.0), + ("Dichotomou", 0.0), + ("s", 4.0), + ("Image", 4.0), + ("Segmentat", 0.0), + ("ion", 0.0), + ] { + c += &format!("BT /F1 16 Tf {x:.2} 700 Td ({piece}) Tj ET\n"); + x += w(piece) + gap_after; + } + // Line 2: the same inside one text object, moved with Td (the other common way). + c += "BT /F1 16 Tf 72 670 Td (evalu) Tj "; + c += &format!("{:.2} 0 Td (ation) Tj {:.2} 0 Td (of) Tj ET\n", w("evalu"), w("ation") + 4.0); + // Line 3, as WPS Writer writes it: the page flipped (y down), each word a text object with a flipped Tm at + // 319 pt × 0.05, and every glyph its own Tj moved by TD in glyph widths. + c += "q 1 0 0 -1 0 842 cm +"; + let mut x = 72.0; + for word in ["Dichotomous", "Image", "Segmentation", "Dataset"] { + c += &format!("q BT /F1 319 Tf 0.05 0 0 -0.05 {x:.3} 230 Tm "); + for (i, ch) in word.chars().enumerate() { + if i > 0 { + let prev = word.chars().nth(i - 1).unwrap().to_string(); + c += &format!("{:.3} -0 TD ", w(&prev) / 16.0 * 319.0); + } + c += &format!("({ch}) Tj "); + } + c += "ET Q +"; + x += w(word) / 16.0 * 319.0 * 0.05 + 4.0; + } + c += "Q +"; + let cid = doc.add_object(Stream::new(dictionary! {}, c.into_bytes())); + let page = doc.add_object(dictionary! {"Type" => "Page", "Parent" => pages_id, "Contents" => cid, + "Resources" => dictionary! {"Font" => dictionary! {"F1" => reg}}}); + doc.objects.insert( + pages_id, + Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1, + "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}), + ); + let cat = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id}); + doc.trailer.set("Root", cat); + let mut out = Vec::new(); + doc.save_to(&mut out).unwrap(); + out +} + +#[test] +fn words_split_over_text_objects_stay_whole() { + let r = pictor_pdf::to_word(engine(), &no_space_glyphs_pdf(), None, &Default::default()).unwrap(); + let text = text_of(&String::from_utf8(part(&r.bytes, "word/document.xml").unwrap()).unwrap()); + let flat = text.split_whitespace().collect::>().join(" "); + assert!(flat.contains("Highly Accurate Dichotomous Image Segmentation"), "{flat:?}"); + assert!(flat.contains("evaluation of"), "{flat:?}"); + assert!(flat.contains("Dichotomous Image Segmentation Dataset"), "{flat:?}"); +} diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 124435c..9a230ce 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -44,7 +44,7 @@ page as displayed (the crop box, `/Rotate` applied). `geometry::PageFrame` conve | password off | lopdf decrypting load + plain save | | | true redaction | pdfium render + lopdf rebuild (below) | | | compress presets (Day 2) | lopdf: images capped at the largest page side × the preset's dpi and re-encoded as JPEG (E-mail 120 → 96 → 72 dpi until ≤ 5 MB, Web 150, Print 300); Flate everywhere; object streams | text, fonts and vectors untouched, so text stays extractable; fonts are not subset (gap) | -| PDF to Word (Day 2) | pdfium characters (box, size, weight, slant) → lines, segments, tables, paragraphs, headings; images at their place; docx-rs writes the .docx | "Layout is approximate"; scanned pages are reported, and OCR text from Fundamentum's Lector can be passed in | +| PDF to Word (Day 2) | pdfium characters (box, size, weight, slant) → lines, segments, tables, paragraphs, headings; images at their place; docx-rs writes the .docx | "Layout is approximate"; spaces come from the gaps between letters (measured against the line's own letter spacing), never from pdfium's invented whitespace, so PDFs without space glyphs keep whole words; glyphs without a Unicode mapping stay U+FFFD; scanned pages are reported, and OCR text from Fundamentum's Lector can be passed in | ### True redaction