Skip to content

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

M11: LZW to Flate leaves streams whose decode parameters aren't direct integers

Marco Arnulfo35b46770195f
diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs
index 028d58d68..70a028c13 100644
--- a/crates/automation/src/tools.rs
+++ b/crates/automation/src/tools.rs
@@ -1359,7 +1359,7 @@ pub fn tools() -> Vec<ToolDef> {
.with(schema(json!({ "doc": doc() }), &["doc"])),
t("doc_open_revision", "Open a revision", "Open saved revision `revision` (1 = the oldest) of a document as a new, unsaved document, to see the file as it was then.")
.with(schema(json!({ "doc": doc(), "revision": { "type": "integer", "minimum": 1 } }), &["doc", "revision"])),
- t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). preset: standard (default; Reduce File Size's choices) or mobile (images to 96 ppi above 144, JPEG high quality); the options below change it. merge_fragments (default true) first puts a page picture drawn as many stacked image strips (as some PDF printers write it) back together into one image, so it can be resampled (merged_images, fragments_merged). 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); lzw_to_flate (true) decodes LZW streams and stores them with Flate instead, leaving any it cannot decode (lzw_streams); remove_invalid_links and remove_unreferenced_dests (true); images and forms the pages list but never draw are always dropped (unused_xobjects). 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.")
+ t("doc_optimize", "Optimize PDF", "Write an optimized copy to `path` (Acrobat's PDF Optimizer). preset: standard (default; Reduce File Size's choices) or mobile (images to 96 ppi above 144, JPEG high quality); the options below change it. merge_fragments (default true) first puts a page picture drawn as many stacked image strips (as some PDF printers write it) back together into one image, so it can be resampled (merged_images, fragments_merged). 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); lzw_to_flate (true) decodes LZW streams and stores them with Flate instead, leaving any it cannot decode unchanged (lzw_streams counts the streams converted); remove_invalid_links and remove_unreferenced_dests (true); images and forms the pages list but never draw are always dropped (unused_xobjects). 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!({
diff --git a/crates/optimize/README.md b/crates/optimize/README.md
index 387c26cb0..06edee534 100644
--- a/crates/optimize/README.md
+++ b/crates/optimize/README.md
@@ -30,7 +30,7 @@ let report = optimize_with_progress(&mut doc, &settings, &mut |stage| keep_going
- **Discard objects:** thumbnails, alternate images, document tags, print settings.
- **Clean up:** Flate for streams with no filter; for streams with an outer ASCII85 or ASCIIHex
layer, that layer is removed when the result is smaller (the inner filters keep their encoded
- bytes). Streams with `/DecodeParms`, images and object streams are left alone. LZW-compressed
+ bytes; streams with `/DecodeParms`, images and object streams keep their ASCII layer. LZW-compressed
streams, content and images alike, are decoded and stored with Flate instead (Acrobat's "In
streams that use LZW encoding, use Flate instead"): a predictor carries over to Flate without
`EarlyChange`, filters applied before the LZW one go with it and those after it keep their
diff --git a/crates/optimize/src/lib.rs b/crates/optimize/src/lib.rs
index 14472106a..5c3155485 100644
--- a/crates/optimize/src/lib.rs
+++ b/crates/optimize/src/lib.rs
@@ -370,6 +370,13 @@ fn lzw_to_flate(s: &Stream, max: usize) -> Option<Stream> {
let chain = s.filters();
let stages = chain.get(..=lzw)?;
let (_, params) = stages.last()?;
+ // The decoded stages' parameters must be direct integers: `filters` reads anything else (a
+ // reference, 12.5, a name) as the default, and the dictionary carried over would then
+ // describe the new data differently from how it was encoded.
+ let direct = |p: &Option<&Dict>| p.is_none_or(|d| d.iter().all(|(_, v)| matches!(v, Object::Int(_))));
+ if !parms.get(..=lzw)?.iter().all(direct) {
+ return None;
+ }
let data = pdfcraft_filters::decode(stages, &s.raw, max).ok()?;
let flate = Params { early_change: 1, ..params.clone() };
let raw = pdfcraft_filters::encode(&Filter::Flate, &flate, &data).ok()?;
diff --git a/crates/optimize/tests/optimize.rs b/crates/optimize/tests/optimize.rs
index b0049a1c6..e78571c1e 100644
--- a/crates/optimize/tests/optimize.rs
+++ b/crates/optimize/tests/optimize.rs
@@ -1271,6 +1271,18 @@ fn lzw_streams_that_cannot_be_read_or_are_not_asked_for_stay_unchanged() {
bad_predictor.dict.set(b"DecodeParms".to_vec(), Object::Dict(parms));
let mut indirect_parms = filtered(&["LZWDecode"], good.clone());
indirect_parms.dict.set(b"DecodeParms".to_vec(), Object::Ref(ObjRef { num: 999, generation: 0 }));
+ // Columns the reader can't take as an integer: read as the default 1 here, so the data is
+ // predicted with one column and decodes, but a viewer resolving the value would use another.
+ let one_column = Params { predictor: 12, ..Params::default() };
+ let odd_columns = |columns: Object| {
+ let mut s = filtered(&["LZWDecode"], lzw(&ops, &one_column));
+ let mut parms = Dict::new();
+ parms.set(b"Predictor".to_vec(), Object::Int(12));
+ parms.set(b"Columns".to_vec(), columns);
+ s.dict.set(b"DecodeParms".to_vec(), Object::Dict(parms));
+ s
+ };
+ assert_eq!(odd_columns(Object::Real(12.5)).decoded_strict().unwrap(), ops, "read with one column");
let mut objstm = filtered(&["LZWDecode"], good.clone());
objstm.dict.set(b"Type".to_vec(), Object::name("ObjStm"));
let mut external = filtered(&["LZWDecode"], good.clone());
@@ -1281,6 +1293,8 @@ fn lzw_streams_that_cannot_be_read_or_are_not_asked_for_stay_unchanged() {
("indirect DecodeParms", indirect_parms, Settings::default()),
("external file", external, Settings::default()),
("object stream, rewritten on save", objstm, Settings::default()),
+ ("Columns by reference", odd_columns(Object::Ref(ObjRef { num: 9, generation: 0 })), Settings::default()),
+ ("Columns not an integer", odd_columns(Object::Real(12.5)), Settings::default()),
("crypt filter", filtered(&["Crypt", "LZWDecode"], good.clone()), Settings::default()),
("option off", filtered(&["LZWDecode"], good.clone()), Settings { lzw_to_flate: false, ..Settings::default() }),
];