Skip to content

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

PDF/A: no sRGB output intent for CMYK documents, and pdfa_verify checks the intent's colour space (#667) (#732)

DWAA1660e4cd9e2557e9
diff --git a/crates/preflight/src/lib.rs b/crates/preflight/src/lib.rs
index eb6bedd52..7dc6ee24f 100644
--- a/crates/preflight/src/lib.rs
+++ b/crates/preflight/src/lib.rs
@@ -138,24 +138,73 @@ fn dict_of(o: &Object) -> Option<&Dict> {
}
fn has_pdfa_intent(doc: &Document) -> bool {
+ pdfa_intent_profile(doc).is_some()
+}
+
+/// The PDF/A output intent's destination profile: `Some(n)` with the profile's number of colour
+/// components (`/N`, else the ICC header's data colour space; `None` when neither says), or
+/// `None` when the document has no PDF/A output intent.
+fn pdfa_intent_profile(doc: &Document) -> Option<Option<i64>> {
let cat = catalog(doc);
- cat.get(b"OutputIntents")
- .map(|o| doc.resolve(o))
- .and_then(|o| o.as_array().cloned())
- .unwrap_or_default()
- .iter()
- .any(|oi| doc.resolve(oi).as_dict().is_some_and(|d| d.name(b"S") == Some(b"GTS_PDFA1") && d.get(b"DestOutputProfile").is_some()))
+ let list = cat.get(b"OutputIntents").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()).unwrap_or_default();
+ list.iter().find_map(|oi| {
+ let d = doc.resolve(oi).as_dict().cloned()?;
+ if d.name(b"S") != Some(b"GTS_PDFA1") {
+ return None;
+ }
+ let profile = doc.resolve(d.get(b"DestOutputProfile")?);
+ let Object::Stream(s) = &*profile else { return Some(None) };
+ Some(s.dict.int(b"N").or_else(|| {
+ // ICC.1 header: the data colour space is bytes 16–19.
+ match s.decoded().ok()?.get(16..20)? {
+ b"GRAY" => Some(1),
+ b"RGB " => Some(3),
+ b"CMYK" => Some(4),
+ _ => None,
+ }
+ }))
+ })
+}
+
+/// Which device colour spaces the document uses.
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+struct DeviceColour {
+ gray: bool,
+ rgb: bool,
+ cmyk: bool,
+ /// Resources that define `DefaultRGB` / `DefaultCMYK`: device colour there is drawn in that
+ /// space, which PDF/A accepts whatever the output intent (ISO 19005-2 6.2.4.3).
+ default_rgb: bool,
+ default_cmyk: bool,
+}
+
+impl DeviceColour {
+ fn any(self) -> bool {
+ self.gray || self.rgb || self.cmyk
+ }
}
/// Whether any content or object uses a device colour space.
-fn uses_device_colour(doc: &Document, objs: &[(ObjRef, std::sync::Arc<Object>)]) -> (bool, bool) {
- let (mut rgb_or_gray, mut cmyk) = (false, false);
+fn uses_device_colour(doc: &Document, objs: &[(ObjRef, std::sync::Arc<Object>)]) -> DeviceColour {
+ let mut used = DeviceColour::default();
for (_, o) in objs {
let Some(d) = dict_of(o) else { continue };
+ // A resource dictionary's /ColorSpace, whether it is this object or the page's inline
+ // /Resources.
+ let resources = d.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned());
+ for holder in [Some(d), resources.as_ref()].into_iter().flatten() {
+ if let Some(spaces) = holder.get(b"ColorSpace").map(|c| doc.resolve(c))
+ && let Some(spaces) = spaces.as_dict()
+ {
+ used.default_rgb |= spaces.get(b"DefaultRGB").is_some();
+ used.default_cmyk |= spaces.get(b"DefaultCMYK").is_some();
+ }
+ }
if let Some(cs) = d.get(b"ColorSpace").map(|c| doc.resolve(c)) {
match &*cs {
- Object::Name(n) if n == b"DeviceRGB" || n == b"DeviceGray" => rgb_or_gray = true,
- Object::Name(n) if n == b"DeviceCMYK" => cmyk = true,
+ Object::Name(n) if n == b"DeviceGray" => used.gray = true,
+ Object::Name(n) if n == b"DeviceRGB" => used.rgb = true,
+ Object::Name(n) if n == b"DeviceCMYK" => used.cmyk = true,
_ => {}
}
}
@@ -167,14 +216,15 @@ fn uses_device_colour(doc: &Document, objs: &[(ObjRef, std::sync::Arc<Object>)])
// Content streams: rg/RG/g/G/k/K operators.
for line in data.split(|b| *b == b'\n' || *b == b' ') {
match line {
- b"rg" | b"RG" | b"g" | b"G" => rgb_or_gray = true,
- b"k" | b"K" => cmyk = true,
+ b"g" | b"G" => used.gray = true,
+ b"rg" | b"RG" => used.rgb = true,
+ b"k" | b"K" => used.cmyk = true,
_ => {}
}
}
}
}
- (rgb_or_gray, cmyk)
+ used
}
/// Check `doc` against `level`.
@@ -204,12 +254,24 @@ pub fn verify(doc: &Document, level: Level) -> Vec<Issue> {
}
// 6.2.2: output intent when device colour is used.
let objs = objects(doc);
- let (rgb, cmyk) = uses_device_colour(doc, &objs);
- if (rgb || cmyk) && !has_pdfa_intent(doc) {
- issue("6.2.3", "Device colour is used, but there is no PDF/A output intent".into(), None, !cmyk);
- if cmyk {
- issue("6.2.4.3", "DeviceCMYK is used: it needs a CMYK output intent (not added automatically)".into(), None, false);
+ let used = uses_device_colour(doc, &objs);
+ match pdfa_intent_profile(doc) {
+ None if used.any() => {
+ issue("6.2.3", "Device colour is used, but there is no PDF/A output intent".into(), None, !used.cmyk);
+ if used.cmyk {
+ issue("6.2.4.3", "DeviceCMYK is used: it needs a CMYK output intent (not added automatically)".into(), None, false);
+ }
+ }
+ // 6.2.4.3: DeviceRGB needs an RGB output intent and DeviceCMYK a CMYK one (#667).
+ Some(n) => {
+ if used.cmyk && !used.default_cmyk && n != Some(4) {
+ issue("6.2.4.3", "DeviceCMYK is used, but the PDF/A output intent isn't a CMYK profile".into(), None, false);
+ }
+ if used.rgb && !used.default_rgb && n != Some(3) {
+ issue("6.2.4.3", "DeviceRGB is used, but the PDF/A output intent isn't an RGB profile".into(), None, false);
+ }
}
+ None => {}
}
// 6.1.3 / 6.6.1: catalog actions.
if cat.get(b"AA").is_some() {
@@ -435,7 +497,9 @@ pub fn convert(doc: &mut Document, level: Level) -> Result<Report, pdfcraft_cos:
cat.set(b"AcroForm".to_vec(), Object::Dict(af));
fixed.push("Cleared NeedAppearances".into());
}
- if !has_pdfa_intent(doc) {
+ // An sRGB output intent describes RGB and gray content only: a document with CMYK content
+ // needs a CMYK output condition, which only the user can choose (#667).
+ if !has_pdfa_intent(doc) && !uses_device_colour(doc, &objects(doc)).cmyk {
let mut icc = Dict::new();
icc.set(b"N".to_vec(), Object::Int(3));
let profile = doc.add(Object::Stream(Stream::flate(icc, &icc::srgb())));
diff --git a/crates/preflight/src/tests.rs b/crates/preflight/src/tests.rs
index 6613e6fc5..35ed85655 100644
--- a/crates/preflight/src/tests.rs
+++ b/crates/preflight/src/tests.rs
@@ -100,3 +100,84 @@ fn embedded_files_differ_between_parts() {
let r = convert(&mut d3, Level::A3b).unwrap();
assert!(r.remaining.is_empty(), "{:#?}", r.remaining);
}
+
+/// A page that paints a DeviceCMYK image (as `doc_create` makes from a CMYK JPEG), with
+/// `intent` as the catalog's extra entries and `extra` as more objects (from object 6 on).
+fn cmyk_page(intent: &str, content: &str, extra: &[&str]) -> Document {
+ let catalog = format!("<< /Type /Catalog /Pages 2 0 R {intent} >>");
+ let stream = format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len());
+ let mut objs = vec![
+ catalog.as_str(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 200] >>",
+ "<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /XObject << /Im0 5 0 R >> >> >>",
+ stream.as_str(),
+ "<< /Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceCMYK /BitsPerComponent 8 /Length 4 >>\nstream\n\u{0}\u{0}\u{0}\u{0}\nendstream",
+ ];
+ objs.extend_from_slice(extra);
+ build(&objs, "")
+}
+
+fn messages(issues: &[Issue]) -> Vec<&str> {
+ issues.iter().map(|i| i.message.as_str()).collect()
+}
+
+/// Issue #667: converting a CMYK-only document doesn't add an sRGB output intent (it would
+/// describe a colour space the document doesn't use); the CMYK output intent it needs is
+/// reported as not fixable instead.
+#[test]
+fn convert_does_not_give_cmyk_documents_an_srgb_output_intent() {
+ let mut doc = cmyk_page("", "q 200 0 0 200 0 0 cm /Im0 Do Q", &[]);
+ let r = convert(&mut doc, Level::A2b).unwrap();
+ assert!(!r.fixed.iter().any(|f| f.contains("output intent")), "{:?}", r.fixed);
+ assert!(declared(&doc).output_intents.is_empty());
+ let left = messages(&r.remaining);
+ assert!(left.contains(&"Device colour is used, but there is no PDF/A output intent"), "{left:#?}");
+ assert!(left.contains(&"DeviceCMYK is used: it needs a CMYK output intent (not added automatically)"), "{left:#?}");
+ assert!(r.remaining.iter().all(|i| !i.fixable));
+}
+
+/// Issue #667: verify checks the output intent's colour space against the device colour the
+/// pages use, not only that an output intent exists.
+#[test]
+fn verify_reports_an_output_intent_that_does_not_match_device_colour() {
+ let intent = "/OutputIntents [<< /Type /OutputIntent /S /GTS_PDFA1 /OutputConditionIdentifier (X) /DestOutputProfile 6 0 R >>]";
+ let profile = |n: u8| format!("<< /N {n} /Length 0 >>\nstream\n\nendstream");
+ let (rgb, cmyk) = (profile(3), profile(4));
+ let cmyk_msg = "DeviceCMYK is used, but the PDF/A output intent isn't a CMYK profile";
+ let rgb_msg = "DeviceRGB is used, but the PDF/A output intent isn't an RGB profile";
+
+ // CMYK content under an sRGB output intent (what convert used to write).
+ let issues = verify(&cmyk_page(intent, "/Im0 Do", &[&rgb]), Level::A2b);
+ assert!(messages(&issues).contains(&cmyk_msg), "{issues:#?}");
+ assert!(issues.iter().find(|i| i.message == cmyk_msg).is_some_and(|i| i.clause == "6.2.4.3" && !i.fixable));
+
+ // CMYK content under a CMYK output intent is fine; RGB and gray content beside it is not
+ // and is, respectively.
+ assert!(!messages(&verify(&cmyk_page(intent, "/Im0 Do 0 g", &[&cmyk]), Level::A2b)).iter().any(|m| m.contains("output intent")));
+ let issues = verify(&cmyk_page(intent, "/Im0 Do 1 0 0 rg", &[&cmyk]), Level::A2b);
+ assert!(messages(&issues).contains(&rgb_msg) && !messages(&issues).contains(&cmyk_msg), "{issues:#?}");
+
+ // DefaultCMYK in the page's resources draws DeviceCMYK in that space, which PDF/A accepts
+ // under any output intent.
+ let catalog = format!("<< /Type /Catalog /Pages 2 0 R {intent} >>");
+ let doc = build(
+ &[
+ catalog.as_str(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 200] >>",
+ "<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /ColorSpace << /DefaultCMYK [/ICCBased 7 0 R] >> /XObject << /Im0 5 0 R >> >> >>",
+ "<< /Length 7 >>\nstream\n/Im0 Do\nendstream",
+ "<< /Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceCMYK /BitsPerComponent 8 /Length 4 >>\nstream\n\u{0}\u{0}\u{0}\u{0}\nendstream",
+ rgb.as_str(),
+ cmyk.as_str(),
+ ],
+ "",
+ );
+ assert!(!messages(&verify(&doc, Level::A2b)).contains(&cmyk_msg), "DefaultCMYK covers DeviceCMYK");
+
+ // Without /N, the ICC header's colour space decides.
+ let mut header = vec![b' '; 128];
+ header[16..20].copy_from_slice(b"CMYK");
+ let header = String::from_utf8(header).unwrap();
+ let headed = format!("<< /Length 128 >>\nstream\n{header}\nendstream");
+ assert!(!messages(&verify(&cmyk_page(intent, "/Im0 Do", &[&headed]), Level::A2b)).contains(&cmyk_msg));
+}
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index 9f1ade7de..347e77e37 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -7660,8 +7660,8 @@ milestone = "M11"
status = "partial"
commands = ["standards.pdfa"]
tools = ["pdfa_verify"]
-evidence = ["crates/preflight/src/tests.rs::verify_reports_what_breaks_pdfa", "crates/preflight/src/tests.rs::convert_fixes_all_but_fonts", "crates/automation/tests/automation.rs::pdfa_through_tools", "crates/ui-egui/tests/compare.rs::pdfa_dialog_verifies_and_converts"]
-notes = "PDF/A-2b/3b structural rules: identification, encryption, output intent, fonts embedded, annotations, actions, images, embedded files. Not yet: content-stream operator checks, transparency details, PDF/A-1 and -4, a veraPDF comparison."
+evidence = ["crates/preflight/src/tests.rs::verify_reports_what_breaks_pdfa", "crates/preflight/src/tests.rs::convert_fixes_all_but_fonts", "crates/preflight/src/tests.rs::verify_reports_an_output_intent_that_does_not_match_device_colour", "crates/automation/tests/automation.rs::pdfa_through_tools", "crates/ui-egui/tests/compare.rs::pdfa_dialog_verifies_and_converts"]
+notes = "PDF/A-2b/3b structural rules: identification, encryption, output intent (present, and RGB/CMYK to match DeviceRGB/DeviceCMYK use), fonts embedded, annotations, actions, images, embedded files. Not yet: content-stream operator checks, transparency details, PDF/A-1 and -4, a veraPDF comparison."
[[feature]]
id = "optimize.pdfa-convert"
@@ -7672,8 +7672,8 @@ milestone = "M11"
status = "partial"
commands = ["standards.pdfa"]
tools = ["pdfa_convert"]
-evidence = ["crates/preflight/src/tests.rs::convert_fixes_all_but_fonts", "crates/automation/tests/automation.rs::pdfa_through_tools", "crates/ui-egui/tests/compare.rs::pdfa_dialog_verifies_and_converts"]
-notes = "Fixes XMP, output intent (generated sRGB ICC profile), forbidden actions, annotation flags, interpolation, encryption, AFRelationship. Not yet: embedding fonts, converting device CMYK, flattening transparency for PDF/A-1."
+evidence = ["crates/preflight/src/tests.rs::convert_fixes_all_but_fonts", "crates/preflight/src/tests.rs::convert_does_not_give_cmyk_documents_an_srgb_output_intent", "crates/automation/tests/automation.rs::pdfa_through_tools", "crates/ui-egui/tests/compare.rs::pdfa_dialog_verifies_and_converts"]
+notes = "Fixes XMP, output intent (generated sRGB ICC profile, only for documents without DeviceCMYK; CMYK documents need a user-chosen CMYK output intent, not yet offered), forbidden actions, annotation flags, interpolation, encryption, AFRelationship. Not yet: embedding fonts, converting device CMYK, flattening transparency for PDF/A-1."
[[feature]]
id = "optimize.pdfa-accessible-levels"