Skip to content

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

Print color: PDF/X-1a export through craft-prepress's flattener

aiongg75c6084a69c6
diff --git a/apps/designcraft-cli/src/main.rs b/apps/designcraft-cli/src/main.rs
index 71e05a480..0e3a02a18 100644
--- a/apps/designcraft-cli/src/main.rs
+++ b/apps/designcraft-cli/src/main.rs
@@ -14,7 +14,8 @@
//! # MCP server over stdio (docs/mcp.md); the roots confine the files it reads and writes
//! designcraft-cli perf [--pages N] [--frames N] [--chars N] [--images N] [--runs N] [--strict] # budgets on a synthetic stress document
//! designcraft-cli bench FILE [--runs N] # the same measurements on one document
-//! designcraft-cli validate-pdf FILE.pdf # run the built-in PDF/X-4 conformance checks
+//! designcraft-cli validate-pdf FILE.pdf [--standard x4|x1a] # the built-in PDF/X-4 or PDF/X-1a checks (default: the
+//! # file's own GTS_PDFXVersion)
//! designcraft-cli links # Discord, website, app page and GitHub links
//! designcraft-cli --version # print the version
//! ```
@@ -122,7 +123,7 @@ fn main() -> ExitCode {
Some("mcp") => report(mcp(&args[1..])),
Some("perf") => report(perf::perf(&args[1..])),
Some("bench") => report(perf::bench(&args[1..])),
- Some("validate-pdf") => report(validate_pdf(args.get(1).map(String::as_str))),
+ Some("validate-pdf") => report(validate_pdf(args.get(1..).unwrap_or_default())),
Some("links") => {
use designcraft_engine::links::*;
outln!("Discord {DISCORD}\nWebsite {WEBSITE}\nApp page {APP_PAGE}\nGitHub {GITHUB}\nIssues {ISSUES}");
@@ -153,14 +154,36 @@ fn report(r: Result<(), String>) -> ExitCode {
}
}
-fn validate_pdf(path: Option<&str>) -> Result<(), String> {
- let path = path.ok_or("usage: designcraft-cli validate-pdf FILE.pdf")?;
+fn validate_pdf(args: &[String]) -> Result<(), String> {
+ const USAGE: &str = "usage: designcraft-cli validate-pdf FILE.pdf [--standard x4|x1a]";
+ const X1A: &[u8] = b"/GTS_PDFXVersion(PDF/X-1:";
+ let mut path = None;
+ let mut standard = None;
+ let mut it = args.iter();
+ while let Some(a) = it.next() {
+ match a.as_str() {
+ "--standard" => standard = Some(it.next().ok_or(USAGE)?.as_str()),
+ p if path.is_none() => path = Some(p),
+ _ => return Err(USAGE.into()),
+ }
+ }
+ let path = path.ok_or(USAGE)?;
let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
- let issues = designcraft_pdf::check_pdfx4(&bytes);
+ let standard = match standard.map(designcraft_pdf::Standard::parse) {
+ Some(Some(s)) => s,
+ Some(None) => return Err(USAGE.into()),
+ None if bytes.windows(X1A.len()).any(|w| w == X1A) => designcraft_pdf::Standard::PdfX1a,
+ None => designcraft_pdf::Standard::PdfX4,
+ };
+ let (name, issues) = match standard {
+ designcraft_pdf::Standard::PdfX1a => ("PDF/X-1a:2003", designcraft_pdf::check_pdfx1a(&bytes)),
+ designcraft_pdf::Standard::PdfX4 => ("PDF/X-4", designcraft_pdf::check_pdfx4(&bytes)),
+ _ => return Err(USAGE.into()),
+ };
let valid = issues.is_empty();
- let report = json!({"path": path, "standard": "PDF/X-4", "valid": valid, "issues": issues});
+ let report = json!({"path": path, "standard": name, "valid": valid, "issues": issues});
outln!("{}", serde_json::to_string_pretty(&report).map_err(|e| e.to_string())?);
- if valid { Ok(()) } else { Err(format!("{path} failed PDF/X-4 validation")) }
+ if valid { Ok(()) } else { Err(format!("{path} failed {name} validation")) }
}
/// `mcp` (headless, in-process engine) or `mcp --connect PORT|HOST:PORT` (drive a running app
diff --git a/crates/engine/src/cmd/export.rs b/crates/engine/src/cmd/export.rs
index 7b1db1afb..3ed4f73ea 100644
--- a/crates/engine/src/cmd/export.rs
+++ b/crates/engine/src/cmd/export.rs
@@ -10,7 +10,7 @@ use crate::{EngineError, Result, Session};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(noundo "file.exportPdf", "Export PDF…", ["File"], None,
- "{path?, pages?: \"1-3,5\" | [1,3] (1-based positions; default all), flatten?: high|medium|low|ppi (Transparency Flattener: spreads with transparency are rasterised), spreads?: bool, fullScreen?: bool, bookmarksPanel?: bool, pageLayout?: single|continuous|twoUp|twoUpCover|twoUpContinuous, view?: fitPage|fitWidth|actual, advanceSeconds?: number (interactive PDF), bleed?: bool (document bleed), marks?: bool | {crop?, bleed?, pageInfo?, weight?, offset?}, standard?: \"none\"|\"x4\"|\"a2b\", compressImages?: bool, tagged?: bool (structure tree: stories as paragraphs, figures with alt text), media?: bool (interactive: embed placed video and sound), title?, author?} → {path, bytes, pages, warnings} (no path: {base64, …})",
+ "{path?, pages?: \"1-3,5\" | [1,3] (1-based positions; default all), flatten?: high|medium|low|ppi (Transparency Flattener: spreads with transparency are rasterised; with standard x1a, the resolution complex transparent regions are rasterized at: high 300, medium 150, low 72, default 300), spreads?: bool, fullScreen?: bool, bookmarksPanel?: bool, pageLayout?: single|continuous|twoUp|twoUpCover|twoUpContinuous, view?: fitPage|fitWidth|actual, advanceSeconds?: number (interactive PDF), bleed?: bool (document bleed), marks?: bool | {crop?, bleed?, pageInfo?, weight?, offset?}, standard?: \"none\"|\"x4\"|\"x1a\"|\"a2b\" (x1a: PDF/X-1a:2003, the PDF/X-4 file flattened in its inks by craft-prepress: no transparency, only CMYK, gray and spot color), compressImages?: bool, tagged?: bool (structure tree: stories as paragraphs, figures with alt text), media?: bool (interactive: embed placed video and sound), title?, author?} → {path, bytes, pages, warnings} (no path: {base64, …})",
has_doc, export_pdf),
cmd!(noundo "file.exportEpub", "Export EPUB (Reflowable)…", ["File"], None,
"{path?, title?, author?, language?: \"en\", identifier?: str (dc:identifier; a stable urn:uuid by default), coverImage?: path (a PNG or JPEG as the cover), tocTitle?: str (the table of contents' title; from the language by default), cover?: bool (the first page as the cover image), embedFonts?: bool (package the stylesheet's fonts whose licence allows it, whole files), fixedLayout?: bool (pre-paginated: each page as an image with its text)} → {path, bytes, warnings} (no path: {base64, bytes, warnings}); warnings name images without alt text, exported as decorative, and fonts that could not be embedded",
@@ -368,7 +368,7 @@ pub(crate) fn options(p: &Value, page_count: usize) -> Result<PdfOptions> {
_ => Marks::NONE,
};
let standard = match str_param(p, "standard") {
- Some(s) => Standard::parse(s).ok_or_else(|| bad(ID, format!("unknown standard `{s}` (none, x4, a2b)")))?,
+ Some(s) => Standard::parse(s).ok_or_else(|| bad(ID, format!("unknown standard `{s}` (none, x4, x1a, a2b)")))?,
None => Standard::None,
};
Ok(PdfOptions {
@@ -524,9 +524,96 @@ fn raster_effects(it: &designcraft_doc::Item) -> bool {
}
/// A copy of `d` where spread-level objects with soft effects are 300 ppi images of their whole
-/// appearance (transparent around them, so they composite over what's behind).
-fn rasterize_effects(d: &designcraft_doc::Document, cache: &designcraft_compose::Cache) -> (Option<designcraft_doc::Document>, usize) {
- rasterize_where(d, cache, 300.0, true, |it| raster_effects(it) && !threaded(d, it))
+/// appearance (transparent around them, so they composite over what's behind). Objects in `skip`
+/// stay as they are.
+fn rasterize_effects(
+ d: &designcraft_doc::Document,
+ cache: &designcraft_compose::Cache,
+ skip: &std::collections::HashMap<designcraft_doc::ItemId, designcraft_pdf::ShadowMask>,
+) -> (Option<designcraft_doc::Document>, usize) {
+ rasterize_where(d, cache, 300.0, true, |it| raster_effects(it) && !threaded(d, it) && !skip.contains_key(&it.id))
+}
+
+/// A drop shadow is the object's only soft effect, and the PDF writer draws its shadow itself
+/// (a leaf object, not a group or a frame with items pasted into it).
+fn shadow_only(it: &designcraft_doc::Item) -> bool {
+ let e = &it.effects;
+ e.drop_shadow.on
+ && !(e.feather > 0.0
+ || e.inner_shadow.on
+ || e.outer_glow.on
+ || e.inner_glow.on
+ || e.bevel.on
+ || e.satin.on
+ || e.directional_feather.on
+ || e.gradient_feather.on)
+ && it.children().is_empty()
+ && !it.has_nested_items()
+}
+
+/// For PDF/X-1a: the coverage of each spread object's soft drop shadow at `ppi`, so the PDF draws
+/// 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.
+fn shadow_masks(
+ d: &designcraft_doc::Document,
+ cache: &designcraft_compose::Cache,
+ ppi: f64,
+) -> std::collections::HashMap<designcraft_doc::ItemId, designcraft_pdf::ShadowMask> {
+ use designcraft_doc::SpreadRef;
+ let mut out = std::collections::HashMap::new();
+ let todo: Vec<(usize, designcraft_doc::ItemId)> = d
+ .spreads
+ .iter()
+ .enumerate()
+ .flat_map(|(si, sp)| sp.items.iter().filter(|it| !it.hidden && shadow_only(it)).map(move |it| (si, it.id)))
+ .collect();
+ if todo.is_empty() {
+ return out;
+ }
+ let mut rr = designcraft_render::Renderer::new();
+ rr.threads = designcraft_render::default_threads();
+ let k = ppi.clamp(36.0, 1200.0) / 72.0;
+ for (si, id) in todo {
+ let Some(it) = d.item(id) else { continue };
+ let grow = designcraft_render::effect_outset(it) + it.stroke.extent() + 2.0;
+ let reach = it.bounds().inflate(grow, grow);
+ let (w, h) = ((reach.width() * k).ceil().max(1.0), (reach.height() * k).ceil().max(1.0));
+ if !(w.is_finite() && h.is_finite()) || w * h > 60_000_000.0 {
+ continue;
+ }
+ let (w, h) = (w as u32, h as u32);
+ let mut alpha = |shadow: bool| {
+ let mut solo = d.clone();
+ let Some(sp) = solo.spreads.get_mut(si) else { return Vec::new() };
+ let sp = std::sync::Arc::make_mut(sp);
+ sp.items.retain(|x| x.id == id);
+ for pg in &mut sp.pages {
+ pg.show_parent_items = false;
+ }
+ if let Some(x) = sp.items.first_mut() {
+ let x = std::sync::Arc::make_mut(x);
+ x.opacity = 1.0;
+ x.blend = Default::default();
+ x.effects.drop_shadow.on = shadow;
+ }
+ let view = designcraft_geom::Affine::scale(k) * designcraft_geom::Affine::translate((-reach.x0, -reach.y0));
+ let opts = designcraft_render::RenderOptions { paper: false, background: None, printing_only: true, ..Default::default() };
+ let placed = [designcraft_render::Placed { spread: SpreadRef::Doc(si), xf: designcraft_geom::Affine::IDENTITY }];
+ rr.render(&solo, cache, &placed, w, h, view, &opts).pixels.as_chunks::<4>().0.iter().map(|px| px[3]).collect::<Vec<u8>>()
+ };
+ let (with, without) = (alpha(true), alpha(false));
+ let n = w as usize * h as usize;
+ if with.len() != n || without.len() != n {
+ continue;
+ }
+ let coverage: Vec<u8> = with.iter().zip(&without).map(|(a, b)| a.saturating_sub(*b)).collect();
+ out.insert(id, designcraft_pdf::ShadowMask { rect: reach, width: w, height: h, coverage: std::sync::Arc::new(coverage) });
+ }
+ out
}
/// A copy of `d` where the spread-level objects `pred` picks are images of their appearance at
@@ -733,12 +820,20 @@ pub(crate) fn pdf_export(s: &Session, p: &Value) -> Result<designcraft_pdf::Expo
v.as_f64().filter(|v| (36.0..=1200.0).contains(v)).ok_or_else(|| bad("file.exportPdf", "`flatten`: high|medium|low or 36–1200 ppi"))?,
),
};
- let flattened = ppi.map(|ppi| flatten(&st.doc, &s.cache, ppi));
+ // PDF/X-1a: craft-prepress flattens the PDF in its inks; `flatten` sets its resolution.
+ let x1a = opts.standard == Standard::PdfX1a;
+ let mut opts = opts;
+ if x1a {
+ opts.flatten_dpi = ppi.unwrap_or(300.0) as f32;
+ }
+ let flattened = if x1a { None } else { ppi.map(|ppi| flatten(&st.doc, &s.cache, ppi)) };
// Placed PDFs with hidden layers go out as images showing just their visible layers.
let base: &designcraft_doc::Document = flattened.as_ref().map_or(&st.doc, |f| &f.0);
let (layered, layer_count) = rasterize_layered(base);
let base2: &designcraft_doc::Document = layered.as_ref().unwrap_or(base);
- let (fx_doc, fx_count) = rasterize_effects(base2, &s.cache);
+ let shadows = if x1a { shadow_masks(base2, &s.cache, f64::from(opts.flatten_dpi)) } else { Default::default() };
+ let (fx_doc, fx_count) = rasterize_effects(base2, &s.cache, &shadows);
+ opts.shadows = std::sync::Arc::new(shadows);
let doc: &designcraft_doc::Document = fx_doc.as_ref().unwrap_or(base2);
let boxed = super::interchange::with_pdf_boxes(doc);
let doc: &designcraft_doc::Document = &boxed;
@@ -979,6 +1074,80 @@ mod text_tests {
std::fs::remove_dir_all(&dir).ok();
}
+ /// The color spaces of every image XObject in `pdf`, as the families and colorant names.
+ fn image_spaces(pdf: &[u8]) -> Vec<String> {
+ use hayro_syntax::object::{Name, Object};
+ let file = hayro_syntax::Pdf::new(pdf.to_vec()).unwrap();
+ file.objects()
+ .into_iter()
+ .filter_map(|o| o.into_stream())
+ .filter(|s| s.dict().get::<Name<'_>>(b"Subtype").is_some_and(|n| n.as_ref() == b"Image"))
+ .filter_map(|s| match s.dict().get::<Object<'_>>(b"ColorSpace")? {
+ Object::Name(n) => Some(n.as_str().to_string()),
+ Object::Array(a) => {
+ let mut it = a.iter::<Object<'_>>();
+ let family = it.next()?.into_name()?.as_str().to_string();
+ let names = match it.next() {
+ Some(Object::Array(n)) => n.iter::<Name<'_>>().map(|n| n.as_str().to_string()).collect::<Vec<_>>().join(" "),
+ Some(Object::Name(n)) => n.as_str().to_string(),
+ _ => String::new(),
+ };
+ Some(format!("{family} {names}"))
+ }
+ _ => None,
+ })
+ .collect()
+ }
+
+ /// 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
+ /// overprint stays `/op`; `flatten` sets the resolution.
+ #[test]
+ fn x1a_export_flattens_in_inks() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"pages": 1})).unwrap();
+ s.execute("swatch.create", &json!({"name": "Gold", "color": {"c": 0, "m": 30, "y": 90, "k": 10}, "spot": true})).unwrap();
+ let bg = s.execute("frame.create", &json!({"rect": [36, 36, 576, 756]})).unwrap()["id"].clone();
+ s.execute("object.fill", &json!({"ids": [bg], "swatch": "Gold"})).unwrap();
+ let shadowed = s.execute("frame.create", &json!({"rect": [72, 72, 200, 200]})).unwrap()["id"].clone();
+ s.execute("object.fill", &json!({"ids": [shadowed], "swatch": "C=0 M=100 Y=0 K=0"})).unwrap();
+ s.execute("object.dropShadow", &json!({"ids": [shadowed], "on": true, "distance": 8, "size": 6})).unwrap();
+ let half = s.execute("frame.create", &json!({"rect": [300, 72, 400, 172]})).unwrap()["id"].clone();
+ s.execute("object.fill", &json!({"ids": [half], "swatch": "C=100 M=0 Y=0 K=0"})).unwrap();
+ s.execute("object.opacity", &json!({"ids": [half], "opacity": 0.5})).unwrap();
+ let a = s.execute("frame.create", &json!({"rect": [72, 300, 172, 400]})).unwrap()["id"].clone();
+ let b = s.execute("frame.create", &json!({"rect": [122, 350, 222, 450]})).unwrap()["id"].clone();
+ s.execute("object.fill", &json!({"ids": [a, b], "swatch": "C=0 M=0 Y=100 K=0"})).unwrap();
+ s.execute("object.opacity", &json!({"ids": [a, b], "opacity": 0.5})).unwrap();
+ let g = s.execute("object.group", &json!({"ids": [a, b]})).unwrap()["id"].clone();
+ s.execute("object.transparencyGroup", &json!({"ids": [g], "knockout": true})).unwrap();
+ let op = s.execute("frame.create", &json!({"rect": [300, 300, 400, 400]})).unwrap()["id"].clone();
+ s.execute("object.fill", &json!({"ids": [op], "swatch": "C=0 M=100 Y=0 K=0"})).unwrap();
+ s.execute("object.attributes", &json!({"ids": [op], "overprintFill": true})).unwrap();
+ s.execute("frame.create", &json!({"rect": [72, 500, 400, 560], "content": "text", "text": "Live text", "caret": false})).unwrap();
+
+ 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());
+ 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}");
+ assert!(warnings.contains("at 72 ppi"), "{warnings}");
+ let spaces = image_spaces(&pdf);
+ assert!(spaces.iter().all(|cs| !cs.contains("RGB") && !cs.contains("ICC")), "{spaces:?}");
+ assert!(
+ spaces.iter().any(|cs| cs.starts_with("DeviceN") && cs.contains("Black") && cs.contains("Gold")),
+ "the shadow over the spot: {spaces:?}"
+ );
+ assert!(text.contains("/op true") && text.contains("/OPM 1"), "overprint");
+ assert!(text.contains("/FontFile"), "the text is still text");
+ // The default resolution.
+ let r = s.execute("file.exportPdf", &json!({"standard": "x1a"})).unwrap();
+ assert!(r["warnings"].to_string().contains("at 300 ppi"), "{}", r["warnings"]);
+ }
+
#[test]
fn flattener_rasterises_spreads_with_transparency() {
let mut s = Session::new();
@@ -1038,7 +1207,7 @@ mod text_tests {
let sid = d.item(designcraft_doc::ItemId(t)).and_then(|it| it.text_frame()).unwrap().story;
let before = designcraft_compose::frame_specs(d, sid)[0].exclusions.clone();
assert_eq!(before.len(), 2);
- let (fx, n) = super::rasterize_effects(d, &s.cache);
+ let (fx, n) = super::rasterize_effects(d, &s.cache, &Default::default());
assert_eq!(n, 2);
let fx = fx.unwrap();
assert_eq!(designcraft_compose::frame_specs(&fx, sid)[0].exclusions, before);
diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs
index c05f5267f..445aa20cb 100644
--- a/crates/pdf/src/export.rs
+++ b/crates/pdf/src/export.rs
@@ -133,7 +133,7 @@ pub(crate) fn mark_start(opts: &PdfOptions, bleed: [f64; 4]) -> f64 {
/// working space (which PDF/X also carries as its output intent). True when the document blends
/// in CMYK, and always in PDF/X; PDF/A exports are RGB.
pub fn print_color(doc: &Document, opts: &PdfOptions) -> bool {
- opts.standard != Standard::PdfA2b && (doc.settings.blend_space == designcraft_doc::BlendSpace::Cmyk || opts.standard == Standard::PdfX4)
+ opts.standard != Standard::PdfA2b && (doc.settings.blend_space == designcraft_doc::BlendSpace::Cmyk || opts.standard.is_pdfx())
}
/// Like [`export_pdf`], also returning warnings about approximated or dropped features.
@@ -145,14 +145,15 @@ fn export_pdf_with_report_inner(doc: &Document, cache: &Cache, opts: &PdfOptions
let sheets = sheets(doc, opts)?;
let (version, archival) = match opts.standard {
Standard::None => (PdfVersion::Pdf17, None),
- Standard::PdfX4 => (PdfVersion::Pdf16, None),
+ // PDF/X-1a starts as the PDF/X-4 print file, then is flattened.
+ Standard::PdfX4 | Standard::PdfX1a => (PdfVersion::Pdf16, None),
Standard::PdfA2b => (PdfVersion::Pdf17, Some(Archival::A2_B)),
};
let configuration = write::configuration(version, archival)?;
let mut warnings = Vec::new();
let base = if print_color(doc, opts) {
// An output intent only for PDF/X, as in InDesign.
- let (settings, warning) = crate::pdfx::print_settings(opts.standard == Standard::PdfX4)?;
+ let (settings, warning) = crate::pdfx::print_settings(opts.standard.is_pdfx())?;
warnings.extend(warning);
let pdfx_version = (opts.standard == Standard::PdfX4).then(|| "PDF/X-4".to_string());
krilla::SerializeSettings { pdfx_version, ..settings }
@@ -253,6 +254,8 @@ fn export_pdf_with_report_inner(doc: &Document, cache: &Cache, opts: &PdfOptions
if !fields.is_empty() || !media.is_empty() {
if opts.standard == Standard::PdfX4 {
warnings.push("PDF/X-4: form fields and media were left out".into());
+ } else if opts.standard == Standard::PdfX1a {
+ warnings.push("PDF/X-1a: form fields and media were left out".into());
} else if opts.standard == Standard::PdfA2b {
warnings.push("PDF/A-2b: form fields and media were left out".into());
} else {
@@ -272,6 +275,9 @@ fn export_pdf_with_report_inner(doc: &Document, cache: &Cache, opts: &PdfOptions
warnings.push(format!("PDF/X-4: {issue}"));
}
}
+ if opts.standard == Standard::PdfX1a {
+ bytes = crate::pdfx1a::flatten_x1a(&bytes, opts.flatten_dpi, created, &mut warnings)?;
+ }
warnings.dedup();
Ok(ExportReport { bytes, pages: sheets.len(), warnings })
}
@@ -628,7 +634,7 @@ pub(crate) fn solid_fill(c: krilla::color::Color, opacity: f32) -> Fill {
impl Exporter<'_> {
/// A print document, or a PDF/X file (whose output intent is CMYK).
pub(crate) fn for_print(&self) -> bool {
- self.doc.settings.intent == designcraft_doc::Intent::Print || self.opts.standard == Standard::PdfX4
+ self.doc.settings.intent == designcraft_doc::Intent::Print || self.opts.standard.is_pdfx()
}
/// Whether a paint overprints: its own attribute, or 100% [Black] when Preferences ›
@@ -966,8 +972,15 @@ impl Exporter<'_> {
if frame_art {
s.start_tagged(ContentTag::Artifact(Artifact::new(ArtifactType::Other, None)));
}
- // Drop shadow (simple offset silhouette, like the renderer).
+ // Drop shadow: its coverage mask when one was rendered, else a simple offset silhouette.
if ds.on
+ && let Some(mask) = self.opts.shadows.get(&it.id)
+ && let Some(c) = self.swatch_color(&ds.color, 1.0)
+ {
+ s.push_transform(&tf(parent));
+ draw_coverage(s, mask, c);
+ s.pop();
+ } else if ds.on
&& let Some(p) = &path
&& let Some(c) = self.swatch_color(&ds.color, 1.0)
{
@@ -1604,6 +1617,33 @@ impl Exporter<'_> {
}
}
+/// `paint` through `mask`'s coverage, a luminosity mask: the color's own inks (spot, process),
+/// never an RGB raster.
+fn draw_coverage(s: &mut Surface, mask: &crate::ShadowMask, paint: krilla::color::Color) {
+ let r = mask.rect;
+ let (Some(size), Some(rect), Some(image)) = (
+ Size::from_wh(r.width().max(1e-3) as f32, r.height().max(1e-3) as f32),
+ to_path(&r.to_path(0.1)),
+ CoverageImage::from_grey(mask.coverage.clone(), (mask.width, mask.height)),
+ ) else {
+ return;
+ };
+ let Ok(image) = Image::from_custom(image, false) else { return };
+ let mut sb = s.stream_builder();
+ let mut ms = sb.surface();
+ ms.push_transform(&tf(Affine::translate((r.x0, r.y0))));
+ ms.draw_image(image, size);
+ ms.pop();
+ ms.finish();
+ let stream = sb.finish();
+ s.push_mask(krilla::mask::Mask::new(stream, krilla::mask::MaskType::Luminosity));
+ s.set_stroke(None);
+ s.set_fill(Some(Fill { paint: paint.into(), ..Default::default() }));
+ s.draw_path(&rect);
+ s.set_fill(None);
+ s.pop();
+}
+
/// The ink coverage of a greyscale or bitmap image (255 = black, 0 = white or transparent) as a
/// DeviceGray image, painted into a luminosity mask.
#[derive(Clone, Hash)]
@@ -1621,6 +1661,12 @@ impl CoverageImage {
let grey = rgba.pixels().map(|p| ((u16::from(255 - p[0]) * u16::from(p[3]) + 127) / 255) as u8).collect();
Some(Self { grey: Arc::new(grey), size })
}
+
+ /// Coverage given directly, one byte per pixel; `None` when the size doesn't match.
+ fn from_grey(grey: Arc<Vec<u8>>, size: (u32, u32)) -> Option<Self> {
+ let n = usize::try_from(u64::from(size.0) * u64::from(size.1)).ok()?;
+ (n > 0 && grey.len() == n).then_some(Self { grey, size })
+ }
}
impl krilla::image::CustomImage for CoverageImage {
@@ -1696,7 +1742,7 @@ struct RasterMode {
impl RasterMode {
fn for_standard(standard: Standard) -> Self {
- Self { interpolate: standard == Standard::None, tag_rgb: standard == Standard::PdfX4 }
+ Self { interpolate: standard == Standard::None, tag_rgb: standard.is_pdfx() }
}
}
diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs
index 26dd69e25..4ba3e6846 100644
--- a/crates/pdf/src/lib.rs
+++ b/crates/pdf/src/lib.rs
@@ -28,7 +28,9 @@
//! right characters), so text is selectable and searchable.
//! - **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. `designcraft-cli validate-pdf` exposes those checks for CI.
+//! 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.
//!
//! 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)]
@@ -42,11 +44,13 @@ mod text;
mod forms;
mod pdfx;
+mod pdfx1a;
mod transitions;
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 transitions::{add_blend_space, add_catalog_entries, add_page_entries, add_transitions};
/// PDF standard to target.
@@ -57,21 +61,30 @@ pub enum Standard {
None,
/// PDF/X-4 (PDF 1.6, trim/bleed boxes, output intent and identification).
PdfX4,
+ /// PDF/X-1a:2003 (PDF 1.4, CMYK and spot only, no transparency): the PDF/X-4 file flattened.
+ PdfX1a,
/// PDF/A-2b (archival; validated by krilla).
PdfA2b,
}
impl Standard {
- /// `none`, `x4` / `pdfx4` / `PDF/X-4`, `a2b` / `pdfa2b` / `PDF/A-2b`.
+ /// `none`, `x4` / `pdfx4` / `PDF/X-4`, `x1a` / `pdfx1a` / `PDF/X-1a:2003`, `a2b` / `pdfa2b` /
+ /// `PDF/A-2b`.
pub fn parse(s: &str) -> Option<Self> {
let k: String = s.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_ascii_lowercase();
match k.as_str() {
"" | "none" => Some(Self::None),
"x4" | "pdfx4" | "pdfx42008" | "pdfx42010" => Some(Self::PdfX4),
+ "x1a" | "pdfx1a" | "pdfx1a2003" => Some(Self::PdfX1a),
"a2b" | "pdfa2b" => Some(Self::PdfA2b),
_ => None,
}
}
+
+ /// PDF/X: a CMYK output intent, trim boxes, no interpolation.
+ pub fn is_pdfx(self) -> bool {
+ matches!(self, Self::PdfX4 | Self::PdfX1a)
+ }
}
/// Printer's marks (Export PDF › Marks and Bleeds).
@@ -128,6 +141,22 @@ pub struct PdfOptions {
pub tagged: bool,
/// Interactive PDF: placed video and sound are embedded and play in Screen annotations.
pub media: bool,
+ /// PDF/X-1a: the resolution (pixels per inch) craft-prepress's flattener rasterizes complex
+ /// transparent regions at.
+ pub flatten_dpi: f32,
+ /// Soft drop shadows drawn as their shadow color through a coverage mask, by item id (spread
+ /// items only). Items without one draw the simple offset silhouette.
+ pub shadows: std::sync::Arc<std::collections::HashMap<designcraft_doc::ItemId, ShadowMask>>,
+}
+
+/// A soft drop shadow's coverage over `rect` (spread coordinates): `width` × `height` greys,
+/// 255 = the shadow color at full strength. Its opacity is in the coverage.
+#[derive(Clone, Debug, PartialEq)]
+pub struct ShadowMask {
+ pub rect: designcraft_geom::Rect,
+ pub width: u32,
+ pub height: u32,
+ pub coverage: std::sync::Arc<Vec<u8>>,
}
impl Default for PdfOptions {
@@ -145,6 +174,8 @@ impl Default for PdfOptions {
created: None,
tagged: false,
media: false,
+ flatten_dpi: 300.0,
+ shadows: Default::default(),
}
}
}
@@ -220,6 +251,8 @@ mod print_tests;
mod rtl_tests;
#[cfg(test)]
mod tests;
+#[cfg(test)]
+mod x1a_tests;
// Run the same public API/output contracts with the unit-only colliding cache hasher as well
// as the production RandomState used by the integration-test executable.
diff --git a/crates/pdf/src/pdfx.rs b/crates/pdf/src/pdfx.rs
index c37cfbd26..1a86e5eba 100644
--- a/crates/pdf/src/pdfx.rs
+++ b/crates/pdf/src/pdfx.rs
@@ -194,7 +194,7 @@ fn device_rgb(pdf: &[u8]) -> Vec<String> {
}
/// Whether the file's PDF/X output intent has a four-channel (CMYK) destination profile.
-fn cmyk_output_intent(file: &hayro_syntax::Pdf) -> bool {
+pub(crate) fn cmyk_output_intent(file: &hayro_syntax::Pdf) -> bool {
let xref = file.xref();
let Some(catalog) = xref.get::<Dict<'_>>(xref.root_id()) else { return false };
let Some(intents) = catalog.get::<Array<'_>>(b"OutputIntents") else { return false };
@@ -224,7 +224,7 @@ fn is_device_rgb(cs: &Object<'_>) -> bool {
}
/// How deep forms, patterns and soft masks may nest before the walk stops.
-const MAX_DEPTH: usize = 16;
+pub(crate) const MAX_DEPTH: usize = 16;
/// What one page uses in device RGB, in the order found.
#[derive(Default)]
diff --git a/crates/pdf/src/pdfx1a.rs b/crates/pdf/src/pdfx1a.rs
new file mode 100644
index 000000000..5abde66f1
--- /dev/null
+++ b/crates/pdf/src/pdfx1a.rs
@@ -0,0 +1,467 @@
+//! 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.
+
+use std::collections::HashSet;
+
+use craft_prepress::flatten::pdf::ReadOptions;
+use craft_prepress::flatten::{FlattenDocumentOptions, FlattenOptions, 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::transitions::{find, int_after, object, rfind};
+
+/// `GTS_PDFXVersion` of PDF/X-1a:2003.
+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>> {
+ 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(),
+ ..FlattenDocumentOptions::default()
+ };
+ let (flat, 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 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;
+ }
+ }
+ 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)
+}
+
+/// 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.
+pub fn check_pdfx1a(pdf: &[u8]) -> Vec<String> {
+ let (mut issues, other) = checks(pdf);
+ issues.extend(other);
+ issues
+}
+
+/// [`check_pdfx1a`]'s findings: transparency and color spaces first, then the rest.
+fn checks(pdf: &[u8]) -> (Vec<String>, Vec<String>) {
+ let mut issues = Vec::new();
+ let text = String::from_utf8_lossy(pdf);
+ if !pdf.starts_with(b"%PDF-1.") || pdf.get(7).is_none_or(|v| *v > b'4') {
+ issues.push("the PDF version must be 1.4 or lower".into());
+ }
+ if !text.contains("/S/GTS_PDFX") {
+ issues.push("no PDF/X output intent".into());
+ }
+ 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());
+ }
+ if text.contains("/Interpolate true") {
+ issues.push("an image asks for interpolation".into());
+ }
+ if text.contains("/Encrypt") {
+ issues.push("the file is encrypted".into());
+ }
+ let pages = text.matches("/Type/Page/").count() + text.matches("/Type/Page>").count();
+ let trims = text.matches("/TrimBox").count();
+ if pages > 0 && trims < pages {
+ issues.push("every page needs a trim box".into());
+ }
+ let (content, fonts) = content(pdf);
+ issues.extend(fonts);
+ (content, issues)
+}
+
+/// Transparency and color spaces, then 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 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() {
+ let mut scan = Scan::default();
+ let res = page.resources();
+ if let Some(group) = page.raw().get::<Dict<'_>>(b"Group") {
+ scan.group(&group);
+ }
+ if let Some(content) = page.page_stream() {
+ scan.content(content, res, 0);
+ }
+ for (list, items) in [(&mut found, scan.found), (&mut font_found, scan.font_issues)] {
+ for what in items {
+ match list.iter_mut().find(|(w, _)| *w == what) {
+ Some((_, pages)) => pages.push(i + 1),
+ None => list.push((what, vec![i + 1])),
+ }
+ }
+ }
+ }
+ let on_pages = |(what, pages): (String, Vec<usize>)| {
+ let list: Vec<String> = pages.iter().take(10).map(|p| p.to_string()).collect();
+ let more = if pages.len() > 10 { ", …" } else { "" };
+ let s = if pages.len() == 1 { "" } else { "s" };
+ format!("{what} on page{s} {}{more}", list.join(", "))
+ };
+ fonts.extend(font_found.into_iter().map(on_pages));
+ (found.into_iter().map(on_pages).collect(), fonts)
+}
+
+/// 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 {
+ return Some("a color space nested too deeply".into());
+ }
+ match cs {
+ Object::Name(n) => match n.as_ref() {
+ b"DeviceCMYK" | b"CMYK" | b"DeviceGray" | b"G" | b"Pattern" => None,
+ b"DeviceRGB" | b"RGB" => Some("DeviceRGB color".into()),
+ b"Indexed" | b"I" => None,
+ other => match res.get_color_space(&Name::new_unescaped(other)) {
+ Some(named) if !matches!(named, Object::Name(_)) => disallowed(&named, res, depth + 1),
+ Some(Object::Name(m)) if m.as_ref() != other => disallowed(&Object::Name(m), res, depth + 1),
+ _ => Some(format!("the color space /{}", String::from_utf8_lossy(other))),
+ },
+ },
+ Object::Array(a) => {
+ let mut items = a.iter::<Object<'_>>();
+ let family = match items.next() {
+ Some(Object::Name(n)) => n,
+ _ => return Some("an unreadable color space".into()),
+ };
+ match family.as_ref() {
+ b"ICCBased" => Some("ICC-based color".into()),
+ b"CalRGB" | b"CalGray" => Some("CIE-based (CalRGB/CalGray) color".into()),
+ b"Lab" => Some("Lab color".into()),
+ b"DeviceRGB" | b"RGB" => Some("DeviceRGB color".into()),
+ b"DeviceCMYK" | b"CMYK" | b"DeviceGray" | b"G" => None,
+ b"Indexed" | b"I" => items.next().and_then(|base| disallowed(&base, res, depth + 1)),
+ b"Pattern" => items.next().and_then(|base| disallowed(&base, res, depth + 1)),
+ 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}"))
+ }
+ other => Some(format!("the color space /{}", String::from_utf8_lossy(other))),
+ }
+ }
+ _ => Some("an unreadable color space".into()),
+ }
+}
+
+/// What one page has that PDF/X-1a doesn't allow, in the order found.
+#[derive(Default)]
+struct Scan {
+ found: Vec<String>,
+ font_issues: Vec<String>,
+ seen: HashSet<ObjectIdentifier>,
+ fonts: HashSet<ObjectIdentifier>,
+}
+
+impl Scan {
+ fn add(&mut self, what: String) {
+ if !self.found.contains(&what) {
+ self.found.push(what);
+ }
+ }
+
+ fn space(&mut self, cs: &Object<'_>, res: &Resources<'_>) {
+ if let Some(why) = disallowed(cs, res, 0) {
+ self.add(why);
+ }
+ }
+
+ fn content(&mut self, data: &[u8], res: &Resources<'_>, depth: usize) {
+ if depth > MAX_DEPTH {
+ return;
+ }
+ let mut ops = UntypedIter::new(data);
+ while let Some(op) = ops.next() {
+ let operator: &[u8] = op.operator;
+ let last = op.operands().last().cloned();
+ let name = || last.clone().and_then(Object::into_name);
+ match operator {
+ b"rg" | b"RG" => self.add("DeviceRGB color".into()),
+ b"cs" | b"CS" => {
+ if let Some(n) = name() {
+ self.space(&Object::Name(n), res);
+ }
+ }
+ b"sh" => {
+ if let Some(sh) = name().and_then(|n| res.get_shading(&n)) {
+ self.shading(sh, res);
+ }
+ }
+ b"scn" | b"SCN" => {
+ if let Some(p) = name().and_then(|n| res.get_pattern(&n)) {
+ self.pattern(p, res, depth);
+ }
+ }
+ b"gs" => {
+ if let Some(gs) = name().and_then(|n| res.get_ext_g_state(&n)) {
+ self.ext_g_state(&gs, res, depth);
+ }
+ }
+ 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);
+ }
+ }
+ b"Do" => {
+ if let Some(xo) = name().and_then(|n| res.get_x_object(&n)) {
+ match xo.dict().get::<Name<'_>>(b"Subtype").as_deref() {
+ Some(b"Image") => self.image(&xo, res),
+ Some(b"Form") => self.form(&xo, res, depth),
+ _ => {}
+ }
+ }
+ }
+ b"BI" | b"EI" => {
+ if let Some(Object::Stream(img)) = last
+ && let Some(cs) = img.dict().get::<Object<'_>>(b"CS").or_else(|| img.dict().get::<Object<'_>>(b"ColorSpace"))
+ {
+ self.space(&cs, res);
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+
+ fn ext_g_state(&mut self, gs: &Dict<'_>, res: &Resources<'_>, depth: usize) {
+ match gs.get::<Object<'_>>(b"SMask") {
+ None => {}
+ Some(Object::Name(n)) if n.as_ref() == b"None" => {}
+ Some(mask) => {
+ self.add("a soft mask (transparency)".into());
+ if let Some(form) = match mask {
+ Object::Dict(d) => d.get::<Stream<'_>>(b"G"),
+ _ => None,
+ } {
+ self.form(&form, res, depth);
+ }
+ }
+ }
+ for key in [&b"CA"[..], b"ca"] {
+ if gs.get::<f32>(key).is_some_and(|a| a < 1.0) {
+ self.add("constant opacity below 100% (transparency)".into());
+ }
+ }
+ let normal = |n: &[u8]| matches!(n, b"Normal" | b"Compatible");
+ match gs.get::<Object<'_>>(b"BM") {
+ Some(Object::Name(n)) if !normal(n.as_ref()) => {
+ self.add(format!("the blend mode /{} (transparency)", String::from_utf8_lossy(n.as_ref())))
+ }
+ Some(Object::Array(a)) if a.iter::<Name<'_>>().any(|n| !normal(n.as_ref())) => {
+ self.add("a blend mode other than Normal (transparency)".into())
+ }
+ _ => {}
+ }
+ }
+
+ fn image(&mut self, img: &Stream<'_>, res: &Resources<'_>) {
+ if !self.seen.insert(img.obj_id()) {
+ return;
+ }
+ let d = img.dict();
+ if d.get::<Object<'_>>(b"SMask").is_some() {
+ self.add(format!("an image with a soft mask (object {}, transparency)", img.obj_id().obj_number));
+ }
+ if d.get::<i32>(b"SMaskInData").is_some_and(|v| v != 0) {
+ self.add(format!("an image with transparency in its data (object {})", img.obj_id().obj_number));
+ }
+ if d.get::<bool>(b"ImageMask") == Some(true) {
+ return;
+ }
+ match d.get::<Object<'_>>(b"ColorSpace") {
+ Some(cs) => {
+ if let Some(why) = disallowed(&cs, res, 0) {
+ let (w, h) = (d.get::<i32>(b"Width").unwrap_or(0), d.get::<i32>(b"Height").unwrap_or(0));
+ self.add(format!("{why} in an image (object {}, {w} × {h} px)", img.obj_id().obj_number));
+ }
+ }
+ // JPX images may carry their own space; X-1a doesn't allow them.
+ None => self.add(format!("an image without a color space (object {})", img.obj_id().obj_number)),
+ }
+ }
+
+ fn form(&mut self, form: &Stream<'_>, parent: &Resources<'_>, depth: usize) {
+ if depth >= MAX_DEPTH || !self.seen.insert(form.obj_id()) {
+ return;
+ }
+ let res = Resources::from_parent(form.dict().get::<Dict<'_>>(b"Resources").unwrap_or_default(), parent.clone());
+ if let Some(group) = form.dict().get::<Dict<'_>>(b"Group") {
+ self.group(&group);
+ }
+ if let Ok(data) = form.decoded() {
+ self.content(&data, &res, depth + 1);
+ }
+ }
+
+ fn group(&mut self, group: &Dict<'_>) {
+ if group.get::<Name<'_>>(b"S").is_some_and(|s| s.as_ref() == b"Transparency") {
+ self.add("a transparency group".into());
+ }
+ }
+
+ fn shading(&mut self, sh: Object<'_>, res: &Resources<'_>) {
+ let dict = match sh {
+ Object::Dict(d) => d,
+ Object::Stream(s) => s.dict().clone(),
+ _ => return,
+ };
+ if let Some(cs) = dict.get::<Object<'_>>(b"ColorSpace") {
+ self.space(&cs, res);
+ }
+ }
+
+ fn pattern(&mut self, p: Object<'_>, res: &Resources<'_>, depth: usize) {
+ match p {
+ Object::Dict(d) => {
+ if let Some(sh) = d.get::<Object<'_>>(b"Shading") {
+ self.shading(sh, res);
+ }
+ if let Some(gs) = d.get::<Dict<'_>>(b"ExtGState") {
+ self.ext_g_state(&gs, res, depth);
+ }
+ }
+ Object::Stream(s) => self.form(&s, res, depth),
+ _ => {}
+ }
+ }
+
+ /// 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<'_>) {
+ if let Some(id) = font.obj_id()
+ && !self.fonts.insert(id)
+ {
+ return;
+ }
+ 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"Type0") => {
+ font.get::<Array<'_>>(b"DescendantFonts").and_then(|a| a.iter::<Dict<'_>>().next()).and_then(|d| d.get::<Dict<'_>>(b"FontDescriptor"))
+ }
+ _ => font.get::<Dict<'_>>(b"FontDescriptor"),
+ };
+ let embedded = descriptor.is_some_and(|d| [&b"FontFile"[..], b"FontFile2", b"FontFile3"].iter().any(|k| d.get::<Stream<'_>>(k).is_some()));
+ if !embedded {
+ self.font_issues.push(format!("the font {name} isn't embedded"));
+ }
+ }
+}
diff --git a/crates/pdf/src/x1a_tests.rs b/crates/pdf/src/x1a_tests.rs
new file mode 100644
index 000000000..0f6490388
--- /dev/null
+++ b/crates/pdf/src/x1a_tests.rs
@@ -0,0 +1,200 @@
+//! PDF/X-1a export, read back from the exported PDF: no transparency left, only process and spot
+//! color, overprint and live text kept, the identification; and the checks refusing what X-1a
+//! doesn't allow.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use designcraft_color::{Color, ColorType, Swatch, SwatchValue};
+use designcraft_compose::Cache;
+use designcraft_doc::build::NewDocument;
+use designcraft_doc::{Content, Document, Fill, Item, ItemId, ParaFormat, SpreadRef};
+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};
+
+fn add(d: &mut Document, r: Rect, swatch: &str, edit: impl FnOnce(&mut Item)) -> ItemId {
+ let lid = d.default_layer();
+ let id = ItemId(d.alloc());
+ let mut b = Item::new(id, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(r));
+ b.fill = Fill::swatch(swatch);
+ edit(&mut b);
+ d.insert_item(SpreadRef::Doc(0), b, None).unwrap();
+ id
+}
+
+/// A spot Gold background with, over it: a box with a soft drop shadow, a 50% cyan box, a
+/// knockout group of two 50% boxes, a magenta box that overprints, and a text frame.
+fn transparent_doc() -> (Document, PdfOptions) {
+ let mut d = Document::new(&NewDocument::default());
+ let gold = Color::cmyk(0.0, 0.3, 0.9, 0.1);
+ d.swatches.push(Swatch { value: SwatchValue::Color { color: gold, color_type: ColorType::Spot }, ..Swatch::color("Gold", gold) });
+ add(&mut d, Rect::new(0.0, 0.0, 612.0, 792.0), "Gold", |_| {});
+ let shadowed = add(&mut d, Rect::new(72.0, 72.0, 172.0, 172.0), "C=0 M=100 Y=0 K=0", |b| {
+ b.effects.drop_shadow.on = true;
+ b.effects.drop_shadow.opacity = 1.0;
+ });
+ add(&mut d, Rect::new(300.0, 72.0, 400.0, 172.0), "C=100 M=0 Y=0 K=0", |b| b.opacity = 0.5);
+ let lid = d.default_layer();
+ let child = |d: &mut Document, r: Rect, swatch: &str| {
+ let mut b = Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(r));
+ b.fill = Fill::swatch(swatch);
+ b.opacity = 0.5;
+ Arc::new(b)
+ };
+ let items = vec![
+ child(&mut d, Rect::new(72.0, 300.0, 172.0, 400.0), "C=100 M=0 Y=0 K=0"),
+ child(&mut d, Rect::new(122.0, 350.0, 222.0, 450.0), "C=0 M=0 Y=100 K=0"),
+ ];
+ let mut g =
+ Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Group, designcraft_geom::shapes::rectangle(Rect::new(72.0, 300.0, 222.0, 450.0)));
+ g.content = Content::Group { items };
+ g.knockout = true;
+ d.insert_item(SpreadRef::Doc(0), g, None).unwrap();
+ add(&mut d, Rect::new(300.0, 300.0, 400.0, 400.0), "C=0 M=100 Y=0 K=0", |b| b.fill.overprint = true);
+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 500.0, 400.0, 600.0), lid, "Live text", ParaFormat::default()).unwrap();
+ // The shadow's coverage: a ramp from 0 to full strength, offset from the box.
+ let (w, h) = (64u32, 64u32);
+ let coverage: Vec<u8> = (0..h).flat_map(|_| (0..w).map(move |x| (x * 255 / (w - 1)) as u8)).collect();
+ let mask = ShadowMask { rect: Rect::new(77.0, 77.0, 182.0, 182.0), width: w, height: h, coverage: Arc::new(coverage) };
+ let opts =
+ PdfOptions { standard: Standard::PdfX1a, flatten_dpi: 72.0, shadows: Arc::new(HashMap::from([(shadowed, mask)])), ..PdfOptions::default() };
+ (d, opts)
+}
+
+/// Every color space family named in the file's resources, images and shadings.
+fn families(bytes: &[u8]) -> Vec<String> {
+ let pdf = Pdf::new(bytes.to_vec()).unwrap();
+ let mut out = Vec::new();
+ let mut add = |o: Option<Object<'_>>| {
+ let name = match o {
+ Some(Object::Name(n)) => Some(n.as_str().to_string()),
+ Some(Object::Array(a)) => a.iter::<Name<'_>>().next().map(|n| n.as_str().to_string()),
+ _ => None,
+ };
+ if let Some(n) = name
+ && !out.contains(&n)
+ {
+ out.push(n);
+ }
+ };
+ for o in pdf.objects() {
+ let dict: Option<Dict<'_>> = match o {
+ Object::Dict(d) => Some(d),
+ Object::Stream(s) => Some(s.dict().clone()),
+ _ => None,
+ };
+ let Some(dict) = dict else { continue };
+ add(dict.get::<Object<'_>>(b"ColorSpace").filter(|o| !matches!(o, Object::Dict(_))));
+ if let Some(spaces) = dict.get::<Dict<'_>>(b"ColorSpace") {
+ for key in spaces.keys() {
+ add(spaces.get::<Object<'_>>(key.as_ref()));
+ }
+ }
+ }
+ out
+}
+
+/// A drop shadow over a spot, a 50% object and a knockout group come out with no transparency,
+/// only process and spot color, the output intent and the PDF/X-1a identification; overprint
+/// and live text survive.
+#[test]
+fn x1a_export_flattens_transparency_into_inks() {
+ let (d, opts) = transparent_doc();
+ let r = export_pdf_with_report(&d, &Cache::new(), &opts).unwrap();
+ 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());
+ assert!(text.contains("/GTS_PDFXVersion(PDF/X-1:2003)"));
+ assert!(text.contains("/GTS_PDFXConformance(PDF/X-1a:2003)"));
+ 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}");
+ }
+ assert!(text.contains("/Gold"), "the spot ink stays a spot");
+ 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()
+ .filter_map(|o| match o {
+ Object::Dict(d) => Some((d.get::<bool>(b"op")?, d.get::<bool>(b"OP")?, d.get::<i32>(b"OPM")?)),
+ _ => None,
+ })
+ .collect();
+ assert!(states.iter().any(|(op, _, opm)| *op && *opm == 1), "overprint survives: {states:?}");
+ 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.
+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(),
+ ];
+ 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());
+ }
+ let xref = out.len();
+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f\r\n", objects.len() + 1).as_bytes());
+ for off in offsets {
+ out.extend_from_slice(format!("{off:010} 00000 n\r\n").as_bytes());
+ }
+ out.extend_from_slice(format!("trailer\n<</Size {}/Root 1 0 R/Info 6 0 R>>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
+ out
+}
+
+/// The X-1a checks refuse soft masks, constant opacity, blend modes, transparency groups, RGB
+/// and ICC-based color; process and spot color pass.
+#[test]
+fn x1a_checks_refuse_transparency_and_rgb() {
+ let clean = check_pdfx1a(&tiny_x1a(
+ "/Resources<</ColorSpace<</Gold[/Separation/Gold/DeviceCMYK 7 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());
+ let has = |entries: &str, content: &str, what: &str| {
+ let issues = check_pdfx1a(&tiny_x1a(entries, content));
+ assert!(issues.iter().any(|i| i.contains(what)), "{what}: {issues:?}");
+ };
+ has("/Resources<<>>", "1 0 0 rg 0 0 10 10 re f", "DeviceRGB");
+ has("/Resources<</ColorSpace<</CS0[/ICCBased 4 0 R]>>>>", "/CS0 cs 0 0 0 1 scn 0 0 10 10 re f", "ICC-based");
+ has("/Resources<</ExtGState<</G0<</SMask<</S/Luminosity/G 5 0 R>>>>>>>>", "/G0 gs 0 0 0 1 k 0 0 10 10 re f", "soft mask");
+ 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<<>>", "q BI /W 1 /H 1 /CS /RGB /BPC 8 /F /AHx ID ff0000> EI Q", "DeviceRGB");
+ // A PDF/X-4 file isn't X-1a.
+ let x4 = export_pdf_with_report(
+ &Document::new(&NewDocument::default()),
+ &Cache::new(),
+ &PdfOptions { standard: Standard::PdfX4, ..Default::default() },
+ )
+ .unwrap();
+ let issues = check_pdfx1a(&x4.bytes);
+ assert!(issues.iter().any(|i| i.contains("1.4")) && issues.iter().any(|i| i.contains("PDF/X-1:2003")), "{issues:?}");
+}
+
+#[test]
+fn x1a_parses() {
+ for s in ["x1a", "PDF/X-1a", "PDF/X-1a:2003", "pdfx1a"] {
+ assert_eq!(Standard::parse(s), Some(Standard::PdfX1a), "{s}");
+ }
+}
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 8b4043787..5e6886d71 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -397,15 +397,17 @@ fn print_dialog(app: &crate::DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
/// The presets offered by the Export PDF dialog, in display order. The stored value is the
/// English name; the caption is translated.
-const PDF_EXPORT_PRESETS: &[&str] = &["Desktop Printing", "Commercial Printing", "Screen and Email", "PDF/X-4", "PDF/A-2b", "Custom"];
+const PDF_EXPORT_PRESETS: &[&str] =
+ &["Desktop Printing", "Commercial Printing", "Screen and Email", "PDF/X-1a:2003", "PDF/X-4", "PDF/A-2b", "Custom"];
-/// Apply a preset's dependent fields. Flatten is only touched by "Screen and Email"; "Custom"
-/// (and any unknown value) changes nothing.
+/// Apply a preset's dependent fields. Flatten is only touched by "Screen and Email" and
+/// "PDF/X-1a:2003" (High Resolution); "Custom" (and any unknown value) changes nothing.
fn apply_pdf_preset(d: &mut Dialog, preset: &str) {
let (standard, compress, crop, bleed, page_info, flatten) = match preset {
"Desktop Printing" => ("none", false, false, false, false, None),
"Commercial Printing" => ("none", true, true, true, false, None),
"Screen and Email" => ("none", true, false, false, false, Some("low")),
+ "PDF/X-1a:2003" => ("x1a", false, true, true, false, Some("high")),
"PDF/X-4" => ("x4", false, true, true, false, None),
"PDF/A-2b" => ("a2b", false, false, false, false, None),
_ => return,
@@ -478,7 +480,20 @@ fn pdf_export(app: &crate::DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
head(ui, "Advanced");
ui.horizontal(|ui| {
crate::rtl::label(ui, crate::i18n::tr(lang, "Standard:"));
- translated_combo(lang, ui, d, "standard", &[("none", "None"), ("x4", "PDF/X-4"), ("a2b", "PDF/A-2b")]);
+ translated_combo(lang, ui, d, "standard", &[("none", "None"), ("x1a", "PDF/X-1a:2003"), ("x4", "PDF/X-4"), ("a2b", "PDF/A-2b")]);
+ });
+ // Spreads with transparency are rasterized at the preset's resolution; in PDF/X-1a it is the
+ // resolution craft-prepress rasterizes complex transparent regions at.
+ head(ui, "Transparency Flattener");
+ ui.horizontal(|ui| {
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Preset:"));
+ translated_combo(
+ lang,
+ ui,
+ d,
+ "flatten",
+ &[("", "None"), ("high", "High Resolution"), ("medium", "Medium Resolution"), ("low", "Low Resolution")],
+ );
});
check(ui, d, "tagged", crate::i18n::tr(lang, "Tagged PDF"));
@@ -9416,6 +9431,17 @@ mod tests {
assert_eq!(d.s("flatten"), "low");
}
+ /// The PDF/X-1a preset exports X-1a with the High Resolution flattener and printer's marks.
+ #[test]
+ fn pdf_export_preset_pdf_x1a_flattens_at_high_resolution() {
+ let mut d = Dialog::new("pdfExport", json!({}));
+ apply_pdf_preset(&mut d, "PDF/X-1a:2003");
+ assert_eq!(d.s("standard"), "x1a");
+ assert_eq!(d.s("flatten"), "high");
+ assert!(d.b("marksCrop") && d.b("marksBleed"));
+ assert!(PDF_EXPORT_PRESETS.contains(&"PDF/X-1a:2003"));
+ }
+
#[test]
fn pdf_export_preset_pdf_x4_keeps_flatten() {
let mut d = Dialog::new("pdfExport", json!({}));
diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs
index efe089ef9..b5e9d89ad 100644
--- a/crates/ui-egui/src/i18n.rs
+++ b/crates/ui-egui/src/i18n.rs
@@ -284,6 +284,10 @@ const TABLE: &[(&str, [&str; 5])] = &[
("Settings for:", ["Einstellungen für:", "Paramètres pour :", "Ajustes para:", "設定対象:", "设置:"]),
("Transparency", ["Transparenz", "Transparence", "Transparencia", "透明", "透明度"]),
("Transparency…", ["Transparenz…", "Transparence…", "Transparencia…", "透明…", "透明度…"]),
+ (
+ "Transparency Flattener",
+ ["Transparenzreduzierung", "Aplatissement de la transparence", "Acoplador de transparencia", "透明の分割・統合", "透明度拼合"],
+ ),
("Basic Blending", ["Grundlegendes Füllen", "Fusion de base", "Fusión básica", "基本的な描画モード", "基本混合"]),
("Opacity:", ["Deckkraft:", "Opacité :", "Opacidad:", "不透明度:", "不透明度:"]),
("Blending", ["Füllmethode", "Fusion", "Fusión", "描画モード", "混合"]),
@@ -1124,6 +1128,7 @@ const TABLE: &[(&str, [&str; 5])] = &[
),
("Paragraph Style:", ["Paragraph Style:", "Style de paragraphe :", "Paragraph Style:", "Paragraph Style:", "段落样式:"]),
("PDF/A-2b", ["PDF/A-2b", "PDF/A-2b", "PDF/A-2b", "PDF/A-2b", "PDF/A-2b"]),
+ ("PDF/X-1a:2003", ["PDF/X-1a:2003", "PDF/X-1a:2003", "PDF/X-1a:2003", "PDF/X-1a:2003", "PDF/X-1a:2003"]),
("PDF/X-4", ["PDF/X-4", "PDF/X-4", "PDF/X-4", "PDF/X-4", "PDF/X-4"]),
("Place PDF", ["Place PDF", "Importer un PDF", "Place PDF", "Place PDF", "置入PDF"]),
("Plain Text", ["Plain Text", "Texte brut", "Plain Text", "Plain Text", "纯文本"]),
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index cb98cac7f..7d1a915a0 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -145,7 +145,7 @@ fn default_zone() -> f64 {
pub struct PdfExportSettings {
/// Preset (one of the five presets, or "Custom" after a manual edit).
pub preset: String,
- /// PDF standard (`none`, `x4`, `a2b`).
+ /// PDF standard (`none`, `x1a`, `x4`, `a2b`).
pub standard: String,
/// Compression › Compress images (JPEG).
pub compress_images: bool,