Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

M11.1: PDF Optimizer: new optimize crate measures each image's effective resolution where pages draw it and resamples (bicubic) and recompresses (JPEG quality steps or ZIP) colour and grayscale images, soft masks with them, only when smaller; discards thumbnails, alternate images, tags and print settings; Flate for unencoded streams. Reduce File Size now downsamples like Acrobat (150 ppi above 225, JPEG medium); Optimize PDF dialog (Images, Discard Objects, Discard User Data, Clean Up) composes Remove Hidden Information; doc_optimize tool (84 tools)

Brandon Thomas9fcece8afbe9
diff --git a/Cargo.lock b/Cargo.lock
index ba7b33c2d..51fa735f3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3349,6 +3349,7 @@ name = "printcraft-automation"
version = "0.1.0"
dependencies = [
"base64",
+ "image",
"png 0.18.1",
"printcraft-engine",
"printcraft-organize",
@@ -3438,6 +3439,7 @@ dependencies = [
"printcraft-edit",
"printcraft-forms",
"printcraft-model",
+ "printcraft-optimize",
"printcraft-organize",
"printcraft-print",
"printcraft-redact",
@@ -3482,6 +3484,18 @@ dependencies = [
"printcraft-cos",
]
+[[package]]
+name = "printcraft-optimize"
+version = "0.1.0"
+dependencies = [
+ "image",
+ "printcraft-annot",
+ "printcraft-content",
+ "printcraft-cos",
+ "printcraft-render",
+ "thiserror 2.0.21",
+]
+
[[package]]
name = "printcraft-organize"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index 6255bbdc8..303ea7aaf 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -26,6 +26,7 @@ printcraft-redact = { path = "crates/redact", version = "0.1.0" }
printcraft-print = { path = "crates/print", version = "0.1.0" }
printcraft-xfdf = { path = "crates/xfdf", version = "0.1.0" }
printcraft-sign = { path = "crates/sign", version = "0.1.0" }
+printcraft-optimize = { path = "crates/optimize", version = "0.1.0" }
printcraft-edit = { path = "crates/edit", version = "0.1.0" }
printcraft-create = { path = "crates/create", version = "0.1.0" }
printcraft-forms = { path = "crates/forms", version = "0.1.0" }
diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml
index a25612a3f..7d59e1526 100644
--- a/crates/automation/Cargo.toml
+++ b/crates/automation/Cargo.toml
@@ -21,3 +21,6 @@ base64 = { version = "0.22", optional = true }
default = ["mcp"]
# The MCP server module. Opt-in at run time either way; disable to leave it out of the build.
mcp = ["dep:base64"]
+
+[dev-dependencies]
+image = { version = "0.25", default-features = false, features = ["jpeg"] }
diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs
index ebc4b3fe3..320382356 100644
--- a/crates/automation/src/lib.rs
+++ b/crates/automation/src/lib.rs
@@ -271,6 +271,7 @@ impl Automation {
write_atomic(&path, &bytes)?;
json!({ "path": path.to_string_lossy(), "bytes_before": before, "bytes_after": bytes.len(), "merged_objects": merged })
}
+ "doc_optimize" => self.doc_optimize(&a)?,
"doc_export_images" | "doc_export_text" => self.export(name, &a)?,
"doc_header_footer" | "doc_watermark" | "doc_background" | "doc_remove_marks" => self.marks(name, &a)?,
"doc_unprotect" => {
@@ -371,6 +372,83 @@ impl Automation {
Ok(json!({ "path": path, "bytes": bytes.len(), "incremental": !full, "document": summary(self.doc(a)?) }))
}
+ fn doc_optimize(&mut self, a: &Args) -> Result<Value> {
+ use printcraft_engine::optimize::{Compression, ImageSettings, Settings};
+ let id = self.doc(a)?.id;
+ let before = self.doc(a)?.bytes.len();
+ let path = self.resolve(a.str("path")?, true)?;
+ let mut settings = Settings::default();
+ let images = |key: &str, base: ImageSettings| -> Result<ImageSettings> {
+ let Some(v) = a.get(key) else { return Ok(base) };
+ let mut s = base;
+ if let Some(d) = v.get("downsample").and_then(Value::as_bool) {
+ s.downsample = d;
+ }
+ if let Some(p) = v.get("ppi").and_then(Value::as_f64) {
+ s.target_ppi = p.clamp(9.0, 2400.0);
+ }
+ if let Some(p) = v.get("above_ppi").and_then(Value::as_f64) {
+ s.above_ppi = p.clamp(9.0, 2400.0);
+ }
+ s.above_ppi = s.above_ppi.max(s.target_ppi);
+ if let Some(c) = v.get("compression").and_then(Value::as_str) {
+ let q = v.get("quality").and_then(Value::as_u64).unwrap_or(60).clamp(1, 100) as u8;
+ s.compression = match c {
+ "jpeg" => Compression::Jpeg(q),
+ "zip" | "flate" => Compression::Flate,
+ "retain" => Compression::Retain,
+ other => return Err(ToolError::InvalidArgs(format!("unknown compression {other:?} (jpeg, zip, retain)"))),
+ };
+ }
+ Ok(s)
+ };
+ settings.color = images("color", settings.color)?;
+ settings.gray = images("gray", settings.gray)?;
+ for (key, flag) in [
+ ("discard_thumbnails", &mut settings.discard_thumbnails),
+ ("discard_alternate_images", &mut settings.discard_alternate_images),
+ ("discard_tags", &mut settings.discard_tags),
+ ("discard_print_settings", &mut settings.discard_print_settings),
+ ("flate_unencoded", &mut settings.flate_unencoded),
+ ] {
+ if let Some(b) = a.opt_bool(key)? {
+ *flag = b;
+ }
+ }
+ let discard: Vec<printcraft_engine::Hidden> = match a.get("discard") {
+ None => Vec::new(),
+ Some(v) => v
+ .as_array()
+ .ok_or_else(|| ToolError::InvalidArgs("discard must be an array".into()))?
+ .iter()
+ .map(|x| {
+ x.as_str()
+ .and_then(printcraft_engine::Hidden::from_id)
+ .ok_or_else(|| ToolError::InvalidArgs(format!("unknown discard category {x}")))
+ })
+ .collect::<Result<_>>()?,
+ };
+ let (bytes, r) = self.session.optimized_bytes(id, &settings, &discard).map_err(failed)?;
+ write_atomic(&path, &bytes)?;
+ let o = &r.optimize;
+ Ok(json!({
+ "path": path.to_string_lossy(),
+ "bytes_before": before,
+ "bytes_after": bytes.len(),
+ "images": o.images,
+ "images_resampled": o.images_resampled,
+ "images_recompressed": o.images_recompressed,
+ "image_bytes_before": o.image_bytes_before,
+ "image_bytes_after": o.image_bytes_after,
+ "thumbnails": o.thumbnails,
+ "alternate_images": o.alternate_images,
+ "tags_removed": o.tags_removed,
+ "streams_compressed": o.streams_compressed,
+ "merged_objects": r.merged,
+ "discarded": r.discarded.iter().map(|(h, n)| json!({ "category": h.id(), "count": n })).collect::<Vec<_>>(),
+ }))
+ }
+
fn apply(&mut self, a: &Args, edit: Edit) -> Result<Value> {
let id = self.doc(a)?.id;
self.session.apply(id, edit).map_err(failed)?;
diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs
index fcce5d605..6d741f626 100644
--- a/crates/automation/src/tools.rs
+++ b/crates/automation/src/tools.rs
@@ -697,9 +697,26 @@ pub fn tools() -> Vec<ToolDef> {
}),
&["from"],
)),
- t("doc_reduce", "Reduce file size", "Write a compacted copy of the document to `path` (identical fonts and images merged, unused objects dropped, compressed object streams). The open document is unchanged.")
+ t("doc_reduce", "Reduce file size", "Write a smaller copy of the document to `path` with Acrobat's Reduce File Size choices: images above 225 ppi downsampled to 150 ppi and JPEG-compressed (medium quality), thumbnails dropped, identical fonts and images merged, unused objects dropped, compressed object streams. The open document is unchanged.")
.cmd("optimize.reduce")
.with(schema(json!({ "doc": doc(), "path": { "type": "string" } }), &["doc", "path"])),
+ t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). color / gray: { downsample, ppi, above_ppi, compression: jpeg|zip|retain, quality 1–100 } (defaults: downsample to 150 ppi above 225, JPEG 60). Images are measured where pages draw them and replaced only when smaller. discard_*: thumbnails (default true), alternate_images (true), tags, print_settings; flate_unencoded (true). discard: Remove Hidden Information categories (metadata, attachments, comments, form-fields, hidden-text, hidden-layers, bookmarks, links-actions-scripts, private-data). Signed documents are refused. The open document is unchanged.")
+ .cmd("optimize.advanced")
+ .with(schema(
+ json!({
+ "doc": doc(),
+ "path": { "type": "string" },
+ "color": { "type": "object" },
+ "gray": { "type": "object" },
+ "discard_thumbnails": { "type": "boolean" },
+ "discard_alternate_images": { "type": "boolean" },
+ "discard_tags": { "type": "boolean" },
+ "discard_print_settings": { "type": "boolean" },
+ "flate_unencoded": { "type": "boolean" },
+ "discard": { "type": "array", "items": { "type": "string" } },
+ }),
+ &["doc", "path"],
+ )),
t("doc_flatten", "Flatten", "Merge comment and/or form field appearances into the page content, so they print and display everywhere but can no longer be edited. Undoable until saved.")
.destructive()
.with(schema(json!({ "doc": doc(), "comments": { "type": "boolean", "description": "Default true." }, "fields": { "type": "boolean", "description": "Default true." } }), &["doc"])),
diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rs
index e8a4b32e1..a021e07c5 100644
--- a/crates/automation/tests/automation.rs
+++ b/crates/automation/tests/automation.rs
@@ -985,3 +985,41 @@ fn digital_ids_signing_and_validation_through_tools() {
assert_eq!(ok(&mut a, "sign_trust", json!({ "clear": true }))["trusted"].as_array().unwrap().len(), 0);
assert_eq!(ok(&mut a, "sign_list", json!({ "doc": doc }))["signatures"][0]["status"], "unknown");
}
+
+#[test]
+fn optimizing_through_tools() {
+ let dir = workdir("optimize");
+ // A 2400 × 1600 photo-like JPEG at 600 dpi: a 4 × 2.67 inch page.
+ let (w, h) = (2400u32, 1600u32);
+ let px: Vec<u8> = (0..w * h)
+ .flat_map(|i| {
+ let (x, y) = (i % w, i / w);
+ [(x * 255 / w) as u8 ^ ((x * y) & 15) as u8, (y * 255 / h) as u8, ((x + y) & 255) as u8]
+ })
+ .collect();
+ let mut jpeg = Vec::new();
+ let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 95);
+ enc.set_pixel_density(image::codecs::jpeg::PixelDensity::dpi(600));
+ enc.encode(&px, w, h, image::ExtendedColorType::Rgb8).unwrap();
+ std::fs::write(dir.join("photo.jpg"), &jpeg).unwrap();
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_create", json!({ "from": "images", "paths": ["photo.jpg"] }))["doc"].as_u64().unwrap();
+ let r = ok(
+ &mut a,
+ "doc_optimize",
+ json!({ "doc": doc, "path": "small.pdf", "color": { "ppi": 100, "above_ppi": 150, "compression": "jpeg", "quality": 45 }, "discard": ["metadata"] }),
+ );
+ assert_eq!((r["images"].as_u64(), r["images_resampled"].as_u64()), (Some(1), Some(1)), "{r}");
+ assert!(r["bytes_after"].as_u64().unwrap() * 5 < r["bytes_before"].as_u64().unwrap(), "{r}");
+ assert_eq!(r["discarded"][0]["category"], "metadata");
+ // The result opens and shows one page of the same size.
+ let small = ok(&mut a, "doc_open", json!({ "path": "small.pdf" }));
+ assert_eq!(small["pages"], 1);
+ let reduced = ok(&mut a, "doc_reduce", json!({ "doc": doc, "path": "reduced.pdf" }));
+ assert!(reduced["bytes_after"].as_u64().unwrap() < reduced["bytes_before"].as_u64().unwrap());
+ assert!(matches!(
+ a.call("doc_optimize", &json!({ "doc": doc, "path": "x.pdf", "color": { "compression": "gif" } })),
+ Err(ToolError::InvalidArgs(_))
+ ));
+ assert!(matches!(a.call("doc_optimize", &json!({ "doc": doc, "path": "x.pdf", "discard": ["everything"] })), Err(ToolError::InvalidArgs(_))));
+}
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index 56f05fc91..5d29f1c6e 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -20,6 +20,7 @@ printcraft-redact = { workspace = true }
printcraft-print = { workspace = true }
printcraft-xfdf = { workspace = true }
printcraft-sign = { workspace = true }
+printcraft-optimize = { workspace = true }
printcraft-create = { workspace = true }
printcraft-model = { workspace = true }
thiserror = { workspace = true }
diff --git a/crates/engine/src/catalog.rs b/crates/engine/src/catalog.rs
index f1d392384..d6e68a4cc 100644
--- a/crates/engine/src/catalog.rs
+++ b/crates/engine/src/catalog.rs
@@ -296,12 +296,12 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[
icon: "file-down",
hue: RED,
badge: None,
- availability: Planned("M11"),
+ availability: Ready,
sections: &[ToolSection {
title: "Optimize",
items: &[
item("Reduce file size", "file-down", "optimize.reduce", Ready),
- item("Advanced optimization", "settings-2", "optimize.advanced", Planned("M11")),
+ item("Advanced optimization", "settings-2", "optimize.advanced", Ready),
item("Audit space usage", "gauge", "optimize.audit", Planned("M11")),
],
}],
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 7d6d280f7..1a8cb6a45 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -233,6 +233,7 @@ pub const COMMANDS: &[CommandSpec] = &[
c("sign.fill.signature", "Fill & Sign: sign", None, None, Annotate, "signature"),
c("export.image", "Export to image…", FILE, None, Document, "image"),
c("optimize.reduce", "Reduce file size…", FILE, None, Document, "file-down"),
+ c("optimize.advanced", "Optimize PDF…", FILE, None, Document, "settings-2"),
c("export.text", "Export to text…", FILE, None, Document, "type"),
c("edit.header_footer", "Add header & footer…", None, None, Modification, "heading"),
c("edit.header_footer.update", "Update header & footer…", None, None, Marks(crate::MarkKind::HeaderFooter), "heading"),
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index da3cd794c..f25b91757 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -35,6 +35,7 @@ pub use printcraft_annot::links::{Highlight as LinkHighlight, LinkAction, LinkIt
pub use printcraft_annot::{
FillMark, Markup, NewAnnotation, NoteIcon, Props as CommentProps, ReviewState, Rgb, Shape, StampGroup, StampKind, Style, rect_quad,
};
+pub use printcraft_optimize as optimize;
pub use printcraft_print as print;
pub use printcraft_redact::patterns::{PATTERNS as REDACT_PATTERNS, Pattern as RedactPattern, find as find_pattern};
pub use printcraft_redact::sanitize::{HIDDEN, Hidden};
@@ -1240,6 +1241,8 @@ pub enum EditError {
NothingToRedo,
#[error("{0}")]
Sign(String),
+ #[error("{0}")]
+ Optimize(String),
#[error("this document is signed: rewriting it would invalidate its signatures (save it incrementally instead)")]
Signed,
}
@@ -1608,18 +1611,32 @@ impl Session {
self.write_new(&printcraft_create::from_text(title, text, printcraft_create::LETTER, 11.0)?)
}
- /// Reduce File Size: identical resources merged, unused objects dropped, objects packed
- /// into compressed object streams. Returns the bytes and how many objects were merged.
- /// The open document is not changed (Acrobat saves the reduced copy as a new file).
+ /// Reduce File Size: Acrobat's defaults (images above 225 ppi to 150 ppi, JPEG medium
+ /// quality; thumbnails dropped), identical resources merged, unused objects dropped, objects
+ /// packed into compressed object streams. Returns the bytes and how many objects were
+ /// merged. The open document is not changed (Acrobat saves the reduced copy as a new file).
pub fn reduced_bytes(&self, id: DocId) -> Result<(Arc<Vec<u8>>, usize), EditError> {
+ let (bytes, report) = self.optimized_bytes(id, &optimize::Settings::default(), &[])?;
+ Ok((bytes, report.merged))
+ }
+
+ /// Optimize PDF ▸ Advanced optimization: `settings` for images and objects, plus Remove
+ /// Hidden Information's `discard` categories (user data). A full rewrite: signed documents
+ /// are refused. The open document is not changed.
+ pub fn optimized_bytes(&self, id: DocId, settings: &optimize::Settings, discard: &[Hidden]) -> Result<(Arc<Vec<u8>>, OptimizeReport), EditError> {
let doc = self.get(id).ok_or(EditError::NoDocument)?;
+ if doc.is_signed() {
+ return Err(EditError::Signed);
+ }
let editor = doc.editor.as_ref().ok_or_else(|| EditError::ReadOnly(doc.read_only_reason.clone().unwrap_or_default()))?;
let mut cos = editor.cos.clone();
+ let discarded = if discard.is_empty() { Vec::new() } else { printcraft_redact::sanitize::remove_hidden(&mut cos, discard)? };
+ let report = optimize::optimize(&mut cos, settings).map_err(|e| EditError::Optimize(e.to_string()))?;
let all: Vec<printcraft_cos::ObjRef> = cos.object_numbers().into_iter().map(|n| printcraft_cos::ObjRef::new(n, cos.generation(n))).collect();
let merged = printcraft_organize::dedupe_resources(&mut cos, &all, false);
let opts = SaveOptions { mod_date: self.now().map(printcraft_cos::pdf_date), ..SaveOptions::default() };
let bytes = write_full(&cos, &opts).map_err(|e| EditError::Write(e.to_string()))?;
- Ok((Arc::new(bytes), merged))
+ Ok((Arc::new(bytes), OptimizeReport { optimize: report, merged, discarded }))
}
/// Export comments and/or form data: XFDF and FDF carry either or both; XML, CSV and text
@@ -1913,6 +1930,16 @@ impl Session {
}
}
+/// What Optimize PDF did.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct OptimizeReport {
+ pub optimize: optimize::Report,
+ /// Identical objects merged.
+ pub merged: usize,
+ /// Remove Hidden Information categories discarded, with counts.
+ pub discarded: Vec<(Hidden, usize)>,
+}
+
/// Order of Summarize Comments.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SummarySort {
diff --git a/crates/optimize/Cargo.toml b/crates/optimize/Cargo.toml
new file mode 100644
index 000000000..ebb619439
--- /dev/null
+++ b/crates/optimize/Cargo.toml
@@ -0,0 +1,22 @@
+[package]
+name = "printcraft-optimize"
+description = "The PDF Optimizer: image downsampling and recompression, discarding objects, clean-up"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+repository.workspace = true
+
+[lints]
+workspace = true
+
+[dependencies]
+printcraft-cos = { workspace = true }
+printcraft-content = { workspace = true }
+printcraft-annot = { workspace = true }
+thiserror.workspace = true
+# JPEG decoding (zune-jpeg) and encoding, and bicubic resampling; already in the tree.
+image = { version = "0.25", default-features = false, features = ["jpeg"] }
+
+[dev-dependencies]
+printcraft-render = { workspace = true }
diff --git a/crates/optimize/README.md b/crates/optimize/README.md
new file mode 100644
index 000000000..5d984d901
--- /dev/null
+++ b/crates/optimize/README.md
@@ -0,0 +1,21 @@
+# printcraft-optimize
+
+Layer L4: the PDF Optimizer (execution plan M11.1; Acrobat's Reduce File Size and Optimize PDF ▸
+Advanced optimization).
+
+```rust
+let report = optimize(&mut doc, &Settings::default())?; // Reduce File Size's choices
+```
+
+- **Images:** the effective resolution of each image is measured where pages draw it (the CTM
+ through form XObjects; the smallest over all uses). Colour and grayscale images above a
+ threshold are resampled with a bicubic (Catmull-Rom) filter to a target resolution and
+ stored as JPEG (Acrobat's quality steps) or ZIP; soft masks are resampled with their image.
+ An image is replaced only if the result is smaller. Left alone: CMYK and other colour spaces,
+ image masks, decode arrays, more than 8 bits, JPEG 2000, JBIG2 and CCITT.
+- **Discard objects:** thumbnails, alternate images, document tags, print settings.
+- **Clean up:** Flate for streams with no filter.
+
+The engine runs Remove Hidden Information (`printcraft-redact`) for the user-data categories,
+then this, then merges identical objects and writes a full, compressed save. JPEG decoding and
+encoding and resampling come from the `image` crate.
diff --git a/crates/optimize/src/images.rs b/crates/optimize/src/images.rs
new file mode 100644
index 000000000..7b6a275f7
--- /dev/null
+++ b/crates/optimize/src/images.rs
@@ -0,0 +1,328 @@
+//! Image resampling and recompression.
+
+use std::collections::{HashMap, HashSet};
+
+use printcraft_content::Matrix;
+use printcraft_cos::{Dict, Document, ObjRef, Object, Stream};
+
+use crate::{Compression, ImageSettings, OptimizeError, Report, Settings};
+
+/// Images with more pixels than this are left alone (memory).
+const MAX_PIXELS: u64 = 80_000_000;
+
+/// The resources of a page, inherited from the page tree if the page has none.
+fn page_resources(doc: &Document, page: ObjRef) -> Option<Dict> {
+ let mut node = Some(page);
+ for _ in 0..64 {
+ let d = doc.get(node?).as_dict()?.clone();
+ if let Some(r) = d.get(b"Resources") {
+ return doc.resolve(r).as_dict().cloned();
+ }
+ node = d.reference(b"Parent");
+ }
+ None
+}
+
+fn content_bytes(doc: &Document, contents: &Object) -> Vec<u8> {
+ match &*doc.resolve(contents) {
+ Object::Stream(s) => s.decoded().unwrap_or_default(),
+ Object::Array(a) => a
+ .iter()
+ .flat_map(|c| match &*doc.resolve(c) {
+ Object::Stream(s) => {
+ let mut v = s.decoded().unwrap_or_default();
+ v.push(b'\n');
+ v
+ }
+ _ => Vec::new(),
+ })
+ .collect(),
+ _ => Vec::new(),
+ }
+}
+
+/// Walk one content stream, recording each image's displayed resolution (pixels per inch, the
+/// smaller of the two axes) and descending into form XObjects.
+fn walk(doc: &Document, data: &[u8], resources: &Dict, ctm: Matrix, depth: usize, seen: &mut HashSet<ObjRef>, out: &mut HashMap<ObjRef, f64>) {
+ if depth > 12 {
+ return;
+ }
+ let xobjects = resources.get(b"XObject").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default();
+ let mut stack = vec![ctm];
+ for op in printcraft_content::parse(data).ops {
+ let top = *stack.last().expect("never empty");
+ match op.op.as_slice() {
+ b"q" => stack.push(top),
+ b"Q" => {
+ if stack.len() > 1 {
+ stack.pop();
+ }
+ }
+ b"cm" => {
+ if let Some(m) = Matrix::from_operands(&op.operands) {
+ *stack.last_mut().expect("never empty") = m.then(&top);
+ }
+ }
+ b"Do" => {
+ let Some(name) = op.name(0) else { continue };
+ let Some(r) = xobjects.get(name).and_then(Object::as_ref) else { continue };
+ let obj = doc.get(r);
+ let Object::Stream(s) = &*obj else { continue };
+ match s.dict.name(b"Subtype") {
+ Some(b"Image") => {
+ let (w, h) = (s.dict.int(b"Width").unwrap_or(0) as f64, s.dict.int(b"Height").unwrap_or(0) as f64);
+ let [a, b, c, d, ..] = top.0;
+ let (sx, sy) = ((a * a + b * b).sqrt(), (c * c + d * d).sqrt());
+ if w > 0.0 && h > 0.0 && sx > 1e-6 && sy > 1e-6 {
+ let ppi = (w / (sx / 72.0)).min(h / (sy / 72.0));
+ let e = out.entry(r).or_insert(f64::INFINITY);
+ *e = e.min(ppi);
+ }
+ }
+ Some(b"Form") => {
+ if !seen.insert(r) && depth > 4 {
+ continue;
+ }
+ let m = s.dict.get(b"Matrix").map(|m| doc.resolve(m)).and_then(|m| m.as_array().map(|a| Matrix::from_operands(a))).flatten();
+ let res =
+ s.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_else(|| resources.clone());
+ let inner = m.unwrap_or(Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0])).then(&top);
+ walk(doc, &s.decoded().unwrap_or_default(), &res, inner, depth + 1, seen, out);
+ }
+ _ => {}
+ }
+ }
+ _ => {}
+ }
+ }
+}
+
+/// The effective resolution (ppi) of every image drawn by `pages`: the smallest over its uses.
+pub fn effective_resolutions(doc: &Document, pages: &[ObjRef]) -> HashMap<ObjRef, f64> {
+ let mut out = HashMap::new();
+ let mut seen = HashSet::new();
+ for p in pages {
+ let Some(d) = doc.get(*p).as_dict().cloned() else { continue };
+ let Some(contents) = d.get(b"Contents") else { continue };
+ let res = page_resources(doc, *p).unwrap_or_default();
+ walk(doc, &content_bytes(doc, contents), &res, Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]), 0, &mut seen, &mut out);
+ }
+ out
+}
+
+/// Colour components of a colour space PrintCraft resamples: gray (1) or RGB (3).
+fn components(doc: &Document, cs: &Object) -> Option<usize> {
+ let cs = doc.resolve(cs);
+ match &*cs {
+ Object::Name(n) => match n.as_slice() {
+ b"DeviceGray" | b"G" => Some(1),
+ b"DeviceRGB" | b"RGB" => Some(3),
+ _ => None,
+ },
+ Object::Array(a) => match a.first()?.as_name()? {
+ b"ICCBased" => match &*doc.resolve(a.get(1)?) {
+ Object::Stream(icc) => match icc.dict.int(b"N")? {
+ 1 => Some(1),
+ 3 => Some(3),
+ _ => None,
+ },
+ _ => None,
+ },
+ b"CalGray" => Some(1),
+ b"CalRGB" => Some(3),
+ _ => None,
+ },
+ _ => None,
+ }
+}
+
+fn is_dct(s: &Stream) -> Option<bool> {
+ match s.dict.get(b"Filter") {
+ None => Some(false),
+ Some(Object::Name(n)) => match n.as_slice() {
+ b"DCTDecode" | b"DCT" => Some(true),
+ b"FlateDecode" | b"Fl" | b"LZWDecode" | b"LZW" | b"RunLengthDecode" | b"RL" | b"ASCII85Decode" | b"A85" | b"ASCIIHexDecode" | b"AHx" => {
+ Some(false)
+ }
+ _ => None,
+ },
+ Some(Object::Array(a)) => {
+ let names: Vec<&[u8]> = a.iter().filter_map(Object::as_name).collect();
+ if names.len() != a.len() {
+ return None;
+ }
+ match names.as_slice() {
+ [b"DCTDecode" | b"DCT"] => Some(true),
+ n if n.iter().all(|f| {
+ matches!(
+ *f,
+ b"FlateDecode"
+ | b"Fl"
+ | b"LZWDecode"
+ | b"LZW"
+ | b"RunLengthDecode"
+ | b"RL"
+ | b"ASCII85Decode"
+ | b"A85"
+ | b"ASCIIHexDecode"
+ | b"AHx"
+ )
+ }) =>
+ {
+ Some(false)
+ }
+ _ => None,
+ }
+ }
+ _ => None,
+ }
+}
+
+/// 8-bit samples of an image (`n` components), decoded.
+fn pixels(s: &Stream, n: usize) -> Option<Vec<u8>> {
+ let (w, h) = (s.dict.int(b"Width")? as usize, s.dict.int(b"Height")? as usize);
+ if is_dct(s)? {
+ let img = image::load_from_memory_with_format(&s.raw, image::ImageFormat::Jpeg).ok()?;
+ // Adobe CMYK/YCCK JPEGs aren't handled (the colour space check excludes them).
+ let v = if n == 1 { img.into_luma8().into_raw() } else { img.into_rgb8().into_raw() };
+ (v.len() == w * h * n).then_some(v)
+ } else {
+ let v = s.decoded().ok()?;
+ (v.len() >= w * h * n).then(|| v[..w * h * n].to_vec())
+ }
+}
+
+fn resample(px: &[u8], n: usize, w: u32, h: u32, nw: u32, nh: u32) -> Option<Vec<u8>> {
+ use image::imageops::{FilterType, resize};
+ Some(match n {
+ 1 => resize(&image::GrayImage::from_raw(w, h, px.to_vec())?, nw, nh, FilterType::CatmullRom).into_raw(),
+ _ => resize(&image::RgbImage::from_raw(w, h, px.to_vec())?, nw, nh, FilterType::CatmullRom).into_raw(),
+ })
+}
+
+fn jpeg(px: &[u8], n: usize, w: u32, h: u32, quality: u8) -> Option<Vec<u8>> {
+ let mut out = Vec::new();
+ let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, quality.clamp(1, 100));
+ let ty = if n == 1 { image::ExtendedColorType::L8 } else { image::ExtendedColorType::Rgb8 };
+ enc.encode(px, w, h, ty).ok()?;
+ Some(out)
+}
+
+/// A new image stream from 8-bit samples: the original dictionary with the new size and filter.
+fn image_stream(old: &Dict, px: &[u8], n: usize, w: u32, h: u32, compression: Compression, was_dct: bool) -> Option<Stream> {
+ let mut d = old.clone();
+ for k in [&b"Filter"[..], b"DecodeParms", b"Length", b"DL"] {
+ d.remove(k);
+ }
+ d.set(b"Width".to_vec(), Object::Int(w as i64));
+ d.set(b"Height".to_vec(), Object::Int(h as i64));
+ d.set(b"BitsPerComponent".to_vec(), Object::Int(8));
+ let use_jpeg = match compression {
+ Compression::Jpeg(_) => true,
+ Compression::Flate => false,
+ Compression::Retain => was_dct,
+ };
+ if use_jpeg {
+ let q = match compression {
+ Compression::Jpeg(q) => q,
+ _ => 80,
+ };
+ let data = jpeg(px, n, w, h, q)?;
+ d.set(b"Filter".to_vec(), Object::name("DCTDecode"));
+ Some(Stream::from_raw(d, data))
+ } else {
+ Some(Stream::flate(d, px))
+ }
+}
+
+/// One image: resample and/or recompress per `settings`; `ppi` is its effective resolution.
+/// Returns the new image and its new soft mask, if the result is smaller.
+fn process(doc: &Document, s: &Stream, ppi: f64, settings: &ImageSettings, n: usize) -> Option<(Stream, Option<(ObjRef, Stream)>)> {
+ let d = &s.dict;
+ if d.contains(b"Decode") || d.contains(b"Mask") || d.name(b"ImageMask").is_some() || matches!(d.get(b"ImageMask"), Some(Object::Bool(true))) {
+ return None;
+ }
+ if d.int(b"BitsPerComponent") != Some(8) {
+ return None;
+ }
+ let was_dct = is_dct(s)?;
+ let (w, h) = (d.int(b"Width")? as u32, d.int(b"Height")? as u32);
+ if w == 0 || h == 0 || (w as u64) * (h as u64) > MAX_PIXELS {
+ return None;
+ }
+ let resize = settings.downsample && ppi.is_finite() && ppi > settings.above_ppi && settings.target_ppi > 0.0;
+ let recompress = matches!(settings.compression, Compression::Jpeg(_)) || (matches!(settings.compression, Compression::Flate) && was_dct);
+ if !resize && !recompress {
+ return None;
+ }
+ // Tiny images (icons, rules) don't benefit and JPEG would blur them.
+ if !resize && (w as u64) * (h as u64) < 64 * 64 {
+ return None;
+ }
+ let (nw, nh) = if resize {
+ let k = settings.target_ppi / ppi;
+ (((w as f64 * k).round() as u32).max(1), ((h as f64 * k).round() as u32).max(1))
+ } else {
+ (w, h)
+ };
+ let px = pixels(s, n)?;
+ let px = if (nw, nh) != (w, h) { resample(&px, n, w, h, nw, nh)? } else { px };
+ let new = image_stream(d, &px, n, nw, nh, settings.compression, was_dct)?;
+ // A soft mask must keep the image's dimensions: resample it with the image (lossless).
+ let mut smask = None;
+ if let Some(mr) = d.reference(b"SMask") {
+ let mobj = doc.get(mr);
+ let Object::Stream(m) = &*mobj else { return None };
+ if (nw, nh) != (w, h) {
+ if m.dict.int(b"BitsPerComponent") != Some(8) || m.dict.contains(b"Matte") || m.dict.contains(b"Decode") {
+ return None;
+ }
+ let (mw, mh) = (m.dict.int(b"Width")? as u32, m.dict.int(b"Height")? as u32);
+ let mpx = pixels(m, 1)?;
+ let mpx = resample(&mpx, 1, mw, mh, nw, nh)?;
+ smask = Some((mr, image_stream(&m.dict, &mpx, 1, nw, nh, Compression::Flate, false)?));
+ }
+ }
+ let before = s.raw.len()
+ + smask.as_ref().map_or(0, |(r, _)| match &*doc.get(*r) {
+ Object::Stream(m) => m.raw.len(),
+ _ => 0,
+ });
+ let after = new.raw.len() + smask.as_ref().map_or(0, |(_, m)| m.raw.len());
+ (after < before).then_some((new, smask))
+}
+
+pub(crate) fn run(doc: &mut Document, pages: &[ObjRef], settings: &Settings, report: &mut Report) -> Result<(), OptimizeError> {
+ let ppi = effective_resolutions(doc, pages);
+ // Soft masks are processed with their image, not on their own.
+ let masks: HashSet<ObjRef> = ppi
+ .keys()
+ .filter_map(|r| match &*doc.get(*r) {
+ Object::Stream(s) => s.dict.reference(b"SMask"),
+ _ => None,
+ })
+ .collect();
+ let mut refs: Vec<(ObjRef, f64)> = ppi.into_iter().filter(|(r, _)| !masks.contains(r)).collect();
+ refs.sort_by_key(|(r, _)| r.num);
+ for (r, ppi) in refs {
+ let obj = doc.get(r);
+ let Object::Stream(s) = &*obj else { continue };
+ report.images += 1;
+ let Some(n) = s.dict.get(b"ColorSpace").and_then(|cs| components(doc, cs)) else { continue };
+ let st = if n == 1 { &settings.gray } else { &settings.color };
+ let Some((new, smask)) = process(doc, s, ppi, st, n) else { continue };
+ let resized = new.dict.int(b"Width") != s.dict.int(b"Width") || new.dict.int(b"Height") != s.dict.int(b"Height");
+ report.image_bytes_before += s.raw.len();
+ report.image_bytes_after += new.raw.len();
+ if resized {
+ report.images_resampled += 1;
+ } else {
+ report.images_recompressed += 1;
+ }
+ doc.set(r, Object::Stream(new));
+ if let Some((mr, m)) = smask {
+ doc.set(mr, Object::Stream(m));
+ }
+ }
+ Ok(())
+}
diff --git a/crates/optimize/src/lib.rs b/crates/optimize/src/lib.rs
new file mode 100644
index 000000000..8a69bd54a
--- /dev/null
+++ b/crates/optimize/src/lib.rs
@@ -0,0 +1,193 @@
+//! The PDF Optimizer (execution plan M11.1; Acrobat: Reduce File Size and Optimize PDF ▸
+//! Advanced optimization).
+//!
+//! - **Images:** each image's effective resolution is measured where pages draw it (the
+//! smallest over its uses, through form XObjects); colour and grayscale images above a
+//! threshold are resampled (bicubic) to a target resolution and recompressed as JPEG or Flate.
+//! A new image replaces the old one only if it is smaller. Images PrintCraft can't decode
+//! faithfully (CMYK and other colour spaces, masks, decode arrays, JPEG 2000, JBIG2, CCITT,
+//! more than 8 bits) are left alone.
+//! - **Discard objects:** page thumbnails, alternate images, document tags (structure tree),
+//! print settings.
+//! - **Clean up:** Flate-compress streams that have no filter.
+//!
+//! Metadata, attachments, comments, scripts, private data, hidden layers, bookmarks and form
+//! fields are discarded by `printcraft-redact`'s Remove Hidden Information, which the engine
+//! runs alongside.
+
+mod images;
+
+use printcraft_cos::{Document, ObjRef, Object, Stream};
+
+pub use images::effective_resolutions;
+
+#[derive(Debug, thiserror::Error)]
+pub enum OptimizeError {
+ #[error("the document has no page tree")]
+ NoPages,
+ #[error(transparent)]
+ Cos(#[from] printcraft_cos::CosError),
+}
+
+/// How resampled (or recompressed) images are stored.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Compression {
+ /// JPEG with a quality from 1 to 100.
+ Jpeg(u8),
+ /// Lossless (zlib).
+ Flate,
+ /// Keep the image's own compression (resampled images become Flate if they weren't JPEG).
+ Retain,
+}
+
+/// Acrobat's JPEG quality steps.
+pub const QUALITIES: [(&str, u8); 5] = [("Minimum", 25), ("Low", 45), ("Medium", 60), ("High", 80), ("Maximum", 95)];
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct ImageSettings {
+ /// Resample images whose effective resolution is above `above_ppi` down to `target_ppi`.
+ pub downsample: bool,
+ pub target_ppi: f64,
+ pub above_ppi: f64,
+ pub compression: Compression,
+}
+
+impl ImageSettings {
+ /// Reduce File Size: bicubic to 150 ppi above 225 ppi, JPEG medium quality.
+ pub const REDUCE: ImageSettings = ImageSettings { downsample: true, target_ppi: 150.0, above_ppi: 225.0, compression: Compression::Jpeg(60) };
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Settings {
+ pub color: ImageSettings,
+ pub gray: ImageSettings,
+ pub discard_thumbnails: bool,
+ pub discard_alternate_images: bool,
+ pub discard_tags: bool,
+ pub discard_print_settings: bool,
+ /// Flate-compress streams stored without a filter.
+ pub flate_unencoded: bool,
+}
+
+impl Default for Settings {
+ /// Acrobat's Reduce File Size choices.
+ fn default() -> Self {
+ Self {
+ color: ImageSettings::REDUCE,
+ gray: ImageSettings::REDUCE,
+ discard_thumbnails: true,
+ discard_alternate_images: true,
+ discard_tags: false,
+ discard_print_settings: false,
+ flate_unencoded: true,
+ }
+ }
+}
+
+/// What an optimization did.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct Report {
+ pub images: usize,
+ pub images_resampled: usize,
+ pub images_recompressed: usize,
+ /// Encoded image bytes before and after (images that changed).
+ pub image_bytes_before: usize,
+ pub image_bytes_after: usize,
+ pub thumbnails: usize,
+ pub alternate_images: usize,
+ pub tags_removed: bool,
+ pub print_settings: usize,
+ pub streams_compressed: usize,
+}
+
+/// Optimize `doc` in place.
+pub fn optimize(doc: &mut Document, settings: &Settings) -> Result<Report, OptimizeError> {
+ let mut report = Report::default();
+ let pages = printcraft_annot::page_refs(doc).map_err(|_| OptimizeError::NoPages)?;
+ images::run(doc, &pages, settings, &mut report)?;
+ if settings.discard_thumbnails {
+ for p in &pages {
+ if doc.get(*p).as_dict().is_some_and(|d| d.contains(b"Thumb")) {
+ doc.update_dict(*p, |d| {
+ d.remove(b"Thumb");
+ })?;
+ report.thumbnails += 1;
+ }
+ }
+ }
+ if settings.discard_alternate_images {
+ for num in doc.object_numbers() {
+ let r = ObjRef { num, generation: doc.generation(num) };
+ let alt = matches!(&*doc.get(r), Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image") && s.dict.contains(b"Alternates"));
+ if alt {
+ if let Object::Stream(s) = &*doc.get(r) {
+ let mut s = s.clone();
+ s.dict.remove(b"Alternates");
+ doc.set(r, Object::Stream(s));
+ }
+ report.alternate_images += 1;
+ }
+ }
+ }
+ let root = doc.root();
+ if settings.discard_tags
+ && let Some(root) = root
+ && doc.get(root).as_dict().is_some_and(|c| c.contains(b"StructTreeRoot"))
+ {
+ doc.update_dict(root, |c| {
+ c.remove(b"StructTreeRoot");
+ c.remove(b"MarkInfo");
+ })?;
+ for p in &pages {
+ if doc.get(*p).as_dict().is_some_and(|d| d.contains(b"StructParents")) {
+ doc.update_dict(*p, |d| {
+ d.remove(b"StructParents");
+ })?;
+ }
+ }
+ report.tags_removed = true;
+ }
+ if settings.discard_print_settings
+ && let Some(root) = root
+ {
+ const PRINT: [&[u8]; 7] = [b"PrintScaling", b"Duplex", b"PickTrayByPDFSize", b"PrintPageRange", b"NumCopies", b"PrintArea", b"PrintClip"];
+ let vp = doc.get(root).as_dict().and_then(|c| c.get(b"ViewerPreferences").cloned());
+ let edit = |d: &mut printcraft_cos::Dict| PRINT.iter().filter(|k| d.remove(k).is_some()).count();
+ match vp {
+ Some(Object::Ref(r)) => {
+ let mut n = 0;
+ doc.update_dict(r, |d| n = edit(d))?;
+ report.print_settings += n;
+ }
+ Some(Object::Dict(_)) => {
+ let mut n = 0;
+ doc.update_dict(root, |c| {
+ if let Some(Object::Dict(d)) = c.get_mut(b"ViewerPreferences") {
+ n = edit(d);
+ }
+ })?;
+ report.print_settings += n;
+ }
+ _ => {}
+ }
+ }
+ if settings.flate_unencoded {
+ for num in doc.object_numbers() {
+ let r = ObjRef { num, generation: doc.generation(num) };
+ let obj = doc.get(r);
+ let Object::Stream(s) = &*obj else { continue };
+ // XMP stays readable as plain text (PDF/A requires it); tiny streams don't gain.
+ if s.dict.contains(b"Filter") || s.dict.name(b"Type") == Some(b"Metadata") || s.dict.name(b"Type") == Some(b"XRef") || s.raw.len() < 64 {
+ continue;
+ }
+ let mut d = s.dict.clone();
+ d.remove(b"Length");
+ let packed = Stream::flate(d, &s.raw);
+ if packed.raw.len() < s.raw.len() {
+ doc.set(r, Object::Stream(packed));
+ report.streams_compressed += 1;
+ }
+ }
+ }
+ Ok(report)
+}
diff --git a/crates/optimize/tests/optimize.rs b/crates/optimize/tests/optimize.rs
new file mode 100644
index 000000000..54f55eb22
--- /dev/null
+++ b/crates/optimize/tests/optimize.rs
@@ -0,0 +1,177 @@
+//! The optimizer on documents with images drawn at known sizes.
+
+use std::sync::Arc;
+
+use printcraft_cos::{Dict, Document, ObjRef, Object, SaveOptions, Stream, write_full};
+use printcraft_optimize::{Compression, ImageSettings, Settings, effective_resolutions, optimize};
+
+fn image(doc: &mut Document, w: u32, h: u32, n: usize, jpeg: bool, smask: Option<ObjRef>) -> ObjRef {
+ // A smooth gradient with a little texture (photo-like).
+ let mut px = Vec::with_capacity((w * h) as usize * n);
+ for y in 0..h {
+ for x in 0..w {
+ let v = ((x * 255 / w.max(1)) as u8).wrapping_add(((x ^ y) & 7) as u8);
+ px.push(v);
+ if n == 3 {
+ px.push((y * 255 / h.max(1)) as u8);
+ px.push(128);
+ }
+ }
+ }
+ let mut d = Dict::new();
+ d.set(b"Type".to_vec(), Object::name("XObject"));
+ d.set(b"Subtype".to_vec(), Object::name("Image"));
+ d.set(b"Width".to_vec(), Object::Int(w as i64));
+ d.set(b"Height".to_vec(), Object::Int(h as i64));
+ d.set(b"BitsPerComponent".to_vec(), Object::Int(8));
+ d.set(b"ColorSpace".to_vec(), Object::name(if n == 1 { "DeviceGray" } else { "DeviceRGB" }));
+ if let Some(m) = smask {
+ d.set(b"SMask".to_vec(), Object::Ref(m));
+ }
+ let s = if jpeg {
+ let mut out = Vec::new();
+ let ty = if n == 1 { image::ExtendedColorType::L8 } else { image::ExtendedColorType::Rgb8 };
+ image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 98).encode(&px, w, h, ty).unwrap();
+ d.set(b"Filter".to_vec(), Object::name("DCTDecode"));
+ Stream::from_raw(d, out)
+ } else {
+ Stream::flate(d, &px)
+ };
+ doc.add(Object::Stream(s))
+}
+
+fn page(doc: &mut Document, xobjects: &[(&str, ObjRef)], content: &str) -> ObjRef {
+ let pages = doc.root().and_then(|r| doc.get(r).as_dict().and_then(|d| d.reference(b"Pages"))).unwrap();
+ let mut x = Dict::new();
+ for (n, r) in xobjects {
+ x.set(n.as_bytes().to_vec(), Object::Ref(*r));
+ }
+ let mut res = Dict::new();
+ res.set(b"XObject".to_vec(), Object::Dict(x));
+ let c = doc.add(Object::Stream(Stream::from_raw(Dict::new(), content.as_bytes().to_vec())));
+ let mut p = Dict::new();
+ p.set(b"Type".to_vec(), Object::name("Page"));
+ p.set(b"Parent".to_vec(), Object::Ref(pages));
+ p.set(b"MediaBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 612.into(), 792.into()]));
+ p.set(b"Resources".to_vec(), Object::Dict(res));
+ p.set(b"Contents".to_vec(), Object::Ref(c));
+ p.set(b"Thumb".to_vec(), Object::Ref(c));
+ let r = doc.add(Object::Dict(p));
+ doc.update_dict(pages, |d| {
+ let mut kids = d.get(b"Kids").and_then(|k| k.as_array().cloned()).unwrap_or_default();
+ kids.push(Object::Ref(r));
+ d.set(b"Count".to_vec(), Object::Int(kids.len() as i64));
+ d.set(b"Kids".to_vec(), Object::Array(kids));
+ })
+ .unwrap();
+ r
+}
+
+fn stream(doc: &Document, r: ObjRef) -> Stream {
+ match &*doc.get(r) {
+ Object::Stream(s) => s.clone(),
+ _ => panic!("not a stream"),
+ }
+}
+
+#[test]
+fn images_are_measured_where_drawn_and_downsampled() {
+ let mut doc = Document::new_empty();
+ // 1200 px drawn 144 pt (2 in) wide → 600 ppi.
+ let big = image(&mut doc, 1200, 1200, 3, false, None);
+ // 100 px at 144 pt → 50 ppi: left at its size.
+ let small = image(&mut doc, 100, 100, 1, false, None);
+ // With a soft mask, 800 px at 72 pt → 800 ppi.
+ let mask = image(&mut doc, 800, 800, 1, false, None);
+ let masked = image(&mut doc, 800, 800, 3, false, Some(mask));
+ // A high-quality JPEG at 72 ppi: recompressed, not resized.
+ let photo = image(&mut doc, 600, 400, 3, true, None);
+ // Drawn twice: 300 ppi and 75 ppi → effective 75 (never downsampled below what a use needs).
+ let twice = image(&mut doc, 300, 300, 3, false, None);
+ page(&mut doc, &[("Im1", big), ("Im2", small)], "q 144 0 0 144 36 600 cm /Im1 Do Q q 144 0 0 144 300 600 cm /Im2 Do Q");
+ page(
+ &mut doc,
+ &[("A", masked), ("B", photo), ("C", twice)],
+ "q 72 0 0 72 36 36 cm /A Do Q q 1 0 0 1 100 100 cm 600 0 0 400 0 0 cm /B Do Q q 72 0 0 72 0 0 cm /C Do Q q 288 0 0 288 300 300 cm /C Do Q",
+ );
+ let pages = printcraft_annot::page_refs(&doc).unwrap();
+ let ppi = effective_resolutions(&doc, &pages);
+ assert_eq!(ppi[&big].round(), 600.0);
+ assert_eq!(ppi[&small].round(), 50.0);
+ assert_eq!(ppi[&masked].round(), 800.0);
+ assert_eq!(ppi[&photo].round(), 72.0);
+ assert_eq!(ppi[&twice].round(), 75.0, "the largest use decides");
+
+ let before = write_full(&doc, &SaveOptions::default()).unwrap().len();
+ let report = optimize(&mut doc, &Settings::default()).unwrap();
+ assert_eq!(report.images, 5, "{report:?}");
+ assert_eq!(report.images_resampled, 2, "{report:?}");
+ assert!(report.thumbnails == 2);
+ let b = stream(&doc, big);
+ assert_eq!((b.dict.int(b"Width"), b.dict.int(b"Height"), b.dict.name(b"Filter")), (Some(300), Some(300), Some(&b"DCTDecode"[..])));
+ let m = stream(&doc, masked);
+ let sm = stream(&doc, mask);
+ assert_eq!((m.dict.int(b"Width"), sm.dict.int(b"Width")), (Some(150), Some(150)), "the soft mask follows its image");
+ assert_eq!(sm.dict.name(b"Filter"), Some(&b"FlateDecode"[..]));
+ assert_eq!(stream(&doc, small).dict.int(b"Width"), Some(100));
+ assert_eq!(stream(&doc, twice).dict.int(b"Width"), Some(300), "75 ppi is below the threshold");
+ let p = stream(&doc, photo);
+ assert_eq!(p.dict.int(b"Width"), Some(600));
+ let after_bytes = write_full(&doc, &SaveOptions::default()).unwrap();
+ assert!(after_bytes.len() * 3 < before, "{} → {}", before, after_bytes.len());
+
+ // The optimized file opens, and the page still shows the picture where it was.
+ let reopened = Document::open(Arc::new(after_bytes.clone())).unwrap();
+ assert_eq!(printcraft_annot::page_refs(&reopened).unwrap().len(), 2);
+ let mut r = printcraft_render::PageRenderer::new(Arc::new(after_bytes), printcraft_render::RenderConfig::default());
+ let out = r.render(printcraft_render::RenderRequest { page: 0, scale: 1.0, ..Default::default() });
+ assert!(out.error.is_none(), "{:?}", out.error);
+ // Top-left image area (36..180 x 600..744 user → y from the top 48..192): drawn, not white.
+ let i = ((100 * out.width + 100) * 4) as usize;
+ assert_ne!(&out.rgba[i..i + 3], &[255, 255, 255]);
+}
+
+#[test]
+fn settings_choose_what_happens() {
+ let mut doc = Document::new_empty();
+ let big = image(&mut doc, 1200, 600, 1, false, None);
+ page(&mut doc, &[("Im1", big)], "q 144 0 0 72 36 600 cm /Im1 Do Q");
+ let mut keep = doc.clone();
+ // Off: nothing changes (but the thumbnail goes).
+ let off = ImageSettings { downsample: false, target_ppi: 150.0, above_ppi: 225.0, compression: Compression::Retain };
+ let r = optimize(&mut keep, &Settings { color: off, gray: off, ..Settings::default() }).unwrap();
+ assert_eq!((r.images_resampled, r.images_recompressed), (0, 0));
+ // Lossless: resampled to 300 ppi, Flate.
+ let lossless = ImageSettings { downsample: true, target_ppi: 300.0, above_ppi: 450.0, compression: Compression::Flate };
+ let r = optimize(&mut doc, &Settings { gray: lossless, ..Settings::default() }).unwrap();
+ assert_eq!(r.images_resampled, 1);
+ let s = stream(&doc, big);
+ assert_eq!((s.dict.int(b"Width"), s.dict.int(b"Height"), s.dict.name(b"Filter")), (Some(600), Some(300), Some(&b"FlateDecode"[..])));
+}
+
+#[test]
+fn discards_and_clean_up() {
+ let mut doc = Document::new_empty();
+ let pages = page(&mut doc, &[], "BT /F1 12 Tf 72 720 Td (Hello world, hello world, hello world, hello world) Tj ET");
+ let root = doc.root().unwrap();
+ let mut vp = Dict::new();
+ vp.set(b"PrintScaling".to_vec(), Object::name("None"));
+ vp.set(b"Duplex".to_vec(), Object::name("Simplex"));
+ vp.set(b"HideToolbar".to_vec(), Object::Bool(true));
+ let st = doc.add(Object::Dict(Dict::new()));
+ doc.update_dict(root, |c| {
+ c.set(b"ViewerPreferences".to_vec(), Object::Dict(vp));
+ c.set(b"StructTreeRoot".to_vec(), Object::Ref(st));
+ c.set(b"MarkInfo".to_vec(), Object::Dict(Dict::new()));
+ })
+ .unwrap();
+ doc.update_dict(pages, |p| p.set(b"StructParents".to_vec(), Object::Int(0))).unwrap();
+ let settings = Settings { discard_tags: true, discard_print_settings: true, ..Settings::default() };
+ let r = optimize(&mut doc, &settings).unwrap();
+ assert!(r.tags_removed);
+ assert_eq!((r.print_settings, r.thumbnails, r.streams_compressed), (2, 1, 1));
+ let c = doc.get(root).as_dict().cloned().unwrap();
+ assert!(!c.contains(b"StructTreeRoot") && !c.contains(b"MarkInfo"));
+ let vp = c.get(b"ViewerPreferences").and_then(|v| v.as_dict().cloned()).unwrap();
+ assert!(vp.contains(b"HideToolbar") && !vp.contains(b"Duplex"), "other preferences stay");
+}
diff --git a/crates/ui-egui/src/commands.rs b/crates/ui-egui/src/commands.rs
index 6a1334a92..d5dd7c04d 100644
--- a/crates/ui-egui/src/commands.rs
+++ b/crates/ui-egui/src/commands.rs
@@ -307,6 +307,7 @@ impl PrintCraftApp {
self.right = Some(RightPanel::Signatures);
}
"sign.panel" => self.right = Some(RightPanel::Signatures),
+ "optimize.advanced" => self.dialog = Some(Dialog::Optimize),
"comment.hide_all" => {
if let Some(i) = active {
let id = self.views[i].id;
diff --git a/crates/ui-egui/src/create_ui.rs b/crates/ui-egui/src/create_ui.rs
index 90f88dafd..cbd9f5497 100644
--- a/crates/ui-egui/src/create_ui.rs
+++ b/crates/ui-egui/src/create_ui.rs
@@ -163,22 +163,35 @@ impl PrintCraftApp {
}
}
- /// Reduce File Size: write a compacted copy (the open document is unchanged).
+ /// Reduce File Size: write a compacted copy with images downsampled (the open document is
+ /// unchanged).
pub(crate) fn reduce_file_size(&mut self) {
let Some((_, id)) = self.active_ids() else { return };
+ let result = self.session.reduced_bytes(id).map(|(b, _)| (b, String::new()));
+ self.save_optimized(id, "reduced", result);
+ }
+
+ /// Save an optimized copy (Reduce File Size, Optimize PDF) next to the original, reporting
+ /// the saving.
+ pub(crate) fn save_optimized(
+ &mut self,
+ id: printcraft_engine::DocId,
+ suffix: &str,
+ result: Result<(Arc<Vec<u8>>, String), printcraft_engine::EditError>,
+ ) {
let Some(doc) = self.session.get(id) else { return };
- let (before, name) = (doc.bytes.len(), format!("{} (reduced).pdf", stem(&doc.name)));
- let (bytes, _) = match self.session.reduced_bytes(id) {
+ let (before, name) = (doc.bytes.len(), format!("{} ({suffix}).pdf", stem(&doc.name)));
+ let (bytes, detail) = match result {
Ok(r) => r,
Err(e) => {
- self.notify(format!("Couldn't reduce the file: {e}"));
+ self.notify(format!("Couldn't optimize the file: {e}"));
return;
}
};
let saved = |app: &mut PrintCraftApp, place: String| {
let pct = 100.0 * (1.0 - bytes.len() as f64 / before.max(1) as f64);
app.notify(format!(
- "Saved {place}: {} → {} ({pct:.0}% smaller)",
+ "Saved {place}: {} → {} ({pct:.0}% smaller){detail}",
crate::panels::human_size(before),
crate::panels::human_size(bytes.len())
));
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 01d5d70b0..682dcda3d 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -43,6 +43,7 @@ pub fn show(app: &mut PrintCraftApp, ctx: &egui::Context) {
let mut print_go = false;
let mut revert_now = false;
let mut summarize_now = false;
+ let mut optimize_now = false;
let mut replace_now = false;
let t = Tokens::get(ctx);
let mut close = false;
@@ -449,6 +450,12 @@ pub fn show(app: &mut PrintCraftApp, ctx: &egui::Context) {
});
return;
}
+ Dialog::Optimize => {
+ let (ok, cancel) = crate::optimize_ui::body(ui, &mut app.optimize_draft, &t);
+ optimize_now = ok;
+ close = ok || cancel;
+ return;
+ }
Dialog::Sign => {
if crate::sign_ui::dialog(ui, app, &t) {
app.sign_draft = None;
@@ -797,6 +804,9 @@ pub fn show(app: &mut PrintCraftApp, ctx: &egui::Context) {
if summarize_now {
app.summarize_comments();
}
+ if optimize_now {
+ app.optimize_with_draft();
+ }
if extract_now {
app.extract_selection();
}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 29b2e1d83..dab0150b9 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -16,6 +16,7 @@ mod create_ui;
mod crop;
mod export_ui;
mod marks_ui;
+mod optimize_ui;
mod sign_ui;
/// Header & footer / watermark / background dialog types (tests and automation).
pub mod marks {
@@ -25,6 +26,7 @@ mod content_ui;
mod link_ui;
pub use create_ui::Clip;
pub use link_ui::LinkDraft;
+pub use optimize_ui::{OptimizeDraft, OptimizeTab};
pub use sign_ui::{DigitalIdEntry, SignDraft, SignStep};
mod dialogs;
mod editing;
@@ -158,6 +160,8 @@ pub enum Dialog {
SummarizeComments,
/// Sign with a Digital ID ▸ Configure ▸ Sign as.
Sign,
+ /// Optimize PDF ▸ Advanced optimization.
+ Optimize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -236,6 +240,8 @@ pub struct PrintCraftApp {
pub digital_ids: Vec<DigitalIdEntry>,
/// Signatures panel: expanded entries (field names).
pub sig_expanded: Vec<String>,
+ /// PDF Optimizer choices.
+ pub optimize_draft: OptimizeDraft,
/// Where autosaves go (`None`: autosave off, e.g. on the web and in tests).
pub recovery: Option<RecoveryStore>,
/// Entries left by a previous session, offered in the Recovery dialog.
@@ -338,6 +344,7 @@ impl PrintCraftApp {
sign_draft: None,
digital_ids: Vec::new(),
sig_expanded: Vec::new(),
+ optimize_draft: OptimizeDraft::default(),
recovery: None,
recoverable: Vec::new(),
recovery_keys: Default::default(),
@@ -691,6 +698,7 @@ impl PrintCraftApp {
"export-image" => Some(Dialog::Export(export_ui::ExportKind::Image)),
"export-text" => Some(Dialog::Export(export_ui::ExportKind::Text)),
"signature" => Some(Dialog::Signature),
+ "optimize" => Some(Dialog::Optimize),
"sign" | "certify" => {
// Sign with a Digital ID for an invisible signature on the current page.
let page = self.active.map_or(0, |i| self.views[i].current);
diff --git a/crates/ui-egui/src/optimize_ui.rs b/crates/ui-egui/src/optimize_ui.rs
new file mode 100644
index 000000000..0531c8b66
--- /dev/null
+++ b/crates/ui-egui/src/optimize_ui.rs
@@ -0,0 +1,170 @@
+//! Optimize PDF ▸ Advanced optimization (Acrobat's PDF Optimizer): Images, Discard Objects,
+//! Discard User Data and Clean Up panels. The result is saved as a copy, like Reduce File Size.
+
+use egui::{Align, Layout};
+use printcraft_engine::Hidden;
+use printcraft_engine::optimize::{Compression, ImageSettings, QUALITIES, Settings};
+
+use crate::theme::{self, Tokens};
+use crate::{PrintCraftApp, widgets};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum OptimizeTab {
+ Images,
+ DiscardObjects,
+ DiscardUserData,
+ CleanUp,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct OptimizeDraft {
+ pub tab: OptimizeTab,
+ pub settings: Settings,
+ /// Remove Hidden Information categories to discard.
+ pub discard: Vec<Hidden>,
+}
+
+impl Default for OptimizeDraft {
+ fn default() -> Self {
+ Self { tab: OptimizeTab::Images, settings: Settings::default(), discard: Vec::new() }
+ }
+}
+
+fn image_row(ui: &mut egui::Ui, id: &str, title: &str, s: &mut ImageSettings) {
+ ui.label(egui::RichText::new(title).font(theme::semibold(13.0)));
+ ui.horizontal(|ui| {
+ ui.checkbox(&mut s.downsample, "Bicubic downsampling to");
+ ui.add_enabled(s.downsample, egui::DragValue::new(&mut s.target_ppi).range(9.0..=2400.0).suffix(" ppi"));
+ ui.label("for images above");
+ ui.add_enabled(s.downsample, egui::DragValue::new(&mut s.above_ppi).range(9.0..=2400.0).suffix(" ppi"));
+ });
+ s.above_ppi = s.above_ppi.max(s.target_ppi);
+ ui.horizontal(|ui| {
+ ui.label("Compression");
+ let label = match s.compression {
+ Compression::Jpeg(_) => "JPEG",
+ Compression::Flate => "ZIP",
+ Compression::Retain => "Retain existing",
+ };
+ egui::ComboBox::from_id_salt((id, "compression")).selected_text(label).show_ui(ui, |ui| {
+ let q = match s.compression {
+ Compression::Jpeg(q) => q,
+ _ => 60,
+ };
+ ui.selectable_value(&mut s.compression, Compression::Jpeg(q), "JPEG");
+ ui.selectable_value(&mut s.compression, Compression::Flate, "ZIP");
+ ui.selectable_value(&mut s.compression, Compression::Retain, "Retain existing");
+ });
+ if let Compression::Jpeg(q) = &mut s.compression {
+ ui.label("Quality");
+ let name = QUALITIES.iter().min_by_key(|(_, v)| (*v as i32 - *q as i32).abs()).map_or("Medium", |(n, _)| n);
+ egui::ComboBox::from_id_salt((id, "quality")).selected_text(name).show_ui(ui, |ui| {
+ for (n, v) in QUALITIES {
+ ui.selectable_value(q, v, n);
+ }
+ });
+ }
+ });
+ ui.add_space(8.0);
+}
+
+fn discard_box(ui: &mut egui::Ui, list: &mut Vec<Hidden>, h: Hidden, label: &str) {
+ let mut on = list.contains(&h);
+ if ui.checkbox(&mut on, label).changed() {
+ if on {
+ list.push(h);
+ } else {
+ list.retain(|x| *x != h);
+ }
+ }
+}
+
+/// Draw the dialog; returns (ok, cancel).
+pub(crate) fn body(ui: &mut egui::Ui, d: &mut OptimizeDraft, t: &Tokens) -> (bool, bool) {
+ ui.label(egui::RichText::new("PDF Optimizer").font(theme::semibold(18.0)));
+ ui.add_space(6.0);
+ ui.horizontal(|ui| {
+ for (tab, label) in [
+ (OptimizeTab::Images, "Images"),
+ (OptimizeTab::DiscardObjects, "Discard Objects"),
+ (OptimizeTab::DiscardUserData, "Discard User Data"),
+ (OptimizeTab::CleanUp, "Clean Up"),
+ ] {
+ if widgets::mode_tab(ui, label, d.tab == tab).clicked() {
+ d.tab = tab;
+ }
+ }
+ });
+ ui.separator();
+ ui.add_space(6.0);
+ let s = &mut d.settings;
+ match d.tab {
+ OptimizeTab::Images => {
+ image_row(ui, "color", "Color Images", &mut s.color);
+ image_row(ui, "gray", "Grayscale Images", &mut s.gray);
+ ui.label(
+ egui::RichText::new("Each image is measured where pages draw it; an image is replaced only if the result is smaller.")
+ .small()
+ .color(t.text_muted),
+ );
+ }
+ OptimizeTab::DiscardObjects => {
+ discard_box(ui, &mut d.discard, Hidden::LinksActionsScripts, "Discard all links, actions and JavaScript");
+ ui.checkbox(&mut s.discard_alternate_images, "Discard alternate images");
+ ui.checkbox(&mut s.discard_thumbnails, "Discard embedded page thumbnails");
+ ui.checkbox(&mut s.discard_tags, "Discard document tags");
+ ui.checkbox(&mut s.discard_print_settings, "Discard embedded print settings");
+ discard_box(ui, &mut d.discard, Hidden::Bookmarks, "Discard bookmarks");
+ discard_box(ui, &mut d.discard, Hidden::FormFields, "Flatten form fields");
+ discard_box(ui, &mut d.discard, Hidden::HiddenLayers, "Discard hidden layer content");
+ }
+ OptimizeTab::DiscardUserData => {
+ discard_box(ui, &mut d.discard, Hidden::Comments, "Discard all comments, forms and multimedia");
+ discard_box(ui, &mut d.discard, Hidden::Metadata, "Discard document information and metadata");
+ discard_box(ui, &mut d.discard, Hidden::Attachments, "Discard all object data (file attachments)");
+ discard_box(ui, &mut d.discard, Hidden::PrivateData, "Discard private data of other applications");
+ discard_box(ui, &mut d.discard, Hidden::HiddenText, "Discard hidden text");
+ }
+ OptimizeTab::CleanUp => {
+ ui.checkbox(&mut s.flate_unencoded, "Use Flate to encode streams that are not encoded");
+ ui.add_enabled(false, egui::Checkbox::new(&mut true, "Compress document structure (object streams)"));
+ ui.add_enabled(false, egui::Checkbox::new(&mut true, "Remove unused objects and merge identical ones"));
+ }
+ }
+ ui.add_space(12.0);
+ let (mut ok, mut cancel) = (false, false);
+ ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
+ if widgets::pill_button(ui, "OK", true).clicked() {
+ ok = true;
+ }
+ if widgets::pill_button(ui, "Cancel", false).clicked() {
+ cancel = true;
+ }
+ });
+ (ok, cancel)
+}
+
+impl PrintCraftApp {
+ /// Optimize PDF with the dialog's choices and save the copy.
+ pub fn optimize_with_draft(&mut self) {
+ let Some((_, id)) = self.active_ids() else { return };
+ let d = self.optimize_draft.clone();
+ let result = self.session.optimized_bytes(id, &d.settings, &d.discard).map(|(b, r)| {
+ let o = &r.optimize;
+ let mut parts = Vec::new();
+ if o.images_resampled + o.images_recompressed > 0 {
+ parts.push(format!(
+ "{} image{} optimized",
+ o.images_resampled + o.images_recompressed,
+ if o.images_resampled + o.images_recompressed == 1 { "" } else { "s" }
+ ));
+ }
+ let discarded: usize = r.discarded.iter().map(|(_, n)| n).sum();
+ if discarded > 0 {
+ parts.push(format!("{discarded} item{} discarded", if discarded == 1 { "" } else { "s" }));
+ }
+ (b, if parts.is_empty() { String::new() } else { format!("; {}", parts.join(", ")) })
+ });
+ self.save_optimized(id, "optimized", result);
+ }
+}
diff --git a/crates/ui-egui/tests/create.rs b/crates/ui-egui/tests/create.rs
index 99462af79..0958c512a 100644
--- a/crates/ui-egui/tests/create.rs
+++ b/crates/ui-egui/tests/create.rs
@@ -59,3 +59,39 @@ fn clipboard_images_and_text_become_new_pdfs() {
assert!((p.width / p.height - 2.0).abs() < 0.01, "{} × {}", p.width, p.height);
assert!(app.create_from_clip(Clip::Image { width: 4, height: 4, rgba: vec![0; 3] }).is_err(), "malformed images are refused");
}
+
+#[test]
+fn the_pdf_optimizer_dialog_saves_an_optimized_copy() {
+ use egui_kittest::Harness;
+ use egui_kittest::kittest::Queryable;
+ let dir = std::env::temp_dir().join(format!("printcraft-optimizer-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let out = dir.join("optimized.pdf");
+ let out2 = out.clone();
+ let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |_cc| {
+ let mut app = PrintCraftApp::new();
+ app.open_bytes("notes.txt", None, "lorem ipsum ".repeat(500).into_bytes()).unwrap();
+ app.save_override = Some(out2.to_string_lossy().into_owned());
+ app
+ });
+ h.run_steps(4);
+ assert!(h.state_mut().execute("optimize.advanced"));
+ h.run_steps(2);
+ h.get_by_label("PDF Optimizer");
+ h.get_by_label("Color Images");
+ h.get_by_label("Discard Objects").click();
+ h.run_steps(2);
+ h.get_by_label("Discard document tags").click();
+ h.get_by_label("Discard User Data").click();
+ h.run_steps(2);
+ h.get_by_label("Discard document information and metadata").click();
+ h.run_steps(1);
+ {
+ let d = &h.state().optimize_draft;
+ assert!(d.settings.discard_tags && d.discard == vec![printcraft_engine::Hidden::Metadata]);
+ }
+ h.get_by_label("OK").click();
+ h.run_steps(3);
+ assert!(std::fs::read(&out).unwrap().starts_with(b"%PDF-"));
+ assert_eq!(h.state().dialog, None);
+}
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index 630c52937..747e82a9d 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -7067,11 +7067,11 @@ title = "Reduce file size (one click)"
area = "K"
tier = "P0"
milestone = "M11"
-status = "partial"
+status = "shipped"
commands = ["optimize.reduce"]
tools = ["doc_reduce"]
-evidence = ["crates/ui-egui/tests/create.rs::reduce_file_size_writes_a_compact_copy", "crates/engine/src/tests.rs::create_and_reduce", "crates/automation/tests/automation.rs::creating_and_reducing_through_tools"]
-notes = "merges identical resources, drops unused objects, object streams; no image downsampling yet"
+evidence = ["crates/ui-egui/tests/create.rs::reduce_file_size_writes_a_compact_copy", "crates/engine/src/tests.rs::create_and_reduce", "crates/automation/tests/automation.rs::creating_and_reducing_through_tools", "crates/automation/tests/automation.rs::optimizing_through_tools"]
+notes = "images above 225 ppi to 150 ppi JPEG medium, thumbnails dropped, resources merged, object streams"
[[feature]]
id = "optimize.compatibility-level"
@@ -7091,11 +7091,11 @@ title = "Advanced optimization (PDF Optimizer)"
area = "K"
tier = "P1"
milestone = "M11"
-status = "planned"
-commands = []
-tools = []
-evidence = []
-notes = ""
+status = "partial"
+commands = ["optimize.advanced"]
+tools = ["doc_optimize"]
+evidence = ["crates/ui-egui/tests/create.rs::the_pdf_optimizer_dialog_saves_an_optimized_copy", "crates/automation/tests/automation.rs::optimizing_through_tools"]
+notes = "Images, Discard Objects, Discard User Data, Clean Up; no Fonts or Transparency panels, no space audit"
[[feature]]
id = "optimize.downsample-images"
@@ -7103,11 +7103,11 @@ title = "Downsample colour, grey and mono images"
area = "K"
tier = "P1"
milestone = "M11"
-status = "planned"
-commands = []
-tools = []
-evidence = []
-notes = ""
+status = "partial"
+commands = ["optimize.advanced"]
+tools = ["doc_optimize"]
+evidence = ["crates/optimize/tests/optimize.rs::images_are_measured_where_drawn_and_downsampled", "crates/optimize/tests/optimize.rs::settings_choose_what_happens", "crates/automation/tests/automation.rs::optimizing_through_tools"]
+notes = "colour and grayscale, bicubic, effective resolution measured where drawn; monochrome not yet"
[[feature]]
id = "optimize.recompress-images"
@@ -7115,11 +7115,11 @@ title = "Recompress images (JPEG, JPEG 2000, Flate)"
area = "K"
tier = "P1"
milestone = "M11"
-status = "planned"
-commands = []
-tools = []
-evidence = []
-notes = ""
+status = "partial"
+commands = ["optimize.advanced"]
+tools = ["doc_optimize"]
+evidence = ["crates/optimize/tests/optimize.rs::images_are_measured_where_drawn_and_downsampled", "crates/optimize/tests/optimize.rs::settings_choose_what_happens"]
+notes = "JPEG (quality steps) and ZIP; no JPEG 2000"
[[feature]]
id = "optimize.mono-compression"
@@ -7139,11 +7139,11 @@ title = "Optimize images only if smaller"
area = "K"
tier = "P1"
milestone = "M11"
-status = "planned"
-commands = []
-tools = []
-evidence = []
-notes = ""
+status = "shipped"
+commands = ["optimize.advanced"]
+tools = ["doc_optimize"]
+evidence = ["crates/optimize/tests/optimize.rs::images_are_measured_where_drawn_and_downsampled"]
+notes = "always on"
[[feature]]
id = "optimize.unembed-fonts"
@@ -7175,11 +7175,11 @@ title = "Discard JavaScript actions"
area = "K"
tier = "P1"
milestone = "M11"
-status = "planned"
-commands = []
-tools = []
-evidence = []
-notes = ""
+status = "shipped"
+commands = ["optimize.advanced"]
+tools = ["doc_optimize"]
+evidence = ["crates/redact/src/tests.rs::hidden_information_is_counted_and_removed", "crates/automation/tests/automation.rs::optimizing_through_tools"]
+notes = "with links and actions (Remove Hidden Information)"
[[feature]]
id = "optimize.discard-thumbnails"
@@ -7187,10 +7187,10 @@ title = "Discard embedded thumbnails"
area = "K"
tier = "P1"
milestone = "M11"
-status = "planned"
-commands = []
-tools = []
-evidence = []
+status = "shipped"
+commands = ["optimize.advanced"]
+tools = ["doc_optimize"]
+evidence = ["crates/optimize/tests/optimize.rs::images_are_measured_where_drawn_and_downsampled"]
notes = ""
[[feature]]
@@ -7199,10 +7199,10 @@ title = "Discard document tags"
area = "K"
tier = "P2"
milestone = "M11"
-status = "planned"
-commands = []
-tools = []
-evidence = []
+status = "shipped"
+commands = ["optimize.advanced"]
+tools = ["doc_optimize"]
+evidence = ["crates/optimize/tests/optimize.rs::discards_and_clean_up", "crates/ui-egui/tests/create.rs::the_pdf_optimizer_dialog_saves_an_optimized_copy"]
notes = ""
[[feature]]
@@ -7211,10 +7211,10 @@ title = "Discard bookmarks"
area = "K"
tier = "P2"
milestone = "M11"
-status = "planned"
-commands = []
-tools = []
-evidence = []
+status = "shipped"
+commands = ["optimize.advanced"]
+tools = ["doc_optimize"]
+evidence = ["crates/redact/src/tests.rs::hidden_information_is_counted_and_removed", "crates/automation/tests/automation.rs::optimizing_through_tools"]
notes = ""
[[feature]]
@@ -7235,10 +7235,10 @@ title = "Discard embedded print settings"
area = "K"
tier = "P2"
milestone = "M11"
-status = "planned"
-commands = []
-tools = []
-evidence = []
+status = "shipped"
+commands = ["optimize.advanced"]
+tools = ["doc_optimize"]
+evidence = ["crates/optimize/tests/optimize.rs::discards_and_clean_up"]
notes = ""
[[feature]]
@@ -7247,10 +7247,10 @@ title = "Discard alternate images"
area = "K"
tier = "P2"
milestone = "M11"
-status = "planned"
-commands = []
-tools = []
-evidence = []
+status = "shipped"
+commands = ["optimize.advanced"]
+tools = ["doc_optimize"]
+evidence = ["crates/optimize/tests/optimize.rs::images_are_measured_where_drawn_and_downsampled"]
notes = ""
[[feature]]
@@ -7271,10 +7271,10 @@ title = "Flatten form fields while optimizing"
area = "K"
tier = "P1"
milestone = "M11"
-status = "planned"
-commands = []
-tools = []
-evidence = []
+status = "shipped"
+commands = ["optimize.advanced"]
+tools = ["doc_optimize"]
+evidence = ["crates/redact/src/tests.rs::hidden_information_is_counted_and_removed", "crates/automation/tests/automation.rs::optimizing_through_tools"]
notes = ""
[[feature]]
@@ -7283,10 +7283,10 @@ title = "Discard comments, forms and multimedia"
area = "K"
tier = "P1"
milestone = "M11"
-status = "planned"
-commands = []
-tools = []
-evidence = []
+status = "shipped"
+commands = ["optimize.advanced"]
+tools = ["doc_optimize"]
+evidence = ["crates/redact/src/tests.rs::hidden_information_is_counted_and_removed", "crates/automation/tests/automation.rs::optimizing_through_tools"]
notes = ""
[[feature]]
@@ -7295,10 +7295,10 @@ title = "Discard document information and metadata"
area = "K"
tier = "P1"
milestone = "M11"
-status = "planned"
-commands = []
-tools = []
-evidence = []
+status = "shipped"
+commands = ["optimize.advanced"]
+tools = ["doc_optimize"]
+evidence = ["crates/automation/tests/automation.rs::optimizing_through_tools", "crates/ui-egui/tests/create.rs::the_pdf_optimizer_dialog_saves_an_optimized_copy"]
notes = ""
[[feature]]
@@ -7307,10 +7307,10 @@ title = "Discard file attachments"
area = "K"
tier = "P1"
milestone = "M11"
-status = "planned"
-commands = []
-tools = []
-evidence = []
+status = "shipped"
+commands = ["optimize.advanced"]
+tools = ["doc_optimize"]
+evidence = ["crates/redact/src/tests.rs::hidden_information_is_counted_and_removed", "crates/automation/tests/automation.rs::optimizing_through_tools"]
notes = ""
[[feature]]
@@ -7319,10 +7319,10 @@ title = "Discard private application data (PieceInfo)"
area = "K"
tier = "P2"
milestone = "M11"
-status = "planned"
-commands = []
-tools = []
-evidence = []
+status = "shipped"
+commands = ["optimize.advanced"]
+tools = ["doc_optimize"]
+evidence = ["crates/redact/src/tests.rs::hidden_information_is_counted_and_removed", "crates/automation/tests/automation.rs::optimizing_through_tools"]
notes = ""
[[feature]]
@@ -7343,11 +7343,11 @@ title = "Discard hidden layers and flatten visible ones"
area = "K"
tier = "P2"
milestone = "M11"
-status = "planned"
-commands = []
-tools = []
-evidence = []
-notes = ""
+status = "partial"
+commands = ["optimize.advanced"]
+tools = ["doc_optimize"]
+evidence = ["crates/redact/src/tests.rs::hidden_information_is_counted_and_removed", "crates/automation/tests/automation.rs::optimizing_through_tools"]
+notes = "hidden layer content removed; visible layers not flattened"
[[feature]]
id = "optimize.merge-image-fragments"
@@ -7391,11 +7391,11 @@ title = "Flate-encode unencoded streams; replace LZW with Flate"
area = "K"
tier = "P1"
milestone = "M11"
-status = "planned"
-commands = []
-tools = []
-evidence = []
-notes = ""
+status = "partial"
+commands = ["optimize.advanced"]
+tools = ["doc_optimize"]
+evidence = ["crates/optimize/tests/optimize.rs::discards_and_clean_up"]
+notes = "unencoded streams; LZW not yet re-encoded"
[[feature]]
id = "optimize.remove-invalid-links"