From 127536c42727da1387600972ece59ece7bcdf331 Mon Sep 17 00:00:00 2001
From: Eric Kaden <608341+EricKaden@users.noreply.github.com>
Date: Sat, 24 Oct 2026 15:33:01 -0400
Subject: [PATCH 1/7] M12: a form saved with its pages is laid out from its
template when it requires dynamic rendering, unless signed
Co-authored-by: EULA <90616501+EULArule@users.noreply.github.com>
---
crates/engine/src/tests.rs | 23 ++++++++++++++
crates/render/src/inspect.rs | 11 +++++--
crates/xfa/README.md | 4 +++
crates/xfa/src/fixtures.rs | 40 +++++++++++++++++++++++++
crates/xfa/src/lib.rs | 11 +++++--
crates/xfa/src/packets.rs | 58 ++++++++++++++++++++++++++++++++++++
crates/xfa/src/tests.rs | 35 ++++++++++++++++++++++
parity/acrobat-features.toml | 4 +--
8 files changed, 180 insertions(+), 6 deletions(-)
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index dc76159d14..202f3a3190 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -5288,6 +5288,29 @@ fn dynamic_xfa_forms_open_with_the_values_and_rows_of_their_data() {
assert!(!doc.dirty);
}
+/// A dynamic form a viewer saved with its pages drawn holds only its signature box, so it opened as
+/// a picture with nothing to fill in. When its configuration says it must be rendered dynamically
+/// it is laid out from its template on opening, and its text field can be filled; once signed, it
+/// opens as saved, its pages and signature untouched.
+#[test]
+fn a_form_saved_with_its_pages_that_requires_dynamic_rendering_is_laid_out_unless_signed() {
+ let mut s = Session::new().with_clock(|| 1_700_000_000);
+ let unsigned = Arc::new(pdfcraft_xfa::fixtures::saved_with_pages_shell("required", false));
+ let id = s.open("saved.pdf", None, unsigned, None).expect("opens");
+ let doc = s.get(id).unwrap();
+ assert_eq!(doc.info.xfa, Some(pdfcraft_render::Xfa::Dynamic));
+ assert!(doc.xfa.is_some(), "laid out from the template");
+ let name = doc.form.iter().find(|f| f.name.contains("name")).map(|f| f.name.clone()).expect("the template's text field");
+ s.apply(id, Edit::SetFieldValue { name: name.clone(), value: FieldValue::Text("Ada".into()) }).expect("fills");
+ assert_eq!(s.get(id).unwrap().form.iter().find(|f| f.name == name).map(|f| f.value.clone()), Some(vec!["Ada".to_string()]));
+ let signed = Arc::new(pdfcraft_xfa::fixtures::saved_with_pages_shell("required", true));
+ let id = s.open("signed.pdf", None, signed.clone(), None).expect("opens");
+ let doc = s.get(id).unwrap();
+ assert_eq!(doc.info.xfa, Some(pdfcraft_render::Xfa::Static), "signed: as saved");
+ assert!(doc.xfa.is_none(), "nothing was laid out");
+ assert_eq!(doc.bytes[..], signed[..], "no revision was appended on open");
+}
+
/// #3180: an XFA form with no fields whose configuration says `dynamicRender` is `forbidden` is a
/// static form: its pages are the form. Opening it used to lay the template out into new pages
/// and write them as a revision, so even a save with no change replaced the pages.
diff --git a/crates/render/src/inspect.rs b/crates/render/src/inspect.rs
index 827e678567..4290c3c48a 100644
--- a/crates/render/src/inspect.rs
+++ b/crates/render/src/inspect.rs
@@ -809,8 +809,15 @@ impl<'a> Inspector<'a> {
// A form with no fields is taken to be laid out from its template, unless its
// configuration says it is a static form (#3180): Designer writes
// `forbidden ` for one, whose pages are the form.
- let static_form = self.xfa_dynamic_render(xfa).as_deref() == Some("forbidden");
- info.xfa = Some(if needs_rendering || (info.fields.is_empty() && !static_form) { Xfa::Dynamic } else { Xfa::Static });
+ let render = self.xfa_dynamic_render(xfa);
+ let static_form = render.as_deref() == Some("forbidden");
+ // A form a viewer saved with its pages drawn, whose configuration says it must be
+ // rendered dynamically, is laid out from its template too: its fields live there.
+ // Not once it is signed: the signature covers the pages as saved (the xfa crate's
+ // `is_dynamic` keeps the same rule).
+ let signed = info.fields.iter().any(|f| f.kind == FieldKind::Signature && f.value.is_some());
+ let required = render.as_deref() == Some("required") && !signed;
+ info.xfa = Some(if needs_rendering || required || (info.fields.is_empty() && !static_form) { Xfa::Dynamic } else { Xfa::Static });
}
self.layers(catalog, &mut info.layers);
info.layer_groups = self.layer_groups(catalog);
diff --git a/crates/xfa/README.md b/crates/xfa/README.md
index 23a6ef0d0e..a48b43c6ec 100644
--- a/crates/xfa/README.md
+++ b/crates/xfa/README.md
@@ -134,6 +134,10 @@ let form = pdfcraft_xfa::layout_xml(template_xml)?; // pages of items, for
only their data is read and written. A form with no fields is also static when its `config`
packet says `forbidden ` (Designer's static PDF form): its pages
are the form and are not laid out again (#3180). Without that, no fields means dynamic.
+ The other way round, a form with fields is dynamic when its `config` packet says
+ `required `: a viewer saved it with its pages drawn and only its
+ signature boxes as fields, so its other fields live in the template. Once one of those boxes
+ is signed it stays as saved, since laying it out would change the pages the signature covers.
- **Flattening and converting.** `strip` takes the XFA out of a document: the packets,
`/NeedsRendering`, the layout mark, the overrides and the private keys on the fields. The
engine calls it after flattening an XFA form's fields (so Adobe's viewers show the baked
diff --git a/crates/xfa/src/fixtures.rs b/crates/xfa/src/fixtures.rs
index b76b3efa1a..f563ad7988 100644
--- a/crates/xfa/src/fixtures.rs
+++ b/crates/xfa/src/fixtures.rs
@@ -674,6 +674,46 @@ pub fn signed_shell() -> Vec {
assemble(objs)
}
+/// A dynamic form as a viewer saves it with its pages drawn: no `/NeedsRendering`, a page with
+/// the form's picture, and only its signature box `sign` among the AcroForm's fields (the text
+/// field `name` lives in the template), signed when `signed`. Its configuration packet says
+/// `{render} ` (none when `render` is empty).
+pub fn saved_with_pages_shell(render: &str, signed: bool) -> Vec {
+ let config = if render.is_empty() {
+ String::new()
+ } else {
+ format!(
+ r#"1.7 {render} "#
+ )
+ };
+ let xdp = format!(
+ r##"
+
+{config}
+
+
+
+
+
+
+
+
+"##
+ );
+ let value = if signed { " /V 7 0 R" } else { "" };
+ let picture = "BT /F1 12 Tf 72 700 Td (Name: ______) Tj ET";
+ let objs: Vec> = vec![
+ b"<< /Type /Catalog /Pages 2 0 R /AcroForm << /XFA 5 0 R /Fields [6 0 R] /SigFlags 3 >> >>".to_vec(),
+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Annots [6 0 R] >>".to_vec(),
+ format!("<< /Length {} >>\nstream\n{picture}\nendstream", picture.len()).into_bytes(),
+ format!("<< /Length {} >>\nstream\n{xdp}\nendstream", xdp.len()).into_bytes(),
+ format!("<< /T (form[0].sign[0]) /FT /Sig{value} /Type /Annot /Subtype /Widget /Rect [72 500 288 572] /P 3 0 R >>").into_bytes(),
+ b"<< /Type /Sig /Name (A Signer) >>".to_vec(),
+ ];
+ assemble(objs)
+}
+
/// A check box `kind` whose change script, once it is checked, opens the protected check box
/// `leave` and shows the invisible field `details`, then fails on an object the form doesn't
/// have (as scripts written for an earlier version of a form do).
diff --git a/crates/xfa/src/lib.rs b/crates/xfa/src/lib.rs
index 7fe372d53a..a90c335231 100644
--- a/crates/xfa/src/lib.rs
+++ b/crates/xfa/src/lib.rs
@@ -130,9 +130,16 @@ pub struct Report {
}
/// Is this a dynamic XFA form still showing its placeholder pages (one PdfCraft has not laid
-/// out yet)?
+/// out yet)? That is a form that asks to be laid out (`/NeedsRendering`), one with no fields of
+/// its own, or one a viewer saved with its pages drawn whose configuration says it must be
+/// rendered dynamically (`required `): its fields live in the
+/// template. A signature on such a form covers the pages as saved, so a signed one is left as it
+/// is: laying it out would change what was signed.
pub fn is_dynamic(doc: &Document) -> bool {
- existing_layout(doc).is_none() && matches!(read_packets(doc), Ok(Some(p)) if p.needs_rendering || !p.has_fields)
+ existing_layout(doc).is_none()
+ && matches!(read_packets(doc), Ok(Some(p)) if p.needs_rendering
+ || !p.has_fields
+ || (packets::requires_dynamic_render(&p.xdp) && !packets::has_signature(doc)))
}
/// Lay a template packet (or whole XDP, whose datasets then fill the fields) out.
diff --git a/crates/xfa/src/packets.rs b/crates/xfa/src/packets.rs
index f79b071c0e..d1ac1831e3 100644
--- a/crates/xfa/src/packets.rs
+++ b/crates/xfa/src/packets.rs
@@ -97,6 +97,64 @@ fn to_text(bytes: &[u8]) -> String {
}
}
+/// Whether the XDP's configuration packet asks for dynamic rendering: `required` at
+/// `config/acrobat/acrobat7/dynamicRender` (Designer writes it for a dynamic form). The same
+/// names in the template or the data are not the configuration.
+pub(crate) fn requires_dynamic_render(xdp: &str) -> bool {
+ // The configuration packet: from `' || c.is_whitespace()))
+ else {
+ return false;
+ };
+ let Some(packet) = xdp.get(start..).and_then(|r| r.find(" ").and_then(|end| r.get(..end + "".len()))) else {
+ return false;
+ };
+ let Ok(config) = roxmltree::Document::parse(packet) else { return false };
+ let mut node = config.root_element();
+ for name in ["acrobat", "acrobat7", "dynamicRender"] {
+ match node.children().find(|c| c.is_element() && c.tag_name().name() == name) {
+ Some(c) => node = c,
+ None => return false,
+ }
+ }
+ node.text().is_some_and(|t| t.trim() == "required")
+}
+
+/// Whether the AcroForm holds a signed signature field (`/FT /Sig` with a value), looked for at
+/// most 32 levels deep and among at most 10 000 fields.
+pub(crate) fn has_signature(doc: &Document) -> bool {
+ let Some(root) = doc.root() else { return false };
+ let catalog = doc.get(root);
+ let Some(acro) = catalog.as_dict().and_then(|c| c.get(b"AcroForm")).map(|a| doc.resolve(a)) else { return false };
+ let Some(fields) = acro.as_dict().and_then(|a| a.get(b"Fields")).map(|f| doc.resolve(f)) else { return false };
+ let Some(fields) = fields.as_array() else { return false };
+ // (field, inherited field type, depth)
+ let mut todo: Vec<(Object, bool, usize)> = fields.iter().map(|f| (f.clone(), false, 0)).collect();
+ let mut seen = std::collections::HashSet::new();
+ let mut budget = 10_000usize;
+ while let Some((f, sig_above, depth)) = todo.pop() {
+ if budget == 0 || depth > 32 || f.as_ref().is_some_and(|r| !seen.insert(r)) {
+ continue;
+ }
+ budget -= 1;
+ let f = doc.resolve(&f);
+ let Some(d) = f.as_dict() else { continue };
+ let sig = d.name(b"FT").map_or(sig_above, |t| t == b"Sig");
+ if sig && d.get(b"V").is_some_and(|v| !matches!(&*doc.resolve(v), Object::Null)) {
+ return true;
+ }
+ if let Some(kids) = d.get(b"Kids").map(|k| doc.resolve(k))
+ && let Some(kids) = kids.as_array()
+ {
+ todo.extend(kids.iter().map(|k| (k.clone(), sig, depth + 1)));
+ }
+ }
+ false
+}
+
/// Read the XFA packets, if the document has any.
pub fn read_packets(doc: &Document) -> Result, XfaError> {
let Some(root) = doc.root() else { return Ok(None) };
diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs
index 3175882f89..7bb0b7d4ca 100644
--- a/crates/xfa/src/tests.rs
+++ b/crates/xfa/src/tests.rs
@@ -299,6 +299,41 @@ fn tables_break_across_pages_and_repeat_their_header_row() {
assert_eq!(all.len(), all.iter().collect::>().len(), "field names are unique");
}
+/// A form a viewer saved with its pages drawn, holding only its signature box, is laid out from
+/// its template when its configuration says it must be rendered dynamically: its other fields
+/// live there. Signed, it is left as saved (laying it out would change what was signed), as it is
+/// without that configuration or with `forbidden`.
+#[test]
+fn a_form_saved_with_its_pages_is_laid_out_when_it_requires_dynamic_rendering() {
+ let open = |render: &str, signed: bool| Document::open(Arc::new(crate::fixtures::saved_with_pages_shell(render, signed))).unwrap();
+ let mut doc = open("required", false);
+ assert!(is_dynamic(&doc));
+ let report = render_into(&mut doc).unwrap();
+ assert_eq!(report.fields, 2, "the text field from the template, and the signature box");
+ assert!(!is_dynamic(&open("required", true)), "signed: left as saved");
+ assert!(!is_dynamic(&open("", false)), "no configuration: the fields it has are the form's");
+ assert!(!is_dynamic(&open("forbidden", false)));
+}
+
+/// Only the configuration packet's `acrobat/acrobat7/dynamicRender` asks for dynamic rendering:
+/// not the same element elsewhere, another element that starts with `config`, or another value.
+#[test]
+fn dynamic_rendering_is_read_from_the_configuration_only() {
+ let required = crate::packets::requires_dynamic_render;
+ let config = |inner: &str| {
+ format!(
+ r#"{inner} "#
+ )
+ };
+ assert!(required(&config(" required ")));
+ assert!(!required(&config("forbidden ")));
+ assert!(!required(&config("required ")), "not under acrobat7");
+ assert!(!required(&config("")));
+ assert!(!required("required "));
+ assert!(!required("required "));
+ assert!(!required("required"), "no end tag");
+}
+
#[test]
fn rendering_into_the_pdf_replaces_the_placeholder_page_and_adds_fields() {
let mut doc = Document::open(Arc::new(shell(&template(2)))).unwrap();
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index 2c9cf17197..852eda27f0 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -5296,8 +5296,8 @@ milestone = "M12"
status = "partial"
commands = ["file.open"]
tools = ["doc_open", "doc_info", "form_fields", "form_fill", "js_run"]
-evidence = ["crates/xfa/src/tests.rs::layout_places_captions_fields_and_sizes_containers_to_their_content", "crates/xfa/src/tests.rs::tables_break_across_pages_and_repeat_their_header_row", "crates/xfa/src/tests.rs::rendering_into_the_pdf_replaces_the_placeholder_page_and_adds_fields", "crates/engine/src/tests.rs::dynamic_xfa_forms_are_laid_out_on_open_filled_and_saved_incrementally", "crates/automation/tests/it/automation.rs::dynamic_xfa_forms_open_render_fill_and_save_through_tools", "crates/ui-egui/tests/it/xfa.rs::a_dynamic_xfa_form_is_laid_out_and_filled", "crates/xfa/src/tests.rs::nested_width_less_subforms_lay_out_in_polynomial_time", "crates/js/src/tests.rs::instance_managers_add_remove_and_count", "crates/xfa/src/tests.rs::the_form_tree_carries_values_presence_instances_and_the_events", "crates/engine/src/tests.rs::xfa_scripts_initialize_calculate_validate_toggle_and_add_rows", "crates/engine/src/tests.rs::xfa_date_arithmetic_reads_the_date_as_its_display_picture_shows_it", "crates/automation/tests/it/automation.rs::xfa_scripts_run_for_buttons_and_field_changes_through_tools", "crates/ui-egui/tests/it/xfa.rs::xfa_buttons_run_their_scripts_in_the_app", "crates/engine/src/tests.rs::hostile_xfa_open_scripts_are_merged_capped_kept_from_printing_and_noted", "crates/engine/src/tests.rs::runaway_xfa_calculations_at_open_end_quickly_with_a_report", "crates/ui-egui/tests/it/xfa.rs::a_form_whose_scripts_were_turned_off_at_open_says_so", "crates/ui-egui/tests/it/xfa.rs::scripts_turned_off_by_a_click_bring_a_closed_notice_bar_back", "crates/automation/tests/it/automation.rs::doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off", "crates/xfa/src/tests.rs::the_live_form_of_nested_repeating_subforms_stops_at_its_node_budget", "crates/xfa/src/tests.rs::data_ops_of_one_event_are_one_datasets_rewrite", "crates/xfa/src/tests.rs::choice_lists_signatures_passwords_and_pictures_become_fields_and_images", "crates/xfa/src/tests.rs::choice_values_come_from_the_data_as_saved_values_and_several_for_lists", "crates/xfa/src/tests.rs::pictures_are_sized_from_their_headers_and_hostile_ones_are_refused_unallocated", "crates/engine/src/tests.rs::xfa_choice_lists_signature_and_picture_fields_open_fill_script_and_save", "crates/xfa/src/tests.rs::repeating_subforms_inside_positioned_content_get_their_instances", "crates/engine/src/tests.rs::xfa_rows_in_areas_are_laid_out_read_calculated_and_written_where_adobe_binds_them", "crates/xfa/src/tests.rs::page_area_without_occur_serves_every_body_page", "apps/pdfcraft-cli/tests/it/xfa.rs::info_reports_the_laid_out_pages_and_fields", "apps/pdfcraft-cli/tests/it/xfa.rs::text_reads_the_layout_including_a_page_absent_from_the_placeholder", "apps/pdfcraft-cli/tests/it/xfa.rs::render_matches_the_engine_layout_on_the_second_page", "apps/pdfcraft-cli/tests/it/xfa.rs::a_laid_out_form_keeps_the_original_copy_permissions", "crates/engine/src/tests.rs::filling_growable_xfa_text_reflows_and_undo_restores_the_layout", "crates/engine/src/tests.rs::xfa_text_growth_refreshes_widget_geometry_but_fixed_height_fields_keep_their_widgets", "crates/automation/tests/it/automation.rs::growable_xfa_text_paginates_after_fill_save_and_print", "crates/engine/src/tests.rs::an_xfa_script_that_fails_partway_keeps_what_it_changed_before_the_error", "crates/engine/src/tests.rs::repeated_xfa_print_buttons_run_their_click_script", "crates/automation/tests/it/automation.rs::repeated_xfa_print_buttons_work_through_tools_and_after_reopen", "crates/xfa/src/tests.rs::rich_text_max_length_reaches_the_field_and_layout", "crates/automation/tests/it/automation.rs::xfa_rich_text_max_length_is_reported_and_enforced_through_tools", "crates/xfa/src/tests.rs::bmp_and_tiff_pictures_are_decoded_and_drawn", "crates/engine/src/tests.rs::active_xfa_does_not_run_pdf_container_scripts_but_keeps_requested_alerts", "crates/engine/src/tests.rs::active_xfa_without_template_scripts_does_not_initialize_pdf_fallback_scripts", "crates/engine/src/tests.rs::inactive_xfa_and_ordinary_pdfs_keep_document_helpers_and_alerts", "crates/automation/tests/it/automation.rs::active_xfa_skips_container_fallback_scripts_after_save_and_reopen", "crates/xfa/src/tests.rs::laying_a_form_out_takes_off_the_usage_rights_it_voids", "crates/engine/src/tests.rs::a_dynamic_xfa_form_is_saved_without_the_usage_rights_its_layout_voided", "crates/xfa/src/tests.rs::faces_measure_text_at_their_standard_14_widths", "crates/xfa/src/tests.rs::rich_text_links_keep_their_address", "crates/xfa/src/tests.rs::links_in_rich_text_become_link_annotations_one_per_line", "crates/xfa/src/tests.rs::a_links_pieces_share_one_address", "crates/xfa/src/tests.rs::a_rule_between_two_pieces_of_a_link_keeps_them_apart", "crates/xfa/src/tests.rs::links_to_anything_but_web_and_email_addresses_stay_plain_text", "crates/automation/tests/it/automation.rs::links_in_xfa_rich_text_are_listed_through_tools", "crates/xfa/src/tests.rs::rounded_corners_make_a_border_one_rounded_shape", "crates/xfa/src/tests.rs::a_rounded_box_cut_by_a_page_break_keeps_its_corners_on_each_page", "crates/xfa/src/tests.rs::rounded_boxes_are_written_as_curved_paths", "crates/xfa/src/tests.rs::a_flowed_subform_is_drawn_with_its_border_under_its_content", "crates/xfa/src/tests.rs::a_check_box_sits_where_its_margins_caption_and_alignment_put_it", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_takes_the_rest_of_the_field", "crates/xfa/src/tests.rs::a_radio_button_sits_where_a_check_box_would", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_is_measured_as_it_is_drawn"]
-notes = "Active XFA layout skips PDF-container document-script initialization for the Acrobat console/field context, so fallback-viewer scripts do not run there. Scripts remain in the file/listing; explicit console/field and XFA alerts still run. Ordinary PDF, static XFA and unlaid-out shells keep document scripts; static-conversion undo restores the XFA policy. Changed growable multiline text (no fixed h) reflows from final datasets after edits, with or without scripts; pages/widgets refresh and undo/redo, save/reopen and print retain all text. Oversized text still uses the existing read-only page-text fallback with a warning; fixed-height fields do not reflow. Repeated page-master buttons resolve their own PDF field to the shared XFA click script; the numPages-based print script requests printing from every copy, including after save/reopen (#2572). Rich-text exData/maxLength is carried into AcroForm MaxLen, reported by form_fields and enforced by form_fill (Unicode characters); limits and accepted values survive save/reopen (#2570). laid out from the template on open by the xfa crate (positioned, tb, lr-tb, table/row, page masters (a page area with no occur repeats without limit, one with occur max=1 is used once, one with occur min=1 the body never reached gets a page after the body, as Acrobat Pro does on a synthetic form), breaks, repeated header rows, borders and fills of flowed subforms (a page break between their children gives each page's part a closed border, the margins repeated at the cut, as measured on a synthetic form in another viewer, and a child's own page break breaks them the same way; one holding an item that doesn't fit on its page, cut across pages or placed past the content area's bottom, is drawn without its border, with a layout warning), captions, rounded and inverted border corners, rich text (its http, https and mailto links clickable), JPEG/PNG/GIF/BMP/TIFF images) into real pages and AcroForm fields (text, password, date with AFDate formats, check boxes and radio groups (each box placed by its field's margins, caption and paragraph alignment as measured on two synthetic forms in another viewer: with no caption at the right of the content area, beside a reserved caption where the alignment puts it, and a caption without a reserve taking the rest of the field; a check box's own margin larger than the box draws a bigger box there, which isn't copied), drop-downs and list boxes with shown/saved item pairs and multi-select, signature fields, image fields showing their picture (pictures decoded once per document, at most 20 million pixels, and reused across re-layouts), buttons with reset/print/save/URL), filled from the datasets packet (including rows another viewer added), saved as an incremental revision with the values merged into the datasets so Adobe's viewers show them; usage rights the form carried (/Perms /UR3) are taken off with a note, as the layout voids them and a form with void usage rights opens with every field locked; doc_info reports xfa_layout. CLI info reports the laid-out page/field counts and dimensions while retaining the input file size and raw counts as pdf_pages/acroform_fields; text and render use those pages too, preserving copy permissions and leaving the source file unchanged (#1645). XFA JavaScript and FormCalc (form.xfa-formcalc) run in the js crate's XFA object model (xfa.form, SOM resolution, rawValue, formattedValue in a date display picture's pattern (number and text display pictures still give the raw value), presence, access, instance managers, xfa.host, xfa.layout, xfa.event): initialize and calculate on open, exit, validate and calculate after a field changes, click for buttons (through js_run and the app), with rows added and removed, subforms shown and hidden, and the form laid out again, all as one undo step and kept in the file. All the scripts of one event run on one thread, each in a fresh context on the form as the engine holds it then (nothing shared between scripts; the live form kept up to date in place for values, rebuilt only when the structure changed), so hundreds of calculations run within the open budget. Hostile scripts are bounded per event (merged and capped effects, messages and console lines, lower loop limits and a time budget on open and calculate, one datasets rewrite per event, print/save/links/focus from clicks only, a runaway script abandoned and the form's scripts turned off, which the app says in a toast and on the notice bar, with a button to the JavaScript console, and doc_info reports as xfa_scripts_off) and what open-time scripts changed is noted. A script that fails partway keeps what it changed before the error, as JavaScript does (forms often trip over an object an earlier version had after their first lines did the work). Missing: a page area's relevant=\"-print\" (on a synthetic form Acrobat still prints the page but leaves it blank; PdfCraft prints its content, #2574); a page break before the first section (Acrobat opens an empty body page first when the first section has breakBefore targetType=pageArea, with or without startNew, as seen on synthetic forms; PdfCraft skips a break on an empty page and lays out one page fewer, #2574); loops inside nested calls are only stopped by abandoning their thread, and script memory is not capped; the change event per keystroke; xfa.template, connections and data descriptions; a hidden instance of a repeating subform hides them all; barcodes are drawn as their text, not bars; keep rules; text is measured at the exact standard-14 widths of the face it is drawn in (bold, italic and Times included), not in the template's own typefaces, and Acrobat fidelity is eyeballed on real forms, not measured (#60)"
+evidence = ["crates/xfa/src/tests.rs::layout_places_captions_fields_and_sizes_containers_to_their_content", "crates/xfa/src/tests.rs::tables_break_across_pages_and_repeat_their_header_row", "crates/xfa/src/tests.rs::rendering_into_the_pdf_replaces_the_placeholder_page_and_adds_fields", "crates/xfa/src/tests.rs::a_form_saved_with_its_pages_is_laid_out_when_it_requires_dynamic_rendering", "crates/engine/src/tests.rs::a_form_saved_with_its_pages_that_requires_dynamic_rendering_is_laid_out_unless_signed", "crates/engine/src/tests.rs::dynamic_xfa_forms_are_laid_out_on_open_filled_and_saved_incrementally", "crates/automation/tests/it/automation.rs::dynamic_xfa_forms_open_render_fill_and_save_through_tools", "crates/ui-egui/tests/it/xfa.rs::a_dynamic_xfa_form_is_laid_out_and_filled", "crates/xfa/src/tests.rs::nested_width_less_subforms_lay_out_in_polynomial_time", "crates/js/src/tests.rs::instance_managers_add_remove_and_count", "crates/xfa/src/tests.rs::the_form_tree_carries_values_presence_instances_and_the_events", "crates/engine/src/tests.rs::xfa_scripts_initialize_calculate_validate_toggle_and_add_rows", "crates/engine/src/tests.rs::xfa_date_arithmetic_reads_the_date_as_its_display_picture_shows_it", "crates/automation/tests/it/automation.rs::xfa_scripts_run_for_buttons_and_field_changes_through_tools", "crates/ui-egui/tests/it/xfa.rs::xfa_buttons_run_their_scripts_in_the_app", "crates/engine/src/tests.rs::hostile_xfa_open_scripts_are_merged_capped_kept_from_printing_and_noted", "crates/engine/src/tests.rs::runaway_xfa_calculations_at_open_end_quickly_with_a_report", "crates/ui-egui/tests/it/xfa.rs::a_form_whose_scripts_were_turned_off_at_open_says_so", "crates/ui-egui/tests/it/xfa.rs::scripts_turned_off_by_a_click_bring_a_closed_notice_bar_back", "crates/automation/tests/it/automation.rs::doc_info_says_when_a_runaway_script_turned_the_forms_scripts_off", "crates/xfa/src/tests.rs::the_live_form_of_nested_repeating_subforms_stops_at_its_node_budget", "crates/xfa/src/tests.rs::data_ops_of_one_event_are_one_datasets_rewrite", "crates/xfa/src/tests.rs::choice_lists_signatures_passwords_and_pictures_become_fields_and_images", "crates/xfa/src/tests.rs::choice_values_come_from_the_data_as_saved_values_and_several_for_lists", "crates/xfa/src/tests.rs::pictures_are_sized_from_their_headers_and_hostile_ones_are_refused_unallocated", "crates/engine/src/tests.rs::xfa_choice_lists_signature_and_picture_fields_open_fill_script_and_save", "crates/xfa/src/tests.rs::repeating_subforms_inside_positioned_content_get_their_instances", "crates/engine/src/tests.rs::xfa_rows_in_areas_are_laid_out_read_calculated_and_written_where_adobe_binds_them", "crates/xfa/src/tests.rs::page_area_without_occur_serves_every_body_page", "apps/pdfcraft-cli/tests/it/xfa.rs::info_reports_the_laid_out_pages_and_fields", "apps/pdfcraft-cli/tests/it/xfa.rs::text_reads_the_layout_including_a_page_absent_from_the_placeholder", "apps/pdfcraft-cli/tests/it/xfa.rs::render_matches_the_engine_layout_on_the_second_page", "apps/pdfcraft-cli/tests/it/xfa.rs::a_laid_out_form_keeps_the_original_copy_permissions", "crates/engine/src/tests.rs::filling_growable_xfa_text_reflows_and_undo_restores_the_layout", "crates/engine/src/tests.rs::xfa_text_growth_refreshes_widget_geometry_but_fixed_height_fields_keep_their_widgets", "crates/automation/tests/it/automation.rs::growable_xfa_text_paginates_after_fill_save_and_print", "crates/engine/src/tests.rs::an_xfa_script_that_fails_partway_keeps_what_it_changed_before_the_error", "crates/engine/src/tests.rs::repeated_xfa_print_buttons_run_their_click_script", "crates/automation/tests/it/automation.rs::repeated_xfa_print_buttons_work_through_tools_and_after_reopen", "crates/xfa/src/tests.rs::rich_text_max_length_reaches_the_field_and_layout", "crates/automation/tests/it/automation.rs::xfa_rich_text_max_length_is_reported_and_enforced_through_tools", "crates/xfa/src/tests.rs::bmp_and_tiff_pictures_are_decoded_and_drawn", "crates/engine/src/tests.rs::active_xfa_does_not_run_pdf_container_scripts_but_keeps_requested_alerts", "crates/engine/src/tests.rs::active_xfa_without_template_scripts_does_not_initialize_pdf_fallback_scripts", "crates/engine/src/tests.rs::inactive_xfa_and_ordinary_pdfs_keep_document_helpers_and_alerts", "crates/automation/tests/it/automation.rs::active_xfa_skips_container_fallback_scripts_after_save_and_reopen", "crates/xfa/src/tests.rs::laying_a_form_out_takes_off_the_usage_rights_it_voids", "crates/engine/src/tests.rs::a_dynamic_xfa_form_is_saved_without_the_usage_rights_its_layout_voided", "crates/xfa/src/tests.rs::faces_measure_text_at_their_standard_14_widths", "crates/xfa/src/tests.rs::rich_text_links_keep_their_address", "crates/xfa/src/tests.rs::links_in_rich_text_become_link_annotations_one_per_line", "crates/xfa/src/tests.rs::a_links_pieces_share_one_address", "crates/xfa/src/tests.rs::a_rule_between_two_pieces_of_a_link_keeps_them_apart", "crates/xfa/src/tests.rs::links_to_anything_but_web_and_email_addresses_stay_plain_text", "crates/automation/tests/it/automation.rs::links_in_xfa_rich_text_are_listed_through_tools", "crates/xfa/src/tests.rs::rounded_corners_make_a_border_one_rounded_shape", "crates/xfa/src/tests.rs::a_rounded_box_cut_by_a_page_break_keeps_its_corners_on_each_page", "crates/xfa/src/tests.rs::rounded_boxes_are_written_as_curved_paths", "crates/xfa/src/tests.rs::a_flowed_subform_is_drawn_with_its_border_under_its_content", "crates/xfa/src/tests.rs::a_check_box_sits_where_its_margins_caption_and_alignment_put_it", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_takes_the_rest_of_the_field", "crates/xfa/src/tests.rs::a_radio_button_sits_where_a_check_box_would", "crates/xfa/src/tests.rs::a_check_box_caption_without_a_reserve_is_measured_as_it_is_drawn"]
+notes = "Active XFA layout skips PDF-container document-script initialization for the Acrobat console/field context, so fallback-viewer scripts do not run there. Scripts remain in the file/listing; explicit console/field and XFA alerts still run. Ordinary PDF, static XFA and unlaid-out shells keep document scripts; static-conversion undo restores the XFA policy. Changed growable multiline text (no fixed h) reflows from final datasets after edits, with or without scripts; pages/widgets refresh and undo/redo, save/reopen and print retain all text. Oversized text still uses the existing read-only page-text fallback with a warning; fixed-height fields do not reflow. Repeated page-master buttons resolve their own PDF field to the shared XFA click script; the numPages-based print script requests printing from every copy, including after save/reopen (#2572). Rich-text exData/maxLength is carried into AcroForm MaxLen, reported by form_fields and enforced by form_fill (Unicode characters); limits and accepted values survive save/reopen (#2570). laid out from the template on open by the xfa crate (positioned, tb, lr-tb, table/row, page masters (a page area with no occur repeats without limit, one with occur max=1 is used once, one with occur min=1 the body never reached gets a page after the body, as Acrobat Pro does on a synthetic form), breaks, repeated header rows, borders and fills of flowed subforms (a page break between their children gives each page's part a closed border, the margins repeated at the cut, as measured on a synthetic form in another viewer, and a child's own page break breaks them the same way; one holding an item that doesn't fit on its page, cut across pages or placed past the content area's bottom, is drawn without its border, with a layout warning), captions, rounded and inverted border corners, rich text (its http, https and mailto links clickable), JPEG/PNG/GIF/BMP/TIFF images) into real pages and AcroForm fields (text, password, date with AFDate formats, check boxes and radio groups (each box placed by its field's margins, caption and paragraph alignment as measured on two synthetic forms in another viewer: with no caption at the right of the content area, beside a reserved caption where the alignment puts it, and a caption without a reserve taking the rest of the field; a check box's own margin larger than the box draws a bigger box there, which isn't copied), drop-downs and list boxes with shown/saved item pairs and multi-select, signature fields, image fields showing their picture (pictures decoded once per document, at most 20 million pixels, and reused across re-layouts), buttons with reset/print/save/URL), filled from the datasets packet (including rows another viewer added), saved as an incremental revision with the values merged into the datasets so Adobe's viewers show them; usage rights the form carried (/Perms /UR3) are taken off with a note, as the layout voids them and a form with void usage rights opens with every field locked; doc_info reports xfa_layout. CLI info reports the laid-out page/field counts and dimensions while retaining the input file size and raw counts as pdf_pages/acroform_fields; text and render use those pages too, preserving copy permissions and leaving the source file unchanged (#1645). A form a viewer saved with its pages drawn and only its signature boxes as fields is laid out too when its configuration says dynamicRender is required, unless one of those boxes is signed: that one stays as saved, and is fillable only once filling a signed dynamic form is designed (#4309). XFA JavaScript and FormCalc (form.xfa-formcalc) run in the js crate's XFA object model (xfa.form, SOM resolution, rawValue, formattedValue in a date display picture's pattern (number and text display pictures still give the raw value), presence, access, instance managers, xfa.host, xfa.layout, xfa.event): initialize and calculate on open, exit, validate and calculate after a field changes, click for buttons (through js_run and the app), with rows added and removed, subforms shown and hidden, and the form laid out again, all as one undo step and kept in the file. All the scripts of one event run on one thread, each in a fresh context on the form as the engine holds it then (nothing shared between scripts; the live form kept up to date in place for values, rebuilt only when the structure changed), so hundreds of calculations run within the open budget. Hostile scripts are bounded per event (merged and capped effects, messages and console lines, lower loop limits and a time budget on open and calculate, one datasets rewrite per event, print/save/links/focus from clicks only, a runaway script abandoned and the form's scripts turned off, which the app says in a toast and on the notice bar, with a button to the JavaScript console, and doc_info reports as xfa_scripts_off) and what open-time scripts changed is noted. A script that fails partway keeps what it changed before the error, as JavaScript does (forms often trip over an object an earlier version had after their first lines did the work). Missing: a page area's relevant=\"-print\" (on a synthetic form Acrobat still prints the page but leaves it blank; PdfCraft prints its content, #2574); a page break before the first section (Acrobat opens an empty body page first when the first section has breakBefore targetType=pageArea, with or without startNew, as seen on synthetic forms; PdfCraft skips a break on an empty page and lays out one page fewer, #2574); loops inside nested calls are only stopped by abandoning their thread, and script memory is not capped; the change event per keystroke; xfa.template, connections and data descriptions; a hidden instance of a repeating subform hides them all; barcodes are drawn as their text, not bars; keep rules; text is measured at the exact standard-14 widths of the face it is drawn in (bold, italic and Times included), not in the template's own typefaces, and Acrobat fidelity is eyeballed on real forms, not measured (#60)"
[[feature]]
id = "form.xfa-formcalc"
From 7d6bf5c1cbfbbbd82e540926c217edc45f4408b6 Mon Sep 17 00:00:00 2001
From: Eric Kaden <608341+EricKaden@users.noreply.github.com>
Date: Sat, 24 Oct 2026 15:40:49 -0400
Subject: [PATCH 2/7] M12: doc comments on the functions the dynamicRender
change touches
---
crates/engine/src/tests.rs | 2 ++
crates/render/src/inspect.rs | 3 +++
crates/xfa/src/tests.rs | 2 ++
3 files changed, 7 insertions(+)
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 202f3a3190..7a181861bd 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -5273,6 +5273,8 @@ fn an_xfa_form_without_a_template_opens_with_its_placeholder_and_a_warning() {
assert!(doc.info.warnings.iter().any(|w| w.contains("could not be laid out") && w.contains("no template")), "{:?}", doc.info.warnings);
}
+/// A dynamic form opens laid out with the values its datasets hold, and with the rows its data
+/// adds to a repeating table row.
#[test]
fn dynamic_xfa_forms_open_with_the_values_and_rows_of_their_data() {
let data = "";
diff --git a/crates/render/src/inspect.rs b/crates/render/src/inspect.rs
index 4290c3c48a..b7a3cb0a8f 100644
--- a/crates/render/src/inspect.rs
+++ b/crates/render/src/inspect.rs
@@ -727,6 +727,9 @@ impl<'a> Inspector<'a> {
me
}
+ /// Fill `info` from the document: its pages, metadata, encryption, outline, fields, XFA kind
+ /// (dynamic when it must be laid out from its template, else static), layers, fonts,
+ /// attachments and open action.
fn fill(&self, info: &mut DocInfo) {
// lopdf drops /Encrypt from the trailer once it has decrypted the file.
info.encrypted = self.doc.encrypted();
diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs
index 7bb0b7d4ca..b34e759af8 100644
--- a/crates/xfa/src/tests.rs
+++ b/crates/xfa/src/tests.rs
@@ -279,6 +279,8 @@ fn layout_places_captions_fields_and_sizes_containers_to_their_content() {
);
}
+/// A table taller than its page continues on the next pages, its header row repeated at the top of
+/// each one.
#[test]
fn tables_break_across_pages_and_repeat_their_header_row() {
let form = layout_xml(&template(40)).unwrap();
From cd769f6d00a14f0bb3f5c49041a7e43a5380442a Mon Sep 17 00:00:00 2001
From: Eric Kaden <608341+EricKaden@users.noreply.github.com>
Date: Sat, 24 Oct 2026 15:44:25 -0400
Subject: [PATCH 3/7] M12: dynamicRender is read from the configuration packet
itself, not the first element named config
---
crates/xfa/src/packets.rs | 47 ++++++++++++++++++++++-----------------
crates/xfa/src/tests.rs | 6 +++++
2 files changed, 32 insertions(+), 21 deletions(-)
diff --git a/crates/xfa/src/packets.rs b/crates/xfa/src/packets.rs
index d1ac1831e3..2b1c85d4dd 100644
--- a/crates/xfa/src/packets.rs
+++ b/crates/xfa/src/packets.rs
@@ -8,6 +8,10 @@ use crate::XfaError;
/// Most decoded packet bytes read in total.
const MAX_XDP: usize = 64 << 20;
+/// Most XML nodes read when the XDP is parsed for its configuration, as many as the template
+/// parser allows.
+const MAX_XDP_NODES: u32 = 2_000_000;
+
/// What was found in the XFA entry.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Packets {
@@ -98,29 +102,30 @@ fn to_text(bytes: &[u8]) -> String {
}
/// Whether the XDP's configuration packet asks for dynamic rendering: `required` at
-/// `config/acrobat/acrobat7/dynamicRender` (Designer writes it for a dynamic form). The same
-/// names in the template or the data are not the configuration.
+/// `config/acrobat/acrobat7/dynamicRender` (Designer writes it for a dynamic form). The packet is
+/// the `config` child of the `xdp` root (a whole-XDP stream, or an array's packets read in order
+/// between its preamble and postamble), or the document itself when it is a bare `config` packet.
+/// An element of that name anywhere else (a data node, inside the template) is not it. XML that
+/// doesn't parse, or has a DTD, asks for nothing.
pub(crate) fn requires_dynamic_render(xdp: &str) -> bool {
- // The configuration packet: from `' || c.is_whitespace()))
- else {
- return false;
- };
- let Some(packet) = xdp.get(start..).and_then(|r| r.find(" ").and_then(|end| r.get(..end + " ".len()))) else {
- return false;
- };
- let Ok(config) = roxmltree::Document::parse(packet) else { return false };
- let mut node = config.root_element();
- for name in ["acrobat", "acrobat7", "dynamicRender"] {
- match node.children().find(|c| c.is_element() && c.tag_name().name() == name) {
- Some(c) => node = c,
- None => return false,
- }
+ let opts = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: MAX_XDP_NODES };
+ let Ok(doc) = roxmltree::Document::parse_with_options(xdp, opts) else { return false };
+ let root = doc.root_element();
+ /// `n`'s first child element named `name` (any namespace).
+ fn child<'a, 'i>(n: roxmltree::Node<'a, 'i>, name: &str) -> Option> {
+ n.children().find(|c| c.is_element() && c.tag_name().name() == name)
}
- node.text().is_some_and(|t| t.trim() == "required")
+ let config = match root.tag_name().name() {
+ "config" => Some(root),
+ "xdp" => child(root, "config"),
+ _ => None,
+ };
+ config
+ .and_then(|c| child(c, "acrobat"))
+ .and_then(|a| child(a, "acrobat7"))
+ .and_then(|a| child(a, "dynamicRender"))
+ .and_then(|d| d.text())
+ .is_some_and(|t| t.trim() == "required")
}
/// Whether the AcroForm holds a signed signature field (`/FT /Sig` with a value), looked for at
diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs
index b34e759af8..fe668d2f7c 100644
--- a/crates/xfa/src/tests.rs
+++ b/crates/xfa/src/tests.rs
@@ -334,6 +334,12 @@ fn dynamic_rendering_is_read_from_the_configuration_only() {
assert!(!required("required "));
assert!(!required("required "));
assert!(!required("required"), "no end tag");
+ // A data node named `config` before the configuration packet is not the configuration.
+ let data_first = r#"required "#;
+ assert!(required(data_first), "the configuration packet after a data node named config");
+ let only_data = r#"required "#;
+ assert!(!required(only_data), "a data node shaped like a configuration");
+ assert!(required("required "), "a bare config packet");
}
#[test]
From 42fa2813fd3d4e367a8ece9bb8b4aefd56510790 Mon Sep 17 00:00:00 2001
From: Eric Kaden <608341+EricKaden@users.noreply.github.com>
Date: Sat, 24 Oct 2026 16:05:56 -0400
Subject: [PATCH 4/7] M12: a form whose fields go past the signature search's
limits counts as signed and stays as saved
---
crates/xfa/src/fixtures.rs | 25 ++++++++++++++++++++++---
crates/xfa/src/packets.rs | 9 +++++++--
crates/xfa/src/tests.rs | 4 ++++
3 files changed, 33 insertions(+), 5 deletions(-)
diff --git a/crates/xfa/src/fixtures.rs b/crates/xfa/src/fixtures.rs
index f563ad7988..f486d749f5 100644
--- a/crates/xfa/src/fixtures.rs
+++ b/crates/xfa/src/fixtures.rs
@@ -679,6 +679,26 @@ pub fn signed_shell() -> Vec {
/// field `name` lives in the template), signed when `signed`. Its configuration packet says
/// `{render} ` (none when `render` is empty).
pub fn saved_with_pages_shell(render: &str, signed: bool) -> Vec {
+ assemble(saved_with_pages_objects(render, signed))
+}
+
+/// [`saved_with_pages_shell`]`("required", false)` whose signature box sits under `depth` nested
+/// fields of its own (none of them a signature, none with a value).
+pub fn deep_saved_with_pages_shell(depth: usize) -> Vec {
+ let mut objs = saved_with_pages_objects("required", false);
+ // Object 6, the box, becomes the outermost of the nested fields; the box goes last.
+ let first = objs.len() + 1;
+ let field = |name: usize, kid: usize| format!("<< /T (n{name}) /Kids [{kid} 0 R] >>").into_bytes();
+ let Some(sig) = objs.get_mut(5).map(|o| std::mem::replace(o, field(0, first))) else { return assemble(objs) };
+ for d in 1..depth {
+ objs.push(field(d, first + d));
+ }
+ objs.push(sig);
+ assemble(objs)
+}
+
+/// The objects of [`saved_with_pages_shell`], in order (the signature box is object 6).
+fn saved_with_pages_objects(render: &str, signed: bool) -> Vec> {
let config = if render.is_empty() {
String::new()
} else {
@@ -702,7 +722,7 @@ pub fn saved_with_pages_shell(render: &str, signed: bool) -> Vec {
);
let value = if signed { " /V 7 0 R" } else { "" };
let picture = "BT /F1 12 Tf 72 700 Td (Name: ______) Tj ET";
- let objs: Vec> = vec![
+ vec![
b"<< /Type /Catalog /Pages 2 0 R /AcroForm << /XFA 5 0 R /Fields [6 0 R] /SigFlags 3 >> >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Annots [6 0 R] >>".to_vec(),
@@ -710,8 +730,7 @@ pub fn saved_with_pages_shell(render: &str, signed: bool) -> Vec {
format!("<< /Length {} >>\nstream\n{xdp}\nendstream", xdp.len()).into_bytes(),
format!("<< /T (form[0].sign[0]) /FT /Sig{value} /Type /Annot /Subtype /Widget /Rect [72 500 288 572] /P 3 0 R >>").into_bytes(),
b"<< /Type /Sig /Name (A Signer) >>".to_vec(),
- ];
- assemble(objs)
+ ]
}
/// A check box `kind` whose change script, once it is checked, opens the protected check box
diff --git a/crates/xfa/src/packets.rs b/crates/xfa/src/packets.rs
index 2b1c85d4dd..71d69dda54 100644
--- a/crates/xfa/src/packets.rs
+++ b/crates/xfa/src/packets.rs
@@ -129,7 +129,9 @@ pub(crate) fn requires_dynamic_render(xdp: &str) -> bool {
}
/// Whether the AcroForm holds a signed signature field (`/FT /Sig` with a value), looked for at
-/// most 32 levels deep and among at most 10 000 fields.
+/// most 32 levels deep and among at most 10 000 fields. A form whose fields go past either limit
+/// counts as signed: what wasn't looked at may be, and laying a signed form out would change
+/// what was signed.
pub(crate) fn has_signature(doc: &Document) -> bool {
let Some(root) = doc.root() else { return false };
let catalog = doc.get(root);
@@ -141,7 +143,10 @@ pub(crate) fn has_signature(doc: &Document) -> bool {
let mut seen = std::collections::HashSet::new();
let mut budget = 10_000usize;
while let Some((f, sig_above, depth)) = todo.pop() {
- if budget == 0 || depth > 32 || f.as_ref().is_some_and(|r| !seen.insert(r)) {
+ if budget == 0 || depth > 32 {
+ return true;
+ }
+ if f.as_ref().is_some_and(|r| !seen.insert(r)) {
continue;
}
budget -= 1;
diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs
index fe668d2f7c..a0772584bf 100644
--- a/crates/xfa/src/tests.rs
+++ b/crates/xfa/src/tests.rs
@@ -315,6 +315,10 @@ fn a_form_saved_with_its_pages_is_laid_out_when_it_requires_dynamic_rendering()
assert!(!is_dynamic(&open("required", true)), "signed: left as saved");
assert!(!is_dynamic(&open("", false)), "no configuration: the fields it has are the form's");
assert!(!is_dynamic(&open("forbidden", false)));
+ // A box under nested fields is found; past the 32 levels looked at, the form counts as signed.
+ let deep = |depth: usize| Document::open(Arc::new(crate::fixtures::deep_saved_with_pages_shell(depth))).unwrap();
+ assert!(is_dynamic(&deep(5)), "nested, unsigned");
+ assert!(!is_dynamic(&deep(40)), "too deep to tell: as if signed");
}
/// Only the configuration packet's `acrobat/acrobat7/dynamicRender` asks for dynamic rendering:
From 9dff84ca361b988f82e032ecb3855ea22f470b27 Mon Sep 17 00:00:00 2001
From: Eric Kaden <608341+EricKaden@users.noreply.github.com>
Date: Sat, 24 Oct 2026 16:19:23 -0400
Subject: [PATCH 5/7] M12: the deep saved-form fixture lists its moved
signature box on the page and links each field to its parent
---
crates/xfa/src/fixtures.rs | 24 +++++++++++++++++++-----
crates/xfa/src/tests.rs | 7 +++++++
2 files changed, 26 insertions(+), 5 deletions(-)
diff --git a/crates/xfa/src/fixtures.rs b/crates/xfa/src/fixtures.rs
index f486d749f5..b45145c1b6 100644
--- a/crates/xfa/src/fixtures.rs
+++ b/crates/xfa/src/fixtures.rs
@@ -686,14 +686,28 @@ pub fn saved_with_pages_shell(render: &str, signed: bool) -> Vec {
/// fields of its own (none of them a signature, none with a value).
pub fn deep_saved_with_pages_shell(depth: usize) -> Vec {
let mut objs = saved_with_pages_objects("required", false);
- // Object 6, the box, becomes the outermost of the nested fields; the box goes last.
+ // Object 6, the box, becomes the outermost of the nested fields, each the parent of the next;
+ // the box goes last, under the innermost, and the page lists it under its new number.
let first = objs.len() + 1;
- let field = |name: usize, kid: usize| format!("<< /T (n{name}) /Kids [{kid} 0 R] >>").into_bytes();
- let Some(sig) = objs.get_mut(5).map(|o| std::mem::replace(o, field(0, first))) else { return assemble(objs) };
+ let depth = depth.max(1);
+ let widget = first + depth - 1;
+ let parent_of = |n: usize| if n == first { 6 } else { n - 1 };
+ let field = |name: usize, kid: usize, parent: Option| {
+ let parent = parent.map(|p| format!(" /Parent {p} 0 R")).unwrap_or_default();
+ format!("<< /T (n{name}) /Kids [{kid} 0 R]{parent} >>").into_bytes()
+ };
+ let kid_of_six = if depth == 1 { widget } else { first };
+ let Some(sig) = objs.get_mut(5).map(|o| std::mem::replace(o, field(0, kid_of_six, None))) else { return assemble(objs) };
for d in 1..depth {
- objs.push(field(d, first + d));
+ let n = first + d - 1;
+ objs.push(field(d, n + 1, Some(parent_of(n))));
+ }
+ let innermost = if depth == 1 { 6 } else { widget - 1 };
+ let sig = String::from_utf8_lossy(&sig).replacen("/T (form[0].sign[0])", &format!("/T (sign[0]) /Parent {innermost} 0 R"), 1);
+ objs.push(sig.into_bytes());
+ if let Some(page) = objs.get_mut(2) {
+ *page = String::from_utf8_lossy(page).replacen("/Annots [6 0 R]", &format!("/Annots [{widget} 0 R]"), 1).into_bytes();
}
- objs.push(sig);
assemble(objs)
}
diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs
index a0772584bf..fe849e3824 100644
--- a/crates/xfa/src/tests.rs
+++ b/crates/xfa/src/tests.rs
@@ -319,6 +319,13 @@ fn a_form_saved_with_its_pages_is_laid_out_when_it_requires_dynamic_rendering()
let deep = |depth: usize| Document::open(Arc::new(crate::fixtures::deep_saved_with_pages_shell(depth))).unwrap();
assert!(is_dynamic(&deep(5)), "nested, unsigned");
assert!(!is_dynamic(&deep(40)), "too deep to tell: as if signed");
+ // The page lists the box under its new number, and the box knows its parent.
+ let doc = deep(5);
+ let page = doc.get(pdfcraft_cos::ObjRef::new(3, 0));
+ let annot = page.as_dict().and_then(|d| d.get(b"Annots")).and_then(|a| a.as_array().and_then(|a| a.first().cloned())).and_then(|a| a.as_ref());
+ let widget = annot.map(|r| doc.get(r));
+ assert_eq!(widget.as_ref().and_then(|w| w.as_dict().and_then(|d| d.name(b"FT")).map(<[u8]>::to_vec)), Some(b"Sig".to_vec()));
+ assert!(widget.as_ref().and_then(|w| w.as_dict().map(|d| d.contains(b"Parent"))).unwrap_or(false));
}
/// Only the configuration packet's `acrobat/acrobat7/dynamicRender` asks for dynamic rendering:
From 469d1f4a21d6d4cbb3d2d669359834bb61a2f14f Mon Sep 17 00:00:00 2001
From: Eric Kaden <608341+EricKaden@users.noreply.github.com>
Date: Sun, 25 Oct 2026 10:56:36 -0400
Subject: [PATCH 6/7] M12: the inspector's signature check shares the xfa
crate's limits, and a form listing fields is not taken for one without
---
crates/engine/src/tests.rs | 14 +++++++++++
crates/render/src/inspect.rs | 47 ++++++++++++++++++++++++++++++++++--
2 files changed, 59 insertions(+), 2 deletions(-)
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index b7ee88b0f9..9a3d54e35c 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -8744,3 +8744,17 @@ fn need_appearances_buttons_are_displayed_from_their_captions() {
assert!(ink(&shown, inside(x, 100)) > 700, "the file's square at {x}");
}
}
+
+/// A form saved with its pages whose signature box sits deeper than the 32 nested fields looked
+/// through counts as signed, as the xfa crate counts it, so it is left as saved rather than laid
+/// out again over a signature that may be there; nested less deep, unsigned, it is laid out.
+#[test]
+fn a_saved_form_too_deep_to_read_through_is_left_as_saved() {
+ let xfa = |depth: usize| {
+ let mut s = Session::new();
+ let id = s.open("deep.pdf", None, Arc::new(pdfcraft_xfa::fixtures::deep_saved_with_pages_shell(depth)), None).expect("opens");
+ s.get(id).unwrap().info.xfa
+ };
+ assert_eq!(xfa(5), Some(pdfcraft_render::Xfa::Dynamic), "nested, unsigned: laid out");
+ assert_eq!(xfa(40), Some(pdfcraft_render::Xfa::Static), "too deep to tell: left as saved");
+}
diff --git a/crates/render/src/inspect.rs b/crates/render/src/inspect.rs
index 38058ddd44..3e5eaa73e4 100644
--- a/crates/render/src/inspect.rs
+++ b/crates/render/src/inspect.rs
@@ -893,9 +893,18 @@ impl<'a> Inspector<'a> {
// rendered dynamically, is laid out from its template too: its fields live there.
// Not once it is signed: the signature covers the pages as saved (the xfa crate's
// `is_dynamic` keeps the same rule).
- let signed = info.fields.iter().any(|f| f.kind == FieldKind::Signature && f.value.is_some());
+ let signed = self.signed_form(catalog);
let required = render.as_deref() == Some("required") && !signed;
- info.xfa = Some(if needs_rendering || required || (info.fields.is_empty() && !static_form) { Xfa::Dynamic } else { Xfa::Static });
+ // Whether the AcroForm lists any field, as the xfa crate's `has_fields` reads it, so
+ // both call the same forms dynamic: fields nested too deep to read through count.
+ let listed = catalog
+ .get(b"AcroForm")
+ .ok()
+ .and_then(|o| self.dict(o))
+ .and_then(|f| f.get(b"Fields").ok())
+ .and_then(|f| self.resolve(f).as_array().ok())
+ .is_some_and(|a| !a.is_empty());
+ info.xfa = Some(if needs_rendering || required || (!listed && !static_form) { Xfa::Dynamic } else { Xfa::Static });
}
self.layers(catalog, &mut info.layers);
info.layer_groups = self.layer_groups(catalog);
@@ -1009,6 +1018,40 @@ impl<'a> Inspector<'a> {
xfa_config_dynamic_render(&xfa_packet_text(&bytes))
}
+ /// Whether the form holds a signature field with a value, read as the xfa crate's
+ /// `has_signature` reads it so that both say the same of a form: down the field tree from the
+ /// AcroForm's `/Fields`, the field type inherited from the parent, and a tree deeper than 32
+ /// fields or larger than 10,000 taken as signed. A form too big to read through is then left
+ /// as saved rather than laid out again over a signature.
+ fn signed_form(&self, catalog: &'a Dictionary) -> bool {
+ let Some(acro) = catalog.get(b"AcroForm").ok().and_then(|o| self.dict(o)) else { return false };
+ let Some(fields) = acro.get(b"Fields").ok().and_then(|f| self.resolve(f).as_array().ok()) else { return false };
+ // (field, signature type inherited, depth)
+ let mut todo: Vec<(&Object, bool, usize)> = fields.iter().map(|f| (f, false, 0)).collect();
+ let mut seen = HashSet::new();
+ let mut budget = 10_000usize;
+ while let Some((f, sig_above, depth)) = todo.pop() {
+ if budget == 0 || depth > 32 {
+ return true;
+ }
+ if let Some(id) = self.resolved_id(f)
+ && !seen.insert(id)
+ {
+ continue;
+ }
+ budget -= 1;
+ let Some(d) = self.dict(f) else { continue };
+ let sig = d.get(b"FT").ok().and_then(|t| self.resolve(t).as_name().ok()).map_or(sig_above, |t| t == b"Sig");
+ if sig && d.get(b"V").ok().is_some_and(|v| !matches!(self.resolve(v), Object::Null)) {
+ return true;
+ }
+ if let Some(kids) = d.get(b"Kids").ok().and_then(|k| self.resolve(k).as_array().ok()) {
+ todo.extend(kids.iter().map(|k| (k, sig, depth + 1)));
+ }
+ }
+ false
+ }
+
fn resolve(&self, o: &'a Object) -> &'a Object {
self.doc.dereference(o).map(|(_, o)| o).unwrap_or(o)
}
From 87f348da316289391d485e7fa41a1a1dbd05ca13 Mon Sep 17 00:00:00 2001
From: Eric Kaden <608341+EricKaden@users.noreply.github.com>
Date: Tue, 27 Oct 2026 22:42:53 -0400
Subject: [PATCH 7/7] M12: the renderer and the xfa crate agree on which saved
forms are laid out (test)
---
crates/engine/src/tests.rs | 24 ++++++++++++++++++++++++
1 file changed, 24 insertions(+)
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index edc19504ef..0b192a6ffd 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -8842,3 +8842,27 @@ fn a_saved_form_too_deep_to_read_through_is_left_as_saved() {
assert_eq!(xfa(5), Some(pdfcraft_render::Xfa::Dynamic), "nested, unsigned: laid out");
assert_eq!(xfa(40), Some(pdfcraft_render::Xfa::Static), "too deep to tell: left as saved");
}
+
+/// The renderer's inspection and the xfa crate each decide whether a form saved with its pages
+/// is laid out again from its template, each walking the field tree for a signature in its own
+/// way (the renderer reads the file through lopdf, the xfa crate through cos). They agree on every
+/// such form: required or not, signed or not, and a signature box nested from shallow to past
+/// the depth either looks through.
+#[test]
+fn the_renderer_and_the_xfa_crate_agree_on_which_saved_forms_are_laid_out() {
+ let mut forms: Vec<(String, Vec)> = Vec::new();
+ for render in ["required", "forbidden", ""] {
+ for signed in [false, true] {
+ forms.push((format!("{render:?}, signed {signed}"), pdfcraft_xfa::fixtures::saved_with_pages_shell(render, signed)));
+ }
+ }
+ for depth in [1, 5, 30, 31, 32, 33, 34, 40] {
+ forms.push((format!("nested {depth} deep"), pdfcraft_xfa::fixtures::deep_saved_with_pages_shell(depth)));
+ }
+ for (what, bytes) in forms {
+ let bytes = Arc::new(bytes);
+ let info = pdfcraft_render::inspect(bytes.clone(), None).expect("inspects");
+ let cos = pdfcraft_cos::Document::open(bytes).expect("opens");
+ assert_eq!(info.xfa == Some(pdfcraft_render::Xfa::Dynamic), pdfcraft_xfa::is_dynamic(&cos), "{what}");
+ }
+}