[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
+112 -11
View File
@@ -118,6 +118,17 @@ fn page_chars(page: &PdfPage) -> Result<Vec<Ch>, 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<f32> = 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<Ch>) -> Vec<Line> {
let mut lines: Vec<Line> = Vec::new();
@@ -144,21 +155,30 @@ fn lines(chars: Vec<Ch>) -> Vec<Line> {
}
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<Ch> = 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<Ch> {
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");
}
}