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

检查字段是否存在

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

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

设置表单字段值

设置字段值

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 变体

变体 描述 示例
Text(String) 文本字段值 FormFieldValue::Text("Hello".into())
Boolean(bool) 复选框/单选按钮状态 FormFieldValue::Boolean(true)
Choice(String) 单选 FormFieldValue::Choice("Option A".into())
MultiChoice(Vec<String>) 多选 FormFieldValue::MultiChoice(vec!["A".into(), "B".into()])
None 无值/清除字段 FormFieldValue::None

添加表单字段

添加新表单字段

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

添加层级字段

为结构化表单创建父子字段关系。

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

移除表单字段

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

表单字段属性

设置属性

按名称配置单个字段属性。

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 属性

使用 get_form_fields() 返回的 FormFieldWrapper 对象时:

方法 返回值 描述
name() &str 完整字段名
partial_name() &str Partial name (without parent prefix)
value() FormFieldValue 当前字段值
set_value(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 必需 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_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) () 设置背景颜色
get_background_color() Option<[f32; 3]> Get background color
set_border_color(rgb) () 设置边框颜色
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

扁平化表单

扁平化将交互式表单字段转换为静态页面内容。字段值成为页面绘制的一部分,不再可编辑。

扁平化单个页面

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

扁平化所有表单

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

检查扁平化状态

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

导出表单数据

将表单字段值导出为 FDF 或 XFDF 格式供外部处理。

导出为 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")

导出为 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 表单支持

PDF Oxide 可以检测、分析并将 XFA 表单转换为标准 AcroForm。

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

分析 XFA 结构

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

完整 API 参考

字段操作

方法 返回值 描述
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

字段属性(按名称)

方法 返回值 描述
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_form_field_border_color(name, rgb) Result<()> 设置边框颜色
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

扁平化

方法 返回值 描述
flatten_forms_on_page(page) Result<()> 扁平化一个页面的表单
flatten_forms() Result<()> 扁平化所有表单
is_page_marked_for_form_flatten(page) bool 检查扁平化状态
will_remove_acroform() bool 检查是否会移除 AcroForm

导出

方法 返回值 描述
export_form_data_fdf(path) Result<()> 导出到 FDF 文件
export_form_data_xfdf(path) Result<()> 导出到 XFDF 文件

XFA

方法 返回值 描述
has_xfa() Result<bool> 检查 XFA 表单数据
analyze_xfa() Result<XfaAnalysis> 分析 XFA 结构
convert_xfa_to_acroform(options) Result<()> 将 XFA 转换为 AcroForm

高级示例:批量填写和扁平化

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

相关页面