[pdf] Word: PDF to .docx (headings, paragraphs, tables, images, OCR text for scans); worker ops compress, to_word, page_png
This commit is contained in:
@@ -14,7 +14,10 @@ lopdf.workspace = true
|
||||
pdfium-render.workspace = true
|
||||
pictor-meta.workspace = true
|
||||
getrandom.workspace = true
|
||||
docx-rs.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
flate2.workspace = true
|
||||
serde_json.workspace = true
|
||||
zip = { version = "8.6.0", default-features = false, features = ["deflate"] }
|
||||
tempfile.workspace = true
|
||||
|
||||
@@ -17,6 +17,7 @@ mod pages;
|
||||
mod reader;
|
||||
mod redact;
|
||||
mod security;
|
||||
mod word;
|
||||
|
||||
pub use compress::{CompressPreset, Compressed, EMAIL_TARGET, compress};
|
||||
pub use edit::*;
|
||||
@@ -27,6 +28,7 @@ pub use pages::*;
|
||||
pub use reader::*;
|
||||
pub use redact::{RedactOptions, Redacted, Redaction, redact};
|
||||
pub use security::{is_encrypted, protect, unlock};
|
||||
pub use word::{WordOptions, WordResult, to_word};
|
||||
|
||||
/// lopdf loading with the caps Pictor uses everywhere (a stream may decompress to at most 256 MiB).
|
||||
pub(crate) fn lopdf_load(bytes: &[u8], password: Option<&str>) -> Result<lopdf::Document, PdfError> {
|
||||
|
||||
@@ -0,0 +1,383 @@
|
||||
//! 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 })
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
//! 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<u8> {
|
||||
let mut doc = Document::with_version("1.7");
|
||||
let pages_id = doc.new_object_id();
|
||||
let reg = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", "Encoding" => "WinAnsiEncoding"});
|
||||
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<Vec<u8>> {
|
||||
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<String> {
|
||||
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("</w:t>").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("<w:tbl>").count(), 1, "tables");
|
||||
assert_eq!(xml.matches("<w:tr").count() - xml.matches("<w:trPr").count(), 4, "rows");
|
||||
// The image is embedded.
|
||||
assert!(xml.contains("<w:drawing>"), "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);
|
||||
}
|
||||
Reference in New Issue
Block a user