DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
H: Image Import Options — crop placed PDFs to trim/bleed/art/media box
Brandon Thomas10dd488e7243
diff --git a/ROADMAP.md b/ROADMAP.mdindex 77866f86d..eef50ab16 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -67,6 +67,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope- Word/RTF Import Options (File ▸ Place with Import Options…, `place.styles`, `file.place {styleMap, styleConflicts}`): map imported styles onto the document's, use existing / redefine / auto-rename on conflicts, or remove formatting.- Custom anchored objects (`anchored.insert/options {position: custom}`): placed relative to the anchor, frame, column, page margins or page edge with reference points and offsets, no space in the text, keep within column; IDML Anchored position.- Variable font axes: Character panel sliders; any axis values (`fontStyle: "Bold {wght:650}"`) make that instance for layout, screen and PDF.+- Image Import Options › Crop to for placed PDFs (`file.place {pdfCrop: crop|trim|bleed|art|media}`, Place PDF dialog): the frame shows that page box.- 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/file.rs b/crates/engine/src/cmd/file.rsindex f2e270796..4567269f4 100644--- a/crates/engine/src/cmd/file.rs+++ b/crates/engine/src/cmd/file.rs@@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {"Place…",["File"],Some("Cmd+D"),- "{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?, pdfPage?: n (1-based, Image Import Options)} — places an image (into the selected empty frame if any); text files (.txt, .docx, .rtf, .md) and Excel workbooks (.xlsx, as a table) go into the insertion point, the selected frame or a new frame on `page`/`rect` — {autoflow?: adds pages with threaded frames until the text fits, removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename}",+ "{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?, pdfPage?: n (1-based, Image Import Options), pdfCrop?: crop|trim|bleed|art|media} — places an image (into the selected empty frame if any); text files (.txt, .docx, .rtf, .md) and Excel workbooks (.xlsx, as a table) go into the insertion point, the selected frame or a new frame on `page`/`rect` — {autoflow?: adds pages with threaded frames until the text fits, removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename}",has_doc,file_place),@@ -237,6 +237,17 @@ fn file_place(s: &mut Session, p: &Value) -> Result<Value> {};// 72 ppi by default unless the file says otherwise; scale so it fits the page when huge.let (nw, nh) = (pw as f64, ph as f64);+ // Image Import Options › Crop to: the frame shows that box of the PDF page.+ let crop_box = match str_param(p, "pdfCrop") {+ Some(k) if designcraft_render::is_pdf(&bytes) => {+ if !["crop", "trim", "bleed", "art", "media"].contains(&k) {+ return Err(bad("file.place", format!("unknown pdfCrop `{k}` (crop, trim, bleed, art, media)")));+ }+ designcraft_render::pdf_page_box(&bytes, pdf_page as usize, k).filter(|b| b.2 > 0.0 && b.3 > 0.0)+ }+ Some(_) => None,+ None => None,+ };let target_frame = super::id_param(p, "frame").or_else(|| {let st = s.active()?;st.selection.items.iter().copied().find(|i| st.doc.item(*i).is_some_and(|it| matches!(it.content, Content::Unassigned | Content::Graphic(_))))@@ -250,11 +261,12 @@ fn file_place(s: &mut Session, p: &Value) -> Result<Value> {let aid = AssetId(d.alloc());let mime = designcraft_render::image_mime(&bytes).to_string();d.assets.insert(aid, Arc::new(Asset { page: pdf_page, id: aid, name, mime, link, data: Arc::new(bytes), pixels: Some((pw, ph)) }));- let (w, h) = match want_w {- Some(w) => (w, w * nh / nw),+ // The width the whole page (or image) gets; the height follows the proportions.+ let w = match want_w {+ Some(w) => w,None => {let page_w = d.settings.page_width * 0.6;- if nw > page_w { (page_w, page_w * nh / nw) } else { (nw, nh) }+ nw.min(page_w)}};let id = if let Some(fid) = target_frame {@@ -277,12 +289,14 @@ fn file_place(s: &mut Session, p: &Value) -> Result<Value> {let pr = sp.pages.first().map(|pg| pg.margin_rect()).unwrap_or(Rect::new(36.0, 36.0, 300.0, 300.0));let (x, y) = (px.unwrap_or(pr.x0), py.unwrap_or(pr.y0));let id = ItemId(d.alloc());- let mut it = Item::new(id, lid, Shape::Rectangle, shapes::rectangle(Rect::new(x, y, x + w, y + h)));+ let k = w / nw;+ let (bx, by, bw, bh) = crop_box.unwrap_or((0.0, 0.0, nw, nh));+ let mut it = Item::new(id, lid, Shape::Rectangle, shapes::rectangle(Rect::new(x, y, x + bw * k, y + bh * k)));it.object_style = d.styles.default_graphic_frame.clone();it.content = Content::Graphic(Graphic {asset: aid,size: (nw, nh),- xf: Affine::translate((x, y)) * Affine::scale(w / nw),+ xf: Affine::translate((x - bx * k, y - by * k)) * Affine::scale(k),auto_fit: Default::default(),fit_align: 4,crop: [0.0; 4],@@ -517,3 +531,31 @@ fn file_revert(s: &mut Session, _: &Value) -> Result<Value> {Err(EngineError::Other("revert isn't available on the web".into()))}}++#[cfg(test)]+mod pdf_crop_tests {+ use serde_json::json;++ use crate::Session;++ #[test]+ fn place_pdf_cropped_to_its_trim_box() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute("layout.documentSetup", &json!({"bleed": 9})).unwrap();+ let b64 = s.execute("file.exportPdf", &json!({"bleed": true})).unwrap()["base64"].as_str().unwrap().to_string();+ let mut t = Session::new();+ t.execute("file.new", &json!({})).unwrap();+ let size = |t: &mut Session, crop: &str| {+ t.execute("edit.deselectAll", &json!({})).unwrap();+ let r = t.execute("file.place", &json!({"base64": b64, "name": "a.pdf", "pdfCrop": crop, "width": 630, "x": 0, "y": 0})).unwrap();+ let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap());+ t.doc().unwrap().doc.item(id).unwrap().bounds()+ };+ let full = size(&mut t, "crop");+ let trim = size(&mut t, "trim");+ assert!((full.width() - 630.0).abs() < 1e-6, "{full:?}");+ assert!((trim.width() - 612.0).abs() < 1e-3 && (trim.height() - 792.0).abs() < 1e-3, "{trim:?}");+ assert!(t.execute("file.place", &json!({"base64": b64, "name": "a.pdf", "pdfCrop": "nope"})).is_err());+ }+}diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rsindex 56d46b719..6df34390f 100644--- a/crates/render/src/lib.rs+++ b/crates/render/src/lib.rs@@ -847,6 +847,28 @@ pub fn render_pdf_page(bytes: &[u8], page: usize, max_side: u32) -> Option<PixmaSome(Pixmap::from_parts(data, pw, ph))}+/// A page box of a PDF page (`crop`, `trim`, `bleed`, `art`, `media`) as (x, y, w, h) in points+/// from the top-left of the page as rendered (its visible crop box); missing boxes fall back to the+/// crop box, as PDF readers do.+pub fn pdf_page_box(bytes: &[u8], page: usize, kind: &str) -> Option<(f64, f64, f64, f64)> {+ use hayro::hayro_syntax::object::{Rect as PRect, dict::keys};+ let pdf = hayro::hayro_syntax::Pdf::new(std::sync::Arc::new(bytes.to_vec())).ok()?;+ let p = pdf.pages().get(page)?;+ let visible = p.intersected_crop_box();+ let key: &[u8] = match kind {+ "trim" => keys::TRIM_BOX,+ "bleed" => keys::BLEED_BOX,+ "art" => keys::ART_BOX,+ "media" => return Some(rel(visible, p.media_box())),+ _ => return Some(rel(visible, visible)),+ };+ let b = p.raw().get::<PRect>(key).map(|b| b.intersect(p.media_box())).unwrap_or(visible);+ fn rel(v: PRect, b: PRect) -> (f64, f64, f64, f64) {+ (b.x0 - v.x0, v.y1 - b.y1, b.width(), b.height())+ }+ Some(rel(visible, b))+}+pub fn image_mime(bytes: &[u8]) -> &'static str {designcraft_images::mime(bytes)}diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex 4c3763191..276c29493 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -849,6 +849,24 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) {ui.label(format!("Page (1–{}):", d.n("pages").unwrap_or(1.0)));text_field(ui, &mut d, "page", 60.0);});+ ui.horizontal(|ui| {+ ui.label("Crop to:");+ let cur = d.s("crop");+ let label = |v: &str| match v {+ "trim" => "Trim",+ "bleed" => "Bleed",+ "art" => "Art",+ "media" => "Media",+ _ => "Crop",+ };+ egui::ComboBox::from_id_salt("pdf_crop").selected_text(label(&cur)).show_ui(ui, |ui| {+ for v in ["crop", "trim", "bleed", "art", "media"] {+ if ui.selectable_label(label(&cur) == label(v), label(v)).clicked() {+ d.fields.insert("crop".into(), json!(v));+ }+ }+ });+ });}"keyboardShortcuts" => keyboard_shortcuts(app, ui, &mut d),"userDictionary" => user_dictionary(app, ui, &mut d),@@ -1169,7 +1187,10 @@ pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {let hex = d.s("hex");app.run("object.color", json!({"color": hex, "target": d.s("target")}))}- "pdfImport" => app.run("file.place", json!({"path": d.s("path"), "pdfPage": d.n("page").unwrap_or(1.0).max(1.0) as u64})),+ "pdfImport" => {+ let crop = d.s("crop");+ app.run("file.place", json!({"path": d.s("path"), "pdfPage": d.n("page").unwrap_or(1.0).max(1.0) as u64, "pdfCrop": if crop.is_empty() { "crop".to_string() } else { crop }}))+ }"print" => {let pages = if d.s("range") == "all" { Value::Null } else { json!(d.s("pages")) };let printer = d.s("printer");diff --git a/docs/parity.md b/docs/parity.mdindex cdc647581..e8923fada 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -10,7 +10,7 @@ Each row of the InDesign feature catalogue is scored **D** (done), **P** (partia| Priority | Features | Done | Partial | Missing | Parity ||---|---|---|---|---|---|| P0 | 102 | 99 | 3 | 0 | 99% |-| P1 | 97 | 89 | 7 | 1 | 95% |+| P1 | 97 | 90 | 6 | 1 | 96% || P2 | 76 | 23 | 13 | 40 | 39% || Area | Parity |@@ -22,7 +22,7 @@ Each row of the InDesign feature catalogue is scored **D** (done), **P** (partia| Transform | 100% || Fill, stroke, colour | 93% || Effects & transparency | 71% |-| Placing & links | 82% |+| Placing & links | 85% || Type & text frames | 94% || Typography | 98% || Styles | 97% |@@ -177,7 +177,7 @@ Open P0 items: Preferences, Vector/page formats (PDF/AI/SVG/EPS place), Export t| Placing & links | Relink to folder / extension | P1 | D || Placing & links | Copy Links To / Package | P1 | D || Placing & links | Captions | P2 | P |-| Placing & links | Image import options | P1 | P |+| Placing & links | Image import options | P1 | D || Placing & links | Linked text/stories | P2 | M || Placing & links | Display performance | P0 | D || Placing & links | Video/audio | P2 | M |