Skip to content

Form Field Editing

PDF Oxide provides comprehensive form field support: read existing values, fill fields programmatically, add new fields, configure properties, flatten forms to static content, and export form data in FDF/XFDF formats. XFA forms can be analyzed and converted to AcroForm.

Reading Form Fields

Get All Form Fields

Rust

use pdf_oxide::editor::DocumentEditor;

let mut editor = DocumentEditor::open("form.pdf")?;
let fields = editor.get_form_fields()?;

for field in &fields {
    println!("Field: {} = {:?}", field.name(), field.value());
    if let Some(ft) = field.field_type() {
        println!("  Type: {:?}", ft);
    }
    if let Some(tooltip) = field.tooltip() {
        println!("  Tooltip: {}", tooltip);
    }
}

WASM

const doc = new WasmPdfDocument(bytes);
const fields = doc.getFormFields();

for (const f of fields) {
  console.log(`${f.name} (${f.fieldType}) = ${f.value}`);
}

Python

from pdf_oxide import PdfDocument

doc = PdfDocument("form.pdf")
fields = doc.get_form_fields()

for field in fields:
    print(f"{field.name} ({field.field_type}) = {field.value}")

Go

doc, _ := pdfoxide.Open("form.pdf")
defer doc.Close()

fields, _ := doc.FormFields()
for _, f := range fields {
    fmt.Printf("%s (%s) = %s\n", f.Name, f.Type, f.Value)
}

C#

using var doc = PdfDocument.Open("form.pdf");
foreach (var f in doc.GetFormFields())
    Console.WriteLine($"{f.Name} ({f.Type}) = {f.Value}");

Java

try (PdfDocument doc = PdfDocument.open(java.nio.file.Path.of("form.pdf"))) {
    for (fyi.oxide.pdf.form.FormField f : doc.formFields()) {
        System.out.println(f.name() + " (" + f.type() + ") = " + f.value().orElse(""));
    }
}

Kotlin

PdfDocument.open(java.nio.file.Path.of("form.pdf")).use { doc ->
    for (f in doc.formFields()) {
        println("${f.name()} (${f.type()}) = ${f.value().orElse("")}")
    }
}

Scala

Using.resource(PdfDocument.open("form.pdf")) { doc =>
  doc.formFieldsSeq.foreach { f =>
    println(s"${f.name} (${f.`type`}) = ${f.valueOption.getOrElse("")}")
  }
}

Clojure

(with-open [doc (pdf/open "form.pdf")]
  (doseq [f (pdf/form-fields doc)]
    (println (.name f) "(" (.type f) ") =" (.orElse (.value f) ""))))

Ruby

PdfOxide::PdfDocument.open('form.pdf') do |doc|
  doc.form_fields.each do |f|
    puts "#{f[:name]} (#{f[:type]}) = #{f[:value]}"
  end
end

C++

auto doc = pdf_oxide::Document::open("form.pdf");
for (const auto& f : doc.get_form_fields())
    std::cout << f.name << " (" << f.type << ") = " << f.value << "\n";

Swift

let doc = try Document.open("form.pdf")
for f in try doc.formFields() {
    print("\(f.name) (\(f.type)) = \(f.value)")
}

Dart

final doc = PdfDocument.open('form.pdf');
for (final f in doc.getFormFields()) {
  print('${f.name} (${f.type}) = ${f.value}');
}

R

doc <- pdf_open("form.pdf")
for (f in pdf_get_form_fields(doc)) {
  cat(sprintf("%s (%s) = %s\n", f$name, f$type, f$value))
}

Julia

doc = open_document("form.pdf")
for f in get_form_fields(doc)
    println("$(f.name) ($(f.type)) = $(f.value)")
end

Zig

var doc = try pdf_oxide.Document.open("form.pdf");
var fields = try doc.formFields();
defer fields.deinit();
const n = try fields.count();
var i: i32 = 0;
while (i < n) : (i += 1) {
    const name = try fields.getName(a, i);
    defer a.free(name);
    const ftype = try fields.getType(a, i);
    defer a.free(ftype);
    const value = try fields.getValue(a, i);
    defer a.free(value);
    std.debug.print("{s} ({s}) = {s}\n", .{ name, ftype, value });
}

Objective-C

NSError *err = nil;
POXDocument *doc = [POXDocument openPath:@"form.pdf" error:&err];
for (POXFormField *f in [doc formFieldsWithError:&err]) {
    NSLog(@"%@ (%@) = %@", f.name, f.type, f.value);
}

Elixir

{:ok, doc} = PdfOxide.open("form.pdf")
{:ok, fields} = PdfOxide.form_fields(doc)
for f <- fields do
  IO.puts("#{f.name} (#{f.type}) = #{f.value}")
end

Get a Specific Field Value

Rust

let mut editor = DocumentEditor::open("form.pdf")?;

let value = editor.get_form_field_value("first_name")?;
println!("First name: {:?}", value);

WASM

const value = doc.getFormFieldValue("first_name");
console.log(`First name: ${value}`);

Python

value = doc.get_form_field_value("first_name")
print(f"First name: {value}")

Check if a Field Exists

let mut editor = DocumentEditor::open("form.pdf")?;

if editor.has_form_field("email")? {
    println!("Email field exists");
}

Setting Form Field Values

Set a Field Value

Rust

use pdf_oxide::editor::DocumentEditor;
use pdf_oxide::editor::form_fields::FormFieldValue;

let mut editor = DocumentEditor::open("form.pdf")?;

// Set a text field
editor.set_form_field_value("first_name", FormFieldValue::Text("Jane".to_string()))?;

// Set a checkbox
editor.set_form_field_value("agree_terms", FormFieldValue::Boolean(true))?;

// Set a choice field
editor.set_form_field_value("country", FormFieldValue::Choice("United States".to_string()))?;

editor.save("filled.pdf")?;

WASM

const doc = new WasmPdfDocument(bytes);

doc.setFormFieldValue("first_name", "Jane");
doc.setFormFieldValue("agree_terms", true);
doc.setFormFieldValue("country", "United States");

writeFileSync("filled.pdf", doc.save());
doc.free();

Python

doc = PdfDocument("form.pdf")

doc.set_form_field_value("first_name", "Jane")
doc.set_form_field_value("agree_terms", True)
doc.set_form_field_value("country", "United States")

doc.save("filled.pdf")

Go

editor, _ := pdfoxide.OpenEditor("form.pdf")
defer editor.Close()

_ = editor.SetFormFieldValue("first_name", "Jane")
_ = editor.SetFormFieldValue("agree_terms", "Yes")
_ = editor.SetFormFieldValue("country", "United States")

_ = editor.Save("filled.pdf")

C#

using var editor = DocumentEditor.Open("form.pdf");

editor.SetFormFieldValue("first_name", "Jane");
editor.SetFormFieldValue("agree_terms", "Yes");
editor.SetFormFieldValue("country", "United States");

editor.Save("filled.pdf");

Java

try (DocumentEditor editor = DocumentEditor.open("form.pdf")) {
    editor.setFormField("first_name", "Jane");
    editor.setFormField("agree_terms", true);
    editor.setFormField("country", "United States");
    editor.saveTo(java.nio.file.Path.of("filled.pdf"));
}

Kotlin

DocumentEditor.open("form.pdf").use { editor ->
    editor.setFormField("first_name", "Jane")
    editor.setFormField("agree_terms", true)
    editor.setFormField("country", "United States")
    editor.saveTo(java.nio.file.Path.of("filled.pdf"))
}

Scala

Using.resource(DocumentEditor.open("form.pdf")) { editor =>
  editor.setFormField("first_name", "Jane")
  editor.setFormField("agree_terms", true)
  editor.setFormField("country", "United States")
  editor.saveTo(java.nio.file.Path.of("filled.pdf"))
}

Clojure

(with-open [editor (pdf/editor "form.pdf")]
  (.setFormField editor "first_name" "Jane")
  (.setFormField editor "agree_terms" true)
  (.setFormField editor "country" "United States")
  (.saveTo editor (java.nio.file.Path/of "filled.pdf" (into-array String []))))

Ruby

PdfOxide::DocumentEditor.open('form.pdf') do |editor|
  editor.set_form_field('first_name', 'Jane')
  editor.set_form_field('agree_terms', true)
  editor.set_form_field('country', 'United States')
  editor.save_to('filled.pdf')
end

C++

auto editor = pdf_oxide::DocumentEditor::open("form.pdf");

editor.set_form_field_value("first_name", "Jane");
editor.set_form_field_value("agree_terms", "Yes");
editor.set_form_field_value("country", "United States");

editor.save("filled.pdf");

Swift

let editor = try DocumentEditor.open("form.pdf")

try editor.setFormFieldValue("first_name", "Jane")
try editor.setFormFieldValue("agree_terms", "Yes")
try editor.setFormFieldValue("country", "United States")

try editor.save("filled.pdf")

Dart

final editor = DocumentEditor.open('form.pdf');

editor.setFormFieldValue('first_name', 'Jane');
editor.setFormFieldValue('agree_terms', 'Yes');
editor.setFormFieldValue('country', 'United States');

editor.save('filled.pdf');

R

editor <- pdf_editor_open("form.pdf")

pdf_editor_set_form_field_value(editor, "first_name", "Jane")
pdf_editor_set_form_field_value(editor, "agree_terms", "Yes")
pdf_editor_set_form_field_value(editor, "country", "United States")

pdf_editor_save(editor, "filled.pdf")

Julia

editor = open_editor("form.pdf")

set_form_field_value(editor, "first_name", "Jane")
set_form_field_value(editor, "agree_terms", "Yes")
set_form_field_value(editor, "country", "United States")

save(editor, "filled.pdf")

Zig

var editor = try pdf_oxide.DocumentEditor.openEditor("form.pdf");
defer editor.deinit();

try editor.setFormFieldValue("first_name", "Jane");
try editor.setFormFieldValue("agree_terms", "Yes");
try editor.setFormFieldValue("country", "United States");

try editor.save("filled.pdf");

Objective-C

NSError *err = nil;
POXDocumentEditor *editor = [POXDocumentEditor openEditor:@"form.pdf" error:&err];

[editor setFormField:@"first_name" value:@"Jane" error:&err];
[editor setFormField:@"agree_terms" value:@"Yes" error:&err];
[editor setFormField:@"country" value:@"United States" error:&err];

[editor saveToPath:@"filled.pdf" error:&err];

Elixir

{:ok, editor} = PdfOxide.open_editor("form.pdf")

PdfOxide.set_form_field_value(editor, "first_name", "Jane")
PdfOxide.set_form_field_value(editor, "agree_terms", "Yes")
PdfOxide.set_form_field_value(editor, "country", "United States")

PdfOxide.editor_save(editor, "filled.pdf")

FormFieldValue Variants

Variant Description Example
Text(String) Text field value FormFieldValue::Text("Hello".into())
Boolean(bool) Checkbox/radio state FormFieldValue::Boolean(true)
Choice(String) Single choice selection FormFieldValue::Choice("Option A".into())
MultiChoice(Vec<String>) Multiple selections FormFieldValue::MultiChoice(vec!["A".into(), "B".into()])
None No value / clear field FormFieldValue::None

Adding Form Fields

Add a New Form Field

use pdf_oxide::editor::DocumentEditor;
use pdf_oxide::writer::form_fields::TextFieldWidget;

let mut editor = DocumentEditor::open("document.pdf")?;

// Create a text input field on page 0
let widget = TextFieldWidget::new("user_name")
    .with_rect(100.0, 700.0, 200.0, 20.0)
    .with_default_value("Enter name");

editor.add_form_field(widget, 0)?;
editor.save("with-form.pdf")?;

Add Hierarchical Fields

Create parent-child field relationships for structured forms.

use pdf_oxide::editor::form_fields::ParentFieldConfig;

let mut editor = DocumentEditor::open("document.pdf")?;

// Create a parent field
let parent = ParentFieldConfig::new("address");
editor.add_parent_field(parent)?;

// Add child fields under the parent
let street = TextFieldWidget::new("street")
    .with_rect(100.0, 600.0, 300.0, 20.0);
editor.add_child_field(street, 0, "address")?;

let city = TextFieldWidget::new("city")
    .with_rect(100.0, 570.0, 150.0, 20.0);
editor.add_child_field(city, 0, "address")?;

editor.save("hierarchical-form.pdf")?;

Remove a Form Field

let mut editor = DocumentEditor::open("form.pdf")?;
editor.remove_form_field("obsolete_field")?;
editor.save("cleaned.pdf")?;

Form Field Properties

Setting Properties

Configure individual field properties by name.

let mut editor = DocumentEditor::open("form.pdf")?;

// Access control
editor.set_form_field_readonly("signature_date", true)?;
editor.set_form_field_required("email", true)?;

// Tooltip
editor.set_form_field_tooltip("phone", "Enter phone number with area code")?;

// Position and size
editor.set_form_field_rect("name", pdf_oxide::geometry::Rect::new(100.0, 700.0, 200.0, 20.0))?;

// Text constraints
editor.set_form_field_max_length("zip_code", 10)?;
editor.set_form_field_alignment("amount", 2)?;  // 0=left, 1=center, 2=right

// Appearance
editor.set_form_field_background_color("highlight_field", [1.0, 1.0, 0.8])?;
editor.set_form_field_border_color("name", [0.0, 0.0, 0.0])?;
editor.set_form_field_border_width("name", 1.0)?;
editor.set_form_field_default_appearance("name", "/Helv 12 Tf 0 g")?;

// Raw flags
editor.set_form_field_flags("options", 0x100000)?;

editor.save("styled-form.pdf")?;

FormFieldWrapper Properties

When working with FormFieldWrapper objects returned by get_form_fields():

Method Returns Description
name() &str Full field name
partial_name() &str Partial name (without parent prefix)
value() FormFieldValue Current field value
set_value(value) () Set the field value
field_type() Option<&FieldType> Field type
page_index() usize Page containing the field
bounds() Option<Rect> Field position and size
tooltip() Option<&str> Tooltip text
is_modified() bool Whether value has been changed
is_new() bool Whether field was added (not from source)
is_readonly() bool Read-only flag
set_readonly(bool) () Set read-only flag
is_required() bool Required flag
set_required(bool) () Set required flag
is_no_export() bool No-export flag
set_no_export(bool) () Set no-export flag
set_tooltip(text) () Set tooltip text
set_rect(rect) () Set position and size
set_max_length(len) () Set maximum text length
get_max_length() Option<u32> Get maximum text length
set_alignment(align) () Set text alignment
get_alignment() Option<u32> Get text alignment
set_background_color(rgb) () Set background color
get_background_color() Option<[f32; 3]> Get background color
set_border_color(rgb) () Set border color
get_border_color() Option<[f32; 3]> Get border color
set_border_width(width) () Set border width
get_border_width() Option<f32> Get border width
set_default_appearance(da) () Set default appearance string
get_default_appearance() Option<&str> Get default appearance string
set_default_value(value) () Set default value
get_default_value() Option<&FormFieldValue> Get default value
has_parent() bool Check for parent field
parent_name() Option<&str> Parent field name

Flattening Forms

Flattening converts interactive form fields into static page content. The field values become part of the page drawing and can no longer be edited.

Flatten a Single Page

Rust

let mut editor = DocumentEditor::open("form.pdf")?;
editor.flatten_forms_on_page(0)?;
editor.save("flat-page0.pdf")?;

WASM

const doc = new WasmPdfDocument(bytes);
doc.flattenFormsOnPage(0);
writeFileSync("flat-page0.pdf", doc.save());
doc.free();

C++

auto editor = pdf_oxide::DocumentEditor::open("form.pdf");
editor.flatten_forms_on_page(0);
editor.save("flat-page0.pdf");

Swift

let editor = try DocumentEditor.open("form.pdf")
try editor.flattenFormsOnPage(0)
try editor.save("flat-page0.pdf")

Dart

final editor = DocumentEditor.open('form.pdf');
editor.flattenFormsOnPage(0);
editor.save('flat-page0.pdf');

R

editor <- pdf_editor_open("form.pdf")
pdf_editor_flatten_forms_on_page(editor, 0)
pdf_editor_save(editor, "flat-page0.pdf")

Julia

editor = open_editor("form.pdf")
flatten_forms_on_page(editor, 0)
save(editor, "flat-page0.pdf")

Zig

var editor = try pdf_oxide.DocumentEditor.openEditor("form.pdf");
defer editor.deinit();
try editor.flattenFormsOnPage(0);
try editor.save("flat-page0.pdf");

Objective-C

NSError *err = nil;
POXDocumentEditor *editor = [POXDocumentEditor openEditor:@"form.pdf" error:&err];
[editor flattenFormsOnPage:0 error:&err];
[editor saveToPath:@"flat-page0.pdf" error:&err];

Elixir

{:ok, editor} = PdfOxide.open_editor("form.pdf")
PdfOxide.flatten_forms_on_page(editor, 0)
PdfOxide.editor_save(editor, "flat-page0.pdf")

Flatten All Forms

Rust

let mut editor = DocumentEditor::open("form.pdf")?;
editor.flatten_forms()?;
editor.save("flat.pdf")?;

WASM

const doc = new WasmPdfDocument(bytes);
doc.flattenForms();
writeFileSync("flat.pdf", doc.save());
doc.free();

Go

editor, _ := pdfoxide.OpenEditor("form.pdf")
defer editor.Close()

_ = editor.FlattenForms()
_ = editor.Save("flat.pdf")

C#

using var editor = DocumentEditor.Open("form.pdf");
editor.FlattenForms();
editor.Save("flat.pdf");

C++

auto editor = pdf_oxide::DocumentEditor::open("form.pdf");
editor.flatten_forms();
editor.save("flat.pdf");

Swift

let editor = try DocumentEditor.open("form.pdf")
try editor.flattenForms()
try editor.save("flat.pdf")

Dart

final editor = DocumentEditor.open('form.pdf');
editor.flattenForms();
editor.save('flat.pdf');

R

editor <- pdf_editor_open("form.pdf")
pdf_editor_flatten_forms(editor)
pdf_editor_save(editor, "flat.pdf")

Julia

editor = open_editor("form.pdf")
flatten_forms(editor)
save(editor, "flat.pdf")

Zig

var editor = try pdf_oxide.DocumentEditor.openEditor("form.pdf");
defer editor.deinit();
try editor.flattenForms();
try editor.save("flat.pdf");

Objective-C

NSError *err = nil;
POXDocumentEditor *editor = [POXDocumentEditor openEditor:@"form.pdf" error:&err];
[editor flattenForms:&err];
[editor saveToPath:@"flat.pdf" error:&err];

Elixir

{:ok, editor} = PdfOxide.open_editor("form.pdf")
PdfOxide.flatten_forms(editor)
PdfOxide.editor_save(editor, "flat.pdf")

Check Flatten Status

editor.flatten_forms_on_page(0)?;
assert!(editor.is_page_marked_for_form_flatten(0));
assert!(editor.will_remove_acroform());

Exporting Form Data

Export form field values to FDF or XFDF format for external processing.

Export to FDF

Rust

let mut editor = DocumentEditor::open("filled-form.pdf")?;
editor.export_form_data_fdf("form-data.fdf")?;

WASM

const doc = new WasmPdfDocument(bytes);
const fdfData = doc.exportFormData("fdf");
writeFileSync("form-data.fdf", fdfData);
doc.free();

Python

doc = PdfDocument("filled-form.pdf")
doc.export_form_data("form-data.fdf", format="fdf")

C++

auto doc = pdf_oxide::Document::open("filled-form.pdf");
auto fdf = doc.export_form_data_to_bytes(0);  // 0 = FDF
std::ofstream("form-data.fdf", std::ios::binary)
    .write(reinterpret_cast<const char*>(fdf.data()), fdf.size());

Swift

let doc = try Document.open("filled-form.pdf")
let fdf = try doc.exportFormData(formatType: 0)  // 0 = FDF
try Data(fdf).write(to: URL(fileURLWithPath: "form-data.fdf"))

Dart

final doc = PdfDocument.open('filled-form.pdf');
final fdf = doc.exportFormDataToBytes(0);  // 0 = FDF
File('form-data.fdf').writeAsBytesSync(fdf);

R

doc <- pdf_open("filled-form.pdf")
fdf <- pdf_export_form_data_to_bytes(doc, 0)  # 0 = FDF
writeBin(fdf, "form-data.fdf")

Julia

doc = open_document("filled-form.pdf")
fdf = export_form_data_to_bytes(doc, 0)  # 0 = FDF
write("form-data.fdf", fdf)

Zig

var doc = try pdf_oxide.Document.open("filled-form.pdf");
const fdf = try doc.exportFormDataToBytes(a, 0);  // 0 = FDF
defer a.free(fdf);
try std.fs.cwd().writeFile(.{ .sub_path = "form-data.fdf", .data = fdf });

Objective-C

NSError *err = nil;
POXDocument *doc = [POXDocument openPath:@"filled-form.pdf" error:&err];
NSData *fdf = [doc exportFormDataToBytes:0 error:&err];  // 0 = FDF
[fdf writeToFile:@"form-data.fdf" atomically:YES];

Elixir

{:ok, doc} = PdfOxide.open("filled-form.pdf")
{:ok, fdf} = PdfOxide.export_form_data_to_bytes(doc, 0)  # 0 = FDF
File.write!("form-data.fdf", fdf)

Export to XFDF

Rust

let mut editor = DocumentEditor::open("filled-form.pdf")?;
editor.export_form_data_xfdf("form-data.xfdf")?;

WASM

const doc = new WasmPdfDocument(bytes);
const xfdfData = doc.exportFormData("xfdf");
writeFileSync("form-data.xfdf", xfdfData);
doc.free();

C++

auto doc = pdf_oxide::Document::open("filled-form.pdf");
auto xfdf = doc.export_form_data_to_bytes(1);  // 1 = XFDF
std::ofstream("form-data.xfdf", std::ios::binary)
    .write(reinterpret_cast<const char*>(xfdf.data()), xfdf.size());

Swift

let doc = try Document.open("filled-form.pdf")
let xfdf = try doc.exportFormData(formatType: 1)  // 1 = XFDF
try Data(xfdf).write(to: URL(fileURLWithPath: "form-data.xfdf"))

Dart

final doc = PdfDocument.open('filled-form.pdf');
final xfdf = doc.exportFormDataToBytes(1);  // 1 = XFDF
File('form-data.xfdf').writeAsBytesSync(xfdf);

R

doc <- pdf_open("filled-form.pdf")
xfdf <- pdf_export_form_data_to_bytes(doc, 1)  # 1 = XFDF
writeBin(xfdf, "form-data.xfdf")

Julia

doc = open_document("filled-form.pdf")
xfdf = export_form_data_to_bytes(doc, 1)  # 1 = XFDF
write("form-data.xfdf", xfdf)

Zig

var doc = try pdf_oxide.Document.open("filled-form.pdf");
const xfdf = try doc.exportFormDataToBytes(a, 1);  // 1 = XFDF
defer a.free(xfdf);
try std.fs.cwd().writeFile(.{ .sub_path = "form-data.xfdf", .data = xfdf });

Objective-C

NSError *err = nil;
POXDocument *doc = [POXDocument openPath:@"filled-form.pdf" error:&err];
NSData *xfdf = [doc exportFormDataToBytes:1 error:&err];  // 1 = XFDF
[xfdf writeToFile:@"form-data.xfdf" atomically:YES];

Elixir

{:ok, doc} = PdfOxide.open("filled-form.pdf")
{:ok, xfdf} = PdfOxide.export_form_data_to_bytes(doc, 1)  # 1 = XFDF
File.write!("form-data.xfdf", xfdf)

Importing Form Data

The inverse of export: load field values from an FDF or XFDF file (or from raw FDF/XFDF bytes) back into a document. This lets you take data that was filled out elsewhere – a desktop PDF reader, another library, a server pipeline – and apply it to your AcroForm fields.

How do I import FDF or XFDF form data into a PDF?

The C ABI declares a dedicated import family, and the Swift binding wraps all four entry points:

C ABI symbol Swift method Source of data
pdf_form_import_from_file importFormFromFile(_:) FDF/XFDF file path
pdf_document_import_form_data importFormData(_:) FDF/XFDF file path
pdf_editor_import_fdf_bytes importFdfBytes(_:) in-memory FDF bytes
pdf_editor_import_xfdf_bytes importXfdfBytes(_:) in-memory XFDF bytes

Exact C ABI signatures (from include/pdf_oxide_c/pdf_oxide.h):

bool    pdf_form_import_from_file(const void *document, const char *filename, int32_t *error_code);
int32_t pdf_document_import_form_data(const void *document, const char *data_path, int32_t *error_code);
int32_t pdf_editor_import_fdf_bytes(const void *document, const uint8_t *data, uintptr_t data_len, int32_t *error_code);
int32_t pdf_editor_import_xfdf_bytes(const void *document, const uint8_t *data, uintptr_t data_len, int32_t *error_code);

Availability in v0.3.69. These four import entry points are declared in the C ABI and surfaced by the Swift wrapper, but the underlying implementation is not yet wired up: in v0.3.69 each one returns the Unsupported status (error code 8) at runtime. They are not exposed at all by the Python, Node.js, Go, or WASM bindings, and there is no Rust-level FDF/XFDF reader (the pdf_oxide::fdf module ships only the FdfWriter/XfdfWriter export side). Until the import path lands, use the parse-and-fill workaround below, which works on every binding today.

Swift (surface present; throws Unsupported until the backend lands)

import PdfOxide

let editor = try DocumentEditor.open(path: "form.pdf")

// From a file on disk (FDF or XFDF):
try editor.importFormFromFile("submission.fdf")   // -> Bool
try editor.importFormData("submission.xfdf")      // -> Int32 status

// From in-memory bytes:
let fdf = Array("%FDF-1.2\n...".utf8)
try editor.importFdfBytes(fdf)                     // -> Int32 status

let xfdf = Array("<?xml version=\"1.0\"?><xfdf>...</xfdf>".utf8)
try editor.importXfdfBytes(xfdf)                   // -> Int32 status

try editor.save(to: "filled.pdf")

Each method returns the FFI status code (or Bool for importFormFromFile) and throws PdfOxideError on a non-zero error code, so today you should expect a thrown Unsupported error rather than mutated fields.

How do I apply FDF/XFDF data today (cross-language workaround)?

Because every binding already exposes set_form_field_value, the portable way to import form data in v0.3.69 is to parse the FDF/XFDF yourself and write each name -> value pair into the document. Both formats are small, well-specified text formats: FDF wraps values in PDF dictionary syntax, and XFDF is plain XML.

Python – import an XFDF file

# `defusedxml` guards against XXE and billion-laughs attacks when parsing
# untrusted XFDF (the stdlib xml parsers are unsafe by default):
#   pip install defusedxml
import defusedxml.ElementTree as ET
from pdf_oxide import PdfDocument

# XFDF: <xfdf><fields><field name="..."><value>...</value></field></fields></xfdf>
tree = ET.parse("submission.xfdf")
ns = {"x": "http://ns.adobe.com/xfdf/"}

doc = PdfDocument("form.pdf")
for field in tree.findall(".//x:field", ns) or tree.findall(".//field"):
    name = field.get("name")
    value_el = field.find("x:value", ns)
    if value_el is None:
        value_el = field.find("value")
    if name and value_el is not None:
        doc.set_form_field_value(name, value_el.text or "")

doc.save("filled.pdf")

Rust – import an XFDF file via DocumentEditor

use pdf_oxide::editor::DocumentEditor;
use pdf_oxide::editor::form_fields::FormFieldValue;

fn import_xfdf(pdf: &str, xfdf: &str, out: &str) -> Result<(), Box<dyn std::error::Error>> {
    let mut editor = DocumentEditor::open(pdf)?;
    let xml = std::fs::read_to_string(xfdf)?;

    // Minimal extraction of <field name="..."><value>...</value></field> pairs.
    for chunk in xml.split("<field ").skip(1) {
        let name = chunk
            .split("name=\"").nth(1)
            .and_then(|s| s.split('"').next());
        let value = chunk
            .split("<value>").nth(1)
            .and_then(|s| s.split("</value>").next());
        if let (Some(name), Some(value)) = (name, value) {
            editor.set_form_field_value(name, FormFieldValue::Text(value.to_string()))?;
        }
    }

    editor.save(out)?;
    Ok(())
}

Node.js – import an XFDF file

const fs = require("fs");
const { PdfDocument } = require("pdf-oxide");

const xfdf = fs.readFileSync("submission.xfdf", "utf8");
const doc = new PdfDocument("form.pdf");

const re = /<field\s+name="([^"]+)"[^>]*>\s*<value>([\s\S]*?)<\/value>/g;
let m;
while ((m = re.exec(xfdf)) !== null) {
  doc.setFormFieldValue(m[1], m[2]);
}

fs.writeFileSync("filled.pdf", doc.save());
doc.close();

The same pattern works for FDF: parse each /T (name) /V (value) entry out of the /Fields array and call set_form_field_value. Once the native import path is implemented, you can drop the manual parsing and call importFdfBytes / importXfdfBytes / importFormFromFile directly.

XFA Form Support

PDF Oxide can detect, analyze, and convert XFA forms to standard AcroForm.

Check for XFA

Rust

let mut editor = DocumentEditor::open("xfa-form.pdf")?;

if editor.has_xfa()? {
    println!("Document contains XFA form data");
}

WASM

const doc = new WasmPdfDocument(bytes);
if (doc.hasXfa()) {
  console.log("Document contains XFA form data");
}

Python

doc = PdfDocument("xfa-form.pdf")
if doc.has_xfa():
    print("Document contains XFA form data")

C++

auto doc = pdf_oxide::Document::open("xfa-form.pdf");
if (doc.has_xfa())
    std::cout << "Document contains XFA form data\n";

Swift

let doc = try Document.open("xfa-form.pdf")
if try doc.hasXfa() {
    print("Document contains XFA form data")
}

Dart

final doc = PdfDocument.open('xfa-form.pdf');
if (doc.hasXfa()) {
  print('Document contains XFA form data');
}

R

doc <- pdf_open("xfa-form.pdf")
if (pdf_has_xfa(doc)) {
  cat("Document contains XFA form data\n")
}

Julia

doc = open_document("xfa-form.pdf")
if has_xfa(doc)
    println("Document contains XFA form data")
end

Zig

var doc = try pdf_oxide.Document.open("xfa-form.pdf");
if (doc.hasXfa()) {
    std.debug.print("Document contains XFA form data\n", .{});
}

Objective-C

NSError *err = nil;
POXDocument *doc = [POXDocument openPath:@"xfa-form.pdf" error:&err];
if ([doc hasXfa]) {
    NSLog(@"Document contains XFA form data");
}

Elixir

{:ok, doc} = PdfOxide.open("xfa-form.pdf")
if PdfOxide.has_xfa?(doc) do
  IO.puts("Document contains XFA form data")
end

Analyze XFA Structure

let mut editor = DocumentEditor::open("xfa-form.pdf")?;

let analysis = editor.analyze_xfa()?;
println!("XFA analysis: {:?}", analysis);

Convert XFA to AcroForm

Convert XFA forms to standard AcroForm fields for broader compatibility.

let mut editor = DocumentEditor::open("xfa-form.pdf")?;
editor.convert_xfa_to_acroform(&Default::default())?;
editor.save("acroform.pdf")?;

Full API Reference

Field Operations

Method Returns Description
get_form_fields() Result<Vec<FormFieldWrapper>> List all form fields
get_form_field_value(name) Result<FormFieldValue> Get a field’s value
has_form_field(name) Result<bool> Check if field exists
set_form_field_value(name, value) Result<()> Set a field’s value
add_form_field(widget, page) Result<()> Add a new field
add_parent_field(config) Result<()> Add a parent field
add_child_field(widget, page, parent) Result<()> Add a child field
remove_form_field(name) Result<()> Remove a field

Field Properties (by name)

Method Returns Description
set_form_field_readonly(name, bool) Result<()> Set read-only
set_form_field_required(name, bool) Result<()> Set required
set_form_field_tooltip(name, text) Result<()> Set tooltip
set_form_field_rect(name, rect) Result<()> Set position/size
set_form_field_max_length(name, len) Result<()> Set max text length
set_form_field_alignment(name, align) Result<()> Set text alignment
set_form_field_background_color(name, rgb) Result<()> Set background color
set_form_field_border_color(name, rgb) Result<()> Set border color
set_form_field_border_width(name, width) Result<()> Set border width
set_form_field_default_appearance(name, da) Result<()> Set default appearance
set_form_field_flags(name, flags) Result<()> Set raw field flags

Flattening

Method Returns Description
flatten_forms_on_page(page) Result<()> Flatten forms on one page
flatten_forms() Result<()> Flatten all forms
is_page_marked_for_form_flatten(page) bool Check flatten status
will_remove_acroform() bool Check if AcroForm will be removed

Export

Method Returns Description
export_form_data_fdf(path) Result<()> Export to FDF file
export_form_data_xfdf(path) Result<()> Export to XFDF file

Import (C ABI + Swift; Unsupported at runtime in v0.3.69)

C ABI symbol Swift method Returns Description
pdf_form_import_from_file importFormFromFile(_:) bool / Bool Import FDF/XFDF from a file path
pdf_document_import_form_data importFormData(_:) int32_t / Int32 Import form data from a file path
pdf_editor_import_fdf_bytes importFdfBytes(_:) int32_t / Int32 Import FDF from in-memory bytes
pdf_editor_import_xfdf_bytes importXfdfBytes(_:) int32_t / Int32 Import XFDF from in-memory bytes

These return error code 8 (Unsupported) until the native import backend lands; use set_form_field_value to apply parsed FDF/XFDF data today.

XFA

Method Returns Description
has_xfa() Result<bool> Check for XFA form data
analyze_xfa() Result<XfaAnalysis> Analyze XFA structure
convert_xfa_to_acroform(options) Result<()> Convert XFA to AcroForm

Advanced Example: Batch Fill and Flatten

use pdf_oxide::editor::DocumentEditor;
use pdf_oxide::editor::form_fields::FormFieldValue;

let mut editor = DocumentEditor::open("template.pdf")?;

// Fill form fields
editor.set_form_field_value("name", FormFieldValue::Text("John Doe".to_string()))?;
editor.set_form_field_value("date", FormFieldValue::Text("2025-12-01".to_string()))?;
editor.set_form_field_value("approved", FormFieldValue::Boolean(true))?;

// Make the completed form non-editable
editor.flatten_forms()?;

// Export data before saving
editor.export_form_data_xfdf("submission.xfdf")?;

editor.save("completed.pdf")?;

FAQ

Can PDF Oxide import FDF/XFDF data back into a PDF in v0.3.69? Not via a native one-call import yet. The C ABI declares pdf_form_import_from_file, pdf_document_import_form_data, pdf_editor_import_fdf_bytes, and pdf_editor_import_xfdf_bytes, and the Swift wrapper surfaces them, but they return the Unsupported status (error code 8) at runtime. Parse the FDF/XFDF and call set_form_field_value for each field – that works on every binding today.

Which bindings expose the import methods? Only the C ABI and the Swift wrapper expose the import surface. The Python, Node.js, Go, and WASM bindings do not. Export (export_form_data_fdf / export_form_data_xfdf and export_form_data) is fully implemented across bindings.

What’s the difference between FDF and XFDF? FDF is a PDF-derived binary/text container (%FDF-1.2 header, /Fields array). XFDF is the XML equivalent (<xfdf><fields>...), which is easier to generate and parse with standard tooling. Both carry the same field name -> value data; PDF Oxide can export either format.

Is filling forms fast enough for batch jobs? Yes. PDF Oxide’s extraction core runs at 0.8 ms mean with a 100% pass rate on the benchmark corpus, so reading fields, setting values, and re-saving stays well under a millisecond of field-level work per document for typical forms.