Skip to content

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

IDML: placed PDFs keep their page and crop

aiongg0f11a4599f50
diff --git a/crates/engine/src/tests_idml.rs b/crates/engine/src/tests_idml.rs
index cc40768ea..ae466e134 100644
--- a/crates/engine/src/tests_idml.rs
+++ b/crates/engine/src/tests_idml.rs
@@ -251,3 +251,64 @@ fn named_lists_round_trip_through_idml() {
assert_eq!(st.paras[0].para.list_name.as_deref(), Some("Steps"));
assert_eq!(st.paras[0].para.start_at, Some(Some(5)));
}
+
+/// IDML says which page of a placed PDF shows and which box its graphic spans, so InDesign opens
+/// it at the same size and position; importing it back gives the same page and geometry.
+#[test]
+fn placed_pdf_page_and_crop_round_trip_through_idml() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"pages": 2})).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();
+ // Page 2, cropped to its trim box: the frame is smaller than the page with its bleed.
+ let place = json!({"base64": b64, "name": "a.pdf", "pdfPage": 2, "pdfCrop": "trim", "width": 315, "x": 20, "y": 30});
+ let r = t.execute("file.place", &place).unwrap();
+ let d = t.doc().unwrap().doc.clone();
+ let item = d.item(ItemId(r["id"].as_u64().unwrap())).unwrap();
+ let (bounds, g) = (item.bounds(), item.graphic().unwrap().clone());
+ assert_eq!(d.assets[&g.asset].page, 1);
+
+ let bytes = designcraft_idml::export_idml(&d);
+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();
+ let mut spreads = String::new();
+ for i in 0..zip.len() {
+ let mut f = zip.by_index(i).unwrap();
+ if f.name().starts_with("Spreads/") {
+ std::io::Read::read_to_string(&mut f, &mut spreads).unwrap();
+ }
+ }
+ let attr = spreads.split("<PDFAttribute ").nth(1).and_then(|a| a.split("/>").next()).expect("a PDFAttribute");
+ assert!(attr.contains(r#"PageNumber="2""#) && attr.contains(r#"PDFCrop="CropPDF""#), "{attr}");
+
+ let back = designcraft_idml::import_idml(&bytes).unwrap();
+ let bi = back.spreads.iter().flat_map(|sp| sp.items.iter()).find(|i| i.graphic().is_some()).unwrap();
+ let bg = bi.graphic().unwrap();
+ assert_eq!(back.assets[&bg.asset].page, 1);
+ let bb = bi.bounds();
+ assert!([bb.x0 - bounds.x0, bb.y0 - bounds.y0, bb.x1 - bounds.x1, bb.y1 - bounds.y1].iter().all(|v| v.abs() < 1e-3), "{bb:?} vs {bounds:?}");
+ assert!((bg.size.0 - g.size.0).abs() < 1e-3 && (bg.size.1 - g.size.1).abs() < 1e-3);
+ let (a, b) = ((bi.xf * bg.xf).as_coeffs(), (item.xf * g.xf).as_coeffs());
+ assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3), "{a:?} vs {b:?}");
+
+ // A page the PDF doesn't have imports, and the PDF export leaves it out with a warning.
+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();
+ let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
+ for i in 0..zip.len() {
+ let mut f = zip.by_index(i).unwrap();
+ let mut body = String::new();
+ std::io::Read::read_to_string(&mut f, &mut body).unwrap();
+ out.start_file(f.name(), zip::write::SimpleFileOptions::default()).unwrap();
+ std::io::Write::write_all(&mut out, body.replace(r#"PageNumber="2""#, r#"PageNumber="4294967295""#).as_bytes()).unwrap();
+ }
+ let hostile = designcraft_idml::import_idml(&out.finish().unwrap().into_inner()).unwrap();
+ assert_eq!(hostile.assets.values().map(|a| a.page).collect::<Vec<_>>(), [u32::MAX - 1]);
+ t.edit(|doc, _| {
+ *doc = hostile;
+ Ok(())
+ })
+ .unwrap();
+ let r = t.execute("file.exportPdf", &json!({})).unwrap();
+ assert!(r["warnings"].to_string().contains("has no page 4294967295"), "{r}");
+}
diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs
index 9d73562b9..00683e747 100644
--- a/crates/idml/src/export.rs
+++ b/crates/idml/src/export.rs
@@ -1802,6 +1802,17 @@ impl<'a> Ex<'a> {
.attr("ImportPolicy", "NoAutoImport")
.attr("ExportPolicy", "NoAutoExport"),
);
+ if is_pdf {
+ // The graphic spans the page's crop box (the page as it shows): InDesign's "Crop to:
+ // Crop". Without `PDFAttribute` InDesign crops the page to its visible content, which
+ // changes the graphic's size and so its scale and position.
+ el.push(
+ El::new("PDFAttribute")
+ .attr("PageNumber", asset.page.saturating_add(1))
+ .attr("PDFCrop", "CropPDF")
+ .attr("TransparentBackground", "true"),
+ );
+ }
el
}
diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs
index 5276f74cb..d639ee128 100644
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@ -2220,7 +2220,8 @@ impl<'r> Importer<'r> {
uri.as_deref().and_then(|p| p.rsplit(['/', '\\']).next()).filter(|n| !n.is_empty()).map(str::to_string).unwrap_or_else(|| "image".into());
let id = AssetId(self.alloc());
let link_path = uri.filter(|p| p.contains('/') || p.contains('\\'));
- self.assets.insert(id, Arc::new(Asset { page: 0, id, name, mime, link: link_path, data: Arc::new(data), pixels }));
+ let page = pdf_page_in(g);
+ self.assets.insert(id, Arc::new(Asset { page, id, name, mime, link: link_path, data: Arc::new(data), pixels }));
Content::Graphic(designcraft_doc::Graphic {
asset: id,
size,
@@ -2531,6 +2532,11 @@ fn path_of(pg: &El) -> PathData {
PathData::new(subs)
}
+/// The page a placed PDF shows (0-based), from its `PDFAttribute` (`PageNumber` is 1-based).
+fn pdf_page_in(g: &El) -> u32 {
+ g.find("PDFAttribute").and_then(|a| a.get("PageNumber")).and_then(|v| v.trim().parse::<u32>().ok()).map_or(0, |n| n.saturating_sub(1))
+}
+
/// IDML link URI → file system path (`file:/a%20b` → `/a b`, `file:///C:/x` → `C:/x`).
pub(crate) fn uri_to_path(uri: &str) -> String {
let rest = uri.strip_prefix("file://").or_else(|| uri.strip_prefix("file:")).unwrap_or(uri);
diff --git a/crates/idml/src/lib.rs b/crates/idml/src/lib.rs
index 71d688255..fc282e509 100644
--- a/crates/idml/src/lib.rs
+++ b/crates/idml/src/lib.rs
@@ -35,6 +35,9 @@
//! - Mixed inks, gradient stop opacity and gradient feathers, effects other than drop shadow and
//! basic feather, EPS/PDF/AI placed graphics (imported as images when the data is available),
//! clipping paths, compound-path fill rules.
+//! - Placed PDFs: the page (`PDFAttribute` `PageNumber`) round-trips and export writes
+//! `PDFCrop="CropPDF"`, the box DesignCraft draws. On import, a `PDFCrop` naming another box
+//! (trim, bleed, media, content) is not mapped: the page's crop box fills `GraphicBounds`.
//! - Unknown elements are ignored; nothing is preserved opaquely for round-trip yet.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs
index d92fc242b..05ac80adf 100644
--- a/crates/pdf/src/export.rs
+++ b/crates/pdf/src/export.rs
@@ -448,8 +448,8 @@ pub(crate) struct Exporter<'a> {
images_by_content: ImageContentCache,
#[cfg(test)]
image_conversions: usize,
- /// Placed PDFs (embedded as vector pages).
- pdfs: HashMap<AssetId, Option<krilla::pdf::PdfDocument>>,
+ /// Placed PDFs (embedded as vector pages) and their page counts.
+ pdfs: HashMap<AssetId, Option<(krilla::pdf::PdfDocument, usize)>>,
/// The PDF version written; placed PDFs must not be newer.
version: PdfVersion,
/// Placed PDFs too new to embed in this version ("name is PDF 2.0"): the export fails.
@@ -1175,7 +1175,8 @@ impl Exporter<'_> {
/// VectorCraft and most tools write 1.7. PDF 1.7 changed nothing in how a page draws, so a 1.7
/// file goes in as 1.6 (its header relabelled, as `qpdf --force-version=1.6` does). A newer
/// file is left out and the export fails naming it ([`Exporter::check_placed_versions`]).
- fn placed_pdf(&mut self, asset: &designcraft_doc::Asset) -> Option<krilla::pdf::PdfDocument> {
+ /// Returns the document with its page count.
+ fn placed_pdf(&mut self, asset: &designcraft_doc::Asset) -> Option<(krilla::pdf::PdfDocument, usize)> {
use hayro_syntax::PdfVersion as V;
let Ok(pdf) = krilla::pdf::Pdf::new(asset.data.clone()) else {
self.warn(format!("{}: can't read the placed PDF", asset.name));
@@ -1190,7 +1191,8 @@ impl Exporter<'_> {
};
let have = pdf.version();
if have <= max {
- return Some(krilla::pdf::PdfDocument::new(Arc::new(pdf)));
+ let pages = pdf.pages().len();
+ return Some((krilla::pdf::PdfDocument::new(Arc::new(pdf)), pages));
}
if have == V::Pdf17
&& max == V::Pdf16
@@ -1199,7 +1201,8 @@ impl Exporter<'_> {
&& pdf.version() <= max
{
self.warn(format!("{}: a PDF 1.7 placed in a PDF 1.6 file, embedded as PDF 1.6", asset.name));
- return Some(krilla::pdf::PdfDocument::new(Arc::new(pdf)));
+ let pages = pdf.pages().len();
+ return Some((krilla::pdf::PdfDocument::new(Arc::new(pdf)), pages));
}
let v = match have {
V::Pdf17 => "PDF 1.7",
@@ -1314,10 +1317,17 @@ impl Exporter<'_> {
p
}
};
- if let Some(placed) = placed {
- s.push_transform(&tf(g.xf));
- s.draw_pdf_page(&placed, size, asset.page as usize);
- s.pop();
+ match placed {
+ // krilla would fail the whole export at the end on a page the PDF doesn't have.
+ Some((_, pages)) if asset.page as usize >= pages => {
+ self.warn(format!("{}: the placed PDF has no page {}", asset.name, u64::from(asset.page) + 1));
+ }
+ Some((placed, _)) => {
+ s.push_transform(&tf(g.xf));
+ s.draw_pdf_page(&placed, size, asset.page as usize);
+ s.pop();
+ }
+ None => {}
}
return;
}