Files
Pictor-public/crates/pdf/src/word.rs
T
2026-11-17 00:57:06 +01:00

404 lines
15 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! PDF to Word (Day 2): editable text with its structure, not a pixel copy ("Layout is approximate").
//!
//! pdfium gives every character with its box, size, weight and slant. Pictor rebuilds, per page, top to bottom:
//! lines (characters on one baseline), segments (pieces of a line split by a wide gap), tables (two or more
//! consecutive lines whose segments start at the same columns), paragraphs (consecutive single-segment lines of the
//! same size and left edge, close together), headings (clearly larger or bold-and-short text, measured against the
//! document's body size) and images (each image object, at its place). The .docx is written by docx-rs.
//!
//! A page with (almost) no text but an image is a scan: it is listed in `scanned_pages`, and text recognised
//! elsewhere (Fundamentum's Lector, through the app) can be passed back in `WordOptions::ocr` for those pages.
use crate::{Engine, PdfError};
use docx_rs::{BreakType, Docx, Paragraph, Pic, Run, RunFonts, Style, StyleType, Table, TableCell, TableRow};
use pdfium_render::prelude::*;
use std::collections::HashMap;
#[derive(Debug, Clone, Default)]
pub struct WordOptions {
/// Recognised text for scanned pages (0-based page → text; blank lines separate paragraphs).
pub ocr: HashMap<usize, String>,
}
#[derive(Debug, Clone)]
pub struct WordResult {
pub bytes: Vec<u8>,
pub pages: usize,
/// Pages with no text layer (scans) that had no OCR text given.
pub scanned_pages: Vec<usize>,
}
#[derive(Clone, Debug)]
struct Ch {
c: char,
x0: f32,
x1: f32,
y0: f32,
y1: f32,
size: f32,
bold: bool,
italic: bool,
}
#[derive(Debug, Clone)]
struct Line {
chars: Vec<Ch>,
top: f32,
bottom: f32,
size: f32,
}
impl Line {
fn left(&self) -> f32 {
self.chars.first().map(|c| c.x0).unwrap_or(0.0)
}
/// Pieces of the line separated by a gap wider than 2.2 × the font size.
fn segments(&self) -> Vec<Vec<Ch>> {
let mut out: Vec<Vec<Ch>> = Vec::new();
let mut cur: Vec<Ch> = Vec::new();
for ch in &self.chars {
if let Some(prev) = cur.iter().rev().find(|c| !c.c.is_whitespace())
&& ch.x0 - prev.x1 > 2.2 * self.size.max(1.0)
&& !ch.c.is_whitespace()
{
out.push(std::mem::take(&mut cur));
}
cur.push(ch.clone());
}
if !cur.is_empty() {
out.push(cur);
}
out.into_iter().map(trim).filter(|s| !s.is_empty()).collect()
}
}
fn trim(mut v: Vec<Ch>) -> Vec<Ch> {
while v.first().is_some_and(|c| c.c.is_whitespace()) {
v.remove(0);
}
while v.last().is_some_and(|c| c.c.is_whitespace()) {
v.pop();
}
v
}
enum Item {
Lines(Vec<Line>),
Image { top: f32, png: Vec<u8>, w_px: u32, h_px: u32, w_pt: f32, h_pt: f32 },
}
fn item_top(i: &Item) -> f32 {
match i {
Item::Lines(l) => l.first().map(|l| l.top).unwrap_or(0.0),
Item::Image { top, .. } => *top,
}
}
fn page_chars(page: &PdfPage) -> Result<Vec<Ch>, PdfError> {
let text = page.text().map_err(PdfError::from_pdfium)?;
let mut out = Vec::new();
for ch in text.chars().iter() {
let Some(c) = ch.unicode_char() else { continue };
if c == '\r' || c == '\n' || c == '\u{2}' || c == '\u{fffe}' {
continue;
}
let Ok(b) = ch.loose_bounds() else { continue };
let name = ch.font_name().to_ascii_lowercase();
let weight = matches!(ch.font_weight(), Some(w) if matches!(w, PdfFontWeight::Weight600 | PdfFontWeight::Weight700Bold | PdfFontWeight::Weight800 | PdfFontWeight::Weight900 | PdfFontWeight::Custom(600..)));
out.push(Ch {
c,
x0: b.left().value,
x1: b.right().value,
y0: b.bottom().value,
y1: b.top().value,
size: ch.scaled_font_size().value.max(1.0),
bold: weight || name.contains("bold") || name.contains("black") || name.contains("heavy"),
italic: ch.font_is_italic() || name.contains("italic") || name.contains("oblique"),
});
}
Ok(out)
}
/// 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();
for ch in chars {
let mid = (ch.y0 + ch.y1) / 2.0;
let found = lines.iter_mut().rev().take(3).find(|l| {
let lmid = (l.top + l.bottom) / 2.0;
(mid - lmid).abs() < 0.45 * l.size.max(ch.size)
});
match found {
Some(l) => {
l.top = l.top.max(ch.y1);
l.bottom = l.bottom.min(ch.y0);
if !ch.c.is_whitespace() {
l.size = l.size.max(ch.size);
}
l.chars.push(ch);
}
None => {
let size = ch.size;
lines.push(Line { top: ch.y1, bottom: ch.y0, size, chars: vec![ch] });
}
}
}
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.
let mut with_spaces: Vec<Ch> = Vec::with_capacity(l.chars.len());
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()) {
continue;
}
with_spaces.push(ch);
}
l.chars = with_spaces;
}
lines.retain(|l| l.chars.iter().any(|c| !c.c.is_whitespace()));
lines.sort_by(|a, b| b.top.total_cmp(&a.top));
lines
}
fn body_size(all: &[Vec<Line>]) -> f32 {
let mut counts: HashMap<u32, usize> = HashMap::new();
for l in all.iter().flatten() {
*counts.entry((l.size * 2.0).round() as u32).or_default() += l.chars.len();
}
counts.into_iter().max_by_key(|(_, n)| *n).map(|(s, _)| s as f32 / 2.0).unwrap_or(11.0)
}
fn heading_level(chars: &[Ch], size: f32, body: f32) -> Option<usize> {
let len = chars.iter().filter(|c| !c.c.is_whitespace()).count();
let bold = chars.iter().filter(|c| !c.c.is_whitespace()).all(|c| c.bold);
if size >= body * 1.8 {
Some(1)
} else if size >= body * 1.25 {
Some(2)
} else if bold && len <= 80 && size >= body * 1.05 {
Some(3)
} else {
None
}
}
fn runs(chars: &[Ch]) -> Vec<Run> {
let mut out = Vec::new();
let mut i = 0;
while i < chars.len() {
let (b, it, sz) = (chars[i].bold, chars[i].italic, (chars[i].size * 2.0).round() as usize);
let mut j = i;
let mut s = String::new();
while j < chars.len() && chars[j].bold == b && chars[j].italic == it {
s.push(chars[j].c);
j += 1;
}
let mut r = Run::new().add_text(s).size(sz.clamp(8, 144));
if b {
r = r.bold();
}
if it {
r = r.italic();
}
out.push(r);
i = j;
}
out
}
/// One page's lines → paragraphs and tables, in order.
fn blocks(lines: Vec<Line>, body: f32, mut out: Docx) -> Docx {
let mut i = 0;
while i < lines.len() {
// A table: two or more consecutive lines with ≥ 2 segments whose starts line up.
let segs = lines[i].segments();
if segs.len() >= 2 {
let cols: Vec<f32> = segs.iter().map(|s| s[0].x0).collect();
let mut rows = vec![segs];
let mut j = i + 1;
while j < lines.len() {
let s = lines[j].segments();
let fits = s.len() == cols.len()
&& s.iter().zip(&cols).all(|(seg, x)| (seg[0].x0 - x).abs() < 0.8 * lines[j].size.max(6.0));
let close = lines[j - 1].bottom - lines[j].top < 2.5 * lines[j].size;
if !fits || !close {
break;
}
rows.push(s);
j += 1;
}
if rows.len() >= 2 {
let table = Table::new(
rows.iter()
.map(|r| {
TableRow::new(
r.iter()
.map(|cell| {
TableCell::new().add_paragraph(
runs(cell).into_iter().fold(Paragraph::new(), |p, r| p.add_run(r)),
)
})
.collect(),
)
})
.collect(),
);
out = out.add_table(table);
i = j;
continue;
}
}
// A paragraph: join following lines of the same size and left edge that sit close below.
let first = &lines[i];
let mut chars: Vec<Ch> = first.chars.clone();
let mut j = i + 1;
while j < lines.len() {
let (prev, next) = (&lines[j - 1], &lines[j]);
let same_size = (next.size - first.size).abs() < 0.6;
let same_left = (next.left() - first.left()).abs() < 1.5 * first.size;
let close = prev.bottom - next.top < 1.0 * first.size;
if !(same_size && same_left && close)
|| next.segments().len() > 1
|| heading_level(&first.chars, first.size, body).is_some()
{
break;
}
// A hyphen at a line end joins the word; else a space.
if chars.last().is_some_and(|c| c.c == '-' || c.c == '\u{ad}') {
chars.pop();
} else {
let mut sp = chars.last().cloned().expect("non-empty");
sp.c = ' ';
chars.push(sp);
}
chars.extend(next.chars.iter().cloned());
j += 1;
}
let chars = trim(chars);
let mut p = runs(&chars).into_iter().fold(Paragraph::new(), |p, r| p.add_run(r));
if let Some(level) = heading_level(&chars, first.size, body) {
p = p.style(&format!("Heading{level}"));
}
out = out.add_paragraph(p);
i = j;
}
out
}
fn styles(doc: Docx) -> Docx {
doc.add_style(Style::new("Heading1", StyleType::Paragraph).name("heading 1").size(40).bold().outline_lvl(0))
.add_style(Style::new("Heading2", StyleType::Paragraph).name("heading 2").size(30).bold().outline_lvl(1))
.add_style(Style::new("Heading3", StyleType::Paragraph).name("heading 3").size(24).bold().outline_lvl(2))
.default_fonts(RunFonts::new().ascii("Calibri").hi_ansi("Calibri").cs("Calibri").east_asia("Calibri"))
.default_size(22)
}
/// Converts a PDF to a .docx.
pub fn to_word(
engine: &Engine,
bytes: &[u8],
password: Option<&str>,
opts: &WordOptions,
) -> Result<WordResult, PdfError> {
let doc = engine.open(bytes, password)?;
let n = doc.pages().len() as usize;
if n > 2000 {
return Err(PdfError::TooLarge(format!("{n} pages")));
}
let mut per_page: Vec<Vec<Item>> = Vec::with_capacity(n);
let mut all_lines: Vec<Vec<Line>> = Vec::with_capacity(n);
let mut scanned = Vec::new();
for (i, page) in doc.pages().iter().enumerate() {
let chars = page_chars(&page)?;
let visible = chars.iter().filter(|c| !c.c.is_whitespace()).count();
let mut items = Vec::new();
let mut images = 0;
for obj in page.objects().iter() {
let Some(img) = obj.as_image_object() else { continue };
let Ok(b) = obj.bounds() else { continue };
let Ok(raw) = img.get_raw_image() else { continue };
let (w_pt, h_pt) = (b.width().value, b.height().value);
if w_pt < 8.0 || h_pt < 8.0 {
continue;
}
images += 1;
// Keep pictures a sensible size in the document (at most 1600 px on the long side).
let raw = if raw.width().max(raw.height()) > 1600 {
raw.resize(1600, 1600, image::imageops::FilterType::Triangle)
} else {
raw
};
let mut png = Vec::new();
if raw.to_rgb8().write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() {
continue;
}
items.push(Item::Image { top: b.top().value, png, w_px: raw.width(), h_px: raw.height(), w_pt, h_pt });
}
let page_lines = lines(chars);
if visible < 10 && images > 0 {
if opts.ocr.contains_key(&i) {
items.clear(); // the recognised text replaces the scan
} else {
scanned.push(i);
}
}
all_lines.push(page_lines);
per_page.push(items);
}
let body = body_size(&all_lines);
let mut docx = styles(Docx::new());
for (i, (page_lines, images)) in all_lines.into_iter().zip(per_page).enumerate() {
if i > 0 {
docx = docx.add_paragraph(Paragraph::new().add_run(Run::new().add_break(BreakType::Page)));
}
if let Some(t) = opts.ocr.get(&i) {
for para in
t.split("\n\n").map(|p| p.split_whitespace().collect::<Vec<_>>().join(" ")).filter(|p| !p.is_empty())
{
docx = docx.add_paragraph(Paragraph::new().add_run(Run::new().add_text(para)));
}
}
// Interleave text runs and images by their top edge.
let mut items: Vec<Item> = images;
let mut group: Vec<Line> = Vec::new();
let mut groups: Vec<Item> = Vec::new();
let tops: Vec<f32> = items.iter().map(item_top).collect();
for l in page_lines {
if tops.iter().any(|t| *t < (group.last().map(|g: &Line| g.top).unwrap_or(f32::MAX)) && *t >= l.top)
&& !group.is_empty()
{
groups.push(Item::Lines(std::mem::take(&mut group)));
}
group.push(l);
}
if !group.is_empty() {
groups.push(Item::Lines(group));
}
items.extend(groups);
items.sort_by(|a, b| item_top(b).total_cmp(&item_top(a)));
for item in items {
match item {
Item::Lines(ls) => docx = blocks(ls, body, docx),
Item::Image { png, w_px, h_px, w_pt, h_pt, .. } => {
// Size in EMU (1 pt = 12 700 EMU), at most 6.5 inches wide.
let k = (468.0 / w_pt).min(1.0);
let pic = Pic::new_with_dimensions(png, w_px, h_px)
.size((w_pt * k * 12_700.0) as u32, (h_pt * k * 12_700.0) as u32);
docx = docx.add_paragraph(Paragraph::new().add_run(Run::new().add_image(pic)));
}
}
}
}
let mut out = std::io::Cursor::new(Vec::new());
docx.build().pack(&mut out).map_err(|e| PdfError::Write(e.to_string()))?;
Ok(WordResult { bytes: out.into_inner(), pages: n, scanned_pages: scanned })
}