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 Android.
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.
The NexPdfDocument methods below are also NexPdfJni methods that take doc.handle() first.
They return -1 (or an empty string) on failure, with the reason in NexPdfJni.lastError().
Inspect a form
import com.nexdevit.nexpdf.NexPdfDocument
import com.nexdevit.nexpdf.NexPdfJni
import org.json.JSONObject
NexPdfDocument.openBytes(taxForm).use { doc ->
val info = JSONObject(doc.xfaInfoJson())
Log.i("NexPDF", "${info.getBoolean("has_xfa")} ${info.getBoolean("dynamic")} " +
"${info.getInt("field_count")} ${info.getInt("acroform_field_count")}")
}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 with null) or as flat json ({"path": "value"}). It returns an empty string when the
document has no XFA.
val values = JSONObject(doc.xfaExportData("json"))
Log.i("NexPDF", values.optString("form1.customer.name"))
val imported = doc.xfaImportData("""{"form1.customer.name":"Ana Silva","form1.item[1].qty":"3"}""", "json")
check(imported >= 0) { NexPdfJni.lastError() }
File(filesDir, "filled.pdf").writeBytes(doc.saveBytes())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
| Call | Result |
|---|---|
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 |
NexPdfDocument.openBytes(taxForm).use { doc ->
val xml = assets.open("data.xml").bufferedReader().use { it.readText() }
doc.xfaImportData(xml, "xml")
check(doc.xfaToAcroform() >= 0) { NexPdfJni.lastError() } // now fill it like any AcroForm
File(filesDir, "tax-form-acroform.pdf").writeBytes(doc.saveBytes())
}AcroForm fields made from XFA are named by their SOM path (form1[0].item[1].qty[0]). See
Forms to fill and flatten them.
Scripts, pictures and fonts
FormCalc (built-in interpreter) and JavaScript scripts run against an XFA object model
(xfa.resolveNode, this.rawValue, xfa.host, instanceManager, script objects). The
initialize, calculate (repeated 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.
- Picture clauses are applied (display, edit and data pictures for dates, times, numbers, currency and text, with built-in locales).
- The layout draws rich text, images (embedded,
hrefand data-bound), table column widths, right-to-left flow, leaders and trailers, overflow targets, conditional breaks andoccuron page areas. Data binding supportsonce,none,globalanddataRefwith full SOM. - Text is drawn in embedded Unicode fonts (the bundled Liberation fonts, then registered fallback fonts), 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.
After conversion, text fields keep the value they show (display picture applied, such as
1,234.50 or 29 Nov 2026) as their value, and the form no longer asks viewers to redraw
appearances, so viewers that draw text fields from the value show the same text. Passwords and
values longer than the field's maximum length keep the raw value. The raw data values stay in the
XFA data only until conversion: export the data first if you need them. Static XFA keeps raw
values when filled fields are synced.
Calls without a typed method
NexPdfJni has no typed method for xfa_to_acroform_json (conversion with options and a report),
xfa_run_scripts_json (run initialize, calculate and validate and store the calculated values)
or register_fallback_font (a TrueType, OpenType or .ttc font for CJK, Arabic and other scripts,
process-wide). Reach them through NexPdfJni.invoke, the whole C API as one JSON call. Its
document handles are its own, not the long handles of NexPdfDocument, so open the document
through invoke too:
import android.util.Base64
import org.json.JSONArray
fun call(fn: String, vararg args: Any?): Any? {
val request = JSONObject().put("fn", fn).put("args", JSONArray(args.toList()))
val response = JSONObject(NexPdfJni.invoke(request.toString()))
if (!response.getBoolean("ok")) error(response.getString("error"))
return response.opt("result")
}
fun b64(bytes: ByteArray) = Base64.encodeToString(bytes, Base64.NO_WRAP)
call("register_fallback_font", b64(assets.open("NotoSansCJK-Regular.ttc").readBytes()))
val h = call("open_bytes", b64(taxForm))
try {
val run = JSONObject(call("xfa_run_scripts_json", h) as String)
Log.i("NexPDF", "${run.get("data_changed")} ${run.get("validation_errors")}")
val r = JSONObject(call("xfa_to_acroform_json", h, """{"scripts":true,"flatten":false}""") as String)
Log.i("NexPDF", "${r.get("fields")} fields on ${r.get("pages")} pages, ${r.get("warnings")}")
val pdf = Base64.decode(call("save_bytes", h) as String, Base64.DEFAULT)
File(filesDir, "tax-form-acroform.pdf").writeBytes(pdf)
} finally {
call("close", h)
}The conversion report has flattened, fields, pages, warnings and validation_errors (each
with som, test, severity and message). The scripts report has data_changed, warnings and
validation_errors. Options default to {"scripts":true,"flatten":false} (null = defaults).
Limits
- Other barcode types (postal codes, RSS, MaxiCode and others) stay text fields, with a warning.
- Host dialogs (
xfa.host.messageBox) are recorded as warnings, not shown.