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 Go.

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

type XfaInfo struct {
	HasXfa             bool     `json:"has_xfa"`
	Dynamic            bool     `json:"dynamic"`
	FieldCount         int      `json:"field_count"`
	AcroformFieldCount int      `json:"acroform_field_count"`
	DataValueCount     int      `json:"data_value_count"`
	Packets            []string `json:"packets"`
}

doc, err := nexpdf.Open("tax-form.pdf")
if err != nil {
	log.Fatal(err)
}
defer doc.Close()

s, err := doc.XfaInfoJSON()
if err != nil {
	log.Fatal(err)
}
var info XfaInfo
json.Unmarshal([]byte(s), &info)
fmt.Println(info.HasXfa, info.Dynamic, info.FieldCount, info.AcroformFieldCount)

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

Export and import data

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

s, err := doc.XfaExportData("json")
if err != nil {
	log.Fatal(err) // also when the document has no XFA
}
var values map[string]string
json.Unmarshal([]byte(s), &values)
fmt.Println(values["form1.customer.name"])

n, err := doc.XfaImportData(`{"form1.customer.name":"Ana Silva","form1.item[1].qty":"3"}`, "json")
if err != nil {
	log.Fatal(err)
}
fmt.Println(n, "values imported")
doc.Save("filled.pdf", false)

XfaImportData(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
XfaToAcroform()A plain AcroForm PDF without XFA. Dynamic forms are laid out into new pages. Returns the number of fields
XfaFlatten()Converts and flattens: a plain PDF with the values drawn. Returns the number of flattened widgets
XfaRemove()Removes XFA and keeps the existing AcroForm fields and pages. Returns 1, or 0 when there was no XFA
doc, err := nexpdf.Open("tax-form.pdf")
if err != nil {
	log.Fatal(err)
}
defer doc.Close()

xml, _ := os.ReadFile("data.xml")
if _, err := doc.XfaImportData(string(xml), "xml"); err != nil {
	log.Fatal(err)
}
if _, err := doc.XfaToAcroform(); err != nil { // now fill it like any AcroForm
	log.Fatal(err)
}
doc.Save("tax-form-acroform.pdf", false)

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

After conversion, text fields hold the value they show (the display picture applied, such as 1,234.50 or 29 Nov 2026) as their value, and the form says appearances are already drawn, so viewers that draw text fields from the value (macOS Preview) show the same text. Passwords and values longer than the field's maximum length keep the raw value. Export the data first (XfaExportData) if you need the raw values. Static XFA keeps raw values when it syncs filled fields.

Scripts and conversion report

Scripts run: FormCalc (built-in interpreter) and JavaScript, against the XFA object model (xfa.resolveNode, this.rawValue, xfa.host, instanceManager, script objects). initialize, calculate (to a fixed point) and validate 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.

CallResult
XfaRunScriptsJSON()Runs initialize, calculate and validate and stores calculated values in the data. Returns {"data_changed","warnings","validation_errors"}
XfaToAcroformJSON(options)Converts like XfaToAcroform with {"scripts":true,"flatten":false} ("" = defaults). Returns {"flattened","fields","pages","warnings","validation_errors"}
RegisterFallbackFont(data)Registers a TrueType/OpenType font (or .ttc) for text the bundled fonts cannot show (CJK, Arabic, ...). Process-wide, the data is copied. Returns 1
type XfaReport struct {
	Fields           int      `json:"fields"`
	Pages            int      `json:"pages"`
	Warnings         []string `json:"warnings"`
	ValidationErrors []struct {
		Som      string `json:"som"`
		Test     string `json:"test"`
		Severity string `json:"severity"`
		Message  string `json:"message"`
	} `json:"validation_errors"`
}

font, _ := os.ReadFile("NotoSansCJK-Regular.ttc")
if _, err := nexpdf.RegisterFallbackFont(font); err != nil {
	log.Fatal(err)
}

s, err := doc.XfaToAcroformJSON(`{"scripts":true,"flatten":false}`)
if err != nil {
	log.Fatal(err)
}
var report XfaReport
json.Unmarshal([]byte(s), &report)
for _, v := range report.ValidationErrors {
	fmt.Println(v.Som, v.Severity, v.Message)
}

Failed validations are reported in validation_errors; they do not stop the conversion.

Layout

  • Picture clauses are applied (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 and occur on page areas are laid out. Data binding supports once, none, global and dataRef with full SOM.
  • Text is drawn in embedded Unicode fonts (bundled Liberation, then fonts registered with RegisterFallbackFont), with OpenType shaping and Unicode bidi. 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 recorded as warnings, not shown.

On this page