Skip to content

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

PDF: preserve placed optional-content visibility in vector exports

KnottyDyes38d692089fb3
diff --git a/ROADMAP.md b/ROADMAP.md
index 153555913..38397898c 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -132,7 +132,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope
- View ▸ Rotate Spread (`view.rotateSpread`, `layout.rotateSpreadView`): the spread in view turns in quarter turns on screen (stored with the document; output is unaffected). The canvas maps each spread through its own transform, so tools, snapping, resize handles, guides, overlays and rendering all follow the turned spread.
- Vertical type (Vertical Type Tool, Type ▸ Story Direction `type.storyDirection`, IDML StoryOrientation): the direction belongs to the story, so every frame of a thread is vertical or horizontal together and a frame threaded onto a story takes its direction (`object.textFrameOptions {vertical}` sets the frames' stories); lines run top to bottom and follow each other right to left; the arrow keys follow them (Down and Up along the line, Left and Right to the next and previous line, keeping the position along it); CJK characters stay upright and other text turns, on screen and in PDF; CJK line breaking with basic kinsoku (also in horizontal text); Korean breaks at spaces, word by word (Hangul in any language, hanja in Korean text), or between syllables when the paragraph asks for it (`type.para {koreanCharBreaks}`, Paragraph Style Options ▸ Justification; not written to IDML). Upright text is shaped top to bottom: punctuation and brackets take their vertical forms (OpenType `vert`; `vkrn` and `vpal` through OpenType features), glyphs advance by their vertical metrics (`vmtx`) and hang from their vertical origins (`VORG`) on the centre of the ideographic em box (`BASE`, else OS/2), which the first line's ascent follows; turned text keeps its horizontal forms. Tate-chu-yoko (Type ▸ Tate-Chu-Yoko, `type.tateChuYoko`, IDML `Tatechuyoko`) sets a run such as "12" side by side within one em of the line. Ruby (Type ▸ Ruby…, `type.ruby`, IDML RubyString; group ruby spread 1-2-1 or centred) and kenten emphasis dots (`type.kenten`, IDML KentenKind) are set over their text — to its right in vertical frames — without changing line breaks. Warichu and ruby options (per-character ruby, positions, overhang) aren't there yet.
- Math expressions (Type ▸ Insert Math Expression…, `math.insert`, `math.svg`): a LaTeX subset (fractions, scripts, roots, big operators with limits, Greek, relations and operators with math spacing, `\left…\right`, `\text`) typeset by our own engine into SVG, placed inline at the cursor or as a frame; the LaTeX is kept as alt text and can be edited.
-- Object Layer Options for placed PDFs (`object.pdfLayers`, `object.layerOptions`, Object ▸ Object Layer Options…): the file's optional-content layers listed and shown or hidden per frame on screen; in exported PDFs such graphics go out as 300 ppi images of their visible layers.
+- Object Layer Options for placed PDFs (`object.pdfLayers`, `object.layerOptions`, Object ▸ Object Layer Options…): the file's optional-content layers listed and shown or hidden per frame on screen; plain and PDF/X-4 exports preserve their visible layers as vectors.
- Effects: Inner Glow (edge or centre), Bevel and Emboss (inner bevel lit from the light angle), Satin (`object.innerGlow`, `object.bevel`, `object.satin`); PDF export now keeps soft effects: objects with shadows, glows, feathers, bevels or satin go out as 300 ppi transparent images of their appearance (threaded text frames excepted).
- Directional Feather (`object.directionalFeather {widths: [top, left, bottom, right]}`): each side fades over its own width.
- View ▸ Flattener Preview (`view.flattenerPreview`): objects involving transparency highlighted in red; knockout groups export as images (PDF output has no knockout groups).
@@ -387,6 +387,8 @@ Newest first.
- **2026-10-17** · Object strokes reject malformed types and unknown type fields before changing the document; command help lists every stroke kind and its required fields. No readiness percentage change.
- **2026-10-17** · Docs: documented a persistent source CLI install with Cargo, MCP-client PATH setup and bare-name server registration in `docs/mcp.md`. No readiness percentage change.
+- **2026-10-18** · Repeated placed-PDF layer variants are prepared once per asset and hidden-name set, with recovery warnings retained. All-visible named layers keep their original source bytes, including PDFs whose cross-reference tables the reader repairs, in plain, PDF/X-4, booklet and book-merge output. Layer changes that require writing still reject an unusable cross-reference table with a file-named damage error; the first placement error is retained (#906). No readiness percentage change.
+- **2026-10-18** · Placed PDF optional-content defaults and per-frame overrides survive plain and PDF/X-4 vector export, including repeated placements, booklet output and book merging (#906). Source usage-application arrays are accepted; groups without a catalog configuration stay visible. Missing or unreadable default configurations and unsupported base states use all-ON defaults with a file-named export warning, retaining explicit frame overrides. Readable groups omitted from the catalog list are added with a distinct file-named warning, preserving their default ON/OFF states. Concurrent recovery warnings are combined. Malformed ON data is recoverable when a known ON base and empty OFF list prove it cannot hide artwork; missing display names are generated without changing known visibility when no override needs name matching. Contradictory states, unresolved references and ambiguous name overrides still fail export. Print-usage adjustments and IDML layer overrides remain follow-ups. No readiness percentage change.
- **2026-10-16** · Selection: drag a column guide to move its gutter, as in InDesign (#1096). Both guides of the gutter move together and keep its width, stop at the neighbouring guides and the margins, and snap to the document grid, guides and objects, or with Shift to the ruler's tick marks; Escape cancels and the drag is one undo step. Locked column guides (the default) are not picked. A document page takes the result as its own columns; on a parent page it passes to the pages that follow it. `layout.moveColumnGuide` does the same over the control channel and MCP. No readiness percentage change.
- **2026-10-16** · Layout: Margins and Columns keeps dragged column guides unless the column count or gutter changes (#1096). The dialog sends every field on OK, so a margin-only change re-divided the columns evenly. Margin changes keep the positions; the columns follow them only while they fit the margin box. No readiness percentage change.
- **2026-10-16** · Layout: autoflow, inserted pages and new parents follow dragged column guides (#1096). Autoflow sets one frame per dragged column and counts the pages it adds from them; Insert Pages and New Parent keep the custom positions with the column count and gutter; `document.inspect` reports each page's gutter, column rects and whether its columns are custom. No readiness percentage change.
diff --git a/crates/engine/src/cmd/export.rs b/crates/engine/src/cmd/export.rs
index 551dd7484..52886c33c 100644
--- a/crates/engine/src/cmd/export.rs
+++ b/crates/engine/src/cmd/export.rs
@@ -733,9 +733,8 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result<Value> {
),
};
let flattened = ppi.map(|ppi| flatten(&st.doc, &s.cache, ppi));
- // Placed PDFs with hidden layers go out as images showing just their visible layers.
let base: &designcraft_doc::Document = flattened.as_ref().map_or(&st.doc, |f| &f.0);
- let (layered, layer_count) = rasterize_layered(base)?;
+ let (layered, layer_count) = if opts.standard == Standard::PdfA2b { rasterize_layered(base)? } else { (None, 0) };
let base2: &designcraft_doc::Document = layered.as_ref().unwrap_or(base);
let (fx_doc, fx_count) = rasterize_effects(base2, &s.cache);
let doc: &designcraft_doc::Document = fx_doc.as_ref().unwrap_or(base2);
diff --git a/crates/engine/src/cmd/pdflayers.rs b/crates/engine/src/cmd/pdflayers.rs
index 937fe81c0..c2543c3f2 100644
--- a/crates/engine/src/cmd/pdflayers.rs
+++ b/crates/engine/src/cmd/pdflayers.rs
@@ -374,8 +374,12 @@ pub(crate) mod tests {
assert!(right[0] > 200 && right[1] > 200 && right[2] > 200, "the red layer is hidden: {right:?}");
assert!(px(&s, 125)[2] > 200, "blue still shows");
assert_eq!(s.execute("object.pdfLayers", &json!({"id": id})).unwrap()[1]["visible"], false);
- // PDF export carries the choice (the graphic goes out as an image).
let r = s.execute("file.exportPdf", &json!({})).unwrap();
- assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("layer")), "{r}");
+ assert!(r["warnings"].as_array().unwrap().is_empty(), "{r}");
+ let bytes = super::super::file::base64_decode(r["base64"].as_str().unwrap());
+ let image = designcraft_render::render_pdf_page(&bytes, 0, 792).unwrap();
+ let width = usize::from(image.width());
+ assert!(image.data()[150 * width + 125].a > 200);
+ assert_eq!(image.data()[150 * width + 175].a, 0);
}
}
diff --git a/crates/engine/tests/pdf_optional_content.rs b/crates/engine/tests/pdf_optional_content.rs
new file mode 100644
index 000000000..e96e34915
--- /dev/null
+++ b/crates/engine/tests/pdf_optional_content.rs
@@ -0,0 +1,238 @@
+#[path = "support/optional_content.rs"]
+mod support;
+
+#[path = "support/optional_content_fallback.rs"]
+mod fallback;
+
+#[path = "support/optional_content_xref.rs"]
+mod xref;
+
+use designcraft_compose::Cache;
+use designcraft_pdf::{PdfOptions, Standard, export_pdf, export_pdf_with_report};
+use support::{catalog, document, fixture, painted};
+
+const DEFAULT: &str = "/BaseState/ON/OFF[6 3 R]";
+const USAGE_APPLICATIONS: &str = "/BaseState/ON/ON[5 0 R]/OFF[6 3 R]/AS[<</Event/View/Category[/View]/OCGs[5 0 R 6 3 R]>><</Event/Print/Category[/Print]/OCGs[5 0 R 6 3 R]>><</Event/Export/Category[/Export]/OCGs[5 0 R 6 3 R]>>]";
+
+#[test]
+fn source_layer_dictionaries_are_readable() {
+ let pdf = hayro_syntax::Pdf::new(fixture(DEFAULT, "Hidden")).unwrap();
+ for id in [(5, 0), (6, 3)] {
+ assert!(pdf.xref().get::<hayro_syntax::object::Dict<'_>>(hayro_syntax::object::ObjectIdentifier::new(id.0, id.1)).is_some(), "{id:?}");
+ }
+}
+
+fn exported(config: &str, standard: Standard) -> Vec<u8> {
+ let doc = document(fixture(config, "Hidden"), &[&[]]);
+ let report = export_pdf_with_report(&doc, &Cache::new(), &PdfOptions { standard, created: Some(0), ..Default::default() }).unwrap();
+ assert!(report.warnings.is_empty(), "{:?}", report.warnings);
+ report.bytes
+}
+
+#[test]
+fn source_default_off_renders_before_export() {
+ let bytes = fixture(DEFAULT, "Hidden");
+
+ painted(&bytes, &[true, false]);
+}
+
+#[test]
+fn plain_export_registers_default_off_layers() {
+ let bytes = exported(DEFAULT, Standard::None);
+
+ assert_eq!(catalog(&bytes), [("Hidden".into(), true), ("Shown".into(), false)]);
+}
+
+#[test]
+fn pdfx_export_preserves_default_off_catalog() {
+ let bytes = exported(DEFAULT, Standard::PdfX4);
+
+ assert_eq!(catalog(&bytes), [("Hidden".into(), true), ("Shown".into(), false)]);
+ assert!(designcraft_pdf::check_pdfx4(&bytes).is_empty());
+}
+
+#[test]
+fn plain_export_paints_only_the_shown_layer() {
+ let bytes = exported(DEFAULT, Standard::None);
+
+ painted(&bytes, &[true, false]);
+}
+
+#[test]
+fn pdfx_export_paints_only_the_shown_layer() {
+ let bytes = exported(DEFAULT, Standard::PdfX4);
+
+ painted(&bytes, &[true, false]);
+}
+
+#[test]
+fn plain_export_preserves_defaults_with_usage_applications() {
+ let bytes = exported(USAGE_APPLICATIONS, Standard::None);
+
+ assert_eq!(catalog(&bytes), [("Hidden".into(), true), ("Shown".into(), false)]);
+ assert_vector(&bytes);
+ painted(&bytes, &[true, false]);
+}
+
+#[test]
+fn pdfx_export_preserves_defaults_with_usage_applications() {
+ let bytes = exported(USAGE_APPLICATIONS, Standard::PdfX4);
+
+ assert_eq!(catalog(&bytes), [("Hidden".into(), true), ("Shown".into(), false)]);
+ assert!(designcraft_pdf::check_pdfx4(&bytes).is_empty());
+ assert_vector(&bytes);
+ painted(&bytes, &[true, false]);
+}
+
+#[test]
+fn plain_export_draws_groups_without_catalog_properties() {
+ let doc = document(support::orphaned_fixture(), &[&[]]);
+
+ let bytes = export_pdf(&doc, &Cache::new(), &PdfOptions::default()).unwrap();
+
+ assert_eq!(catalog(&bytes), [("Hidden".into(), false), ("Shown".into(), false)]);
+ assert_vector(&bytes);
+ painted(&bytes, &[true, true]);
+}
+
+#[test]
+fn pdfx_export_draws_groups_without_catalog_properties() {
+ let doc = document(support::orphaned_fixture(), &[&[]]);
+
+ let bytes = export_pdf(&doc, &Cache::new(), &PdfOptions { standard: Standard::PdfX4, ..Default::default() }).unwrap();
+
+ assert_eq!(catalog(&bytes), [("Hidden".into(), false), ("Shown".into(), false)]);
+ assert!(designcraft_pdf::check_pdfx4(&bytes).is_empty());
+ assert_vector(&bytes);
+ painted(&bytes, &[true, true]);
+}
+
+#[test]
+fn base_off_with_on_exception_is_preserved() {
+ let bytes = exported("/BaseState/OFF/ON[5 0 R]", Standard::None);
+
+ assert_eq!(catalog(&bytes), [("Hidden".into(), true), ("Shown".into(), false)]);
+ painted(&bytes, &[true, false]);
+}
+
+#[test]
+fn same_asset_placements_keep_opposing_layer_states() {
+ let doc = document(fixture(DEFAULT, "Hidden"), &[&[], &["Shown"]]);
+
+ let bytes = export_pdf(&doc, &Cache::new(), &PdfOptions::default()).unwrap();
+
+ assert_eq!(catalog(&bytes), [("Hidden".into(), false), ("Hidden".into(), true), ("Shown".into(), false), ("Shown".into(), true)]);
+ painted(&bytes, &[true, false, false, true]);
+}
+
+#[test]
+fn duplicate_names_with_distinct_generations_keep_default_states() {
+ let doc = document(fixture(DEFAULT, "Shown"), &[&[]]);
+
+ let bytes = export_pdf(&doc, &Cache::new(), &PdfOptions::default()).unwrap();
+
+ assert_eq!(catalog(&bytes), [("Shown".into(), false), ("Shown".into(), true)]);
+ painted(&bytes, &[true, false]);
+}
+
+#[test]
+fn unresolved_default_off_reference_fails_export() {
+ let doc = document(fixture("/OFF[99 0 R]", "Hidden"), &[&[]]);
+
+ let result = export_pdf(&doc, &Cache::new(), &PdfOptions::default());
+
+ assert!(result.is_err(), "an unreadable layer state must not print hidden artwork");
+}
+
+#[test]
+fn unlayered_pdf_stays_vector_without_optional_content() {
+ let doc = document(support::unlayered_fixture(), &[&[]]);
+
+ let bytes = export_pdf(&doc, &Cache::new(), &PdfOptions::default()).unwrap();
+
+ let pdf = hayro_syntax::Pdf::new(bytes.clone()).unwrap();
+ let root = pdf.xref().get::<hayro_syntax::object::Dict<'_>>(pdf.xref().root_id()).unwrap();
+ assert!(!root.contains_key(b"OCProperties"));
+ assert_vector(&bytes);
+ painted(&bytes, &[true, false]);
+}
+
+fn assert_vector(bytes: &[u8]) {
+ use hayro_syntax::object::{Name, Object};
+ let pdf = hayro_syntax::Pdf::new(bytes.to_vec()).unwrap();
+ for object in pdf.objects() {
+ if let Object::Stream(stream) = object {
+ assert_ne!(stream.dict().get::<Name<'_>>(b"Subtype").as_ref().map(AsRef::as_ref), Some(b"Image".as_slice()));
+ }
+ }
+}
+
+#[test]
+fn layer_options_command_preserves_vector_overrides_in_plain_and_pdfx() {
+ use designcraft_engine::{
+ Session,
+ cmd::{base64_decode, base64_encode},
+ };
+ use serde_json::json;
+ for standard in ["none", "x4"] {
+ let mut session = Session::new();
+ session.execute("file.new", &json!({"width": 100, "height": 100, "pages": 1, "facingPages": false, "margins": 0})).unwrap();
+ session
+ .execute("file.place", &json!({"base64": base64_encode(&fixture(DEFAULT, "Hidden")), "name": "layers.pdf", "x": 0, "y": 0, "width": 100}))
+ .unwrap();
+ session.execute("object.layerOptions", &json!({"hidden": ["Shown"]})).unwrap();
+
+ let result = session.execute("file.exportPdf", &json!({"standard": standard})).unwrap();
+
+ let bytes = base64_decode(result["base64"].as_str().unwrap());
+ assert_eq!(catalog(&bytes), [("Hidden".into(), false), ("Shown".into(), true)]);
+ assert_vector(&bytes);
+ painted(&bytes, &[false, true]);
+ }
+}
+
+#[test]
+fn exported_optional_content_survives_replacement_and_book_merge() {
+ let first = exported(DEFAULT, Standard::None);
+ let doc = document(first.clone(), &[&[]]);
+
+ let replaced = export_pdf(&doc, &Cache::new(), &PdfOptions::default()).unwrap();
+ let merged = designcraft_pdf::merge_pdfs(&[(first, vec![(100.0, 100.0)])], None).unwrap();
+
+ for bytes in [replaced, merged] {
+ assert_eq!(catalog(&bytes), [("Hidden".into(), true), ("Shown".into(), false)]);
+ painted(&bytes, &[true, false]);
+ }
+}
+
+#[test]
+fn booklet_export_preserves_optional_content() {
+ let doc = document(fixture(DEFAULT, "Hidden"), &[&[]]);
+ let options = designcraft_pdf::BookletOptions { kind: designcraft_pdf::BookletKind::TwoUpConsecutive, ..Default::default() };
+
+ let report = designcraft_pdf::export_booklet(&doc, &Cache::new(), &options).unwrap();
+
+ assert!(report.warnings.is_empty());
+ assert_eq!(catalog(&report.bytes), [("Hidden".into(), true), ("Shown".into(), false)]);
+ assert_vector(&report.bytes);
+ painted(&report.bytes, &[true, false, false, false]);
+}
+
+#[test]
+fn archival_export_still_rejects_unvalidated_placed_pdf() {
+ let doc = document(fixture(DEFAULT, "Hidden"), &[&[]]);
+
+ let error = export_pdf(&doc, &Cache::new(), &PdfOptions { standard: Standard::PdfA2b, ..Default::default() }).unwrap_err();
+
+ assert!(error.to_string().contains("EmbeddedPDF"), "{error}");
+}
+
+#[test]
+fn source_xref_stream_preserves_layer_states() {
+ let doc = document(support::stream_fixture(DEFAULT), &[&[]]);
+
+ let bytes = export_pdf(&doc, &Cache::new(), &PdfOptions::default()).unwrap();
+
+ assert_eq!(catalog(&bytes), [("Hidden".into(), true), ("Shown".into(), false)]);
+ painted(&bytes, &[true, false]);
+}
diff --git a/crates/engine/tests/support/optional_content.rs b/crates/engine/tests/support/optional_content.rs
new file mode 100644
index 000000000..3ed73d74f
--- /dev/null
+++ b/crates/engine/tests/support/optional_content.rs
@@ -0,0 +1,173 @@
+use std::sync::Arc;
+
+use designcraft_doc::{Asset, AssetId, Content, Document, Graphic, Item, ItemId, Shape, SpreadRef, build::NewDocument};
+use designcraft_geom::{Affine, Rect, shapes};
+use hayro_syntax::{
+ Pdf,
+ object::{Array, Dict, Name, ObjectIdentifier},
+};
+
+pub fn fixture(config: &str, second_name: &str) -> Vec<u8> {
+ layered_fixture(Some(config), second_name)
+}
+
+pub fn orphaned_fixture() -> Vec<u8> {
+ layered_fixture(None, "Hidden")
+}
+
+fn layered_fixture(config: Option<&str>, second_name: &str) -> Vec<u8> {
+ let properties = config.map(|config| format!("/OCProperties<</OCGs[5 0 R 6 3 R]/D<<{config}>>>>")).unwrap_or_default();
+ properties_fixture(&properties, second_name)
+}
+
+pub fn properties_fixture(properties: &str, second_name: &str) -> Vec<u8> {
+ grouped_fixture(properties, Some(second_name))
+}
+
+pub fn nameless_fixture(config: &str) -> Vec<u8> {
+ grouped_fixture(&format!("/OCProperties<</OCGs[5 0 R 6 3 R]/D<<{config}>>>>"), None)
+}
+
+fn grouped_fixture(properties: &str, second_name: Option<&str>) -> Vec<u8> {
+ let content = "/OC /a BDC 1 0 0 0 k 0 0 50 100 re f EMC /OC /b BDC 0 1 0 0 k 50 0 50 100 re f EMC";
+ let name = second_name.map(|name| format!("/Name({name})")).unwrap_or_default();
+ let objects = [
+ format!("<</Type/Catalog/Pages 2 0 R{properties}>>"),
+ "<</Type/Pages/Kids[3 0 R]/Count 1>>".into(),
+ "<</Type/Page/Parent 2 0 R/MediaBox[0 0 100 100]/Resources<</Properties<</a 5 0 R/b 6 3 R>>>>/Contents 4 0 R>>".into(),
+ format!("<</Length {}>>\nstream\n{content}\nendstream", content.len()),
+ "<</Type/OCG/Name(Shown)/Intent[/View/Design]/Usage<</Print<</PrintState/ON>>>>/Custom(keep \\(this\\) >>)>>".into(),
+ format!("<</Type/OCG{name}/Intent[/View/Design]/Usage<</Print<</PrintState/ON>>>>/Custom<00ff80>>>"),
+ ];
+ assemble(&objects, &[2, 0, 0, 0, 0, 3])
+}
+
+pub fn unlayered_fixture() -> Vec<u8> {
+ let content = "1 0 0 0 k 0 0 50 100 re f";
+ assemble(
+ &[
+ "<</Type/Catalog/Pages 2 0 R>>".into(),
+ "<</Type/Pages/Kids[3 0 R]/Count 1>>".into(),
+ "<</Type/Page/Parent 2 0 R/MediaBox[0 0 100 100]/Resources<<>>/Contents 4 0 R>>".into(),
+ format!("<</Length {}>>\nstream\n{content}\nendstream", content.len()),
+ ],
+ &[2, 0, 0, 0],
+ )
+}
+
+pub fn stream_fixture(config: &str) -> Vec<u8> {
+ let mut bytes = fixture(config, "Hidden");
+ let tail = std::str::from_utf8(&bytes).unwrap();
+ let previous: usize = tail.rsplit("startxref").next().unwrap().split_whitespace().next().unwrap().parse().unwrap();
+ let offset = bytes.len();
+ let mut entry = vec![1];
+ entry.extend_from_slice(&u32::try_from(offset).unwrap().to_be_bytes());
+ entry.extend_from_slice(&0u16.to_be_bytes());
+ bytes.extend_from_slice(format!("7 0 obj\n<</Type/XRef/Size 8/Root 1 2 R/Prev {previous}/W[1 4 2]/Index[7 1]/Length 7>>\nstream\n").as_bytes());
+ bytes.extend_from_slice(&entry);
+ bytes.extend_from_slice(format!("\nendstream\nendobj\nstartxref\n{offset}\n%%EOF\n").as_bytes());
+ bytes
+}
+
+fn assemble(objects: &[String], generations: &[i32]) -> Vec<u8> {
+ let mut bytes = b"%PDF-1.5\n".to_vec();
+ let mut offsets = Vec::new();
+ for (index, body) in objects.iter().enumerate() {
+ offsets.push(bytes.len());
+ bytes.extend_from_slice(format!("{} {} obj\n{body}\nendobj\n", index + 1, generations[index]).as_bytes());
+ }
+ let xref = bytes.len();
+ bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f\r\n", objects.len() + 1).as_bytes());
+ for (offset, generation) in offsets.iter().zip(generations) {
+ bytes.extend_from_slice(format!("{offset:010} {generation:05} n\r\n").as_bytes());
+ }
+ bytes.extend_from_slice(format!("trailer\n<</Size {}/Root 1 2 R>>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
+ bytes
+}
+
+pub fn document(bytes: Vec<u8>, hidden_sets: &[&[&str]]) -> Document {
+ let width = 100.0 * f64::from(u32::try_from(hidden_sets.len()).unwrap());
+ let mut doc = Document::new(&NewDocument { width, height: 100.0, facing_pages: false, ..Default::default() });
+ let asset = AssetId(doc.alloc());
+ doc.add_asset(Asset {
+ id: asset,
+ name: "layers.pdf".into(),
+ mime: "application/pdf".into(),
+ data: Arc::new(bytes),
+ link: None,
+ pixels: None,
+ page: 0,
+ pdf_crop: Default::default(),
+ pdf_box: None,
+ });
+ for (index, hidden) in hidden_sets.iter().enumerate() {
+ let x = 100.0 * f64::from(u32::try_from(index).unwrap());
+ let mut item = Item::new(ItemId(doc.alloc()), doc.default_layer(), Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)));
+ item.xf = Affine::translate((x, 0.0));
+ item.pdf_hidden_layers = hidden.iter().map(|name| (*name).to_owned()).collect();
+ item.content = Content::Graphic(Graphic {
+ asset,
+ size: (100.0, 100.0),
+ xf: Affine::IDENTITY,
+ clip: None,
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
+ });
+ doc.insert_item(SpreadRef::Doc(0), item, None).unwrap();
+ }
+ doc
+}
+
+pub fn refs(dict: &Dict<'_>, key: &[u8]) -> Vec<ObjectIdentifier> {
+ dict.get::<Array<'_>>(key).unwrap().raw_iter().map(|value| value.as_obj_ref().unwrap().into()).collect()
+}
+
+pub fn catalog(bytes: &[u8]) -> Vec<(String, bool)> {
+ let pdf = Pdf::new(bytes.to_vec()).unwrap();
+ let root = pdf.xref().get::<Dict<'_>>(pdf.xref().root_id()).unwrap();
+ let properties = root.get::<Dict<'_>>(b"OCProperties").expect("export must register its embedded OCGs");
+ let groups = refs(&properties, b"OCGs");
+ let defaults = properties.get::<Dict<'_>>(b"D").unwrap();
+ assert!(defaults.get::<hayro_syntax::object::String<'_>>(b"Name").is_some());
+ assert_eq!(defaults.get::<Name<'_>>(b"BaseState").unwrap().as_ref(), b"ON");
+ assert!(!defaults.contains_key(b"AS"));
+ assert_eq!(refs(&defaults, b"Order"), groups);
+ let off = refs(&defaults, b"OFF");
+ assert!(off.iter().all(|id| groups.contains(id)));
+ let mut unique = groups.clone();
+ unique.sort();
+ unique.dedup();
+ assert_eq!(unique.len(), groups.len());
+ let mut result = Vec::new();
+ for id in groups {
+ let group = pdf.xref().get::<Dict<'_>>(id).unwrap();
+ assert!(group.contains_key(b"Usage"));
+ assert!(group.contains_key(b"Intent"));
+ assert!(group.contains_key(b"Custom"));
+ let custom = group.get::<hayro_syntax::object::String<'_>>(b"Custom").unwrap();
+ assert!([b"keep (this) >>".as_slice(), &[0, 255, 128]].contains(&custom.as_bytes()));
+ let intent = group.get::<Array<'_>>(b"Intent").unwrap();
+ assert_eq!(intent.iter::<Name<'_>>().map(|name| name.as_ref().to_vec()).collect::<Vec<_>>(), [b"View".to_vec(), b"Design".to_vec()]);
+ let usage = group.get::<Dict<'_>>(b"Usage").unwrap().get::<Dict<'_>>(b"Print").unwrap();
+ assert_eq!(usage.get::<Name<'_>>(b"PrintState").unwrap().as_ref(), b"ON");
+ let name = group.get::<hayro_syntax::object::String<'_>>(b"Name").unwrap();
+ result.push((String::from_utf8(name.as_bytes().to_vec()).unwrap(), off.contains(&id)));
+ }
+ result.sort();
+ result
+}
+
+pub fn painted(bytes: &[u8], expected: &[bool]) {
+ let width = u32::try_from(expected.len()).unwrap() * 50;
+ let image = designcraft_render::render_pdf_page(bytes, 0, width.max(100)).unwrap();
+ for (index, painted) in expected.iter().enumerate() {
+ let image_width = usize::from(image.width());
+ let x = (2 * index + 1) * image_width / (2 * expected.len());
+ let y = usize::from(image.height()) / 2;
+ let pixel = image.data()[y * image_width + x];
+ assert_eq!(pixel.a > 200, *painted, "half {index}: {pixel:?}");
+ }
+}
diff --git a/crates/engine/tests/support/optional_content_fallback.rs b/crates/engine/tests/support/optional_content_fallback.rs
new file mode 100644
index 000000000..5a94bb7b1
--- /dev/null
+++ b/crates/engine/tests/support/optional_content_fallback.rs
@@ -0,0 +1,263 @@
+use super::support::{catalog, document, nameless_fixture, painted, properties_fixture};
+use designcraft_compose::Cache;
+use designcraft_engine::{Session, cmd::base64_encode};
+use designcraft_pdf::{PdfOptions, Standard, export_pdf, export_pdf_with_report};
+use serde_json::json;
+
+const CASES: &[&str] = &[
+ "/OCGs[5 0 R 6 3 R]",
+ "/OCGs[5 0 R 6 3 R]/D null",
+ "/OCGs[5 0 R 6 3 R]/D 42",
+ "/OCGs[5 0 R 6 3 R]/D 99 0 R",
+ "/OCGs[5 0 R 6 3 R]/D<</BaseState/Unchanged/OFF[6 3 R]>>",
+ "/OCGs[5 0 R 6 3 R]/D<</BaseState/Other/OFF[6 3 R]>>",
+ "/OCGs[5 0 R 6 3 R]/D<</BaseState 42/OFF[6 3 R]>>",
+ "/OCGs[5 0 R 6 3 R]/D<</BaseState/ON/ON 42>>",
+ "/OCGs[5 0 R 6 3 R]/D<</BaseState/ON/ON[null 5 0 R]>>",
+];
+
+fn incomplete_inventory(standard: &str, off: bool) {
+ let cases: &[&str] = if off {
+ &["/OCGs[5 0 R]/D<</BaseState/ON/OFF[6 3 R]>>", "/D<</ON[5 0 R]/OFF[6 3 R]>>"]
+ } else {
+ &["/OCGs[6 3 R]/D<</BaseState/OFF/ON[5 0 R]>>"]
+ };
+ for properties in cases {
+ let source = properties_fixture(&format!("/OCProperties<<{properties}>>"), "Hidden");
+ let mut session = Session::new();
+ session.execute("file.new", &json!({"width": 100, "height": 100, "pages": 1, "facingPages": false, "margins": 0})).unwrap();
+ session.execute("file.place", &json!({"base64": base64_encode(&source), "name": "incomplete.pdf", "x": 0, "y": 0, "width": 100})).unwrap();
+
+ let result = session.execute("file.exportPdf", &json!({"standard": standard})).unwrap();
+
+ let bytes = designcraft_engine::cmd::base64_decode(result["base64"].as_str().unwrap());
+ assert_eq!(catalog(&bytes), [("Hidden".into(), true), ("Shown".into(), false)]);
+ painted(&bytes, &[true, false]);
+ super::assert_vector(&bytes);
+ let warnings = result["warnings"].as_array().unwrap();
+ assert_eq!(warnings.len(), 1);
+ let warning = warnings[0].as_str().unwrap();
+ assert!(warning.contains("incomplete.pdf") && warning.contains("layer list incomplete"), "{warning}");
+ assert!(!warning.contains("layer state not readable"), "{warning}");
+ if standard == "x4" {
+ assert!(designcraft_pdf::check_pdfx4(&bytes).is_empty());
+ }
+ }
+}
+
+#[test]
+fn plain_incomplete_inventory_preserves_off() {
+ incomplete_inventory("none", true);
+}
+
+#[test]
+fn pdfx_incomplete_inventory_preserves_off() {
+ incomplete_inventory("x4", true);
+}
+
+#[test]
+fn plain_incomplete_inventory_preserves_on() {
+ incomplete_inventory("none", false);
+}
+
+#[test]
+fn pdfx_incomplete_inventory_preserves_on() {
+ incomplete_inventory("x4", false);
+}
+
+#[test]
+fn incomplete_inventory_reports_both_warnings_during_fallback() {
+ for standard in [Standard::None, Standard::PdfX4] {
+ let source = properties_fixture("/OCProperties<</OCGs[5 0 R]/D<</BaseState/Unchanged/OFF[6 3 R]>>>>", "Hidden");
+ let doc = document(source, &[&[]]);
+
+ let report = export_pdf_with_report(&doc, &Cache::new(), &PdfOptions { standard, ..Default::default() }).unwrap();
+
+ assert_eq!(report.warnings.len(), 1);
+ let warning = &report.warnings[0];
+ assert!(
+ warning.contains("layers.pdf") && warning.contains("layer list incomplete") && warning.contains("layer state not readable"),
+ "{warning}"
+ );
+ painted(&report.bytes, &[true, true]);
+ if standard == Standard::PdfX4 {
+ assert!(designcraft_pdf::check_pdfx4(&report.bytes).is_empty());
+ }
+ }
+}
+
+fn visible_recovery(source: Vec<u8>, standard: &str) {
+ let mut session = Session::new();
+ session.execute("file.new", &json!({"width": 100, "height": 100, "pages": 1, "facingPages": false, "margins": 0})).unwrap();
+ session.execute("file.place", &json!({"base64": base64_encode(&source), "name": "visible-recovery.pdf", "x": 0, "y": 0, "width": 100})).unwrap();
+
+ let result = session.execute("file.exportPdf", &json!({"standard": standard})).unwrap();
+
+ let warnings = result["warnings"].as_array().unwrap();
+ assert_eq!(warnings.len(), 1);
+ assert!(warnings[0].as_str().unwrap().contains("visible-recovery.pdf"));
+ let bytes = designcraft_engine::cmd::base64_decode(result["base64"].as_str().unwrap());
+ let groups = catalog(&bytes);
+ assert_eq!(groups.len(), 2);
+ assert!(groups.iter().all(|(name, hidden)| !name.is_empty() && !hidden));
+ super::assert_vector(&bytes);
+ painted(&bytes, &[true, true]);
+ if standard == "x4" {
+ assert!(designcraft_pdf::check_pdfx4(&bytes).is_empty());
+ }
+}
+
+#[test]
+fn plain_export_recovers_malformed_on_when_defaults_are_visible() {
+ visible_recovery(super::support::fixture("/BaseState/ON/ON 42", "Hidden"), "none");
+}
+
+#[test]
+fn pdfx_export_recovers_malformed_on_when_defaults_are_visible() {
+ visible_recovery(super::support::fixture("/BaseState/ON/ON 42", "Hidden"), "x4");
+}
+
+#[test]
+fn plain_export_names_visible_group_when_display_name_is_missing() {
+ visible_recovery(nameless_fixture("/BaseState/ON"), "none");
+}
+
+#[test]
+fn pdfx_export_names_visible_group_when_display_name_is_missing() {
+ visible_recovery(nameless_fixture("/BaseState/ON"), "x4");
+}
+
+#[test]
+fn missing_display_name_fails_when_an_override_could_match() {
+ for standard in [Standard::None, Standard::PdfX4] {
+ let doc = document(nameless_fixture("/BaseState/ON"), &[&["Shown"]]);
+
+ let result = export_pdf(&doc, &Cache::new(), &PdfOptions { standard, ..Default::default() });
+
+ assert!(result.is_err(), "a nameless group could match the explicit hidden name");
+ }
+}
+
+#[test]
+fn malformed_on_fails_when_base_state_can_hide_groups() {
+ for standard in [Standard::None, Standard::PdfX4] {
+ let doc = document(super::support::fixture("/BaseState/OFF/ON 42", "Hidden"), &[&[]]);
+
+ let result = export_pdf(&doc, &Cache::new(), &PdfOptions { standard, ..Default::default() });
+
+ assert!(result.is_err(), "all-ON recovery would expose groups hidden by BaseState OFF");
+ }
+}
+
+#[test]
+fn name_repair_preserves_readable_default_off_state() {
+ for standard in [Standard::None, Standard::PdfX4] {
+ let doc = document(nameless_fixture("/BaseState/ON/OFF[6 3 R]"), &[&[]]);
+
+ let report = export_pdf_with_report(&doc, &Cache::new(), &PdfOptions { standard, ..Default::default() }).unwrap();
+
+ assert_eq!(report.warnings.len(), 1);
+ assert!(report.warnings[0].contains("layers.pdf"));
+ assert_eq!(catalog(&report.bytes).iter().filter(|(_, hidden)| *hidden).count(), 1);
+ painted(&report.bytes, &[true, false]);
+ if standard == Standard::PdfX4 {
+ assert!(designcraft_pdf::check_pdfx4(&report.bytes).is_empty());
+ }
+ }
+}
+
+fn fallback_exports(standard: Standard) {
+ let mut failures = Vec::new();
+ for properties in CASES {
+ let source = properties_fixture(&format!("/OCProperties<<{properties}>>"), "Hidden");
+ let doc = document(source, &[&[], &["Shown"]]);
+
+ let report = match export_pdf_with_report(&doc, &Cache::new(), &PdfOptions { standard, created: Some(0), ..Default::default() }) {
+ Ok(report) => report,
+ Err(error) => {
+ failures.push(format!("{properties}: {error}"));
+ continue;
+ }
+ };
+
+ if report.warnings.len() != 1 {
+ failures.push(format!("{properties}: expected one fallback warning, got {:?}", report.warnings));
+ continue;
+ }
+ assert!(report.warnings[0].contains("layers.pdf"));
+ assert_eq!(catalog(&report.bytes), [("Hidden".into(), false), ("Hidden".into(), false), ("Shown".into(), false), ("Shown".into(), true)]);
+ super::assert_vector(&report.bytes);
+ painted(&report.bytes, &[true, true, false, true]);
+ if standard == Standard::PdfX4 {
+ assert!(designcraft_pdf::check_pdfx4(&report.bytes).is_empty());
+ }
+ }
+ assert!(failures.is_empty(), "fallback export failures: {failures:#?}");
+}
+
+#[test]
+fn plain_fallback_shows_all_layers_and_preserves_frame_overrides() {
+ fallback_exports(Standard::None);
+}
+
+#[test]
+fn pdfx_fallback_shows_all_layers_and_preserves_frame_overrides() {
+ fallback_exports(Standard::PdfX4);
+}
+
+#[test]
+fn file_export_reports_fallback_with_filename_and_preserves_overrides() {
+ for properties in CASES {
+ for standard in ["none", "x4"] {
+ for hidden in [false, true] {
+ let source = properties_fixture(&format!("/OCProperties<<{properties}>>"), "Hidden");
+ let mut session = Session::new();
+ session.execute("file.new", &json!({"width": 100, "height": 100, "pages": 1, "facingPages": false, "margins": 0})).unwrap();
+ session
+ .execute("file.place", &json!({"base64": base64_encode(&source), "name": "fallback.pdf", "x": 0, "y": 0, "width": 100}))
+ .unwrap();
+ if hidden {
+ session.execute("object.layerOptions", &json!({"hidden": ["Shown"]})).unwrap();
+ }
+
+ let result = session.execute("file.exportPdf", &json!({"standard": standard})).unwrap();
+
+ let warnings = result["warnings"].as_array().unwrap();
+ assert_eq!(warnings.len(), 1, "{properties}: {result}");
+ assert!(warnings[0].as_str().unwrap().contains("fallback.pdf"));
+ let bytes = designcraft_engine::cmd::base64_decode(result["base64"].as_str().unwrap());
+ assert_eq!(catalog(&bytes), [("Hidden".into(), false), ("Shown".into(), hidden)]);
+ painted(&bytes, &[!hidden, true]);
+ }
+ }
+ }
+}
+
+#[test]
+fn contradictory_and_unresolved_states_fail_even_with_fallback_or_overrides() {
+ for properties in [
+ "/OCGs[5 0 R 6 3 R]/D<</ON[6 3 R]/OFF[6 3 R]>>",
+ "/OCGs[5 0 R]/D<</BaseState/Unchanged/ON[6 3 R]/OFF[6 3 R]>>",
+ "/OCGs[5 0 R 6 3 R]/D<</BaseState/Unchanged/OFF[99 0 R]>>",
+ "/OCGs[5 0 R 6 3 R]/D<</ON[99 0 R]>>",
+ "/OCGs[5 0 R 6 3 R 99 0 R]",
+ "/OCGs[5 0 R 6 3 R]/D<</OFF[2 0 R]>>",
+ "/OCGs[5 0 R 6 3 R]/D<</OFF[6 0 R]>>",
+ "/OCGs[5 0 R 6 3 R]/D<</OFF[null]>>",
+ "/OCGs[5 0 R 6 3 R]/D<</OFF 42>>",
+ "/OCGs[5 0 R 6 3 R]/D<</OFF 99 0 R>>",
+ "/OCGs[5 0 R 6 3 R]/D<</BaseState/ON/ON[null 99 0 R]>>",
+ "/OCGs[5 0 R 6 3 R]/D<</BaseState/ON/ON 99 0 R>>",
+ "/OCGs[5 0 R 6 3 R]/D<</BaseState/ON/ON 42/OFF[6 3 R]>>",
+ ] {
+ for standard in [Standard::None, Standard::PdfX4] {
+ for hidden in [&[][..], &["Shown"][..]] {
+ let doc = document(properties_fixture(&format!("/OCProperties<<{properties}>>"), "Hidden"), &[hidden]);
+
+ let result = export_pdf(&doc, &Cache::new(), &PdfOptions { standard, ..Default::default() });
+
+ assert!(result.is_err(), "unsafe state accepted: {properties}");
+ }
+ }
+ }
+}
diff --git a/crates/engine/tests/support/optional_content_xref.rs b/crates/engine/tests/support/optional_content_xref.rs
new file mode 100644
index 000000000..9730969e2
--- /dev/null
+++ b/crates/engine/tests/support/optional_content_xref.rs
@@ -0,0 +1,143 @@
+use super::support::{catalog, document, fixture, nameless_fixture, painted};
+use designcraft_compose::Cache;
+use designcraft_doc::{AssetId, Content};
+use designcraft_pdf::{BookletKind, BookletOptions, PdfOptions, Standard, export_booklet, export_pdf, export_pdf_with_report, merge_pdfs};
+use std::sync::Arc;
+
+fn broken_xref(bytes: Vec<u8>) -> Vec<u8> {
+ let text = String::from_utf8(bytes).unwrap();
+ let (body, _) = text.rsplit_once("startxref").unwrap();
+ let bytes = format!("{body}startxref\n1\n%%EOF\n").into_bytes();
+ let pdf = hayro_syntax::Pdf::new(bytes.clone()).expect("hayro must repair the synthetic broken xref");
+ assert_eq!(pdf.pages().len(), 1);
+ let root = pdf.xref().get::<hayro_syntax::object::Dict<'_>>(pdf.xref().root_id()).unwrap();
+ assert!(root.get::<hayro_syntax::object::Dict<'_>>(b"OCProperties").is_some());
+ bytes
+}
+
+fn all_visible(standard: Standard) {
+ let source = broken_xref(fixture("/BaseState/ON", "Hidden"));
+ painted(&source, &[true, true]);
+ let doc = document(source, &[&[]]);
+
+ let report = export_pdf_with_report(&doc, &Cache::new(), &PdfOptions { standard, ..Default::default() }).unwrap();
+
+ assert!(report.warnings.is_empty(), "{:?}", report.warnings);
+ assert_eq!(catalog(&report.bytes), [("Hidden".into(), false), ("Shown".into(), false)]);
+ super::assert_vector(&report.bytes);
+ painted(&report.bytes, &[true, true]);
+ if standard == Standard::PdfX4 {
+ assert!(designcraft_pdf::check_pdfx4(&report.bytes).is_empty());
+ }
+}
+
+#[test]
+fn plain_export_accepts_repaired_xref_when_all_layers_are_visible() {
+ all_visible(Standard::None);
+}
+
+#[test]
+fn pdfx_export_accepts_repaired_xref_when_all_layers_are_visible() {
+ all_visible(Standard::PdfX4);
+}
+
+#[test]
+fn booklet_accepts_repaired_xref_when_all_layers_are_visible() {
+ let doc = document(broken_xref(fixture("/BaseState/ON", "Hidden")), &[&[]]);
+ let options = BookletOptions { kind: BookletKind::TwoUpConsecutive, ..Default::default() };
+
+ let report = export_booklet(&doc, &Cache::new(), &options).unwrap();
+
+ assert!(report.warnings.is_empty());
+ assert_eq!(catalog(&report.bytes), [("Hidden".into(), false), ("Shown".into(), false)]);
+ super::assert_vector(&report.bytes);
+ painted(&report.bytes, &[true, true, false, false]);
+}
+
+#[test]
+fn book_merge_accepts_repaired_xref_when_all_layers_are_visible() {
+ let source = broken_xref(fixture("/BaseState/ON", "Hidden"));
+
+ let bytes = merge_pdfs(&[(source, vec![(100.0, 100.0)])], None).unwrap();
+
+ assert_eq!(catalog(&bytes), [("Hidden".into(), false), ("Shown".into(), false)]);
+ super::assert_vector(&bytes);
+ painted(&bytes, &[true, true]);
+}
+
+#[test]
+fn repaired_xref_with_default_off_fails_with_named_damage_error() {
+ let doc = document(broken_xref(fixture("/BaseState/ON/OFF[6 3 R]", "Hidden")), &[&[]]);
+
+ for standard in [Standard::None, Standard::PdfX4] {
+ let error = export_pdf(&doc, &Cache::new(), &PdfOptions { standard, ..Default::default() }).unwrap_err().to_string();
+ assert!(error.contains("layers.pdf"), "{error}");
+ assert!(error.contains("cross-reference table is damaged"), "{error}");
+ assert!(!error.contains("optional-content state"), "{error}");
+ }
+}
+
+#[test]
+fn repaired_xref_with_explicit_hidden_layer_fails_with_named_damage_error() {
+ let doc = document(broken_xref(fixture("/BaseState/ON", "Hidden")), &[&["Hidden"]]);
+
+ let error = export_pdf(&doc, &Cache::new(), &PdfOptions::default()).unwrap_err().to_string();
+
+ assert!(error.contains("layers.pdf") && error.contains("cross-reference table is damaged"), "{error}");
+}
+
+#[test]
+fn repaired_xref_needing_generated_name_fails_with_named_damage_error() {
+ let doc = document(broken_xref(nameless_fixture("/BaseState/ON")), &[&[]]);
+
+ let error = export_pdf(&doc, &Cache::new(), &PdfOptions::default()).unwrap_err().to_string();
+
+ assert!(error.contains("layers.pdf") && error.contains("cross-reference table is damaged"), "{error}");
+}
+
+fn two_assets(first: Vec<u8>, second: Vec<u8>) -> designcraft_doc::Document {
+ let mut doc = document(first, &[&[], &[]]);
+ let original = doc.assets.values().next().unwrap().as_ref().clone();
+ Arc::make_mut(doc.assets.values_mut().next().unwrap()).name = "first.pdf".into();
+ let id = AssetId(doc.alloc());
+ let mut other = original;
+ other.id = id;
+ other.name = "second.pdf".into();
+ other.data = Arc::new(second);
+ doc.add_asset(other);
+ let spread = Arc::make_mut(doc.spreads.first_mut().unwrap());
+ let item = Arc::make_mut(spread.items.last_mut().unwrap());
+ let Content::Graphic(graphic) = &mut item.content else { panic!("fixture must have a graphic") };
+ graphic.asset = id;
+ doc
+}
+
+#[test]
+fn error_identifies_unresolvable_pdf_among_two_placements() {
+ let doc = two_assets(fixture("/BaseState/ON", "Hidden"), fixture("/OFF[99 0 R]", "Hidden"));
+
+ let error = export_pdf(&doc, &Cache::new(), &PdfOptions::default()).unwrap_err().to_string();
+
+ assert_eq!(error, "PDF writer error: second.pdf: the placed PDF's optional-content state could not be preserved safely");
+}
+
+#[test]
+fn first_placement_error_is_not_overwritten() {
+ let doc = two_assets(fixture("/OFF[99 0 R]", "Hidden"), fixture("/OFF[98 0 R]", "Hidden"));
+
+ let error = export_pdf(&doc, &Cache::new(), &PdfOptions::default()).unwrap_err().to_string();
+
+ assert!(error.contains("first.pdf"), "{error}");
+ assert!(!error.contains("second.pdf"), "{error}");
+}
+
+#[test]
+fn repeated_recoverable_variant_reports_one_warning_and_paints_each_placement() {
+ let doc = document(fixture("/BaseState/Unchanged", "Hidden"), &[&[], &[]]);
+
+ let report = export_pdf_with_report(&doc, &Cache::new(), &PdfOptions::default()).unwrap();
+
+ assert_eq!(report.warnings.len(), 1);
+ assert!(report.warnings[0].contains("layers.pdf"));
+ painted(&report.bytes, &[true, true, true, true]);
+}
diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs
index 34934b911..61fea9ac2 100644
--- a/crates/pdf/src/export.rs
+++ b/crates/pdf/src/export.rs
@@ -1,5 +1,9 @@
//! Document → PDF. The item walk mirrors `designcraft-render`'s `draw_spread` / `draw_item`.
+#[cfg(test)]
+#[path = "registration_tests.rs"]
+pub(crate) mod registration_tests;
+
use std::collections::HashMap;
use std::sync::Arc;
@@ -169,6 +173,11 @@ fn export_pdf_with_report_inner(doc: &Document, cache: &Cache, opts: &PdfOptions
#[cfg(test)]
image_conversions: 0,
pdfs: HashMap::new(),
+ variants: HashMap::new(),
+ has_optional_content: false,
+ #[cfg(test)]
+ pdf_preparations: 0,
+ layer_error: None,
version,
too_new: Vec::new(),
svgs: HashMap::new(),
@@ -227,6 +236,9 @@ fn export_pdf_with_report_inner(doc: &Document, cache: &Cache, opts: &PdfOptions
pdf.set_tag_tree(ex.tag_tree());
}
ex.check_placed_versions()?;
+ if let Some(error) = ex.layer_error {
+ return Err(error);
+ }
let mut bytes = writer.finish().map_err(PdfError::from)?;
// Transparency blends in the document's blend space: CMYK for print (and always in PDF/X).
let mut warnings = ex.warnings;
@@ -235,6 +247,9 @@ fn export_pdf_with_report_inner(doc: &Document, cache: &Cache, opts: &PdfOptions
// group that got past it, with its page.
crate::pdfx::cmyk_group_spaces(&mut bytes);
}
+ if ex.has_optional_content {
+ bytes = crate::optional_content::register(&bytes)?;
+ }
// Form fields (Buttons and Forms) and, for interactive PDF, video and sound; not in PDF/X
// or PDF/A: this update comes after krilla's validator ran, and its NeedAppearances fields and
// Screen annotations aren't allowed in PDF/A.
@@ -277,8 +292,11 @@ fn merge_pdfs_inner(parts: &[(Vec<u8>, Vec<(f32, f32)>)], title: Option<&str>) -
let mut writer = Writer::new(krilla::SerializeSettings::default(), metadata);
let pdf = writer.document_mut();
let mut pages = 0;
+ let mut has_optional_content = false;
for (bytes, sizes) in parts {
- let src = krilla::pdf::Pdf::new(Arc::new(bytes.clone())).map_err(|e| PdfError::Write(format!("{e:?}")))?;
+ let variant = crate::optional_content::prepare(&Arc::new(bytes.clone()), &[])?;
+ has_optional_content |= !sizes.is_empty() && variant.has_optional_content;
+ let src = krilla::pdf::Pdf::new(variant.data).map_err(|e| PdfError::Write(format!("{e:?}")))?;
let doc = krilla::pdf::PdfDocument::new(Arc::new(src));
for (i, &(w, h)) in sizes.iter().enumerate() {
let size = Size::from_wh(w.max(1.0), h.max(1.0)).ok_or(PdfError::NoPages)?;
@@ -295,7 +313,8 @@ fn merge_pdfs_inner(parts: &[(Vec<u8>, Vec<(f32, f32)>)], title: Option<&str>) -
if pages == 0 {
return Err(PdfError::NoPages);
}
- writer.finish().map_err(PdfError::from)
+ let bytes = writer.finish().map_err(PdfError::from)?;
+ if has_optional_content { crate::optional_content::register(&bytes) } else { Ok(bytes) }
}
/// File › Print Booklet: how pages pair up on printer spreads.
@@ -356,6 +375,11 @@ fn export_booklet_inner(doc: &Document, cache: &Cache, opts: &BookletOptions) ->
#[cfg(test)]
image_conversions: 0,
pdfs: HashMap::new(),
+ variants: HashMap::new(),
+ has_optional_content: false,
+ #[cfg(test)]
+ pdf_preparations: 0,
+ layer_error: None,
// krilla's default.
version: PdfVersion::Pdf17,
too_new: Vec::new(),
@@ -405,10 +429,16 @@ fn export_booklet_inner(doc: &Document, cache: &Cache, opts: &BookletOptions) ->
page.finish();
}
ex.check_placed_versions()?;
+ if let Some(error) = ex.layer_error {
+ return Err(error);
+ }
let mut bytes = writer.finish().map_err(PdfError::from)?;
if doc.settings.blend_space == designcraft_doc::BlendSpace::Cmyk {
crate::pdfx::cmyk_group_spaces(&mut bytes);
}
+ if ex.has_optional_content {
+ bytes = crate::optional_content::register(&bytes)?;
+ }
let mut warnings = ex.warnings;
warnings.dedup();
Ok(ExportReport { bytes, pages: pairs.len(), warnings })
@@ -487,7 +517,12 @@ pub(crate) struct Exporter<'a> {
#[cfg(test)]
image_conversions: usize,
/// Placed PDFs (embedded as vector pages) and their page counts.
- pdfs: HashMap<AssetId, Option<(krilla::pdf::PdfDocument, usize)>>,
+ pdfs: HashMap<(AssetId, Vec<hayro_syntax::object::ObjectIdentifier>), Option<(krilla::pdf::PdfDocument, usize)>>,
+ variants: HashMap<(AssetId, Vec<String>), crate::optional_content::Variant>,
+ has_optional_content: bool,
+ #[cfg(test)]
+ pdf_preparations: usize,
+ layer_error: Option<PdfError>,
/// 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.
@@ -965,7 +1000,7 @@ impl Exporter<'_> {
let g = &if it.media.is_some() { it.drawn_graphic(&self.doc.assets).unwrap_or_else(|| g.clone()) } else { g.clone() };
if let Some(p) = &path {
s.push_clip_path(p, &FillRule::NonZero);
- self.graphic(s, g);
+ self.graphic(s, g, &it.pdf_hidden_layers);
s.pop();
}
}
@@ -1258,9 +1293,9 @@ impl Exporter<'_> {
/// `qpdf --force-version=1.6` does). A newer
/// file is left out and the export fails naming it ([`Exporter::check_placed_versions`]).
/// Returns the document with its page count.
- fn placed_pdf(&mut self, asset: &designcraft_doc::Asset) -> Option<(krilla::pdf::PdfDocument, usize)> {
+ fn placed_pdf(&mut self, asset: &designcraft_doc::Asset, data: Arc<Vec<u8>>) -> Option<(krilla::pdf::PdfDocument, usize)> {
use hayro_syntax::PdfVersion as V;
- let Ok(pdf) = krilla::pdf::Pdf::new(asset.data.clone()) else {
+ let Ok(pdf) = krilla::pdf::Pdf::new(data.clone()) else {
self.warn(format!("{}: can't read the placed PDF", asset.name));
return None;
};
@@ -1278,7 +1313,7 @@ impl Exporter<'_> {
}
if have == V::Pdf17
&& max == V::Pdf16
- && let bytes = relabel_pdf_header(&asset.data, b"%PDF-1.7", b"%PDF-1.6").unwrap_or_else(|| asset.data.to_vec())
+ && let bytes = relabel_pdf_header(&data, b"%PDF-1.7", b"%PDF-1.6").unwrap_or_else(|| data.to_vec())
&& let Ok(pdf) = krilla::pdf::Pdf::new(Arc::new(relabel_catalog_version(bytes)))
&& pdf.version() <= max
{
@@ -1372,24 +1407,24 @@ impl Exporter<'_> {
}
/// Draw a placed graphic, inside its clipping path when it has one.
- pub(crate) fn graphic(&mut self, s: &mut Surface, g: &designcraft_doc::Graphic) {
+ pub(crate) fn graphic(&mut self, s: &mut Surface, g: &designcraft_doc::Graphic, hidden: &[String]) {
match g.clip_region().map(|(region, even_odd)| (to_path(&region), even_odd)) {
Some((Some(clip), even_odd)) => {
s.push_clip_path(&clip, if even_odd { &FillRule::EvenOdd } else { &FillRule::NonZero });
- self.graphic_unclipped(s, g);
+ self.graphic_unclipped(s, g, hidden);
s.pop();
}
// A degenerate outline shows nothing, or everything when inverted.
Some((None, even_odd)) => {
if even_odd {
- self.graphic_unclipped(s, g);
+ self.graphic_unclipped(s, g, hidden);
}
}
- None => self.graphic_unclipped(s, g),
+ None => self.graphic_unclipped(s, g, hidden),
}
}
- fn graphic_unclipped(&mut self, s: &mut Surface, g: &designcraft_doc::Graphic) {
+ fn graphic_unclipped(&mut self, s: &mut Surface, g: &designcraft_doc::Graphic, hidden: &[String]) {
// Video / sound without a poster: a dark frame with a play mark.
if let Some(asset) = self.doc.assets.get(&g.asset)
&& designcraft_doc::media_kind(&asset.mime).is_some()
@@ -1423,11 +1458,39 @@ impl Exporter<'_> {
let [l, t, r, b] = shown.unwrap_or([0.0, 0.0, 1.0, 1.0]);
let (page_w, page_h) = (g.size.0 / (r - l), g.size.1 / (b - t));
let Some(size) = Size::from_wh(page_w.max(1e-3) as f32, page_h.max(1e-3) as f32) else { return };
- let placed = match self.pdfs.get(&g.asset) {
+ let request = (g.asset, hidden.to_vec());
+ let variant = match self.variants.get(&request) {
+ Some(variant) => variant.clone(),
+ None => {
+ #[cfg(test)]
+ {
+ self.pdf_preparations += 1;
+ }
+ match crate::optional_content::prepare(&asset.data, hidden) {
+ Ok(variant) => {
+ self.variants.insert(request, variant.clone());
+ variant
+ }
+ Err(error) => {
+ let message = match error {
+ PdfError::Write(message) => message,
+ other => other.to_string(),
+ };
+ self.layer_error.get_or_insert(PdfError::Write(format!("{}: {message}", asset.name)));
+ return;
+ }
+ }
+ }
+ };
+ if let Some(warning) = variant.warning {
+ self.warn(format!("{}: {warning}", asset.name));
+ }
+ let key = (g.asset, variant.hidden);
+ let placed = match self.pdfs.get(&key) {
Some(p) => p.clone(),
None => {
- let p = self.placed_pdf(asset);
- self.pdfs.insert(g.asset, p.clone());
+ let p = self.placed_pdf(asset, variant.data);
+ self.pdfs.insert(key, p.clone());
p
}
};
@@ -1437,6 +1500,7 @@ impl Exporter<'_> {
self.warn(format!("{}: the placed PDF has no page {}", asset.name, u64::from(asset.page) + 1));
}
Some((placed, _)) => {
+ self.has_optional_content |= variant.has_optional_content;
s.push_transform(&tf(g.xf));
let clip = shown.and_then(|_| to_path(&Rect::new(0.0, 0.0, g.size.0, g.size.1).to_path(0.1)));
if let Some(clip) = &clip {
@@ -1884,6 +1948,10 @@ mod image_content_cache_tests {
images_by_content: ImageContentCache::default(),
image_conversions: 0,
pdfs: HashMap::new(),
+ variants: HashMap::new(),
+ has_optional_content: false,
+ pdf_preparations: 0,
+ layer_error: None,
version: PdfVersion::Pdf17,
too_new: Vec::new(),
svgs: HashMap::new(),
@@ -1898,6 +1966,42 @@ mod image_content_cache_tests {
}
}
#[test]
+ fn prepared_pdf_variants_reuse_parsing_by_asset_and_hidden_names() {
+ let mut doc = Document::new(&Default::default());
+ let cache = Cache::new();
+ let opts = PdfOptions::default();
+ let source = export_pdf(&doc, &cache, &opts).unwrap();
+ let a = asset(&mut doc, source.clone(), "a.pdf");
+ let b = asset(&mut doc, source, "b.pdf");
+ let mut ex = exporter(&doc, &cache, &opts);
+ let mut writer = Writer::new(Default::default(), Default::default());
+ let mut page = writer.document_mut().start_page_with(PageSettings::new(Size::from_wh(100.0, 100.0).unwrap()));
+ let mut surface = page.surface();
+ for (id, hidden, count) in [(a, vec![], 1), (a, vec![], 1), (a, vec!["Hidden".into()], 2), (b, vec![], 3), (a, vec![], 3)] {
+ let graphic = designcraft_doc::Graphic {
+ asset: id,
+ size: (100.0, 100.0),
+ xf: Affine::IDENTITY,
+ clip: None,
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
+ };
+ ex.graphic_unclipped(&mut surface, &graphic, &hidden);
+ assert!(ex.layer_error.is_none());
+ assert_eq!(ex.pdf_preparations, count, "count actual preparations, not writer resource deduplication");
+ }
+ assert_eq!(ex.variants.len(), 3);
+ assert_eq!(ex.pdfs.len(), 2);
+ let variant = ex.variants.get(&(a, Vec::new())).unwrap();
+ assert!(Arc::ptr_eq(&variant.data, &doc.assets[&a].data));
+ surface.finish();
+ page.finish();
+ assert!(writer.finish().is_ok());
+ }
+ #[test]
fn exact_bytes_reuse_conversion_under_real_hash_collisions() {
use std::hash::{BuildHasher, Hasher};
let mut d = Document::new(&Default::default());
diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs
index ad1123897..72e4028cd 100644
--- a/crates/pdf/src/lib.rs
+++ b/crates/pdf/src/lib.rs
@@ -35,6 +35,7 @@ mod marks;
mod text;
mod forms;
+mod optional_content;
mod pdfx;
mod transitions;
pub use export::{BookletKind, BookletOptions, booklet_pairs, export_booklet, export_pdf, export_pdf_with_report, merge_pdfs, sheet_spreads};
diff --git a/crates/pdf/src/optional_content.rs b/crates/pdf/src/optional_content.rs
new file mode 100644
index 000000000..8bd795937
--- /dev/null
+++ b/crates/pdf/src/optional_content.rs
@@ -0,0 +1,279 @@
+use hayro_syntax::Pdf;
+use hayro_syntax::object::{Array, Dict, MaybeRef, Name, Object, ObjectIdentifier, Stream};
+use hayro_syntax::reader::{Reader, ReaderExt};
+use std::sync::Arc;
+
+use crate::{PdfError, Result};
+
+const MARKER: &[u8] = b"DesignCraftHiddenOCG";
+
+fn invalid() -> PdfError {
+ PdfError::Write("the placed PDF's optional-content state could not be preserved safely".into())
+}
+
+fn references(dict: &Dict<'_>, key: &[u8]) -> Result<Vec<ObjectIdentifier>> {
+ if !dict.contains_key(key) {
+ return Ok(Vec::new());
+ }
+ dict.get::<Array<'_>>(key).ok_or_else(invalid)?.raw_iter().map(|value| value.as_obj_ref().map(Into::into).ok_or_else(invalid)).collect()
+}
+
+fn edited(dict: &Dict<'_>, replacements: &[(&[u8], &[u8])]) -> Result<Vec<u8>> {
+ let data = dict.data();
+ let body = data.strip_prefix(b"<<").and_then(|d| d.strip_suffix(b">>")).ok_or_else(invalid)?;
+ let mut reader = Reader::new(body);
+ let mut out = b"<<".to_vec();
+ loop {
+ reader.skip_white_spaces_and_comments();
+ if reader.at_end() {
+ break;
+ }
+ let start = reader.offset();
+ let name = reader.read_without_context::<Name<'_>>().ok_or_else(invalid)?;
+ reader.skip_white_spaces_and_comments();
+ reader.skip::<MaybeRef<Object<'_>>>(false).ok_or_else(invalid)?;
+ if !replacements.iter().any(|(key, _)| *key == name.as_ref()) {
+ out.push(b'\n');
+ out.extend_from_slice(body.get(start..reader.offset()).ok_or_else(invalid)?);
+ }
+ }
+ for (key, value) in replacements {
+ if !value.is_empty() {
+ out.extend_from_slice(b"\n/");
+ out.extend_from_slice(key);
+ out.push(b' ');
+ out.extend_from_slice(value);
+ }
+ }
+ out.extend_from_slice(b"\n>>");
+ Ok(out)
+}
+
+fn append(bytes: &[u8], changes: &[(ObjectIdentifier, Vec<u8>)], root: ObjectIdentifier) -> Result<Vec<u8>> {
+ let damaged = || PdfError::Write("the placed PDF's cross-reference table is damaged; layer changes could not be preserved safely".into());
+ let at = crate::transitions::rfind(bytes, b"startxref").ok_or_else(damaged)?;
+ let tail = std::str::from_utf8(bytes.get(at..).ok_or_else(damaged)?).map_err(|_| damaged())?;
+ let prev = crate::transitions::int_after(tail, "startxref").ok_or_else(damaged)?;
+ let section = bytes.get(prev..).ok_or_else(damaged)?;
+ let trailer = if section.starts_with(b"xref") {
+ let at = crate::transitions::find(section, b"trailer", 0).ok_or_else(damaged)?;
+ let mut reader = Reader::new(section.get(at + 7..).ok_or_else(damaged)?);
+ reader.skip_white_spaces_and_comments();
+ reader.read_without_context::<Dict<'_>>().ok_or_else(damaged)?
+ } else {
+ let mut reader = Reader::new(section);
+ reader.read_without_context::<ObjectIdentifier>().ok_or_else(damaged)?;
+ reader.skip_white_spaces_and_comments();
+ let stream = reader.read_without_context::<Stream<'_>>().ok_or_else(damaged)?;
+ if stream.dict().get::<Name<'_>>(b"Type").as_ref().map(AsRef::as_ref) != Some(b"XRef") {
+ return Err(damaged());
+ }
+ stream.dict().clone()
+ };
+ if trailer.contains_key(b"Encrypt") {
+ return Err(invalid());
+ }
+ trailer.get::<i32>(b"Size").filter(|n| *n > 0).ok_or_else(damaged)?;
+ let mut out = bytes.to_vec();
+ out.push(b'\n');
+ let mut offsets = Vec::new();
+ for (id, body) in changes {
+ offsets.push((*id, out.len()));
+ out.extend_from_slice(format!("{} {} obj\n", id.obj_number, id.gen_number).as_bytes());
+ out.extend_from_slice(body);
+ out.extend_from_slice(b"\nendobj\n");
+ }
+ let xref = out.len();
+ out.extend_from_slice(b"xref\n");
+ offsets.sort_by_key(|(id, _)| *id);
+ for (id, offset) in offsets {
+ out.extend_from_slice(format!("{} 1\n{offset:010} {:05} n\r\n", id.obj_number, id.gen_number).as_bytes());
+ }
+ let root = format!("{} {} R", root.obj_number, root.gen_number);
+ let prev = prev.to_string();
+ let trailer = edited(
+ &trailer,
+ &[
+ (b"Root", root.as_bytes()),
+ (b"Prev", prev.as_bytes()),
+ (b"XRefStm", b""),
+ (b"Type", b""),
+ (b"W", b""),
+ (b"Index", b""),
+ (b"Length", b""),
+ (b"Filter", b""),
+ (b"DecodeParms", b""),
+ ],
+ )?;
+ out.extend_from_slice(b"trailer\n");
+ out.extend_from_slice(&trailer);
+ out.extend_from_slice(format!("\nstartxref\n{xref}\n%%EOF\n").as_bytes());
+ Ok(out)
+}
+
+#[derive(Clone)]
+pub(crate) struct Variant {
+ pub data: Arc<Vec<u8>>,
+ pub hidden: Vec<ObjectIdentifier>,
+ pub warning: Option<String>,
+ pub has_optional_content: bool,
+}
+
+pub(crate) fn prepare(bytes: &Arc<Vec<u8>>, hidden: &[String]) -> Result<Variant> {
+ let pdf = Pdf::new(bytes.clone()).map_err(|_| invalid())?;
+ let xref = pdf.xref();
+ let root = xref.get::<Dict<'_>>(xref.root_id()).ok_or_else(invalid)?;
+ if !root.contains_key(b"OCProperties") {
+ let has_optional_content = pdf
+ .objects()
+ .into_iter()
+ .any(|object| matches!(object, Object::Dict(dict) if dict.get::<Name<'_>>(b"Type").as_ref().map(AsRef::as_ref) == Some(b"OCG")));
+ return Ok(Variant { data: bytes.clone(), hidden: Vec::new(), warning: None, has_optional_content });
+ }
+ let properties = root.get::<Dict<'_>>(b"OCProperties").ok_or_else(invalid)?;
+ let mut groups = references(&properties, b"OCGs")?;
+ let config = properties.get::<Dict<'_>>(b"D");
+ let mut fallback = config.is_none();
+ let config = config.unwrap_or_default();
+ let base_off = match config.get::<Name<'_>>(b"BaseState").as_ref().map(AsRef::as_ref) {
+ None if !config.contains_key(b"BaseState") => false,
+ Some(b"ON") => false,
+ Some(b"OFF") => true,
+ None | Some(_) => {
+ fallback = true;
+ false
+ }
+ };
+ let off = references(&config, b"OFF")?;
+ let on = match references(&config, b"ON") {
+ Ok(on) => on,
+ Err(error) if !fallback && !base_off && off.is_empty() => {
+ let value = config.get::<Object<'_>>(b"ON").ok_or(error)?;
+ fallback = true;
+ value.into_array().map(|array| array.raw_iter().filter_map(|value| value.as_obj_ref().map(Into::into)).collect()).unwrap_or_default()
+ }
+ Err(error) => return Err(error),
+ };
+ if on.iter().any(|id| off.contains(id)) {
+ return Err(invalid());
+ }
+ let incomplete = on.iter().chain(&off).any(|id| !groups.contains(id));
+ groups.extend(on.iter().chain(&off).copied());
+ groups.sort();
+ groups.dedup();
+ // Aggregating applications use the default state, not /AS usage-event adjustments.
+ let mut changes = Vec::new();
+ let mut effective = Vec::new();
+ let mut renamed = false;
+ for id in groups {
+ let group = xref.get::<Dict<'_>>(id).ok_or_else(invalid)?;
+ if group.get::<Name<'_>>(b"Type").as_ref().map(AsRef::as_ref) != Some(b"OCG") {
+ return Err(invalid());
+ }
+ let name = group.get::<hayro_syntax::object::String<'_>>(b"Name");
+ let is_hidden = match (hidden.is_empty(), name.as_ref()) {
+ (true, _) => !fallback && (off.contains(&id) || (base_off && !on.contains(&id))),
+ (false, Some(name)) => {
+ let name = String::from_utf8_lossy(name.as_bytes());
+ hidden.iter().any(|n| n == name.as_ref())
+ }
+ (false, None) => return Err(invalid()),
+ };
+ if is_hidden {
+ effective.push(id);
+ }
+ // Unmarked groups are visible when registered in the output catalog.
+ if !is_hidden && name.is_some() {
+ continue;
+ }
+ let marker = is_hidden.to_string();
+ let body = match name {
+ Some(_) => edited(&group, &[(MARKER, marker.as_bytes())])?,
+ None => {
+ if group.contains_key(b"Name") && group.get::<Object<'_>>(b"Name").is_none() {
+ return Err(invalid());
+ }
+ renamed = true;
+ let label = format!("(Placed PDF layer {} {})", id.obj_number, id.gen_number);
+ edited(&group, &[(MARKER, marker.as_bytes()), (b"Name", label.as_bytes())])?
+ }
+ };
+ changes.push((id, body));
+ }
+ effective.sort();
+ effective.dedup();
+ let data = if changes.is_empty() { bytes.clone() } else { Arc::new(append(bytes, &changes, xref.root_id())?) };
+ let mut warnings = Vec::new();
+ if fallback {
+ warnings.push("layer state not readable, all layers shown unless hidden by Object Layer Options");
+ }
+ if incomplete {
+ warnings.push("layer list incomplete; layers named in the default configuration were added");
+ }
+ if renamed {
+ warnings.push("layer display name not readable; generated a name, visibility preserved");
+ }
+ let warning = if warnings.is_empty() { None } else { Some(warnings.join("; ")) };
+ Ok(Variant { data, hidden: effective, warning, has_optional_content: true })
+}
+
+pub(crate) fn register(bytes: &[u8]) -> Result<Vec<u8>> {
+ #[cfg(test)]
+ crate::export::registration_tests::REGISTRATIONS.with(|count| count.set(count.get() + 1));
+ let pdf = Pdf::new(bytes.to_vec()).map_err(|_| invalid())?;
+ let mut groups = Vec::new();
+ let mut changes = Vec::new();
+ for object in pdf.objects() {
+ let Object::Dict(dict) = object else { continue };
+ if dict.get::<Name<'_>>(b"Type").as_ref().map(AsRef::as_ref) != Some(b"OCG") {
+ continue;
+ }
+ // Resource-only OCGs without a catalog configuration are visible by default.
+ let hidden = if dict.contains_key(MARKER) { dict.get::<bool>(MARKER).ok_or_else(invalid)? } else { false };
+ let id = dict.obj_id().ok_or_else(invalid)?;
+ groups.push((id, hidden));
+ changes.push((id, edited(&dict, &[(MARKER, b"")])?));
+ }
+ if groups.is_empty() {
+ return Ok(bytes.to_vec());
+ }
+ groups.sort_by_key(|(id, _)| *id);
+ let refs = |hidden_only: bool| {
+ groups
+ .iter()
+ .filter(|(_, hidden)| !hidden_only || *hidden)
+ .map(|(id, _)| format!("{} {} R", id.obj_number, id.gen_number))
+ .collect::<Vec<_>>()
+ .join(" ")
+ };
+ let all = refs(false);
+ let properties = format!("<</OCGs[{all}]/D<</Name(Placed PDF layers)/BaseState/ON/OFF[{}]/Order[{all}]>>>>", refs(true));
+ let root = pdf.xref().root_id();
+ let catalog = pdf.xref().get::<Dict<'_>>(root).ok_or_else(invalid)?;
+ changes.push((root, edited(&catalog, &[(b"OCProperties", properties.as_bytes())])?));
+ append(bytes, &changes, root)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn visible_named_groups_keep_original_buffer_with_repaired_xref() {
+ let bytes = Arc::new(
+ b"%PDF-1.5\n1 0 obj\n<</Type/Catalog/Pages 2 0 R/OCProperties<</OCGs[4 0 R]/D<</BaseState/ON>>>>>>\nendobj\n\
+ 2 0 obj\n<</Type/Pages/Kids[3 0 R]/Count 1>>\nendobj\n\
+ 3 0 obj\n<</Type/Page/Parent 2 0 R/MediaBox[0 0 100 100]/Resources<<>>>>\nendobj\n\
+ 4 0 obj\n<</Type/OCG/Name(Visible)>>\nendobj\n\
+ trailer\n<</Size 5/Root 1 0 R>>\nstartxref\n1\n%%EOF\n"
+ .to_vec(),
+ );
+ assert!(Pdf::new(bytes.clone()).is_ok());
+
+ let variant = prepare(&bytes, &[]).unwrap();
+
+ assert!(Arc::ptr_eq(&bytes, &variant.data), "visible groups must not copy the complete PDF or require incremental writes");
+ assert!(variant.hidden.is_empty());
+ assert!(variant.warning.is_none());
+ }
+}
diff --git a/crates/pdf/src/registration_tests.rs b/crates/pdf/src/registration_tests.rs
new file mode 100644
index 000000000..e69d87051
--- /dev/null
+++ b/crates/pdf/src/registration_tests.rs
@@ -0,0 +1,204 @@
+use super::*;
+
+fn placed_document(source: Vec<u8>) -> Document {
+ use designcraft_doc::{Asset, Graphic, ItemId, Shape};
+ let mut doc = Document::new(&Default::default());
+ let asset = AssetId(doc.alloc());
+ doc.add_asset(Asset { id: asset, name: "placed.pdf".into(), mime: "application/pdf".into(), data: Arc::new(source), ..Default::default() });
+ let mut item =
+ Item::new(ItemId(doc.alloc()), doc.default_layer(), Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)));
+ item.content = Content::Graphic(Graphic {
+ asset,
+ size: (100.0, 100.0),
+ xf: Affine::IDENTITY,
+ clip: None,
+ auto_fit: Default::default(),
+ fit_align: 4,
+ crop: [0.0; 4],
+ wrap: Default::default(),
+ fill: Default::default(),
+ });
+ doc.insert_item(SpreadRef::Doc(0), item, None).unwrap();
+ doc
+}
+
+fn layered_source(catalog: bool) -> Vec<u8> {
+ let properties = if catalog { "/OCProperties<</OCGs[5 0 R]/D<</OFF[5 0 R]>>>>" } else { "" };
+ let content = b"/OC /a BDC 0.125 0.625 0.875 rg 0 0 100 100 re f EMC";
+ let objects = [
+ format!("<</Type/Catalog/Pages 2 0 R{properties}>>"),
+ "<</Type/Pages/Kids[3 0 R]/Count 1>>".into(),
+ "<</Type/Page/Parent 2 0 R/MediaBox[0 0 100 100]/Resources<</Properties<</a 5 0 R>>>>/Contents 4 0 R>>".into(),
+ format!("<</Length {}>>\nstream\n{}\nendstream", content.len(), String::from_utf8_lossy(content)),
+ "<</Type/OCG/Name(Hidden)>>".into(),
+ ];
+ assemble(&objects)
+}
+
+fn unlayered_source() -> Vec<u8> {
+ let content = "0.125 0.625 0.875 rg 0 0 100 100 re f";
+ assemble(&[
+ "<</Type/Catalog/Pages 2 0 R>>".into(),
+ "<</Type/Pages/Kids[3 0 R]/Count 1>>".into(),
+ "<</Type/Page/Parent 2 0 R/MediaBox[0 0 100 100]/Resources<<>>/Contents 4 0 R>>".into(),
+ format!("<</Length {}>>\nstream\n{content}\nendstream", content.len()),
+ ])
+}
+
+fn assemble(objects: &[String]) -> Vec<u8> {
+ let mut bytes = b"%PDF-1.5\n".to_vec();
+ let mut offsets = Vec::new();
+ for (index, body) in objects.iter().enumerate() {
+ offsets.push(bytes.len());
+ bytes.extend_from_slice(format!("{} 0 obj\n{body}\nendobj\n", index + 1).as_bytes());
+ }
+ let xref = bytes.len();
+ let size = objects.len() + 1;
+ bytes.extend_from_slice(format!("xref\n0 {size}\n0000000000 65535 f\r\n").as_bytes());
+ for offset in offsets {
+ bytes.extend_from_slice(format!("{offset:010} 00000 n\r\n").as_bytes());
+ }
+ bytes.extend_from_slice(format!("trailer\n<</Size {size}/Root 1 0 R>>\nstartxref\n{xref}\n%%EOF\n").as_bytes());
+ bytes
+}
+
+thread_local! {
+ pub(crate) static REGISTRATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
+}
+
+fn registrations(action: impl FnOnce()) -> usize {
+ REGISTRATIONS.set(0);
+ action();
+ REGISTRATIONS.get()
+}
+
+fn check_vector_artwork(pdf: &hayro_syntax::Pdf) {
+ use hayro_syntax::object::{Name, Object};
+
+ let mut found = false;
+ for object in pdf.objects() {
+ let Object::Stream(stream) = object else { continue };
+ let subtype = stream.dict().get::<Name<'_>>(b"Subtype");
+ assert_ne!(subtype.as_ref().map(AsRef::as_ref), Some(b"Image".as_slice()), "placed artwork must remain vector");
+ if subtype.as_ref().map(AsRef::as_ref) == Some(b"Form".as_slice()) {
+ let content = stream.decoded().unwrap();
+ let content = String::from_utf8_lossy(&content);
+ found |= content.contains("0.125 0.625 0.875 rg") && content.contains("0 0 100 100 re f");
+ }
+ }
+ assert!(found, "placed rectangle and its distinctive fill colour must survive in a vector Form XObject");
+}
+
+fn check_unlayered_pdf(bytes: &[u8], pages: usize, artwork: bool) {
+ use hayro_syntax::object::Dict;
+
+ let pdf = hayro_syntax::Pdf::new(bytes.to_vec()).unwrap();
+ assert_eq!(pdf.pages().len(), pages);
+ let catalog = pdf.xref().get::<Dict<'_>>(pdf.xref().root_id()).unwrap();
+ assert!(!catalog.contains_key(b"OCProperties"), "unlayered output must not acquire optional content");
+ if artwork {
+ check_vector_artwork(&pdf);
+ }
+}
+
+fn check_unlayered(doc: &Document, artwork: bool) {
+ let cache = Cache::new();
+ let mut bytes = Vec::new();
+ assert_eq!(
+ registrations(|| {
+ bytes = export_pdf(doc, &cache, &PdfOptions::default()).unwrap();
+ check_unlayered_pdf(&bytes, 1, artwork);
+ }),
+ 0
+ );
+ assert_eq!(
+ registrations(|| {
+ let report = export_booklet(doc, &cache, &BookletOptions::default()).unwrap();
+ check_unlayered_pdf(&report.bytes, 2, artwork);
+ }),
+ 0
+ );
+ assert_eq!(
+ registrations(|| {
+ let merged = merge_pdfs(&[(bytes, vec![(100.0, 100.0)])], None).unwrap();
+ check_unlayered_pdf(&merged, 1, artwork);
+ }),
+ 0
+ );
+}
+
+#[test]
+fn no_placed_pdfs_skip_optional_content_registration() {
+ check_unlayered(&Document::new(&Default::default()), false);
+}
+
+#[test]
+fn unlayered_placed_pdf_skips_optional_content_registration() {
+ check_unlayered(&placed_document(unlayered_source()), true);
+}
+
+#[test]
+fn layered_and_resource_only_inputs_register_optional_content() {
+ for hidden in [true, false] {
+ let source = layered_source(hidden);
+ let doc = placed_document(source.clone());
+ let cache = Cache::new();
+ let mut exported = Vec::new();
+ assert_eq!(
+ registrations(|| {
+ exported = export_pdf(&doc, &cache, &PdfOptions::default()).unwrap();
+ }),
+ 1
+ );
+ check_registered(&exported, hidden);
+ assert_eq!(
+ registrations(|| {
+ let report = export_booklet(&doc, &cache, &BookletOptions::default()).unwrap();
+ check_registered(&report.bytes, hidden);
+ }),
+ 1
+ );
+ for input in [source, exported] {
+ assert_eq!(
+ registrations(|| {
+ let merged = merge_pdfs(&[(input, vec![(100.0, 100.0)])], None).unwrap();
+ check_registered(&merged, hidden);
+ }),
+ 1
+ );
+ }
+ }
+}
+
+fn check_registered(bytes: &[u8], hidden: bool) {
+ use hayro_syntax::object::{Array, Dict, Name, Object, ObjectIdentifier};
+
+ let pdf = hayro_syntax::Pdf::new(bytes.to_vec()).unwrap();
+ check_vector_artwork(&pdf);
+ let xref = pdf.xref();
+ let catalog = xref.get::<Dict<'_>>(xref.root_id()).unwrap();
+ let properties = catalog.get::<Dict<'_>>(b"OCProperties").unwrap();
+ let groups = properties.get::<Array<'_>>(b"OCGs").unwrap();
+ assert_eq!(groups.raw_iter().count(), 1);
+ let group_id: ObjectIdentifier = groups.raw_iter().next().unwrap().as_obj_ref().unwrap().into();
+ let group = xref.get::<Dict<'_>>(group_id).unwrap();
+ assert_eq!(group.get::<Name<'_>>(b"Type").unwrap().as_ref(), b"OCG");
+ assert_eq!(group.get::<hayro_syntax::object::String<'_>>(b"Name").unwrap().as_bytes(), b"Hidden");
+
+ let config = properties.get::<Dict<'_>>(b"D").unwrap();
+ if hidden {
+ let off = config.get::<Array<'_>>(b"OFF").unwrap();
+ assert_eq!(off.raw_iter().count(), 1);
+ let off_id: ObjectIdentifier = off.raw_iter().next().unwrap().as_obj_ref().unwrap().into();
+ assert_eq!(off_id, group_id, "OFF must reference the Hidden OCG listed in OCGs");
+ } else if config.contains_key(b"OFF") {
+ assert_eq!(config.get::<Array<'_>>(b"OFF").unwrap().raw_iter().count(), 0);
+ }
+ // Superseded revisions may retain the marker; readers use only the objects resolved by the current xref.
+ for object in pdf.objects() {
+ let Object::Dict(dict) = object else { continue };
+ if dict.get::<Name<'_>>(b"Type").as_ref().map(AsRef::as_ref) == Some(b"OCG") {
+ assert!(!dict.contains_key(b"DesignCraftHiddenOCG"), "internal marker remains in resolved OCG {:?}", dict.obj_id());
+ }
+ }
+}
diff --git a/crates/pdf/src/text.rs b/crates/pdf/src/text.rs
index 1aaf435d9..655669c6a 100644
--- a/crates/pdf/src/text.rs
+++ b/crates/pdf/src/text.rs
@@ -318,7 +318,7 @@ impl Exporter<'_> {
if let Some(clip) = to_path(&c.clip.to_path(0.1)) {
s.push_clip_path(&clip, &krilla::paint::FillRule::NonZero);
s.push_transform(&tf(Affine::translate((c.clip.x0, c.clip.y0))));
- self.graphic(s, g);
+ self.graphic(s, g, &[]);
s.pop();
s.pop();
}
diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md
index 8ae902a21..9e8f70e8c 100644
--- a/docs/target-app-parity.md
+++ b/docs/target-app-parity.md
@@ -394,7 +394,8 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level
- View ▸ Rotate Spread (`view.rotateSpread`, `layout.rotateSpreadView`): the spread in view turns in quarter turns on screen (stored with the document and in IDML's spread transform; output is unaffected). The canvas maps each spread through its own transform, so tools, snapping, resize handles, guides, overlays and rendering all follow the turned spread.
- Vertical type (Vertical Type Tool, Type ▸ Story Direction `type.storyDirection`, IDML StoryOrientation): the direction belongs to the story, so every frame of a thread is vertical or horizontal together and a frame threaded onto a story takes its direction (`object.textFrameOptions {vertical}` sets the frames' stories); lines run top to bottom and follow each other right to left; the arrow keys follow them (Down and Up along the line, Left and Right to the next and previous line, keeping the position along it); CJK characters stay upright and other text turns, on screen and in PDF; CJK line breaking with basic kinsoku (also in horizontal text); Korean breaks at spaces, word by word (Hangul in any language, hanja in Korean text), or between syllables when the paragraph asks for it (`type.para {koreanCharBreaks}`, Paragraph Style Options ▸ Justification; not written to IDML). Upright text is shaped top to bottom: punctuation and brackets take their vertical forms (OpenType `vert`; `vkrn` and `vpal` through OpenType features), glyphs advance by their vertical metrics (`vmtx`) and hang from their vertical origins (`VORG`) on the centre of the ideographic em box (`BASE`, else OS/2), which the first line's ascent follows; turned text keeps its horizontal forms. Tate-chu-yoko (Type ▸ Tate-Chu-Yoko, `type.tateChuYoko`, IDML `Tatechuyoko`) sets a run such as "12" side by side within one em of the line. Ruby (Type ▸ Ruby…, `type.ruby`, IDML RubyString; group ruby spread 1-2-1 or centred) and kenten emphasis dots (`type.kenten`, IDML KentenKind) are set over their text — to its right in vertical frames — without changing line breaks. Warichu and ruby options (per-character ruby, positions, overhang) aren't there yet.
- Math expressions (Type ▸ Insert Math Expression…, `math.insert`, `math.svg`): a LaTeX subset (fractions, scripts, roots, big operators with limits, Greek, relations and operators with math spacing, `\left…\right`, `\text`) typeset by our own engine into SVG, placed inline at the cursor or as a frame; the LaTeX is kept as alt text and can be edited.
-- Object Layer Options for placed PDFs (`object.pdfLayers`, `object.layerOptions`, Object ▸ Object Layer Options…): the file's optional-content layers listed and shown or hidden per frame on screen; in exported PDFs such graphics go out as 300 ppi images of their visible layers.
+- Object Layer Options for placed PDFs (`object.pdfLayers`, `object.layerOptions`, Object ▸ Object Layer Options…): the file's optional-content layers listed and shown or hidden per frame on screen. Plain and PDF/X-4 exports retain vector artwork and optional content with the source defaults or per-frame overrides, including independent states for repeated placements. Missing or unreadable default configurations and unsupported base states fall back to all-ON defaults with a file-named warning, preserving explicit frame overrides. Readable groups omitted from `/OCGs` are added with a distinct file-named warning, preserving their default ON/OFF states; concurrent recovery warnings are combined. Malformed ON data is recoverable only when a known ON base and empty OFF list prove it cannot hide artwork; missing display names are generated without changing known visibility when no override needs name matching. Contradictory states, unresolved references and ambiguous name overrides remain errors. PDF/A-2b command exports retain the existing 300 ppi raster path for explicit overrides; PDF/A-2 permits optional content, but this change does not extend archival validation. IDML GraphicLayer visibility import remains unsupported.
+- Placed-PDF export preparation is cached per asset and hidden-name set; repeated placements retain recovery warnings (identical warnings are deduplicated). When all groups are visible and named, the original source bytes are embedded without an incremental layer update, including sources whose broken cross-reference tables the reader repairs. Plain, PDF/X-4, booklet and book-merge output register those unmarked groups as visible. Hidden groups or generated names still require a usable cross-reference table; damage errors identify the placed file, and export retains the first placement error rather than replacing it with a later failure.
- Effects: Inner Glow (edge or centre), Bevel and Emboss (inner bevel lit from the light angle), Satin (`object.innerGlow`, `object.bevel`, `object.satin`); PDF export now keeps soft effects: objects with shadows, glows, feathers, bevels or satin go out as 300 ppi transparent images of their appearance (threaded text frames excepted).
- Directional Feather (`object.directionalFeather {widths: [top, left, bottom, right]}`): each side fades over its own width.
- View ▸ Flattener Preview (`view.flattenerPreview`): objects involving transparency highlighted in red; knockout groups export as images (PDF output has no knockout groups).