Skip to content

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

Merge print-color into print-color-x1a

aiongg074db000795c
diff --cc Cargo.lock
index da8c59928,3f39c5918..737b3e022
--- a/Cargo.lock
+++ b/Cargo.lock
@@@ -862,19 -981,6 +984,19 @@@ dependencies =
"thiserror 2.0.21",
]
+[[package]]
+name = "craft-prepress"
+version = "0.1.0"
- source = "git+https://github.com/aiongg/craft-libs?rev=d30598dcb4b389561c485b97d4a97a0c86bc36e4#d30598dcb4b389561c485b97d4a97a0c86bc36e4"
++source = "git+https://github.com/storytold/craft-libs?rev=e3b9e239c52c14677be462e94d8920ea243de4f3#e3b9e239c52c14677be462e94d8920ea243de4f3"
+dependencies = [
- "craft-cms 0.1.0 (git+https://github.com/aiongg/craft-libs?rev=d30598dcb4b389561c485b97d4a97a0c86bc36e4)",
++ "craft-cms",
+ "craft-pdf",
+ "kurbo",
+ "linesweeper",
+ "thiserror 2.0.21",
+ "ttf-parser",
+]
+
[[package]]
name = "craft-print"
version = "0.1.0"
@@@ -1179,12 -1362,11 +1378,12 @@@ dependencies =
[[package]]
name = "designcraft-pdf"
- version = "0.12.0"
+ version = "0.13.0"
dependencies = [
"chrono",
- "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e9546e191dd62f2bc1d61eca45dbdc2f1b3c1d8e)",
+ "craft-cms",
"craft-pdf",
+ "craft-prepress",
"designcraft-color",
"designcraft-compose",
"designcraft-doc",
diff --cc Cargo.toml
index 3c8b1e6ed,324c022b4..c4cd90c74
--- a/Cargo.toml
+++ b/Cargo.toml
@@@ -12,9 -12,9 +12,9 @@@ repository = "https://github.com/storyt
[workspace.dependencies]
# Shared reader and writer; publish the immutable revision before this consumer.
- craft-pdf = { git = "https://github.com/aiongg/craft-libs", rev = "d30598dcb4b389561c485b97d4a97a0c86bc36e4", version = "=0.1.0", default-features = false }
+ craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "e3b9e239c52c14677be462e94d8920ea243de4f3", version = "=0.1.0", default-features = false }
# Separations, ink coverage and the ink manager; same revision as craft-pdf and the krilla patch.
- craft-prepress = { git = "https://github.com/aiongg/craft-libs", rev = "d30598dcb4b389561c485b97d4a97a0c86bc36e4", version = "=0.1.0", features = ["flatten"] }
-craft-prepress = { git = "https://github.com/storytold/craft-libs", rev = "e3b9e239c52c14677be462e94d8920ea243de4f3", version = "=0.1.0" }
++craft-prepress = { git = "https://github.com/storytold/craft-libs", rev = "e3b9e239c52c14677be462e94d8920ea243de4f3", version = "=0.1.0", features = ["flatten"] }
# internal
designcraft-geom = { path = "crates/geom" }
designcraft-color = { path = "crates/color" }
diff --cc ROADMAP.md
index 5dbc9326a,d40ddff0d..68f23b064
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -348,12 -381,45 +381,46 @@@ list) · [roadmap.md](docs/roadmap.md)
Newest first.
+- **2026-10-20** · PDF/X-1a:2003 export (craft-libs#194): `file.exportPdf {standard: "x1a"}`, the Export PDF dialog's PDF/X-1a:2003 preset and standard. The PDF/X-4 print file is flattened in its inks by craft-prepress (no transparency; spot, process, overprint and live text kept; complex regions as DeviceN images at the Transparency Flattener preset's resolution), then written as PDF 1.4 with the X-1a identification and checked; `validate-pdf --standard x1a`. Soft drop shadows reach the flattener in their swatch's inks; other soft effects are still RGB images. No readiness percentage change.
- **2026-10-20** · Print color (craft-libs#190): CMYK print PDFs blend in DeviceCMYK through craft-pdf's print settings instead of byte rewrites, with the CMYK working space as the output intent in PDF/X-4 only; overprint (Overprint Fill, Stroke and Gap, overprinting text, 100% [Black]) is written as `/op` `/OP` `/OPM 1`; Knockout Group writes `/K true` instead of becoming an image; File › Print prints the PDF Export PDF writes. No readiness percentage change.
- **2026-10-20** · Spot gradients print on their plates. A gradient stop keeps the swatch it was given (Gradient panel drop, `swatch.create {gradient}`, `object.gradient`, IDML `StopColor`), following its renames and edits. PDF export shades one spot with its tints or [Paper] as a Separation, and a spot with process inks or a second spot as DeviceN; a process gradient to [Paper] prints in DeviceCMYK. Documents with plain-color stops export as before. No readiness percentage change.
+ - **2026-10-24** · Panels dock through the suite's shared docking (craft-libs), and on desktop a floating panel opens in its own window that can leave the main window: keys pressed there run the main window's shortcuts, clipboard and tool keys, and the canvas paints no tool cursor while another of the app's windows has the pointer. The web build keeps floating panels in the page. No readiness percentage change.
+ - **2026-10-24** · Story Options rejects malformed or nonexistent explicit story/frame IDs without changing the selected story, including an invalid frame alongside a valid story. Null targets remain absent; omitted targets still use the selection. No readiness percentage change.
+ - **2026-10-24** · Text Frame Options explains that a custom baseline-grid increment must be a measure greater than zero when zero, a negative value or a non-measure is entered. Validation is unchanged. No readiness percentage change.
+ - **2026-10-24** · Renaming a paragraph or character style, or moving it into a style group, keeps its Export Tagging under the new name, and undo puts it back under the old one. Deleting a tagged style drops its tagging and leaves the replacement style's own tagging as it was. No readiness percentage change.
+ - **2026-10-24** · Quick Apply and the application bar's search leave out the interface commands that failed or reset a setting when chosen there: those that need a workspace, a command and shortcut, a menu item, a panel, a window edge, an app page, a recent file or a swatch they can't give them, a Contextual Task Bar place, and Interface Color Theme, UI Scaling, Reset Shortcuts, the flattener preset, Screen Mode and Zoom To, which without a value switched to the dark theme, set 100%, cleared every custom shortcut or the preset, or went to Normal mode or 100% zoom. Each stays in the menu, panel or dialog that gives it the value. No readiness percentage change.
+ - **2026-10-24** · EPUB Export Options › Split Document, a dialog before File › Export EPUB… saves (`document.epubSplit`, stored with the document): off, a single paragraph style, or based on paragraph style export tags, with Paragraph Style Options › Export Tagging's Split Document flag marking those styles. A reflowable EPUB is one content file unless Split Document is on; the split before each top-level h1 from #791 is gone. A split before a list item or preformatted line no longer leaves an unclosed list or block in a content file. IDML import and export keep the setting and the flag, and Load Styles the flag. No readiness percentage change.
+ - **2026-10-18** · Repeated placed-PDF layer variants are prepared once per asset and hidden-name set, with recovery warnings retained. All-visible named layers keep their original source bytes, including PDFs whose cross-reference tables the reader repairs, in plain, PDF/X-4, booklet and book-merge output. Layer changes that require writing still reject an unusable cross-reference table with a file-named damage error; the first placement error is retained (#906). No readiness percentage change.
+ - **2026-10-18** · Placed PDF optional-content defaults and per-frame overrides survive plain and PDF/X-4 vector export, including repeated placements, booklet output and book merging (#906). Source usage-application arrays are accepted; groups without a catalog configuration stay visible. Missing or unreadable default configurations and unsupported base states use all-ON defaults with a file-named export warning, retaining explicit frame overrides. Readable groups omitted from the catalog list are added with a distinct file-named warning, preserving their default ON/OFF states. Concurrent recovery warnings are combined. Malformed ON data is recoverable when a known ON base and empty OFF list prove it cannot hide artwork; missing display names are generated without changing known visibility when no override needs name matching. Contradictory states, unresolved references and ambiguous name overrides still fail export. Print-usage adjustments and IDML layer overrides remain follow-ups. No readiness percentage change.
+
+ - **2026-10-24** · Optical Margin Alignment and hanging punctuation apply to lines with a tab or a right indent tab, as both composers already measured them: the edge glyphs hang, and tab stops stay where they are. Such a line was set without the hang: a justified line that fit only because its period or closing quote hangs had its word spaces squeezed to make up for it, and text after a right indent tab stopped at the measure instead of hanging. No readiness percentage change.
+ - **2026-10-23** · `designcraft-cli mcp` takes `--automation-read-root` and `--automation-write-root` more than once, as the suite's other apps do (#1552): a path inside any root of its kind passes, and the roots' common parent, `..` or a link out of them and the other kind's roots stay refused. No readiness percentage change.
+ - **2026-10-23** · Layout › Go Back and Go Forward (Cmd+Page Up / Cmd+Page Down, Ctrl on Windows and Linux) retrace the jumps between pages (Go to Page, the page and spread commands, the Pages panel) as InDesign's do, returning to where the view was on each page at the current zoom; a new jump after going back drops the pages ahead, scrolling adds no entry, and pages deleted since are skipped. No readiness percentage change.
+ - **2026-10-24** · Split Note (`note.split {story, id, at}`, the Notes panel's Split Note button): as in InDesign, a note splits in two at the insertion point in its text. DesignCraft moves the text after it into a new note by the same author, anchored right after the first. No readiness percentage change.
+ - **2026-10-24** · Type › Notes › Previous Note and Next Note (`note.previous`, `note.next`): as in InDesign, they move the insertion point from note to note in the story, putting the caret after the note's anchor. Each item is unavailable when no note lies in its direction in the story, or when the insertion point is in a table cell or a footnote. No readiness percentage change.
+ - **2026-10-24** · Type › Notes › Convert to Note (`note.convertFromText {author?}`): as in InDesign, the selected text leaves the story and becomes the text of a new note, whose anchor takes its place; Convert Note to Text puts it back. DesignCraft refuses a selection in a table cell, or one that holds a note, footnote, endnote, anchored object, index marker, text anchor, cross-reference or table. No readiness percentage change.
+ - **2026-10-23** · Effects dialog: with Use Global Light on, the Angle field (and the Bevel and Emboss one) stays editable and shows the document's global light angle; a change there sets the global light for every effect that uses it, applied with the effects in one undo step (`object.effects` takes `globalLight`). Before, the field was greyed out and the angle couldn't be changed in the dialog. No readiness percentage change.
+ - **2026-10-24** · Story panel (Window › Type & Tables › Story): Optical Margin Alignment and its size for the stories of the text selection or the selected text frames, disabled without either; `type.selectionAttrs` reports them as `storyOptions`, null where the stories differ. The Paragraph panel menu has Ignore Optical Margin in place of the per-paragraph Optical Margin Alignment switch, which stays in `type.para`, and Paragraph Style Options › Indents and Spacing has Ignore Optical Margin (#947). No readiness percentage change.
+ - **2026-10-24** · Optical Margin Alignment per story with a size (`story.options {opticalMargin, opticalMarginSize}`, off by default): when it is on, the story's paragraphs hang punctuation and letter edges by amounts set for that type size, except paragraphs with Ignore Optical Margin (`ignoreOpticalMargin` in `type.para` and paragraph styles). Table cells and footnotes don't take the story setting yet. When it is off, the per-paragraph switch still hangs at the text's own size. IDML imports and exports both (`StoryPreference/@OpticalMarginAlignment`, `@OpticalMarginSize`, `IgnoreEdgeAlignment`) (#947). No readiness percentage change.
+ - **2026-10-24** · Text frames: a custom baseline grid's Relative To (Text Frame Options › Baseline Options, `object.textFrameOptions {baselineGrid: {relativeTo}}`, IDML `BaselineFrameGridRelativeOption`) measures the grid's start from the top of the page, the top margin, the top of the frame or its top inset. Text Frame Options had no custom baseline grid controls, imports dropped the setting and every frame grid started from the page top, so grid-aligned text in a frame measured from its own top sat on the wrong lines. No readiness percentage change.
+ - **2026-10-24** · Paragraph Style Options › Indents and Spacing has an Align to Grid menu: None, All Lines or First Line Only. It shows the style's current setting. A First Line Only style could be set only in the CJK Grid Settings section, which shows only with CJK features on, or through commands. No readiness percentage change.
+ - **2026-10-24** · Anchored text frames, such as marginal notes, compose where their host story places them: they align to the baseline grid at that position, and page-number markers and spine-relative alignment inside them read the host's page. They composed against a grid measured from their stored position and on no page, so a note set to Only Align First Line to Grid could sit a fraction of a line off the body text's grid line. No readiness percentage change.
+ - **2026-10-24** · Tables: a gradient swatch in a cell fill draws as a gradient on the canvas and in PDF, in one gradient space for the whole table, so it runs across cells without restarting. Cells showed the gradient's first stop as a solid colour. No readiness percentage change.
+ - **2026-10-24** · New documents start with Hyphenate Capitalized Words, Hyphenate Last Word and Hyphenate Across Column off in [Basic Paragraph], as in InDesign. Opened and imported files keep the values they carry. No readiness percentage change.
+ - **2026-10-24** · The baseline grid's Relative To setting applies: with Top Margin, the grid starts at each page's own top margin in text composition, on the canvas and for snapping. It started at the page top, so grid-aligned text sat on the wrong lines and a page could fit one line fewer. No readiness percentage change.
+ - **2026-10-24** · Custom-positioned anchored objects honour Relative to Spine (`anchored.options {spineRelative}`, IDML `SpineRelative`): the settings describe a left-hand page and mirror on a right-hand page, so marginal notes stay in the outside margin on both pages of a spread. On right-hand pages they took the left-hand placement and landed in the inside margin, across the spine or over the body text. No readiness percentage change.
+ - **2026-10-24** · Text frames: a custom baseline grid (Text Frame Options › Baseline Options) from an IDML file sets lines from its start by its increment. The composer read the two values in the other order, so lines landed on the wrong grid. No readiness percentage change.
+ - **2026-10-23** · File › File Info… edits the document's Document Title, Author, Description, Keywords, Copyright Notice and Copyright Info URL (`file.info`), and the document saves them. PDF export (PDF/X-4 and Print Booklet included) writes the title, author, description and keywords into the PDF's document information and XMP. EPUB export takes the title and author from File Info, and HTML export takes the title. A title or author given to the export replaces File Info's, and an empty Document Title leaves the document's name as the title. No readiness percentage change.
+ - **2026-10-23** · Save and export dialogs (Save As, Save a Copy, Export PDF and the other exports, Package, libraries and books) start in the active document's folder once it has been saved, and for a document never saved in the folder of the last file saved or exported, remembered across sessions (#1653). A folder deleted since falls back to the system's choice. No readiness percentage change.
+ - **2026-10-22** · Autoflow (Shift-click with the loaded text cursor, autoflow on Place, `text.thread {autoflow}`) fills the pages that follow before it adds any, as InDesign does: one frame per column on each following page, whatever else the page holds, then new pages at the end of the document. It inserted pages right after the story's last frame, in front of the document's own pages. Frames it set past the end of the text go again; a page the document had stays, and a page autoflow added only for such a frame goes with it. Smart Text Reflow of the primary text frame is unchanged. No readiness percentage change.
- **2026-10-16** · Edit › Keyboard Shortcuts imports a set saved by InDesign's Show Set (.txt, Windows or Mac key names, UTF-8 or UTF-16): matched commands take its Default shortcuts or lose theirs, other commands give up keys it takes, and a report lists what it changed and the items it could not match (`window.importShortcuts`, #1180). Tool keys stay fixed. No readiness percentage change.
+ - **2026-10-23** · Translations: a missing string shows in English and fails no test; `cargo xtask i18n-report`, run by `cargo xtask ci`, prints the missing strings per language. Tests keep duplicate-key and placeholder checks and the language mechanics (lookup, context captions, plural captions, right-to-left). No readiness percentage change.
+ - **2026-10-22** · Hyphenation Settings, as in InDesign: the Paragraph panel menu's Hyphenation… (`app.hyphenationDialog`) sets the selected paragraphs' Hyphenate, Words with at Least, After First, Before Last, Hyphen Limit, Hyphenation Zone, the Better Spacing ↔ Fewer Hyphens slider (InDesign's 0–10 steps), Hyphenate Capitalized Words, Last Word and Across Column, with Preview, as one undo step; Paragraph Style Options › Hyphenation has the same form. The panel menu lists its items in InDesign's order. Replicated from a hyphenation tutorial: the same text in Minion Pro breaks into the same lines as InDesign's with hyphenation on, off, and at Fewer Hyphens. No readiness percentage change.
+ - **2026-10-22** · Hyphenate Across Column (Hyphenation Settings; IDML HyphenateAcrossColumns) is applied: with it off, a paragraph whose line ending in an automatic hyphen would end a column or frame is re-composed without that hyphenation point, so the word moves on whole, as in InDesign. Opened and imported files keep their own setting, so their layouts don't change. No readiness percentage change.
+ - **2026-10-22** · The Paragraph panel is laid out as InDesign's: the nine alignment buttons in groups; indent, spacing and drop cap fields by their icons in two columns, with Space Between Paragraphs Using Same Style (Ignore or a space); Shading and Border with the Paragraph Borders and Shading button and colour; Hyphenate with Do Not Align / Align to Baseline Grid. Its panel menu follows InDesign's order: Paragraph and Single-line Composer, Only Align First Line to Grid, Balance Ragged Lines, Optical Margin Alignment, Justification…, Keep Options…, Span Columns…, Hyphenation…, Drop Caps and Nested Styles…, GREP Styles… (these three now open for the selected paragraphs), Paragraph Rules…, Paragraph Borders and Shading…, Bullets and Numbering…, Restart/Continue Numbering, Define Lists… and the paragraph direction. Convert Bullets and Numbering to Text is listed but not available yet. No readiness percentage change.
- **2026-10-22** · A ruler guide dragged with the Selection tools, out of a ruler, on its own or with other selected guides, snaps along its axis as objects do (#1221): to other ruler guides, margins, columns, bleed, page and object edges and centers (with the smart-guide mark) and the document grid, within the snap zone and following Snap to Guides and Smart Guides. Shift snaps to the ruler's ticks and Cmd suspends snapping. The preview line, the position readout and the drop use the same snapped position. No readiness percentage change.
- **2026-10-22** · macOS: the app menu has a Language submenu after Settings… with each interface language in its own name and the current one checked, as in the suite's other apps; Preferences › General › Interface Language stays. No readiness percentage change.
+ - **2026-10-23** · Type › Text Variables › Convert Variable to Text (`variables.convertToText`): the variable instances in the selected text, in a story, a table cell or a footnote, become plain text of the value each shows on its own page (a running header on page 3 becomes page 3's heading). `variables.convertAllToText {name}` does the same for every instance of one variable in the document, as the Text Variables dialog's Convert to Text button. The variable stays defined; one undo step. No readiness percentage change.
- **2026-10-22** · macOS menu bar: the menus keep working after the interface language or Show CJK Features changes (a rebuilt menu bar lost every click, Quit included), and its key equivalents are the shortcuts in effect, so a shortcut moved in the Keyboard Shortcuts editor leaves its old menu item. No readiness percentage change.
- **2026-10-22** · Paragraph rules: Rule Above's offset is measured from the first line's baseline to the rule's bottom edge, as in InDesign. Rules sat one ascent too high and crossed the previous paragraph's text (reported from an imported INDD document). No readiness percentage change.
- **2026-10-21** · Ruler guides are selected like objects (#1282): a click with the Selection tools selects a guide (also where it crosses an object), Shift-click adds or removes one, a new guide from the rulers is selected, a marquee that touches no object selects the guides it crosses, and Edit › Select All Guides (⌥⌘G, `guide.selectAll`) selects every unlocked guide on the spread. Selected guides draw thicker in their layer's color, drag together (all of them shown moving), nudge with the arrow keys and go with Delete, each as one undo step (`guide.select`, `guide.deselect`, `guide.moveBy`, `guide.delete {}`). With one guide selected the Control bar's X (vertical guide) or Y (horizontal guide) field and Properties › Transform show where it is, as the rulers measure, and typing a value moves it there. No readiness percentage change.
diff --cc apps/designcraft-cli/src/main.rs
index 929c5cccf,d631f5671..9ce15674c
--- a/apps/designcraft-cli/src/main.rs
+++ b/apps/designcraft-cli/src/main.rs
@@@ -123,9 -122,9 +123,9 @@@ 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::*;
+ use designcraft_engine::links::{APP_PAGE, DISCORD, GITHUB, ISSUES, WEBSITE};
outln!("Discord {DISCORD}\nWebsite {WEBSITE}\nApp page {APP_PAGE}\nGitHub {GITHUB}\nIssues {ISSUES}");
ExitCode::SUCCESS
}
diff --cc crates/engine/src/cmd/export.rs
index 89075ab61,808f4d79c..3b7dd48d1
--- a/crates/engine/src/cmd/export.rs
+++ b/crates/engine/src/cmd/export.rs
@@@ -10,11 -10,33 +10,33 @@@ use crate::{EngineError, Result, Sessio
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; 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, …})",
- "{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?, created?: int (creation date in Unix seconds; default now, for reproducible files)} → {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?, created?: int (creation date in Unix seconds; default now, for reproducible files)} → {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",
+ "{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), split?: \"off\"|\"exportTags\"|{style: name} (Split Document for this export, not stored; the document's `document.epubSplit` by default), 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",
has_doc, export_epub),
+ cmd!(
+ "document.epubSplit",
+ "EPUB Split Document",
+ [],
+ None,
+ "{split?: \"off\"|\"exportTags\"|{style: name}} — EPUB Export Options › Split Document, stored with the document: one content file (off, the default), a file before each paragraph whose style has Export Tagging › Split Document on (exportTags), or before each paragraph of one style → {split}",
+ has_doc,
+ |s, p| {
+ const ID: &str = "document.epubSplit";
+ let cur = s.doc()?.doc.settings.epub_split.clone();
+ let Some(v) = p.get("split") else { return Ok(json!({"split": cur})) };
+ let split = epub_split_param(ID, &s.doc()?.doc, v)?;
+ if split != cur {
+ let stored = split.clone();
+ s.edit(move |d, _| {
+ d.settings.epub_split = stored;
+ Ok(Value::Null)
+ })?;
+ }
+ Ok(json!({"split": split}))
+ }
+ ),
cmd!(noundo "file.exportFixedEpub", "Export EPUB (Fixed Layout)…", ["File"], None,
"{path?, title?, author?, language?} — pre-paginated EPUB → {path, bytes} (no path: {base64, bytes})",
has_doc, |s, p| {
@@@ -368,9 -422,13 +422,13 @@@ pub(crate) fn options(p: &Value, page_c
_ => 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,
};
+ let created = match p.get("created") {
+ None | Some(Value::Null) => None,
+ Some(v) => Some(v.as_i64().ok_or_else(|| bad(ID, "`created`: Unix seconds, an integer"))?),
+ };
Ok(PdfOptions {
pages,
spreads,
@@@ -833,20 -812,11 +911,19 @@@ pub(crate) fn pdf_export(s: &Session, p
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 (layered, layer_count) = if opts.standard == Standard::PdfA2b { rasterize_layered(base)? } else { (None, 0) };
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;
diff --cc crates/pdf/src/export.rs
index 64bd853a4,86e0f90e0..0d4c9d9a9
--- a/crates/pdf/src/export.rs
+++ b/crates/pdf/src/export.rs
@@@ -141,6 -145,25 +145,26 @@@ pub fn export_pdf_with_report(doc: &Doc
write::guard(|| export_pdf_with_report_inner(doc, cache, opts))
}
+ /// Form fields (Buttons and Forms) and, for interactive PDF, video and sound; not in PDF/X
+ /// or PDF/A: this update comes after krilla's validator ran, and its NeedAppearances fields and
+ /// Screen annotations aren't allowed in PDF/A.
+ fn add_form_fields(bytes: &mut Vec<u8>, warnings: &mut Vec<String>, doc: &Document, sheets: &[Sheet], opts: &PdfOptions) {
+ let fields = crate::forms::collect(doc, sheets);
+ let media = if opts.media { crate::forms::collect_media(doc, sheets) } else { Vec::new() };
+ if fields.is_empty() && media.is_empty() {
+ return;
+ }
+ match opts.standard {
+ Standard::PdfX4 => warnings.push("PDF/X-4: form fields and media were left out".into()),
++ Standard::PdfX1a => warnings.push("PDF/X-1a: form fields and media were left out".into()),
+ Standard::PdfA2b => warnings.push("PDF/A-2b: form fields and media were left out".into()),
+ _ => match crate::forms::add_fields(&*bytes, &fields, &media) {
+ Some(b) => *bytes = b,
+ None => warnings.push("form fields and media couldn't be added to this PDF".into()),
+ },
+ }
+ }
+
fn export_pdf_with_report_inner(doc: &Document, cache: &Cache, opts: &PdfOptions) -> Result<ExportReport> {
let sheets = sheets(doc, opts)?;
let (version, archival) = match opts.standard {
diff --cc crates/pdf/src/lib.rs
index f7f6e47b7,c14b77f99..602d225ba
--- a/crates/pdf/src/lib.rs
+++ b/crates/pdf/src/lib.rs
@@@ -43,8 -41,8 +43,9 @@@ mod marks
mod text;
mod forms;
+ mod optional_content;
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,
@@@ -68,10 -63,9 +69,10 @@@ pub enum Standard
}
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();
+ let k: String = s.chars().filter(char::is_ascii_alphanumeric).collect::<String>().to_ascii_lowercase();
match k.as_str() {
"" | "none" => Some(Self::None),
"x4" | "pdfx4" | "pdfx42008" | "pdfx42010" => Some(Self::PdfX4),
diff --cc crates/pdf/src/x1a_tests.rs
index fbb1bda39,000000000..777d1e2a6
mode 100644,000000..100644
--- a/crates/pdf/src/x1a_tests.rs
+++ b/crates/pdf/src/x1a_tests.rs
@@@ -1,319 -1,0 +1,320 @@@
+//! 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::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)") && 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");
+ 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 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));
+}
+
+/// 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(entries, content, "/OutputConditionIdentifier(Custom)/DestOutputProfile 4 0 R", &icc_header(2))
+}
+
+/// [`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)/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() {
+ offsets.push(out.len());
+ out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
+ out.extend_from_slice(o);
+ out.extend_from_slice(b"\nendobj\n");
+ }
+ let xref = out.len();
+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f\r\n", objects.len() + 1).as_bytes());
+ 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 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());
+ 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 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 9 0 R<</Subtype/NChannel/Colorants<<>>>>]>>>>",
+ "/N cs 1 1 scn 0 0 10 10 re f",
+ "NChannel",
+ );
+ // 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()),
+ &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}");
+ }
+}
+
+/// 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 mut totals = craft_prepress::flatten::FlattenTotals::default();
++ totals.dropped_inks = 3;
+ 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:?}");
+}
diff --cc docs/gaps.md
index ef5e9c062,ea5b70840..759fdb610
--- a/docs/gaps.md
+++ b/docs/gaps.md
@@@ -116,14 -116,25 +116,26 @@@ Kind: **F** feature · **U** UI/UX · *
- **Estimate:** 10–20 h. **Doc:** [localization-parity.md](localization-parity.md)
### 9. PDF output presets and standards (FF)
-- **Missing:** PDF/X-1a and PDF/X-3 (no flattener to PDF 1.3/1.4), Adobe PDF Presets and
- `.joboptions` load/save, output-intent choice beyond the built-in profile, PDF/UA validation;
- #159, #32.
-- **Have:** PDF/X-4 with output intent and a validator (`#200`), PDF/A-2b, tagged PDF, CMYK and
- spot, marks and bleed, the options dialog with remembered settings (#196).
-- **Estimate:** 40–70 h. **Doc:** [file-format-parity.md](file-format-parity.md)
+- **Missing:** PDF/X-3, Adobe PDF Presets and `.joboptions` load/save, output-intent choice
+ beyond the built-in profile, PDF/UA validation; soft effects other than the drop shadow reach
+ the PDF/X-1a flattener as RGB images; #159, #32.
+- **Have:** PDF/X-4 with output intent and a validator (`#200`), PDF/X-1a:2003 through
+ craft-prepress's flattener with its own checks, PDF/A-2b, tagged PDF, CMYK and spot, marks and
+ bleed, the options dialog with remembered settings (#196).
+- **Estimate:** 30–60 h. **Doc:** [file-format-parity.md](file-format-parity.md)
+ ### 28. Placed-PDF font repair for PDF/X-4 (FF)
+ - **Missing:** embedding, substitution or outlining of unembedded fonts in placed PDFs; export
+ does not automatically embed or outline them.
+ - **Have:** PDF/X-4 export warnings and `validate-pdf` report unembedded fonts drawing visible
+ text, including inside placed PDF forms, with font names and pages (#909). Invisible text
+ (render mode 3) is exempt from this font-embedding check. A document-wide operation limit and a
+ form-nesting depth limit report incomplete font checks rather than traversing pathological
+ nesting.
+ - **Impact:** detection now ships, but a placed PDF with visible unembedded fonts still needs
+ font repair before it can meet PDF/X-4 requirements.
+ - **Doc:** [file-format-parity.md](file-format-parity.md)
+
### 10. Printing (H, F)
- **Missing:** PostScript, a printer-driver options UI, separations to device, print presets, or trapping.
- **Have:** `file.print` exports selected pages/spreads with marks and bleed, then submits through