Skip to content

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

Merge #511: Place: PDF pages and SVGs keep their exact size

aiongg5bc95946794e
diff --cc crates/engine/src/cmd/file.rs
index f235a4258,3a2885ce3..a0bf1f897
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@@ -423,25 -313,19 +423,26 @@@ fn file_place(s: &mut Session, p: &Valu
.map(|(w, h)| (w.round().max(1.0) as u32, h.round().max(1.0) as u32))
.ok_or_else(|| bad("file.place", "can't read that PDF page"))?,
};
- // 72 ppi by default unless the file says otherwise; scale so it fits the page when huge.
- let (nw, nh) = eps_size.unwrap_or((pw as f64, ph as f64));
+ // 72 ppi by default unless the file says otherwise; scale so it fits the page when huge. PDF pages
+ // and SVGs keep their exact size: rounding it to whole points would stretch them unevenly.
+ let (nw, nh) = eps_size.or_else(|| designcraft_render::natural_size(&bytes, pdf_page as usize)).unwrap_or((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)
+ // Image Import Options › Crop to: the graphic spans that box of the PDF page.
+ let is_pdf = designcraft_render::is_pdf(&bytes);
+ let pdf_crop = match str_param(p, "pdfCrop") {
+ Some(k) if is_pdf => PdfCrop::from_name(k)
+ .ok_or_else(|| bad("file.place", format!("unknown pdfCrop `{k}` (crop, art, trim, bleed, media, contentVisible, contentAll)")))?,
+ _ => PdfCrop::Crop,
+ };
+ let mime = designcraft_render::image_mime(&bytes).to_string();
+ let mut asset = Asset { page: pdf_page, name, mime, link, data: Arc::new(bytes), pixels: Some((pw, ph)), pdf_crop, ..Default::default() };
+ // The graphic's natural size: the box in points (the whole page when the box can't be found,
+ // and then the document says so).
+ let (bw, bh) = match crop_pdf(&mut asset) {
+ Some(size) => size,
+ None => {
+ asset.pdf_crop = PdfCrop::Crop;
+ (nw, nh)
}
- Some(_) => None,
- None => None,
};
let target_frame = super::id_param(p, "frame").or_else(|| {
let st = s.active()?;
@@@ -570,20 -441,17 +571,21 @@@ pub(crate) fn read_source(p: &Value) -
fn place_load(s: &mut Session, p: &Value) -> Result<Value> {
let (bytes, name, link) = read_source(p)?;
let (pw, ph) = designcraft_render::image_size(&bytes).ok_or_else(|| bad("place.load", "unsupported or corrupt image"))?;
+ let natural = designcraft_render::natural_size(&bytes, 0).unwrap_or((pw as f64, ph as f64));
let aid = s.edit(|d, _| {
- let aid = AssetId(d.alloc());
+ let fresh = AssetId(d.alloc());
let mime = designcraft_render::image_mime(&bytes).to_string();
- d.assets.insert(
- aid,
- Arc::new(Asset { page: 0, id: aid, name: name.clone(), mime, link: link.clone(), data: Arc::new(bytes), pixels: Some((pw, ph)) }),
- );
- Ok(aid)
+ Ok(d.add_asset(Asset {
+ id: fresh,
+ name: name.clone(),
+ mime,
+ link: link.clone(),
+ data: Arc::new(bytes),
+ pixels: Some((pw, ph)),
+ ..Default::default()
+ }))
})?;
- s.loaded = Some((aid, (pw as f64, ph as f64)));
+ s.loaded = Some((aid, natural));
s.set_tool("placeGun");
Ok(json!({"asset": aid.0, "name": name, "width": pw, "height": ph}))
}
@@@ -889,57 -692,23 +891,75 @@@ mod pdf_crop_tests
assert!(t.execute("file.place", &json!({"base64": b64, "name": "a.pdf", "pdfCrop": "nope"})).is_err());
}
+ /// Placing with `trim` stores the choice; the graphic spans the trim box and draws only it,
+ /// even in a frame larger than the graphic.
+ #[test]
+ fn a_pdf_placed_with_its_trim_box_stores_and_draws_that_box() {
+ // Letter with a 9 pt bleed: black in the bleed's top-left corner and a black square inside.
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ s.execute("layout.documentSetup", &json!({"bleed": 9})).unwrap();
+ for rect in [[-9, -9, 0, 0], [10, 10, 30, 30]] {
+ let id = s.execute("frame.create", &json!({"rect": rect})).unwrap()["id"].clone();
+ s.execute("object.fill", &json!({"ids": [id], "swatch": "[Black]"})).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();
+ // `width` is the whole page's (630 pt with its bleed): half size.
+ let r = t.execute("file.place", &json!({"base64": b64, "name": "a.pdf", "pdfCrop": "trim", "width": 315, "x": 100, "y": 100})).unwrap();
+ let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap());
+ let d = t.doc().unwrap().doc.clone();
+ let it = d.item(id).unwrap();
+ let g = it.graphic().unwrap().clone();
+ let a = &d.assets[&g.asset];
+ assert_eq!(a.pdf_crop, designcraft_doc::PdfCrop::Trim);
+ let b = a.shown_box().unwrap();
+ let want = [9.0 / 630.0, 9.0 / 810.0, 621.0 / 630.0, 801.0 / 810.0];
+ assert!(b.iter().zip(want).all(|(x, y)| (x - y).abs() < 1e-4), "{b:?}");
+ assert!((g.size.0 - 612.0).abs() < 1e-3 && (g.size.1 - 792.0).abs() < 1e-3, "{:?}", g.size);
+ let shown = (it.xf * g.xf).transform_rect_bbox(designcraft_geom::Rect::new(0.0, 0.0, g.size.0, g.size.1));
+ let fb = it.bounds();
+ for (x, y) in [(shown.x0, 100.0), (shown.y0, 100.0), (shown.x1, 406.0), (shown.y1, 496.0), (fb.x1, 406.0), (fb.y1, 496.0)] {
+ assert!((x - y).abs() < 1e-3, "{shown:?} {fb:?}");
+ }
+
+ // A frame larger than the graphic still shows only the trim box.
+ t.edit(|d, _| {
+ d.item_mut(id).unwrap().path = designcraft_geom::shapes::rectangle(designcraft_geom::Rect::new(90.0, 90.0, 416.0, 506.0));
+ Ok(())
+ })
+ .unwrap();
+ let d = t.doc().unwrap().doc.clone();
+ let mut rr = designcraft_render::Renderer::new();
+ rr.threads = 0;
+ let img = rr.render_page(&d, &t.cache, 0, 1.0, false, &Default::default()).unwrap();
+ let dark = |x: u32, y: u32| img.pixel(x, y)[0] < 60;
+ // The page sits at 95.5: its bleed corner (95.5–100) is cut off, the square (105–115) shows
+ // where it is on the page.
+ assert!(!dark(97, 97), "the bleed is outside the trim box");
+ assert!(!dark(103, 103), "the page is offset by its bleed");
+ assert!(dark(110, 110), "the square inside the trim box");
+ }
++
+ #[test]
+ fn placed_pdf_keeps_its_exact_page_size() {
+ // A 100.4 x 50.4 pt page placed 100.4 pt wide is 50.4 pt tall, not stretched to whole points.
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 100.4, "height": 50.4, "pages": 1})).unwrap();
+ let b64 = s.execute("file.exportPdf", &json!({})).unwrap()["base64"].as_str().unwrap().to_string();
+ let mut t = Session::new();
+ t.execute("file.new", &json!({})).unwrap();
+ let r = t.execute("file.place", &json!({"base64": b64, "name": "a.pdf", "width": 100.4, "x": 0, "y": 0})).unwrap();
+ let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap());
+ let d = &t.doc().unwrap().doc;
+ let it = d.item(id).unwrap();
+ let b = it.bounds();
+ assert!((b.width() - 100.4).abs() < 1e-3 && (b.height() - 50.4).abs() < 1e-3, "{b:?}");
+ let designcraft_doc::Content::Graphic(g) = &it.content else { panic!("not a graphic") };
+ assert!((g.size.0 - 100.4).abs() < 1e-3 && (g.size.1 - 50.4).abs() < 1e-3, "{:?}", g.size);
+ }
}
#[cfg(test)]