From 5c32aadb801f27c05c1c3792baca31c7f967f546 Mon Sep 17 00:00:00 2001 From: Dmytro Chornyi Date: Fri, 20 Nov 2026 08:46:22 +0100 Subject: [PATCH] PDF export: the CMYK document warning says whether RGB images are converted (#1242) In a CMYK document exported with No conversion, RGB vector colours are separated into CMYK but placed RGB images are written as RGB. The export warning still said they "are converted to CMYK through the colour settings", so files reached printers with RGB images in them. The warning now counts RGB images by what actually happens to them: converted to CMYK with a CMYK destination (Convert to destination, or PDF/X-1a), else written in RGB, with the settings that write them in CMYK. Grey images stay grey either way and are no longer counted as RGB. RGB colours keep their wording. The written PDF is unchanged. --- crates/pdf/src/export/entry.rs | 49 ++++++++++++++++++---------- crates/pdf/src/export/images.rs | 8 +++-- crates/pdf/src/images.rs | 19 +++++++++-- crates/pdf/src/tests/output.rs | 58 +++++++++++++++++++++++++++++++++ 4 files changed, 112 insertions(+), 22 deletions(-) diff --git a/crates/pdf/src/export/entry.rs b/crates/pdf/src/export/entry.rs index fcdcd01f63..83ed7e07da 100644 --- a/crates/pdf/src/export/entry.rs +++ b/crates/pdf/src/export/entry.rs @@ -369,38 +369,51 @@ fn long_page_warning(set: &PdfSettings, artboard: usize, w: f64, h: f64, unit: f } } -/// The RGB colours and non-CMYK images a CMYK document carries, which the export separates into -/// CMYK. Their darkest values come out as rich blacks, so the export says how many there are. +/// The RGB colours and RGB images a CMYK document carries. Its RGB colours are always separated +/// into CMYK; its RGB images only with a CMYK destination (Output › Color conversion, or a +/// PDF/X-1a preset), else they are written in RGB (#1242). The export says how many of each +/// there are: converted ones' darkest values come out as rich blacks, and kept ones aren't CMYK. +/// Grey images stay grey either way and aren't counted. #[derive(Default)] pub(crate) struct RgbInCmyk { /// Distinct RGB colours, by the bits of their channels. pub(super) colours: HashSet<[u32; 3]>, - /// Keys of the raster images that aren't CMYK. - pub(super) images: HashSet, + /// Keys of the RGB images converted to CMYK. + pub(super) converted: HashSet, + /// Keys of the RGB images written in RGB. + pub(super) kept: HashSet, +} + +/// `n` `thing`s, in the plural unless `n` is 1. +fn count(n: usize, thing: &str) -> String { + format!("{n} {thing}{}", if n == 1 { "" } else { "s" }) } impl RgbInCmyk { pub(super) fn merge(&mut self, other: RgbInCmyk) { self.colours.extend(other.colours); - self.images.extend(other.images); + self.converted.extend(other.converted); + self.kept.extend(other.kept); } /// The warning for the export report; `None` when the document has nothing of the sort. pub(super) fn warning(&self) -> Option { - let (c, i) = (self.colours.len(), self.images.len()); - if c == 0 && i == 0 { - return None; + let (c, i, k) = (self.colours.len(), self.converted.len(), self.kept.len()); + let mut sentences = vec![]; + let converted: Vec<_> = [(c, "RGB colour"), (i, "RGB image")].into_iter().filter(|(n, _)| *n > 0).map(|(n, t)| count(n, t)).collect(); + if !converted.is_empty() { + sentences.push(format!( + "{}: they are converted to CMYK through the colour settings, so dark ones can come out as rich blacks on several plates; paint them with CMYK colours (Edit › Edit Colors › Convert to CMYK) for pure black ink", + converted.join(" and ") + )); } - let mut parts = vec![]; - if c > 0 { - parts.push(format!("{c} RGB colour{}", if c == 1 { "" } else { "s" })); + if k > 0 { + let (it, is) = if k == 1 { ("it", "is") } else { ("them", "are") }; + sentences.push(format!( + "{} that {is} written in RGB, not CMYK: to write {it} in CMYK, choose Output › Color conversion › Convert to destination with a CMYK destination, or the PDF/X-1a:2001 preset", + count(k, "RGB image") + )); } - if i > 0 { - parts.push(format!("{i} RGB or grey image{}", if i == 1 { "" } else { "s" })); - } - Some(format!( - "this CMYK document has {}: they are converted to CMYK through the colour settings, so dark ones can come out as rich blacks on several plates; paint them with CMYK colours (Edit › Edit Colors › Convert to CMYK) for pure black ink", - parts.join(" and ") - )) + (!sentences.is_empty()).then(|| format!("this CMYK document has {}", sentences.join("; and "))) } } diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 3da2079b9b..763a8e2c1b 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -149,8 +149,12 @@ impl Exporter<'_> { let mut unconverted = false; let img = doc.image_blob(im).filter(|_| !self.left_out.contains(key)).and_then(|blob| { let cmyk_image = blob.is_cmyk(); - if !cmyk_image && self.convert && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { - self.rgb_in_cmyk.images.insert(key.to_string()); + // RGB images of a CMYK document go to CMYK only with a CMYK destination; grey ones stay + // grey ([`crate::images::recode`]). + if !cmyk_image && self.convert && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk && !crate::images::is_grey(&blob.bytes) { + let to_cmyk = matches!(out.pixels(), Some(crate::output::Pixels::Cmyk(_))); + let set = if to_cmyk { &mut self.rgb_in_cmyk.converted } else { &mut self.rgb_in_cmyk.kept }; + set.insert(key.to_string()); } let r = if cmyk_image { let icc = out.cmyk_image_icc(blob); diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index eaff6c781f..7f6b721c7b 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -528,6 +528,22 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic } } +/// Are samples of type `t` grey (with or without alpha)? [`recode`] keeps such pixels grey. +fn grey_type(t: ExtendedColorType) -> bool { + use ExtendedColorType as T; + matches!(t, T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16) +} + +/// Does the image in `bytes` hold grey samples, which [`recode`] keeps grey whatever the Output +/// settings? Reads only its header; `false` for one that can't be read. +pub(crate) fn is_grey(bytes: &[u8]) -> bool { + ImageReader::new(Cursor::new(bytes)) + .with_guessed_format() + .ok() + .and_then(|r| r.into_decoder().ok()) + .is_some_and(|d| grey_type(d.original_color_type())) +} + /// Encoded image `bytes` placed `size` points wide and high, as the Compression settings `c` ask: /// resampled when its resolution is above the threshold, compressed with ZIP or JPEG, its colours /// converted by `convert` (colour images). Pixels that keep their colours keep the ICC profile @@ -554,8 +570,7 @@ pub(crate) fn recode( let jpeg = reader.format() == Some(ImageFormat::Jpeg); let Ok(mut decoder) = reader.into_decoder() else { return keep }; let dims = decoder.dimensions(); - use ExtendedColorType as T; - let grey = matches!(decoder.original_color_type(), T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16); + let grey = grey_type(decoder.original_color_type()); // Pixels in a profile they are converted from are decoded, whatever the Compression settings. // Grey pixels keep their profile unless the destination is sRGB ([`ToSrgb::grey`]). let then = to_srgb.and_then(|t| t.then); diff --git a/crates/pdf/src/tests/output.rs b/crates/pdf/src/tests/output.rs index d9c2fedc1d..42a1dcafaa 100644 --- a/crates/pdf/src/tests/output.rs +++ b/crates/pdf/src/tests/output.rs @@ -705,3 +705,61 @@ fn colours_are_in_the_profiles_assigned_to_the_document() { assert!(r.warnings.iter().any(|w| w.contains("No Such Press")), "{:?}", r.warnings); assert!(icc_streams(&r.bytes) == [cms::icc_bytes(&working).unwrap().to_vec()]); } + +/// A 4 × 4 greyscale PNG of one level. +fn grey_png(level: u8) -> Vec { + let img = craft_image_codecs::Image::from_raw(4, 4, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, vec![level; 16]) + .unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() +} + +/// The CMYK document warning says what happens to its RGB images (#1242): with No conversion +/// they are written in RGB, and it names the settings that write them in CMYK; with a CMYK +/// destination they are converted. Grey images stay grey either way and aren't counted. +#[test] +fn the_cmyk_document_warning_says_whether_rgb_images_are_converted() { + let warning = |d: &Document, settings: Value| { + let r = pdf(d, settings); + let w: Vec<_> = r.warnings.iter().filter(|w| w.contains("this CMYK document")).cloned().collect(); + assert!(w.len() <= 1, "{w:?}"); + w.into_iter().next() + }; + let mut d = image_doc(png([200, 30, 30])); + d.color_mode = ColorMode::Cmyk; + + // No conversion: the image is written in RGB, and the warning doesn't say otherwise. + let kept = warning(&d, json!({})).unwrap(); + assert!(kept.contains("1 RGB image") && kept.contains("written in RGB"), "{kept}"); + assert!(!kept.contains("converted to CMYK"), "{kept}"); + assert!(kept.contains("Convert to destination") && kept.contains("PDF/X-1a"), "{kept}"); + + // A CMYK destination converts it. + for settings in + [json!({"output": {"conversion": "destination", "destination": GENERIC_CMYK}}), json!({"standard": "pdfX1a", "compatibility": "1.3"})] + { + let converted = warning(&d, settings.clone()).unwrap(); + assert!(converted.contains("1 RGB image") && converted.contains("converted to CMYK"), "{settings}: {converted}"); + assert!(!converted.contains("written in RGB"), "{settings}: {converted}"); + } + + // A grey image is not an RGB image: nothing to warn about. + let mut grey = image_doc(grey_png(90)); + grey.color_mode = ColorMode::Cmyk; + for settings in [json!({}), json!({"output": {"conversion": "destination", "destination": GENERIC_CMYK}})] { + assert_eq!(warning(&grey, settings.clone()), None, "{settings}"); + } + + // RGB colours keep their wording beside images kept in RGB. + let mut both = image_doc(png([200, 30, 30])); + both.color_mode = ColorMode::Cmyk; + let l = both.layers[0].id; + let n = Node::path( + both.alloc_id(), + shapes::rectangle(Rect::new(50.0, 50.0, 70.0, 70.0)), + Appearance::basic(Paint::solid(Color::Rgb { r: 0.1, g: 0.1, b: 0.1 }), Paint::None, 0.0), + ); + both.insert(Some(l), 1, n).unwrap(); + let w = warning(&both, json!({})).unwrap(); + assert!(w.contains("1 RGB colour") && w.contains("converted to CMYK") && w.contains("rich blacks"), "{w}"); + assert!(w.contains("1 RGB image") && w.contains("written in RGB"), "{w}"); +}