[repo] Format
This commit is contained in:
@@ -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
|
||||||
};
|
};
|
||||||
|
|||||||
+403
-383
@@ -1,383 +1,403 @@
|
|||||||
//! PDF to Word (Day 2): editable text with its structure, not a pixel copy ("Layout is approximate").
|
//! 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:
|
//! 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
|
//! 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
|
//! 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
|
//! 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.
|
//! 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
|
//! 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 std::collections::HashMap;
|
||||||
use pdfium_render::prelude::*;
|
|
||||||
use std::collections::HashMap;
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct WordOptions {
|
||||||
#[derive(Debug, Clone, Default)]
|
/// Recognised text for scanned pages (0-based page → text; blank lines separate paragraphs).
|
||||||
pub struct WordOptions {
|
pub ocr: HashMap<usize, String>,
|
||||||
/// Recognised text for scanned pages (0-based page → text; blank lines separate paragraphs).
|
}
|
||||||
pub ocr: HashMap<usize, String>,
|
|
||||||
}
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct WordResult {
|
||||||
#[derive(Debug, Clone)]
|
pub bytes: Vec<u8>,
|
||||||
pub struct WordResult {
|
pub pages: usize,
|
||||||
pub bytes: Vec<u8>,
|
/// Pages with no text layer (scans) that had no OCR text given.
|
||||||
pub pages: usize,
|
pub scanned_pages: Vec<usize>,
|
||||||
/// Pages with no text layer (scans) that had no OCR text given.
|
}
|
||||||
pub scanned_pages: Vec<usize>,
|
|
||||||
}
|
#[derive(Clone, Debug)]
|
||||||
|
struct Ch {
|
||||||
#[derive(Clone, Debug)]
|
c: char,
|
||||||
struct Ch {
|
x0: f32,
|
||||||
c: char,
|
x1: f32,
|
||||||
x0: f32,
|
y0: f32,
|
||||||
x1: f32,
|
y1: f32,
|
||||||
y0: f32,
|
size: f32,
|
||||||
y1: f32,
|
bold: bool,
|
||||||
size: f32,
|
italic: bool,
|
||||||
bold: bool,
|
}
|
||||||
italic: bool,
|
|
||||||
}
|
#[derive(Debug, Clone)]
|
||||||
|
struct Line {
|
||||||
#[derive(Debug, Clone)]
|
chars: Vec<Ch>,
|
||||||
struct Line {
|
top: f32,
|
||||||
chars: Vec<Ch>,
|
bottom: f32,
|
||||||
top: f32,
|
size: f32,
|
||||||
bottom: f32,
|
}
|
||||||
size: f32,
|
|
||||||
}
|
impl Line {
|
||||||
|
fn left(&self) -> f32 {
|
||||||
impl Line {
|
self.chars.first().map(|c| c.x0).unwrap_or(0.0)
|
||||||
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>> {
|
||||||
/// Pieces of the line separated by a gap wider than 2.2 × the font size.
|
let mut out: Vec<Vec<Ch>> = Vec::new();
|
||||||
fn segments(&self) -> Vec<Vec<Ch>> {
|
let mut cur: Vec<Ch> = Vec::new();
|
||||||
let mut out: Vec<Vec<Ch>> = Vec::new();
|
for ch in &self.chars {
|
||||||
let mut cur: Vec<Ch> = Vec::new();
|
if let Some(prev) = cur.iter().rev().find(|c| !c.c.is_whitespace())
|
||||||
for ch in &self.chars {
|
&& ch.x0 - prev.x1 > 2.2 * self.size.max(1.0)
|
||||||
if let Some(prev) = cur.iter().rev().find(|c| !c.c.is_whitespace())
|
&& !ch.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));
|
||||||
{
|
}
|
||||||
out.push(std::mem::take(&mut cur));
|
cur.push(ch.clone());
|
||||||
}
|
}
|
||||||
cur.push(ch.clone());
|
if !cur.is_empty() {
|
||||||
}
|
out.push(cur);
|
||||||
if !cur.is_empty() {
|
}
|
||||||
out.push(cur);
|
out.into_iter().map(trim).filter(|s| !s.is_empty()).collect()
|
||||||
}
|
}
|
||||||
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()) {
|
||||||
fn trim(mut v: Vec<Ch>) -> Vec<Ch> {
|
v.remove(0);
|
||||||
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();
|
||||||
while v.last().is_some_and(|c| c.c.is_whitespace()) {
|
}
|
||||||
v.pop();
|
v
|
||||||
}
|
}
|
||||||
v
|
|
||||||
}
|
enum Item {
|
||||||
|
Lines(Vec<Line>),
|
||||||
enum Item {
|
Image { top: f32, png: Vec<u8>, w_px: u32, h_px: u32, w_pt: f32, h_pt: f32 },
|
||||||
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 {
|
||||||
fn item_top(i: &Item) -> f32 {
|
Item::Lines(l) => l.first().map(|l| l.top).unwrap_or(0.0),
|
||||||
match i {
|
Item::Image { top, .. } => *top,
|
||||||
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)?;
|
||||||
fn page_chars(page: &PdfPage) -> Result<Vec<Ch>, PdfError> {
|
let mut out = Vec::new();
|
||||||
let text = page.text().map_err(PdfError::from_pdfium)?;
|
for ch in text.chars().iter() {
|
||||||
let mut out = Vec::new();
|
let Some(c) = ch.unicode_char() else { continue };
|
||||||
for ch in text.chars().iter() {
|
if c == '\r' || c == '\n' || c == '\u{2}' || c == '\u{fffe}' {
|
||||||
let Some(c) = ch.unicode_char() else { continue };
|
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 Ok(b) = ch.loose_bounds() else { continue };
|
let weight = matches!(ch.font_weight(), Some(w) if matches!(w, PdfFontWeight::Weight600 | PdfFontWeight::Weight700Bold | PdfFontWeight::Weight800 | PdfFontWeight::Weight900 | PdfFontWeight::Custom(600..)));
|
||||||
let name = ch.font_name().to_ascii_lowercase();
|
out.push(Ch {
|
||||||
let weight = matches!(ch.font_weight(), Some(w) if matches!(w, PdfFontWeight::Weight600 | PdfFontWeight::Weight700Bold | PdfFontWeight::Weight800 | PdfFontWeight::Weight900 | PdfFontWeight::Custom(600..)));
|
c,
|
||||||
out.push(Ch {
|
x0: b.left().value,
|
||||||
c,
|
x1: b.right().value,
|
||||||
x0: b.left().value,
|
y0: b.bottom().value,
|
||||||
x1: b.right().value,
|
y1: b.top().value,
|
||||||
y0: b.bottom().value,
|
size: ch.scaled_font_size().value.max(1.0),
|
||||||
y1: b.top().value,
|
bold: weight || name.contains("bold") || name.contains("black") || name.contains("heavy"),
|
||||||
size: ch.scaled_font_size().value.max(1.0),
|
italic: ch.font_is_italic() || name.contains("italic") || name.contains("oblique"),
|
||||||
bold: weight || name.contains("bold") || name.contains("black") || name.contains("heavy"),
|
});
|
||||||
italic: ch.font_is_italic() || name.contains("italic") || name.contains("oblique"),
|
}
|
||||||
});
|
Ok(out)
|
||||||
}
|
}
|
||||||
Ok(out)
|
|
||||||
}
|
/// Characters in pdfium's order → lines, top to bottom (PDF y grows upwards).
|
||||||
|
fn lines(chars: Vec<Ch>) -> Vec<Line> {
|
||||||
/// Characters in pdfium's order → lines, top to bottom (PDF y grows upwards).
|
let mut lines: Vec<Line> = Vec::new();
|
||||||
fn lines(chars: Vec<Ch>) -> Vec<Line> {
|
for ch in chars {
|
||||||
let mut lines: Vec<Line> = Vec::new();
|
let mid = (ch.y0 + ch.y1) / 2.0;
|
||||||
for ch in chars {
|
let found = lines.iter_mut().rev().take(3).find(|l| {
|
||||||
let mid = (ch.y0 + ch.y1) / 2.0;
|
let lmid = (l.top + l.bottom) / 2.0;
|
||||||
let found = lines.iter_mut().rev().take(3).find(|l| {
|
(mid - lmid).abs() < 0.45 * l.size.max(ch.size)
|
||||||
let lmid = (l.top + l.bottom) / 2.0;
|
});
|
||||||
(mid - lmid).abs() < 0.45 * l.size.max(ch.size)
|
match found {
|
||||||
});
|
Some(l) => {
|
||||||
match found {
|
l.top = l.top.max(ch.y1);
|
||||||
Some(l) => {
|
l.bottom = l.bottom.min(ch.y0);
|
||||||
l.top = l.top.max(ch.y1);
|
if !ch.c.is_whitespace() {
|
||||||
l.bottom = l.bottom.min(ch.y0);
|
l.size = l.size.max(ch.size);
|
||||||
if !ch.c.is_whitespace() {
|
}
|
||||||
l.size = l.size.max(ch.size);
|
l.chars.push(ch);
|
||||||
}
|
}
|
||||||
l.chars.push(ch);
|
None => {
|
||||||
}
|
let size = ch.size;
|
||||||
None => {
|
lines.push(Line { top: ch.y1, bottom: ch.y0, size, chars: vec![ch] });
|
||||||
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));
|
||||||
for l in &mut lines {
|
// pdfium adds spaces of its own between words; make sure words that touch get one too.
|
||||||
l.chars.sort_by(|a, b| a.x0.total_cmp(&b.x0));
|
let mut with_spaces: Vec<Ch> = Vec::with_capacity(l.chars.len());
|
||||||
// pdfium adds spaces of its own between words; make sure words that touch get one too.
|
for ch in std::mem::take(&mut l.chars) {
|
||||||
let mut with_spaces: Vec<Ch> = Vec::with_capacity(l.chars.len());
|
if let Some(prev) = with_spaces.last()
|
||||||
for ch in std::mem::take(&mut l.chars) {
|
&& !prev.c.is_whitespace()
|
||||||
if let Some(prev) = with_spaces.last()
|
&& !ch.c.is_whitespace()
|
||||||
&& !prev.c.is_whitespace()
|
&& ch.x0 - prev.x1 > 0.18 * ch.size
|
||||||
&& !ch.c.is_whitespace()
|
{
|
||||||
&& ch.x0 - prev.x1 > 0.18 * ch.size
|
let mut sp = prev.clone();
|
||||||
{
|
sp.c = ' ';
|
||||||
let mut sp = prev.clone();
|
with_spaces.push(sp);
|
||||||
sp.c = ' ';
|
}
|
||||||
with_spaces.push(sp);
|
if ch.c.is_whitespace() && with_spaces.last().is_some_and(|p| p.c.is_whitespace()) {
|
||||||
}
|
continue;
|
||||||
if ch.c.is_whitespace() && with_spaces.last().is_some_and(|p| p.c.is_whitespace()) {
|
}
|
||||||
continue;
|
with_spaces.push(ch);
|
||||||
}
|
}
|
||||||
with_spaces.push(ch);
|
l.chars = with_spaces;
|
||||||
}
|
}
|
||||||
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.retain(|l| l.chars.iter().any(|c| !c.c.is_whitespace()));
|
lines
|
||||||
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();
|
||||||
fn body_size(all: &[Vec<Line>]) -> f32 {
|
for l in all.iter().flatten() {
|
||||||
let mut counts: HashMap<u32, usize> = HashMap::new();
|
*counts.entry((l.size * 2.0).round() as u32).or_default() += l.chars.len();
|
||||||
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)
|
||||||
}
|
}
|
||||||
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();
|
||||||
fn heading_level(chars: &[Ch], size: f32, body: f32) -> Option<usize> {
|
let bold = chars.iter().filter(|c| !c.c.is_whitespace()).all(|c| c.bold);
|
||||||
let len = chars.iter().filter(|c| !c.c.is_whitespace()).count();
|
if size >= body * 1.8 {
|
||||||
let bold = chars.iter().filter(|c| !c.c.is_whitespace()).all(|c| c.bold);
|
Some(1)
|
||||||
if size >= body * 1.8 {
|
} else if size >= body * 1.25 {
|
||||||
Some(1)
|
Some(2)
|
||||||
} else if size >= body * 1.25 {
|
} else if bold && len <= 80 && size >= body * 1.05 {
|
||||||
Some(2)
|
Some(3)
|
||||||
} else if bold && len <= 80 && size >= body * 1.05 {
|
} else {
|
||||||
Some(3)
|
None
|
||||||
} else {
|
}
|
||||||
None
|
}
|
||||||
}
|
|
||||||
}
|
fn runs(chars: &[Ch]) -> Vec<Run> {
|
||||||
|
let mut out = Vec::new();
|
||||||
fn runs(chars: &[Ch]) -> Vec<Run> {
|
let mut i = 0;
|
||||||
let mut out = Vec::new();
|
while i < chars.len() {
|
||||||
let mut i = 0;
|
let (b, it, sz) = (chars[i].bold, chars[i].italic, (chars[i].size * 2.0).round() as usize);
|
||||||
while i < chars.len() {
|
let mut j = i;
|
||||||
let (b, it, sz) = (chars[i].bold, chars[i].italic, (chars[i].size * 2.0).round() as usize);
|
let mut s = String::new();
|
||||||
let mut j = i;
|
while j < chars.len() && chars[j].bold == b && chars[j].italic == it {
|
||||||
let mut s = String::new();
|
s.push(chars[j].c);
|
||||||
while j < chars.len() && chars[j].bold == b && chars[j].italic == it {
|
j += 1;
|
||||||
s.push(chars[j].c);
|
}
|
||||||
j += 1;
|
let mut r = Run::new().add_text(s).size(sz.clamp(8, 144));
|
||||||
}
|
if b {
|
||||||
let mut r = Run::new().add_text(s).size(sz.clamp(8, 144));
|
r = r.bold();
|
||||||
if b {
|
}
|
||||||
r = r.bold();
|
if it {
|
||||||
}
|
r = r.italic();
|
||||||
if it {
|
}
|
||||||
r = r.italic();
|
out.push(r);
|
||||||
}
|
i = j;
|
||||||
out.push(r);
|
}
|
||||||
i = j;
|
out
|
||||||
}
|
}
|
||||||
out
|
|
||||||
}
|
/// One page's lines → paragraphs and tables, in order.
|
||||||
|
fn blocks(lines: Vec<Line>, body: f32, mut out: Docx) -> Docx {
|
||||||
/// One page's lines → paragraphs and tables, in order.
|
let mut i = 0;
|
||||||
fn blocks(lines: Vec<Line>, body: f32, mut out: Docx) -> Docx {
|
while i < lines.len() {
|
||||||
let mut i = 0;
|
// A table: two or more consecutive lines with ≥ 2 segments whose starts line up.
|
||||||
while i < lines.len() {
|
let segs = lines[i].segments();
|
||||||
// A table: two or more consecutive lines with ≥ 2 segments whose starts line up.
|
if segs.len() >= 2 {
|
||||||
let segs = lines[i].segments();
|
let cols: Vec<f32> = segs.iter().map(|s| s[0].x0).collect();
|
||||||
if segs.len() >= 2 {
|
let mut rows = vec![segs];
|
||||||
let cols: Vec<f32> = segs.iter().map(|s| s[0].x0).collect();
|
let mut j = i + 1;
|
||||||
let mut rows = vec![segs];
|
while j < lines.len() {
|
||||||
let mut j = i + 1;
|
let s = lines[j].segments();
|
||||||
while j < lines.len() {
|
let fits = s.len() == cols.len()
|
||||||
let s = lines[j].segments();
|
&& 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;
|
}
|
||||||
}
|
rows.push(s);
|
||||||
rows.push(s);
|
j += 1;
|
||||||
j += 1;
|
}
|
||||||
}
|
if rows.len() >= 2 {
|
||||||
if rows.len() >= 2 {
|
let table = Table::new(
|
||||||
let table = Table::new(
|
rows.iter()
|
||||||
rows.iter()
|
.map(|r| {
|
||||||
.map(|r| {
|
TableRow::new(
|
||||||
TableRow::new(
|
r.iter()
|
||||||
r.iter()
|
.map(|cell| {
|
||||||
.map(|cell| TableCell::new().add_paragraph(runs(cell).into_iter().fold(Paragraph::new(), |p, r| p.add_run(r))))
|
TableCell::new().add_paragraph(
|
||||||
.collect(),
|
runs(cell).into_iter().fold(Paragraph::new(), |p, r| p.add_run(r)),
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
);
|
)
|
||||||
out = out.add_table(table);
|
})
|
||||||
i = j;
|
.collect(),
|
||||||
continue;
|
);
|
||||||
}
|
out = out.add_table(table);
|
||||||
}
|
i = j;
|
||||||
// A paragraph: join following lines of the same size and left edge that sit close below.
|
continue;
|
||||||
let first = &lines[i];
|
}
|
||||||
let mut chars: Vec<Ch> = first.chars.clone();
|
}
|
||||||
let mut j = i + 1;
|
// A paragraph: join following lines of the same size and left edge that sit close below.
|
||||||
while j < lines.len() {
|
let first = &lines[i];
|
||||||
let (prev, next) = (&lines[j - 1], &lines[j]);
|
let mut chars: Vec<Ch> = first.chars.clone();
|
||||||
let same_size = (next.size - first.size).abs() < 0.6;
|
let mut j = i + 1;
|
||||||
let same_left = (next.left() - first.left()).abs() < 1.5 * first.size;
|
while j < lines.len() {
|
||||||
let close = prev.bottom - next.top < 1.0 * first.size;
|
let (prev, next) = (&lines[j - 1], &lines[j]);
|
||||||
if !(same_size && same_left && close) || next.segments().len() > 1 || heading_level(&first.chars, first.size, body).is_some() {
|
let same_size = (next.size - first.size).abs() < 0.6;
|
||||||
break;
|
let same_left = (next.left() - first.left()).abs() < 1.5 * first.size;
|
||||||
}
|
let close = prev.bottom - next.top < 1.0 * first.size;
|
||||||
// A hyphen at a line end joins the word; else a space.
|
if !(same_size && same_left && close)
|
||||||
if chars.last().is_some_and(|c| c.c == '-' || c.c == '\u{ad}') {
|
|| next.segments().len() > 1
|
||||||
chars.pop();
|
|| heading_level(&first.chars, first.size, body).is_some()
|
||||||
} else {
|
{
|
||||||
let mut sp = chars.last().cloned().expect("non-empty");
|
break;
|
||||||
sp.c = ' ';
|
}
|
||||||
chars.push(sp);
|
// 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.extend(next.chars.iter().cloned());
|
chars.pop();
|
||||||
j += 1;
|
} else {
|
||||||
}
|
let mut sp = chars.last().cloned().expect("non-empty");
|
||||||
let chars = trim(chars);
|
sp.c = ' ';
|
||||||
let mut p = runs(&chars).into_iter().fold(Paragraph::new(), |p, r| p.add_run(r));
|
chars.push(sp);
|
||||||
if let Some(level) = heading_level(&chars, first.size, body) {
|
}
|
||||||
p = p.style(&format!("Heading{level}"));
|
chars.extend(next.chars.iter().cloned());
|
||||||
}
|
j += 1;
|
||||||
out = out.add_paragraph(p);
|
}
|
||||||
i = j;
|
let chars = trim(chars);
|
||||||
}
|
let mut p = runs(&chars).into_iter().fold(Paragraph::new(), |p, r| p.add_run(r));
|
||||||
out
|
if let Some(level) = heading_level(&chars, first.size, body) {
|
||||||
}
|
p = p.style(&format!("Heading{level}"));
|
||||||
|
}
|
||||||
fn styles(doc: Docx) -> Docx {
|
out = out.add_paragraph(p);
|
||||||
doc.add_style(Style::new("Heading1", StyleType::Paragraph).name("heading 1").size(40).bold().outline_lvl(0))
|
i = j;
|
||||||
.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))
|
out
|
||||||
.default_fonts(RunFonts::new().ascii("Calibri").hi_ansi("Calibri").cs("Calibri").east_asia("Calibri"))
|
}
|
||||||
.default_size(22)
|
|
||||||
}
|
fn styles(doc: Docx) -> Docx {
|
||||||
|
doc.add_style(Style::new("Heading1", StyleType::Paragraph).name("heading 1").size(40).bold().outline_lvl(0))
|
||||||
/// Converts a PDF to a .docx.
|
.add_style(Style::new("Heading2", StyleType::Paragraph).name("heading 2").size(30).bold().outline_lvl(1))
|
||||||
pub fn to_word(engine: &Engine, bytes: &[u8], password: Option<&str>, opts: &WordOptions) -> Result<WordResult, PdfError> {
|
.add_style(Style::new("Heading3", StyleType::Paragraph).name("heading 3").size(24).bold().outline_lvl(2))
|
||||||
let doc = engine.open(bytes, password)?;
|
.default_fonts(RunFonts::new().ascii("Calibri").hi_ansi("Calibri").cs("Calibri").east_asia("Calibri"))
|
||||||
let n = doc.pages().len() as usize;
|
.default_size(22)
|
||||||
if n > 2000 {
|
}
|
||||||
return Err(PdfError::TooLarge(format!("{n} pages")));
|
|
||||||
}
|
/// Converts a PDF to a .docx.
|
||||||
let mut per_page: Vec<Vec<Item>> = Vec::with_capacity(n);
|
pub fn to_word(
|
||||||
let mut all_lines: Vec<Vec<Line>> = Vec::with_capacity(n);
|
engine: &Engine,
|
||||||
let mut scanned = Vec::new();
|
bytes: &[u8],
|
||||||
for (i, page) in doc.pages().iter().enumerate() {
|
password: Option<&str>,
|
||||||
let chars = page_chars(&page)?;
|
opts: &WordOptions,
|
||||||
let visible = chars.iter().filter(|c| !c.c.is_whitespace()).count();
|
) -> Result<WordResult, PdfError> {
|
||||||
let mut items = Vec::new();
|
let doc = engine.open(bytes, password)?;
|
||||||
let mut images = 0;
|
let n = doc.pages().len() as usize;
|
||||||
for obj in page.objects().iter() {
|
if n > 2000 {
|
||||||
let Some(img) = obj.as_image_object() else { continue };
|
return Err(PdfError::TooLarge(format!("{n} pages")));
|
||||||
let Ok(b) = obj.bounds() else { continue };
|
}
|
||||||
let Ok(raw) = img.get_raw_image() else { continue };
|
let mut per_page: Vec<Vec<Item>> = Vec::with_capacity(n);
|
||||||
let (w_pt, h_pt) = (b.width().value, b.height().value);
|
let mut all_lines: Vec<Vec<Line>> = Vec::with_capacity(n);
|
||||||
if w_pt < 8.0 || h_pt < 8.0 {
|
let mut scanned = Vec::new();
|
||||||
continue;
|
for (i, page) in doc.pages().iter().enumerate() {
|
||||||
}
|
let chars = page_chars(&page)?;
|
||||||
images += 1;
|
let visible = chars.iter().filter(|c| !c.c.is_whitespace()).count();
|
||||||
// Keep pictures a sensible size in the document (at most 1600 px on the long side).
|
let mut items = Vec::new();
|
||||||
let raw = if raw.width().max(raw.height()) > 1600 { raw.resize(1600, 1600, image::imageops::FilterType::Triangle) } else { raw };
|
let mut images = 0;
|
||||||
let mut png = Vec::new();
|
for obj in page.objects().iter() {
|
||||||
if raw.to_rgb8().write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() {
|
let Some(img) = obj.as_image_object() else { continue };
|
||||||
continue;
|
let Ok(b) = obj.bounds() else { continue };
|
||||||
}
|
let Ok(raw) = img.get_raw_image() else { continue };
|
||||||
items.push(Item::Image { top: b.top().value, png, w_px: raw.width(), h_px: raw.height(), w_pt, h_pt });
|
let (w_pt, h_pt) = (b.width().value, b.height().value);
|
||||||
}
|
if w_pt < 8.0 || h_pt < 8.0 {
|
||||||
let page_lines = lines(chars);
|
continue;
|
||||||
if visible < 10 && images > 0 {
|
}
|
||||||
if opts.ocr.contains_key(&i) {
|
images += 1;
|
||||||
items.clear(); // the recognised text replaces the scan
|
// Keep pictures a sensible size in the document (at most 1600 px on the long side).
|
||||||
} else {
|
let raw = if raw.width().max(raw.height()) > 1600 {
|
||||||
scanned.push(i);
|
raw.resize(1600, 1600, image::imageops::FilterType::Triangle)
|
||||||
}
|
} else {
|
||||||
}
|
raw
|
||||||
all_lines.push(page_lines);
|
};
|
||||||
per_page.push(items);
|
let mut png = Vec::new();
|
||||||
}
|
if raw.to_rgb8().write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).is_err() {
|
||||||
let body = body_size(&all_lines);
|
continue;
|
||||||
let mut docx = styles(Docx::new());
|
}
|
||||||
for (i, (page_lines, images)) in all_lines.into_iter().zip(per_page).enumerate() {
|
items.push(Item::Image { top: b.top().value, png, w_px: raw.width(), h_px: raw.height(), w_pt, h_pt });
|
||||||
if i > 0 {
|
}
|
||||||
docx = docx.add_paragraph(Paragraph::new().add_run(Run::new().add_break(BreakType::Page)));
|
let page_lines = lines(chars);
|
||||||
}
|
if visible < 10 && images > 0 {
|
||||||
if let Some(t) = opts.ocr.get(&i) {
|
if opts.ocr.contains_key(&i) {
|
||||||
for para in t.split("\n\n").map(|p| p.split_whitespace().collect::<Vec<_>>().join(" ")).filter(|p| !p.is_empty()) {
|
items.clear(); // the recognised text replaces the scan
|
||||||
docx = docx.add_paragraph(Paragraph::new().add_run(Run::new().add_text(para)));
|
} else {
|
||||||
}
|
scanned.push(i);
|
||||||
}
|
}
|
||||||
// Interleave text runs and images by their top edge.
|
}
|
||||||
let mut items: Vec<Item> = images;
|
all_lines.push(page_lines);
|
||||||
let mut group: Vec<Line> = Vec::new();
|
per_page.push(items);
|
||||||
let mut groups: Vec<Item> = Vec::new();
|
}
|
||||||
let tops: Vec<f32> = items.iter().map(item_top).collect();
|
let body = body_size(&all_lines);
|
||||||
for l in page_lines {
|
let mut docx = styles(Docx::new());
|
||||||
if tops.iter().any(|t| *t < (group.last().map(|g: &Line| g.top).unwrap_or(f32::MAX)) && *t >= l.top) && !group.is_empty() {
|
for (i, (page_lines, images)) in all_lines.into_iter().zip(per_page).enumerate() {
|
||||||
groups.push(Item::Lines(std::mem::take(&mut group)));
|
if i > 0 {
|
||||||
}
|
docx = docx.add_paragraph(Paragraph::new().add_run(Run::new().add_break(BreakType::Page)));
|
||||||
group.push(l);
|
}
|
||||||
}
|
if let Some(t) = opts.ocr.get(&i) {
|
||||||
if !group.is_empty() {
|
for para in
|
||||||
groups.push(Item::Lines(group));
|
t.split("\n\n").map(|p| p.split_whitespace().collect::<Vec<_>>().join(" ")).filter(|p| !p.is_empty())
|
||||||
}
|
{
|
||||||
items.extend(groups);
|
docx = docx.add_paragraph(Paragraph::new().add_run(Run::new().add_text(para)));
|
||||||
items.sort_by(|a, b| item_top(b).total_cmp(&item_top(a)));
|
}
|
||||||
for item in items {
|
}
|
||||||
match item {
|
// Interleave text runs and images by their top edge.
|
||||||
Item::Lines(ls) => docx = blocks(ls, body, docx),
|
let mut items: Vec<Item> = images;
|
||||||
Item::Image { png, w_px, h_px, w_pt, h_pt, .. } => {
|
let mut group: Vec<Line> = Vec::new();
|
||||||
// Size in EMU (1 pt = 12 700 EMU), at most 6.5 inches wide.
|
let mut groups: Vec<Item> = Vec::new();
|
||||||
let k = (468.0 / w_pt).min(1.0);
|
let tops: Vec<f32> = items.iter().map(item_top).collect();
|
||||||
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);
|
for l in page_lines {
|
||||||
docx = docx.add_paragraph(Paragraph::new().add_run(Run::new().add_image(pic)));
|
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)));
|
||||||
}
|
}
|
||||||
let mut out = std::io::Cursor::new(Vec::new());
|
group.push(l);
|
||||||
docx.build().pack(&mut out).map_err(|e| PdfError::Write(e.to_string()))?;
|
}
|
||||||
Ok(WordResult { bytes: out.into_inner(), pages: n, scanned_pages: scanned })
|
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 })
|
||||||
|
}
|
||||||
|
|||||||
@@ -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,
|
||||||
@@ -51,7 +54,7 @@ fn heavy_pdf(pages: usize, px: u32, jpeg: bool) -> Vec<u8> {
|
|||||||
doc.objects.insert(
|
doc.objects.insert(
|
||||||
pages_id,
|
pages_id,
|
||||||
Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => pages as i64,
|
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});
|
let cat = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id});
|
||||||
doc.trailer.set("Root", cat);
|
doc.trailer.set("Root", cat);
|
||||||
|
|||||||
+217
-180
@@ -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
|
//! 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.
|
//! 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
|
//! 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.
|
//! (Scriptum's engine, Prelum, is private): Pictor/apps/desktop/src-tauri/tests/word_scriptum.rs.
|
||||||
mod common;
|
mod common;
|
||||||
use common::*;
|
use common::*;
|
||||||
use lopdf::{Document, Object, Stream, dictionary};
|
use lopdf::{Document, Object, Stream, dictionary};
|
||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
|
|
||||||
const BODY: &[&str] = &[
|
const BODY: &[&str] = &[
|
||||||
"Pictor turns this PDF into a document you can edit.",
|
"Pictor turns this PDF into a document you can edit.",
|
||||||
"The paragraph wraps over three lines on purpose, so",
|
"The paragraph wraps over three lines on purpose, so",
|
||||||
"that the converter has to join the lines back together.",
|
"that the converter has to join the lines back together.",
|
||||||
];
|
];
|
||||||
|
|
||||||
pub fn report_pdf() -> Vec<u8> {
|
pub fn report_pdf() -> Vec<u8> {
|
||||||
let mut doc = Document::with_version("1.7");
|
let mut doc = Document::with_version("1.7");
|
||||||
let pages_id = doc.new_object_id();
|
let pages_id = doc.new_object_id();
|
||||||
let reg = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", "Encoding" => "WinAnsiEncoding"});
|
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 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 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(
|
let mut im = Stream::new(
|
||||||
dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => 120, "Height" => 80, "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8},
|
dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => 120, "Height" => 80, "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8},
|
||||||
img.into_raw(),
|
img.into_raw(),
|
||||||
);
|
);
|
||||||
im.compress().unwrap();
|
im.compress().unwrap();
|
||||||
let im = doc.add_object(im);
|
let im = doc.add_object(im);
|
||||||
let mut c1 = String::new();
|
let mut c1 = String::new();
|
||||||
c1 += "BT /F2 26 Tf 72 770 Td (Quarterly report) Tj ET\n";
|
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";
|
c1 += "BT /F2 16 Tf 72 730 Td (Summary) Tj ET\n";
|
||||||
for (i, line) in BODY.iter().enumerate() {
|
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 += &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 = [
|
||||||
for (r, row) in rows.iter().enumerate() {
|
["Month", "Sales", "Notes"],
|
||||||
for (c, cell) in row.iter().enumerate() {
|
["January", "1200", "cold"],
|
||||||
let font = if r == 0 { "/F2" } else { "/F1" };
|
["February", "1350", "better"],
|
||||||
c1 += &format!("BT {font} 11 Tf {} {} Td ({cell}) Tj ET\n", 72 + c * 150, 615 - r as i32 * 18);
|
["March", "1600", "best"],
|
||||||
}
|
];
|
||||||
}
|
for (r, row) in rows.iter().enumerate() {
|
||||||
c1 += "q 120 0 0 80 72 420 cm /Im0 Do Q\n";
|
for (c, cell) in row.iter().enumerate() {
|
||||||
c1 += "BT /F1 11 Tf 72 400 Td (A picture of the gradient above.) Tj ET\n";
|
let font = if r == 0 { "/F2" } else { "/F1" };
|
||||||
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";
|
c1 += &format!("BT {font} 11 Tf {} {} Td ({cell}) Tj ET\n", 72 + c * 150, 615 - r as i32 * 18);
|
||||||
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()] {
|
c1 += "q 120 0 0 80 72 420 cm /Im0 Do Q\n";
|
||||||
let cid = doc.add_object(Stream::new(dictionary! {}, c.into_bytes()));
|
c1 += "BT /F1 11 Tf 72 400 Td (A picture of the gradient above.) Tj ET\n";
|
||||||
kids.push(Object::Reference(doc.add_object(dictionary! {"Type" => "Page", "Parent" => pages_id, "Contents" => cid, "Resources" => res()})));
|
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 =
|
||||||
doc.objects.insert(pages_id, Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => 2,
|
|| dictionary! {"Font" => dictionary! {"F1" => reg, "F2" => bold}, "XObject" => dictionary! {"Im0" => im}};
|
||||||
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}));
|
let mut kids = Vec::new();
|
||||||
let cat = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id});
|
for c in [c1, c2.to_string()] {
|
||||||
doc.trailer.set("Root", cat);
|
let cid = doc.add_object(Stream::new(dictionary! {}, c.into_bytes()));
|
||||||
let mut out = Vec::new();
|
kids.push(Object::Reference(doc.add_object(
|
||||||
doc.save_to(&mut out).unwrap();
|
dictionary! {"Type" => "Page", "Parent" => pages_id, "Contents" => cid, "Resources" => res()},
|
||||||
out
|
)));
|
||||||
}
|
}
|
||||||
|
doc.objects.insert(
|
||||||
fn part(docx: &[u8], name: &str) -> Option<Vec<u8>> {
|
pages_id,
|
||||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap();
|
Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => 2,
|
||||||
let mut f = z.by_name(name).ok()?;
|
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}),
|
||||||
let mut v = Vec::new();
|
);
|
||||||
f.read_to_end(&mut v).unwrap();
|
let cat = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id});
|
||||||
Some(v)
|
doc.trailer.set("Root", cat);
|
||||||
}
|
let mut out = Vec::new();
|
||||||
|
doc.save_to(&mut out).unwrap();
|
||||||
fn entries(docx: &[u8]) -> Vec<String> {
|
out
|
||||||
let z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap();
|
}
|
||||||
z.file_names().map(String::from).collect()
|
|
||||||
}
|
fn part(docx: &[u8], name: &str) -> Option<Vec<u8>> {
|
||||||
|
let mut z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap();
|
||||||
/// The text of word/document.xml: every w:t, a newline per paragraph.
|
let mut f = z.by_name(name).ok()?;
|
||||||
fn text_of(xml: &str) -> String {
|
let mut v = Vec::new();
|
||||||
let mut out = String::new();
|
f.read_to_end(&mut v).unwrap();
|
||||||
let mut rest = xml;
|
Some(v)
|
||||||
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];
|
fn entries(docx: &[u8]) -> Vec<String> {
|
||||||
if tag.starts_with("w:t") && !tag.ends_with('/') && (tag == "w:t" || tag.starts_with("w:t ")) {
|
let z = zip::ZipArchive::new(std::io::Cursor::new(docx)).unwrap();
|
||||||
let body = &rest[tag_end + 1..];
|
z.file_names().map(String::from).collect()
|
||||||
let end = body.find("</w:t>").unwrap_or(0);
|
}
|
||||||
out.push_str(&body[..end].replace("&", "&").replace("<", "<").replace(">", ">"));
|
|
||||||
} else if tag == "/w:p" {
|
/// The text of word/document.xml: every w:t, a newline per paragraph.
|
||||||
out.push('\n');
|
fn text_of(xml: &str) -> String {
|
||||||
}
|
let mut out = String::new();
|
||||||
rest = &rest[tag_end + 1..];
|
let mut rest = xml;
|
||||||
}
|
while let Some(i) = rest.find('<') {
|
||||||
out
|
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 ")) {
|
||||||
fn assert_in_order(text: &str, words: &[&str]) {
|
let body = &rest[tag_end + 1..];
|
||||||
let mut at = 0;
|
let end = body.find("</w:t>").unwrap_or(0);
|
||||||
for w in words {
|
out.push_str(&body[..end].replace("&", "&").replace("<", "<").replace(">", ">"));
|
||||||
match text[at..].find(w) {
|
} else if tag == "/w:p" {
|
||||||
Some(i) => at += i + w.len(),
|
out.push('\n');
|
||||||
None => panic!("{w:?} missing or out of order in:\n{text}"),
|
}
|
||||||
}
|
rest = &rest[tag_end + 1..];
|
||||||
}
|
}
|
||||||
}
|
out
|
||||||
|
}
|
||||||
const ORDER: &[&str] = &[
|
|
||||||
"Quarterly report", "Summary", "Pictor turns", "edit.", "wraps over three lines", "join the lines back together.",
|
fn assert_in_order(text: &str, words: &[&str]) {
|
||||||
"Figures", "Month", "Sales", "Notes", "January", "1200", "cold", "March", "1600", "best",
|
let mut at = 0;
|
||||||
"A picture of the gradient", "Next steps", "Page two closes the report.",
|
for w in words {
|
||||||
];
|
match text[at..].find(w) {
|
||||||
|
Some(i) => at += i + w.len(),
|
||||||
#[test]
|
None => panic!("{w:?} missing or out of order in:\n{text}"),
|
||||||
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);
|
const ORDER: &[&str] = &[
|
||||||
assert_in_order(&text, ORDER);
|
"Quarterly report",
|
||||||
// The wrapped paragraph is one paragraph, not three.
|
"Summary",
|
||||||
assert!(text.contains("so that the converter"), "the wrapped lines were not joined:\n{text}");
|
"Pictor turns",
|
||||||
// Headings: the title and the section heads carry heading styles.
|
"edit.",
|
||||||
assert!(xml.matches("w:pStyle w:val=\"Heading1\"").count() >= 1, "no Heading 1");
|
"wraps over three lines",
|
||||||
assert!(xml.matches("w:pStyle w:val=\"Heading2\"").count() >= 3, "fewer than 3 Heading 2");
|
"join the lines back together.",
|
||||||
// One table of 4 rows × 3 cells.
|
"Figures",
|
||||||
assert_eq!(xml.matches("<w:tbl>").count(), 1, "tables");
|
"Month",
|
||||||
assert_eq!(xml.matches("<w:tr").count() - xml.matches("<w:trPr").count(), 4, "rows");
|
"Sales",
|
||||||
// The image is embedded.
|
"Notes",
|
||||||
assert!(xml.contains("<w:drawing>"), "no picture");
|
"January",
|
||||||
assert!(entries(&r.bytes).iter().any(|e| e.starts_with("word/media/")), "no media part");
|
"1200",
|
||||||
// A page break between the two pages.
|
"cold",
|
||||||
assert!(xml.contains("w:type=\"page\""), "no page break");
|
"March",
|
||||||
}
|
"1600",
|
||||||
|
"best",
|
||||||
#[test]
|
"A picture of the gradient",
|
||||||
fn a_page_without_text_is_reported_as_scanned_and_takes_ocr_text() {
|
"Next steps",
|
||||||
// A "scan": one page that is only an image.
|
"Page two closes the report.",
|
||||||
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,
|
#[test]
|
||||||
0.0,
|
fn headings_paragraphs_table_and_image_come_out_in_order() {
|
||||||
)
|
let r = pictor_pdf::to_word(engine(), &report_pdf(), None, &Default::default()).unwrap();
|
||||||
.unwrap();
|
assert!(r.scanned_pages.is_empty(), "{:?}", r.scanned_pages);
|
||||||
let r = pictor_pdf::to_word(engine(), &input, None, &Default::default()).unwrap();
|
let xml = String::from_utf8(part(&r.bytes, "word/document.xml").expect("document.xml")).unwrap();
|
||||||
assert_eq!(r.scanned_pages, vec![0]);
|
let text = text_of(&xml);
|
||||||
let mut opts = pictor_pdf::WordOptions::default();
|
assert_in_order(&text, ORDER);
|
||||||
opts.ocr.insert(0, "Recognised line one\n\nSecond paragraph from OCR".into());
|
// The wrapped paragraph is one paragraph, not three.
|
||||||
let r = pictor_pdf::to_word(engine(), &input, None, &opts).unwrap();
|
assert!(text.contains("so that the converter"), "the wrapped lines were not joined:\n{text}");
|
||||||
let text = text_of(&String::from_utf8(part(&r.bytes, "word/document.xml").unwrap()).unwrap());
|
// Headings: the title and the section heads carry heading styles.
|
||||||
assert_in_order(&text, &["Recognised line one", "Second paragraph from OCR"]);
|
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.
|
||||||
#[test]
|
assert_eq!(xml.matches("<w:tbl>").count(), 1, "tables");
|
||||||
fn libreoffice_reads_every_word_in_order() {
|
assert_eq!(xml.matches("<w:tr").count() - xml.matches("<w:trPr").count(), 4, "rows");
|
||||||
let soffice = std::path::Path::new(r"C:\Program Files\LibreOffice\program\soffice.com");
|
// The image is embedded.
|
||||||
if !soffice.exists() {
|
assert!(xml.contains("<w:drawing>"), "no picture");
|
||||||
println!("LibreOffice is not installed here: skipped");
|
assert!(entries(&r.bytes).iter().any(|e| e.starts_with("word/media/")), "no media part");
|
||||||
return;
|
// A page break between the two pages.
|
||||||
}
|
assert!(xml.contains("w:type=\"page\""), "no page break");
|
||||||
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();
|
#[test]
|
||||||
let profile = format!("file:///{}", dir.path().join("lo-profile").display().to_string().replace('\\', "/"));
|
fn a_page_without_text_is_reported_as_scanned_and_takes_ocr_text() {
|
||||||
// A fresh LibreOffice profile makes the first start exit with 1 while it restarts itself and still converts:
|
// A "scan": one page that is only an image.
|
||||||
// wait for the file rather than trusting the exit code (one retry if nothing comes).
|
let input = pictor_pdf::images_to_pdf(
|
||||||
let out = dir.path().join("report.txt");
|
&[(
|
||||||
for _ in 0..2 {
|
Vec::new(),
|
||||||
let _ = std::process::Command::new(soffice)
|
image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(800, 1100, image::Rgb([240, 240, 240]))),
|
||||||
.args([&format!("-env:UserInstallation={profile}"), "--headless", "--invisible", "--norestore", "--nolockcheck"])
|
)],
|
||||||
.args(["--convert-to", "txt:Text (encoded):UTF8", "--outdir"])
|
pictor_pdf::PageFit::A4,
|
||||||
.arg(dir.path())
|
0.0,
|
||||||
.arg(&docx)
|
)
|
||||||
.status();
|
.unwrap();
|
||||||
let start = std::time::Instant::now();
|
let r = pictor_pdf::to_word(engine(), &input, None, &Default::default()).unwrap();
|
||||||
while !out.exists() && start.elapsed() < std::time::Duration::from_secs(60) {
|
assert_eq!(r.scanned_pages, vec![0]);
|
||||||
std::thread::sleep(std::time::Duration::from_millis(250));
|
let mut opts = pictor_pdf::WordOptions::default();
|
||||||
}
|
opts.ocr.insert(0, "Recognised line one\n\nSecond paragraph from OCR".into());
|
||||||
if out.exists() {
|
let r = pictor_pdf::to_word(engine(), &input, None, &opts).unwrap();
|
||||||
break;
|
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"]);
|
||||||
}
|
}
|
||||||
std::thread::sleep(std::time::Duration::from_millis(500));
|
|
||||||
let text = std::fs::read_to_string(&out).expect("LibreOffice converted the .docx");
|
#[test]
|
||||||
assert_in_order(&text, ORDER);
|
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);
|
||||||
|
}
|
||||||
|
|||||||
+501
-500
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user