306 lines
13 KiB
Rust
306 lines
13 KiB
Rust
//! 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);
|
||
}
|
||
|
||
/// A PDF written like many real ones (Word's own export among them): no space glyphs between words, only gaps, and
|
||
/// a word split over two text objects where the line was justified ("Dichotomou" | "s"). pdfium invents a
|
||
/// zero-width space at such a split; the .docx must not break the word there, and must still space the words.
|
||
fn no_space_glyphs_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"});
|
||
// Helvetica advance widths (AFM, /1000 em) for the pieces, so each piece starts exactly where the last ended.
|
||
let w = |s: &str| -> f32 {
|
||
s.chars()
|
||
.map(|c| match c {
|
||
'D' => 722.0,
|
||
'I' | 'i' | 'l' | 'j' => 222.0,
|
||
'c' | 'k' | 's' | 'v' | 'x' | 'y' | 'z' => 500.0,
|
||
'f' | 't' => 278.0,
|
||
'm' => 833.0,
|
||
'r' => 333.0,
|
||
'w' => 722.0,
|
||
'S' | 'H' | 'A' | 'E' => 667.0,
|
||
_ => 556.0,
|
||
})
|
||
.sum::<f32>()
|
||
* 16.0
|
||
/ 1000.0
|
||
};
|
||
let mut c = String::new();
|
||
// Line 1: words as separate objects, a 4 pt gap between them, "Dichotomous" split in two touching objects.
|
||
let mut x = 72.0;
|
||
for (piece, gap_after) in [
|
||
("Highly", 4.0),
|
||
("Accurate", 4.0),
|
||
("Dichotomou", 0.0),
|
||
("s", 4.0),
|
||
("Image", 4.0),
|
||
("Segmentat", 0.0),
|
||
("ion", 0.0),
|
||
] {
|
||
c += &format!("BT /F1 16 Tf {x:.2} 700 Td ({piece}) Tj ET\n");
|
||
x += w(piece) + gap_after;
|
||
}
|
||
// Line 2: the same inside one text object, moved with Td (the other common way).
|
||
c += "BT /F1 16 Tf 72 670 Td (evalu) Tj ";
|
||
c += &format!("{:.2} 0 Td (ation) Tj {:.2} 0 Td (of) Tj ET\n", w("evalu"), w("ation") + 4.0);
|
||
// Line 3, as WPS Writer writes it: the page flipped (y down), each word a text object with a flipped Tm at
|
||
// 319 pt × 0.05, and every glyph its own Tj moved by TD in glyph widths.
|
||
c += "q 1 0 0 -1 0 842 cm
|
||
";
|
||
let mut x = 72.0;
|
||
for word in ["Dichotomous", "Image", "Segmentation", "Dataset"] {
|
||
c += &format!("q BT /F1 319 Tf 0.05 0 0 -0.05 {x:.3} 230 Tm ");
|
||
for (i, ch) in word.chars().enumerate() {
|
||
if i > 0 {
|
||
let prev = word.chars().nth(i - 1).unwrap().to_string();
|
||
c += &format!("{:.3} -0 TD ", w(&prev) / 16.0 * 319.0);
|
||
}
|
||
c += &format!("({ch}) Tj ");
|
||
}
|
||
c += "ET Q
|
||
";
|
||
x += w(word) / 16.0 * 319.0 * 0.05 + 4.0;
|
||
}
|
||
c += "Q
|
||
";
|
||
let cid = doc.add_object(Stream::new(dictionary! {}, c.into_bytes()));
|
||
let page = doc.add_object(dictionary! {"Type" => "Page", "Parent" => pages_id, "Contents" => cid,
|
||
"Resources" => dictionary! {"Font" => dictionary! {"F1" => reg}}});
|
||
doc.objects.insert(
|
||
pages_id,
|
||
Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => vec![Object::Reference(page)], "Count" => 1,
|
||
"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
|
||
}
|
||
|
||
#[test]
|
||
fn words_split_over_text_objects_stay_whole() {
|
||
let r = pictor_pdf::to_word(engine(), &no_space_glyphs_pdf(), None, &Default::default()).unwrap();
|
||
let text = text_of(&String::from_utf8(part(&r.bytes, "word/document.xml").unwrap()).unwrap());
|
||
let flat = text.split_whitespace().collect::<Vec<_>>().join(" ");
|
||
assert!(flat.contains("Highly Accurate Dichotomous Image Segmentation"), "{flat:?}");
|
||
assert!(flat.contains("evaluation of"), "{flat:?}");
|
||
assert!(flat.contains("Dichotomous Image Segmentation Dataset"), "{flat:?}");
|
||
}
|