Compare commits
8 Commits
feature/v1
...
v0.2.1
| Author | SHA1 | Date | |
|---|---|---|---|
| e46cbe3547 | |||
| 45f1d40c5b | |||
| 47576bd6e0 | |||
| 6efc835d24 | |||
| f1f0234ffb | |||
| fcc9840fdc | |||
| a400ff88a6 | |||
| 27d7e12a51 |
@@ -0,0 +1,19 @@
|
|||||||
|
# Pictor's core: every test, on the Windows runner (Fabrica on Mark's PC), in the background. pdfium is fetched by
|
||||||
|
# its pinned script; the optional hostile corpus too. LibreOffice, when installed, is used by the PDF-to-Word test.
|
||||||
|
name: test
|
||||||
|
on:
|
||||||
|
push: [main]
|
||||||
|
manual: true
|
||||||
|
runner: windows
|
||||||
|
env:
|
||||||
|
RUST_BACKTRACE: "1"
|
||||||
|
steps:
|
||||||
|
- id: pdfium
|
||||||
|
run: powershell -NoProfile -ExecutionPolicy Bypass -File scripts/fetch-pdfium.ps1
|
||||||
|
- id: corpus
|
||||||
|
run: powershell -NoProfile -ExecutionPolicy Bypass -File fixtures-fetch/fetch.ps1
|
||||||
|
- id: test
|
||||||
|
needs: [pdfium, corpus]
|
||||||
|
run: cargo test --workspace --release
|
||||||
|
- id: licences
|
||||||
|
run: node --test scripts/deps.test.mjs && node scripts/deps.mjs --check
|
||||||
Generated
+67
@@ -321,6 +321,22 @@ dependencies = [
|
|||||||
"crypto-common",
|
"crypto-common",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "docx-rs"
|
||||||
|
version = "0.4.22"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7fdf00e8af6d0b3e92d4bbf9b76f773d8b84ea80f310324ad16cbdc2e653e02c"
|
||||||
|
dependencies = [
|
||||||
|
"base64",
|
||||||
|
"crc32fast",
|
||||||
|
"quick-xml",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"smallvec",
|
||||||
|
"thiserror",
|
||||||
|
"zip",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ecb"
|
name = "ecb"
|
||||||
version = "0.2.1"
|
version = "0.2.1"
|
||||||
@@ -833,6 +849,7 @@ dependencies = [
|
|||||||
name = "pictor-pdf"
|
name = "pictor-pdf"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"docx-rs",
|
||||||
"flate2",
|
"flate2",
|
||||||
"getrandom",
|
"getrandom",
|
||||||
"image",
|
"image",
|
||||||
@@ -841,7 +858,9 @@ dependencies = [
|
|||||||
"pictor-meta",
|
"pictor-meta",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
"tempfile",
|
||||||
"thiserror",
|
"thiserror",
|
||||||
|
"zip",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -982,6 +1001,16 @@ version = "2.0.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
|
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "quick-xml"
|
||||||
|
version = "0.41.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"
|
||||||
|
dependencies = [
|
||||||
|
"encoding_rs",
|
||||||
|
"memchr",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "quote"
|
name = "quote"
|
||||||
version = "1.0.47"
|
version = "1.0.47"
|
||||||
@@ -1161,6 +1190,12 @@ version = "0.4.12"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "smallvec"
|
||||||
|
version = "1.16.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "stringprep"
|
name = "stringprep"
|
||||||
version = "0.1.5"
|
version = "0.1.5"
|
||||||
@@ -1286,6 +1321,12 @@ dependencies = [
|
|||||||
"winnow",
|
"winnow",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "typed-path"
|
||||||
|
version = "0.12.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "54ec2755506471f54baf5e4bb5499d8e510cc1caf271270e778a736bd2d7336c"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "typenum"
|
name = "typenum"
|
||||||
version = "1.20.1"
|
version = "1.20.1"
|
||||||
@@ -1577,6 +1618,20 @@ dependencies = [
|
|||||||
"syn 2.0.119",
|
"syn 2.0.119",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zip"
|
||||||
|
version = "8.6.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b"
|
||||||
|
dependencies = [
|
||||||
|
"crc32fast",
|
||||||
|
"flate2",
|
||||||
|
"indexmap",
|
||||||
|
"memchr",
|
||||||
|
"typed-path",
|
||||||
|
"zopfli",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "zlib-rs"
|
name = "zlib-rs"
|
||||||
version = "0.6.8"
|
version = "0.6.8"
|
||||||
@@ -1589,6 +1644,18 @@ version = "1.0.23"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zopfli"
|
||||||
|
version = "0.8.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"
|
||||||
|
dependencies = [
|
||||||
|
"bumpalo",
|
||||||
|
"crc32fast",
|
||||||
|
"log",
|
||||||
|
"simd-adler32",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "zune-core"
|
name = "zune-core"
|
||||||
version = "0.5.3"
|
version = "0.5.3"
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ pdfium-render = { version = "0.9.5", default-features = false, features = ["thre
|
|||||||
tempfile = "3"
|
tempfile = "3"
|
||||||
sha2 = "0.11"
|
sha2 = "0.11"
|
||||||
getrandom = "0.4"
|
getrandom = "0.4"
|
||||||
|
docx-rs = { version = "0.4.22", default-features = false }
|
||||||
flate2 = "1"
|
flate2 = "1"
|
||||||
windows = "0.62"
|
windows = "0.62"
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,10 @@ lopdf.workspace = true
|
|||||||
pdfium-render.workspace = true
|
pdfium-render.workspace = true
|
||||||
pictor-meta.workspace = true
|
pictor-meta.workspace = true
|
||||||
getrandom.workspace = true
|
getrandom.workspace = true
|
||||||
|
docx-rs.workspace = true
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
flate2.workspace = true
|
flate2.workspace = true
|
||||||
serde_json.workspace = true
|
serde_json.workspace = true
|
||||||
|
zip = { version = "8.6.0", default-features = false, features = ["deflate"] }
|
||||||
|
tempfile.workspace = true
|
||||||
|
|||||||
@@ -0,0 +1,246 @@
|
|||||||
|
//! Compress presets (Day 2): images are downsampled to the preset's resolution and re-encoded as JPEG, every stream
|
||||||
|
//! is Flate-compressed, unreferenced objects are dropped and the file is written with object streams. Text, fonts,
|
||||||
|
//! vector content and the page structure are not touched, so all text stays extractable.
|
||||||
|
//!
|
||||||
|
//! "Resolution" needs no content-stream analysis: an image is never shown larger than the largest page, so its
|
||||||
|
//! pixel size is capped at (largest page side in inches × the preset's dpi). Images Pictor cannot decode safely
|
||||||
|
//! (JPEG 2000, CCITT, JBIG2, indexed or 16-bit colour, masks) are left as they are. Fonts are not subset (a gap,
|
||||||
|
//! recorded in docs/02_v1-1.md of the app).
|
||||||
|
use crate::{PdfError, lopdf_load};
|
||||||
|
use image::{DynamicImage, GenericImageView};
|
||||||
|
use lopdf::{Dictionary, Document, Object, Stream};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum CompressPreset {
|
||||||
|
/// Small enough to attach to an e-mail: target 5 MB or less.
|
||||||
|
Email,
|
||||||
|
/// For the web and the screen.
|
||||||
|
Web,
|
||||||
|
/// Good enough to print.
|
||||||
|
Print,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The E-mail preset's target.
|
||||||
|
pub const EMAIL_TARGET: usize = 5 << 20;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Compressed {
|
||||||
|
pub bytes: Vec<u8>,
|
||||||
|
pub before: usize,
|
||||||
|
pub after: usize,
|
||||||
|
pub images_changed: usize,
|
||||||
|
/// Plain sentences (for example: the E-mail target could not be reached).
|
||||||
|
pub warnings: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Step {
|
||||||
|
dpi: f32,
|
||||||
|
quality: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn steps(preset: CompressPreset) -> &'static [Step] {
|
||||||
|
match preset {
|
||||||
|
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::Print => &[Step { dpi: 300.0, quality: 86 }],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compresses a document with a preset. A protected document stays protected with the same password.
|
||||||
|
pub fn compress(bytes: &[u8], password: Option<&str>, preset: CompressPreset) -> Result<Compressed, PdfError> {
|
||||||
|
let mut last = None;
|
||||||
|
for (i, step) in steps(preset).iter().enumerate() {
|
||||||
|
let r = compress_step(bytes, password, step)?;
|
||||||
|
let done = preset != CompressPreset::Email || r.after <= EMAIL_TARGET || i + 1 == steps(preset).len();
|
||||||
|
last = Some(r);
|
||||||
|
if done {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut r = last.expect("at least one step");
|
||||||
|
if preset == CompressPreset::Email && r.after > EMAIL_TARGET {
|
||||||
|
r.warnings.push(format!(
|
||||||
|
"Pictor got it down to {:.1} MB; the rest is text, fonts and drawings it does not change.",
|
||||||
|
r.after as f64 / 1048576.0
|
||||||
|
));
|
||||||
|
}
|
||||||
|
// Never hand back something bigger than the original.
|
||||||
|
if r.after >= r.before {
|
||||||
|
r.bytes = bytes.to_vec();
|
||||||
|
r.after = r.before;
|
||||||
|
r.images_changed = 0;
|
||||||
|
r.warnings.push("This PDF is already as small as Pictor can make it.".into());
|
||||||
|
}
|
||||||
|
Ok(r)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn compress_step(bytes: &[u8], password: Option<&str>, step: &Step) -> Result<Compressed, PdfError> {
|
||||||
|
let mut doc = lopdf_load(bytes, password)?;
|
||||||
|
let largest_side_in = largest_page_side(&doc) / 72.0;
|
||||||
|
let max_px = (largest_side_in * step.dpi).ceil().max(64.0) as u32;
|
||||||
|
let ids: Vec<_> = doc.objects.keys().copied().collect();
|
||||||
|
let masks = soft_masks(&doc);
|
||||||
|
let mut changed = 0;
|
||||||
|
for id in ids {
|
||||||
|
if masks.contains(&id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(Object::Stream(s)) = doc.objects.get(&id) else { continue };
|
||||||
|
if !is_image(&s.dict) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(new) = recompress(&doc, s, max_px, step.quality) else { continue };
|
||||||
|
if let Some(Object::Stream(s)) = doc.objects.get_mut(&id) {
|
||||||
|
*s = new;
|
||||||
|
changed += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
doc.compress();
|
||||||
|
doc.prune_objects();
|
||||||
|
let opts = lopdf::SaveOptions::builder().use_object_streams(true).use_xref_streams(true).build();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
match password {
|
||||||
|
Some(p) => {
|
||||||
|
let plain = {
|
||||||
|
let mut v = Vec::new();
|
||||||
|
doc.save_with_options(&mut v, opts).map_err(|e| PdfError::Write(e.to_string()))?;
|
||||||
|
v
|
||||||
|
};
|
||||||
|
out = crate::protect(&plain, None, p, None)?;
|
||||||
|
}
|
||||||
|
None => doc.save_with_options(&mut out, opts).map_err(|e| PdfError::Write(e.to_string()))?,
|
||||||
|
}
|
||||||
|
Ok(Compressed { before: bytes.len(), after: out.len(), bytes: out, images_changed: changed, warnings: Vec::new() })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn largest_page_side(doc: &Document) -> f32 {
|
||||||
|
let mut side: f32 = 0.0;
|
||||||
|
for page in doc.get_pages().values() {
|
||||||
|
let f = crate::edit::lopdf_frame(doc, *page);
|
||||||
|
side = side.max(f.crop[2] - f.crop[0]).max(f.crop[3] - f.crop[1]);
|
||||||
|
}
|
||||||
|
if side <= 0.0 { 842.0 } else { side.min(14_400.0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Images used as another image's soft mask: left alone (their size must stay what their parent expects).
|
||||||
|
fn soft_masks(doc: &Document) -> std::collections::HashSet<lopdf::ObjectId> {
|
||||||
|
doc.objects
|
||||||
|
.values()
|
||||||
|
.filter_map(|o| match o {
|
||||||
|
Object::Stream(s) => s.dict.get(b"SMask").ok().and_then(|m| m.as_reference().ok()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_image(d: &Dictionary) -> bool {
|
||||||
|
matches!(d.get(b"Subtype"), Ok(Object::Name(n)) if n == b"Image")
|
||||||
|
&& !matches!(d.get(b"ImageMask"), Ok(Object::Boolean(true)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn name_or_first(o: Option<&Object>) -> Option<Vec<u8>> {
|
||||||
|
match o? {
|
||||||
|
Object::Name(n) => Some(n.clone()),
|
||||||
|
Object::Array(a) if a.len() == 1 => a[0].as_name().ok().map(|n| n.to_vec()),
|
||||||
|
Object::Array(a) if a.is_empty() => Some(Vec::new()),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Channels of a colour space Pictor can re-encode as JPEG: DeviceGray, DeviceRGB, or ICCBased with N 1 or 3.
|
||||||
|
fn channels(doc: &Document, cs: Option<&Object>) -> Option<u8> {
|
||||||
|
let cs = match cs? {
|
||||||
|
Object::Reference(r) => doc.get_object(*r).ok()?,
|
||||||
|
o => o,
|
||||||
|
};
|
||||||
|
match cs {
|
||||||
|
Object::Name(n) if n == b"DeviceGray" => Some(1),
|
||||||
|
Object::Name(n) if n == b"DeviceRGB" => Some(3),
|
||||||
|
Object::Array(a) if a.len() == 2 && a[0].as_name().ok() == Some(b"ICCBased") => {
|
||||||
|
let s = match &a[1] {
|
||||||
|
Object::Reference(r) => doc.get_object(*r).ok()?.as_stream().ok()?,
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
match s.dict.get(b"N").ok()?.as_i64().ok()? {
|
||||||
|
1 => Some(1),
|
||||||
|
3 => Some(3),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn recompress(doc: &Document, s: &Stream, max_px: u32, quality: u8) -> Option<Stream> {
|
||||||
|
let d = &s.dict;
|
||||||
|
let w = d.get(b"Width").ok()?.as_i64().ok()? as u32;
|
||||||
|
let h = d.get(b"Height").ok()?.as_i64().ok()? as u32;
|
||||||
|
if w == 0 || h == 0 || (w as u64) * (h as u64) > 150_000_000 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if d.get(b"BitsPerComponent").ok().and_then(|b| b.as_i64().ok()) != Some(8) || d.has(b"Decode") {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let n = channels(doc, d.get(b"ColorSpace").ok())?;
|
||||||
|
let filter = name_or_first(d.get(b"Filter").ok()).unwrap_or_default();
|
||||||
|
let img: DynamicImage = match &filter[..] {
|
||||||
|
b"DCTDecode" => {
|
||||||
|
let i = image::load_from_memory_with_format(&s.content, image::ImageFormat::Jpeg).ok()?;
|
||||||
|
// CMYK JPEGs (Adobe) and odd channel counts are left alone.
|
||||||
|
if i.color().channel_count() != n {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
i
|
||||||
|
}
|
||||||
|
b"FlateDecode" | b"" => {
|
||||||
|
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;
|
||||||
|
if raw.len() < need {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
match n {
|
||||||
|
1 => DynamicImage::ImageLuma8(image::GrayImage::from_raw(w, h, raw[..need].to_vec())?),
|
||||||
|
_ => DynamicImage::ImageRgb8(image::RgbImage::from_raw(w, h, raw[..need].to_vec())?),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
let (iw, ih) = img.dimensions();
|
||||||
|
let img = if iw.max(ih) > max_px + max_px / 10 {
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
img
|
||||||
|
};
|
||||||
|
let mut jpeg = Vec::new();
|
||||||
|
let enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, quality);
|
||||||
|
match n {
|
||||||
|
1 => img.to_luma8().write_with_encoder(enc).ok()?,
|
||||||
|
_ => img.to_rgb8().write_with_encoder(enc).ok()?,
|
||||||
|
}
|
||||||
|
let old = s.content.len();
|
||||||
|
if jpeg.len() as f64 > old as f64 * 0.9 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut dict = d.clone();
|
||||||
|
dict.set("Width", img.width() as i64);
|
||||||
|
dict.set("Height", img.height() as i64);
|
||||||
|
dict.set("Filter", "DCTDecode");
|
||||||
|
dict.remove(b"DecodeParms");
|
||||||
|
dict.remove(b"Length");
|
||||||
|
let mut out = Stream::new(dict, jpeg);
|
||||||
|
out.allows_compression = false;
|
||||||
|
Some(out)
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@
|
|||||||
//! Every function takes the document as bytes plus an optional password and returns new bytes: nothing here touches
|
//! Every function takes the document as bytes plus an optional password and returns new bytes: nothing here touches
|
||||||
//! the file system. Outside files are hostile; call these only inside `pictor-worker`.
|
//! the file system. Outside files are hostile; call these only inside `pictor-worker`.
|
||||||
|
|
||||||
|
mod compress;
|
||||||
mod edit;
|
mod edit;
|
||||||
mod engine;
|
mod engine;
|
||||||
mod error;
|
mod error;
|
||||||
@@ -16,7 +17,9 @@ mod pages;
|
|||||||
mod reader;
|
mod reader;
|
||||||
mod redact;
|
mod redact;
|
||||||
mod security;
|
mod security;
|
||||||
|
mod word;
|
||||||
|
|
||||||
|
pub use compress::{CompressPreset, Compressed, EMAIL_TARGET, compress};
|
||||||
pub use edit::*;
|
pub use edit::*;
|
||||||
pub use engine::Engine;
|
pub use engine::Engine;
|
||||||
pub use error::PdfError;
|
pub use error::PdfError;
|
||||||
@@ -25,6 +28,7 @@ pub use pages::*;
|
|||||||
pub use reader::*;
|
pub use reader::*;
|
||||||
pub use redact::{RedactOptions, Redacted, Redaction, redact};
|
pub use redact::{RedactOptions, Redacted, Redaction, redact};
|
||||||
pub use security::{is_encrypted, protect, unlock};
|
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).
|
/// 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> {
|
pub(crate) fn lopdf_load(bytes: &[u8], password: Option<&str>) -> Result<lopdf::Document, PdfError> {
|
||||||
|
|||||||
@@ -0,0 +1,504 @@
|
|||||||
|
//! 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)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The median gap between neighbouring visible characters of a line (sorted by x), not below 0; 0 for short lines.
|
||||||
|
fn median_gap(chars: &[Ch]) -> f32 {
|
||||||
|
let visible: Vec<&Ch> = chars.iter().filter(|c| !c.c.is_whitespace()).collect();
|
||||||
|
let mut gaps: Vec<f32> = visible.windows(2).map(|w| w[1].x0 - w[0].x1).collect();
|
||||||
|
if gaps.len() < 4 {
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
gaps.sort_by(f32::total_cmp);
|
||||||
|
gaps[gaps.len() / 2].max(0.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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));
|
||||||
|
// Spaces come from the gaps between letters, not from pdfium's whitespace: many PDFs have no space glyphs,
|
||||||
|
// and pdfium then invents zero-width spaces, some of them inside a word where the producer split it into
|
||||||
|
// two text objects ("Dichotomou" + "s"). A whitespace character only lowers the gap a space needs.
|
||||||
|
// The gap is measured against the line's own letter spacing (its median gap: most neighbours are letters of
|
||||||
|
// one word), so justified text with narrow word gaps (0.14 em) is spaced and tracked-out headings are not
|
||||||
|
// split into letters.
|
||||||
|
let letter_gap = median_gap(&l.chars);
|
||||||
|
let mut with_spaces: Vec<Ch> = Vec::with_capacity(l.chars.len());
|
||||||
|
let mut whitespace_seen = false;
|
||||||
|
for ch in std::mem::take(&mut l.chars) {
|
||||||
|
if ch.c.is_whitespace() {
|
||||||
|
whitespace_seen = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(prev) = with_spaces.last() {
|
||||||
|
let gap = ch.x0 - prev.x1 - letter_gap;
|
||||||
|
let size = ch.size.max(prev.size);
|
||||||
|
if gap > 0.1 * size || (whitespace_seen && gap > 0.05 * size) {
|
||||||
|
let mut sp = prev.clone();
|
||||||
|
sp.c = ' ';
|
||||||
|
with_spaces.push(sp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
whitespace_seen = false;
|
||||||
|
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 })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn ch(c: char, x0: f32, x1: f32, size: f32) -> Ch {
|
||||||
|
Ch { c, x0, x1, y0: 700.0, y1: 700.0 + size, size, bold: false, italic: false }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn text(line: &Line) -> String {
|
||||||
|
line.chars.iter().map(|c| c.c).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The characters pdfium gave for a WPS Writer PDF (no space glyphs, words split over text objects): a
|
||||||
|
/// zero-width space of size 1 between the touching "u" and "s" of "Dichotomous", and a misplaced one in the
|
||||||
|
/// real 4 pt gap before "Segmentation".
|
||||||
|
#[test]
|
||||||
|
fn invented_spaces_inside_a_word_are_dropped_and_gaps_make_spaces() {
|
||||||
|
let s = 15.9;
|
||||||
|
let chars = vec![
|
||||||
|
ch('o', 277.86, 285.83, s),
|
||||||
|
ch('u', 285.86, 294.72, s),
|
||||||
|
ch(' ', 292.53, 292.53, 1.0),
|
||||||
|
ch('s', 294.75, 300.96, s),
|
||||||
|
ch('I', 304.92, 311.12, s),
|
||||||
|
ch('m', 311.15, 324.43, s),
|
||||||
|
ch('e', 324.47, 332.45, s),
|
||||||
|
ch(' ', 326.0, 326.0, 1.0),
|
||||||
|
ch('S', 336.60, 345.47, s),
|
||||||
|
];
|
||||||
|
let l = lines(chars);
|
||||||
|
assert_eq!(l.len(), 1);
|
||||||
|
assert_eq!(text(&l[0]), "ous Ime S");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A PDF with real space glyphs keeps one space per gap, and a narrow space (a condensed font) still counts.
|
||||||
|
#[test]
|
||||||
|
fn real_space_glyphs_still_make_spaces() {
|
||||||
|
let s = 10.0;
|
||||||
|
let chars = vec![
|
||||||
|
ch('a', 0.0, 5.0, s),
|
||||||
|
ch(' ', 5.0, 6.2, s),
|
||||||
|
ch('b', 6.2, 11.0, s),
|
||||||
|
ch(' ', 11.0, 11.5, s),
|
||||||
|
ch(' ', 11.5, 14.0, s),
|
||||||
|
ch('c', 14.0, 19.0, s),
|
||||||
|
ch('d', 19.02, 24.0, s),
|
||||||
|
];
|
||||||
|
assert_eq!(text(&lines(chars)[0]), "a b cd");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lays a line out from words: letters `track` apart, words `space` apart (in points), no space glyphs.
|
||||||
|
fn laid_out(words: &[&str], size: f32, track: f32, space: f32) -> Vec<Ch> {
|
||||||
|
let mut x = 0.0;
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for (i, w) in words.iter().enumerate() {
|
||||||
|
if i > 0 {
|
||||||
|
x += space - track;
|
||||||
|
}
|
||||||
|
for c in w.chars() {
|
||||||
|
out.push(ch(c, x, x + 0.5 * size, size));
|
||||||
|
x += 0.5 * size + track;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Justified text from the same WPS PDF: "of personal" is 1.55 pt apart at 11 pt (0.14 em).
|
||||||
|
#[test]
|
||||||
|
fn narrow_justified_word_gaps_are_spaces() {
|
||||||
|
let chars = laid_out(&["terms", "of", "personal", "data"], 11.05, 0.03, 1.55);
|
||||||
|
assert_eq!(text(&lines(chars)[0]), "terms of personal data");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A heading tracked out to 0.15 em between letters is not split into letters.
|
||||||
|
#[test]
|
||||||
|
fn tracked_out_letters_stay_one_word() {
|
||||||
|
let chars = laid_out(&["CHAPTER", "ONE"], 20.0, 3.0, 12.0);
|
||||||
|
assert_eq!(text(&lines(chars)[0]), "CHAPTER ONE");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
//! Day 2 mandatory test 5: compress presets. The output is smaller, opens in pdfium, keeps every page and keeps all
|
||||||
|
//! text extractable; the E-mail preset reaches its 5 MB target for a heavy scan-like PDF.
|
||||||
|
mod common;
|
||||||
|
use common::*;
|
||||||
|
use lopdf::{Document, Object, Stream, dictionary};
|
||||||
|
use pictor_pdf::CompressPreset;
|
||||||
|
|
||||||
|
/// `pages` A4 pages, each with a line of text and a noisy `px` × `px` photo (Flate RGB, or JPEG at q95).
|
||||||
|
fn heavy_pdf(pages: usize, px: u32, jpeg: bool) -> Vec<u8> {
|
||||||
|
let mut doc = Document::with_version("1.7");
|
||||||
|
let pages_id = doc.new_object_id();
|
||||||
|
let font = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica"});
|
||||||
|
let mut kids = Vec::new();
|
||||||
|
let mut seed = 0x1234_5678u32;
|
||||||
|
for p in 0..pages {
|
||||||
|
let img = image::RgbImage::from_fn(px, px, |x, y| {
|
||||||
|
seed ^= seed << 13;
|
||||||
|
seed ^= seed >> 17;
|
||||||
|
seed ^= seed << 5;
|
||||||
|
let n = (seed & 0x1f) as u8;
|
||||||
|
image::Rgb([(x * 255 / px) as u8 ^ n, (y * 255 / px) as u8, 120u8.wrapping_add(n)])
|
||||||
|
});
|
||||||
|
let stream = if jpeg {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 95).encode_image(&img).unwrap();
|
||||||
|
let mut s = Stream::new(
|
||||||
|
dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => px as i64, "Height" => px as i64,
|
||||||
|
"ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8, "Filter" => "DCTDecode"},
|
||||||
|
out,
|
||||||
|
);
|
||||||
|
s.allows_compression = false;
|
||||||
|
s
|
||||||
|
} else {
|
||||||
|
let mut s = Stream::new(
|
||||||
|
dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => px as i64, "Height" => px as i64,
|
||||||
|
"ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8},
|
||||||
|
img.into_raw(),
|
||||||
|
);
|
||||||
|
s.compress().unwrap();
|
||||||
|
s
|
||||||
|
};
|
||||||
|
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 c = doc.add_object(Stream::new(dictionary! {}, content.into_bytes()));
|
||||||
|
let page = doc.add_object(dictionary! {
|
||||||
|
"Type" => "Page", "Parent" => pages_id, "Contents" => c,
|
||||||
|
"Resources" => dictionary! {"Font" => dictionary! {"F1" => font}, "XObject" => dictionary! {"Im0" => im}},
|
||||||
|
});
|
||||||
|
kids.push(Object::Reference(page));
|
||||||
|
}
|
||||||
|
doc.objects.insert(
|
||||||
|
pages_id,
|
||||||
|
Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => pages as i64,
|
||||||
|
"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 texts(bytes: &[u8]) -> Vec<String> {
|
||||||
|
pictor_pdf::extract_text(engine(), bytes, None).unwrap().into_iter().map(|t| t.trim().to_string()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_preset_makes_it_smaller_and_keeps_the_text() {
|
||||||
|
let input = heavy_pdf(3, 2400, false);
|
||||||
|
let before = texts(&input);
|
||||||
|
for preset in [CompressPreset::Email, CompressPreset::Web, CompressPreset::Print] {
|
||||||
|
let out = pictor_pdf::compress(&input, None, preset).unwrap();
|
||||||
|
assert!(out.bytes.len() < input.len(), "{preset:?} did not shrink ({} → {})", input.len(), out.bytes.len());
|
||||||
|
assert_eq!(out.before, input.len());
|
||||||
|
assert_eq!(out.after, out.bytes.len());
|
||||||
|
assert_eq!(texts(&out.bytes), before, "{preset:?} lost text");
|
||||||
|
let sizes = pictor_pdf::page_sizes(engine(), &out.bytes, None).unwrap();
|
||||||
|
assert_eq!(sizes.len(), 3);
|
||||||
|
assert!(out.images_changed >= 3, "{preset:?}: {} images changed", out.images_changed);
|
||||||
|
// It still renders: the photo is there (not white) in the middle of the page.
|
||||||
|
let img = pictor_pdf::render_page(engine(), &out.bytes, None, 0, 595).unwrap().to_rgb8();
|
||||||
|
let p = img.get_pixel(297, 400).0;
|
||||||
|
assert!(p != [255, 255, 255], "{preset:?}: the photo disappeared");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn presets_are_ordered_email_smallest_print_largest() {
|
||||||
|
let input = heavy_pdf(2, 2400, true);
|
||||||
|
let email = pictor_pdf::compress(&input, None, CompressPreset::Email).unwrap().after;
|
||||||
|
let web = pictor_pdf::compress(&input, None, CompressPreset::Web).unwrap().after;
|
||||||
|
let print = pictor_pdf::compress(&input, None, CompressPreset::Print).unwrap().after;
|
||||||
|
assert!(email <= web && web <= print, "email {email}, web {web}, print {print}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn email_reaches_five_megabytes() {
|
||||||
|
let input = heavy_pdf(8, 3000, false);
|
||||||
|
assert!(input.len() > 20 << 20, "fixture too small: {}", input.len());
|
||||||
|
let out = pictor_pdf::compress(&input, None, CompressPreset::Email).unwrap();
|
||||||
|
assert!(out.after <= 5 << 20, "E-mail preset left {} bytes", out.after);
|
||||||
|
assert_eq!(texts(&out.bytes).len(), 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_pdf_with_nothing_to_shrink_is_left_alone_and_says_so() {
|
||||||
|
let input = numbered_pdf(2, "Plain");
|
||||||
|
let out = pictor_pdf::compress(&input, None, CompressPreset::Web).unwrap();
|
||||||
|
assert_eq!(out.images_changed, 0);
|
||||||
|
assert!(out.after <= out.before + 64, "grew from {} to {}", out.before, out.after);
|
||||||
|
assert_eq!(texts(&out.bytes), ["Plain page 1", "Plain page 2"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_protected_pdf_needs_its_password_and_stays_readable() {
|
||||||
|
let locked = pictor_pdf::protect(&heavy_pdf(1, 1600, false), None, "pw", None).unwrap();
|
||||||
|
assert!(pictor_pdf::compress(&locked, None, CompressPreset::Web).is_err());
|
||||||
|
let out = pictor_pdf::compress(&locked, Some("pw"), CompressPreset::Web).unwrap();
|
||||||
|
assert!(out.after < out.before);
|
||||||
|
// Still protected, with the same password.
|
||||||
|
assert!(pictor_pdf::is_encrypted(&out.bytes));
|
||||||
|
let text = pictor_pdf::extract_text(engine(), &out.bytes, Some("pw")).unwrap();
|
||||||
|
assert_eq!(text[0].trim(), "Invoice page 1 of the compress test");
|
||||||
|
}
|
||||||
@@ -0,0 +1,305 @@
|
|||||||
|
//! 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:?}");
|
||||||
|
}
|
||||||
@@ -224,6 +224,58 @@ pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result<Value, OpError>
|
|||||||
}
|
}
|
||||||
Ok(json!({"paths": paths}))
|
Ok(json!({"paths": paths}))
|
||||||
}
|
}
|
||||||
|
"pdf.compress" => {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct A {
|
||||||
|
doc: u32,
|
||||||
|
preset: pictor_pdf::CompressPreset,
|
||||||
|
output: String,
|
||||||
|
}
|
||||||
|
let a: A = args(a)?;
|
||||||
|
let d = state.doc(a.doc)?;
|
||||||
|
let r = pictor_pdf::compress(&d.bytes, d.password.as_deref(), a.preset)?;
|
||||||
|
let mut out = write_out(&a.output, &r.bytes, SaveMode::New)?;
|
||||||
|
out["before"] = json!(r.before);
|
||||||
|
out["after"] = json!(r.after);
|
||||||
|
out["images_changed"] = json!(r.images_changed);
|
||||||
|
out["warnings"] = json!(r.warnings);
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
"pdf.to_word" => {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct A {
|
||||||
|
doc: u32,
|
||||||
|
output: String,
|
||||||
|
/// Recognised text for scanned pages: {"0": "text", …}.
|
||||||
|
#[serde(default)]
|
||||||
|
ocr: std::collections::HashMap<usize, String>,
|
||||||
|
}
|
||||||
|
let a: A = args(a)?;
|
||||||
|
let engine = state.engine()?;
|
||||||
|
let d = state.doc(a.doc)?;
|
||||||
|
let r =
|
||||||
|
pictor_pdf::to_word(engine, &d.bytes, d.password.as_deref(), &pictor_pdf::WordOptions { ocr: a.ocr })?;
|
||||||
|
let mut out = write_out(&a.output, &r.bytes, SaveMode::New)?;
|
||||||
|
out["pages"] = json!(r.pages);
|
||||||
|
out["scanned_pages"] = json!(r.scanned_pages);
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
"pdf.page_png" => {
|
||||||
|
// A page as a PNG file (for OCR of a scanned page by Fundamentum's Lector, through the app).
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct A {
|
||||||
|
doc: u32,
|
||||||
|
page: usize,
|
||||||
|
dpi: u32,
|
||||||
|
output: String,
|
||||||
|
}
|
||||||
|
let a: A = args(a)?;
|
||||||
|
let engine = state.engine()?;
|
||||||
|
let d = state.doc(a.doc)?;
|
||||||
|
let img = pictor_pdf::pages_to_images(engine, &d.bytes, d.password.as_deref(), &[a.page], a.dpi)?.remove(0);
|
||||||
|
let bytes = png(&img)?;
|
||||||
|
write_out(&a.output, &bytes, SaveMode::Overwrite)
|
||||||
|
}
|
||||||
// ---- PDF files ----------------------------------------------------------------------------------------
|
// ---- PDF files ----------------------------------------------------------------------------------------
|
||||||
"pdf.merge" => {
|
"pdf.merge" => {
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
|
|||||||
+124
-88
@@ -1,91 +1,92 @@
|
|||||||
# Dependencies and their licences
|
# Dependencies and their licences
|
||||||
|
|
||||||
Every crate and binary Pictor's core uses, with its licence, recorded **before** it is used.
|
Every crate and binary Pictor's core uses, with its licence, recorded **before** it is used.
|
||||||
The brief's rule: only components that need no licence deal — MIT, Apache-2.0, BSD, Zlib, MPL-2.0, or a codec the
|
The brief's rule: only components that need no licence deal — MIT, Apache-2.0, BSD, Zlib, MPL-2.0, or a codec the
|
||||||
OS already provides. Nothing paid, copyleft-to-bundle, patent-encumbered or non-commercial.
|
OS already provides. Nothing paid, copyleft-to-bundle, patent-encumbered or non-commercial.
|
||||||
|
|
||||||
## The allowed set, as checked by `scripts/deps.mjs`
|
## The allowed set, as checked by `scripts/deps.mjs`
|
||||||
|
|
||||||
| Licence (SPDX) | Why it is allowed |
|
| Licence (SPDX) | Why it is allowed |
|
||||||
| :-- | :-- |
|
| :-- | :-- |
|
||||||
| MIT, MIT-0 | named in the brief |
|
| MIT, MIT-0 | named in the brief |
|
||||||
| Apache-2.0, Apache-2.0 WITH LLVM-exception | named in the brief |
|
| Apache-2.0, Apache-2.0 WITH LLVM-exception | named in the brief |
|
||||||
| BSD-2-Clause, BSD-3-Clause, 0BSD | named in the brief ("BSD") |
|
| BSD-2-Clause, BSD-3-Clause, 0BSD | named in the brief ("BSD") |
|
||||||
| Zlib | named in the brief |
|
| Zlib | named in the brief |
|
||||||
| MPL-2.0 | named in the brief (file-level copyleft: our own changes to such files stay MPL, which suits this repo) |
|
| MPL-2.0 | named in the brief (file-level copyleft: our own changes to such files stay MPL, which suits this repo) |
|
||||||
| ISC | **interpretation, Mark to confirm**: the BSD-style licence of the ISC; OSI calls it functionally the simplified BSD licence |
|
| ISC | **interpretation, Mark to confirm**: the BSD-style licence of the ISC; OSI calls it functionally the simplified BSD licence |
|
||||||
| Unicode-3.0, Unicode-DFS-2016 | **interpretation, Mark to confirm**: the MIT-style licence of Unicode's data tables; every Rust program that parses identifiers or text pulls it in (`unicode-ident`) |
|
| Unicode-3.0, Unicode-DFS-2016 | **interpretation, Mark to confirm**: the MIT-style licence of Unicode's data tables; every Rust program that parses identifiers or text pulls it in (`unicode-ident`) |
|
||||||
| BSL-1.0, CC0-1.0 | **interpretation, Mark to confirm**: Boost (MIT-like, no attribution in binaries) and public domain |
|
| BSL-1.0, CC0-1.0 | **interpretation, Mark to confirm**: Boost (MIT-like, no attribution in binaries) and public domain |
|
||||||
|
|
||||||
An SPDX expression with `OR` passes when one branch passes; `AND` needs every part to pass. Anything else makes the
|
An SPDX expression with `OR` passes when one branch passes; `AND` needs every part to pass. Anything else makes the
|
||||||
script exit 1, and the feature that needs it waits (the brief: "it never gets a fallback").
|
script exit 1, and the feature that needs it waits (the brief: "it never gets a fallback").
|
||||||
|
|
||||||
## Direct dependencies
|
## Direct dependencies
|
||||||
|
|
||||||
| Crate | Version | Licence | Used by | For |
|
| Crate | Version | Licence | Used by | For |
|
||||||
| :-- | :-- | :-- | :-- | :-- |
|
| :-- | :-- | :-- | :-- | :-- |
|
||||||
| thiserror | 2 | MIT OR Apache-2.0 | all | error types |
|
| thiserror | 2 | MIT OR Apache-2.0 | all | error types |
|
||||||
| serde, serde_json | 1 | MIT OR Apache-2.0 | worker, pdf, meta, qr | the worker protocol, reports |
|
| serde, serde_json | 1 | MIT OR Apache-2.0 | worker, pdf, meta, qr | the worker protocol, reports |
|
||||||
| base64 | 0.22 | MIT OR Apache-2.0 | worker | binary payloads in the protocol |
|
| base64 | 0.22 | MIT OR Apache-2.0 | worker | binary payloads in the protocol |
|
||||||
| image | 0.25 | MIT OR Apache-2.0 | raster, pdf, qr | PNG, JPG, WebP, BMP, GIF, TIFF, ICO decode/encode (no default features: only these codecs) |
|
| image | 0.25 | MIT OR Apache-2.0 | raster, pdf, qr | PNG, JPG, WebP, BMP, GIF, TIFF, ICO decode/encode (no default features: only these codecs) |
|
||||||
| kamadak-exif | 0.6 | BSD-2-Clause | meta | reading EXIF (and writing EXIF fixtures in tests) |
|
| kamadak-exif | 0.6 | BSD-2-Clause | meta | reading EXIF (and writing EXIF fixtures in tests) |
|
||||||
| img-parts | 0.4 (dev) | MIT OR Apache-2.0 | meta tests | building PNG and WebP fixtures (meta walks the containers with its own bounds-checked parsers) |
|
| img-parts | 0.4 (dev) | MIT OR Apache-2.0 | meta tests | building PNG and WebP fixtures (meta walks the containers with its own bounds-checked parsers) |
|
||||||
| qrcode | 0.14 | MIT OR Apache-2.0 | qr | QR matrix and SVG |
|
| qrcode | 0.14 | MIT OR Apache-2.0 | qr | QR matrix and SVG |
|
||||||
| lopdf | 0.47 | MIT | pdf, meta | PDF structure: annotations, stamps, the redaction rebuild, encryption, metadata |
|
| lopdf | 0.47 | MIT | pdf, meta | PDF structure: annotations, stamps, the redaction rebuild, encryption, metadata |
|
||||||
| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | pdf | bindings to pdfium (render, text, forms, pages) |
|
| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | pdf | bindings to pdfium (render, text, forms, pages) |
|
||||||
| tempfile | 3 | MIT OR Apache-2.0 | save (and tests) | temporary files next to the target |
|
| docx-rs | 0.4 | MIT | pdf | PDF to Word: writing the .docx (headings, runs, tables, inline images) |
|
||||||
| sha2 | 0.11 | MIT OR Apache-2.0 | worker, tests | hashes for fixtures and the fetch scripts' self-check |
|
| tempfile | 3 | MIT OR Apache-2.0 | save (and tests) | temporary files next to the target |
|
||||||
| getrandom | 0.4 | MIT OR Apache-2.0 | pdf | the OS random generator, for the AES-256 file key of a password-protected PDF |
|
| sha2 | 0.11 | MIT OR Apache-2.0 | worker, tests | hashes for fixtures and the fetch scripts' self-check |
|
||||||
| flate2 | 1 (dev) | MIT OR Apache-2.0 | pdf tests | building compressed hostile fixtures (a deflate bomb) |
|
| getrandom | 0.4 | MIT OR Apache-2.0 | pdf | the OS random generator, for the AES-256 file key of a password-protected PDF |
|
||||||
| windows | 0.62 | MIT OR Apache-2.0 | raster (Windows only), worker | WIC (HEIC), MFTEnumEx (is an HEVC decoder installed?), Job Objects |
|
| flate2 | 1 (dev) | MIT OR Apache-2.0 | pdf tests | building compressed hostile fixtures (a deflate bomb) |
|
||||||
| rqrr | 0.11 (dev) | (MIT OR Apache-2.0) AND ISC | qr tests | decoding generated codes back (ISC: see above) |
|
| windows | 0.62 | MIT OR Apache-2.0 | raster (Windows only), worker | WIC (HEIC), MFTEnumEx (is an HEVC decoder installed?), Job Objects |
|
||||||
| proptest | 1 (dev) | MIT OR Apache-2.0 | tests | property tests |
|
| rqrr | 0.11 (dev) | (MIT OR Apache-2.0) AND ISC | qr tests | decoding generated codes back (ISC: see above) |
|
||||||
|
| proptest | 1 (dev) | MIT OR Apache-2.0 | tests | property tests |
|
||||||
## Binaries (fetched, never in git)
|
|
||||||
|
## Binaries (fetched, never in git)
|
||||||
| Binary | Licence | Fetched by |
|
|
||||||
| :-- | :-- | :-- |
|
| Binary | Licence | Fetched by |
|
||||||
| pdfium (bblanchon/pdfium-binaries, Windows x64) | see "pdfium" below | `scripts/fetch-pdfium.ps1`, sha256-pinned |
|
| :-- | :-- | :-- |
|
||||||
|
| pdfium (bblanchon/pdfium-binaries, Windows x64) | see "pdfium" below | `scripts/fetch-pdfium.ps1`, sha256-pinned |
|
||||||
### pdfium
|
|
||||||
|
### pdfium
|
||||||
Release `chromium/8125` (PDFium 158.0.8125.0), `pdfium-win-x64.tgz`, sha256
|
|
||||||
`9a964261760cff52570aabf038ab346d3a5034dd8b30d0d5fe8861235d356b8b`, built without V8 and XFA (`args.gn`). It matches
|
Release `chromium/8125` (PDFium 158.0.8125.0), `pdfium-win-x64.tgz`, sha256
|
||||||
pdfium-render 0.9.5's `pdfium_latest` (= `pdfium_8125`). The archive's `LICENSE` and `licenses/` folder ship beside
|
`9a964261760cff52570aabf038ab346d3a5034dd8b30d0d5fe8861235d356b8b`, built without V8 and XFA (`args.gn`). It matches
|
||||||
the dll (the app's installer copies them). Read from those files on 2026-11-16:
|
pdfium-render 0.9.5's `pdfium_latest` (= `pdfium_8125`). The archive's `LICENSE` and `licenses/` folder ship beside
|
||||||
|
the dll (the app's installer copies them). Read from those files on 2026-11-16:
|
||||||
| Component inside pdfium.dll | Licence | In the allowed set? |
|
|
||||||
| :-- | :-- | :-- |
|
| Component inside pdfium.dll | Licence | In the allowed set? |
|
||||||
| the binary build (bblanchon/pdfium-binaries) | MIT | yes |
|
| :-- | :-- | :-- |
|
||||||
| PDFium | BSD-3-Clause (+ Apache-2.0 parts) | yes |
|
| the binary build (bblanchon/pdfium-binaries) | MIT | yes |
|
||||||
| abseil, highway | Apache-2.0 | yes |
|
| PDFium | BSD-3-Clause (+ Apache-2.0 parts) | yes |
|
||||||
| llvm-libc, dragonbox | Apache-2.0 WITH LLVM-exception (dragonbox also BSL-1.0) | yes |
|
| abseil, highway | Apache-2.0 | yes |
|
||||||
| fast_float, simdutf | MIT | yes |
|
| llvm-libc, dragonbox | Apache-2.0 WITH LLVM-exception (dragonbox also BSL-1.0) | yes |
|
||||||
| lcms2, agg 2.3 | MIT-style permission notice | yes (MIT family) |
|
| fast_float, simdutf | MIT | yes |
|
||||||
| OpenJPEG | BSD-2-Clause | yes |
|
| lcms2, agg 2.3 | MIT-style permission notice | yes (MIT family) |
|
||||||
| zlib | Zlib | yes |
|
| OpenJPEG | BSD-2-Clause | yes |
|
||||||
| HarfBuzz | "Old MIT" | yes (MIT family) |
|
| zlib | Zlib | yes |
|
||||||
| ICU | Unicode-3.0 | **interpretation** (see above) |
|
| HarfBuzz | "Old MIT" | yes (MIT family) |
|
||||||
| libpng | PNG Reference Library License v2 (Libpng-2.0, zlib-style) | **interpretation**: zlib-style permissive |
|
| ICU | Unicode-3.0 | **interpretation** (see above) |
|
||||||
| libjpeg-turbo | IJG + BSD-3-Clause | **interpretation**: IJG is BSD-style (credit in documentation) |
|
| libpng | PNG Reference Library License v2 (Libpng-2.0, zlib-style) | **interpretation**: zlib-style permissive |
|
||||||
| FreeType | The FreeType Project License (FTL; dual with GPL-2.0, we take FTL) | **interpretation**: BSD-style with a credit clause — the app's About box says "Portions of this software are copyright © The FreeType Project (www.freetype.org). All rights reserved." |
|
| libjpeg-turbo | IJG + BSD-3-Clause | **interpretation**: IJG is BSD-style (credit in documentation) |
|
||||||
|
| FreeType | The FreeType Project License (FTL; dual with GPL-2.0, we take FTL) | **interpretation**: BSD-style with a credit clause — the app's About box says "Portions of this software are copyright © The FreeType Project (www.freetype.org). All rights reserved." |
|
||||||
None of these needs a licence deal, is paid, copyleft-to-bundle, patent-encumbered or non-commercial. The four marked
|
|
||||||
"interpretation" are not named in the brief's list; they are BSD/zlib-style, and **Mark should confirm** them (PDF
|
None of these needs a licence deal, is paid, copyleft-to-bundle, patent-encumbered or non-commercial. The four marked
|
||||||
support depends on pdfium, which the brief chose).
|
"interpretation" are not named in the brief's list; they are BSD/zlib-style, and **Mark should confirm** them (PDF
|
||||||
|
support depends on pdfium, which the brief chose).
|
||||||
## OS codecs (not bundled)
|
|
||||||
|
## OS codecs (not bundled)
|
||||||
| Codec | Provided by | Used for |
|
|
||||||
| :-- | :-- | :-- |
|
| Codec | Provided by | Used for |
|
||||||
| HEIF/HEIC through WIC | Windows (HEIF Image Extensions + an HEVC decoder from the Microsoft Store) | decoding iPhone photos; never bundled |
|
| :-- | :-- | :-- |
|
||||||
|
| HEIF/HEIC through WIC | Windows (HEIF Image Extensions + an HEVC decoder from the Microsoft Store) | decoding iPhone photos; never bundled |
|
||||||
## Every crate in Cargo.lock
|
|
||||||
|
## Every crate in Cargo.lock
|
||||||
Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
|
|
||||||
|
Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
|
||||||
|
|
||||||
<!-- deps:begin -->
|
<!-- deps:begin -->
|
||||||
141 crates; 0 outside the allowed set.
|
176 crates; 0 outside the allowed set.
|
||||||
|
|
||||||
| Crate | Version | Licence | Allowed |
|
| Crate | Version | Licence | Allowed |
|
||||||
| :-- | :-- | :-- | :-- |
|
| :-- | :-- | :-- | :-- |
|
||||||
@@ -93,6 +94,7 @@ Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
|
|||||||
| aes | 0.9.2 | MIT OR Apache-2.0 | yes |
|
| aes | 0.9.2 | MIT OR Apache-2.0 | yes |
|
||||||
| alloc-no-stdlib | 2.0.4 | BSD-3-Clause | yes |
|
| alloc-no-stdlib | 2.0.4 | BSD-3-Clause | yes |
|
||||||
| alloc-stdlib | 0.2.4 | BSD-3-Clause | yes |
|
| alloc-stdlib | 0.2.4 | BSD-3-Clause | yes |
|
||||||
|
| android_system_properties | 0.1.6 | MIT OR Apache-2.0 | yes |
|
||||||
| autocfg | 1.5.1 | Apache-2.0 OR MIT | yes |
|
| autocfg | 1.5.1 | Apache-2.0 OR MIT | yes |
|
||||||
| base64 | 0.22.1 | MIT OR Apache-2.0 | yes |
|
| base64 | 0.22.1 | MIT OR Apache-2.0 | yes |
|
||||||
| bit-set | 0.11.1 | Apache-2.0 OR MIT | yes |
|
| bit-set | 0.11.1 | Apache-2.0 OR MIT | yes |
|
||||||
@@ -103,34 +105,46 @@ Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
|
|||||||
| borsh | 1.8.1 | MIT OR Apache-2.0 | yes |
|
| borsh | 1.8.1 | MIT OR Apache-2.0 | yes |
|
||||||
| borsh-derive | 1.8.1 | Apache-2.0 | yes |
|
| borsh-derive | 1.8.1 | Apache-2.0 | yes |
|
||||||
| brotli-decompressor | 5.0.3 | BSD-3-Clause/MIT | yes |
|
| brotli-decompressor | 5.0.3 | BSD-3-Clause/MIT | yes |
|
||||||
|
| bumpalo | 3.20.4 | MIT OR Apache-2.0 | yes |
|
||||||
| bytemuck | 1.25.2 | Zlib OR Apache-2.0 OR MIT | yes |
|
| bytemuck | 1.25.2 | Zlib OR Apache-2.0 OR MIT | yes |
|
||||||
| byteorder | 1.5.0 | Unlicense OR MIT | yes |
|
| byteorder | 1.5.0 | Unlicense OR MIT | yes |
|
||||||
| byteorder-lite | 0.1.0 | Unlicense OR MIT | yes |
|
| byteorder-lite | 0.1.0 | Unlicense OR MIT | yes |
|
||||||
| bytes | 1.12.1 | MIT | yes |
|
| bytes | 1.12.1 | MIT | yes |
|
||||||
| cbc | 0.2.1 | MIT OR Apache-2.0 | yes |
|
| cbc | 0.2.1 | MIT OR Apache-2.0 | yes |
|
||||||
|
| cc | 1.11.2 | MIT OR Apache-2.0 | yes |
|
||||||
| cfg_aliases | 0.2.2 | MIT | yes |
|
| cfg_aliases | 0.2.2 | MIT | yes |
|
||||||
| cfg-if | 1.0.5 | MIT OR Apache-2.0 | yes |
|
| cfg-if | 1.0.5 | MIT OR Apache-2.0 | yes |
|
||||||
| chacha20 | 0.10.2 | MIT OR Apache-2.0 | yes |
|
| chacha20 | 0.10.2 | MIT OR Apache-2.0 | yes |
|
||||||
| chrono | 0.4.45 | MIT OR Apache-2.0 | yes |
|
| chrono | 0.4.45 | MIT OR Apache-2.0 | yes |
|
||||||
| cipher | 0.5.2 | MIT OR Apache-2.0 | yes |
|
| cipher | 0.5.2 | MIT OR Apache-2.0 | yes |
|
||||||
| color_quant | 1.1.0 | MIT | yes |
|
| color_quant | 1.1.0 | MIT | yes |
|
||||||
|
| console_error_panic_hook | 0.1.7 | Apache-2.0/MIT | yes |
|
||||||
|
| console_log | 1.1.0 | MIT/Apache-2.0 | yes |
|
||||||
| const-oid | 0.10.3 | Apache-2.0 OR MIT | yes |
|
| const-oid | 0.10.3 | Apache-2.0 OR MIT | yes |
|
||||||
| core_detect | 1.0.0 | MIT/Apache-2.0 | yes |
|
| core_detect | 1.0.0 | MIT/Apache-2.0 | yes |
|
||||||
|
| core-foundation-sys | 0.8.7 | MIT OR Apache-2.0 | yes |
|
||||||
| cpubits | 0.1.1 | MIT OR Apache-2.0 | yes |
|
| cpubits | 0.1.1 | MIT OR Apache-2.0 | yes |
|
||||||
| cpufeatures | 0.3.1 | MIT OR Apache-2.0 | yes |
|
| cpufeatures | 0.3.1 | MIT OR Apache-2.0 | yes |
|
||||||
| crc32fast | 1.5.5 | MIT OR Apache-2.0 | yes |
|
| crc32fast | 1.5.5 | MIT OR Apache-2.0 | yes |
|
||||||
|
| crunchy | 0.2.4 | MIT | yes |
|
||||||
| crypto-common | 0.2.2 | MIT OR Apache-2.0 | yes |
|
| crypto-common | 0.2.2 | MIT OR Apache-2.0 | yes |
|
||||||
| digest | 0.11.3 | MIT OR Apache-2.0 | yes |
|
| digest | 0.11.3 | MIT OR Apache-2.0 | yes |
|
||||||
|
| docx-rs | 0.4.22 | MIT | yes |
|
||||||
| ecb | 0.2.1 | MIT OR Apache-2.0 | yes |
|
| ecb | 0.2.1 | MIT OR Apache-2.0 | yes |
|
||||||
| either | 1.19.0 | MIT OR Apache-2.0 | yes |
|
| either | 1.19.0 | MIT OR Apache-2.0 | yes |
|
||||||
| encoding_rs | 0.8.44 | (Apache-2.0 OR MIT) AND BSD-3-Clause | yes |
|
| encoding_rs | 0.8.44 | (Apache-2.0 OR MIT) AND BSD-3-Clause | yes |
|
||||||
| equivalent | 1.0.3 | Apache-2.0 OR MIT | yes |
|
| equivalent | 1.0.3 | Apache-2.0 OR MIT | yes |
|
||||||
|
| errno | 0.3.15 | MIT OR Apache-2.0 | yes |
|
||||||
| fastrand | 2.5.0 | Apache-2.0 OR MIT | yes |
|
| fastrand | 2.5.0 | Apache-2.0 OR MIT | yes |
|
||||||
| fax | 0.2.7 | MIT | yes |
|
| fax | 0.2.7 | MIT | yes |
|
||||||
| fdeflate | 0.3.7 | MIT OR Apache-2.0 | yes |
|
| fdeflate | 0.3.7 | MIT OR Apache-2.0 | yes |
|
||||||
|
| find-msvc-tools | 0.1.15 | MIT OR Apache-2.0 | yes |
|
||||||
| flate2 | 1.1.11 | MIT OR Apache-2.0 | yes |
|
| flate2 | 1.1.11 | MIT OR Apache-2.0 | yes |
|
||||||
| fnv | 1.0.7 | Apache-2.0 / MIT | yes |
|
| fnv | 1.0.7 | Apache-2.0 / MIT | yes |
|
||||||
| foldhash | 0.2.0 | Zlib | yes |
|
| foldhash | 0.2.0 | Zlib | yes |
|
||||||
|
| futures-core | 0.3.34 | MIT OR Apache-2.0 | yes |
|
||||||
|
| futures-task | 0.3.34 | MIT OR Apache-2.0 | yes |
|
||||||
|
| futures-util | 0.3.34 | MIT OR Apache-2.0 | yes |
|
||||||
| g2gen | 1.2.2 | MIT/Apache-2.0 | yes |
|
| g2gen | 1.2.2 | MIT/Apache-2.0 | yes |
|
||||||
| g2p | 1.2.2 | MIT/Apache-2.0 | yes |
|
| g2p | 1.2.2 | MIT/Apache-2.0 | yes |
|
||||||
| g2poly | 1.2.2 | MIT/Apache-2.0 | yes |
|
| g2poly | 1.2.2 | MIT/Apache-2.0 | yes |
|
||||||
@@ -139,6 +153,8 @@ Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
|
|||||||
| half | 2.7.1 | MIT OR Apache-2.0 | yes |
|
| half | 2.7.1 | MIT OR Apache-2.0 | yes |
|
||||||
| hashbrown | 0.17.1 | MIT OR Apache-2.0 | yes |
|
| hashbrown | 0.17.1 | MIT OR Apache-2.0 | yes |
|
||||||
| hybrid-array | 0.4.15 | MIT OR Apache-2.0 | yes |
|
| hybrid-array | 0.4.15 | MIT OR Apache-2.0 | yes |
|
||||||
|
| iana-time-zone | 0.1.65 | MIT OR Apache-2.0 | yes |
|
||||||
|
| iana-time-zone-haiku | 0.1.2 | MIT OR Apache-2.0 | yes |
|
||||||
| image | 0.25.10 | MIT OR Apache-2.0 | yes |
|
| image | 0.25.10 | MIT OR Apache-2.0 | yes |
|
||||||
| image-webp | 0.2.4 | MIT OR Apache-2.0 | yes |
|
| image-webp | 0.2.4 | MIT OR Apache-2.0 | yes |
|
||||||
| img-parts | 0.4.2 | MIT OR Apache-2.0 | yes |
|
| img-parts | 0.4.2 | MIT OR Apache-2.0 | yes |
|
||||||
@@ -146,8 +162,11 @@ Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
|
|||||||
| inout | 0.2.6 | MIT OR Apache-2.0 | yes |
|
| inout | 0.2.6 | MIT OR Apache-2.0 | yes |
|
||||||
| itertools | 0.15.0 | MIT OR Apache-2.0 | yes |
|
| itertools | 0.15.0 | MIT OR Apache-2.0 | yes |
|
||||||
| itoa | 1.0.19 | MIT OR Apache-2.0 | yes |
|
| itoa | 1.0.19 | MIT OR Apache-2.0 | yes |
|
||||||
|
| js-sys | 0.3.107 | MIT OR Apache-2.0 | yes |
|
||||||
| kamadak-exif | 0.6.2 | BSD-2-Clause | yes |
|
| kamadak-exif | 0.6.2 | BSD-2-Clause | yes |
|
||||||
|
| libc | 0.2.191 | MIT OR Apache-2.0 | yes |
|
||||||
| libloading | 0.9.1 | ISC | yes |
|
| libloading | 0.9.1 | ISC | yes |
|
||||||
|
| linux-raw-sys | 0.12.1 | Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT | yes |
|
||||||
| log | 0.4.35 | MIT OR Apache-2.0 | yes |
|
| log | 0.4.35 | MIT OR Apache-2.0 | yes |
|
||||||
| lopdf | 0.47.0 | MIT | yes |
|
| lopdf | 0.47.0 | MIT | yes |
|
||||||
| lru | 0.18.5 | MIT | yes |
|
| lru | 0.18.5 | MIT | yes |
|
||||||
@@ -163,6 +182,7 @@ Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
|
|||||||
| num-traits | 0.2.19 | MIT OR Apache-2.0 | yes |
|
| num-traits | 0.2.19 | MIT OR Apache-2.0 | yes |
|
||||||
| once_cell | 1.21.4 | MIT OR Apache-2.0 | yes |
|
| once_cell | 1.21.4 | MIT OR Apache-2.0 | yes |
|
||||||
| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | yes |
|
| pdfium-render | 0.9.5 | MIT OR Apache-2.0 | yes |
|
||||||
|
| pin-project-lite | 0.2.17 | Apache-2.0 OR MIT | yes |
|
||||||
| piston-float | 1.0.1 | MIT | yes |
|
| piston-float | 1.0.1 | MIT | yes |
|
||||||
| png | 0.18.1 | MIT OR Apache-2.0 | yes |
|
| png | 0.18.1 | MIT OR Apache-2.0 | yes |
|
||||||
| proc-macro-crate | 3.5.0 | MIT OR Apache-2.0 | yes |
|
| proc-macro-crate | 3.5.0 | MIT OR Apache-2.0 | yes |
|
||||||
@@ -172,13 +192,16 @@ Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
|
|||||||
| qrcode | 0.14.1 | MIT OR Apache-2.0 | yes |
|
| qrcode | 0.14.1 | MIT OR Apache-2.0 | yes |
|
||||||
| quick-error | 1.2.3 | MIT/Apache-2.0 | yes |
|
| quick-error | 1.2.3 | MIT/Apache-2.0 | yes |
|
||||||
| quick-error | 2.0.1 | MIT/Apache-2.0 | yes |
|
| quick-error | 2.0.1 | MIT/Apache-2.0 | yes |
|
||||||
|
| quick-xml | 0.41.0 | MIT | yes |
|
||||||
| quote | 1.0.47 | MIT OR Apache-2.0 | yes |
|
| quote | 1.0.47 | MIT OR Apache-2.0 | yes |
|
||||||
|
| r-efi | 6.0.0 | MIT OR Apache-2.0 OR LGPL-2.1-or-later | yes |
|
||||||
| rand | 0.10.4 | MIT OR Apache-2.0 | yes |
|
| rand | 0.10.4 | MIT OR Apache-2.0 | yes |
|
||||||
| rand_core | 0.10.1 | MIT OR Apache-2.0 | yes |
|
| rand_core | 0.10.1 | MIT OR Apache-2.0 | yes |
|
||||||
| rand_xorshift | 0.5.0 | MIT OR Apache-2.0 | yes |
|
| rand_xorshift | 0.5.0 | MIT OR Apache-2.0 | yes |
|
||||||
| rangemap | 1.8.0 | MIT/Apache-2.0 | yes |
|
| rangemap | 1.8.0 | MIT/Apache-2.0 | yes |
|
||||||
| regex-syntax | 0.8.11 | MIT OR Apache-2.0 | yes |
|
| regex-syntax | 0.8.11 | MIT OR Apache-2.0 | yes |
|
||||||
| rqrr | 0.11.0 | (MIT OR Apache-2.0) AND ISC | yes |
|
| rqrr | 0.11.0 | (MIT OR Apache-2.0) AND ISC | yes |
|
||||||
|
| rustix | 1.1.6 | Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT | yes |
|
||||||
| rustversion | 1.0.23 | MIT OR Apache-2.0 | yes |
|
| rustversion | 1.0.23 | MIT OR Apache-2.0 | yes |
|
||||||
| rusty-fork | 0.3.1 | MIT/Apache-2.0 | yes |
|
| rusty-fork | 0.3.1 | MIT/Apache-2.0 | yes |
|
||||||
| scopeguard | 1.2.0 | MIT OR Apache-2.0 | yes |
|
| scopeguard | 1.2.0 | MIT OR Apache-2.0 | yes |
|
||||||
@@ -187,8 +210,11 @@ Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
|
|||||||
| serde_derive | 1.0.229 | MIT OR Apache-2.0 | yes |
|
| serde_derive | 1.0.229 | MIT OR Apache-2.0 | yes |
|
||||||
| serde_json | 1.0.154 | MIT OR Apache-2.0 | yes |
|
| serde_json | 1.0.154 | MIT OR Apache-2.0 | yes |
|
||||||
| sha2 | 0.11.1 | MIT OR Apache-2.0 | yes |
|
| sha2 | 0.11.1 | MIT OR Apache-2.0 | yes |
|
||||||
|
| shlex | 2.0.1 | MIT OR Apache-2.0 | yes |
|
||||||
| simd-adler32 | 0.3.10 | MIT | yes |
|
| simd-adler32 | 0.3.10 | MIT | yes |
|
||||||
| simdutf8 | 0.1.5 | MIT OR Apache-2.0 | yes |
|
| simdutf8 | 0.1.5 | MIT OR Apache-2.0 | yes |
|
||||||
|
| slab | 0.4.12 | MIT | yes |
|
||||||
|
| smallvec | 1.16.5 | MIT OR Apache-2.0 | yes |
|
||||||
| stringprep | 0.1.5 | MIT/Apache-2.0 | yes |
|
| stringprep | 0.1.5 | MIT/Apache-2.0 | yes |
|
||||||
| syn | 2.0.119 | MIT OR Apache-2.0 | yes |
|
| syn | 2.0.119 | MIT OR Apache-2.0 | yes |
|
||||||
| syn | 3.0.10 | MIT OR Apache-2.0 | yes |
|
| syn | 3.0.10 | MIT OR Apache-2.0 | yes |
|
||||||
@@ -197,9 +223,11 @@ Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
|
|||||||
| thiserror-impl | 2.0.21 | MIT OR Apache-2.0 | yes |
|
| thiserror-impl | 2.0.21 | MIT OR Apache-2.0 | yes |
|
||||||
| tiff | 0.11.3 | MIT | yes |
|
| tiff | 0.11.3 | MIT | yes |
|
||||||
| tinyvec | 1.13.3 | Zlib OR Apache-2.0 OR MIT | yes |
|
| tinyvec | 1.13.3 | Zlib OR Apache-2.0 OR MIT | yes |
|
||||||
|
| tokio | 1.54.1 | MIT | yes |
|
||||||
| toml_datetime | 1.1.3+spec-1.1.0 | MIT OR Apache-2.0 | yes |
|
| toml_datetime | 1.1.3+spec-1.1.0 | MIT OR Apache-2.0 | yes |
|
||||||
| toml_edit | 0.25.19+spec-1.1.0 | MIT OR Apache-2.0 | yes |
|
| toml_edit | 0.25.19+spec-1.1.0 | MIT OR Apache-2.0 | yes |
|
||||||
| toml_parser | 1.1.5+spec-1.1.0 | MIT OR Apache-2.0 | yes |
|
| toml_parser | 1.1.5+spec-1.1.0 | MIT OR Apache-2.0 | yes |
|
||||||
|
| typed-path | 0.12.4 | MIT OR Apache-2.0 | yes |
|
||||||
| typenum | 1.20.1 | MIT OR Apache-2.0 | yes |
|
| typenum | 1.20.1 | MIT OR Apache-2.0 | yes |
|
||||||
| unarray | 0.1.4 | MIT OR Apache-2.0 | yes |
|
| unarray | 0.1.4 | MIT OR Apache-2.0 | yes |
|
||||||
| unicode-bidi | 0.3.18 | MIT OR Apache-2.0 | yes |
|
| unicode-bidi | 0.3.18 | MIT OR Apache-2.0 | yes |
|
||||||
@@ -209,6 +237,12 @@ Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
|
|||||||
| utf16string | 0.2.0 | MIT OR Apache-2.0 | yes |
|
| utf16string | 0.2.0 | MIT OR Apache-2.0 | yes |
|
||||||
| vecmath | 1.0.0 | MIT | yes |
|
| vecmath | 1.0.0 | MIT | yes |
|
||||||
| wait-timeout | 0.2.1 | MIT/Apache-2.0 | yes |
|
| wait-timeout | 0.2.1 | MIT/Apache-2.0 | yes |
|
||||||
|
| wasm-bindgen | 0.2.130 | MIT OR Apache-2.0 | yes |
|
||||||
|
| wasm-bindgen-futures | 0.4.80 | MIT OR Apache-2.0 | yes |
|
||||||
|
| wasm-bindgen-macro | 0.2.130 | MIT OR Apache-2.0 | yes |
|
||||||
|
| wasm-bindgen-macro-support | 0.2.130 | MIT OR Apache-2.0 | yes |
|
||||||
|
| wasm-bindgen-shared | 0.2.130 | MIT OR Apache-2.0 | yes |
|
||||||
|
| web-sys | 0.3.107 | MIT OR Apache-2.0 | yes |
|
||||||
| weezl | 0.1.12 | MIT OR Apache-2.0 | yes |
|
| weezl | 0.1.12 | MIT OR Apache-2.0 | yes |
|
||||||
| weezl | 0.2.1 | MIT OR Apache-2.0 | yes |
|
| weezl | 0.2.1 | MIT OR Apache-2.0 | yes |
|
||||||
| windows | 0.62.2 | MIT OR Apache-2.0 | yes |
|
| windows | 0.62.2 | MIT OR Apache-2.0 | yes |
|
||||||
@@ -226,8 +260,10 @@ Generated by `node scripts/deps.mjs` from `cargo metadata`; do not edit by hand.
|
|||||||
| winnow | 1.0.5 | MIT | yes |
|
| winnow | 1.0.5 | MIT | yes |
|
||||||
| zerocopy | 0.8.63 | BSD-2-Clause OR Apache-2.0 OR MIT | yes |
|
| zerocopy | 0.8.63 | BSD-2-Clause OR Apache-2.0 OR MIT | yes |
|
||||||
| zerocopy-derive | 0.8.63 | BSD-2-Clause OR Apache-2.0 OR MIT | yes |
|
| zerocopy-derive | 0.8.63 | BSD-2-Clause OR Apache-2.0 OR MIT | yes |
|
||||||
|
| zip | 8.6.0 | MIT | yes |
|
||||||
| zlib-rs | 0.6.8 | Zlib | yes |
|
| zlib-rs | 0.6.8 | Zlib | yes |
|
||||||
| zmij | 1.0.23 | MIT | yes |
|
| zmij | 1.0.23 | MIT | yes |
|
||||||
|
| zopfli | 0.8.4 | Apache-2.0 | yes |
|
||||||
| zune-core | 0.5.3 | MIT OR Apache-2.0 OR Zlib | yes |
|
| zune-core | 0.5.3 | MIT OR Apache-2.0 OR Zlib | yes |
|
||||||
| zune-jpeg | 0.5.15 | MIT OR Apache-2.0 OR Zlib | yes |
|
| zune-jpeg | 0.5.15 | MIT OR Apache-2.0 OR Zlib | yes |
|
||||||
<!-- deps:end -->
|
<!-- deps:end -->
|
||||||
|
|||||||
+111
-106
@@ -1,106 +1,111 @@
|
|||||||
# Formats and the worker protocol
|
# Formats and the worker protocol
|
||||||
|
|
||||||
What Pictor's core reads and writes, which library does each PDF operation, and how the app talks to
|
What Pictor's core reads and writes, which library does each PDF operation, and how the app talks to
|
||||||
`pictor-worker`. Version 1 (Day 1, core v0.1.0). The `.pictor` document format arrives on Day 3 and gets its own
|
`pictor-worker`. Version 1 (Day 1, core v0.1.0). The `.pictor` document format arrives on Day 3 and gets its own
|
||||||
section here.
|
section here.
|
||||||
|
|
||||||
## Images (crates/raster, crates/meta)
|
## Images (crates/raster, crates/meta)
|
||||||
|
|
||||||
| Format | Read | Write | Metadata strip |
|
| Format | Read | Write | Metadata strip |
|
||||||
| :-- | :-- | :-- | :-- |
|
| :-- | :-- | :-- | :-- |
|
||||||
| PNG | yes | yes | container-level (eXIf, tEXt, zTXt, iTXt, tIME dropped); pixels identical |
|
| PNG | yes | yes | container-level (eXIf, tEXt, zTXt, iTXt, tIME dropped); pixels identical |
|
||||||
| JPEG | yes, EXIF orientation applied | yes (quality 88 default; alpha onto white) | container-level (APP1 Exif/XMP, APP13 IPTC, COM, other APPn dropped; JFIF, ICC, Adobe kept); orientation ≠ 1 kept as a 36-byte EXIF; pixels identical |
|
| JPEG | yes, EXIF orientation applied | yes (quality 88 default; alpha onto white) | container-level (APP1 Exif/XMP, APP13 IPTC, COM, other APPn dropped; JFIF, ICC, Adobe kept); orientation ≠ 1 kept as a 36-byte EXIF; pixels identical |
|
||||||
| WebP | yes | lossless only (the image crate's encoder) | EXIF and XMP chunks dropped, VP8X flags fixed |
|
| WebP | yes | lossless only (the image crate's encoder) | EXIF and XMP chunks dropped, VP8X flags fixed |
|
||||||
| GIF | yes (first frame for conversion) | single frame | block-level (comments, XMP dropped; every frame and the loop kept) |
|
| GIF | yes (first frame for conversion) | single frame | block-level (comments, XMP dropped; every frame and the loop kept) |
|
||||||
| TIFF | yes | yes | re-encoded losslessly (uncompressed; ICC and orientation are lost: a known gap); multi-page refused |
|
| TIFF | yes | yes | re-encoded losslessly (uncompressed; ICC and orientation are lost: a known gap); multi-page refused |
|
||||||
| BMP | yes | yes | (no metadata) |
|
| BMP | yes | yes | (no metadata) |
|
||||||
| ICO | yes | 256/48/32/16 px | — |
|
| ICO | yes | 256/48/32/16 px | — |
|
||||||
| HEIC/HEIF | Windows only, through WIC with the codecs Windows has; never bundled | no | convert to JPG first |
|
| HEIC/HEIF | Windows only, through WIC with the codecs Windows has; never bundled | no | convert to JPG first |
|
||||||
| AVIF | recognised; decoding needs the AV1 extension (reported as missing) | no | — |
|
| AVIF | recognised; decoding needs the AV1 extension (reported as missing) | no | — |
|
||||||
|
|
||||||
Formats are recognised by their content (magic bytes), never by the extension. Caps (`pictor_raster::Limits`):
|
Formats are recognised by their content (magic bytes), never by the extension. Caps (`pictor_raster::Limits`):
|
||||||
128 million pixels, 512 MiB input, 1 GiB decoded; the pixel count is checked from the header before decoding.
|
128 million pixels, 512 MiB input, 1 GiB decoded; the pixel count is checked from the header before decoding.
|
||||||
|
|
||||||
HEIC needs two Store extensions: "HEIF Image Extensions" (free, `9PMMSR1CGPWG`) and an HEVC decoder ("HEVC Video
|
HEIC needs two Store extensions: "HEIF Image Extensions" (free, `9PMMSR1CGPWG`) and an HEVC decoder ("HEVC Video
|
||||||
Extensions", `9NMZLZ57R3T7`, US$0.99; checked 2026-11-16). `heif_support()` says which one is missing.
|
Extensions", `9NMZLZ57R3T7`, US$0.99; checked 2026-11-16). `heif_support()` says which one is missing.
|
||||||
|
|
||||||
## PDF (crates/pdf)
|
## PDF (crates/pdf)
|
||||||
|
|
||||||
Coordinates between the app and the core are in **view space**: points (1/72 inch) from the top-left corner of the
|
Coordinates between the app and the core are in **view space**: points (1/72 inch) from the top-left corner of the
|
||||||
page as displayed (the crop box, `/Rotate` applied). `geometry::PageFrame` converts to PDF user space.
|
page as displayed (the crop box, `/Rotate` applied). `geometry::PageFrame` converts to PDF user space.
|
||||||
|
|
||||||
| Operation | Library | Why |
|
| Operation | Library | Why |
|
||||||
| :-- | :-- | :-- |
|
| :-- | :-- | :-- |
|
||||||
| open, page sizes, render, text, search, outline | pdfium | what Chrome and Edge use: a file Edge opens, Pictor opens |
|
| open, page sizes, render, text, search, outline | pdfium | what Chrome and Edge use: a file Edge opens, Pictor opens |
|
||||||
| reorder, rotate, delete, insert blank, extract, split | lopdf, in place | keeps the form, bookmarks and metadata; deleted pages and their annotations and fields really leave the file (pdfium's save keeps unreferenced objects) |
|
| reorder, rotate, delete, insert blank, extract, split | lopdf, in place | keeps the form, bookmarks and metadata; deleted pages and their annotations and fields really leave the file (pdfium's save keeps unreferenced objects) |
|
||||||
| merge | pdfium page import | handles inherited resources across files; merged forms keep their look but are no longer fillable; bookmarks are not carried over |
|
| merge | pdfium page import | handles inherited resources across files; merged forms keep their look but are no longer fillable; bookmarks are not carried over |
|
||||||
| images → PDF | lopdf | a JPEG is embedded byte for byte (no re-encoding); others are stored losslessly with an alpha mask |
|
| images → PDF | lopdf | a JPEG is embedded byte for byte (no re-encoding); others are stored losslessly with an alpha mask |
|
||||||
| PDF → PNG/JPG | pdfium | rendering |
|
| PDF → PNG/JPG | pdfium | rendering |
|
||||||
| form fill | lopdf (`/V`, `/AS` with each checkbox's own on-state) + `NeedAppearances`, then pdfium builds the appearances while rendering with the form | the appearance comes from the same engine as Edge's, Czech letters included; viewers that ignore the flag show the value too |
|
| form fill | lopdf (`/V`, `/AS` with each checkbox's own on-state) + `NeedAppearances`, then pdfium builds the appearances while rendering with the form | the appearance comes from the same engine as Edge's, Czech letters included; viewers that ignore the flag show the value too |
|
||||||
| annotations: highlight, underline, strike, note, free text, ink, rectangle, ellipse, line/arrow | lopdf, each with its own appearance stream | looks the same in every viewer; free text uses Helvetica with WinAnsi plus the Central European letters through `/Differences` |
|
| annotations: highlight, underline, strike, note, free text, ink, rectangle, ellipse, line/arrow | lopdf, each with its own appearance stream | looks the same in every viewer; free text uses Helvetica with WinAnsi plus the Central European letters through `/Differences` |
|
||||||
| visual signature (stamp) | lopdf: the image goes into the page content, the old content wrapped in `q … Q` | it is part of the page, not a movable annotation |
|
| visual signature (stamp) | lopdf: the image goes into the page content, the old content wrapped in `q … Q` | it is part of the page, not a movable annotation |
|
||||||
| flatten | pdfium `FPDFPage_Flatten`, then lopdf drops the form and orphans | |
|
| flatten | pdfium `FPDFPage_Flatten`, then lopdf drops the form and orphans | |
|
||||||
| password on | lopdf, AES-256 (V5/R6), no permission restrictions | pdfium cannot write encryption; qpdf was not needed |
|
| password on | lopdf, AES-256 (V5/R6), no permission restrictions | pdfium cannot write encryption; qpdf was not needed |
|
||||||
| password off | lopdf decrypting load + plain save | |
|
| password off | lopdf decrypting load + plain save | |
|
||||||
| true redaction | pdfium render + lopdf rebuild (below) | |
|
| true redaction | pdfium render + lopdf rebuild (below) | |
|
||||||
|
| compress presets (Day 2) | lopdf: images capped at the largest page side × the preset's dpi and re-encoded as JPEG (E-mail 120 → 96 → 72 dpi until ≤ 5 MB, Web 150, Print 300); Flate everywhere; object streams | text, fonts and vectors untouched, so text stays extractable; fonts are not subset (gap) |
|
||||||
### True redaction
|
| PDF to Word (Day 2) | pdfium characters (box, size, weight, slant) → lines, segments, tables, paragraphs, headings; images at their place; docx-rs writes the .docx | "Layout is approximate"; spaces come from the gaps between letters (measured against the line's own letter spacing), never from pdfium's invented whitespace, so PDFs without space glyphs keep whole words; glyphs without a Unicode mapping stay U+FFFD; scanned pages are reported, and OCR text from Fundamentum's Lector can be passed in |
|
||||||
|
|
||||||
Each redacted page is rendered by pdfium at 200 dpi (annotations and form fields included), the boxes are painted
|
### True redaction
|
||||||
black into the pixels, and the page is rebuilt as that one JPEG image (same object number, displayed size kept,
|
|
||||||
`/Rotate 0`). The page's old annotations go, fields that lived only there go, resources inherited from the page
|
Each redacted page is rendered by pdfium at 200 dpi (annotations and form fields included), the boxes are painted
|
||||||
tree are pushed down to the pages that use them, and the document loses `/Info`, every `/Metadata` and
|
black into the pixels, and the page is rebuilt as that one JPEG image (same object number, displayed size kept,
|
||||||
`/PieceInfo`, the struct tree (its ActualText can hold text), bookmarks, attachments, document JavaScript and
|
`/Rotate 0`). The page's old annotations go, fields that lived only there go, resources inherited from the page
|
||||||
non-destination open actions. Hidden layers (`/OCProperties`) go when no remaining page uses them; otherwise they
|
tree are pushed down to the pages that use them, and the document loses `/Info`, every `/Metadata` and
|
||||||
stay and the result carries a warning naming those pages. Then every unreferenced object is pruned and the file is
|
`/PieceInfo`, the struct tree (its ActualText can hold text), bookmarks, attachments, document JavaScript and
|
||||||
written fresh (no incremental history). The other pages' objects are written back byte for byte.
|
non-destination open actions. Hidden layers (`/OCProperties`) go when no remaining page uses them; otherwise they
|
||||||
|
stay and the result carries a warning naming those pages. Then every unreferenced object is pruned and the file is
|
||||||
Cost: the text of a redacted page is no longer selectable or searchable. A content-stream rewrite (cutting out only
|
written fresh (no incremental history). The other pages' objects are written back byte for byte.
|
||||||
what is under the box) was not used: it needs a full content-stream interpreter (fonts and glyph positions, form
|
|
||||||
XObjects, inline images, clipping, shadings, Type 3 fonts), and any gap leaves text behind. The tests
|
Cost: the text of a redacted page is no longer selectable or searchable. A content-stream rewrite (cutting out only
|
||||||
(`crates/pdf/tests/redaction.rs`) check pdfium text extraction, a lopdf scan of every string, name and stream (raw
|
what is under the box) was not used: it needs a full content-stream interpreter (fonts and glyph positions, form
|
||||||
and decompressed), and a raw byte grep.
|
XObjects, inline images, clipping, shadings, Type 3 fonts), and any gap leaves text behind. The tests
|
||||||
|
(`crates/pdf/tests/redaction.rs`) check pdfium text extraction, a lopdf scan of every string, name and stream (raw
|
||||||
## The worker protocol (crates/worker), version 1
|
and decompressed), and a raw byte grep.
|
||||||
|
|
||||||
`pictor-worker.exe` reads one JSON object per line on stdin and answers one per line on stdout. Its first line is
|
## The worker protocol (crates/worker), version 1
|
||||||
`{"hello": "pictor-worker", "protocol": 1, "version": "0.1.0"}`; the client refuses another protocol.
|
|
||||||
|
`pictor-worker.exe` reads one JSON object per line on stdin and answers one per line on stdout. Its first line is
|
||||||
```
|
`{"hello": "pictor-worker", "protocol": 1, "version": "0.1.0"}`; the client refuses another protocol.
|
||||||
→ {"id": 7, "op": "pdf.render", "args": {"doc": 1, "page": 0, "width": 1200}}
|
|
||||||
← {"id": 7, "ok": {"png": "<base64>", "width": 1200, "height": 1553}}
|
```
|
||||||
← {"id": 7, "err": {"kind": "needs_password", "message": "This PDF is password-protected. Enter its password to open it."}}
|
→ {"id": 7, "op": "pdf.render", "args": {"doc": 1, "page": 0, "width": 1200}}
|
||||||
```
|
← {"id": 7, "ok": {"png": "<base64>", "width": 1200, "height": 1553}}
|
||||||
|
← {"id": 7, "err": {"kind": "needs_password", "message": "This PDF is password-protected. Enter its password to open it."}}
|
||||||
Error kinds: `needs_password`, `wrong_password`, `damaged`, `unsupported`, `too_large`, `codec_missing`, `invalid`,
|
```
|
||||||
`io`, `exists`, `not_open`, `cannot_reach_target`, `engine_missing`; the client adds `timed_out`,
|
|
||||||
`out_of_memory`, `crashed` and `spawn`. `message` is a plain sentence for the user.
|
Error kinds: `needs_password`, `wrong_password`, `damaged`, `unsupported`, `too_large`, `codec_missing`, `invalid`,
|
||||||
|
`io`, `exists`, `not_open`, `cannot_reach_target`, `engine_missing`; the client adds `timed_out`,
|
||||||
| Operation | Arguments | Result |
|
`out_of_memory`, `crashed` and `spawn`. `message` is a plain sentence for the user.
|
||||||
| :-- | :-- | :-- |
|
|
||||||
| `pdf.open` | `path`, `password?` | `doc` (a session id), `info` (pages with sizes and labels, outline, `has_form`) |
|
| Operation | Arguments | Result |
|
||||||
| `pdf.close` | `doc` | — |
|
| :-- | :-- | :-- |
|
||||||
| `pdf.render` | `doc`, `page`, `width` (px) | `png` (base64), `width`, `height` |
|
| `pdf.open` | `path`, `password?` | `doc` (a session id), `info` (pages with sizes and labels, outline, `has_form`) |
|
||||||
| `pdf.text` | `doc` | `pages`: text per page |
|
| `pdf.close` | `doc` | — |
|
||||||
| `pdf.search` | `doc`, `query` | `hits`: `{page, rects}` in view space (max 2000) |
|
| `pdf.render` | `doc`, `page`, `width` (px) | `png` (base64), `width`, `height` |
|
||||||
| `pdf.form` | `doc` | `fields`: name, kind, value, options, page, rect, read_only, multiline |
|
| `pdf.text` | `doc` | `pages`: text per page |
|
||||||
| `pdf.save` | `doc`, `edits` (see `pictor_pdf::Edits`), `output`, `mode` (`new` / `overwrite`) | `path`, `bytes`, `bak?`, `warnings` |
|
| `pdf.search` | `doc`, `query` | `hits`: `{page, rects}` in view space (max 2000) |
|
||||||
| `pdf.extract` | `doc`, `pages`, `output` | `path` |
|
| `pdf.form` | `doc` | `fields`: name, kind, value, options, page, rect, read_only, multiline |
|
||||||
| `pdf.to_images` | `doc`, `pages`, `dpi`, `format`, `output` (with `{n}`) | `paths` |
|
| `pdf.save` | `doc`, `edits` (see `pictor_pdf::Edits`), `output`, `mode` (`new` / `overwrite`) | `path`, `bytes`, `bak?`, `warnings` |
|
||||||
| `pdf.merge` | `inputs` [{`path`, `password?`}], `output` | `path` |
|
| `pdf.extract` | `doc`, `pages`, `output` | `path` |
|
||||||
| `pdf.split` | `path`, `password?`, `ranges` ("1-3, 5, 8-"), `output` (with `{n}`) | `paths` |
|
| `pdf.compress` | `doc`, `preset` (`email` ≤ 5 MB / `web` / `print`), `output` | `path`, `before`, `after`, `images_changed`, `warnings` |
|
||||||
| `pdf.from_images` | `inputs`, `output`, `fit` (`image`/`a4`/`letter`), `margin` | `path` |
|
| `pdf.to_word` | `doc`, `output` (.docx), `ocr?` ({page: text} for scanned pages) | `path`, `pages`, `scanned_pages` |
|
||||||
| `image.probe` | `path` | `format`, `width`, `height`, `has_alpha`, `frames`, `bytes` |
|
| `pdf.page_png` | `doc`, `page`, `dpi`, `output` | `path` (a page for OCR) |
|
||||||
| `image.thumb` | `path`, `max` | `png`, original `width`, `height` |
|
| `pdf.to_images` | `doc`, `pages`, `dpi`, `format`, `output` (with `{n}`) | `paths` |
|
||||||
| `image.convert` | `input`, `output`, `format`, `quality?`, `crop?`, `rotate?`, `resize?`, `preset?`, `target_bytes?`, `overwrite?` | `path`, `bytes`, `format`, `width`, `height` |
|
| `pdf.merge` | `inputs` [{`path`, `password?`}], `output` | `path` |
|
||||||
| `image.heif_support` | — | `support` |
|
| `pdf.split` | `path`, `password?`, `ranges` ("1-3, 5, 8-"), `output` (with `{n}`) | `paths` |
|
||||||
| `meta.read` | `path` | `report` (items by group), `groups` (with labels) |
|
| `pdf.from_images` | `inputs`, `output`, `fit` (`image`/`a4`/`letter`), `margin` | `path` |
|
||||||
| `meta.strip` | `input`, `output`, `overwrite?` | `path`, `removed` |
|
| `image.probe` | `path` | `format`, `width`, `height`, `has_alpha`, `frames`, `bytes` |
|
||||||
| `qr.render` | `payload`, `level`, `style`, `logo?` (a path) | `png`, `svg`, `level_used`, `size`, `text` |
|
| `image.thumb` | `path`, `max` | `png`, original `width`, `height` |
|
||||||
|
| `image.convert` | `input`, `output`, `format`, `quality?`, `crop?`, `rotate?`, `resize?`, `preset?`, `target_bytes?`, `overwrite?` | `path`, `bytes`, `format`, `width`, `height` |
|
||||||
Saving: `mode: new` refuses to replace a file (the app picks `<name>-edited.pdf`); `overwrite` writes
|
| `image.heif_support` | — | `support` |
|
||||||
`<file>.bak` first, then replaces the file in one rename (`crates/save`).
|
| `meta.read` | `path` | `report` (items by group), `groups` (with labels) |
|
||||||
|
| `meta.strip` | `input`, `output`, `overwrite?` | `path`, `removed` |
|
||||||
Caps: files over 1 GB are refused; the client runs the worker in a Job Object (2 GB by default, killed with the
|
| `qr.render` | `payload`, `level`, `style`, `logo?` (a path) | `png`, `svg`, `level_used`, `size`, `text` |
|
||||||
app) and gives each request a time cap; a worker that hangs or dies is replaced on the next request (open documents
|
|
||||||
must then be opened again).
|
Saving: `mode: new` refuses to replace a file (the app picks `<name>-edited.pdf`); `overwrite` writes
|
||||||
|
`<file>.bak` first, then replaces the file in one rename (`crates/save`).
|
||||||
|
|
||||||
|
Caps: files over 1 GB are refused; the client runs the worker in a Job Object (2 GB by default, killed with the
|
||||||
|
app) and gives each request a time cap; a worker that hangs or dies is replaced on the next request (open documents
|
||||||
|
must then be opened again).
|
||||||
|
|||||||
+4
-3
@@ -32,11 +32,12 @@ export function allowed(expr) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function main() {
|
function main() {
|
||||||
const meta = JSON.parse(execFileSync('cargo', ['metadata', '--format-version', '1', '--locked', '--filter-platform', 'x86_64-pc-windows-msvc'], {
|
// Every package in Cargo.lock (all platforms): a crate that is locked must be listed, whatever it is built for.
|
||||||
|
const meta = JSON.parse(execFileSync('cargo', ['metadata', '--format-version', '1', '--locked'], {
|
||||||
cwd: root, maxBuffer: 1 << 28, encoding: 'utf8',
|
cwd: root, maxBuffer: 1 << 28, encoding: 'utf8',
|
||||||
}));
|
}));
|
||||||
// Only crates reachable on Windows x64 (the one target of V1), not every lockfile entry of every platform:
|
// resolve.nodes lists every package the lockfile resolves (all targets).
|
||||||
// with --filter-platform, resolve.nodes lists what the workspace really depends on there.
|
|
||||||
const used = new Set(meta.resolve.nodes.map((n) => n.id));
|
const used = new Set(meta.resolve.nodes.map((n) => n.id));
|
||||||
const workspace = new Set(meta.workspace_members);
|
const workspace = new Set(meta.workspace_members);
|
||||||
const rows = meta.packages
|
const rows = meta.packages
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
// The licence rule's SPDX evaluator (scripts/deps.mjs). Run: node --test scripts/deps.test.mjs
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { allowed } from './deps.mjs';
|
||||||
|
|
||||||
|
test('the allowed licences pass', () => {
|
||||||
|
for (const l of ['MIT', 'Apache-2.0', 'BSD-3-Clause', 'Zlib', 'MPL-2.0', 'ISC', 'Unicode-3.0', 'MIT OR Apache-2.0', 'MIT/Apache-2.0', '(MIT OR Apache-2.0) AND Unicode-3.0', 'Apache-2.0 WITH LLVM-exception'])
|
||||||
|
assert.ok(allowed(l), l);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('copyleft, non-commercial and missing licences fail', () => {
|
||||||
|
for (const l of ['GPL-3.0', 'AGPL-3.0-only', 'LGPL-2.1', 'CC-BY-NC-4.0', 'MIT AND GPL-2.0', '', undefined, 'SSPL-1.0', 'OpenSSL'])
|
||||||
|
assert.equal(allowed(l), false, String(l));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('OR needs one allowed branch, AND needs all', () => {
|
||||||
|
assert.ok(allowed('GPL-2.0 OR MIT'));
|
||||||
|
assert.equal(allowed('GPL-2.0 AND MIT'), false);
|
||||||
|
assert.ok(allowed('(GPL-2.0 OR MIT) AND Apache-2.0'));
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user