[repo] Format

This commit is contained in:
2026-11-17 00:57:06 +01:00
parent f1f0234ffb
commit 6efc835d24
5 changed files with 1139 additions and 1068 deletions
+13 -3
View File
@@ -42,7 +42,9 @@ struct Step {
fn steps(preset: CompressPreset) -> &'static [Step] { fn steps(preset: CompressPreset) -> &'static [Step] {
match preset { 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::Web => &[Step { dpi: 150.0, quality: 72 }],
CompressPreset::Print => &[Step { dpi: 300.0, quality: 86 }], CompressPreset::Print => &[Step { dpi: 300.0, quality: 86 }],
} }
@@ -195,7 +197,11 @@ fn recompress(doc: &Document, s: &Stream, max_px: u32, quality: u8) -> Option<St
i i
} }
b"FlateDecode" | b"" => { b"FlateDecode" | b"" => {
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; let need = (w as usize) * (h as usize) * n as usize;
if raw.len() < need { if raw.len() < need {
return None; return None;
@@ -210,7 +216,11 @@ fn recompress(doc: &Document, s: &Stream, max_px: u32, quality: u8) -> Option<St
let (iw, ih) = img.dimensions(); let (iw, ih) = img.dimensions();
let img = if iw.max(ih) > max_px + max_px / 10 { let img = if iw.max(ih) > max_px + max_px / 10 {
let k = max_px as f32 / iw.max(ih) as f32; 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 { } else {
img img
}; };
+31 -11
View File
@@ -9,9 +9,7 @@
//! A page with (almost) no text but an image is a scan: it is listed in `scanned_pages`, and text recognised //! 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. //! elsewhere (Fundamentum's Lector, through the app) can be passed back in `WordOptions::ocr` for those pages.
use crate::{Engine, PdfError}; use crate::{Engine, PdfError};
use docx_rs::{ use docx_rs::{BreakType, Docx, Paragraph, Pic, Run, RunFonts, Style, StyleType, Table, TableCell, TableRow};
BreakType, Docx, Paragraph, Pic, Run, RunFonts, Style, StyleType, Table, TableCell, TableRow,
};
use pdfium_render::prelude::*; use pdfium_render::prelude::*;
use std::collections::HashMap; use std::collections::HashMap;
@@ -228,7 +226,8 @@ fn blocks(lines: Vec<Line>, body: f32, mut out: Docx) -> Docx {
let mut j = i + 1; let mut j = i + 1;
while j < lines.len() { while j < lines.len() {
let s = lines[j].segments(); 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 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; let close = lines[j - 1].bottom - lines[j].top < 2.5 * lines[j].size;
if !fits || !close { if !fits || !close {
break; break;
@@ -242,7 +241,11 @@ fn blocks(lines: Vec<Line>, body: f32, mut out: Docx) -> Docx {
.map(|r| { .map(|r| {
TableRow::new( TableRow::new(
r.iter() r.iter()
.map(|cell| TableCell::new().add_paragraph(runs(cell).into_iter().fold(Paragraph::new(), |p, r| p.add_run(r)))) .map(|cell| {
TableCell::new().add_paragraph(
runs(cell).into_iter().fold(Paragraph::new(), |p, r| p.add_run(r)),
)
})
.collect(), .collect(),
) )
}) })
@@ -262,7 +265,10 @@ fn blocks(lines: Vec<Line>, body: f32, mut out: Docx) -> Docx {
let same_size = (next.size - first.size).abs() < 0.6; let same_size = (next.size - first.size).abs() < 0.6;
let same_left = (next.left() - first.left()).abs() < 1.5 * first.size; let same_left = (next.left() - first.left()).abs() < 1.5 * first.size;
let close = prev.bottom - next.top < 1.0 * 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() { if !(same_size && same_left && close)
|| next.segments().len() > 1
|| heading_level(&first.chars, first.size, body).is_some()
{
break; break;
} }
// A hyphen at a line end joins the word; else a space. // A hyphen at a line end joins the word; else a space.
@@ -296,7 +302,12 @@ fn styles(doc: Docx) -> Docx {
} }
/// Converts a PDF to a .docx. /// Converts a PDF to a .docx.
pub fn to_word(engine: &Engine, bytes: &[u8], password: Option<&str>, opts: &WordOptions) -> Result<WordResult, PdfError> { pub fn to_word(
engine: &Engine,
bytes: &[u8],
password: Option<&str>,
opts: &WordOptions,
) -> Result<WordResult, PdfError> {
let doc = engine.open(bytes, password)?; let doc = engine.open(bytes, password)?;
let n = doc.pages().len() as usize; let n = doc.pages().len() as usize;
if n > 2000 { if n > 2000 {
@@ -320,7 +331,11 @@ pub fn to_word(engine: &Engine, bytes: &[u8], password: Option<&str>, opts: &Wor
} }
images += 1; images += 1;
// Keep pictures a sensible size in the document (at most 1600 px on the long side). // 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 raw = if raw.width().max(raw.height()) > 1600 {
raw.resize(1600, 1600, image::imageops::FilterType::Triangle)
} else {
raw
};
let mut png = Vec::new(); let mut png = Vec::new();
if raw.to_rgb8().write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() { if raw.to_rgb8().write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() {
continue; continue;
@@ -345,7 +360,9 @@ pub fn to_word(engine: &Engine, bytes: &[u8], password: Option<&str>, opts: &Wor
docx = docx.add_paragraph(Paragraph::new().add_run(Run::new().add_break(BreakType::Page))); docx = docx.add_paragraph(Paragraph::new().add_run(Run::new().add_break(BreakType::Page)));
} }
if let Some(t) = opts.ocr.get(&i) { 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()) { 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))); docx = docx.add_paragraph(Paragraph::new().add_run(Run::new().add_text(para)));
} }
} }
@@ -355,7 +372,9 @@ pub fn to_word(engine: &Engine, bytes: &[u8], password: Option<&str>, opts: &Wor
let mut groups: Vec<Item> = Vec::new(); let mut groups: Vec<Item> = Vec::new();
let tops: Vec<f32> = items.iter().map(item_top).collect(); let tops: Vec<f32> = items.iter().map(item_top).collect();
for l in page_lines { 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() { 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))); groups.push(Item::Lines(std::mem::take(&mut group)));
} }
group.push(l); group.push(l);
@@ -371,7 +390,8 @@ pub fn to_word(engine: &Engine, bytes: &[u8], password: Option<&str>, opts: &Wor
Item::Image { png, w_px, h_px, w_pt, h_pt, .. } => { 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. // Size in EMU (1 pt = 12 700 EMU), at most 6.5 inches wide.
let k = (468.0 / w_pt).min(1.0); 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); 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))); docx = docx.add_paragraph(Paragraph::new().add_run(Run::new().add_image(pic)));
} }
} }
+4 -1
View File
@@ -40,7 +40,10 @@ fn heavy_pdf(pages: usize, px: u32, jpeg: bool) -> Vec<u8> {
s s
}; };
let im = doc.add_object(stream); 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 c = doc.add_object(Stream::new(dictionary! {}, content.into_bytes()));
let page = doc.add_object(dictionary! { let page = doc.add_object(dictionary! {
"Type" => "Page", "Parent" => pages_id, "Contents" => c, "Type" => "Page", "Parent" => pages_id, "Contents" => c,
+48 -11
View File
@@ -32,7 +32,12 @@ pub fn report_pdf() -> Vec<u8> {
c1 += &format!("BT /F1 11 Tf 72 {} Td ({line}) Tj ET\n", 705 - i as i32 * 14); 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"; 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"]]; let rows = [
["Month", "Sales", "Notes"],
["January", "1200", "cold"],
["February", "1350", "better"],
["March", "1600", "best"],
];
for (r, row) in rows.iter().enumerate() { for (r, row) in rows.iter().enumerate() {
for (c, cell) in row.iter().enumerate() { for (c, cell) in row.iter().enumerate() {
let font = if r == 0 { "/F2" } else { "/F1" }; let font = if r == 0 { "/F2" } else { "/F1" };
@@ -42,14 +47,20 @@ pub fn report_pdf() -> Vec<u8> {
c1 += "q 120 0 0 80 72 420 cm /Im0 Do Q\n"; 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"; 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 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 res =
|| dictionary! {"Font" => dictionary! {"F1" => reg, "F2" => bold}, "XObject" => dictionary! {"Im0" => im}};
let mut kids = Vec::new(); let mut kids = Vec::new();
for c in [c1, c2.to_string()] { for c in [c1, c2.to_string()] {
let cid = doc.add_object(Stream::new(dictionary! {}, c.into_bytes())); 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()}))); 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, doc.objects.insert(
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]})); 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}); let cat = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id});
doc.trailer.set("Root", cat); doc.trailer.set("Root", cat);
let mut out = Vec::new(); let mut out = Vec::new();
@@ -100,9 +111,25 @@ fn assert_in_order(text: &str, words: &[&str]) {
} }
const ORDER: &[&str] = &[ const ORDER: &[&str] = &[
"Quarterly report", "Summary", "Pictor turns", "edit.", "wraps over three lines", "join the lines back together.", "Quarterly report",
"Figures", "Month", "Sales", "Notes", "January", "1200", "cold", "March", "1600", "best", "Summary",
"A picture of the gradient", "Next steps", "Page two closes the report.", "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] #[test]
@@ -131,7 +158,10 @@ fn headings_paragraphs_table_and_image_come_out_in_order() {
fn a_page_without_text_is_reported_as_scanned_and_takes_ocr_text() { fn a_page_without_text_is_reported_as_scanned_and_takes_ocr_text() {
// A "scan": one page that is only an image. // A "scan": one page that is only an image.
let input = pictor_pdf::images_to_pdf( let input = pictor_pdf::images_to_pdf(
&[(Vec::new(), image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(800, 1100, image::Rgb([240, 240, 240]))))], &[(
Vec::new(),
image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(800, 1100, image::Rgb([240, 240, 240]))),
)],
pictor_pdf::PageFit::A4, pictor_pdf::PageFit::A4,
0.0, 0.0,
) )
@@ -154,14 +184,21 @@ fn libreoffice_reads_every_word_in_order() {
} }
let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap(); let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap();
let docx = dir.path().join("report.docx"); let docx = dir.path().join("report.docx");
std::fs::write(&docx, pictor_pdf::to_word(engine(), &report_pdf(), None, &Default::default()).unwrap().bytes).unwrap(); 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('\\', "/")); 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: // 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). // wait for the file rather than trusting the exit code (one retry if nothing comes).
let out = dir.path().join("report.txt"); let out = dir.path().join("report.txt");
for _ in 0..2 { for _ in 0..2 {
let _ = std::process::Command::new(soffice) let _ = std::process::Command::new(soffice)
.args([&format!("-env:UserInstallation={profile}"), "--headless", "--invisible", "--norestore", "--nolockcheck"]) .args([
&format!("-env:UserInstallation={profile}"),
"--headless",
"--invisible",
"--norestore",
"--nolockcheck",
])
.args(["--convert-to", "txt:Text (encoded):UTF8", "--outdir"]) .args(["--convert-to", "txt:Text (encoded):UTF8", "--outdir"])
.arg(dir.path()) .arg(dir.path())
.arg(&docx) .arg(&docx)
+2 -1
View File
@@ -253,7 +253,8 @@ pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result<Value, OpError>
let a: A = args(a)?; let a: A = args(a)?;
let engine = state.engine()?; let engine = state.engine()?;
let d = state.doc(a.doc)?; 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 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)?; let mut out = write_out(&a.output, &r.bytes, SaveMode::New)?;
out["pages"] = json!(r.pages); out["pages"] = json!(r.pages);
out["scanned_pages"] = json!(r.scanned_pages); out["scanned_pages"] = json!(r.scanned_pages);