[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:
@@ -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