From 6efc835d24c497386e0ed0c79abeda50e7b76e66 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 00:57:06 +0100 Subject: [PATCH] [repo] Format --- crates/pdf/src/compress.rs | 16 +- crates/pdf/src/word.rs | 786 +++++++++++++------------- crates/pdf/tests/compress.rs | 7 +- crates/pdf/tests/word.rs | 397 ++++++++------ crates/worker/src/ops.rs | 1001 +++++++++++++++++----------------- 5 files changed, 1139 insertions(+), 1068 deletions(-) diff --git a/crates/pdf/src/compress.rs b/crates/pdf/src/compress.rs index 76ca250..a05e858 100644 --- a/crates/pdf/src/compress.rs +++ b/crates/pdf/src/compress.rs @@ -42,7 +42,9 @@ struct Step { fn steps(preset: CompressPreset) -> &'static [Step] { match preset { - CompressPreset::Email => &[Step { dpi: 120.0, quality: 62 }, Step { dpi: 96.0, quality: 55 }, Step { dpi: 72.0, quality: 50 }], + CompressPreset::Email => { + &[Step { dpi: 120.0, quality: 62 }, Step { dpi: 96.0, quality: 55 }, Step { dpi: 72.0, quality: 50 }] + } CompressPreset::Web => &[Step { dpi: 150.0, quality: 72 }], CompressPreset::Print => &[Step { dpi: 300.0, quality: 86 }], } @@ -195,7 +197,11 @@ fn recompress(doc: &Document, s: &Stream, max_px: u32, quality: u8) -> Option { - let raw = if filter.is_empty() { s.content.clone() } else { s.decompressed_content_with_limit(600 << 20).ok()? }; + let raw = if filter.is_empty() { + s.content.clone() + } else { + s.decompressed_content_with_limit(600 << 20).ok()? + }; let need = (w as usize) * (h as usize) * n as usize; if raw.len() < need { return None; @@ -210,7 +216,11 @@ fn recompress(doc: &Document, s: &Stream, max_px: u32, quality: u8) -> Option max_px + max_px / 10 { let k = max_px as f32 / iw.max(ih) as f32; - img.resize_exact(((iw as f32 * k).round() as u32).max(1), ((ih as f32 * k).round() as u32).max(1), image::imageops::FilterType::Lanczos3) + img.resize_exact( + ((iw as f32 * k).round() as u32).max(1), + ((ih as f32 * k).round() as u32).max(1), + image::imageops::FilterType::Lanczos3, + ) } else { img }; diff --git a/crates/pdf/src/word.rs b/crates/pdf/src/word.rs index 5e9d18d..8ffed9c 100644 --- a/crates/pdf/src/word.rs +++ b/crates/pdf/src/word.rs @@ -1,383 +1,403 @@ -//! 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, -} - -#[derive(Debug, Clone)] -pub struct WordResult { - pub bytes: Vec, - pub pages: usize, - /// Pages with no text layer (scans) that had no OCR text given. - pub scanned_pages: Vec, -} - -#[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, - 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> { - let mut out: Vec> = Vec::new(); - let mut cur: Vec = 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) -> Vec { - 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), - Image { top: f32, png: Vec, 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, 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) -> Vec { - let mut lines: Vec = 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 = 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]) -> f32 { - let mut counts: HashMap = 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 { - 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 { - 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, 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 = 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 = 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 { - 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::with_capacity(n); - let mut all_lines: Vec> = 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::>().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 = images; - let mut group: Vec = Vec::new(); - let mut groups: Vec = Vec::new(); - let tops: Vec = 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 }) -} +//! 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, +} + +#[derive(Debug, Clone)] +pub struct WordResult { + pub bytes: Vec, + pub pages: usize, + /// Pages with no text layer (scans) that had no OCR text given. + pub scanned_pages: Vec, +} + +#[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, + 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> { + let mut out: Vec> = Vec::new(); + let mut cur: Vec = 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) -> Vec { + 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), + Image { top: f32, png: Vec, 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, 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) -> Vec { + let mut lines: Vec = 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 = 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]) -> f32 { + let mut counts: HashMap = 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 { + 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 { + 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, 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 = 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 = 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 { + 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::with_capacity(n); + let mut all_lines: Vec> = 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::>().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 = images; + let mut group: Vec = Vec::new(); + let mut groups: Vec = Vec::new(); + let tops: Vec = 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 }) +} diff --git a/crates/pdf/tests/compress.rs b/crates/pdf/tests/compress.rs index 0d4c421..61e902b 100644 --- a/crates/pdf/tests/compress.rs +++ b/crates/pdf/tests/compress.rs @@ -40,7 +40,10 @@ fn heavy_pdf(pages: usize, px: u32, jpeg: bool) -> Vec { s }; let im = doc.add_object(stream); - let content = format!("BT /F1 18 Tf 72 780 Td (Invoice page {} of the compress test) Tj ET q 450 0 0 450 72 250 cm /Im0 Do Q", p + 1); + let content = format!( + "BT /F1 18 Tf 72 780 Td (Invoice page {} of the compress test) Tj ET q 450 0 0 450 72 250 cm /Im0 Do Q", + p + 1 + ); let c = doc.add_object(Stream::new(dictionary! {}, content.into_bytes())); let page = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages_id, "Contents" => c, @@ -51,7 +54,7 @@ fn heavy_pdf(pages: usize, px: u32, jpeg: bool) -> Vec { doc.objects.insert( pages_id, Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => pages as i64, - "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}), + "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); diff --git a/crates/pdf/tests/word.rs b/crates/pdf/tests/word.rs index 20c222e..9fcb0ab 100644 --- a/crates/pdf/tests/word.rs +++ b/crates/pdf/tests/word.rs @@ -1,180 +1,217 @@ -//! Day 2 mandatory test 4 (core part): PDF to Word. A PDF with a title, headings, a wrapped paragraph, a table and -//! an image becomes a .docx with every word in reading order, heading styles, one table of 4 rows and the image. -//! LibreOffice (when installed) reads the same text back. "Opens in Scriptum" is checked in the app repository -//! (Scriptum's engine, Prelum, is private): Pictor/apps/desktop/src-tauri/tests/word_scriptum.rs. -mod common; -use common::*; -use lopdf::{Document, Object, Stream, dictionary}; -use std::io::Read; - -const BODY: &[&str] = &[ - "Pictor turns this PDF into a document you can edit.", - "The paragraph wraps over three lines on purpose, so", - "that the converter has to join the lines back together.", -]; - -pub fn report_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"}); - let bold = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica-Bold", "Encoding" => "WinAnsiEncoding"}); - let img = image::RgbImage::from_fn(120, 80, |x, y| image::Rgb([(x * 2) as u8, (y * 3) as u8, 200])); - let mut im = Stream::new( - dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => 120, "Height" => 80, "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8}, - img.into_raw(), - ); - im.compress().unwrap(); - let im = doc.add_object(im); - let mut c1 = String::new(); - c1 += "BT /F2 26 Tf 72 770 Td (Quarterly report) Tj ET\n"; - c1 += "BT /F2 16 Tf 72 730 Td (Summary) Tj ET\n"; - for (i, line) in BODY.iter().enumerate() { - c1 += &format!("BT /F1 11 Tf 72 {} Td ({line}) Tj ET\n", 705 - i as i32 * 14); - } - c1 += "BT /F2 16 Tf 72 640 Td (Figures) Tj ET\n"; - let rows = [["Month", "Sales", "Notes"], ["January", "1200", "cold"], ["February", "1350", "better"], ["March", "1600", "best"]]; - for (r, row) in rows.iter().enumerate() { - for (c, cell) in row.iter().enumerate() { - let font = if r == 0 { "/F2" } else { "/F1" }; - c1 += &format!("BT {font} 11 Tf {} {} Td ({cell}) Tj ET\n", 72 + c * 150, 615 - r as i32 * 18); - } - } - c1 += "q 120 0 0 80 72 420 cm /Im0 Do Q\n"; - c1 += "BT /F1 11 Tf 72 400 Td (A picture of the gradient above.) Tj ET\n"; - let c2 = "BT /F2 16 Tf 72 770 Td (Next steps) Tj ET\nBT /F1 11 Tf 72 745 Td (Page two closes the report.) Tj ET\n"; - let res = || dictionary! {"Font" => dictionary! {"F1" => reg, "F2" => bold}, "XObject" => dictionary! {"Im0" => im}}; - let mut kids = Vec::new(); - for c in [c1, c2.to_string()] { - let cid = doc.add_object(Stream::new(dictionary! {}, c.into_bytes())); - kids.push(Object::Reference(doc.add_object(dictionary! {"Type" => "Page", "Parent" => pages_id, "Contents" => cid, "Resources" => res()}))); - } - doc.objects.insert(pages_id, Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => 2, - "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 -} - -fn part(docx: &[u8], name: &str) -> Option> { - let mut z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap(); - let mut f = z.by_name(name).ok()?; - let mut v = Vec::new(); - f.read_to_end(&mut v).unwrap(); - Some(v) -} - -fn entries(docx: &[u8]) -> Vec { - let z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap(); - z.file_names().map(String::from).collect() -} - -/// The text of word/document.xml: every w:t, a newline per paragraph. -fn text_of(xml: &str) -> String { - let mut out = String::new(); - let mut rest = xml; - while let Some(i) = rest.find('<') { - let tag_end = rest[i..].find('>').map(|j| i + j).unwrap_or(rest.len() - 1); - let tag = &rest[i + 1..tag_end]; - if tag.starts_with("w:t") && !tag.ends_with('/') && (tag == "w:t" || tag.starts_with("w:t ")) { - let body = &rest[tag_end + 1..]; - let end = body.find("").unwrap_or(0); - out.push_str(&body[..end].replace("&", "&").replace("<", "<").replace(">", ">")); - } else if tag == "/w:p" { - out.push('\n'); - } - rest = &rest[tag_end + 1..]; - } - out -} - -fn assert_in_order(text: &str, words: &[&str]) { - let mut at = 0; - for w in words { - match text[at..].find(w) { - Some(i) => at += i + w.len(), - None => panic!("{w:?} missing or out of order in:\n{text}"), - } - } -} - -const ORDER: &[&str] = &[ - "Quarterly report", "Summary", "Pictor turns", "edit.", "wraps over three lines", "join the lines back together.", - "Figures", "Month", "Sales", "Notes", "January", "1200", "cold", "March", "1600", "best", - "A picture of the gradient", "Next steps", "Page two closes the report.", -]; - -#[test] -fn headings_paragraphs_table_and_image_come_out_in_order() { - let r = pictor_pdf::to_word(engine(), &report_pdf(), None, &Default::default()).unwrap(); - assert!(r.scanned_pages.is_empty(), "{:?}", r.scanned_pages); - let xml = String::from_utf8(part(&r.bytes, "word/document.xml").expect("document.xml")).unwrap(); - let text = text_of(&xml); - assert_in_order(&text, ORDER); - // The wrapped paragraph is one paragraph, not three. - assert!(text.contains("so that the converter"), "the wrapped lines were not joined:\n{text}"); - // Headings: the title and the section heads carry heading styles. - assert!(xml.matches("w:pStyle w:val=\"Heading1\"").count() >= 1, "no Heading 1"); - assert!(xml.matches("w:pStyle w:val=\"Heading2\"").count() >= 3, "fewer than 3 Heading 2"); - // One table of 4 rows × 3 cells. - assert_eq!(xml.matches("").count(), 1, "tables"); - assert_eq!(xml.matches(""), "no picture"); - assert!(entries(&r.bytes).iter().any(|e| e.starts_with("word/media/")), "no media part"); - // A page break between the two pages. - assert!(xml.contains("w:type=\"page\""), "no page break"); -} - -#[test] -fn a_page_without_text_is_reported_as_scanned_and_takes_ocr_text() { - // A "scan": one page that is only an image. - let input = pictor_pdf::images_to_pdf( - &[(Vec::new(), image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(800, 1100, image::Rgb([240, 240, 240]))))], - pictor_pdf::PageFit::A4, - 0.0, - ) - .unwrap(); - let r = pictor_pdf::to_word(engine(), &input, None, &Default::default()).unwrap(); - assert_eq!(r.scanned_pages, vec![0]); - let mut opts = pictor_pdf::WordOptions::default(); - opts.ocr.insert(0, "Recognised line one\n\nSecond paragraph from OCR".into()); - let r = pictor_pdf::to_word(engine(), &input, None, &opts).unwrap(); - let text = text_of(&String::from_utf8(part(&r.bytes, "word/document.xml").unwrap()).unwrap()); - assert_in_order(&text, &["Recognised line one", "Second paragraph from OCR"]); -} - -#[test] -fn libreoffice_reads_every_word_in_order() { - let soffice = std::path::Path::new(r"C:\Program Files\LibreOffice\program\soffice.com"); - if !soffice.exists() { - println!("LibreOffice is not installed here: skipped"); - return; - } - let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap(); - let docx = dir.path().join("report.docx"); - std::fs::write(&docx, pictor_pdf::to_word(engine(), &report_pdf(), None, &Default::default()).unwrap().bytes).unwrap(); - let profile = format!("file:///{}", dir.path().join("lo-profile").display().to_string().replace('\\', "/")); - // A fresh LibreOffice profile makes the first start exit with 1 while it restarts itself and still converts: - // wait for the file rather than trusting the exit code (one retry if nothing comes). - let out = dir.path().join("report.txt"); - for _ in 0..2 { - let _ = std::process::Command::new(soffice) - .args([&format!("-env:UserInstallation={profile}"), "--headless", "--invisible", "--norestore", "--nolockcheck"]) - .args(["--convert-to", "txt:Text (encoded):UTF8", "--outdir"]) - .arg(dir.path()) - .arg(&docx) - .status(); - let start = std::time::Instant::now(); - while !out.exists() && start.elapsed() < std::time::Duration::from_secs(60) { - std::thread::sleep(std::time::Duration::from_millis(250)); - } - if out.exists() { - break; - } - } - std::thread::sleep(std::time::Duration::from_millis(500)); - let text = std::fs::read_to_string(&out).expect("LibreOffice converted the .docx"); - assert_in_order(&text, ORDER); -} +//! Day 2 mandatory test 4 (core part): PDF to Word. A PDF with a title, headings, a wrapped paragraph, a table and +//! an image becomes a .docx with every word in reading order, heading styles, one table of 4 rows and the image. +//! LibreOffice (when installed) reads the same text back. "Opens in Scriptum" is checked in the app repository +//! (Scriptum's engine, Prelum, is private): Pictor/apps/desktop/src-tauri/tests/word_scriptum.rs. +mod common; +use common::*; +use lopdf::{Document, Object, Stream, dictionary}; +use std::io::Read; + +const BODY: &[&str] = &[ + "Pictor turns this PDF into a document you can edit.", + "The paragraph wraps over three lines on purpose, so", + "that the converter has to join the lines back together.", +]; + +pub fn report_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"}); + let bold = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica-Bold", "Encoding" => "WinAnsiEncoding"}); + let img = image::RgbImage::from_fn(120, 80, |x, y| image::Rgb([(x * 2) as u8, (y * 3) as u8, 200])); + let mut im = Stream::new( + dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => 120, "Height" => 80, "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8}, + img.into_raw(), + ); + im.compress().unwrap(); + let im = doc.add_object(im); + let mut c1 = String::new(); + c1 += "BT /F2 26 Tf 72 770 Td (Quarterly report) Tj ET\n"; + c1 += "BT /F2 16 Tf 72 730 Td (Summary) Tj ET\n"; + for (i, line) in BODY.iter().enumerate() { + c1 += &format!("BT /F1 11 Tf 72 {} Td ({line}) Tj ET\n", 705 - i as i32 * 14); + } + c1 += "BT /F2 16 Tf 72 640 Td (Figures) Tj ET\n"; + let rows = [ + ["Month", "Sales", "Notes"], + ["January", "1200", "cold"], + ["February", "1350", "better"], + ["March", "1600", "best"], + ]; + for (r, row) in rows.iter().enumerate() { + for (c, cell) in row.iter().enumerate() { + let font = if r == 0 { "/F2" } else { "/F1" }; + c1 += &format!("BT {font} 11 Tf {} {} Td ({cell}) Tj ET\n", 72 + c * 150, 615 - r as i32 * 18); + } + } + c1 += "q 120 0 0 80 72 420 cm /Im0 Do Q\n"; + c1 += "BT /F1 11 Tf 72 400 Td (A picture of the gradient above.) Tj ET\n"; + let c2 = "BT /F2 16 Tf 72 770 Td (Next steps) Tj ET\nBT /F1 11 Tf 72 745 Td (Page two closes the report.) Tj ET\n"; + let res = + || dictionary! {"Font" => dictionary! {"F1" => reg, "F2" => bold}, "XObject" => dictionary! {"Im0" => im}}; + let mut kids = Vec::new(); + for c in [c1, c2.to_string()] { + let cid = doc.add_object(Stream::new(dictionary! {}, c.into_bytes())); + kids.push(Object::Reference(doc.add_object( + dictionary! {"Type" => "Page", "Parent" => pages_id, "Contents" => cid, "Resources" => res()}, + ))); + } + doc.objects.insert( + pages_id, + Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => 2, + "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 +} + +fn part(docx: &[u8], name: &str) -> Option> { + let mut z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap(); + let mut f = z.by_name(name).ok()?; + let mut v = Vec::new(); + f.read_to_end(&mut v).unwrap(); + Some(v) +} + +fn entries(docx: &[u8]) -> Vec { + let z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap(); + z.file_names().map(String::from).collect() +} + +/// The text of word/document.xml: every w:t, a newline per paragraph. +fn text_of(xml: &str) -> String { + let mut out = String::new(); + let mut rest = xml; + while let Some(i) = rest.find('<') { + let tag_end = rest[i..].find('>').map(|j| i + j).unwrap_or(rest.len() - 1); + let tag = &rest[i + 1..tag_end]; + if tag.starts_with("w:t") && !tag.ends_with('/') && (tag == "w:t" || tag.starts_with("w:t ")) { + let body = &rest[tag_end + 1..]; + let end = body.find("").unwrap_or(0); + out.push_str(&body[..end].replace("&", "&").replace("<", "<").replace(">", ">")); + } else if tag == "/w:p" { + out.push('\n'); + } + rest = &rest[tag_end + 1..]; + } + out +} + +fn assert_in_order(text: &str, words: &[&str]) { + let mut at = 0; + for w in words { + match text[at..].find(w) { + Some(i) => at += i + w.len(), + None => panic!("{w:?} missing or out of order in:\n{text}"), + } + } +} + +const ORDER: &[&str] = &[ + "Quarterly report", + "Summary", + "Pictor turns", + "edit.", + "wraps over three lines", + "join the lines back together.", + "Figures", + "Month", + "Sales", + "Notes", + "January", + "1200", + "cold", + "March", + "1600", + "best", + "A picture of the gradient", + "Next steps", + "Page two closes the report.", +]; + +#[test] +fn headings_paragraphs_table_and_image_come_out_in_order() { + let r = pictor_pdf::to_word(engine(), &report_pdf(), None, &Default::default()).unwrap(); + assert!(r.scanned_pages.is_empty(), "{:?}", r.scanned_pages); + let xml = String::from_utf8(part(&r.bytes, "word/document.xml").expect("document.xml")).unwrap(); + let text = text_of(&xml); + assert_in_order(&text, ORDER); + // The wrapped paragraph is one paragraph, not three. + assert!(text.contains("so that the converter"), "the wrapped lines were not joined:\n{text}"); + // Headings: the title and the section heads carry heading styles. + assert!(xml.matches("w:pStyle w:val=\"Heading1\"").count() >= 1, "no Heading 1"); + assert!(xml.matches("w:pStyle w:val=\"Heading2\"").count() >= 3, "fewer than 3 Heading 2"); + // One table of 4 rows × 3 cells. + assert_eq!(xml.matches("").count(), 1, "tables"); + assert_eq!(xml.matches(""), "no picture"); + assert!(entries(&r.bytes).iter().any(|e| e.starts_with("word/media/")), "no media part"); + // A page break between the two pages. + assert!(xml.contains("w:type=\"page\""), "no page break"); +} + +#[test] +fn a_page_without_text_is_reported_as_scanned_and_takes_ocr_text() { + // A "scan": one page that is only an image. + let input = pictor_pdf::images_to_pdf( + &[( + Vec::new(), + image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(800, 1100, image::Rgb([240, 240, 240]))), + )], + pictor_pdf::PageFit::A4, + 0.0, + ) + .unwrap(); + let r = pictor_pdf::to_word(engine(), &input, None, &Default::default()).unwrap(); + assert_eq!(r.scanned_pages, vec![0]); + let mut opts = pictor_pdf::WordOptions::default(); + opts.ocr.insert(0, "Recognised line one\n\nSecond paragraph from OCR".into()); + let r = pictor_pdf::to_word(engine(), &input, None, &opts).unwrap(); + let text = text_of(&String::from_utf8(part(&r.bytes, "word/document.xml").unwrap()).unwrap()); + assert_in_order(&text, &["Recognised line one", "Second paragraph from OCR"]); +} + +#[test] +fn libreoffice_reads_every_word_in_order() { + let soffice = std::path::Path::new(r"C:\Program Files\LibreOffice\program\soffice.com"); + if !soffice.exists() { + println!("LibreOffice is not installed here: skipped"); + return; + } + let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap(); + let docx = dir.path().join("report.docx"); + std::fs::write(&docx, pictor_pdf::to_word(engine(), &report_pdf(), None, &Default::default()).unwrap().bytes) + .unwrap(); + let profile = format!("file:///{}", dir.path().join("lo-profile").display().to_string().replace('\\', "/")); + // A fresh LibreOffice profile makes the first start exit with 1 while it restarts itself and still converts: + // wait for the file rather than trusting the exit code (one retry if nothing comes). + let out = dir.path().join("report.txt"); + for _ in 0..2 { + let _ = std::process::Command::new(soffice) + .args([ + &format!("-env:UserInstallation={profile}"), + "--headless", + "--invisible", + "--norestore", + "--nolockcheck", + ]) + .args(["--convert-to", "txt:Text (encoded):UTF8", "--outdir"]) + .arg(dir.path()) + .arg(&docx) + .status(); + let start = std::time::Instant::now(); + while !out.exists() && start.elapsed() < std::time::Duration::from_secs(60) { + std::thread::sleep(std::time::Duration::from_millis(250)); + } + if out.exists() { + break; + } + } + std::thread::sleep(std::time::Duration::from_millis(500)); + let text = std::fs::read_to_string(&out).expect("LibreOffice converted the .docx"); + assert_in_order(&text, ORDER); +} diff --git a/crates/worker/src/ops.rs b/crates/worker/src/ops.rs index b61b2a1..102ae9d 100644 --- a/crates/worker/src/ops.rs +++ b/crates/worker/src/ops.rs @@ -1,500 +1,501 @@ -//! The worker's operations. Each takes the request's JSON arguments and returns JSON or an [`OpError`]. -//! Files are read and written here (the paths come from the app); open PDFs stay in memory as sessions. -use crate::OpError; -use base64::Engine as _; -use pictor_pdf::{Edits, Engine, PageFit, PageSpec}; -use pictor_raster::{Format, Limits}; -use serde::Deserialize; -use serde_json::{Value, json}; -use std::collections::HashMap; -use std::path::{Path, PathBuf}; - -/// Largest outside file the worker reads at all. -pub const MAX_FILE_BYTES: u64 = 1 << 30; - -pub struct State { - engine: Option<&'static Engine>, - pdfium_dir: Option, - docs: HashMap, - next_doc: u32, - debug: bool, -} - -struct Doc { - bytes: Vec, - password: Option, -} - -impl State { - pub fn new(pdfium_dir: Option, debug: bool) -> State { - State { engine: None, pdfium_dir, docs: HashMap::new(), next_doc: 1, debug } - } - - fn engine(&mut self) -> Result<&'static Engine, OpError> { - if let Some(e) = self.engine { - return Ok(e); - } - let e = Engine::load(self.pdfium_dir.as_deref())?; - self.engine = Some(e); - Ok(e) - } - - fn doc(&self, id: u32) -> Result<&Doc, OpError> { - self.docs.get(&id).ok_or_else(|| OpError::new("not_open", "That PDF is no longer open. Open it again.")) - } -} - -fn b64(bytes: &[u8]) -> String { - base64::engine::general_purpose::STANDARD.encode(bytes) -} - -fn read_file(path: &str) -> Result, OpError> { - let meta = std::fs::metadata(path).map_err(|e| OpError::new("io", format!("Pictor could not open {path}: {e}")))?; - if !meta.is_file() { - return Err(OpError::new("io", format!("{path} is not a file."))); - } - if meta.len() > MAX_FILE_BYTES { - return Err(OpError::new("too_large", "This file is larger than 1 GB, which Pictor does not open.")); - } - std::fs::read(path).map_err(|e| OpError::new("io", format!("Pictor could not read {path}: {e}"))) -} - -fn args Deserialize<'de>>(v: Value) -> Result { - serde_json::from_value(v).map_err(|e| OpError::new("invalid", format!("bad request: {e}"))) -} - -#[derive(Deserialize)] -#[serde(rename_all = "snake_case")] -enum SaveMode { - /// A new file; refuses to replace one. - New, - /// Replace the file, keeping a .bak. - Overwrite, -} - -fn write_out(path: &str, bytes: &[u8], mode: SaveMode) -> Result { - let p = Path::new(path); - match mode { - SaveMode::New => { - pictor_save::save_new(p, bytes)?; - Ok(json!({"path": path, "bytes": bytes.len()})) - } - SaveMode::Overwrite => { - let bak = pictor_save::save_overwrite(p, bytes)?; - Ok(json!({"path": path, "bytes": bytes.len(), "bak": bak.exists().then(|| bak.display().to_string())})) - } - } -} - -fn png(img: &image::DynamicImage) -> Result, OpError> { - let mut out = Vec::new(); - image::codecs::png::PngEncoder::new_with_quality( - &mut out, - image::codecs::png::CompressionType::Fast, - image::codecs::png::FilterType::Sub, - ) - .write_image(img.as_bytes(), img.width(), img.height(), img.color().into()) - .map_err(|e| OpError::new("io", e.to_string()))?; - Ok(out) -} - -use image::ImageEncoder; - -pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result { - match op { - // ---- PDF sessions ------------------------------------------------------------------------------------- - "pdf.open" => { - #[derive(Deserialize)] - struct A { - path: String, - password: Option, - } - let a: A = args(a)?; - let bytes = read_file(&a.path)?; - let engine = state.engine()?; - let info = pictor_pdf::info(engine, &bytes, a.password.as_deref())?; - let id = state.next_doc; - state.next_doc += 1; - state.docs.insert(id, Doc { bytes, password: a.password }); - Ok(json!({"doc": id, "info": info})) - } - "pdf.close" => { - #[derive(Deserialize)] - struct A { - doc: u32, - } - let a: A = args(a)?; - state.docs.remove(&a.doc); - Ok(json!({})) - } - "pdf.render" => { - #[derive(Deserialize)] - struct A { - doc: u32, - page: usize, - width: u32, - } - let a: A = args(a)?; - let engine = state.engine()?; - let d = state.doc(a.doc)?; - let img = pictor_pdf::render_page(engine, &d.bytes, d.password.as_deref(), a.page, a.width)?; - Ok(json!({"png": b64(&png(&img)?), "width": img.width(), "height": img.height()})) - } - "pdf.text" => { - #[derive(Deserialize)] - struct A { - doc: u32, - } - let a: A = args(a)?; - let engine = state.engine()?; - let d = state.doc(a.doc)?; - Ok(json!({"pages": pictor_pdf::extract_text(engine, &d.bytes, d.password.as_deref())?})) - } - "pdf.search" => { - #[derive(Deserialize)] - struct A { - doc: u32, - query: String, - } - let a: A = args(a)?; - let engine = state.engine()?; - let d = state.doc(a.doc)?; - Ok(json!({"hits": pictor_pdf::search(engine, &d.bytes, d.password.as_deref(), &a.query, 2000)?})) - } - "pdf.form" => { - #[derive(Deserialize)] - struct A { - doc: u32, - } - let a: A = args(a)?; - let engine = state.engine()?; - let d = state.doc(a.doc)?; - Ok(json!({"fields": pictor_pdf::form_fields(engine, &d.bytes, d.password.as_deref())?})) - } - "pdf.save" => { - #[derive(Deserialize)] - struct A { - doc: u32, - edits: Edits, - output: String, - mode: SaveMode, - } - let a: A = args(a)?; - let engine = state.engine()?; - let d = state.doc(a.doc)?; - let applied = pictor_pdf::apply(engine, &d.bytes, d.password.as_deref(), &a.edits)?; - let mut out = write_out(&a.output, &applied.bytes, a.mode)?; - out["warnings"] = json!(applied.warnings); - Ok(out) - } - "pdf.extract" => { - #[derive(Deserialize)] - struct A { - doc: u32, - pages: Vec, - output: String, - } - let a: A = args(a)?; - let d = state.doc(a.doc)?; - let specs: Vec = a.pages.iter().map(|&index| PageSpec::Existing { index, rotate: 0 }).collect(); - let bytes = pictor_pdf::reorganise(&d.bytes, d.password.as_deref(), &specs)?; - write_out(&a.output, &bytes, SaveMode::New) - } - "pdf.to_images" => { - #[derive(Deserialize)] - struct A { - doc: u32, - pages: Vec, - dpi: u32, - format: String, - /// Output path pattern with `{n}` for the 1-based page number. - output: String, - } - let a: A = args(a)?; - let engine = state.engine()?; - let d = state.doc(a.doc)?; - let format = Format::from_name(&a.format).ok_or_else(|| OpError::new("invalid", "Choose PNG or JPG."))?; - let mut paths = Vec::new(); - for &p in &a.pages { - let img = pictor_pdf::pages_to_images(engine, &d.bytes, d.password.as_deref(), &[p], a.dpi)?.remove(0); - let bytes = pictor_raster::encode(&img, format, &Default::default())?; - let path = a.output.replace("{n}", &(p + 1).to_string()); - pictor_save::save_new(Path::new(&path), &bytes)?; - paths.push(path); - } - Ok(json!({"paths": paths})) - } - "pdf.compress" => { - #[derive(Deserialize)] - struct A { - doc: u32, - preset: pictor_pdf::CompressPreset, - output: String, - } - let a: A = args(a)?; - let d = state.doc(a.doc)?; - let r = pictor_pdf::compress(&d.bytes, d.password.as_deref(), a.preset)?; - let mut out = write_out(&a.output, &r.bytes, SaveMode::New)?; - out["before"] = json!(r.before); - out["after"] = json!(r.after); - out["images_changed"] = json!(r.images_changed); - out["warnings"] = json!(r.warnings); - Ok(out) - } - "pdf.to_word" => { - #[derive(Deserialize)] - struct A { - doc: u32, - output: String, - /// Recognised text for scanned pages: {"0": "text", …}. - #[serde(default)] - ocr: std::collections::HashMap, - } - let a: A = args(a)?; - let engine = state.engine()?; - let d = state.doc(a.doc)?; - let r = pictor_pdf::to_word(engine, &d.bytes, d.password.as_deref(), &pictor_pdf::WordOptions { ocr: a.ocr })?; - let mut out = write_out(&a.output, &r.bytes, SaveMode::New)?; - out["pages"] = json!(r.pages); - out["scanned_pages"] = json!(r.scanned_pages); - Ok(out) - } - "pdf.page_png" => { - // A page as a PNG file (for OCR of a scanned page by Fundamentum's Lector, through the app). - #[derive(Deserialize)] - struct A { - doc: u32, - page: usize, - dpi: u32, - output: String, - } - let a: A = args(a)?; - let engine = state.engine()?; - let d = state.doc(a.doc)?; - let img = pictor_pdf::pages_to_images(engine, &d.bytes, d.password.as_deref(), &[a.page], a.dpi)?.remove(0); - let bytes = png(&img)?; - write_out(&a.output, &bytes, SaveMode::Overwrite) - } - // ---- PDF files ---------------------------------------------------------------------------------------- - "pdf.merge" => { - #[derive(Deserialize)] - struct Input { - path: String, - password: Option, - } - #[derive(Deserialize)] - struct A { - inputs: Vec, - output: String, - } - let a: A = args(a)?; - let engine = state.engine()?; - let files: Vec<(Vec, Option)> = a - .inputs - .iter() - .map(|i| read_file(&i.path).map(|b| (b, i.password.clone()))) - .collect::>()?; - let refs: Vec<(&[u8], Option<&str>)> = files.iter().map(|(b, p)| (b.as_slice(), p.as_deref())).collect(); - let bytes = pictor_pdf::merge(engine, &refs)?; - write_out(&a.output, &bytes, SaveMode::New) - } - "pdf.split" => { - #[derive(Deserialize)] - struct A { - path: String, - password: Option, - ranges: String, - /// Output path pattern with `{n}` for the part number. - output: String, - } - let a: A = args(a)?; - let engine = state.engine()?; - let bytes = read_file(&a.path)?; - let pages = pictor_pdf::page_sizes(engine, &bytes, a.password.as_deref())?.len(); - let ranges = pictor_pdf::parse_ranges(&a.ranges, pages)?; - let parts = pictor_pdf::split(&bytes, a.password.as_deref(), &ranges)?; - let mut paths = Vec::new(); - for (i, part) in parts.iter().enumerate() { - let path = a.output.replace("{n}", &(i + 1).to_string()); - pictor_save::save_new(Path::new(&path), part)?; - paths.push(path); - } - Ok(json!({"paths": paths})) - } - "pdf.from_images" => { - #[derive(Deserialize)] - struct A { - inputs: Vec, - output: String, - fit: PageFit, - #[serde(default)] - margin: f32, - } - let a: A = args(a)?; - let limits = Limits::default(); - let mut images = Vec::new(); - for p in &a.inputs { - let bytes = read_file(p)?; - let img = pictor_raster::decode(&bytes, &limits)?; - images.push((bytes, img)); - } - let bytes = pictor_pdf::images_to_pdf(&images, a.fit, a.margin)?; - write_out(&a.output, &bytes, SaveMode::New) - } - // ---- Images ------------------------------------------------------------------------------------------- - "image.probe" => { - #[derive(Deserialize)] - struct A { - path: String, - } - let a: A = args(a)?; - let bytes = read_file(&a.path)?; - let p = pictor_raster::probe(&bytes, &Limits::default())?; - Ok(json!({"format": p.format, "width": p.width, "height": p.height, "has_alpha": p.has_alpha, - "frames": p.frames, "bytes": bytes.len()})) - } - "image.thumb" => { - #[derive(Deserialize)] - struct A { - path: String, - max: u32, - } - let a: A = args(a)?; - let bytes = read_file(&a.path)?; - let img = pictor_raster::decode(&bytes, &Limits::default())?; - let (w, h) = (img.width(), img.height()); - let t = - pictor_raster::resize(&img, pictor_raster::Fit::LongEdge(a.max.clamp(16, 2048)), &Limits::default())?; - Ok(json!({"png": b64(&png(&t)?), "width": w, "height": h})) - } - "image.convert" => { - #[derive(Deserialize)] - struct A { - input: String, - output: String, - format: String, - #[serde(default)] - quality: Option, - #[serde(default)] - crop: Option, - #[serde(default)] - rotate: Option, - #[serde(default)] - resize: Option, - #[serde(default)] - preset: Option, - #[serde(default)] - target_bytes: Option, - #[serde(default)] - overwrite: bool, - } - let a: A = args(a)?; - let limits = Limits::default(); - let src = read_file(&a.input)?; - let src_format = pictor_raster::probe(&src, &limits)?.format; - let mut img = pictor_raster::decode(&src, &limits)?; - if let Some(c) = a.crop { - img = pictor_raster::crop(&img, c)?; - } - if let Some(r) = a.rotate { - img = pictor_raster::rotate(&img, r); - } - if let Some(f) = a.resize { - img = pictor_raster::resize(&img, f, &limits)?; - } - let format = - Format::from_name(&a.format).ok_or_else(|| OpError::new("invalid", "Choose an output format."))?; - let (bytes, format) = if let Some(target) = a.target_bytes { - let c = pictor_raster::compress_to(&img, format, target, &limits)?; - (c.bytes, c.format) - } else if let Some(p) = a.preset { - let _ = src_format; - pictor_raster::apply_preset(&img, format, p)? - } else { - let mut o = pictor_raster::EncodeOptions::default(); - if let Some(q) = a.quality { - o.jpeg_quality = q.clamp(10, 100); - } - (pictor_raster::encode(&img, format, &o)?, format) - }; - let mut out = write_out(&a.output, &bytes, if a.overwrite { SaveMode::Overwrite } else { SaveMode::New })?; - out["format"] = json!(format); - out["width"] = json!(img.width()); - out["height"] = json!(img.height()); - Ok(out) - } - "image.heif_support" => Ok(json!({"support": pictor_raster::heif_support()})), - // ---- Metadata ----------------------------------------------------------------------------------------- - "meta.read" => { - #[derive(Deserialize)] - struct A { - path: String, - } - let a: A = args(a)?; - let bytes = read_file(&a.path)?; - let report = pictor_meta::read(&bytes)?; - let groups: Vec<_> = report.groups().into_iter().map(|g| json!({"group": g, "label": g.label()})).collect(); - Ok(json!({"report": report, "groups": groups})) - } - "meta.strip" => { - #[derive(Deserialize)] - struct A { - input: String, - output: String, - #[serde(default)] - overwrite: bool, - } - let a: A = args(a)?; - let bytes = read_file(&a.input)?; - let stripped = pictor_meta::strip(&bytes)?; - let mut out = - write_out(&a.output, &stripped.bytes, if a.overwrite { SaveMode::Overwrite } else { SaveMode::New })?; - out["removed"] = json!(stripped.removed); - Ok(out) - } - // ---- QR ----------------------------------------------------------------------------------------------- - "qr.render" => { - #[derive(Deserialize)] - struct A { - payload: pictor_qr::Payload, - #[serde(default)] - level: pictor_qr::Level, - style: pictor_qr::Style, - #[serde(default)] - logo: Option, - } - let a: A = args(a)?; - let text = pictor_qr::payload_string(&a.payload)?; - let logo_bytes = match &a.logo { - Some(p) => Some(read_file(p)?), - None => None, - }; - let logo = match &logo_bytes { - Some(b) => Some(pictor_raster::decode(b, &Limits::default())?.to_rgba8()), - None => None, - }; - let r = pictor_qr::render_rgba(&text, a.level, &a.style, logo.as_ref())?; - let png = pictor_qr::encode_png(&r.image)?; - let logo_png = match &logo { - Some(l) => Some(pictor_qr::encode_png(l)?), - None => None, - }; - let svg = pictor_qr::render_svg(&text, a.level, &a.style, logo_png.as_deref())?; - Ok(json!({"png": b64(&png), "svg": svg, "level_used": r.level_used, "size": r.size_px, "text": text})) - } - // ---- Tests only (PICTOR_WORKER_DEBUG=1) --------------------------------------------------------------- - "debug.crash" if state.debug => std::process::abort(), - "debug.sleep" if state.debug => { - std::thread::sleep(std::time::Duration::from_secs(a["secs"].as_u64().unwrap_or(60))); - Ok(json!({})) - } - "debug.alloc" if state.debug => { - let mb = a["mb"].as_u64().unwrap_or(4096) as usize; - let mut v: Vec = Vec::new(); - v.try_reserve_exact(mb << 20).map_err(|_| OpError::new("too_large", "out of memory"))?; - v.resize(mb << 20, 1); - Ok(json!({"len": v.len()})) - } - _ => Err(OpError::new("invalid", format!("unknown operation {op}"))), - } -} +//! The worker's operations. Each takes the request's JSON arguments and returns JSON or an [`OpError`]. +//! Files are read and written here (the paths come from the app); open PDFs stay in memory as sessions. +use crate::OpError; +use base64::Engine as _; +use pictor_pdf::{Edits, Engine, PageFit, PageSpec}; +use pictor_raster::{Format, Limits}; +use serde::Deserialize; +use serde_json::{Value, json}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +/// Largest outside file the worker reads at all. +pub const MAX_FILE_BYTES: u64 = 1 << 30; + +pub struct State { + engine: Option<&'static Engine>, + pdfium_dir: Option, + docs: HashMap, + next_doc: u32, + debug: bool, +} + +struct Doc { + bytes: Vec, + password: Option, +} + +impl State { + pub fn new(pdfium_dir: Option, debug: bool) -> State { + State { engine: None, pdfium_dir, docs: HashMap::new(), next_doc: 1, debug } + } + + fn engine(&mut self) -> Result<&'static Engine, OpError> { + if let Some(e) = self.engine { + return Ok(e); + } + let e = Engine::load(self.pdfium_dir.as_deref())?; + self.engine = Some(e); + Ok(e) + } + + fn doc(&self, id: u32) -> Result<&Doc, OpError> { + self.docs.get(&id).ok_or_else(|| OpError::new("not_open", "That PDF is no longer open. Open it again.")) + } +} + +fn b64(bytes: &[u8]) -> String { + base64::engine::general_purpose::STANDARD.encode(bytes) +} + +fn read_file(path: &str) -> Result, OpError> { + let meta = std::fs::metadata(path).map_err(|e| OpError::new("io", format!("Pictor could not open {path}: {e}")))?; + if !meta.is_file() { + return Err(OpError::new("io", format!("{path} is not a file."))); + } + if meta.len() > MAX_FILE_BYTES { + return Err(OpError::new("too_large", "This file is larger than 1 GB, which Pictor does not open.")); + } + std::fs::read(path).map_err(|e| OpError::new("io", format!("Pictor could not read {path}: {e}"))) +} + +fn args Deserialize<'de>>(v: Value) -> Result { + serde_json::from_value(v).map_err(|e| OpError::new("invalid", format!("bad request: {e}"))) +} + +#[derive(Deserialize)] +#[serde(rename_all = "snake_case")] +enum SaveMode { + /// A new file; refuses to replace one. + New, + /// Replace the file, keeping a .bak. + Overwrite, +} + +fn write_out(path: &str, bytes: &[u8], mode: SaveMode) -> Result { + let p = Path::new(path); + match mode { + SaveMode::New => { + pictor_save::save_new(p, bytes)?; + Ok(json!({"path": path, "bytes": bytes.len()})) + } + SaveMode::Overwrite => { + let bak = pictor_save::save_overwrite(p, bytes)?; + Ok(json!({"path": path, "bytes": bytes.len(), "bak": bak.exists().then(|| bak.display().to_string())})) + } + } +} + +fn png(img: &image::DynamicImage) -> Result, OpError> { + let mut out = Vec::new(); + image::codecs::png::PngEncoder::new_with_quality( + &mut out, + image::codecs::png::CompressionType::Fast, + image::codecs::png::FilterType::Sub, + ) + .write_image(img.as_bytes(), img.width(), img.height(), img.color().into()) + .map_err(|e| OpError::new("io", e.to_string()))?; + Ok(out) +} + +use image::ImageEncoder; + +pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result { + match op { + // ---- PDF sessions ------------------------------------------------------------------------------------- + "pdf.open" => { + #[derive(Deserialize)] + struct A { + path: String, + password: Option, + } + let a: A = args(a)?; + let bytes = read_file(&a.path)?; + let engine = state.engine()?; + let info = pictor_pdf::info(engine, &bytes, a.password.as_deref())?; + let id = state.next_doc; + state.next_doc += 1; + state.docs.insert(id, Doc { bytes, password: a.password }); + Ok(json!({"doc": id, "info": info})) + } + "pdf.close" => { + #[derive(Deserialize)] + struct A { + doc: u32, + } + let a: A = args(a)?; + state.docs.remove(&a.doc); + Ok(json!({})) + } + "pdf.render" => { + #[derive(Deserialize)] + struct A { + doc: u32, + page: usize, + width: u32, + } + let a: A = args(a)?; + let engine = state.engine()?; + let d = state.doc(a.doc)?; + let img = pictor_pdf::render_page(engine, &d.bytes, d.password.as_deref(), a.page, a.width)?; + Ok(json!({"png": b64(&png(&img)?), "width": img.width(), "height": img.height()})) + } + "pdf.text" => { + #[derive(Deserialize)] + struct A { + doc: u32, + } + let a: A = args(a)?; + let engine = state.engine()?; + let d = state.doc(a.doc)?; + Ok(json!({"pages": pictor_pdf::extract_text(engine, &d.bytes, d.password.as_deref())?})) + } + "pdf.search" => { + #[derive(Deserialize)] + struct A { + doc: u32, + query: String, + } + let a: A = args(a)?; + let engine = state.engine()?; + let d = state.doc(a.doc)?; + Ok(json!({"hits": pictor_pdf::search(engine, &d.bytes, d.password.as_deref(), &a.query, 2000)?})) + } + "pdf.form" => { + #[derive(Deserialize)] + struct A { + doc: u32, + } + let a: A = args(a)?; + let engine = state.engine()?; + let d = state.doc(a.doc)?; + Ok(json!({"fields": pictor_pdf::form_fields(engine, &d.bytes, d.password.as_deref())?})) + } + "pdf.save" => { + #[derive(Deserialize)] + struct A { + doc: u32, + edits: Edits, + output: String, + mode: SaveMode, + } + let a: A = args(a)?; + let engine = state.engine()?; + let d = state.doc(a.doc)?; + let applied = pictor_pdf::apply(engine, &d.bytes, d.password.as_deref(), &a.edits)?; + let mut out = write_out(&a.output, &applied.bytes, a.mode)?; + out["warnings"] = json!(applied.warnings); + Ok(out) + } + "pdf.extract" => { + #[derive(Deserialize)] + struct A { + doc: u32, + pages: Vec, + output: String, + } + let a: A = args(a)?; + let d = state.doc(a.doc)?; + let specs: Vec = a.pages.iter().map(|&index| PageSpec::Existing { index, rotate: 0 }).collect(); + let bytes = pictor_pdf::reorganise(&d.bytes, d.password.as_deref(), &specs)?; + write_out(&a.output, &bytes, SaveMode::New) + } + "pdf.to_images" => { + #[derive(Deserialize)] + struct A { + doc: u32, + pages: Vec, + dpi: u32, + format: String, + /// Output path pattern with `{n}` for the 1-based page number. + output: String, + } + let a: A = args(a)?; + let engine = state.engine()?; + let d = state.doc(a.doc)?; + let format = Format::from_name(&a.format).ok_or_else(|| OpError::new("invalid", "Choose PNG or JPG."))?; + let mut paths = Vec::new(); + for &p in &a.pages { + let img = pictor_pdf::pages_to_images(engine, &d.bytes, d.password.as_deref(), &[p], a.dpi)?.remove(0); + let bytes = pictor_raster::encode(&img, format, &Default::default())?; + let path = a.output.replace("{n}", &(p + 1).to_string()); + pictor_save::save_new(Path::new(&path), &bytes)?; + paths.push(path); + } + Ok(json!({"paths": paths})) + } + "pdf.compress" => { + #[derive(Deserialize)] + struct A { + doc: u32, + preset: pictor_pdf::CompressPreset, + output: String, + } + let a: A = args(a)?; + let d = state.doc(a.doc)?; + let r = pictor_pdf::compress(&d.bytes, d.password.as_deref(), a.preset)?; + let mut out = write_out(&a.output, &r.bytes, SaveMode::New)?; + out["before"] = json!(r.before); + out["after"] = json!(r.after); + out["images_changed"] = json!(r.images_changed); + out["warnings"] = json!(r.warnings); + Ok(out) + } + "pdf.to_word" => { + #[derive(Deserialize)] + struct A { + doc: u32, + output: String, + /// Recognised text for scanned pages: {"0": "text", …}. + #[serde(default)] + ocr: std::collections::HashMap, + } + let a: A = args(a)?; + let engine = state.engine()?; + let d = state.doc(a.doc)?; + let r = + pictor_pdf::to_word(engine, &d.bytes, d.password.as_deref(), &pictor_pdf::WordOptions { ocr: a.ocr })?; + let mut out = write_out(&a.output, &r.bytes, SaveMode::New)?; + out["pages"] = json!(r.pages); + out["scanned_pages"] = json!(r.scanned_pages); + Ok(out) + } + "pdf.page_png" => { + // A page as a PNG file (for OCR of a scanned page by Fundamentum's Lector, through the app). + #[derive(Deserialize)] + struct A { + doc: u32, + page: usize, + dpi: u32, + output: String, + } + let a: A = args(a)?; + let engine = state.engine()?; + let d = state.doc(a.doc)?; + let img = pictor_pdf::pages_to_images(engine, &d.bytes, d.password.as_deref(), &[a.page], a.dpi)?.remove(0); + let bytes = png(&img)?; + write_out(&a.output, &bytes, SaveMode::Overwrite) + } + // ---- PDF files ---------------------------------------------------------------------------------------- + "pdf.merge" => { + #[derive(Deserialize)] + struct Input { + path: String, + password: Option, + } + #[derive(Deserialize)] + struct A { + inputs: Vec, + output: String, + } + let a: A = args(a)?; + let engine = state.engine()?; + let files: Vec<(Vec, Option)> = a + .inputs + .iter() + .map(|i| read_file(&i.path).map(|b| (b, i.password.clone()))) + .collect::>()?; + let refs: Vec<(&[u8], Option<&str>)> = files.iter().map(|(b, p)| (b.as_slice(), p.as_deref())).collect(); + let bytes = pictor_pdf::merge(engine, &refs)?; + write_out(&a.output, &bytes, SaveMode::New) + } + "pdf.split" => { + #[derive(Deserialize)] + struct A { + path: String, + password: Option, + ranges: String, + /// Output path pattern with `{n}` for the part number. + output: String, + } + let a: A = args(a)?; + let engine = state.engine()?; + let bytes = read_file(&a.path)?; + let pages = pictor_pdf::page_sizes(engine, &bytes, a.password.as_deref())?.len(); + let ranges = pictor_pdf::parse_ranges(&a.ranges, pages)?; + let parts = pictor_pdf::split(&bytes, a.password.as_deref(), &ranges)?; + let mut paths = Vec::new(); + for (i, part) in parts.iter().enumerate() { + let path = a.output.replace("{n}", &(i + 1).to_string()); + pictor_save::save_new(Path::new(&path), part)?; + paths.push(path); + } + Ok(json!({"paths": paths})) + } + "pdf.from_images" => { + #[derive(Deserialize)] + struct A { + inputs: Vec, + output: String, + fit: PageFit, + #[serde(default)] + margin: f32, + } + let a: A = args(a)?; + let limits = Limits::default(); + let mut images = Vec::new(); + for p in &a.inputs { + let bytes = read_file(p)?; + let img = pictor_raster::decode(&bytes, &limits)?; + images.push((bytes, img)); + } + let bytes = pictor_pdf::images_to_pdf(&images, a.fit, a.margin)?; + write_out(&a.output, &bytes, SaveMode::New) + } + // ---- Images ------------------------------------------------------------------------------------------- + "image.probe" => { + #[derive(Deserialize)] + struct A { + path: String, + } + let a: A = args(a)?; + let bytes = read_file(&a.path)?; + let p = pictor_raster::probe(&bytes, &Limits::default())?; + Ok(json!({"format": p.format, "width": p.width, "height": p.height, "has_alpha": p.has_alpha, + "frames": p.frames, "bytes": bytes.len()})) + } + "image.thumb" => { + #[derive(Deserialize)] + struct A { + path: String, + max: u32, + } + let a: A = args(a)?; + let bytes = read_file(&a.path)?; + let img = pictor_raster::decode(&bytes, &Limits::default())?; + let (w, h) = (img.width(), img.height()); + let t = + pictor_raster::resize(&img, pictor_raster::Fit::LongEdge(a.max.clamp(16, 2048)), &Limits::default())?; + Ok(json!({"png": b64(&png(&t)?), "width": w, "height": h})) + } + "image.convert" => { + #[derive(Deserialize)] + struct A { + input: String, + output: String, + format: String, + #[serde(default)] + quality: Option, + #[serde(default)] + crop: Option, + #[serde(default)] + rotate: Option, + #[serde(default)] + resize: Option, + #[serde(default)] + preset: Option, + #[serde(default)] + target_bytes: Option, + #[serde(default)] + overwrite: bool, + } + let a: A = args(a)?; + let limits = Limits::default(); + let src = read_file(&a.input)?; + let src_format = pictor_raster::probe(&src, &limits)?.format; + let mut img = pictor_raster::decode(&src, &limits)?; + if let Some(c) = a.crop { + img = pictor_raster::crop(&img, c)?; + } + if let Some(r) = a.rotate { + img = pictor_raster::rotate(&img, r); + } + if let Some(f) = a.resize { + img = pictor_raster::resize(&img, f, &limits)?; + } + let format = + Format::from_name(&a.format).ok_or_else(|| OpError::new("invalid", "Choose an output format."))?; + let (bytes, format) = if let Some(target) = a.target_bytes { + let c = pictor_raster::compress_to(&img, format, target, &limits)?; + (c.bytes, c.format) + } else if let Some(p) = a.preset { + let _ = src_format; + pictor_raster::apply_preset(&img, format, p)? + } else { + let mut o = pictor_raster::EncodeOptions::default(); + if let Some(q) = a.quality { + o.jpeg_quality = q.clamp(10, 100); + } + (pictor_raster::encode(&img, format, &o)?, format) + }; + let mut out = write_out(&a.output, &bytes, if a.overwrite { SaveMode::Overwrite } else { SaveMode::New })?; + out["format"] = json!(format); + out["width"] = json!(img.width()); + out["height"] = json!(img.height()); + Ok(out) + } + "image.heif_support" => Ok(json!({"support": pictor_raster::heif_support()})), + // ---- Metadata ----------------------------------------------------------------------------------------- + "meta.read" => { + #[derive(Deserialize)] + struct A { + path: String, + } + let a: A = args(a)?; + let bytes = read_file(&a.path)?; + let report = pictor_meta::read(&bytes)?; + let groups: Vec<_> = report.groups().into_iter().map(|g| json!({"group": g, "label": g.label()})).collect(); + Ok(json!({"report": report, "groups": groups})) + } + "meta.strip" => { + #[derive(Deserialize)] + struct A { + input: String, + output: String, + #[serde(default)] + overwrite: bool, + } + let a: A = args(a)?; + let bytes = read_file(&a.input)?; + let stripped = pictor_meta::strip(&bytes)?; + let mut out = + write_out(&a.output, &stripped.bytes, if a.overwrite { SaveMode::Overwrite } else { SaveMode::New })?; + out["removed"] = json!(stripped.removed); + Ok(out) + } + // ---- QR ----------------------------------------------------------------------------------------------- + "qr.render" => { + #[derive(Deserialize)] + struct A { + payload: pictor_qr::Payload, + #[serde(default)] + level: pictor_qr::Level, + style: pictor_qr::Style, + #[serde(default)] + logo: Option, + } + let a: A = args(a)?; + let text = pictor_qr::payload_string(&a.payload)?; + let logo_bytes = match &a.logo { + Some(p) => Some(read_file(p)?), + None => None, + }; + let logo = match &logo_bytes { + Some(b) => Some(pictor_raster::decode(b, &Limits::default())?.to_rgba8()), + None => None, + }; + let r = pictor_qr::render_rgba(&text, a.level, &a.style, logo.as_ref())?; + let png = pictor_qr::encode_png(&r.image)?; + let logo_png = match &logo { + Some(l) => Some(pictor_qr::encode_png(l)?), + None => None, + }; + let svg = pictor_qr::render_svg(&text, a.level, &a.style, logo_png.as_deref())?; + Ok(json!({"png": b64(&png), "svg": svg, "level_used": r.level_used, "size": r.size_px, "text": text})) + } + // ---- Tests only (PICTOR_WORKER_DEBUG=1) --------------------------------------------------------------- + "debug.crash" if state.debug => std::process::abort(), + "debug.sleep" if state.debug => { + std::thread::sleep(std::time::Duration::from_secs(a["secs"].as_u64().unwrap_or(60))); + Ok(json!({})) + } + "debug.alloc" if state.debug => { + let mb = a["mb"].as_u64().unwrap_or(4096) as usize; + let mut v: Vec = Vec::new(); + v.try_reserve_exact(mb << 20).map_err(|_| OpError::new("too_large", "out of memory"))?; + v.resize(mb << 20, 1); + Ok(json!({"len": v.len()})) + } + _ => Err(OpError::new("invalid", format!("unknown operation {op}"))), + } +}