Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Print color: X-1a written by craft-pdf at PDF 1.4 (craft-libs#194 d30598d)

aionggc50321c852fb
diff --git a/Cargo.lock b/Cargo.lock
index eae5c79a1..61b84b72d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -822,7 +822,7 @@ dependencies = [
[[package]]
name = "craft-cms"
version = "0.1.0"
-source = "git+https://github.com/aiongg/craft-libs?rev=d11403fde04311cd50cc9913f3bc43ff6a419945#d11403fde04311cd50cc9913f3bc43ff6a419945"
+source = "git+https://github.com/aiongg/craft-libs?rev=d30598dcb4b389561c485b97d4a97a0c86bc36e4#d30598dcb4b389561c485b97d4a97a0c86bc36e4"
dependencies = [
"rayon",
]
@@ -843,7 +843,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=82a24b006eefa036b43c09
[[package]]
name = "craft-pdf"
version = "0.1.0"
-source = "git+https://github.com/aiongg/craft-libs?rev=d11403fde04311cd50cc9913f3bc43ff6a419945#d11403fde04311cd50cc9913f3bc43ff6a419945"
+source = "git+https://github.com/aiongg/craft-libs?rev=d30598dcb4b389561c485b97d4a97a0c86bc36e4#d30598dcb4b389561c485b97d4a97a0c86bc36e4"
dependencies = [
"bytemuck",
"hayro",
@@ -856,9 +856,9 @@ dependencies = [
[[package]]
name = "craft-prepress"
version = "0.1.0"
-source = "git+https://github.com/aiongg/craft-libs?rev=d11403fde04311cd50cc9913f3bc43ff6a419945#d11403fde04311cd50cc9913f3bc43ff6a419945"
+source = "git+https://github.com/aiongg/craft-libs?rev=d30598dcb4b389561c485b97d4a97a0c86bc36e4#d30598dcb4b389561c485b97d4a97a0c86bc36e4"
dependencies = [
- "craft-cms 0.1.0 (git+https://github.com/aiongg/craft-libs?rev=d11403fde04311cd50cc9913f3bc43ff6a419945)",
+ "craft-cms 0.1.0 (git+https://github.com/aiongg/craft-libs?rev=d30598dcb4b389561c485b97d4a97a0c86bc36e4)",
"craft-pdf",
"kurbo",
"linesweeper",
@@ -2135,7 +2135,7 @@ dependencies = [
[[package]]
name = "hayro"
version = "0.7.1"
-source = "git+https://github.com/aiongg/craft-libs?rev=d11403fde04311cd50cc9913f3bc43ff6a419945#d11403fde04311cd50cc9913f3bc43ff6a419945"
+source = "git+https://github.com/aiongg/craft-libs?rev=d30598dcb4b389561c485b97d4a97a0c86bc36e4#d30598dcb4b389561c485b97d4a97a0c86bc36e4"
dependencies = [
"bytemuck",
"hayro-interpret",
@@ -2165,7 +2165,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
-source = "git+https://github.com/aiongg/craft-libs?rev=d11403fde04311cd50cc9913f3bc43ff6a419945#d11403fde04311cd50cc9913f3bc43ff6a419945"
+source = "git+https://github.com/aiongg/craft-libs?rev=d30598dcb4b389561c485b97d4a97a0c86bc36e4#d30598dcb4b389561c485b97d4a97a0c86bc36e4"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -2183,7 +2183,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
-source = "git+https://github.com/aiongg/craft-libs?rev=d11403fde04311cd50cc9913f3bc43ff6a419945#d11403fde04311cd50cc9913f3bc43ff6a419945"
+source = "git+https://github.com/aiongg/craft-libs?rev=d30598dcb4b389561c485b97d4a97a0c86bc36e4#d30598dcb4b389561c485b97d4a97a0c86bc36e4"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -2207,7 +2207,7 @@ checksum = "885c5ef0654933139a9b9546fc2c69e18d37f38aa2520f079092b1be18f1fcaa"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
-source = "git+https://github.com/aiongg/craft-libs?rev=d11403fde04311cd50cc9913f3bc43ff6a419945#d11403fde04311cd50cc9913f3bc43ff6a419945"
+source = "git+https://github.com/aiongg/craft-libs?rev=d30598dcb4b389561c485b97d4a97a0c86bc36e4#d30598dcb4b389561c485b97d4a97a0c86bc36e4"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -2571,7 +2571,7 @@ dependencies = [
[[package]]
name = "krilla"
version = "0.8.2"
-source = "git+https://github.com/aiongg/craft-libs?rev=d11403fde04311cd50cc9913f3bc43ff6a419945#d11403fde04311cd50cc9913f3bc43ff6a419945"
+source = "git+https://github.com/aiongg/craft-libs?rev=d30598dcb4b389561c485b97d4a97a0c86bc36e4#d30598dcb4b389561c485b97d4a97a0c86bc36e4"
dependencies = [
"base64",
"bumpalo",
diff --git a/Cargo.toml b/Cargo.toml
index b1ba7e495..c50b2dc1b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -12,9 +12,9 @@ repository = "https://github.com/storytold/designcraft"
[workspace.dependencies]
# Shared writer; the immutable revision must be published before this consumer.
-craft-pdf = { git = "https://github.com/aiongg/craft-libs", rev = "d11403fde04311cd50cc9913f3bc43ff6a419945", version = "=0.1.0", default-features = false }
+craft-pdf = { git = "https://github.com/aiongg/craft-libs", rev = "d30598dcb4b389561c485b97d4a97a0c86bc36e4", version = "=0.1.0", default-features = false }
# Separations, ink coverage and the ink manager; same revision as craft-pdf and the krilla patch.
-craft-prepress = { git = "https://github.com/aiongg/craft-libs", rev = "d11403fde04311cd50cc9913f3bc43ff6a419945", version = "=0.1.0", features = ["flatten"] }
+craft-prepress = { git = "https://github.com/aiongg/craft-libs", rev = "d30598dcb4b389561c485b97d4a97a0c86bc36e4", version = "=0.1.0", features = ["flatten"] }
# internal
designcraft-geom = { path = "crates/geom" }
designcraft-color = { path = "crates/color" }
@@ -119,10 +119,10 @@ debug = 0
# Opt-in cancelable macOS termination on the pinned winit 0.30 line.
[patch.crates-io]
winit = { git = "https://github.com/skylartaylor/winit.git", rev = "3d51077fd1a966f84df9ef287839dc84fd5b4ca7" }
-krilla = { git = "https://github.com/aiongg/craft-libs", rev = "d11403fde04311cd50cc9913f3bc43ff6a419945", version = "=0.8.2" }
+krilla = { git = "https://github.com/aiongg/craft-libs", rev = "d30598dcb4b389561c485b97d4a97a0c86bc36e4", version = "=0.8.2" }
# The hayro crates from craft-libs' vendor/ directory (pdfcraft's patches plus craft-libs'; see its
# vendor/README.craft-reader.md), at the craft-pdf revision.
-hayro = { git = "https://github.com/aiongg/craft-libs", rev = "d11403fde04311cd50cc9913f3bc43ff6a419945" }
-hayro-interpret = { git = "https://github.com/aiongg/craft-libs", rev = "d11403fde04311cd50cc9913f3bc43ff6a419945" }
-hayro-syntax = { git = "https://github.com/aiongg/craft-libs", rev = "d11403fde04311cd50cc9913f3bc43ff6a419945" }
-hayro-jbig2 = { git = "https://github.com/aiongg/craft-libs", rev = "d11403fde04311cd50cc9913f3bc43ff6a419945" }
+hayro = { git = "https://github.com/aiongg/craft-libs", rev = "d30598dcb4b389561c485b97d4a97a0c86bc36e4" }
+hayro-interpret = { git = "https://github.com/aiongg/craft-libs", rev = "d30598dcb4b389561c485b97d4a97a0c86bc36e4" }
+hayro-syntax = { git = "https://github.com/aiongg/craft-libs", rev = "d30598dcb4b389561c485b97d4a97a0c86bc36e4" }
+hayro-jbig2 = { git = "https://github.com/aiongg/craft-libs", rev = "d30598dcb4b389561c485b97d4a97a0c86bc36e4" }
diff --git a/apps/designcraft-cli/src/main.rs b/apps/designcraft-cli/src/main.rs
index 0e3a02a18..929c5cccf 100644
--- a/apps/designcraft-cli/src/main.rs
+++ b/apps/designcraft-cli/src/main.rs
@@ -180,8 +180,10 @@ fn validate_pdf(args: &[String]) -> Result<(), String> {
designcraft_pdf::Standard::PdfX4 => ("PDF/X-4", designcraft_pdf::check_pdfx4(&bytes)),
_ => return Err(USAGE.into()),
};
+ let (warnings, issues): (Vec<String>, Vec<String>) = issues.into_iter().partition(|i| i.starts_with("warning: "));
+ let warnings: Vec<&str> = warnings.iter().map(|w| w.trim_start_matches("warning: ")).collect();
let valid = issues.is_empty();
- let report = json!({"path": path, "standard": name, "valid": valid, "issues": issues});
+ let report = json!({"path": path, "standard": name, "valid": valid, "issues": issues, "warnings": warnings});
outln!("{}", serde_json::to_string_pretty(&report).map_err(|e| e.to_string())?);
if valid { Ok(()) } else { Err(format!("{path} failed {name} validation")) }
}
diff --git a/crates/engine/src/cmd/export.rs b/crates/engine/src/cmd/export.rs
index b644eebc6..9655432ad 100644
--- a/crates/engine/src/cmd/export.rs
+++ b/crates/engine/src/cmd/export.rs
@@ -1154,7 +1154,9 @@ mod text_tests {
let r = s.execute("file.exportPdf", &json!({"standard": "x1a", "flatten": "low"})).unwrap();
let pdf = super::super::file::base64_decode(r["base64"].as_str().unwrap());
let text = String::from_utf8_lossy(&pdf).to_string();
- assert_eq!(designcraft_pdf::check_pdfx1a(&pdf), Vec::<String>::new());
+ // The only finding: the built-in Coated FOGRA39 output intent is an ICC v4 profile.
+ let issues = designcraft_pdf::check_pdfx1a(&pdf);
+ assert!(issues.iter().all(|i| i.contains("ICC v4")), "{issues:?}");
assert!(pdf.starts_with(b"%PDF-1.4") && text.contains("/GTS_PDFXVersion(PDF/X-1:2003)") && text.contains("/S/GTS_PDFX"));
let warnings = r["warnings"].to_string();
assert!(!warnings.contains("soft effects"), "the shadow isn't an RGB image of the object: {warnings}");
diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs
index 9287ba325..bd7440faa 100644
--- a/crates/pdf/src/export.rs
+++ b/crates/pdf/src/export.rs
@@ -276,7 +276,7 @@ fn export_pdf_with_report_inner(doc: &Document, cache: &Cache, opts: &PdfOptions
}
}
if opts.standard == Standard::PdfX1a {
- bytes = crate::pdfx1a::flatten_x1a(&bytes, opts.flatten_dpi, created, &mut warnings)?;
+ bytes = crate::pdfx1a::flatten_x1a(&bytes, opts.flatten_dpi, &mut warnings)?;
}
warnings.dedup();
Ok(ExportReport { bytes, pages: sheets.len(), warnings })
diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs
index 4ba3e6846..f7f6e47b7 100644
--- a/crates/pdf/src/lib.rs
+++ b/crates/pdf/src/lib.rs
@@ -29,8 +29,8 @@
//! - **Marks:** crop marks, bleed marks and a page-information line, drawn in `[Registration]`.
//! - **Standards:** PDF/A-2b through krilla's validator and PDF/X-4 output intent/identification
//! with built-in conformance checks. PDF/X-1a:2003 is the PDF/X-4 print file flattened by
-//! craft-prepress (no transparency, only DeviceCMYK, DeviceGray, Separation and DeviceN), then
-//! identified as PDF 1.4 and PDF/X-1a. `designcraft-cli validate-pdf` exposes those checks for CI.
+//! craft-prepress (no transparency, only DeviceCMYK, DeviceGray, Separation and DeviceN) and
+//! written by krilla as PDF 1.4 with the PDF/X-1a identification. `designcraft-cli validate-pdf` exposes those checks for CI.
//!
//! Not yet: tagged PDF, bookmarks, hyperlinks, layers as optional content.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
@@ -50,7 +50,7 @@ pub use export::{
BookletKind, BookletOptions, booklet_pairs, export_booklet, export_pdf, export_pdf_with_report, merge_pdfs, print_color, sheet_spreads,
};
pub use pdfx::{check_pdfx4, has_rgb_groups, make_pdfx4};
-pub use pdfx1a::{check_pdfx1a, make_pdfx1a};
+pub use pdfx1a::check_pdfx1a;
pub use transitions::{add_blend_space, add_catalog_entries, add_page_entries, add_transitions};
/// PDF standard to target.
diff --git a/crates/pdf/src/pdfx1a.rs b/crates/pdf/src/pdfx1a.rs
index 5abde66f1..d17bba741 100644
--- a/crates/pdf/src/pdfx1a.rs
+++ b/crates/pdf/src/pdfx1a.rs
@@ -1,9 +1,10 @@
//! PDF/X-1a:2003: the PDF/X-4 print file flattened by craft-prepress (no transparency left; RGB
//! and ICC color converted into the output intent's CMYK; inks, overprint and live text kept),
-//! then identified as PDF 1.4 and PDF/X-1a, and checked.
+//! written by krilla as PDF 1.4 with the PDF/X-1a identification, then checked.
use std::collections::HashSet;
+use craft_pdf::write::backend::configure::PdfVersion;
use craft_prepress::flatten::pdf::ReadOptions;
use craft_prepress::flatten::{FlattenDocumentOptions, FlattenOptions, flatten_document};
use hayro_syntax::content::UntypedIter;
@@ -12,25 +13,30 @@ use hayro_syntax::page::Resources;
use crate::PdfError;
use crate::pdfx::{MAX_DEPTH, cmyk_output_intent};
-use crate::transitions::{find, int_after, object, rfind};
-/// `GTS_PDFXVersion` of PDF/X-1a:2003.
+/// `GTS_PDFXVersion` of PDF/X-1a:2003 (ISO 15930-4).
const VERSION: &str = "PDF/X-1:2003";
-/// `GTS_PDFXConformance` of PDF/X-1a:2003.
-const CONFORMANCE: &str = "PDF/X-1a:2003";
-/// The PDF/X-1a file for `pdf`, the PDF/X-4 print file: flattened at `dpi`, identified, checked.
-/// Fails when the flattener fails or the result still has transparency or color outside
-/// DeviceCMYK, DeviceGray, Separation and DeviceN; other check findings become warnings.
-pub(crate) fn flatten_x1a(pdf: &[u8], dpi: f32, date: Option<i64>, warnings: &mut Vec<String>) -> crate::Result<Vec<u8>> {
+/// [`check_pdfx1a`]'s finding for an ICC v4 output intent in a file of PDF 1.5 or lower: a
+/// warning, as the file may still pass a given preflight.
+const V4_INTENT: &str = "warning: the output intent's profile is ICC v4, which PDF/X-1a preflight in a PDF 1.4 file may reject: \
+ choose a CMYK working space with an ICC v2 profile";
+
+/// The PDF/X-1a file for `pdf`, the PDF/X-4 print file: flattened at `dpi`, written at PDF 1.4
+/// with the identification, checked. Fails when the flattener fails or the result still has
+/// transparency or color outside DeviceCMYK, DeviceGray, Separation and DeviceN; other check
+/// findings become warnings.
+pub(crate) fn flatten_x1a(pdf: &[u8], dpi: f32, warnings: &mut Vec<String>) -> crate::Result<Vec<u8>> {
let dpi = if dpi.is_finite() { dpi.clamp(36.0, 2400.0) } else { 300.0 };
let opts = FlattenDocumentOptions {
read: ReadOptions { raster_dpi: dpi, ..ReadOptions::default() },
flatten: FlattenOptions { raster_dpi: dpi, ..FlattenOptions::default() },
producer: "DesignCraft".into(),
+ version: PdfVersion::Pdf14,
+ pdfx_version: Some(VERSION.into()),
..FlattenDocumentOptions::default()
};
- let (flat, report) = flatten_document(pdf, &opts).map_err(|e| PdfError::Write(format!("PDF/X-1a: the transparency flattener failed: {e}")))?;
+ let (bytes, report) = flatten_document(pdf, &opts).map_err(|e| PdfError::Write(format!("PDF/X-1a: the transparency flattener failed: {e}")))?;
let t = &report.totals;
if t.complex_regions > 0 || t.complex_groups > 0 {
let at = t.lowest_dpi.map(|d| format!(", some below {dpi:.0} ppi (lowest {d:.0} ppi)")).unwrap_or_default();
@@ -42,93 +48,24 @@ pub(crate) fn flatten_x1a(pdf: &[u8], dpi: f32, date: Option<i64>, warnings: &mu
if t.dropped_inks > 0 {
warnings.push(format!("PDF/X-1a: {} ink(s) past the flattener's limit were converted to process", t.dropped_inks));
}
- let bytes = make_pdfx1a(&flat, date).ok_or_else(|| PdfError::Write("PDF/X-1a: the flattened file couldn't be identified as PDF/X-1a".into()))?;
let (fatal, other) = checks(&bytes);
if !fatal.is_empty() {
return Err(PdfError::Write(format!("PDF/X-1a: after flattening, {}", fatal.join("; "))));
}
- warnings.extend(other.into_iter().map(|i| format!("PDF/X-1a: {i}")));
- Ok(bytes)
-}
-
-/// Identify a flattened PDF as PDF/X-1a:2003: the `%PDF-1.4` header, `GTS_PDFXVersion` and
-/// `GTS_PDFXConformance` in the document information and the XMP metadata (with
-/// `pdf:PDFVersion` 1.4, `xmp:MetadataDate` and `xmpMM:VersionID`), as an incremental update.
-/// `date` (Unix seconds, UTC) is the metadata date. `None` back when the file isn't the simple
-/// kind this understands (a classic cross-reference table, an information dictionary, an
-/// uncompressed XMP stream) or is newer than PDF 1.7.
-pub fn make_pdfx1a(pdf: &[u8], date: Option<i64>) -> Option<Vec<u8>> {
- // Same length, so no offset moves.
- if !pdf.starts_with(b"%PDF-1.") || !pdf.get(7).is_some_and(|v| (b'3'..=b'7').contains(v)) {
- return None;
- }
- let t_at = rfind(pdf, b"trailer")?;
- let trailer = String::from_utf8_lossy(pdf.get(t_at..)?).to_string();
- let size = int_after(&trailer, "/Size")?;
- let root = int_after(&trailer, "/Root")?;
- let prev = int_after(&trailer, "startxref")?;
- let info = int_after(&trailer, "/Info")?;
- let id = trailer.find("/ID").and_then(|i| trailer.get(i..)?.find(']').and_then(|j| trailer.get(i..i + j + 1)).map(str::to_string));
- let info_dict = String::from_utf8_lossy(pdf.get(object(pdf, info)?)?).to_string();
- let close = info_dict.rfind(">>")?;
- let mut info_body = info_dict.get(..close)?.trim().to_string();
- for key in ["/GTS_PDFXVersion", "/GTS_PDFXConformance"] {
- if info_body.contains(key) {
- return None;
+ let fallback =
+ || hayro_syntax::Pdf::new(bytes.clone()).ok().and_then(|f| intent_profile(&f)).is_some_and(|p| p == craft_cms::builtin::COATED_FOGRA39_ICC);
+ for issue in other {
+ if issue == V4_INTENT && fallback() {
+ warnings.push(
+ "PDF/X-1a: the output intent is the built-in Coated FOGRA39, an ICC v4 profile that PDF/X-1a preflight in a PDF 1.4 \
+ file may reject: choose a CMYK working space with an ICC v2 profile"
+ .into(),
+ );
+ } else {
+ warnings.push(format!("PDF/X-1a: {}", issue.trim_start_matches("warning: ")));
}
}
- info_body.push_str(&format!("/GTS_PDFXVersion({VERSION})/GTS_PDFXConformance({CONFORMANCE})>>"));
- let mut objects = vec![(info, info_body)];
- let cat = String::from_utf8_lossy(pdf.get(object(pdf, root)?)?).to_string();
- if let Some(meta) = int_after(&cat, "/Metadata") {
- let body = pdf.get(object(pdf, meta)?)?;
- let s0 = find(body, b"stream", 0)? + b"stream".len();
- let s0 = s0 + body.get(s0..)?.iter().take_while(|c| **c == b'\r' || **c == b'\n').count();
- let s1 = rfind(body, b"endstream")?;
- let xml = String::from_utf8_lossy(body.get(s0..s1)?).trim_end().to_string();
- let dict = String::from_utf8_lossy(body.get(..find(body, b"stream", 0)?)?).to_string();
- if dict.contains("/Filter") || !xml.contains("</rdf:RDF>") {
- return None;
- }
- let (y, mo, d, h, mi, se) = crate::export::civil(date.unwrap_or(0));
- let stamp = format!("{y:04}-{mo:02}-{d:02}T{h:02}:{mi:02}:{se:02}Z");
- let added = format!(
- "<rdf:Description rdf:about=\"\" xmlns:pdfxid=\"http://www.npes.org/pdfx/ns/id/\" xmlns:pdfx=\"http://ns.adobe.com/pdfx/1.3/\">\
- <pdfxid:GTS_PDFXVersion>{VERSION}</pdfxid:GTS_PDFXVersion><pdfx:GTS_PDFXVersion>{VERSION}</pdfx:GTS_PDFXVersion>\
- <pdfx:GTS_PDFXConformance>{CONFORMANCE}</pdfx:GTS_PDFXConformance></rdf:Description>\
- <rdf:Description rdf:about=\"\" xmlns:xmp=\"http://ns.adobe.com/xap/1.0/\" xmlns:xmpMM=\"http://ns.adobe.com/xap/1.0/mm/\">\
- <xmp:MetadataDate>{stamp}</xmp:MetadataDate><xmpMM:VersionID>1</xmpMM:VersionID></rdf:Description>"
- );
- let mut xml = xml;
- for v in ["1.5", "1.6", "1.7"] {
- xml = xml.replace(&format!("<pdf:PDFVersion>{v}</pdf:PDFVersion>"), "<pdf:PDFVersion>1.4</pdf:PDFVersion>");
- xml = xml.replace(&format!("pdf:PDFVersion=\"{v}\""), "pdf:PDFVersion=\"1.4\"");
- }
- let xml = xml.replacen("</rdf:RDF>", &format!("{added}</rdf:RDF>"), 1);
- let i = dict.find("/Length")?;
- let rest = dict.get(i + 7..)?.trim_start();
- let end = rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len());
- let dict = format!("{}/Length {}{}", dict.get(..i)?, xml.len(), rest.get(end..)?);
- objects.push((meta, format!("{}\nstream\n{xml}\nendstream", dict.trim())));
- }
- let mut out = pdf.to_vec();
- out.get_mut(..8)?.copy_from_slice(b"%PDF-1.4");
- if !out.ends_with(b"\n") {
- out.push(b'\n');
- }
- objects.sort_by_key(|(n, _)| *n);
- let mut xref = String::from("xref\n");
- for (n, body) in &objects {
- xref.push_str(&format!("{n} 1\n{:010} 00000 n\r\n", out.len()));
- out.extend_from_slice(format!("{n} 0 obj\n{body}\nendobj\n").as_bytes());
- }
- let xref_at = out.len();
- let id = id.unwrap_or_default();
- out.extend_from_slice(xref.as_bytes());
- out.extend_from_slice(
- format!("trailer\n<</Size {size}/Root {root} 0 R/Info {info} 0 R{id}/Prev {prev}>>\nstartxref\n{xref_at}\n%%EOF\n").as_bytes(),
- );
- Some(out)
+ Ok(bytes)
}
/// PDF/X-1a:2003 checks on an exported file (empty = passes them): PDF 1.4 or lower, the
@@ -136,7 +73,8 @@ pub fn make_pdfx1a(pdf: &[u8], date: Option<i64>) -> Option<Vec<u8>> {
/// encryption or interpolation; no transparency (soft masks, transparency groups, constant
/// opacity below 1, blend modes other than Normal); only DeviceCMYK, DeviceGray, Separation and
/// DeviceN (and Indexed and Pattern spaces over them), a spot's alternate space process; every
-/// font embedded and none Type 3.
+/// font embedded and none Type 3. Findings starting `warning: ` don't break conformance by
+/// themselves (an ICC v4 output intent profile in a PDF 1.4 file).
pub fn check_pdfx1a(pdf: &[u8]) -> Vec<String> {
let (mut issues, other) = checks(pdf);
issues.extend(other);
@@ -156,9 +94,6 @@ fn checks(pdf: &[u8]) -> (Vec<String>, Vec<String>) {
if !text.contains(&format!("/GTS_PDFXVersion({VERSION})")) {
issues.push(format!("the document information doesn't name {VERSION}"));
}
- if !text.contains(&format!("/GTS_PDFXConformance({CONFORMANCE})")) {
- issues.push(format!("the document information doesn't name the conformance {CONFORMANCE}"));
- }
if !text.contains("/Trapped/False") && !text.contains("/Trapped/True") && !text.contains("/Trapped /False") && !text.contains("/Trapped /True") {
issues.push("the document information needs /Trapped True or False".into());
}
@@ -188,6 +123,10 @@ fn content(pdf: &[u8]) -> (Vec<String>, Vec<String>) {
if !cmyk_output_intent(&file) {
fonts.push("the output intent has no CMYK destination profile".into());
}
+ let below_16 = pdf.starts_with(b"%PDF-1.") && pdf.get(7).is_some_and(|v| *v <= b'5');
+ if below_16 && intent_profile_major(&file) == Some(4) {
+ fonts.push(V4_INTENT.into());
+ }
let mut found: Vec<(String, Vec<usize>)> = Vec::new();
let mut font_found: Vec<(String, Vec<usize>)> = Vec::new();
for (i, page) in file.pages().iter().enumerate() {
@@ -218,6 +157,20 @@ fn content(pdf: &[u8]) -> (Vec<String>, Vec<String>) {
(found.into_iter().map(on_pages).collect(), fonts)
}
+/// The `GTS_PDFX` output intent's destination profile.
+fn intent_profile(file: &hayro_syntax::Pdf) -> Option<Vec<u8>> {
+ let xref = file.xref();
+ let catalog = xref.get::<Dict<'_>>(xref.root_id())?;
+ let intents = catalog.get::<Array<'_>>(b"OutputIntents")?;
+ let oi = intents.iter::<Dict<'_>>().find(|oi| oi.get::<Name<'_>>(b"S").is_some_and(|s| s.as_ref() == b"GTS_PDFX"))?;
+ Some(oi.get::<Stream<'_>>(b"DestOutputProfile")?.decoded().ok()?.into_owned())
+}
+
+/// The ICC major version of the output intent's profile (byte 8 of its header).
+fn intent_profile_major(file: &hayro_syntax::Pdf) -> Option<u8> {
+ intent_profile(file)?.get(8).copied()
+}
+
/// Why a color space isn't allowed in PDF/X-1a, or `None` when it is.
fn disallowed(cs: &Object<'_>, res: &Resources<'_>, depth: usize) -> Option<String> {
if depth > 4 {
@@ -251,7 +204,18 @@ fn disallowed(cs: &Object<'_>, res: &Resources<'_>, depth: usize) -> Option<Stri
b"Separation" | b"DeviceN" => {
let _names = items.next();
let alt = items.next()?;
- disallowed(&alt, res, depth + 1).map(|why| format!("a spot color whose alternate space is {why}"))
+ if let Some(why) = disallowed(&alt, res, depth + 1) {
+ return Some(format!("a spot color whose alternate space is {why}"));
+ }
+ let _tint = items.next();
+ // NChannel attributes are PDF 1.6, past the 1.4 that PDF/X-1a:2003 allows.
+ let attrs = items.next().and_then(|o| match o {
+ Object::Dict(d) => Some(d),
+ _ => None,
+ });
+ attrs
+ .filter(|a| a.get::<Name<'_>>(b"Subtype").is_some_and(|n| n.as_ref() == b"NChannel") || a.contains_key(b"Process"))
+ .map(|_| "a DeviceN space with NChannel attributes (PDF 1.6)".into())
}
other => Some(format!("the color space /{}", String::from_utf8_lossy(other))),
}
diff --git a/crates/pdf/src/x1a_tests.rs b/crates/pdf/src/x1a_tests.rs
index 0f6490388..330719af2 100644
--- a/crates/pdf/src/x1a_tests.rs
+++ b/crates/pdf/src/x1a_tests.rs
@@ -109,9 +109,18 @@ fn x1a_export_flattens_transparency_into_inks() {
let bytes = &r.bytes;
let text = String::from_utf8_lossy(bytes);
assert!(bytes.starts_with(b"%PDF-1.4"), "{:?}", text.get(..8));
- assert_eq!(check_pdfx1a(bytes), Vec::<String>::new());
+ // The only finding: the built-in Coated FOGRA39 output intent is an ICC v4 profile.
+ let v4 = |i: &String| i.contains("ICC v4");
+ let issues = check_pdfx1a(bytes);
+ assert!(issues.iter().all(v4), "{issues:?}");
+ let profile = output_intent(bytes).unwrap().profile;
+ assert_eq!(profile.get(8) == Some(&4), issues.iter().any(v4), "the v4 warning follows the profile");
+ assert_eq!(profile.get(8) == Some(&4), r.warnings.iter().any(|w| w.contains("ICC v4")), "{:?}", r.warnings);
+ if profile == craft_cms::builtin::COATED_FOGRA39_ICC {
+ assert!(r.warnings.iter().any(|w| w.contains("built-in Coated FOGRA39")), "{:?}", r.warnings);
+ }
assert!(text.contains("/GTS_PDFXVersion(PDF/X-1:2003)"));
- assert!(text.contains("/GTS_PDFXConformance(PDF/X-1a:2003)"));
+ assert!(!text.contains("/NChannel"), "no PDF 1.6 NChannel attributes at PDF 1.4");
assert!(text.contains("/Trapped/False"), "Trapped");
assert!(output_intent(bytes).is_some(), "output intent");
for f in families(bytes) {
@@ -137,19 +146,26 @@ fn x1a_export_flattens_transparency_into_inks() {
/// A minimal PDF 1.4 with a CMYK output intent, the X-1a identification and `content` on its
/// page; `entries` go into the page dictionary.
fn tiny_x1a(entries: &str, content: &str) -> Vec<u8> {
- let objects = [
- "<</Type/Catalog/Pages 2 0 R/OutputIntents[<</Type/OutputIntent/S/GTS_PDFX/DestOutputProfile 4 0 R>>]>>".to_string(),
- "<</Type/Pages/Kids[3 0 R]/Count 1>>".to_string(),
- format!("<</Type/Page/Parent 2 0 R/MediaBox[0 0 100 100]/TrimBox[0 0 100 100]{entries}/Contents 5 0 R>>"),
- "<</N 4/Length 0>>\nstream\n\nendstream".to_string(),
- format!("<</Length {}>>\nstream\n{content}\nendstream", content.len()),
- "<</GTS_PDFXVersion(PDF/X-1:2003)/GTS_PDFXConformance(PDF/X-1a:2003)/Trapped/False>>".to_string(),
+ tiny_x1a_with_profile(entries, content, b"")
+}
+
+/// [`tiny_x1a`] whose output intent profile holds `profile`.
+fn tiny_x1a_with_profile(entries: &str, content: &str, profile: &[u8]) -> Vec<u8> {
+ let objects: [Vec<u8>; 6] = [
+ b"<</Type/Catalog/Pages 2 0 R/OutputIntents[<</Type/OutputIntent/S/GTS_PDFX/DestOutputProfile 4 0 R>>]>>".to_vec(),
+ b"<</Type/Pages/Kids[3 0 R]/Count 1>>".to_vec(),
+ format!("<</Type/Page/Parent 2 0 R/MediaBox[0 0 100 100]/TrimBox[0 0 100 100]{entries}/Contents 5 0 R>>").into_bytes(),
+ [format!("<</N 4/Length {}>>\nstream\n", profile.len()).as_bytes(), profile, b"\nendstream"].concat(),
+ format!("<</Length {}>>\nstream\n{content}\nendstream", content.len()).into_bytes(),
+ b"<</GTS_PDFXVersion(PDF/X-1:2003)/Trapped/False>>".to_vec(),
];
let mut out = b"%PDF-1.4\n".to_vec();
let mut offsets = Vec::new();
for (i, o) in objects.iter().enumerate() {
offsets.push(out.len());
- out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
+ out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
+ out.extend_from_slice(o);
+ out.extend_from_slice(b"\nendobj\n");
}
let xref = out.len();
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f\r\n", objects.len() + 1).as_bytes());
@@ -181,6 +197,16 @@ fn x1a_checks_refuse_transparency_and_rgb() {
has("/Resources<<>>/Group<</S/Transparency/CS/DeviceCMYK>>", "0 0 0 1 k", "transparency group");
has("/Resources<</ColorSpace<</S[/Separation/Gold/DeviceRGB 7 0 R]>>>>", "/S cs 1 scn 0 0 10 10 re f", "alternate space");
has("/Resources<<>>", "q BI /W 1 /H 1 /CS /RGB /BPC 8 /F /AHx ID ff0000> EI Q", "DeviceRGB");
+ has(
+ "/Resources<</ColorSpace<</N[/DeviceN[/Cyan/Gold]/DeviceCMYK 7 0 R<</Subtype/NChannel/Colorants<<>>>>]>>>>",
+ "/N cs 1 1 scn 0 0 10 10 re f",
+ "NChannel",
+ );
+ // An ICC v4 output intent profile in a PDF 1.4 file is a warning; v2 passes.
+ let header = |major: u8| [&[0u8; 8][..], &[major, 0x20, 0, 0], b"prtrCMYK"].concat();
+ let v4 = check_pdfx1a(&tiny_x1a_with_profile("/Resources<<>>", "0 0 0 1 k", &header(4)));
+ assert!(v4.iter().any(|i| i.starts_with("warning: ") && i.contains("ICC v4")), "{v4:?}");
+ assert_eq!(check_pdfx1a(&tiny_x1a_with_profile("/Resources<<>>", "0 0 0 1 k", &header(2))), Vec::<String>::new());
// A PDF/X-4 file isn't X-1a.
let x4 = export_pdf_with_report(
&Document::new(&NewDocument::default()),
diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs
index e469cf937..34868f407 100644
--- a/xtask/src/pdf_deps.rs
+++ b/xtask/src/pdf_deps.rs
@@ -5,7 +5,7 @@ use std::process::Command;
use serde_json::Value;
const REPO: &str = "https://github.com/aiongg/craft-libs";
-const REV: &str = "d11403fde04311cd50cc9913f3bc43ff6a419945";
+const REV: &str = "d30598dcb4b389561c485b97d4a97a0c86bc36e4";
const PACKAGES: &[(&str, &str)] = &[("craft-pdf", "0.1.0"), ("krilla", "0.8.2")];
pub fn run(root: &Path) -> Result<(), String> {