Skip to content

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

X: Print Booklet — saddle-stitch and 2-up printer spreads as PDF

Brandon Thomasc9b969a60df0
diff --git a/ROADMAP.md b/ROADMAP.md
index b0b8f8a45..8db5b0a6d 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -48,6 +48,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope
- Conditional text (`condition.new/options/delete/apply/list`, Conditional Text panel): hidden conditions drop their text from layout and exports, indicators underline on screen, IDML Condition/AppliedConditions.
- Endnotes (`endnote.insert/edit/delete/list/options`, Type ▸ Insert Endnote): references number through the document, the endnote frame on a new last page lists them under a heading; IDML keeps the listed text only.
- Editorial notes (`note.new/edit/delete/convertToText/list`, Notes panel): anchored in text, flagged on screen, never printed or exported.
+- File ▸ Print Booklet (`file.printBooklet`): saddle-stitch or 2-up consecutive printer spreads as PDF, padded with blanks, with a gap between pages.
- Drag and drop text editing: drag selected text to move it (Alt copies) with its formatting (`text.release`).
- Image Import Options: place any page of a multi-page PDF (`file.place {pdfPage}`; the app asks which page), shown on screen and embedded as that page in PDF export.
- Define Lists: named numbered lists that continue across stories in page order (`list.define`, paragraph `listName` / `startAt`), round-tripped through IDML; `null` in `type.para` / `type.char` now removes an override.
diff --git a/crates/engine/src/cmd/export.rs b/crates/engine/src/cmd/export.rs
index f1735a4a4..acd472c1b 100644
--- a/crates/engine/src/cmd/export.rs
+++ b/crates/engine/src/cmd/export.rs
@@ -14,6 +14,9 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!(noundo "file.exportEpub", "Export EPUB (Reflowable)…", ["File"], None,
"{path?, title?, author?, language?: \"en\"} → {path, bytes} (no path: {base64, bytes})",
has_doc, export_epub),
+ cmd!(noundo "file.printBooklet", "Print Booklet…", ["File"], None,
+ "{path?, type?: saddleStitch|twoUpConsecutive, spaceBetween? (pt)} — printer spreads as PDF (pages imposed in booklet order) → {path, bytes, sheets} (no path: {base64, …})",
+ has_doc, print_booklet),
cmd!(noundo "file.exportHtml", "Export HTML…", ["File"], None,
"{path?, title?, language?} — one self-contained page (styles inline, images embedded), stories and graphics in reading order → {path, bytes} (no path: {text, bytes})",
has_doc, export_html),
@@ -23,6 +26,26 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
+fn print_booklet(s: &mut Session, p: &Value) -> Result<Value> {
+ const ID: &str = "file.printBooklet";
+ let kind = match str_param(p, "type").unwrap_or("saddleStitch") {
+ "saddleStitch" => designcraft_pdf::BookletKind::SaddleStitch,
+ "twoUpConsecutive" | "twoUp" => designcraft_pdf::BookletKind::TwoUpConsecutive,
+ t => return Err(bad(ID, format!("unknown type `{t}` (saddleStitch, twoUpConsecutive)"))),
+ };
+ let opts = designcraft_pdf::BookletOptions { kind, space_between: p.get("spaceBetween").and_then(Value::as_f64).unwrap_or(0.0), title: None };
+ let st = s.doc()?;
+ let r = designcraft_pdf::export_booklet(&st.doc, &s.cache, &opts).map_err(|e| EngineError::Other(e.to_string()))?;
+ match str_param(p, "path") {
+ Some(path) => {
+ #[cfg(not(target_arch = "wasm32"))]
+ std::fs::write(path, &r.bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
+ Ok(json!({"path": path, "bytes": r.bytes.len(), "sheets": r.pages, "warnings": r.warnings}))
+ }
+ None => Ok(json!({"base64": super::file::base64_encode(&r.bytes), "bytes": r.bytes.len(), "sheets": r.pages, "warnings": r.warnings})),
+ }
+}
+
fn export_html(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let opts =
@@ -230,3 +253,37 @@ mod variable_font_tests {
assert!(fonts.to_string().contains("Black"), "{fonts}");
}
}
+
+#[cfg(test)]
+mod booklet_tests {
+ use serde_json::json;
+
+ use crate::Session;
+
+ #[test]
+ fn booklet_imposes_pages_in_pairs() {
+ use designcraft_pdf::{BookletKind, booklet_pairs};
+ assert_eq!(booklet_pairs(8, BookletKind::SaddleStitch), [(Some(7), Some(0)), (Some(1), Some(6)), (Some(5), Some(2)), (Some(3), Some(4))]);
+ assert_eq!(booklet_pairs(6, BookletKind::SaddleStitch)[0], (None, Some(0)), "padded with blanks");
+ assert_eq!(booklet_pairs(3, BookletKind::TwoUpConsecutive), [(Some(0), Some(1)), (Some(2), None)]);
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"pages": 4})).unwrap();
+ let r = s.execute("file.printBooklet", &json!({"spaceBetween": 18})).unwrap();
+ assert_eq!(r["sheets"], 2);
+ let pdf = String::from_utf8_lossy(&super::super::file::base64_decode(r["base64"].as_str().unwrap())).into_owned();
+ let mb = pdf.find("/MediaBox").map(|i| pdf[i..i + 40].to_string()).unwrap_or_default();
+ assert!(mb.contains("1242"), "two 612 pt pages and an 18 pt gap: {mb}");
+ assert!(s.execute("file.printBooklet", &json!({"type": "perfectBound"})).is_err());
+ // Page 1's black box lands on the right half of the first sheet (page 4 is on the left).
+ let id = s.execute("frame.create", &json!({"rect": [100, 100, 300, 300]})).unwrap()["id"].clone();
+ s.execute("object.fill", &json!({"swatch": "[Black]", "ids": [id]})).unwrap();
+ let r = s.execute("file.printBooklet", &json!({})).unwrap();
+ let bytes = super::super::file::base64_decode(r["base64"].as_str().unwrap());
+ let px = designcraft_render::decode_pixmap_page(&bytes, 0).expect("rasterised");
+ let (w, h) = (px.width() as f64, px.height() as f64);
+ let at = |x: f64, y: f64| px.sample((x / 1224.0 * w) as u16, (y / 792.0 * h) as u16);
+ let (ink, blank) = (at(612.0 + 200.0, 200.0), at(200.0, 200.0));
+ assert!(ink.a > 200 && ink.r < 60, "right half has page 1: {ink:?}");
+ assert!(blank.a < 30 || blank.r > 200, "left half (page 4) is empty: {blank:?}");
+ }
+}
diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs
index 9a030b345..e16ab00d6 100644
--- a/crates/pdf/src/export.rs
+++ b/crates/pdf/src/export.rs
@@ -204,6 +204,105 @@ pub fn export_pdf_with_report(doc: &Document, cache: &Cache, opts: &PdfOptions)
Ok(ExportReport { bytes, pages: sheets.len(), warnings })
}
+/// File › Print Booklet: how pages pair up on printer spreads.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum BookletKind {
+ /// Folded and stapled: pages padded to a multiple of 4, outer pages together.
+ #[default]
+ SaddleStitch,
+ /// Two pages side by side in reading order.
+ TwoUpConsecutive,
+}
+
+#[derive(Clone, Debug, Default)]
+pub struct BookletOptions {
+ pub kind: BookletKind,
+ /// Gap between the two pages of a printer spread (points).
+ pub space_between: f64,
+ pub title: Option<String>,
+}
+
+/// The printer spreads for `n` pages: (left, right) absolute page indices, `None` = blank.
+pub fn booklet_pairs(n: usize, kind: BookletKind) -> Vec<(Option<usize>, Option<usize>)> {
+ let page = |i: usize| (i < n).then_some(i);
+ match kind {
+ BookletKind::TwoUpConsecutive => (0..n.div_ceil(2)).map(|k| (page(2 * k), page(2 * k + 1))).collect(),
+ BookletKind::SaddleStitch => {
+ let m = n.div_ceil(4).max(1) * 4;
+ (0..m / 2).map(|i| if i % 2 == 0 { (page(m - 1 - i), page(i)) } else { (page(i), page(m - 1 - i)) }).collect()
+ }
+ }
+}
+
+/// An imposed PDF: two document pages per sheet, in booklet order.
+pub fn export_booklet(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 mut ex = Exporter {
+ doc,
+ cache,
+ opts: &pdf_opts,
+ clip: Rect::ZERO,
+ warnings: Vec::new(),
+ images: HashMap::new(),
+ pdfs: HashMap::new(),
+ svgs: HashMap::new(),
+ fonts: HashMap::new(),
+ reverse_cmaps: HashMap::new(),
+ rgb_only: false,
+ tags: Vec::new(),
+ story_tags: HashMap::new(),
+ };
+ let pairs = booklet_pairs(n, opts.kind);
+ // Sheet size from the largest page.
+ let (mut pw, mut ph) = (0.0f64, 0.0f64);
+ for i in 0..n {
+ if let Some((si, pi)) = doc.page_loc(i) {
+ let p = &doc.spreads[si].pages[pi];
+ pw = pw.max(p.width);
+ ph = ph.max(p.height);
+ }
+ }
+ let gap = opts.space_between.max(0.0);
+ let size = Size::from_wh((2.0 * pw + gap) as f32, ph as f32).ok_or(PdfError::NoPages)?;
+ for (left, right) in &pairs {
+ let mut page = pdf.start_page_with(PageSettings::new(size));
+ let mut s = page.surface();
+ 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];
+ let r = Rect::new(p.x, 0.0, p.x + p.width, p.height);
+ // Pages narrower than the slot sit against the fold.
+ let dx = if slot == 0.0 { pw - p.width } else { 0.0 };
+ s.push_transform(&tf(Affine::translate((slot + dx - p.x, (ph - p.height) / 2.0))));
+ ex.clip = r;
+ if let Some(clip) = to_path(&r.to_path(0.1)) {
+ s.push_clip_path(&clip, &FillRule::NonZero);
+ ex.spread(&mut s, si);
+ s.pop();
+ }
+ s.pop();
+ }
+ s.finish();
+ page.finish();
+ }
+ let bytes = pdf.finish().map_err(|e| PdfError::Write(format!("{e:?}")))?;
+ let mut warnings = ex.warnings;
+ warnings.dedup();
+ Ok(ExportReport { bytes, pages: pairs.len(), warnings })
+}
+
#[cfg(not(target_arch = "wasm32"))]
fn now_unix() -> Option<i64> {
use std::time::{SystemTime, UNIX_EPOCH};
diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs
index 646b5894f..1ad30be9c 100644
--- a/crates/pdf/src/lib.rs
+++ b/crates/pdf/src/lib.rs
@@ -30,7 +30,7 @@ mod links;
mod marks;
mod text;
-pub use export::{export_pdf, export_pdf_with_report};
+pub use export::{BookletKind, BookletOptions, booklet_pairs, export_booklet, export_pdf, export_pdf_with_report};
/// PDF standard to target.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 8fb6f7a73..4b4be09ac 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -19,6 +19,7 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[
("app.exportIdml", "Export IDML…", None, "{path?} — InDesign Markup (IDML) package"),
("app.exportEpub", "Export EPUB…", None, "{path?} — reflowable EPUB 3"),
("app.exportHtml", "Export HTML…", None, "{path?} — one self-contained web page"),
+ ("app.printBooklet", "Print Booklet…", None, "{path?} — saddle-stitched printer spreads as PDF"),
("app.qrCode", "Generate QR Code…", None, "{} — the QR Code dialog (object.qrCode does the work)"),
("app.exportText", "Export Text…", None, "{path?} — the story being edited, as Text Only (.txt) or Rich Text Format (.rtf)"),
("app.exportPdf", "Export PDF…", None, "{path?, …file.exportPdf options} — asks for a path when none is given"),
@@ -104,6 +105,7 @@ pub const MENUS: &[(&str, &[&str])] = &[
"-",
"ui:app.exportPdf",
"ui:app.packageDialog",
+ "ui:app.printBooklet",
"ui:app.exportPng",
"ui:app.exportIdml",
"ui:app.exportEpub",
@@ -539,6 +541,7 @@ pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value,
"app.exportIdml" => export_idml(app, p),
"app.exportEpub" => export_bytes(app, p, "epub", "file.exportEpub"),
"app.exportHtml" => export_bytes(app, p, "html", "file.exportHtml"),
+ "app.printBooklet" => export_bytes(app, p, "pdf", "file.printBooklet"),
"app.qrCode" => {
app.ui.dialog = Some(crate::dialogs::Dialog::new("qrCode", json!({})));
Ok(Value::Null)
diff --git a/docs/parity.md b/docs/parity.md
index 939b949ab..4253ed101 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -11,7 +11,7 @@ Each row of the InDesign feature catalogue is scored **D** (done), **P** (partia
|---|---|---|---|---|---|
| P0 | 102 | 99 | 3 | 0 | 99% |
| P1 | 97 | 75 | 20 | 2 | 88% |
-| P2 | 76 | 18 | 13 | 45 | 32% |
+| P2 | 76 | 19 | 13 | 44 | 34% |
| Area | Parity |
|---|---|
@@ -29,7 +29,7 @@ Each row of the InDesign feature catalogue is scored **D** (done), **P** (partia
| Tables | 88% |
| Long documents | 88% |
| Interactivity & digital | 45% |
-| Output & production | 70% |
+| Output & production | 75% |
| XML & automation | 50% |
| View & navigation | 82% |
| Undo, history, saving | 100% |
@@ -279,7 +279,7 @@ Open P0 items: Preferences, Vector/page formats (PDF/AI/SVG/EPS place), Export t
| Output & production | Export to PDF (print) | P0 | P |
| Output & production | Interactive PDF | P2 | P |
| Output & production | Print dialog | P1 | D |
-| Output & production | Print booklet | P2 | M |
+| Output & production | Print booklet | P2 | D |
| Output & production | Package | P1 | D |
| Output & production | Preflight | P1 | D |
| Output & production | Export JPEG/PNG | P1 | D |