表单字段编辑
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.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
获取特定字段的值
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")
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 变体
| 变体 | 说明 | 示例 |
|---|---|---|
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 |
局部名称(不含父级前缀) |
value() |
FormFieldValue |
当前字段值 |
set_value(value) |
() |
设置字段值 |
field_type() |
Option<&FieldType> |
字段类型 |
page_index() |
usize |
包含该字段的页码 |
bounds() |
Option<Rect> |
字段位置和大小 |
tooltip() |
Option<&str> |
提示文本 |
is_modified() |
bool |
值是否已更改 |
is_new() |
bool |
字段是否为新添加(非原文档) |
is_readonly() |
bool |
只读标志 |
set_readonly(bool) |
() |
设置只读标志 |
is_required() |
bool |
必填标志 |
set_required(bool) |
() |
设置必填标志 |
is_no_export() |
bool |
禁止导出标志 |
set_no_export(bool) |
() |
设置禁止导出标志 |
set_tooltip(text) |
() |
设置提示文本 |
set_rect(rect) |
() |
设置位置和大小 |
set_max_length(len) |
() |
设置文本最大长度 |
get_max_length() |
Option<u32> |
获取文本最大长度 |
set_alignment(align) |
() |
设置文本对齐方式 |
get_alignment() |
Option<u32> |
获取文本对齐方式 |
set_background_color(rgb) |
() |
设置背景颜色 |
get_background_color() |
Option<[f32; 3]> |
获取背景颜色 |
set_border_color(rgb) |
() |
设置边框颜色 |
get_border_color() |
Option<[f32; 3]> |
获取边框颜色 |
set_border_width(width) |
() |
设置边框宽度 |
get_border_width() |
Option<f32> |
获取边框宽度 |
set_default_appearance(da) |
() |
设置默认外观字符串 |
get_default_appearance() |
Option<&str> |
获取默认外观字符串 |
set_default_value(value) |
() |
设置默认值 |
get_default_value() |
Option<&FormFieldValue> |
获取默认值 |
has_parent() |
bool |
检查是否有父字段 |
parent_name() |
Option<&str> |
父字段名称 |
扁平化表单
扁平化将交互式表单字段转换为静态页面内容。字段值将成为页面绘制的一部分,无法再编辑。
扁平化单页
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")
扁平化所有表单
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")
检查扁平化状态
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")
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)
导出为 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)
导入表单数据
这是导出的逆操作:从 FDF 或 XFDF 文件(或原始 FDF/XFDF 字节)将字段值加载回文档。这样可以将在桌面 PDF 阅读器、其他库或服务器管道中填写的数据应用到 AcroForm 字段中。
如何将 FDF 或 XFDF 表单数据导入 PDF?
C ABI 声明了专用的导入函数族,Swift 绑定封装了全部 4 个入口点:
| C ABI 符号 | Swift 方法 | 数据来源 |
|---|---|---|
pdf_form_import_from_file |
importFormFromFile(_:) |
FDF/XFDF 文件路径 |
pdf_document_import_form_data |
importFormData(_:) |
FDF/XFDF 文件路径 |
pdf_editor_import_fdf_bytes |
importFdfBytes(_:) |
内存中的 FDF 字节 |
pdf_editor_import_xfdf_bytes |
importXfdfBytes(_:) |
内存中的 XFDF 字节 |
C ABI 精确签名(来自 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);
v0.3.69 可用性说明。 这 4 个导入入口点已在 C ABI 中声明并由 Swift 封装公开,但底层实现尚未接通:在 v0.3.69 中,每个函数在运行时均返回
Unsupported状态(错误码8)。Python、Node.js、Go 和 WASM 绑定完全未暴露这些接口,Rust 层面也不存在 FDF/XFDF 读取器(pdf_oxide::fdf模块仅包含FdfWriter/XfdfWriter导出端)。在导入路径正式落地之前,请使用下面的"解析后填写"变通方案——该方案在目前所有绑定中均可正常工作。
Swift(接口已存在;后端实现落地前会抛出 Unsupported)
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")
每个方法返回 FFI 状态码(importFormFromFile 返回 Bool),错误码非零时抛出 PdfOxideError,因此目前应预期收到 Unsupported 错误而非字段被修改。
现在如何应用 FDF/XFDF 数据(跨语言变通方案)?
由于所有绑定都已公开 set_form_field_value,在 v0.3.69 中导入表单数据的通用做法是:自行解析 FDF/XFDF,然后将每个 name -> value 对写入文档。两种格式都是小巧、规范明确的文本格式:FDF 用 PDF 字典语法包裹值,XFDF 是纯 XML。
Python – 导入 XFDF 文件
# `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 – 通过 DocumentEditor 导入 XFDF 文件
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 – 导入 XFDF 文件
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();
FDF 同理:从 /Fields 数组中解析每个 /T (name) /V (value) 条目,然后调用 set_form_field_value。一旦原生导入路径实现,就可以去掉手动解析,直接调用 importFdfBytes / importXfdfBytes / importFormFromFile。
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")
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
分析 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> |
获取字段值 |
has_form_field(name) |
Result<bool> |
检查字段是否存在 |
set_form_field_value(name, value) |
Result<()> |
设置字段值 |
add_form_field(widget, page) |
Result<()> |
添加新字段 |
add_parent_field(config) |
Result<()> |
添加父字段 |
add_child_field(widget, page, parent) |
Result<()> |
添加子字段 |
remove_form_field(name) |
Result<()> |
删除字段 |
字段属性(按名称)
| 方法 | 返回值 | 说明 |
|---|---|---|
set_form_field_readonly(name, bool) |
Result<()> |
设置只读 |
set_form_field_required(name, bool) |
Result<()> |
设置必填 |
set_form_field_tooltip(name, text) |
Result<()> |
设置提示文本 |
set_form_field_rect(name, rect) |
Result<()> |
设置位置和大小 |
set_form_field_max_length(name, len) |
Result<()> |
设置文本最大长度 |
set_form_field_alignment(name, align) |
Result<()> |
设置文本对齐 |
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_form_field_default_appearance(name, da) |
Result<()> |
设置默认外观 |
set_form_field_flags(name, flags) |
Result<()> |
设置原始字段标志 |
扁平化
| 方法 | 返回值 | 说明 |
|---|---|---|
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 文件 |
导入(C ABI + Swift;v0.3.69 运行时返回 Unsupported)
| C ABI 符号 | Swift 方法 | 返回值 | 说明 |
|---|---|---|---|
pdf_form_import_from_file |
importFormFromFile(_:) |
bool / Bool |
从文件路径导入 FDF/XFDF |
pdf_document_import_form_data |
importFormData(_:) |
int32_t / Int32 |
从文件路径导入表单数据 |
pdf_editor_import_fdf_bytes |
importFdfBytes(_:) |
int32_t / Int32 |
从内存字节导入 FDF |
pdf_editor_import_xfdf_bytes |
importXfdfBytes(_:) |
int32_t / Int32 |
从内存字节导入 XFDF |
原生导入后端落地之前,这些函数返回错误码 8(Unsupported);当前请使用 set_form_field_value 来应用解析后的 FDF/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")?;
常见问题
PDF Oxide 在 v0.3.69 中能将 FDF/XFDF 数据导入 PDF 吗?
目前尚不支持原生的一次性调用导入。C ABI 声明了 pdf_form_import_from_file、pdf_document_import_form_data、pdf_editor_import_fdf_bytes 和 pdf_editor_import_xfdf_bytes,Swift 封装也将其公开,但运行时均返回 Unsupported 状态(错误码 8)。请解析 FDF/XFDF 后对每个字段调用 set_form_field_value——该方式在所有绑定中今天就能用。
哪些绑定公开了导入方法?
只有 C ABI 和 Swift 封装公开了导入接口。Python、Node.js、Go 和 WASM 绑定均未公开。导出(export_form_data_fdf / export_form_data_xfdf 以及 export_form_data)在各绑定中已完整实现。
FDF 与 XFDF 有什么区别?
FDF 是 PDF 衍生的二进制/文本容器(%FDF-1.2 头部,/Fields 数组)。XFDF 是其 XML 等价形式(<xfdf><fields>...),用标准工具生成和解析更加方便。两者承载相同的 字段名 -> 值 数据;PDF Oxide 均可导出。
填写速度能满足批量任务的需求吗? 完全可以。PDF Oxide 的提取核心在基准测试语料库上的平均耗时为 0.8 ms,通过率 100%,因此对于典型表单,读取字段、设置值并重新保存的字段级操作远低于每文档一毫秒。