Skip to Content
NexPDF

XFA forms

Read XFA forms, export and import their data as XML or JSON, convert them to AcroForm, flatten them or remove XFA with NexPDF for Rust.

English

License module

XFA forms need the forms module (Indie tier and above).

XFA (XML Forms Architecture) forms keep their layout and data in XML inside the PDF. Many government and bank forms use them, and many viewers no longer open them. NexPDF reads both kinds:

  • static XFA, where the PDF also has AcroForm fields: the XFA data and the AcroForm fields are kept in step, so filling either side updates the other;
  • dynamic XFA, where the pages are laid out from the XFA template: NexPDF lays the template out into ordinary PDF pages with AcroForm fields.

Inspect a form

use nexpdf_sdk::Document;

fn main() -> nexpdf_sdk::Result<()> {
    let doc = Document::open("tax-form.pdf")?;
    let info = doc.xfa_info_json_value()?;          // `serde` feature; or xfa_info_json()
    println!(
        "{} {} {} {}",
        info["has_xfa"], info["dynamic"], info["field_count"], info["acroform_field_count"]
    );
    Ok(())
}

The result has has_xfa, dynamic, field_count, acroform_field_count, data_value_count and the list of XDP packets.

Export and import data

xfa_export_data(format) returns the data as xml (the data document, <form1>…</form1>, the default, also with None) or as flat json ({"path": "value"}), as a String. It is an Err when the document has no XFA.

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut doc = nexpdf_sdk::Document::open("tax-form.pdf")?;
    let values: serde_json::Value = serde_json::from_str(&doc.xfa_export_data("json")?)?;
    println!("{}", values["form1.customer.name"]);

    doc.xfa_import_data(r#"{"form1.customer.name":"Ana Silva","form1.item[1].qty":"3"}"#, "json")?;
    doc.save("filled.pdf")?;
    Ok(())
}

xfa_import_data(data, format) returns the number of values imported. XML replaces the data; JSON (flat paths or nested objects) sets the given values and creates repeated groups as needed. Data paths are dotted names with an index for repeated siblings (form1.item[1].qty).

Convert, flatten or remove

CallResult
xfa_to_acroform()A plain AcroForm PDF without XFA. Dynamic forms are laid out into new pages. Returns the number of fields
xfa_flatten()Converts and flattens: a plain PDF with the values drawn. Returns the number of flattened widgets
xfa_remove()Removes XFA and keeps the existing AcroForm fields and pages. Returns 1, or 0 when there was no XFA

All three take &mut self and return nexpdf_sdk::Result<i32>.

let mut doc = Document::open("tax-form.pdf")?;
doc.xfa_import_data(&std::fs::read_to_string("data.xml")?, "xml")?;
doc.xfa_to_acroform()?;            // now fill it like any AcroForm
doc.save("tax-form-acroform.pdf")?;

AcroForm fields made from XFA are named by their SOM path (form1[0].item[1].qty[0]). See Forms to fill and flatten them.

Convert with a report

xfa_to_acroform_json(options_json) converts like xfa_to_acroform() and returns a report. Options (None = defaults): {"scripts":true,"flatten":false}. "flatten":true flattens as xfa_flatten() does; "scripts":false skips the form's scripts.

let mut doc = Document::open("tax-form.pdf")?;
let report = doc.xfa_to_acroform_json_value(r#"{"scripts":true,"flatten":false}"#)?; // `serde`
println!("{} fields, {} pages", report["fields"], report["pages"]);
for e in report["validation_errors"].as_array().into_iter().flatten() {
    println!("{} ({}): {}", e["som"], e["severity"], e["message"]);
}
doc.save("tax-form-acroform.pdf")?;

The report has flattened, fields, pages, warnings and validation_errors (each with som, test, severity and message).

The converted text fields keep the value they show, with the display picture applied ("1,234.50", "29 Nov 2026"), as /V, and the form has /NeedAppearances false. Viewers that draw text fields from /V (macOS Preview) then show the same as the appearance. Passwords and values longer than the field's MaxLen keep the raw value. The raw data values stay only in the XFA data before conversion: call xfa_export_data first if you need them. Filling a static XFA form keeps raw values in /V.

Scripts

FormCalc (a built-in interpreter) and JavaScript scripts run against an XFA object model (xfa.resolveNode, this.rawValue, xfa.host, instanceManager, script objects). The initialize, calculate (to a fixed point) and validate events run when data is imported and when the form is converted or flattened; conversion also runs ready, docReady, prePrint, page-area layoutReady and conditional breaks. Failed validations are reported.

xfa_run_scripts_json() runs initialize, calculate and validate without converting and stores the calculated values in the data:

let mut doc = Document::open("tax-form.pdf")?;
doc.xfa_import_data(r#"{"form1.item[1].qty":"3"}"#, "json")?;
let run = doc.xfa_run_scripts_json_value()?;     // `serde`; or xfa_run_scripts_json()
println!("{} {}", run["data_changed"], run["validation_errors"]);
let totals = doc.xfa_export_data("json")?;       // calculated values included

The result has data_changed, warnings and validation_errors.

Layout and fonts

Dynamic forms are laid out with picture clauses (display, edit and data pictures for dates, times, numbers, currency and text, with built-in locales), rich text, images (embedded, href and data-bound), table columnWidths, right-to-left flow, leaders and trailers, overflow targets, conditional breaks, occur on page areas, and data binding once, none, global and dataRef with full SOM.

Text is drawn in embedded Unicode fonts (the bundled Liberation fonts), with OpenType shaping and full Unicode bidi. For CJK, Arabic and other scripts, register a fallback font once per process (TrueType, OpenType or .ttc; the data is copied):

nexpdf_sdk::register_fallback_font(&std::fs::read("NotoSansCJK-Regular.ttc")?)?;

When no font has the glyphs, a warning says to register one.

Barcode fields are drawn as vector barcodes: QR, Data Matrix, Aztec, PDF417, Code 128 (A/B/C, GS1-128), Code 39, Code 93, EAN-13, EAN-8, UPC-A, UPC-E, Interleaved 2 of 5, Codabar and Telepen.

Limits

  • Other barcode types (postal codes, RSS, MaxiCode, ...) stay text fields, with a warning.
  • Host dialogs (xfa.host.messageBox) are not shown: they are recorded as warnings.

On this page