Skip to content

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

E: transparency flattener for PDF export (+ presets)

Brandon Thomas443812126634
diff --git a/ROADMAP.md b/ROADMAP.md
index 01793f7db..178beee96 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -91,6 +91,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope
- Live Distribute (Space while dragging a selection handle; `transform.resize {distribute}`): objects keep their size and spread with the bounds.
- Liquid Layout (`liquid.pageRule/object`, `guide.liquid`, `layout.createAlternate`, Liquid Layout panel): scale / re-center / guide-based / object-based page rules applied on page resize and Document Setup; dashed liquid guides; alternate layouts as resized page copies in a named section. Alternate layouts aren't linked to their source.
- Split Window / New Window (`window.split`, `window.newWindow`, Window ▸ Arrange): two side-by-side views of the document with their own zoom, scroll and render cache. New Window opens that second view rather than a separate OS window.
+- Transparency flattener (`file.exportPdf {flatten: high|medium|low|ppi}`, Edit ▸ Transparency Flattener Presets): spreads with transparency are rasterised per page in the exported PDF. It doesn't yet keep text and vectors outside transparent areas.
- 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 acd472c1b..94219622c 100644
--- a/crates/engine/src/cmd/export.rs
+++ b/crates/engine/src/cmd/export.rs
@@ -9,7 +9,7 @@ use crate::{EngineError, Result, Session};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(noundo "file.exportPdf", "Export PDF…", ["File"], None,
- "{path?, pages?: \"1-3,5\" | [1,3] (1-based positions; default all), spreads?: bool, 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), 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, 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), title?, author?} → {path, bytes, pages, warnings} (no path: {base64, …})",
has_doc, export_pdf),
cmd!(noundo "file.exportEpub", "Export EPUB (Reflowable)…", ["File"], None,
"{path?, title?, author?, language?: \"en\"} → {path, bytes} (no path: {base64, bytes})",
@@ -161,10 +161,97 @@ pub(crate) fn options(p: &Value, page_count: usize) -> Result<PdfOptions> {
})
}
+/// Does this object (or anything in it) need the transparency flattener?
+fn transparent(it: &designcraft_doc::Item) -> bool {
+ it.opacity < 1.0 || it.blend != Default::default() || it.effects.any() || it.knockout || it.children().iter().any(|c| transparent(c))
+}
+
+/// Transparency Flattener: spreads with transparency become one raster per page at `ppi`
+/// (in a copy of the document made for export). Returns the copy and the flattened page count.
+fn flatten(d: &designcraft_doc::Document, cache: &designcraft_compose::Cache, ppi: f64) -> (designcraft_doc::Document, usize) {
+ use designcraft_doc::{Asset, AssetId, Content, Graphic, Item, ItemId, Shape, SpreadRef};
+ let mut out = d.clone();
+ let mut n = 0;
+ let mut rr = designcraft_render::Renderer::new();
+ rr.threads = designcraft_render::default_threads();
+ let k = ppi / 72.0;
+ let parent_transparent = |pid: Option<designcraft_doc::SpreadId>| {
+ pid.and_then(|id| d.parents.iter().find(|p| p.id == id)).is_some_and(|p| p.items.iter().any(|it| transparent(it)))
+ };
+ for (si, sp) in d.spreads.iter().enumerate() {
+ if !sp.items.iter().any(|it| transparent(it)) && !sp.pages.iter().any(|pg| pg.show_parent_items && parent_transparent(pg.parent)) {
+ continue;
+ }
+ let first = d.first_page_of_spread(si);
+ let mut images = Vec::new();
+ for (pi, pg) in sp.pages.iter().enumerate() {
+ if let Some(img) = rr.render_page(d, cache, first + pi, k, false, &Default::default()) {
+ images.push((pg.bounds(), img));
+ }
+ }
+ let lid = out.default_layer();
+ let osp = std::sync::Arc::make_mut(&mut out.spreads[si]);
+ osp.items.clear();
+ for pg in &mut osp.pages {
+ pg.show_parent_items = false;
+ }
+ for (b, img) in images {
+ let (w, h) = (img.width, img.height);
+ let aid = AssetId(out.alloc());
+ out.assets.insert(
+ aid,
+ std::sync::Arc::new(Asset {
+ page: 0,
+ id: aid,
+ name: format!("flattened-{}.png", aid.0),
+ mime: "image/png".into(),
+ link: None,
+ data: std::sync::Arc::new(img.to_png()),
+ pixels: Some((w, h)),
+ }),
+ );
+ let id = ItemId(out.alloc());
+ let mut it = Item::new(id, lid, Shape::Rectangle, designcraft_geom::shapes::rectangle(b));
+ it.content = Content::Graphic(Graphic {
+ asset: aid,
+ size: (w as f64, h as f64),
+ xf: designcraft_geom::Affine::translate((b.x0, b.y0))
+ * designcraft_geom::Affine::scale_non_uniform(b.width() / w as f64, b.height() / h as f64),
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ });
+ it.stroke.weight = 0.0;
+ let _ = out.insert_item(SpreadRef::Doc(si), it, None);
+ n += 1;
+ }
+ }
+ (out, n)
+}
+
fn export_pdf(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let opts = options(p, st.doc.page_count())?;
- let r = designcraft_pdf::export_pdf_with_report(&st.doc, &s.cache, &opts).map_err(|e| EngineError::Other(e.to_string()))?;
+ // Transparency Flattener presets: High / Medium / Low Resolution, or a ppi.
+ let ppi = match p.get("flatten") {
+ None | Some(Value::Null) | Some(Value::Bool(false)) => None,
+ Some(Value::String(s)) if s == "high" => Some(300.0),
+ Some(Value::String(s)) if s == "medium" => Some(150.0),
+ Some(Value::String(s)) if s == "low" => Some(72.0),
+ Some(Value::Bool(true)) => Some(300.0),
+ Some(v) => Some(
+ 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));
+ let doc: &designcraft_doc::Document = flattened.as_ref().map_or(&st.doc, |f| &f.0);
+ let r = designcraft_pdf::export_pdf_with_report(doc, &s.cache, &opts).map_err(|e| EngineError::Other(e.to_string()))?;
+ let mut r = r;
+ if let Some((_, n)) = &flattened
+ && *n > 0
+ {
+ r.warnings.push(format!("transparency flattened: {n} page(s) rasterised"));
+ }
match str_param(p, "path") {
Some(path) => {
write_file(path, &r.bytes)?;
@@ -189,6 +276,26 @@ mod text_tests {
use crate::Session;
+ #[test]
+ fn flattener_rasterises_spreads_with_transparency() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"pages": 3})).unwrap();
+ 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();
+ // Opaque: nothing to flatten.
+ let r = s.execute("file.exportPdf", &json!({"flatten": "low"})).unwrap();
+ assert!(r["warnings"].as_array().unwrap().iter().all(|w| !w.as_str().unwrap().contains("flattened")));
+ s.execute("object.opacity", &json!({"ids": [id], "opacity": 0.5})).unwrap();
+ let r = s.execute("file.exportPdf", &json!({"flatten": "low"})).unwrap();
+ assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("flattened: 1 page")), "{r}");
+ assert_eq!(r["pages"], 3);
+ let bytes = super::super::file::base64_decode(r["base64"].as_str().unwrap());
+ assert_eq!(designcraft_render::pdf_page_count(&bytes), Some(3));
+ // The document itself is untouched.
+ assert!(s.doc().unwrap().doc.item(designcraft_doc::ItemId(id.as_u64().unwrap())).is_some());
+ assert!(s.execute("file.exportPdf", &json!({"flatten": 5})).is_err());
+ }
+
#[test]
fn export_story_as_text_and_rtf() {
let mut s = Session::new();
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 11062b926..3cb7f3a4a 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -102,6 +102,8 @@ pub struct UiState {
/// Edit › Menus: hidden menu items (`menu/label`), and Show Full Menus.
pub hidden_menu_items: Vec<String>,
pub show_full_menus: bool,
+ /// Edit › Transparency Flattener Presets: "" (none), "high", "medium" or "low" for PDF export.
+ pub flattener: String,
/// View › Separations Preview: a process plate (0–3) and/or an ink limit (total, 0–4).
#[serde(skip)]
pub separation: Option<u8>,
@@ -169,6 +171,7 @@ impl Default for UiState {
tagged_frames: false,
hidden_menu_items: Vec::new(),
show_full_menus: false,
+ flattener: String::new(),
separation: None,
ink_limit: None,
display_quality: designcraft_render::DisplayQuality::High,
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 2c9951da8..7c7e3b01e 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -26,6 +26,12 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[
("app.fittingOptions", "Frame Fitting Options…", None, "{} — the dialog for object.fittingOptions"),
("app.menus", "Menus…", None, "{} — show or hide menu items"),
("window.hideMenuItem", "Hide Menu Item", None, "{item: \"Menu/Label\", hidden?: bool}"),
+ (
+ "app.flattener",
+ "Transparency Flattener Presets",
+ None,
+ "{preset: \"\"|high|medium|low} — PDF export rasterises spreads with transparency at 300 / 150 / 72 ppi",
+ ),
("app.graphicCell", "Convert Cell to Graphic Cell…", None, "{} — pick an image for the target table cell"),
("app.placeAndLink", "Place and Link", None, "{} — a linked copy of the selected frame's story, beside it"),
("app.placeWithOptions", "Place with Import Options…", Some("Cmd+Shift+D"), "{} — Word/RTF style mapping before placing"),
@@ -170,6 +176,12 @@ pub const MENUS: &[(&str, &[&str])] = &[
"cmd:edit.transparencyBlendSpace|Document RGB|{\"space\": \"rgb\"}",
"cmd:edit.transparencyBlendSpace|Document CMYK|{\"space\": \"cmyk\"}",
"<",
+ ">Transparency Flattener Presets",
+ "ui:app.flattener|None (keep transparency)|{\"preset\": \"\"}",
+ "ui:app.flattener|High Resolution|{\"preset\": \"high\"}",
+ "ui:app.flattener|Medium Resolution|{\"preset\": \"medium\"}",
+ "ui:app.flattener|Low Resolution|{\"preset\": \"low\"}",
+ "<",
"-",
"ui:app.palette",
"ui:app.keyboardShortcuts",
@@ -690,6 +702,14 @@ pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value,
None => Ok(Value::Null),
}
}
+ "app.flattener" => {
+ let v = p.get("preset").and_then(Value::as_str).unwrap_or("");
+ if !["", "high", "medium", "low"].contains(&v) {
+ return Some(Err(format!("unknown preset `{v}`")));
+ }
+ app.ui.flattener = v.to_string();
+ Ok(json!(v))
+ }
"app.graphicCell" => {
let Some(pick) = app.services.pick_open.as_mut() else { return Some(Err("needs a file picker".into())) };
match pick("place") {
@@ -1207,6 +1227,9 @@ fn export_pdf(app: &mut DesignApp, p: &Value) -> Result<Value, String> {
o.remove("path");
o.entry("bleed").or_insert(json!(true));
o.entry("tagged").or_insert(json!(true));
+ if !app.ui.flattener.is_empty() {
+ o.entry("flatten").or_insert(json!(app.ui.flattener));
+ }
}
let r = app.run("file.exportPdf", params)?;
let bytes = designcraft_engine::cmd::base64_decode(r["base64"].as_str().unwrap_or_default());
@@ -1389,6 +1412,7 @@ pub fn checked(app: &DesignApp, id: &str, params: &Value) -> Option<bool> {
"changes.track" => app.session.active().is_some_and(|d| d.doc.settings.track_changes),
"window.controlBar" => app.ui.control_bar,
"window.split" => app.split,
+ "app.flattener" => app.ui.flattener == params.get("preset").and_then(Value::as_str).unwrap_or(""),
"window.taskBar" => app.ui.task_bar,
"window.toolsDoubleColumn" => app.ui.tools_double_column,
"view.togglePreview" => app.ui.screen_mode == crate::ScreenMode::Preview,
diff --git a/docs/parity.md b/docs/parity.md
index f7f902162..57e23b467 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 | 92 | 5 | 0 | 97% |
-| P2 | 76 | 40 | 25 | 11 | 69% |
+| P2 | 76 | 40 | 26 | 10 | 70% |
| Area | Parity |
|---|---|
@@ -21,7 +21,7 @@ Each row of the InDesign feature catalogue is scored **D** (done), **P** (partia
| Frames, shapes & paths | 100% |
| Transform | 100% |
| Fill, stroke, colour | 96% |
-| Effects & transparency | 71% |
+| Effects & transparency | 75% |
| Placing & links | 90% |
| Type & text frames | 94% |
| Typography | 98% |
@@ -165,7 +165,7 @@ Open P0 items: Preferences, Vector/page formats (PDF/AI/SVG/EPS place), Export t
| Effects & transparency | Basic/Directional/Gradient Feather | P2 | P |
| Effects & transparency | Global Light | P2 | D |
| Effects & transparency | Transparency blend space | P1 | P |
-| Effects & transparency | Transparency flattener | P2 | M |
+| Effects & transparency | Transparency flattener | P2 | P |
| Placing & links | Place | P0 | D |
| Placing & links | Place into frame / by click or drag | P0 | D |
| Placing & links | Raster formats | P0 | D |