Skip to content

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

Print color: PDF/X-1a conformance level, intent profile and review fixes

aiongg4c29b6070003
diff --git a/crates/engine/src/cmd/export.rs b/crates/engine/src/cmd/export.rs
index c9e847ccd..89075ab61 100644
--- a/crates/engine/src/cmd/export.rs
+++ b/crates/engine/src/cmd/export.rs
@@ -555,9 +555,9 @@ fn shadow_only(it: &designcraft_doc::Item) -> bool {
/// the shadow in its own swatch's inks through a mask (which craft-prepress flattens per ink)
/// instead of an RGB image of the object. Objects whose only soft effect is the drop shadow.
///
-/// The coverage is the object drawn alone with its shadow minus the object without it (alpha),
-/// at full opacity and Normal blending: what of the shadow shows past the object, its opacity
-/// included. The object's own opacity and blend mode stay on the object's group in the PDF.
+/// The coverage comes from the object drawn alone, at full opacity and Normal blending, with its
+/// shadow and without it ([`shadow_coverage`]): the shadow's own alpha, its opacity included. The
+/// object's own opacity and blend mode stay on the object's group in the PDF.
fn shadow_masks(
d: &designcraft_doc::Document,
cache: &designcraft_compose::Cache,
@@ -610,12 +610,24 @@ fn shadow_masks(
if with.len() != n || without.len() != n {
continue;
}
- let coverage: Vec<u8> = with.iter().zip(&without).map(|(a, b)| a.saturating_sub(*b)).collect();
+ let coverage: Vec<u8> = with.iter().zip(&without).map(|(a, b)| shadow_coverage(*a, *b)).collect();
out.insert(id, designcraft_pdf::ShadowMask { rect: reach, width: w, height: h, coverage: std::sync::Arc::new(coverage) });
}
out
}
+/// The shadow's alpha `s` at a pixel where the object alone has alpha `without` and the object
+/// over its shadow `with`: `with = a + s(1 − a)` for the object's alpha `a`, so the PDF, which
+/// draws the object over the shadow, gets the same pixel back. 0 where the object is opaque.
+fn shadow_coverage(with: u8, without: u8) -> u8 {
+ let rest = 255 - u32::from(without);
+ if rest == 0 {
+ return 0;
+ }
+ let shown = u32::from(with.saturating_sub(without));
+ u8::try_from(((shown * 255 + rest / 2) / rest).min(255)).unwrap_or(u8::MAX)
+}
+
/// A copy of `d` where the spread-level objects `pred` picks are images of their appearance at
/// `ppi` (transparent around them). With `keep_wrap`, each object also stays behind as a
/// nonprinting [`wrap_stand_in`], so text wraps around it as before.
@@ -1124,6 +1136,22 @@ mod text_tests {
out
}
+ /// The shadow coverage gives the rendered pixel back when the PDF draws the object over the
+ /// shadow, also under a partly transparent object (an anti-aliased edge, a soft-alpha image).
+ #[test]
+ fn shadow_coverage_composites_back() {
+ for a in (0..=255u32).step_by(15) {
+ for s in (0..=255u32).step_by(15) {
+ let over = |c: u32| a + (c * (255 - a) + 127) / 255;
+ let with = over(s) as u8;
+ let c = u32::from(super::shadow_coverage(with, a as u8));
+ assert!(over(c).abs_diff(u32::from(with)) <= 1, "object {a}, shadow {s}: coverage {c}");
+ }
+ }
+ assert_eq!(super::shadow_coverage(255, 255), 0);
+ assert_eq!(super::shadow_coverage(10, 20), 0);
+ }
+
/// PDF/X-1a through craft-prepress: a soft drop shadow over a spot, a 50% object and a
/// knockout group leave no transparency and no RGB; the shadow is flattened in the page's
/// inks (Black over the spot), not exported as an RGB image of the object; text stays text and
@@ -1155,10 +1183,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();
- // 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_eq!(designcraft_pdf::check_pdfx1a(&pdf), Vec::<String>::new());
assert!(pdf.starts_with(b"%PDF-1.4") && text.contains("/GTS_PDFXVersion(PDF/X-1:2003)") && text.contains("/S/GTS_PDFX"));
+ assert!(text.contains("/GTS_PDFXConformance(PDF/X-1a:2003)"), "the conformance level");
let warnings = r["warnings"].to_string();
assert!(!warnings.contains("soft effects"), "the shadow isn't an RGB image of the object: {warnings}");
assert!(warnings.contains("at 72 ppi"), "{warnings}");
diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs
index bdfe98e75..a9f5eb7c1 100644
--- a/crates/pdf/src/export.rs
+++ b/crates/pdf/src/export.rs
@@ -276,12 +276,30 @@ 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, &mut warnings)?;
+ bytes = crate::pdfx1a::flatten_x1a(&bytes, opts.flatten_dpi, &page_graphics(doc, &sheets), &mut warnings)?;
}
warnings.dedup();
Ok(ExportReport { bytes, pages: sheets.len(), warnings })
}
+/// Each sheet's name and the names of the graphics placed on it, for PDF/X-1a's errors.
+fn page_graphics(doc: &Document, sheets: &[Sheet]) -> Vec<crate::pdfx1a::PageGraphics> {
+ sheets
+ .iter()
+ .map(|sh| {
+ let mut graphics: Vec<String> = Vec::new();
+ for (xf, it) in exported_items(doc, sh.spread) {
+ let Some(asset) = it.graphic().and_then(|g| doc.assets.get(&g.asset)) else { continue };
+ let shown = xf.transform_rect_bbox(it.bounds()).intersect(sh.media);
+ if shown.width() > 0.0 && shown.height() > 0.0 && !graphics.contains(&asset.name) {
+ graphics.push(asset.name.clone());
+ }
+ }
+ crate::pdfx1a::PageGraphics { label: sh.label.clone(), graphics }
+ })
+ .collect()
+}
+
/// One PDF from several (a book's documents), every page carried over as vectors; each part
/// comes with its pages' sizes (points).
pub fn merge_pdfs(parts: &[(Vec<u8>, Vec<(f32, f32)>)], title: Option<&str>) -> Result<Vec<u8>> {
diff --git a/crates/pdf/src/pdfx1a.rs b/crates/pdf/src/pdfx1a.rs
index d17bba741..88759b071 100644
--- a/crates/pdf/src/pdfx1a.rs
+++ b/crates/pdf/src/pdfx1a.rs
@@ -1,32 +1,46 @@
//! 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),
-//! written by krilla as PDF 1.4 with the PDF/X-1a identification, then checked.
+//! written by krilla as PDF 1.4, given the PDF/X-1a identification and output intent, then
+//! checked.
-use std::collections::HashSet;
+use std::collections::{HashMap, HashSet};
use craft_pdf::write::backend::configure::PdfVersion;
use craft_prepress::flatten::pdf::ReadOptions;
-use craft_prepress::flatten::{FlattenDocumentOptions, FlattenOptions, flatten_document};
+use craft_prepress::flatten::{FlattenDocumentOptions, FlattenOptions, FlattenTotals, flatten_document};
use hayro_syntax::content::UntypedIter;
use hayro_syntax::object::{Array, Dict, Name, Object, ObjectIdentifier, Stream};
use hayro_syntax::page::Resources;
use crate::PdfError;
-use crate::pdfx::{MAX_DEPTH, cmyk_output_intent};
+use crate::pdfx::MAX_DEPTH;
+use crate::transitions::{find, int_after, rfind};
-/// `GTS_PDFXVersion` of PDF/X-1a:2003 (ISO 15930-4).
+/// `GTS_PDFXVersion` of PDF/X-1a:2003 (ISO 15930-4): the base level, PDF/X-1:2003.
const VERSION: &str = "PDF/X-1:2003";
-/// [`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";
+/// `GTS_PDFXConformance` of PDF/X-1a:2003 (ISO 15930-4): with [`VERSION`], it names the
+/// conformance level.
+const CONFORMANCE: &str = "PDF/X-1a:2003";
-/// 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>> {
+/// `/RegistryName` of the ICC's registry of characterized printing conditions. An output intent
+/// naming one of them needs no `/DestOutputProfile` in PDF/X.
+const ICC_REGISTRY: &str = "http://www.color.org";
+
+/// The graphics placed on one output page, to name in errors: the page's name and the graphics'
+/// names.
+#[derive(Clone, Debug, Default)]
+pub(crate) struct PageGraphics {
+ pub label: String,
+ pub graphics: Vec<String>,
+}
+
+/// The PDF/X-1a file for `pdf`, the PDF/X-4 print file: flattened at `dpi`, written at PDF 1.4,
+/// identified, checked. `pages` names each output page and its graphics for errors. Fails when
+/// the flattener fails or leaves an image out, when the output intent's profile can't go into a
+/// PDF 1.4 file, or when 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, pages: &[PageGraphics], 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() },
@@ -37,44 +51,61 @@ pub(crate) fn flatten_x1a(pdf: &[u8], dpi: f32, warnings: &mut Vec<String>) -> c
..FlattenDocumentOptions::default()
};
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();
- warnings.push(format!("PDF/X-1a: transparency flattened: {} region(s) rasterized at {dpi:.0} ppi{at}", t.complex_regions + t.complex_groups));
- }
- if t.unreadable_images > 0 {
- warnings.push(format!("PDF/X-1a: {} image(s) couldn't be read by the flattener and were left out", t.unreadable_images));
- }
- 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 unread: Vec<String> = report
+ .pages
+ .iter()
+ .filter(|(_, r)| r.read.unreadable_images > 0)
+ .map(|(page, r)| {
+ let n = r.read.unreadable_images;
+ let images = if n == 1 { "1 image".to_string() } else { format!("{n} images") };
+ let fallback = PageGraphics { label: page.saturating_add(1).to_string(), graphics: Vec::new() };
+ let at = pages.get(*page).unwrap_or(&fallback);
+ let names: Vec<String> = at.graphics.iter().take(5).map(|g| format!("`{g}`")).collect();
+ let more = if at.graphics.len() > 5 { ", …" } else { "" };
+ let placed = if names.is_empty() { String::new() } else { format!(" (graphics on it: {}{more})", names.join(", ")) };
+ format!("{images} on page {}{placed}", at.label)
+ })
+ .collect();
+ if !unread.is_empty() {
+ return Err(PdfError::Write(format!(
+ "PDF/X-1a: the transparency flattener couldn't read {}, and a PDF/X file can't leave images out: replace the graphic, or export without PDF/X-1a",
+ unread.join("; ")
+ )));
}
+ warnings.extend(flatten_warnings(&report.totals, dpi));
+ let bytes = finish(&bytes).map_err(|e| PdfError::Write(format!("PDF/X-1a: {e}")))?;
let (fatal, other) = checks(&bytes);
if !fatal.is_empty() {
return Err(PdfError::Write(format!("PDF/X-1a: after flattening, {}", fatal.join("; "))));
}
- 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: ")));
- }
- }
+ warnings.extend(other.into_iter().map(|issue| format!("PDF/X-1a: {issue}")));
Ok(bytes)
}
+/// What the flattener's `t` (at `dpi`) tells the user: rasterized transparency, and spot inks past
+/// the ink set's capacity, whose tints the flattener drops.
+pub(crate) fn flatten_warnings(t: &FlattenTotals, dpi: f32) -> Vec<String> {
+ let mut out = Vec::new();
+ 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();
+ out.push(format!("PDF/X-1a: transparency flattened: {} region(s) rasterized at {dpi:.0} ppi{at}", t.complex_regions + t.complex_groups));
+ }
+ if t.dropped_inks > 0 {
+ out.push(format!(
+ "PDF/X-1a: the document has more spot inks than the flattener can separate: {} tint(s) in the inks past its limit were dropped and won't print",
+ t.dropped_inks
+ ));
+ }
+ out
+}
+
/// PDF/X-1a:2003 checks on an exported file (empty = passes them): PDF 1.4 or lower, the
-/// identification, a CMYK `GTS_PDFX` output intent, `/Trapped` True or False, trim boxes, no
-/// 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. Findings starting `warning: ` don't break conformance by
-/// themselves (an ICC v4 output intent profile in a PDF 1.4 file).
+/// identification (`GTS_PDFXVersion` and `GTS_PDFXConformance`), a CMYK `GTS_PDFX` output intent
+/// whose profile, when it has one, is ICC v2 (and without one, names a registered printing
+/// condition), `/Trapped` True or False, trim boxes, no 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.
pub fn check_pdfx1a(pdf: &[u8]) -> Vec<String> {
let (mut issues, other) = checks(pdf);
issues.extend(other);
@@ -94,6 +125,9 @@ 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 level {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());
}
@@ -113,20 +147,13 @@ fn checks(pdf: &[u8]) -> (Vec<String>, Vec<String>) {
(content, issues)
}
-/// Transparency and color spaces, then fonts, walked through every page's content and what it
-/// uses.
+/// Transparency and color spaces, then the output intent and fonts, walked through every page's
+/// content and what it uses.
fn content(pdf: &[u8]) -> (Vec<String>, Vec<String>) {
let Ok(file) = hayro_syntax::Pdf::new(pdf.to_vec()) else {
return (vec!["the file couldn't be read to check its transparency and color spaces".into()], Vec::new());
};
- let mut fonts = Vec::new();
- 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 fonts = intent_issues(&file);
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() {
@@ -157,18 +184,286 @@ 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>> {
+/// A `GTS_PDFX` output intent, as PDF/X-1a judges it.
+struct Intent {
+ /// Its object number, when it is an indirect object.
+ obj: Option<usize>,
+ /// `/OutputCondition`, else `/OutputConditionIdentifier`, for messages.
+ name: String,
+ /// An `/OutputConditionIdentifier` other than `Custom` in the ICC registry.
+ registered: bool,
+ /// Whether it has a `/DestOutputProfile`, and the profile's object number.
+ has_profile: bool,
+ profile_obj: Option<usize>,
+ /// The profile's `/N` and decoded bytes.
+ channels: Option<i32>,
+ profile: Option<Vec<u8>>,
+}
+
+impl Intent {
+ /// The profile's ICC major version (byte 8 of its header).
+ fn major(&self) -> Option<u8> {
+ self.profile.as_deref()?.get(8).copied()
+ }
+
+ /// "ICC v4", or what keeps the version from being read.
+ fn version(&self) -> String {
+ self.major().map_or_else(|| "unreadable".to_string(), |v| format!("ICC v{v}"))
+ }
+}
+
+/// The catalog's `GTS_PDFX` output intents.
+fn pdfx_intents(file: &hayro_syntax::Pdf) -> Vec<Intent> {
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())
+ let Some(catalog) = xref.get::<Dict<'_>>(xref.root_id()) else { return Vec::new() };
+ let Some(intents) = catalog.get::<Array<'_>>(b"OutputIntents") else { return Vec::new() };
+ let number = |n: i32| usize::try_from(n).ok();
+ intents
+ .iter::<Dict<'_>>()
+ .filter(|oi| oi.get::<Name<'_>>(b"S").is_some_and(|s| s.as_ref() == b"GTS_PDFX"))
+ .map(|oi| {
+ let text = |key: &[u8]| {
+ oi.get::<hayro_syntax::object::String<'_>>(key)
+ .map(|s| String::from_utf8_lossy(s.as_bytes()).trim().to_string())
+ .filter(|s| !s.is_empty())
+ };
+ let identifier = text(b"OutputConditionIdentifier");
+ let registry = text(b"RegistryName");
+ let profile = oi.get::<Stream<'_>>(b"DestOutputProfile");
+ Intent {
+ obj: oi.obj_id().and_then(|id| number(id.obj_number)),
+ name: text(b"OutputCondition").or_else(|| identifier.clone()).unwrap_or_else(|| "?".into()),
+ registered: registry.is_some_and(|r| r.trim_end_matches('/') == ICC_REGISTRY) && identifier.as_deref().is_some_and(|i| i != "Custom"),
+ has_profile: oi.contains_key(b"DestOutputProfile"),
+ profile_obj: oi.get_ref(b"DestOutputProfile").and_then(|r| number(r.obj_number)),
+ channels: profile.as_ref().and_then(|p| p.dict().get::<i32>(b"N")),
+ profile: profile.and_then(|p| p.decoded().ok()).map(|b| b.into_owned()),
+ }
+ })
+ .collect()
}
-/// 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()
+/// What PDF/X-1a finds wrong with the file's output intent: a CMYK profile, ICC v2 (PDF 1.4
+/// allows no later version), or none for a registered printing condition.
+fn intent_issues(file: &hayro_syntax::Pdf) -> Vec<String> {
+ let Some(oi) = pdfx_intents(file).into_iter().next() else { return Vec::new() };
+ let mut issues = Vec::new();
+ if oi.has_profile {
+ if oi.channels != Some(4) {
+ issues.push("the output intent has no CMYK destination profile".into());
+ }
+ if oi.major() != Some(2) {
+ issues.push(format!("the output intent's profile is {}, and PDF/X-1a (PDF 1.4) allows only ICC v2 profiles", oi.version()));
+ }
+ } else if !oi.registered {
+ issues
+ .push(format!("the output intent has no destination profile and doesn't name a printing condition in the ICC registry ({ICC_REGISTRY})"));
+ }
+ issues
+}
+
+/// krilla's PDF 1.4 file with what PDF/X-1a needs and krilla doesn't write, rewritten as one
+/// revision: `GTS_PDFXConformance` in the document information and the XMP, and the output intent
+/// of a registered printing condition without `/DestOutputProfile` (its profile is left out of
+/// the file). An unregistered condition keeps its profile, which must then be ICC v2.
+pub(crate) fn finish(pdf: &[u8]) -> Result<Vec<u8>, String> {
+ let unreadable = || "the flattened file couldn't be read to add the PDF/X-1a identification".to_string();
+ let layout = Layout::read(pdf).ok_or_else(unreadable)?;
+ let file = hayro_syntax::Pdf::new(pdf.to_vec()).map_err(|_| unreadable())?;
+ let mut bodies: HashMap<usize, Vec<u8>> = HashMap::new();
+ let info = int_after(&layout.trailer, "/Info").ok_or_else(unreadable)?;
+ let body = layout.body(pdf, info).ok_or_else(unreadable)?;
+ let (head, close) = body.split_at_checked(rfind(body, b">>").ok_or_else(unreadable)?).ok_or_else(unreadable)?;
+ bodies.insert(info, [head, format!("/GTS_PDFXConformance({CONFORMANCE})").as_bytes(), close].concat());
+ let xref = file.xref();
+ if let Some(meta) = xref.get::<Dict<'_>>(xref.root_id()).and_then(|c| c.get_ref(b"Metadata")).and_then(|r| usize::try_from(r.obj_number).ok())
+ && let Some(xmp) = layout.body(pdf, meta).and_then(xmp_with_conformance)
+ {
+ bodies.insert(meta, xmp);
+ }
+ let mut stripped: Vec<usize> = Vec::new();
+ for oi in pdfx_intents(&file) {
+ if !oi.has_profile {
+ continue;
+ }
+ if !oi.registered {
+ if oi.major() != Some(2) {
+ return Err(format!(
+ "the output intent's profile `{}` is {}, and PDF/X-1a (PDF 1.4) allows only ICC v2 profiles: choose a CMYK working space with an ICC v2 profile, or Coated FOGRA39",
+ oi.name,
+ oi.version()
+ ));
+ }
+ continue;
+ }
+ let (Some(obj), Some(profile)) = (oi.obj, oi.profile_obj) else { return Err(unreadable()) };
+ let body = match bodies.get(&obj) {
+ Some(b) => b.clone(),
+ None => layout.body(pdf, obj).ok_or_else(unreadable)?.to_vec(),
+ };
+ let key = format!("/DestOutputProfile {profile} 0 R");
+ let at = find(&body, key.as_bytes(), 0).ok_or_else(unreadable)?;
+ let (before, rest) = body.split_at_checked(at).ok_or_else(unreadable)?;
+ let after = rest.get(key.len()..).ok_or_else(unreadable)?;
+ bodies.insert(obj, [before, after].concat());
+ stripped.push(profile);
+ }
+ // A profile only the stripped intents named goes too.
+ let dropped: HashSet<usize> = stripped.iter().copied().filter(|p| references(pdf, *p) == stripped.iter().filter(|q| *q == p).count()).collect();
+ layout.write(pdf, &bodies, &dropped).ok_or_else(unreadable)
+}
+
+/// How often `n 0 R` appears in `pdf` (a stream that happens to hold those bytes counts too, which
+/// only ever keeps an object).
+fn references(pdf: &[u8], n: usize) -> usize {
+ let needle = format!("{n} 0 R");
+ let mut count = 0;
+ let mut from = 0;
+ while let Some(at) = find(pdf, needle.as_bytes(), from) {
+ let before = at.checked_sub(1).and_then(|i| pdf.get(i)).is_none_or(|c| !c.is_ascii_digit());
+ let after = pdf.get(at + needle.len()).is_none_or(|c| !c.is_ascii_alphanumeric());
+ if before && after {
+ count += 1;
+ }
+ from = at + needle.len();
+ }
+ count
+}
+
+/// The body of an uncompressed XMP metadata stream object with the Adobe `pdfx` properties of
+/// the identification (`GTS_PDFXVersion`, `GTS_PDFXConformance`) added and its `/Length` updated;
+/// `None` when the stream is filtered or isn't XMP.
+fn xmp_with_conformance(body: &[u8]) -> Option<Vec<u8>> {
+ let s0 = find(body, b"stream", 0)?;
+ let dict = String::from_utf8_lossy(body.get(..s0)?).to_string();
+ let s0 = s0 + 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();
+ if dict.contains("/Filter") || !xml.contains("</rdf:RDF>") {
+ return None;
+ }
+ let ids = format!(
+ "<rdf:Description rdf:about=\"\" xmlns:pdfx=\"http://ns.adobe.com/pdfx/1.3/\"><pdfx:GTS_PDFXVersion>{VERSION}</pdfx:GTS_PDFXVersion>\
+ <pdfx:GTS_PDFXConformance>{CONFORMANCE}</pdfx:GTS_PDFXConformance></rdf:Description>"
+ );
+ let xml = xml.replacen("</rdf:RDF>", &format!("{ids}</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..)?);
+ Some(format!("\n{}\nstream\n{xml}\nendstream\n", dict.trim()).into_bytes())
+}
+
+/// Where the objects of a single-revision file with a classic cross-reference table are.
+struct Layout {
+ /// (object number, start, end), by start: from `n 0 obj` up to the next object or the table.
+ objects: Vec<(usize, usize, usize)>,
+ /// Where the cross-reference table starts.
+ table: usize,
+ /// The trailer dictionary.
+ trailer: String,
+ size: usize,
+}
+
+impl Layout {
+ fn read(pdf: &[u8]) -> Option<Layout> {
+ let sx = rfind(pdf, b"startxref")?;
+ let table: usize = std::str::from_utf8(pdf.get(sx + b"startxref".len()..)?).ok()?.split_whitespace().next()?.parse().ok()?;
+ let section = pdf.get(table..sx)?;
+ let t = find(section, b"trailer", 0)?;
+ let trailer = String::from_utf8_lossy(section.get(t + b"trailer".len()..)?).trim().to_string();
+ if trailer.contains("/Prev") || trailer.contains("/XRefStm") {
+ return None;
+ }
+ let size = int_after(&trailer, "/Size")?;
+ let mut tokens = std::str::from_utf8(section.get(..t)?).ok()?.split_whitespace();
+ if tokens.next()? != "xref" {
+ return None;
+ }
+ let mut starts: Vec<(usize, usize)> = Vec::new();
+ let mut seen = HashSet::new();
+ while let Some(first) = tokens.next() {
+ let first: usize = first.parse().ok()?;
+ let count: usize = tokens.next()?.parse().ok()?;
+ for i in 0..count {
+ let (offset, generation, kind) = (tokens.next()?, tokens.next()?, tokens.next()?);
+ if kind != "n" {
+ continue;
+ }
+ let n = first.checked_add(i)?;
+ let offset: usize = offset.parse().ok()?;
+ if generation != "00000" || offset >= table || n >= size || !seen.insert(n) {
+ return None;
+ }
+ starts.push((n, offset));
+ }
+ }
+ // Free entries past the objects would only make the rewritten table longer.
+ let max = starts.iter().map(|(n, _)| *n).max().unwrap_or(0);
+ if size > max.saturating_mul(2).saturating_add(16) {
+ return None;
+ }
+ starts.sort_by_key(|(_, offset)| *offset);
+ let mut objects = Vec::with_capacity(starts.len());
+ for (i, &(n, start)) in starts.iter().enumerate() {
+ let end = starts.get(i + 1).map_or(table, |(_, s)| *s);
+ if !pdf.get(start..end)?.starts_with(format!("{n} 0 obj").as_bytes()) {
+ return None;
+ }
+ objects.push((n, start, end));
+ }
+ Some(Layout { objects, table, trailer, size })
+ }
+
+ /// Object `n` between `n 0 obj` and `endobj`.
+ fn body<'p>(&self, pdf: &'p [u8], n: usize) -> Option<&'p [u8]> {
+ let &(_, start, end) = self.objects.iter().find(|(m, _, _)| *m == n)?;
+ let obj = pdf.get(start..end)?;
+ obj.get(format!("{n} 0 obj").len()..rfind(obj, b"endobj")?)
+ }
+
+ /// The file with the objects in `bodies` replaced and those in `dropped` left out, and a new
+ /// cross-reference table.
+ fn write(&self, pdf: &[u8], bodies: &HashMap<usize, Vec<u8>>, dropped: &HashSet<usize>) -> Option<Vec<u8>> {
+ let first = self.objects.first().map_or(self.table, |o| o.1);
+ let mut out = pdf.get(..first)?.to_vec();
+ let mut offsets = HashMap::new();
+ for &(n, start, end) in &self.objects {
+ if dropped.contains(&n) {
+ continue;
+ }
+ offsets.insert(n, out.len());
+ match bodies.get(&n) {
+ Some(body) => {
+ out.extend_from_slice(format!("{n} 0 obj").as_bytes());
+ out.extend_from_slice(body);
+ out.extend_from_slice(b"endobj\n");
+ }
+ None => out.extend_from_slice(pdf.get(start..end)?),
+ }
+ }
+ if !out.ends_with(b"\n") {
+ out.push(b'\n');
+ }
+ let table = out.len();
+ // The free entries, each pointing at the next.
+ let free: Vec<usize> = (1..self.size).filter(|n| !offsets.contains_key(n)).collect();
+ let next: HashMap<usize, usize> = free.iter().copied().zip(free.iter().skip(1).copied().chain([0])).collect();
+ out.extend_from_slice(format!("xref\n0 {}\n{:010} 65535 f\r\n", self.size, free.first().copied().unwrap_or(0)).as_bytes());
+ for n in 1..self.size {
+ let next = next.get(&n).copied().unwrap_or(0);
+ let entry = match offsets.get(&n) {
+ Some(offset) => format!("{offset:010} 00000 n\r\n"),
+ // A dropped object's number could be used again, at the next generation.
+ None if dropped.contains(&n) => format!("{next:010} 00001 f\r\n"),
+ None => format!("{next:010} 65535 f\r\n"),
+ };
+ out.extend_from_slice(entry.as_bytes());
+ }
+ out.extend_from_slice(format!("trailer\n{}\nstartxref\n{table}\n%%EOF\n", self.trailer).as_bytes());
+ Some(out)
+ }
}
/// Why a color space isn't allowed in PDF/X-1a, or `None` when it is.
@@ -280,7 +575,7 @@ impl Scan {
b"Tf" => {
let font = op.operands().next().cloned().and_then(Object::into_name).and_then(|n| res.get_font(&n));
if let Some(font) = font {
- self.font(&font);
+ self.font(&font, res, depth);
}
}
b"Do" => {
@@ -406,9 +701,9 @@ impl Scan {
}
}
- /// Embedded and not Type 3: a simple font's descriptor, or a Type 0 font's descendant's,
- /// has a font file.
- fn font(&mut self, font: &Dict<'_>) {
+ /// Embedded: a simple font's descriptor, or a Type 0 font's descendant's, has a font file. A
+ /// Type 3 font's glyphs are content streams in the file, scanned like the page's.
+ fn font(&mut self, font: &Dict<'_>, parent: &Resources<'_>, depth: usize) {
if let Some(id) = font.obj_id()
&& !self.fonts.insert(id)
{
@@ -417,7 +712,7 @@ impl Scan {
let name = font.get::<Name<'_>>(b"BaseFont").map(|n| String::from_utf8_lossy(n.as_ref()).to_string()).unwrap_or_else(|| "?".into());
let subtype = font.get::<Name<'_>>(b"Subtype");
let descriptor = match subtype.as_deref() {
- Some(b"Type3") => return self.font_issues.push(format!("the Type 3 font {name}")),
+ Some(b"Type3") => return self.type3(font, parent, depth),
Some(b"Type0") => {
font.get::<Array<'_>>(b"DescendantFonts").and_then(|a| a.iter::<Dict<'_>>().next()).and_then(|d| d.get::<Dict<'_>>(b"FontDescriptor"))
}
@@ -428,4 +723,21 @@ impl Scan {
self.font_issues.push(format!("the font {name} isn't embedded"));
}
}
+
+ /// A Type 3 font's glyph procedures, with the font's resources over `parent`'s.
+ fn type3(&mut self, font: &Dict<'_>, parent: &Resources<'_>, depth: usize) {
+ if depth >= MAX_DEPTH {
+ return;
+ }
+ let res = Resources::from_parent(font.get::<Dict<'_>>(b"Resources").unwrap_or_default(), parent.clone());
+ let Some(procs) = font.get::<Dict<'_>>(b"CharProcs") else { return };
+ for key in procs.keys() {
+ if let Some(glyph) = procs.get::<Stream<'_>>(key.as_ref())
+ && self.seen.insert(glyph.obj_id())
+ && let Ok(data) = glyph.decoded()
+ {
+ self.content(&data, &res, depth + 1);
+ }
+ }
+ }
}
diff --git a/crates/pdf/src/x1a_tests.rs b/crates/pdf/src/x1a_tests.rs
index 330719af2..fbb1bda39 100644
--- a/crates/pdf/src/x1a_tests.rs
+++ b/crates/pdf/src/x1a_tests.rs
@@ -13,7 +13,6 @@ use designcraft_geom::Rect;
use hayro_syntax::Pdf;
use hayro_syntax::object::{Dict, Name, Object};
-use crate::print_tests::output_intent;
use crate::tests::extract_text;
use crate::{PdfOptions, ShadowMask, Standard, check_pdfx1a, export_pdf_with_report};
@@ -109,20 +108,19 @@ 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));
- // 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_eq!(check_pdfx1a(bytes), Vec::<String>::new());
+ assert!(text.contains("/GTS_PDFXVersion(PDF/X-1:2003)") && text.contains("/GTS_PDFXConformance(PDF/X-1a:2003)"), "the identification");
+ assert!(text.contains("<pdfx:GTS_PDFXConformance>PDF/X-1a:2003</pdfx:GTS_PDFXConformance>"), "the identification in XMP");
+ // The default Coated FOGRA39 is a registered condition: no (ICC v4) profile in the file.
+ let pdf = Pdf::new(bytes.to_vec()).unwrap();
+ let oi = pdfx_intent(&pdf);
+ assert_eq!(oi.get::<hayro_syntax::object::String<'_>>(b"OutputConditionIdentifier").unwrap().as_bytes(), b"FOGRA39");
+ assert_eq!(oi.get::<hayro_syntax::object::String<'_>>(b"RegistryName").unwrap().as_bytes(), b"http://www.color.org");
+ assert!(!oi.contains_key(b"DestOutputProfile"), "no destination profile");
+ let profiles = pdf.objects().into_iter().filter(|o| matches!(o, Object::Stream(s) if s.dict().get::<i32>(b"N") == Some(4))).count();
+ assert_eq!(profiles, 0, "the profile is left out of the file");
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) {
assert!(["DeviceCMYK", "DeviceGray", "Separation", "DeviceN", "Indexed", "Pattern"].contains(&f.as_str()), "color space {f}");
}
@@ -130,7 +128,6 @@ fn x1a_export_flattens_transparency_into_inks() {
for gone in ["/SMask<<", "/SMask <<", "/S/Transparency", "/ca 0.5", "/CA 0.5", "/BM/Multiply"] {
assert!(!text.contains(gone), "{gone}");
}
- let pdf = Pdf::new(bytes.to_vec()).unwrap();
let states: Vec<(bool, bool, i32)> = pdf
.objects()
.into_iter()
@@ -143,22 +140,46 @@ fn x1a_export_flattens_transparency_into_inks() {
assert!(extract_text(bytes).concat().contains("Live text"), "{:?}", extract_text(bytes));
}
-/// 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.
+/// The catalog's `GTS_PDFX` output intent.
+fn pdfx_intent<'a>(pdf: &'a Pdf) -> Dict<'a> {
+ let xref = pdf.xref();
+ let catalog = xref.get::<Dict<'_>>(xref.root_id()).unwrap();
+ let intents = catalog.get::<hayro_syntax::object::Array<'_>>(b"OutputIntents").unwrap();
+ intents.iter::<Dict<'_>>().find(|oi| oi.get::<Name<'_>>(b"S").is_some_and(|s| s.as_ref() == b"GTS_PDFX")).unwrap()
+}
+
+/// An ICC profile header of major version `major`, all a check reads of it.
+fn icc_header(major: u8) -> Vec<u8> {
+ [&[0u8; 8][..], &[major, 0x20, 0, 0], b"prtrCMYK"].concat()
+}
+
+/// A minimal PDF 1.4 with a CMYK output intent (an unregistered condition with an ICC v2
+/// profile), the X-1a identification and `content` on its page; `entries` go into the page
+/// dictionary.
fn tiny_x1a(entries: &str, content: &str) -> Vec<u8> {
- tiny_x1a_with_profile(entries, content, b"")
+ tiny_x1a_with(entries, content, "/OutputConditionIdentifier(Custom)/DestOutputProfile 4 0 R", &icc_header(2))
}
-/// [`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(),
+/// [`tiny_x1a`] whose output intent (object 7) has `intent` and whose object 4 holds `profile`.
+fn tiny_x1a_with(entries: &str, content: &str, intent: &str, profile: &[u8]) -> Vec<u8> {
+ assemble(&tiny_objects(entries, content, intent, profile))
+}
+
+/// [`tiny_x1a_with`]'s objects, from 1.
+fn tiny_objects(entries: &str, content: &str, intent: &str, profile: &[u8]) -> Vec<Vec<u8>> {
+ vec![
+ b"<</Type/Catalog/Pages 2 0 R/OutputIntents[7 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(),
- ];
+ b"<</GTS_PDFXVersion(PDF/X-1:2003)/GTS_PDFXConformance(PDF/X-1a:2003)/Trapped/False>>".to_vec(),
+ format!("<</Type/OutputIntent/S/GTS_PDFX{intent}>>").into_bytes(),
+ ]
+}
+
+/// A PDF 1.4 file of `objects` (from 1), object 1 the catalog and 6 the information dictionary.
+fn assemble(objects: &[Vec<u8>]) -> Vec<u8> {
let mut out = b"%PDF-1.4\n".to_vec();
let mut offsets = Vec::new();
for (i, o) in objects.iter().enumerate() {
@@ -181,7 +202,7 @@ fn tiny_x1a_with_profile(entries: &str, content: &str, profile: &[u8]) -> Vec<u8
#[test]
fn x1a_checks_refuse_transparency_and_rgb() {
let clean = check_pdfx1a(&tiny_x1a(
- "/Resources<</ColorSpace<</Gold[/Separation/Gold/DeviceCMYK 7 0 R]>>>>",
+ "/Resources<</ColorSpace<</Gold[/Separation/Gold/DeviceCMYK 9 0 R]>>>>",
"0 0 0 1 k 0 0 10 10 re f 0.5 G /Gold cs 1 scn 0 0 5 5 re f",
));
assert_eq!(clean, Vec::<String>::new());
@@ -195,18 +216,37 @@ fn x1a_checks_refuse_transparency_and_rgb() {
has("/Resources<</ExtGState<</G0<</ca 0.5>>>>>>", "/G0 gs 0 0 0 1 k 0 0 10 10 re f", "opacity");
has("/Resources<</ExtGState<</G0<</BM/Multiply>>>>>>", "/G0 gs 0 0 0 1 k 0 0 10 10 re f", "/Multiply");
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<</ColorSpace<</S[/Separation/Gold/DeviceRGB 9 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<<>>>>]>>>>",
+ "/Resources<</ColorSpace<</N[/DeviceN[/Cyan/Gold]/DeviceCMYK 9 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());
+ // The output intent: an ICC v2 profile, or none for a registered condition.
+ let intent = |intent: &str, profile: &[u8]| check_pdfx1a(&tiny_x1a_with("/Resources<<>>", "0 0 0 1 k", intent, profile));
+ let v4 = intent("/OutputConditionIdentifier(Custom)/DestOutputProfile 4 0 R", &icc_header(4));
+ assert!(v4.iter().any(|i| i.contains("ICC v4")), "{v4:?}");
+ let registered = "/OutputConditionIdentifier(FOGRA39)/RegistryName(http://www.color.org)";
+ assert!(!intent(&format!("{registered}/DestOutputProfile 4 0 R"), &icc_header(4)).is_empty(), "v4 even when registered");
+ assert_eq!(intent(registered, b""), Vec::<String>::new());
+ let unnamed = intent("/OutputConditionIdentifier(Custom)", b"");
+ assert!(unnamed.iter().any(|i| i.contains("no destination profile")), "{unnamed:?}");
+ // The identification names the conformance level.
+ let base_only = String::from_utf8_lossy(&tiny_x1a("/Resources<<>>", "0 0 0 1 k")).replace("/GTS_PDFXConformance(PDF/X-1a:2003)", "");
+ let issues = check_pdfx1a(base_only.as_bytes());
+ assert!(issues.iter().any(|i| i.contains("PDF/X-1a:2003")), "{issues:?}");
+ // A Type 3 font is embedded by nature; its glyphs are checked like the page.
+ let type3 = |glyph: &str| {
+ let font = "/Resources<</Font<</F0<</Type/Font/Subtype/Type3/FontBBox[0 0 1 1]/FontMatrix[1 0 0 1 0 0]/CharProcs<</a 8 0 R>>\
+ /Encoding<</Type/Encoding/Differences[97/a]>>/FirstChar 97/LastChar 97/Widths[1]>>>>>>";
+ let mut objects = tiny_objects(font, "BT /F0 10 Tf (a) Tj ET", "/OutputConditionIdentifier(Custom)/DestOutputProfile 4 0 R", &icc_header(2));
+ objects.push(format!("<</Length {}>>\nstream\n{glyph}\nendstream", glyph.len()).into_bytes());
+ check_pdfx1a(&assemble(&objects))
+ };
+ assert_eq!(type3("1 0 d0 0 0 0 1 k 0 0 1 1 re f"), Vec::<String>::new());
+ let rgb = type3("1 0 d0 1 0 0 rg 0 0 1 1 re f");
+ assert!(rgb.iter().any(|i| i.contains("DeviceRGB")), "{rgb:?}");
// A PDF/X-4 file isn't X-1a.
let x4 = export_pdf_with_report(
&Document::new(&NewDocument::default()),
@@ -224,3 +264,56 @@ fn x1a_parses() {
assert_eq!(Standard::parse(s), Some(Standard::PdfX1a), "{s}");
}
}
+
+/// The identification and output intent krilla doesn't write: the conformance level goes into
+/// the document information; a registered condition's intent loses its profile, which leaves the
+/// file; an unregistered condition keeps an ICC v2 profile and refuses a v4 one.
+#[test]
+fn x1a_finish_names_the_conformance_and_fixes_the_intent() {
+ let base = |intent: &str, major: u8| {
+ let mut objects = tiny_objects("/Resources<<>>", "0 0 0 1 k", intent, &icc_header(major));
+ objects[5] = b"<</GTS_PDFXVersion(PDF/X-1:2003)/Trapped/False>>".to_vec();
+ assemble(&objects)
+ };
+ let registered = "/OutputConditionIdentifier(FOGRA39)/RegistryName(http://www.color.org)/DestOutputProfile 4 0 R";
+ let before = base(registered, 4);
+ assert!(!check_pdfx1a(&before).is_empty());
+ let out = crate::pdfx1a::finish(&before).unwrap();
+ assert_eq!(check_pdfx1a(&out), Vec::<String>::new());
+ let pdf = Pdf::new(out.clone()).unwrap();
+ assert!(!pdfx_intent(&pdf).contains_key(b"DestOutputProfile"));
+ assert!(!String::from_utf8_lossy(&out).contains("/N 4"), "the profile is left out");
+ assert_eq!(pdf.pages().len(), 1);
+
+ let custom = "/OutputConditionIdentifier(Custom)/OutputCondition(Press)/DestOutputProfile 4 0 R";
+ let kept = crate::pdfx1a::finish(&base(custom, 2)).unwrap();
+ assert_eq!(check_pdfx1a(&kept), Vec::<String>::new());
+ assert!(pdfx_intent(&Pdf::new(kept).unwrap()).contains_key(b"DestOutputProfile"));
+ let refused = crate::pdfx1a::finish(&base(custom, 4)).unwrap_err();
+ assert!(refused.contains("`Press`") && refused.contains("ICC v4"), "{refused}");
+}
+
+/// An image the flattener can't read fails the export, naming the page and its graphics.
+#[test]
+fn x1a_refuses_to_leave_images_out() {
+ let objects = vec![
+ b"<</Type/Catalog/Pages 2 0 R>>".to_vec(),
+ b"<</Type/Pages/Kids[3 0 R]/Count 1>>".to_vec(),
+ b"<</Type/Page/Parent 2 0 R/MediaBox[0 0 100 100]/TrimBox[0 0 100 100]/Resources<</XObject<</Im0 4 0 R>>>>/Contents 5 0 R>>".to_vec(),
+ b"<</Type/XObject/Subtype/Image/Width 2/Height 2/ColorSpace/DeviceCMYK/BitsPerComponent 8/Filter/DCTDecode/Length 8>>\nstream\nnot jpeg\nendstream".to_vec(),
+ b"<</Length 30>>\nstream\nq 50 0 0 50 10 10 cm /Im0 Do Q\nendstream".to_vec(),
+ b"<</Producer(test)>>".to_vec(),
+ ];
+ let pages = [crate::pdfx1a::PageGraphics { label: "iv".into(), graphics: vec!["logo.pdf".into()] }];
+ let err = crate::pdfx1a::flatten_x1a(&assemble(&objects), 72.0, &pages, &mut Vec::new()).unwrap_err().to_string();
+ assert!(err.contains("1 image on page iv") && err.contains("`logo.pdf`"), "{err}");
+}
+
+/// Spot inks past the flattener's ink set lose their tints: the warning says they won't print.
+#[test]
+fn x1a_dropped_inks_warning_says_they_wont_print() {
+ let totals = craft_prepress::flatten::FlattenTotals { dropped_inks: 3, ..Default::default() };
+ let warnings = crate::pdfx1a::flatten_warnings(&totals, 300.0);
+ assert!(warnings.iter().any(|w| w.contains("3 tint(s)") && w.contains("dropped and won't print")), "{warnings:?}");
+ assert!(warnings.iter().all(|w| !w.contains("converted to process")), "{warnings:?}");
+}