Skip to content

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

M11: Export ▸ Images decodes CCITT fax images behind other filters

Grzegorz Martens7ca7e01f921f
diff --git a/crates/create/README.md b/crates/create/README.md
index e8ed9a872..8e0bdc68b 100644
--- a/crates/create/README.md
+++ b/crates/create/README.md
@@ -34,4 +34,4 @@ The existing 16-bit path still uses each sample's high byte.
JPEG image Decode handling remains limited.
ICC transforms and calibrated color conversion remain outside this export path.
CCITT fax images (Group 3 and 4) are decoded for export through `hayro-ccitt` with their `/DecodeParms`
-(`/Columns` has to be the image's width); JPEG 2000 and JBIG2 images are still reported, not exported.
+(`/Columns` has to be the image's width), behind other filters such as `ASCII85Decode` too; JPEG 2000 and JBIG2 images are still reported, not exported.
diff --git a/crates/create/src/extract.rs b/crates/create/src/extract.rs
index 1053df2d7..c67d80bd8 100644
--- a/crates/create/src/extract.rs
+++ b/crates/create/src/extract.rs
@@ -4,6 +4,7 @@
//! key as alpha. Images PdfCraft can't decode yet (JPEG 2000, JBIG2, separations) are
//! reported, never silently left out.
+use std::borrow::Cow;
use std::collections::HashSet;
use pdfcraft_cos::{Dict, Document, ObjRef, Object, Stream};
@@ -100,34 +101,48 @@ fn filters(s: &Stream) -> Vec<Vec<u8>> {
}
}
-/// The samples of image `s`, decoded: through its filters, or, for a CCITT fax image (its only
-/// filter), through a CCITT decoder, as rows of one-bit samples each starting on a byte, with black
-/// as 0 unless `/BlackIs1` says 1, as `CCITTFaxDecode` gives them (ISO 32000-2 §7.4.6).
+/// The samples of image `s`, decoded: through its filters, or, for a CCITT fax image (its last
+/// filter), through the filters before it and then a CCITT decoder, as rows of one-bit samples
+/// each starting on a byte, with black as 0 unless `/BlackIs1` says 1, as `CCITTFaxDecode` gives
+/// them (ISO 32000-2 §7.4.6).
fn decoded(doc: &Document, s: &Stream) -> Result<Vec<u8>, String> {
- match filters(s).as_slice() {
- [f] if f == b"CCITTFaxDecode" || f == b"CCF" => ccitt(doc, s),
+ let names = filters(s);
+ match names.split_last() {
+ Some((f, outer)) if f == b"CCITTFaxDecode" || f == b"CCF" => {
+ // Such as ASCII85Decode, undone first (7.4.1).
+ let chain = s.filters();
+ let data = match chain.split_last() {
+ Some((_, before)) if !before.is_empty() => {
+ Cow::Owned(pdfcraft_filters::decode_tolerant(before, &s.raw, pdfcraft_cos::MAX_DECODED).map_err(|e| e.to_string())?.0)
+ }
+ _ => Cow::Borrowed(&s.raw[..]),
+ };
+ ccitt(doc, s, &data, decode_parms(doc, s, outer.len()))
+ }
_ => s.decoded().map_err(|e| e.to_string()),
}
}
-/// The `/DecodeParms` of a stream with one filter: a dictionary, or the one in an array (7.4.2).
-fn decode_parms(doc: &Document, s: &Stream) -> Dict {
+/// The `/DecodeParms` of filter `index` of a stream: the dictionary of a stream with one filter,
+/// or that entry of an array (7.4.2).
+fn decode_parms(doc: &Document, s: &Stream, index: usize) -> Dict {
let Some(p) = s.dict.get(b"DecodeParms").map(|p| doc.resolve(p)) else { return Dict::default() };
let p = match &*p {
- Object::Array(a) => match a.first() {
- Some(first) => doc.resolve(first),
+ Object::Array(a) => match a.get(index) {
+ Some(entry) => doc.resolve(entry),
None => return Dict::default(),
},
- _ => p,
+ _ if index == 0 => p,
+ _ => return Dict::default(),
};
p.as_dict().cloned().unwrap_or_default()
}
-/// [`decoded`] for a CCITT fax image, with its `/DecodeParms` (Table 11 defaults). `/Columns` has to
-/// be the image's width; pixels past it and rows past the image's height are dropped, so the output
-/// is bounded by the size the caller already checked. A stream that ends early gives fewer rows,
-/// which the caller refuses.
-fn ccitt(doc: &Document, s: &Stream) -> Result<Vec<u8>, String> {
+/// [`decoded`] for a CCITT fax image: `data`, coded with parameters `p` (Table 11 defaults).
+/// `/Columns` has to be the image's width; pixels past it and rows past the image's height are
+/// dropped, so the output is bounded by the size the caller already checked. A stream that ends
+/// early gives fewer rows, which the caller refuses.
+fn ccitt(doc: &Document, s: &Stream, data: &[u8], p: Dict) -> Result<Vec<u8>, String> {
struct Rows {
out: Vec<u8>,
row: Vec<u8>,
@@ -164,7 +179,6 @@ fn ccitt(doc: &Document, s: &Stream) -> Result<Vec<u8>, String> {
self.x = 0;
}
}
- let p = decode_parms(doc, s);
let flag = |key: &[u8], default: bool| match p.get(key).map(|v| doc.resolve(v)).as_deref() {
Some(Object::Bool(b)) => *b,
_ => default,
@@ -197,7 +211,7 @@ fn ccitt(doc: &Document, s: &Stream) -> Result<Vec<u8>, String> {
let mut out =
Rows { out: Vec::new(), row: vec![0; stride], x: 0, columns: columns as usize, rows: rows as usize, black_is_1: flag(b"BlackIs1", false) };
// Rows decoded before damaged data are kept; too few rows are refused by the caller.
- let _ = hayro_ccitt::decode(&s.raw, &mut out, &mut hayro_ccitt::DecoderContext::new(settings));
+ let _ = hayro_ccitt::decode(data, &mut out, &mut hayro_ccitt::DecoderContext::new(settings));
Ok(out.out)
}
diff --git a/crates/create/src/tests.rs b/crates/create/src/tests.rs
index 8ad8a54cd..dd9414dc6 100644
--- a/crates/create/src/tests.rs
+++ b/crates/create/src/tests.rs
@@ -1518,8 +1518,8 @@ fn exported_white(png_data: &[u8]) -> Vec<bool> {
/// Export ▸ Images reads CCITT fax images: a page created from a 1-bit PNG (Group 4 now) exports as
/// the picture, as does the picture coded the other way round with /BlackIs1, the picture with its
-/// filter and parameters in arrays, with /K and /Columns given by reference, and with a /Rows below
-/// its height. One whose /Columns aren't its width is skipped, not misread.
+/// filter and parameters in arrays, with /K and /Columns given by reference, with a /Rows below its
+/// height, and behind another filter. One whose /Columns aren't its width is skipped, not misread.
#[test]
fn ccitt_fax_images_export_as_their_picture() {
use png::{BitDepth, ColorType};
@@ -1579,6 +1579,26 @@ fn ccitt_fax_images_export_as_their_picture() {
assert!(out.skipped.is_empty(), "{:?}", out.skipped);
assert_eq!(exported_white(&out.images[0].data), picture, "/K and /Columns by reference, /Rows 1");
+ // Behind another filter, with its parameters second in the array, as 7.4.1 pairs them.
+ let g4 = pdfcraft_filters::encode_g4(&bits, w, h).unwrap();
+ let hex = g4.iter().map(|b| format!("{b:02x}")).chain([">".to_string()]).collect::<String>().into_bytes();
+ for (outer, data) in [("ASCIIHexDecode", hex), ("FlateDecode", pdfcraft_filters::encode_flate(&g4))] {
+ let mut stream = with(false, i64::from(w), data);
+ let parms = stream.dict.get(b"DecodeParms").cloned().unwrap();
+ stream.dict.set(b"DecodeParms".to_vec(), Object::Array(vec![Object::Null, parms]));
+ stream.dict.set(b"Filter".to_vec(), Object::Array(vec![Object::name(outer), Object::name("CCITTFaxDecode")]));
+ doc.set(r, Object::Stream(stream));
+ let out = extract_images(&doc, &[0], 0);
+ assert!(out.skipped.is_empty(), "{outer}: {:?}", out.skipped);
+ assert_eq!(exported_white(&out.images[0].data), picture, "behind {outer}");
+ }
+ // CCITT before another filter isn't a picture yet.
+ let mut stream = with(false, i64::from(w), pdfcraft_filters::encode_flate(&g4));
+ stream.dict.set(b"Filter".to_vec(), Object::Array(vec![Object::name("CCITTFaxDecode"), Object::name("FlateDecode")]));
+ doc.set(r, Object::Stream(stream));
+ let out = extract_images(&doc, &[0], 0);
+ assert!(out.images.is_empty() && out.skipped.len() == 1, "CCITT, then Flate: skipped");
+
let stream = with(false, i64::from(w) + 8, pdfcraft_filters::encode_g4(&bits, w, h).unwrap());
doc.set(r, Object::Stream(stream));
let out = extract_images(&doc, &[0], 0);
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index e7c515e61..bf96832b1 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -7165,7 +7165,7 @@ status = "shipped"
commands = ["export.all_images"]
tools = ["doc_export_all_images"]
evidence = ["crates/create/src/tests.rs::ccitt_fax_images_export_as_their_picture", "crates/create/src/tests.rs::images_export_as_jpeg_unchanged_and_others_as_png", "crates/create/src/tests.rs::indexed_and_one_bit_images_decode", "crates/create/src/tests.rs::jpeg_images_with_a_soft_mask_export_as_png_with_alpha", "crates/create/src/tests.rs::soft_masks_of_another_size_and_stencil_and_colour_key_masks_become_alpha", "crates/create/src/tests.rs::soft_mask_decode_ranges_become_exported_alpha", "crates/create/src/tests.rs::soft_mask_decode_maps_packed_and_jpeg_masks_before_resizing", "crates/automation/tests/it/automation.rs::exporting_all_images_through_tools", "crates/ui-egui/tests/it/export.rs::export_dialogs_write_images_and_text", "crates/create/src/tests.rs::lossless_decode_maps_each_component_before_colour_conversion", "crates/create/src/tests.rs::lossless_indexed_decode_rounds_in_index_units_then_clamps"]
-notes = "each image once (page resources and nested forms); JPEG unchanged unless it has transparency, others PNG (gray/RGB/CMYK/ICC/Indexed, 1–16 bpc, stencil masks); transparency as PNG alpha: /SMask (scaled to the image size, /Matte un-blended), stencil /Mask and colour-key /Mask, JPEG images included (#645); JPX/JBIG2 masks are left out (image exported opaque); JPX/JBIG2/separations reported as skipped; minimum size filter. Lossless images apply per-component Decode; Indexed values round and clip before palette lookup. Missing, null or malformed Decode arrays keep the default mapping. Soft-mask Decode intervals preserve opacity before resizing, including indirect arrays and endpoints. Still limited: 16-bit samples use high bytes; general JPEG image Decode, ICC transforms, and calibrated colors remain unsupported. CCITT fax images (Group 3 and 4, with their /DecodeParms) export as their picture, masks included."
+notes = "each image once (page resources and nested forms); JPEG unchanged unless it has transparency, others PNG (gray/RGB/CMYK/ICC/Indexed, 1–16 bpc, stencil masks); transparency as PNG alpha: /SMask (scaled to the image size, /Matte un-blended), stencil /Mask and colour-key /Mask, JPEG images included (#645); JPX/JBIG2 masks are left out (image exported opaque); JPX/JBIG2/separations reported as skipped; minimum size filter. Lossless images apply per-component Decode; Indexed values round and clip before palette lookup. Missing, null or malformed Decode arrays keep the default mapping. Soft-mask Decode intervals preserve opacity before resizing, including indirect arrays and endpoints. Still limited: 16-bit samples use high bytes; general JPEG image Decode, ICC transforms, and calibrated colors remain unsupported. CCITT fax images (Group 3 and 4, with their /DecodeParms, behind other filters too) export as their picture, masks included."
[[feature]]
id = "create.export-html"