Skip to content

Редагування форм

PDF Oxide надає повну підтримку полів форм: читання існуючих значень, програмне заповнення полів, додавання нових полів, налаштування властивостей, згладжування форм у статичний вміст та експорт даних форм у форматах FDF/XFDF. Форми XFA можна аналізувати та конвертувати в AcroForm.

Читання полів форми

Отримати всі поля форми

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.field_type}) = ${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}")

Отримати значення конкретного поля

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")

FormFieldValue Variants

Варіант Опис 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

Створення зв’язків батько-дитина для структурованих форм.

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

При роботі з об’єктами FormFieldWrapper, що повертаються get_form_fields():

Метод Повертає Опис
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> Тип поля
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

Згладжування форм

Вирівнювання конвертує інтерактивні поля форми у статичний вміст сторінки. Значення полів стають частиною малюнку сторінки і більше не можуть бути відредаговані.

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();

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();

Check Flatten Status

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

Експорт даних форми

Експорт значень полів форми у формат FDF або XFDF для зовнішньої обробки.

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")

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();

XFA Form Support

PDF Oxide може виявляти, аналізувати та конвертувати форми XFA у стандартні 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")

Analyze XFA Structure

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

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

Конвертувати XFA у AcroForm

Конвертація форм XFA у стандартні поля AcroForm для ширшої сумісності.

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

Full API Reference

Field Operations

Метод Повертає Опис
get_form_fields() Result<Vec<FormFieldWrapper>> Перелічити всі поля форми
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)

Метод Повертає Опис
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

Метод Повертає Опис
flatten_forms_on_page(page) Result<()> Згладити форми on one page
flatten_forms() Result<()> Flatten all forms
is_page_marked_for_form_flatten(page) bool Перевірити статус вирівнювання
will_remove_acroform() bool Check if AcroForm will be removed

Export

Метод Повертає Опис
export_form_data_fdf(path) Result<()> Export to FDF file
export_form_data_xfdf(path) Result<()> Export to XFDF file

XFA

Метод Повертає Опис
has_xfa() Result<bool> Check for XFA form data
analyze_xfa() Result<XfaAnalysis> Analyze XFA structure
convert_xfa_to_acroform(options) Result<()> Конвертувати XFA у 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")?;

Пов’язані сторінки