[pdf] PDF to Word: spaces from letter gaps, not pdfium's invented whitespace (whole words in PDFs without space glyphs)

This commit is contained in:
2026-11-17 03:08:37 +01:00
parent 47576bd6e0
commit 45f1d40c5b
3 changed files with 201 additions and 12 deletions
+88
View File
@@ -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<u8> {
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::<f32>()
* 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::<Vec<_>>().join(" ");
assert!(flat.contains("Highly Accurate Dichotomous Image Segmentation"), "{flat:?}");
assert!(flat.contains("evaluation of"), "{flat:?}");
assert!(flat.contains("Dichotomous Image Segmentation Dataset"), "{flat:?}");
}