DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
PDF: transparency groups blend in CMYK in print exports
japbcoelho0ce21b476ccc
diff --git a/crates/engine/src/cmd/export.rs b/crates/engine/src/cmd/export.rsindex c9d7e28dd..0ed003cfe 100644--- a/crates/engine/src/cmd/export.rs+++ b/crates/engine/src/cmd/export.rs@@ -851,3 +851,49 @@ mod placed_pdf_print_tests {assert!(e.contains("logo.pdf is PDF 2.0") && e.contains("PDF 1.6"), "{e}");}}++#[cfg(test)]+mod print_group_tests {+ use serde_json::json;++ use crate::Session;+ use crate::cmd::{base64_decode, base64_encode};++ /// A one-page PDF 1.7 with a black box, as VectorCraft writes a logo.+ fn logo() -> Vec<u8> {+ let mut s = Session::new();+ s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();+ s.execute("frame.create", &json!({"rect": [10, 10, 90, 40]})).unwrap();+ s.execute("object.fill", &json!({"swatch": "[Black]"})).unwrap();+ let r = s.execute("file.exportPdf", &json!({})).unwrap();+ base64_decode(r["base64"].as_str().unwrap())+ }++ fn page_with(pdf: &[u8]) -> Session {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute("file.place", &json!({"base64": base64_encode(pdf), "name": "logo.pdf", "x": 72, "y": 72})).unwrap();+ s+ }++ /// The placed PDF's transparency group blended in DeviceRGB in a print document+ /// (`/Group<</Type/Group/S/Transparency/I true/CS/DeviceRGB>>`).+ #[test]+ fn print_transparency_groups_blend_in_cmyk() {+ let mut s = page_with(&logo());+ let text = |s: &mut Session| {+ let r = s.execute("file.exportPdf", &json!({"compress": false})).unwrap();+ String::from_utf8_lossy(&base64_decode(r["base64"].as_str().unwrap())).into_owned()+ };+ let t = text(&mut s);+ assert!(t.contains("/S/Transparency/I true/CS/DeviceCMYK>>"), "CMYK group");+ assert!(!t.contains("DeviceRGB"), "no RGB left");+ // The file still reads, with the same page.+ let r = s.execute("file.exportPdf", &json!({})).unwrap();+ let bytes = base64_decode(r["base64"].as_str().unwrap());+ assert_eq!(hayro_syntax::Pdf::new(bytes).unwrap().pages().len(), 1);+ // An RGB blend space keeps RGB groups.+ s.execute("edit.transparencyBlendSpace", &json!({"space": "rgb"})).unwrap();+ assert!(text(&mut s).contains("/CS/DeviceRGB"));+ }+}diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rsindex 213d7676c..0800e61bf 100644--- a/crates/pdf/src/export.rs+++ b/crates/pdf/src/export.rs@@ -204,6 +204,10 @@ pub fn export_pdf_with_report(doc: &Document, cache: &Cache, opts: &PdfOptions)}ex.check_placed_versions()?;let mut bytes = pdf.finish().map_err(|e| PdfError::Write(format!("{e:?}")))?;+ // Transparency blends in the document's blend space: CMYK for print (and always in PDF/X).+ if !ex.rgb_only && (doc.settings.blend_space == designcraft_doc::BlendSpace::Cmyk || opts.standard == Standard::PdfX4) {+ crate::pdfx::cmyk_group_spaces(&mut bytes);+ }let mut warnings = ex.warnings;// Form fields (Buttons and Forms) and, for interactive PDF, video and sound; not in PDF/X.let fields = crate::forms::collect(doc, &sheets);@@ -360,7 +364,10 @@ pub fn export_booklet(doc: &Document, cache: &Cache, opts: &BookletOptions) -> Rpage.finish();}ex.check_placed_versions()?;- let bytes = pdf.finish().map_err(|e| PdfError::Write(format!("{e:?}")))?;+ let mut bytes = pdf.finish().map_err(|e| PdfError::Write(format!("{e:?}")))?;+ if doc.settings.blend_space == designcraft_doc::BlendSpace::Cmyk {+ crate::pdfx::cmyk_group_spaces(&mut bytes);+ }let mut warnings = ex.warnings;warnings.dedup();Ok(ExportReport { bytes, pages: pairs.len(), warnings })diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rsindex 41f89305a..8aff66036 100644--- a/crates/pdf/src/lib.rs+++ b/crates/pdf/src/lib.rs@@ -35,7 +35,7 @@ mod forms;mod pdfx;mod transitions;pub use export::{BookletKind, BookletOptions, booklet_pairs, export_booklet, export_pdf, export_pdf_with_report, merge_pdfs, sheet_spreads};-pub use pdfx::{check_pdfx4, make_pdfx4};+pub use pdfx::{check_pdfx4, cmyk_group_spaces, make_pdfx4};pub use transitions::{add_blend_space, add_catalog_entries, add_page_entries, add_transitions};/// PDF standard to target.diff --git a/crates/pdf/src/pdfx.rs b/crates/pdf/src/pdfx.rsindex 891cf2e47..2a1348907 100644--- a/crates/pdf/src/pdfx.rs+++ b/crates/pdf/src/pdfx.rs@@ -118,6 +118,68 @@ pub fn make_pdfx4(pdf: &[u8], title: &str) -> Option<Vec<u8>> {Some(out)}+/// krilla gives every transparency group it writes (placed PDF pages, opacity, isolated+/// blending) a DeviceRGB blending space. In a print document that puts DeviceRGB in a CMYK file+/// (PDF/X-4 forbids it under a CMYK output intent) and blends CMYK art through RGB, which can+/// turn a K-only black into a four-colour black. This rewrites those group dictionaries to+/// DeviceCMYK in place and at the same length (the optional `/Type/Group` gives the room), so+/// every cross-reference offset stays valid. Only object dictionaries are touched, never stream+/// data. Returns how many groups changed.+pub fn cmyk_group_spaces(pdf: &mut [u8]) -> usize {+ const FORMS: [(&[u8], &[u8]); 2] = [+ (b"/Group<</Type/Group/S/Transparency/I true/CS/DeviceRGB>>", b"/Group<</S/Transparency/I true/CS/DeviceCMYK>>"),+ (b"/Group<</Type/Group/S/Transparency/CS/DeviceRGB>>", b"/Group<</S/Transparency/CS/DeviceCMYK>>"),+ ];+ let Some(dicts) = dictionary_ranges(pdf) else { return 0 };+ let mut changed = 0;+ for r in dicts {+ for (from, to) in FORMS {+ let mut at = r.start;+ while let Some(i) = find(pdf.get(..r.end).unwrap_or_default(), from, at) {+ if let Some(dst) = pdf.get_mut(i..i + from.len()) {+ dst.fill(b' ');+ if let Some(head) = dst.get_mut(..to.len()) {+ head.copy_from_slice(to);+ changed += 1;+ }+ }+ at = i + from.len();+ }+ }+ }+ changed+}++/// Byte ranges of the dictionary part of every object in a file with one classic+/// cross-reference table (krilla's output): from the object's offset to its `stream` keyword or+/// `endobj`. `None` when the table can't be read.+fn dictionary_ranges(pdf: &[u8]) -> Option<Vec<std::ops::Range<usize>>> {+ let tail = String::from_utf8_lossy(pdf.get(rfind(pdf, b"startxref")?..)?).to_string();+ let xref = int_after(&tail, "startxref")?;+ let table = pdf.get(xref..)?;+ if !table.starts_with(b"xref") {+ return None;+ }+ let end = find(table, b"trailer", 0)?;+ let text = String::from_utf8_lossy(table.get(4..end)?).to_string();+ let mut words = text.split_ascii_whitespace();+ let mut out = Vec::new();+ while let (Some(_first), Some(count)) = (words.next(), words.next()) {+ let count: usize = count.parse().ok()?;+ for _ in 0..count {+ let (off, _gen, kind) = (words.next()?, words.next()?, words.next()?);+ if kind != "n" {+ continue;+ }+ let start: usize = off.parse().ok()?;+ let endobj = find(pdf, b"endobj", start)?;+ let stop = find(pdf.get(..endobj)?, b"stream", start).unwrap_or(endobj);+ out.push(start..stop);+ }+ }+ Some(out)+}+/// PDF/X-4 checks on an exported file: what's missing (empty = passes these checks).pub fn check_pdfx4(pdf: &[u8]) -> Vec<String> {let mut issues = Vec::new();