Skip to content

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

refactor(pdf): share writer backend (PDFW)

skylar taylor-barrickefd2310c83c6
diff --git a/Cargo.lock b/Cargo.lock
index ef525c84e..21064be13 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -796,6 +796,15 @@ dependencies = [
"libm",
]
+[[package]]
+name = "craft-pdf"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=c3487320b2d1de657b860b3c8abb44e1f2b32bd8#c3487320b2d1de657b860b3c8abb44e1f2b32bd8"
+dependencies = [
+ "krilla",
+ "thiserror 2.0.21",
+]
+
[[package]]
name = "craft-print"
version = "0.1.0"
@@ -1079,6 +1088,7 @@ dependencies = [
name = "designcraft-pdf"
version = "0.7.1"
dependencies = [
+ "craft-pdf",
"designcraft-color",
"designcraft-compose",
"designcraft-doc",
@@ -1089,7 +1099,6 @@ dependencies = [
"hayro-interpret",
"hayro-syntax",
"image",
- "krilla",
"krilla-svg",
"kurbo",
"log",
@@ -2437,8 +2446,7 @@ dependencies = [
[[package]]
name = "krilla"
version = "0.8.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "27da593198b20eeba65caeb73c2bbeec3e53ab08fa549898312ce81c4fce5e33"
+source = "git+https://github.com/storytold/craft-libs?rev=c3487320b2d1de657b860b3c8abb44e1f2b32bd8#c3487320b2d1de657b860b3c8abb44e1f2b32bd8"
dependencies = [
"base64",
"bumpalo",
diff --git a/Cargo.toml b/Cargo.toml
index b08a82fc2..14655b205 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -11,6 +11,8 @@ rust-version = "1.95"
repository = "https://github.com/storytold/designcraft"
[workspace.dependencies]
+# Shared writer; the immutable revision must be published before this consumer.
+craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "c3487320b2d1de657b860b3c8abb44e1f2b32bd8", version = "=0.1.0", default-features = false }
craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "d991bf6792f8ade99c51358bf3c1d902c8cd96b5" }
# internal
designcraft-geom = { path = "crates/geom" }
@@ -57,12 +59,11 @@ image = { version = "0.25", default-features = false, features = ["png", "jpeg",
tiff = "0.11"
# SVG (same usvg as krilla-svg).
resvg = { version = "0.47", default-features = false, features = ["text"] }
-krilla-svg = "0.8"
+krilla-svg = "=0.8.1"
# Boolean operations on Bézier paths (Pathfinder).
flo_curves = "0.8"
# QR codes (Object › Generate QR Code); MIT.
qrcodegen = "1.8"
-krilla = { version = "0.8", features = ["pdf"] }
hayro = "0.7"
quick-xml = "0.38"
zip = { version = "3", default-features = false, features = ["deflate"] }
@@ -100,4 +101,5 @@ debug = 0
# Opt-in cancelable macOS termination on the pinned winit 0.30 line.
[patch.crates-io]
+krilla = { git = "https://github.com/storytold/craft-libs", rev = "c3487320b2d1de657b860b3c8abb44e1f2b32bd8", version = "=0.8.2" }
winit = { git = "https://github.com/skylartaylor/winit.git", rev = "3d51077fd1a966f84df9ef287839dc84fd5b4ca7" }
diff --git a/ROADMAP.md b/ROADMAP.md
index 8a0f82071..2cd564f94 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -129,6 +129,8 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m
Newest first.
+- **2026-10-12 (PDFW)** · PDF, booklet and book composition share guarded writing, metadata and font preparation through craft-pdf. Layout, shaping, placed graphics, colour policy, tagging and PDF/X postprocessing remain in DesignCraft. Failed native drawing returns an export error; failed writer cleanup cannot serialize an incomplete document. No readiness percentage change.
+
- **2026-10-12** · macOS Dock Quit uses the same unsaved-document prompts as window and menu Quit. Repeated requests keep the current answers; Cancel retains every tab and unsaved recovery checkpoint, and completed Save/Don't Save answers exit through the ordinary event loop. No readiness percentage change.
- **2026-10-12** · Orderly native exit writes the latest recovery state after finalizing current quit approvals; incomplete or stale plans keep their documents, and Undo to the saved state clears stale recovery. Unavailable or failed recovery is reported. Cancelable macOS Dock Quit remains open (#544). No readiness percentage change.
- **2026-10-12** · Recovered documents keep a checkpoint until saved, closed or reverted, including a second crash before autosave. Restarted document IDs and explicit recovery folders preserve other snapshots; failed republishing retains the original. No readiness percentage change.
diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs
index debdbb124..0258bd7e4 100644
--- a/crates/mcp/src/backend.rs
+++ b/crates/mcp/src/backend.rs
@@ -172,6 +172,8 @@ mod tests {
Err(e) => panic!("accept failed: {e}"),
}
};
+ // Accepted sockets inherit nonblocking mode on macOS; only accept should poll.
+ stream.set_nonblocking(false).unwrap();
stream.set_read_timeout(Some(Duration::from_secs(2))).unwrap();
stream.set_write_timeout(Some(Duration::from_secs(2))).unwrap();
let mut reader = BufReader::new(stream.try_clone().unwrap());
diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml
index 47c384470..6f40462b7 100644
--- a/crates/pdf/Cargo.toml
+++ b/crates/pdf/Cargo.toml
@@ -14,7 +14,7 @@ designcraft-color = { workspace = true }
designcraft-doc = { workspace = true }
designcraft-fonts = { workspace = true }
designcraft-compose = { workspace = true }
-krilla = { workspace = true }
+craft-pdf = { workspace = true, features = ["write-pdf"] }
krilla-svg = { workspace = true }
designcraft-images = { workspace = true }
image = { workspace = true }
diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs
index dcf8abb83..f9d09b616 100644
--- a/crates/pdf/src/export.rs
+++ b/crates/pdf/src/export.rs
@@ -3,6 +3,8 @@
use std::collections::HashMap;
use std::sync::Arc;
+use craft_pdf::write::backend as krilla;
+use craft_pdf::write::{self, Metadata, Writer};
use designcraft_color::swatch::{ColorType, SwatchValue};
use designcraft_color::{BlendMode as DcBlend, Color, GradientKind};
use designcraft_compose::Cache;
@@ -10,10 +12,9 @@ use designcraft_doc::{AssetId, Content, Document, Item, PageSide, Spread, Stroke
use designcraft_geom::kurbo::{PathEl, Shape as _};
use designcraft_geom::{Affine, BezPath, Rect, Vec2, corners};
use krilla::color::{cmyk, luma, rgb};
-use krilla::configure::{Archival, ConfigurationBuilder, PdfVersion};
+use krilla::configure::{Archival, PdfVersion};
use krilla::geom::{Path, PathBuilder, Size, Transform};
use krilla::image::Image;
-use krilla::metadata::Metadata;
use krilla::num::NormalizedF32;
use krilla::page::PageSettings;
use krilla::paint::{Fill, FillRule, LinearGradient, RadialGradient, SpreadMethod, Stop, Stroke, StrokeDash};
@@ -59,13 +60,13 @@ fn sheets(doc: &Document, opts: &PdfOptions) -> Result<Vec<Sheet>> {
return Err(PdfError::NoPages);
}
if let Some(bad) = pages.iter().find(|p| **p >= count) {
- return Err(PdfError::BadPage(bad + 1));
+ return Err(PdfError::BadPage(bad.saturating_add(1)));
}
let b = doc.settings.bleed.map(|v| if opts.bleed { v.max(0.0) } else { 0.0 });
let mut out: Vec<Sheet> = Vec::new();
let mut seen_spreads: Vec<usize> = Vec::new();
for abs in pages {
- let (si, pi) = doc.page_loc(abs).ok_or(PdfError::BadPage(abs + 1))?;
+ let (si, pi) = doc.page_loc(abs).ok_or(PdfError::BadPage(abs.saturating_add(1)))?;
let sp: &Spread = &doc.spreads[si];
let (trim, l, r, label) = if opts.spreads {
if seen_spreads.contains(&si) {
@@ -101,6 +102,10 @@ pub(crate) fn mark_start(opts: &PdfOptions, bleed: [f64; 4]) -> f64 {
/// Like [`export_pdf`], also returning warnings about approximated or dropped features.
pub fn export_pdf_with_report(doc: &Document, cache: &Cache, opts: &PdfOptions) -> Result<ExportReport> {
+ write::guard(|| export_pdf_with_report_inner(doc, cache, opts))
+}
+
+fn export_pdf_with_report_inner(doc: &Document, cache: &Cache, opts: &PdfOptions) -> Result<ExportReport> {
let sheets = sheets(doc, opts)?;
let warnings = Vec::new();
let (version, archival) = match opts.standard {
@@ -108,37 +113,20 @@ pub fn export_pdf_with_report(doc: &Document, cache: &Cache, opts: &PdfOptions)
Standard::PdfX4 => (PdfVersion::Pdf16, None),
Standard::PdfA2b => (PdfVersion::Pdf17, Some(Archival::A2_B)),
};
- let mut cb = ConfigurationBuilder::new().with_version(version);
- if let Some(a) = archival {
- cb = cb.with_archival_validator(a);
- }
- let configuration = cb.finish().map_err(|e| PdfError::Write(format!("{e:?}")))?;
+ let configuration = write::configuration(version, archival)?;
let settings = krilla::SerializeSettings { compress_content_streams: opts.compress, configuration, ..Default::default() };
- let mut pdf = krilla::Document::new_with(settings);
-
let title = opts.title.clone().unwrap_or_else(|| doc.title.clone());
- let mut meta = Metadata::new().creator("DesignCraft".into()).producer("DesignCraft".into());
- if !title.is_empty() {
- meta = meta.title(title.clone());
- }
- if let Some(a) = &opts.author {
- meta = meta.authors(vec![a.clone()]);
- }
let created = opts.created.or_else(now_unix);
- if let Some(t) = created {
- let c = civil(t);
- meta = meta.creation_date(
- krilla::metadata::DateTime::new(c.0.clamp(0, 9999) as u16)
- .month(c.1)
- .day(c.2)
- .hour(c.3)
- .minute(c.4)
- .second(c.5)
- .utc_offset_hour(0)
- .utc_offset_minute(0),
- );
- }
- pdf.set_metadata(meta);
+ let metadata = Metadata {
+ creator: "DesignCraft".into(),
+ producer: "DesignCraft".into(),
+ title: Some(title.clone()),
+ authors: opts.author.iter().cloned().collect(),
+ created: created.map(date_time),
+ ..Default::default()
+ };
+ let mut writer = Writer::new(settings, metadata);
+ let pdf = writer.document_mut();
let mut ex = Exporter {
doc,
@@ -182,6 +170,8 @@ pub fn export_pdf_with_report(doc: &Document, cache: &Cache, opts: &PdfOptions)
let settings = PageSettings::new(size).with_trim_box(local(sh.trim)).with_bleed_box(local(sh.bleed));
let mut page = pdf.start_page_with(settings);
let mut s = page.surface();
+ #[cfg(all(test, not(target_arch = "wasm32")))]
+ unwind_tests::inject(&mut s);
s.push_transform(&tf(Affine::translate(-sh.media.origin().to_vec2())));
ex.clip = sh.bleed;
if let Some(clip) = to_path(&sh.bleed.to_path(0.1)) {
@@ -207,7 +197,7 @@ pub fn export_pdf_with_report(doc: &Document, cache: &Cache, opts: &PdfOptions)
pdf.set_tag_tree(ex.tag_tree());
}
ex.check_placed_versions()?;
- let mut bytes = pdf.finish().map_err(|e| PdfError::Write(format!("{e:?}")))?;
+ let mut bytes = writer.finish().map_err(PdfError::from)?;
// Transparency blends in the document's blend space: CMYK for print (and always in PDF/X).
let mut warnings = ex.warnings;
if !ex.rgb_only && (doc.settings.blend_space == designcraft_doc::BlendSpace::Cmyk || opts.standard == Standard::PdfX4) {
@@ -245,12 +235,13 @@ pub fn export_pdf_with_report(doc: &Document, cache: &Cache, opts: &PdfOptions)
/// One PDF from several (a book's documents), every page carried over as vectors; each part
/// comes with its pages' sizes (points).
pub fn merge_pdfs(parts: &[(Vec<u8>, Vec<(f32, f32)>)], title: Option<&str>) -> Result<Vec<u8>> {
- let mut pdf = krilla::Document::new_with(krilla::SerializeSettings::default());
- let mut meta = Metadata::new().creator("DesignCraft".into()).producer("DesignCraft".into());
- if let Some(t) = title {
- meta = meta.title(t.to_string());
- }
- pdf.set_metadata(meta);
+ write::guard(|| merge_pdfs_inner(parts, title))
+}
+
+fn merge_pdfs_inner(parts: &[(Vec<u8>, Vec<(f32, f32)>)], title: Option<&str>) -> Result<Vec<u8>> {
+ let metadata = Metadata { creator: "DesignCraft".into(), producer: "DesignCraft".into(), title: title.map(str::to_owned), ..Default::default() };
+ let mut writer = Writer::new(krilla::SerializeSettings::default(), metadata);
+ let pdf = writer.document_mut();
let mut pages = 0;
for (bytes, sizes) in parts {
let src = krilla::pdf::Pdf::new(Arc::new(bytes.clone())).map_err(|e| PdfError::Write(format!("{e:?}")))?;
@@ -259,6 +250,8 @@ pub fn merge_pdfs(parts: &[(Vec<u8>, Vec<(f32, f32)>)], title: Option<&str>) ->
let size = Size::from_wh(w.max(1.0), h.max(1.0)).ok_or(PdfError::NoPages)?;
let mut page = pdf.start_page_with(PageSettings::new(size));
let mut s = page.surface();
+ #[cfg(all(test, not(target_arch = "wasm32")))]
+ unwind_tests::inject(&mut s);
s.draw_pdf_page(&doc, size, i);
s.finish();
page.finish();
@@ -268,7 +261,7 @@ pub fn merge_pdfs(parts: &[(Vec<u8>, Vec<(f32, f32)>)], title: Option<&str>) ->
if pages == 0 {
return Err(PdfError::NoPages);
}
- pdf.finish().map_err(|e| PdfError::Write(format!("{e:?}")))
+ writer.finish().map_err(PdfError::from)
}
/// File › Print Booklet: how pages pair up on printer spreads.
@@ -303,19 +296,20 @@ pub fn booklet_pairs(n: usize, kind: BookletKind) -> Vec<(Option<usize>, Option<
/// An imposed PDF: two document pages per sheet, in booklet order.
pub fn export_booklet(doc: &Document, cache: &Cache, opts: &BookletOptions) -> Result<ExportReport> {
+ write::guard(|| export_booklet_inner(doc, cache, opts))
+}
+
+fn export_booklet_inner(doc: &Document, cache: &Cache, opts: &BookletOptions) -> Result<ExportReport> {
let n = doc.page_count();
if n == 0 {
return Err(PdfError::NoPages);
}
let pdf_opts = PdfOptions { title: opts.title.clone(), ..PdfOptions::default() };
let settings = krilla::SerializeSettings { compress_content_streams: true, ..Default::default() };
- let mut pdf = krilla::Document::new_with(settings);
let title = opts.title.clone().unwrap_or_else(|| doc.title.clone());
- let mut meta = Metadata::new().creator("DesignCraft".into()).producer("DesignCraft".into());
- if !title.is_empty() {
- meta = meta.title(title);
- }
- pdf.set_metadata(meta);
+ let metadata = Metadata { creator: "DesignCraft".into(), producer: "DesignCraft".into(), title: Some(title), ..Default::default() };
+ let mut writer = Writer::new(settings, metadata);
+ let pdf = writer.document_mut();
let mut ex = Exporter {
doc,
cache,
@@ -355,6 +349,8 @@ pub fn export_booklet(doc: &Document, cache: &Cache, opts: &BookletOptions) -> R
for (left, right) in &pairs {
let mut page = pdf.start_page_with(PageSettings::new(size));
let mut s = page.surface();
+ #[cfg(all(test, not(target_arch = "wasm32")))]
+ unwind_tests::inject(&mut s);
for (slot, abs) in [(0.0, left), (pw + gap, right)] {
let Some((si, pi)) = abs.and_then(|a| doc.page_loc(a)) else { continue };
let p = &doc.spreads[si].pages[pi];
@@ -374,7 +370,7 @@ pub fn export_booklet(doc: &Document, cache: &Cache, opts: &BookletOptions) -> R
page.finish();
}
ex.check_placed_versions()?;
- let mut bytes = pdf.finish().map_err(|e| PdfError::Write(format!("{e:?}")))?;
+ let mut bytes = writer.finish().map_err(PdfError::from)?;
if doc.settings.blend_space == designcraft_doc::BlendSpace::Cmyk {
crate::pdfx::cmyk_group_spaces(&mut bytes);
}
@@ -393,6 +389,18 @@ fn now_unix() -> Option<i64> {
None
}
+fn date_time(t: i64) -> krilla::metadata::DateTime {
+ let c = civil(t);
+ krilla::metadata::DateTime::new(c.0.clamp(0, 9999) as u16)
+ .month(c.1)
+ .day(c.2)
+ .hour(c.3)
+ .minute(c.4)
+ .second(c.5)
+ .utc_offset_hour(0)
+ .utc_offset_minute(0)
+}
+
/// Unix seconds (UTC) → (year, month, day, hour, minute, second), proleptic Gregorian.
pub(crate) fn civil(t: i64) -> (i64, u8, u8, u8, u8, u8) {
let days = t.div_euclid(86_400);
@@ -1751,3 +1759,54 @@ mod image_content_cache_tests {
assert!(duplicate.upgrade().is_none());
}
}
+
+#[cfg(all(test, not(target_arch = "wasm32")))]
+mod unwind_tests {
+ use super::*;
+ use std::cell::Cell;
+
+ thread_local! {
+ static FAIL_NEXT_SURFACE: Cell<bool> = const { Cell::new(false) };
+ }
+
+ // Fail with live backend drawing state, so a missing guard or an unpatched destructor
+ // makes the child fail. Thread-local state keeps unrelated export tests independent.
+ #[allow(clippy::panic)] // Test-only fault injection exercises recovery with a live surface.
+ pub(super) fn inject(surface: &mut krilla::surface::Surface<'_>) {
+ if FAIL_NEXT_SURFACE.replace(false) {
+ surface.push_transform(&krilla::geom::Transform::from_translate(2.0, 3.0));
+ panic!("synthetic export drawing failure");
+ }
+ }
+
+ #[test]
+ fn export_entry_points_recover_in_a_subprocess() {
+ const CHILD: &str = "DESIGNCRAFT_PDF_EXPORT_PANIC_PROBE";
+ if std::env::var_os(CHILD).is_none() {
+ let output = std::process::Command::new(std::env::current_exe().unwrap())
+ .args(["--exact", "export::unwind_tests::export_entry_points_recover_in_a_subprocess", "--nocapture"])
+ .env(CHILD, "1")
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "export child failed: {:?}\n{}", output.status, String::from_utf8_lossy(&output.stderr));
+ assert!(String::from_utf8_lossy(&output.stdout).contains("all three export entry points recovered"));
+ return;
+ }
+ let doc = Document::new(&designcraft_doc::build::NewDocument { pages: 1, ..Default::default() });
+ let cache = Cache::new();
+ let source = export_pdf(&doc, &cache, &Default::default()).unwrap();
+ let parts = [(source, vec![(612.0, 792.0)])];
+ for entry in ["document", "booklet", "merge"] {
+ let export = || match entry {
+ "document" => export_pdf(&doc, &cache, &Default::default()),
+ "booklet" => export_booklet(&doc, &cache, &Default::default()).map(|report| report.bytes),
+ _ => merge_pdfs(&parts, None),
+ };
+ FAIL_NEXT_SURFACE.set(true);
+ assert!(matches!(export(), Err(PdfError::Write(message)) if message.contains("synthetic export drawing failure")), "{entry}");
+ let fresh = export().unwrap();
+ assert!(!hayro_syntax::Pdf::new(Arc::new(fresh)).unwrap().pages().is_empty(), "fresh {entry} export must still work");
+ }
+ println!("all three export entry points recovered");
+ }
+}
diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs
index c4aad577c..d22098cb8 100644
--- a/crates/pdf/src/lib.rs
+++ b/crates/pdf/src/lib.rs
@@ -200,6 +200,12 @@ pub fn parse_page_range(s: &str, count: usize) -> Result<Vec<usize>> {
Ok(out)
}
+impl From<craft_pdf::write::WriteError> for PdfError {
+ fn from(error: craft_pdf::write::WriteError) -> Self {
+ Self::Write(error.to_string())
+ }
+}
+
#[cfg(test)]
mod tests;
diff --git a/crates/pdf/src/links.rs b/crates/pdf/src/links.rs
index ce81287a1..07541ad1f 100644
--- a/crates/pdf/src/links.rs
+++ b/crates/pdf/src/links.rs
@@ -1,6 +1,7 @@
//! Interactive PDF: hyperlink annotations (frames and text ranges → URLs, e-mail, pages) and the
//! bookmark outline.
+use craft_pdf::write::backend as krilla;
use designcraft_doc::{Bookmark, Document, HyperlinkDest, HyperlinkSource, SpreadRef};
use designcraft_geom::{Affine, Rect};
use krilla::action::{Action, LinkAction};
diff --git a/crates/pdf/src/marks.rs b/crates/pdf/src/marks.rs
index a2dab3356..07894e06a 100644
--- a/crates/pdf/src/marks.rs
+++ b/crates/pdf/src/marks.rs
@@ -1,6 +1,7 @@
//! Printer's marks drawn in the slug area: crop marks at the trim corners, bleed marks at the bleed
//! corners, and a page-information line. All marks use `[Registration]` (every plate).
+use craft_pdf::write::backend as krilla;
use designcraft_geom::{BezPath, Point};
use krilla::num::NormalizedF32;
use krilla::paint::{LineCap, LineJoin, Stroke};
diff --git a/crates/pdf/src/pdfx.rs b/crates/pdf/src/pdfx.rs
index 3218ffc76..ebb3d12da 100644
--- a/crates/pdf/src/pdfx.rs
+++ b/crates/pdf/src/pdfx.rs
@@ -452,6 +452,7 @@ impl RgbScan {
#[cfg(test)]
mod tests {
+ use craft_pdf::write::backend as krilla;
use std::sync::Arc;
use designcraft_color::{Color, Swatch};
diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs
index 9ac53d057..fdda4b28d 100644
--- a/crates/pdf/src/tests.rs
+++ b/crates/pdf/src/tests.rs
@@ -446,3 +446,26 @@ fn column_rules_are_drawn() {
assert!((xs[0] - 214.0).abs() < 0.01 && (xs[1] - 398.0).abs() < 0.01, "{xs:?}");
assert!(rules(false).is_empty());
}
+
+#[test]
+fn extreme_page_selection_is_a_page_error_without_overflow() {
+ let doc = doc_with_text("Bounded page selection");
+ let opts = PdfOptions { pages: Some(vec![usize::MAX]), ..Default::default() };
+ assert_eq!(export_pdf(&doc, &Cache::new(), &opts), Err(PdfError::BadPage(usize::MAX)));
+}
+
+#[test]
+fn empty_and_populated_export_metadata_preserve_key_presence() {
+ let mut d = Document::new(&NewDocument::default());
+ d.title.clear();
+ let s = uncompressed(&d, PdfOptions::default());
+ for key in ["/Title", "/Author", "<dc:title>", "<dc:creator>"] {
+ assert!(!s.contains(key), "unexpected empty metadata {key}");
+ }
+ d.title = "Synthetic title".into();
+ let s = uncompressed(&d, PdfOptions { author: Some("Test author".into()), created: Some(1_700_000_000), ..Default::default() });
+ for key in ["/Title", "/Author", "/CreationDate", "<dc:title>", "<dc:creator>"] {
+ assert!(s.contains(key), "missing populated metadata {key}");
+ }
+ assert!(s.contains("Synthetic title") && s.contains("Test author"));
+}
diff --git a/crates/pdf/src/text.rs b/crates/pdf/src/text.rs
index bf59efded..ba06d48ab 100644
--- a/crates/pdf/src/text.rs
+++ b/crates/pdf/src/text.rs
@@ -10,6 +10,7 @@ use std::collections::HashMap;
use std::ops::Range;
use std::sync::Arc;
+use craft_pdf::write::backend as krilla;
use designcraft_compose::{ComposedStory, FrameText, PlacedGlyph};
use designcraft_fonts::{FontDb, FontFace};
use designcraft_geom::kurbo::Shape as _;
@@ -66,13 +67,11 @@ impl Exporter<'_> {
self.fonts
.entry(face.id())
.or_insert_with(|| {
- if face.is_variable() {
- // A named instance: krilla embeds the font at these axis settings.
- let coords: Vec<(krilla::text::Tag, f32)> = face.coords.iter().map(|(t, v)| (krilla::text::Tag::new(t), *v)).collect();
- Font::new_variable(face.data().to_vec().into(), face.index(), &coords)
- } else {
- Font::new(face.data().to_vec().into(), face.index())
- }
+ // Keep the existing outline fallback and warning when embedding fails.
+ let variations = face.is_variable().then_some(face.coords.as_slice());
+ craft_pdf::write::font(face.data(), face.index(), variations)
+ .inspect_err(|error| log::warn!("PDF font `{} {}` could not be embedded: {error}", face.family, face.style))
+ .ok()
})
.clone()
}
diff --git a/crates/pdf/tests/support/image_content_cache_contract.rs b/crates/pdf/tests/support/image_content_cache_contract.rs
index 6a4ac91f1..c7812ce7b 100644
--- a/crates/pdf/tests/support/image_content_cache_contract.rs
+++ b/crates/pdf/tests/support/image_content_cache_contract.rs
@@ -3,6 +3,8 @@
//! All images and placed PDFs are tiny procedural fixtures.
use std::sync::Arc;
+use craft_pdf::write::backend as krilla;
+
use designcraft_compose::Cache;
use designcraft_doc::{Asset, AssetId, Content, Document, Graphic, Item, ItemId, Shape, SpreadRef};
use designcraft_geom::{Affine, Rect, shapes};
diff --git a/docs/architecture.md b/docs/architecture.md
index 39a9039dc..5073a4b86 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -1,6 +1,6 @@
# DesignCraft architecture
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (cancelable macOS Dock Quit) · **Target:** Adobe InDesign 2026
+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (shared PDF writing) · **Target:** Adobe InDesign 2026
How DesignCraft is built today. The design notes behind it are in `plan/architecture.md`
(local, gitignored); this file describes what the code on `main` does. Agents: AGENTS.md has the
@@ -21,7 +21,7 @@ lines of Rust, 1,122 tests (2026-10-10). Pure Rust, no C dependencies by default
| L2 | `compose` | the text engine: style resolution, shaping, Knuth–Plass and single-line breaking, Liang hyphenation, justification, tabs, keeps, columns, span/split, baseline grid, vertical justification, wrap, threading, overset, anchored objects, footnotes, tables, bidi, CJK (ruby, warichu, kinsoku), caret and hit testing | 11.7k |
| L2 | `images` | decoding placed graphics (PNG, JPEG, GIF, WebP, TIFF incl. CMYK, BMP, PSD composite, EPS preview) | 1.6k |
| L3 | `render` | document to pixels with vello_cpu (SIMD, multithreaded): items, composed text, images with mips, gradients, effects, damage regions, placed PDF via hayro | 3.5k |
-| L3 | `pdf` | PDF export with krilla: real text with subset fonts, CMYK and spot, bleed and marks, tagged PDF, links, forms, transitions, PDF/X-4 and PDF/A-2b | 5.0k |
+| L3 | `pdf` | PDF export through craft-pdf with Krilla: real text with subset fonts, CMYK and spot, bleed and marks, tagged PDF, links, forms, transitions, PDF/X-4 and PDF/A-2b | 5.0k |
| L3 | `idml` | IDML import and export (designmap, spreads, parents, stories, styles, graphics, preferences; CJK and Arabic attributes) | 8.0k |
| L3 | `epub` | EPUB 3 reflowable and fixed-layout export | 0.9k |
| L3 | `textimport` | Word (.docx), RTF, Excel (.xlsx), Tagged Text import; text export | 1.8k |
@@ -83,6 +83,12 @@ Native `.designcraft` (zip + JSON); IDML both ways; PDF, EPUB, HTML, PNG/JPEG, t
placed graphics through `images` (PDF/AI pages through hayro); Word/RTF/Excel/Tagged Text through
`textimport`. INDD is not readable. Details: [file-format-parity.md](file-format-parity.md).
+PDF authoring uses the independently pinned `craft-pdf` writer and patched Krilla. Document,
+booklet and merge entry points guard the full export; a failed native drawing unwind returns
+an error and incomplete backend state cannot serialize. Layout, shaping, PDF/X processing and
+print preparation remain app-owned. Reader dependencies and the UI/print pins are unchanged.
+See [pdf-backend.md](pdf-backend.md) for dependency and failure contracts.
+
## Agent control
The desktop app opens a loopback JSON-lines control channel (`--control PORT`) with
diff --git a/docs/pdf-backend.md b/docs/pdf-backend.md
new file mode 100644
index 000000000..fcc6afeaa
--- /dev/null
+++ b/docs/pdf-backend.md
@@ -0,0 +1,34 @@
+# PDF writing boundary
+
+DesignCraft pins `craft-pdf` and its patched Krilla 0.8.2 backend to craft-libs revision
+`c3487320b2d1de657b860b3c8abb44e1f2b32bd8`. The `write-pdf` capability is required for
+placed PDF pages and book merging. The ordinary reader dependencies, `craft-ui` and
+`craft-print` revisions remain unchanged by this writer migration.
+
+The shared library supplies fallible font copying/preparation, metadata setup, version and
+archival configuration, final serialization and a native unwind guard. DesignCraft retains
+layout, shaping, font choice/licensing, fallback warnings, image caches, links, tagging,
+bleed/marks, PDF/X postprocessing and export presets. A shared writer does not improve the
+format-conformance or product-parity claims by itself.
+
+`export_pdf_with_report`, `export_booklet` and `merge_pdfs` guard the whole export, including
+painting and postprocessing. A native drawing panic becomes `PdfError::Write`. A failed
+page or surface cleanup permanently poisons the backend writer, preventing successful
+serialization of an incomplete document after a narrow catch. Discard other captured app
+state after an internal failure. These guards do not catch WASM aborts, allocation aborts,
+or errors in preceding application operations such as print preparation.
+
+Cargo applies patches only from the consuming workspace root. Keep the Krilla patch and
+facade at the same full immutable commit, including Krilla reached through `krilla-svg`.
+`cargo xtask pdf-deps` verifies their resolved versions, source and uniqueness, and runs in
+`cargo xtask ci`. Publish the dependency revision before publishing this consumer branch.
+Local path replacements are suitable only for development and should not be committed.
+
+The vendored Krilla patch ledger, per-file hashes, licence texts and four unchanged CC0
+Compact ICC profiles live in craft-libs (`vendor/krilla`, `licenses/pdf-writer`, and
+`ATTRIBUTION.md`). No fonts or binary PDF fixtures are added to DesignCraft by this migration.
+
+Tests cover metadata key presence, hostile page selection, successful PDF export and native
+subprocess recovery for all three export entry points. Native/WASM export comparisons and
+independent PDF parsing/rendering supplement the repository gates. Physical printer output,
+Windows/Linux runtime and PDF/A/PDF/X certification remain separate acceptance work.
diff --git a/xtask/src/main.rs b/xtask/src/main.rs
index 4850efeae..c89b7e8d7 100644
--- a/xtask/src/main.rs
+++ b/xtask/src/main.rs
@@ -7,6 +7,7 @@ mod assets;
mod ico;
mod layers;
mod parity;
+mod pdf_deps;
mod stats;
mod version;
@@ -24,6 +25,7 @@ commands:
corpus [--download]
show where test corpora live; --download fetches PngSuite into corpus/pngsuite
stats [--exact] count tests and lines per crate (--exact: ask the test harness via `-- --list`)
+ pdf-deps verify the pinned shared PDF writer and patched Krilla
parity recompute the InDesign feature-parity summary in docs/parity-checklist.md
ico <out.ico> <in.png>...
pack square PNGs (<= 256 px) into a Windows .ico (see packaging/icons.sh)
@@ -39,6 +41,7 @@ fn main() -> ExitCode {
Some("ci") => cmd_ci(),
Some("corpus") => cmd_corpus(rest.contains(&"--download")),
Some("stats") => stats::run(&root(), rest.contains(&"--exact")),
+ Some("pdf-deps") => pdf_deps::run(&root()),
Some("parity") => parity::run(&root()),
Some("ico") => ico::run(&rest),
Some("version") => version::run(&root(), &rest),
@@ -175,6 +178,7 @@ fn cmd_ci() -> Result<(), String> {
run(c, "cargo test --workspace")
}),
),
+ ("pdf-deps", Box::new(|| pdf_deps::run(&root()))),
("assets", Box::new(|| assets::run(&root()))),
("layers", Box::new(cmd_layers)),
("wasm", Box::new(cmd_wasm)),
diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs
new file mode 100644
index 000000000..d7dfb1cb7
--- /dev/null
+++ b/xtask/src/pdf_deps.rs
@@ -0,0 +1,87 @@
+//! Check the shared writer source, including transitive users such as krilla-svg.
+use std::path::Path;
+use std::process::Command;
+
+use serde_json::Value;
+
+const REV: &str = "c3487320b2d1de657b860b3c8abb44e1f2b32bd8";
+const PACKAGES: &[(&str, &str)] = &[("craft-pdf", "0.1.0"), ("krilla", "0.8.2")];
+
+pub fn run(root: &Path) -> Result<(), String> {
+ let output = Command::new(std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into()))
+ .current_dir(root)
+ .args(["metadata", "--locked", "--format-version", "1"])
+ .output()
+ .map_err(|e| format!("cargo metadata: {e}"))?;
+ if !output.status.success() {
+ return Err(format!("cargo metadata: {}", String::from_utf8_lossy(&output.stderr)));
+ }
+ let metadata: Value = serde_json::from_slice(&output.stdout).map_err(|e| format!("cargo metadata: {e}"))?;
+ validate(&metadata)?;
+ println!("PDF writer: facade and patched Krilla resolve once to {REV}");
+ Ok(())
+}
+
+fn validate(metadata: &Value) -> Result<(), String> {
+ let packages = metadata.get("packages").and_then(Value::as_array).ok_or("cargo metadata has no packages")?;
+ let source = format!("git+https://github.com/storytold/craft-libs?rev={REV}#{REV}");
+ for (name, version) in PACKAGES {
+ let matching: Vec<_> = packages.iter().filter(|p| p.get("name").and_then(Value::as_str) == Some(name)).collect();
+ let [package] = matching.as_slice() else {
+ return Err(format!("{name}: expected one resolved package, found {}", matching.len()));
+ };
+ if package.get("version").and_then(Value::as_str) != Some(version) || package.get("source").and_then(Value::as_str) != Some(source.as_str()) {
+ return Err(format!("{name}: expected {version} from {source}; got {package}"));
+ }
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn metadata() -> Value {
+ json!({"packages": PACKAGES.iter().map(|(name, version)| json!({"name":name,"version":version,
+ "source":format!("git+https://github.com/storytold/craft-libs?rev={REV}#{REV}")})).collect::<Vec<_>>()})
+ }
+
+ #[test]
+ fn accepts_one_pinned_facade_and_writer() {
+ assert!(validate(&metadata()).is_ok());
+ }
+
+ #[test]
+ fn rejects_unpatched_and_local_writer_sources() {
+ for source in [Value::Null, json!("registry+https://github.com/rust-lang/crates.io-index")] {
+ let mut m = metadata();
+ m["packages"][1]["source"] = source;
+ assert!(validate(&m).is_err());
+ }
+ }
+
+ #[test]
+ fn rejects_missing_duplicate_and_wrong_version_packages() {
+ for index in [0, 1] {
+ let mut m = metadata();
+ m["packages"][index]["version"] = json!("99.0.0");
+ assert!(validate(&m).is_err());
+ let mut m = metadata();
+ let duplicate = m["packages"][index].clone();
+ m["packages"].as_array_mut().unwrap().push(duplicate);
+ assert!(validate(&m).is_err());
+ let mut m = metadata();
+ m["packages"].as_array_mut().unwrap().remove(index);
+ assert!(validate(&m).is_err());
+ }
+ }
+
+ #[test]
+ fn rejects_facade_revision_drift_and_malformed_metadata() {
+ let mut m = metadata();
+ m["packages"][0]["source"] = json!("git+https://github.com/storytold/craft-libs?branch=main#other");
+ assert!(validate(&m).is_err());
+ assert!(validate(&json!({})).is_err());
+ }
+}