Edição de Campos de Formulário
O PDF Oxide oferece suporte completo a campos de formulário: leitura de valores existentes, preenchimento programático de campos, adição de novos campos, configuração de propriedades, achatamento de formulários em conteúdo estático e exportação de dados em formato FDF/XFDF. Formulários XFA podem ser analisados e convertidos para AcroForm.
Lendo Campos de Formulário
Obter Todos os Campos
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
Obter o Valor de um Campo Específico
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}")
Verificar se um Campo Existe
let mut editor = DocumentEditor::open("form.pdf")?;
if editor.has_form_field("email")? {
println!("Email field exists");
}
Definindo Valores de Campos
Definir o Valor de um Campo
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")
Variantes de FormFieldValue
| Variante | Descrição | Exemplo |
|---|---|---|
Text(String) |
Valor de campo de texto | FormFieldValue::Text("Hello".into()) |
Boolean(bool) |
Estado de caixa de seleção/rádio | FormFieldValue::Boolean(true) |
Choice(String) |
Seleção única | FormFieldValue::Choice("Option A".into()) |
MultiChoice(Vec<String>) |
Seleção múltipla | FormFieldValue::MultiChoice(vec!["A".into(), "B".into()]) |
None |
Sem valor / limpar campo | FormFieldValue::None |
Adicionando Campos de Formulário
Adicionar um Novo Campo
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")?;
Adicionar Campos Hierárquicos
Crie relações pai-filho entre campos para formulários estruturados.
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")?;
Remover um Campo de Formulário
let mut editor = DocumentEditor::open("form.pdf")?;
editor.remove_form_field("obsolete_field")?;
editor.save("cleaned.pdf")?;
Propriedades de Campos de Formulário
Configurando Propriedades
Configure propriedades individuais de campo por nome.
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")?;
Propriedades do FormFieldWrapper
Ao trabalhar com objetos FormFieldWrapper retornados por get_form_fields():
| Método | Retorna | Descrição |
|---|---|---|
name() |
&str |
Nome completo do campo |
partial_name() |
&str |
Nome parcial (sem prefixo do pai) |
value() |
FormFieldValue |
Valor atual do campo |
set_value(value) |
() |
Define o valor do campo |
field_type() |
Option<&FieldType> |
Tipo do campo |
page_index() |
usize |
Página que contém o campo |
bounds() |
Option<Rect> |
Posição e tamanho do campo |
tooltip() |
Option<&str> |
Texto de dica |
is_modified() |
bool |
Se o valor foi alterado |
is_new() |
bool |
Se o campo foi adicionado (não do original) |
is_readonly() |
bool |
Flag somente leitura |
set_readonly(bool) |
() |
Define flag somente leitura |
is_required() |
bool |
Flag obrigatório |
set_required(bool) |
() |
Define flag obrigatório |
is_no_export() |
bool |
Flag sem exportação |
set_no_export(bool) |
() |
Define flag sem exportação |
set_tooltip(text) |
() |
Define texto de dica |
set_rect(rect) |
() |
Define posição e tamanho |
set_max_length(len) |
() |
Define comprimento máximo do texto |
get_max_length() |
Option<u32> |
Obtém comprimento máximo do texto |
set_alignment(align) |
() |
Define alinhamento do texto |
get_alignment() |
Option<u32> |
Obtém alinhamento do texto |
set_background_color(rgb) |
() |
Define cor de fundo |
get_background_color() |
Option<[f32; 3]> |
Obtém cor de fundo |
set_border_color(rgb) |
() |
Define cor da borda |
get_border_color() |
Option<[f32; 3]> |
Obtém cor da borda |
set_border_width(width) |
() |
Define largura da borda |
get_border_width() |
Option<f32> |
Obtém largura da borda |
set_default_appearance(da) |
() |
Define string de aparência padrão |
get_default_appearance() |
Option<&str> |
Obtém string de aparência padrão |
set_default_value(value) |
() |
Define valor padrão |
get_default_value() |
Option<&FormFieldValue> |
Obtém valor padrão |
has_parent() |
bool |
Verifica se há campo pai |
parent_name() |
Option<&str> |
Nome do campo pai |
Achatamento de Formulários
O achatamento converte campos de formulário interativos em conteúdo estático de página. Os valores dos campos passam a fazer parte do desenho da página e não podem mais ser editados.
Achatar uma Única Página
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")
Achatar Todos os Formulários
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")
Verificar Status do Achatamento
editor.flatten_forms_on_page(0)?;
assert!(editor.is_page_marked_for_form_flatten(0));
assert!(editor.will_remove_acroform());
Exportando Dados de Formulário
Exporte valores de campos para os formatos FDF ou XFDF para processamento externo.
Exportar para 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)
Exportar para 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)
Importando Dados de Formulário
O inverso da exportação: carregue valores de campos de um arquivo FDF ou XFDF (ou de bytes brutos de FDF/XFDF) de volta para um documento. Isso permite pegar dados preenchidos em outro lugar — um leitor de PDF de desktop, outra biblioteca, um pipeline de servidor — e aplicá-los aos campos do AcroForm.
Como importar dados FDF ou XFDF para um PDF?
O C ABI declara uma família dedicada de funções de importação, e o binding Swift expõe todos os quatro pontos de entrada:
| Símbolo C ABI | Método Swift | Fonte dos dados |
|---|---|---|
pdf_form_import_from_file |
importFormFromFile(_:) |
Caminho de arquivo FDF/XFDF |
pdf_document_import_form_data |
importFormData(_:) |
Caminho de arquivo FDF/XFDF |
pdf_editor_import_fdf_bytes |
importFdfBytes(_:) |
Bytes FDF em memória |
pdf_editor_import_xfdf_bytes |
importXfdfBytes(_:) |
Bytes XFDF em memória |
Assinaturas exatas do C ABI (de 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);
Disponibilidade na v0.3.69. Esses quatro pontos de entrada estão declarados no C ABI e expostos pelo wrapper Swift, mas a implementação subjacente ainda não está conectada: na v0.3.69, cada um retorna o status
Unsupported(código de erro8) em tempo de execução. Eles não são expostos de forma alguma pelos bindings Python, Node.js, Go ou WASM, e não existe um leitor FDF/XFDF em nível Rust (o módulopdf_oxide::fdfinclui apenas o lado de exportaçãoFdfWriter/XfdfWriter). Até que o caminho de importação seja implementado, use o contorno “analisar e preencher” abaixo, que funciona em todos os bindings hoje.
Swift (interface presente; lança Unsupported até o backend chegar)
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")
Cada método retorna o código de status FFI (ou Bool para importFormFromFile) e lança PdfOxideError com código de erro diferente de zero, então hoje você deve esperar um erro Unsupported em vez de campos modificados.
Como aplicar dados FDF/XFDF hoje (contorno multiplataforma)?
Como todos os bindings já expõem set_form_field_value, a forma portátil de importar dados de formulário na v0.3.69 é analisar o FDF/XFDF você mesmo e escrever cada par nome -> valor no documento. Ambos os formatos são formatos de texto pequenos e bem especificados: FDF envolve valores na sintaxe de dicionário PDF, e XFDF é XML simples.
Python – importar um arquivo 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 – importar um arquivo XFDF 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 – importar um arquivo 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();
O mesmo padrão funciona para FDF: analise cada entrada /T (name) /V (value) do array /Fields e chame set_form_field_value. Assim que o caminho nativo de importação for implementado, você pode eliminar a análise manual e chamar importFdfBytes / importXfdfBytes / importFormFromFile diretamente.
Suporte a Formulários XFA
O PDF Oxide consegue detectar, analisar e converter formulários XFA para AcroForm padrão.
Verificar 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
Analisar Estrutura XFA
let mut editor = DocumentEditor::open("xfa-form.pdf")?;
let analysis = editor.analyze_xfa()?;
println!("XFA analysis: {:?}", analysis);
Converter XFA para AcroForm
Converta formulários XFA em campos AcroForm padrão para maior compatibilidade.
let mut editor = DocumentEditor::open("xfa-form.pdf")?;
editor.convert_xfa_to_acroform(&Default::default())?;
editor.save("acroform.pdf")?;
Referência Completa da API
Operações com Campos
| Método | Retorna | Descrição |
|---|---|---|
get_form_fields() |
Result<Vec<FormFieldWrapper>> |
Listar todos os campos de formulário |
get_form_field_value(name) |
Result<FormFieldValue> |
Obter valor de um campo |
has_form_field(name) |
Result<bool> |
Verificar se o campo existe |
set_form_field_value(name, value) |
Result<()> |
Definir valor de um campo |
add_form_field(widget, page) |
Result<()> |
Adicionar novo campo |
add_parent_field(config) |
Result<()> |
Adicionar campo pai |
add_child_field(widget, page, parent) |
Result<()> |
Adicionar campo filho |
remove_form_field(name) |
Result<()> |
Remover um campo |
Propriedades de Campo (por nome)
| Método | Retorna | Descrição |
|---|---|---|
set_form_field_readonly(name, bool) |
Result<()> |
Definir somente leitura |
set_form_field_required(name, bool) |
Result<()> |
Definir obrigatório |
set_form_field_tooltip(name, text) |
Result<()> |
Definir dica |
set_form_field_rect(name, rect) |
Result<()> |
Definir posição e tamanho |
set_form_field_max_length(name, len) |
Result<()> |
Definir comprimento máximo do texto |
set_form_field_alignment(name, align) |
Result<()> |
Definir alinhamento do texto |
set_form_field_background_color(name, rgb) |
Result<()> |
Definir cor de fundo |
set_form_field_border_color(name, rgb) |
Result<()> |
Definir cor da borda |
set_form_field_border_width(name, width) |
Result<()> |
Definir largura da borda |
set_form_field_default_appearance(name, da) |
Result<()> |
Definir aparência padrão |
set_form_field_flags(name, flags) |
Result<()> |
Definir flags brutas do campo |
Achatamento
| Método | Retorna | Descrição |
|---|---|---|
flatten_forms_on_page(page) |
Result<()> |
Achatar formulários de uma página |
flatten_forms() |
Result<()> |
Achatar todos os formulários |
is_page_marked_for_form_flatten(page) |
bool |
Verificar status de achatamento |
will_remove_acroform() |
bool |
Verificar se o AcroForm será removido |
Exportação
| Método | Retorna | Descrição |
|---|---|---|
export_form_data_fdf(path) |
Result<()> |
Exportar para arquivo FDF |
export_form_data_xfdf(path) |
Result<()> |
Exportar para arquivo XFDF |
Importação (C ABI + Swift; retorna Unsupported em tempo de execução na v0.3.69)
| Símbolo C ABI | Método Swift | Retorna | Descrição |
|---|---|---|---|
pdf_form_import_from_file |
importFormFromFile(_:) |
bool / Bool |
Importar FDF/XFDF de caminho de arquivo |
pdf_document_import_form_data |
importFormData(_:) |
int32_t / Int32 |
Importar dados de formulário de caminho de arquivo |
pdf_editor_import_fdf_bytes |
importFdfBytes(_:) |
int32_t / Int32 |
Importar FDF de bytes em memória |
pdf_editor_import_xfdf_bytes |
importXfdfBytes(_:) |
int32_t / Int32 |
Importar XFDF de bytes em memória |
Retornam código de erro 8 (Unsupported) até o backend nativo de importação chegar; use set_form_field_value para aplicar dados FDF/XFDF analisados hoje.
XFA
| Método | Retorna | Descrição |
|---|---|---|
has_xfa() |
Result<bool> |
Verificar dados de formulário XFA |
analyze_xfa() |
Result<XfaAnalysis> |
Analisar estrutura XFA |
convert_xfa_to_acroform(options) |
Result<()> |
Converter XFA para AcroForm |
Exemplo Avançado: Preenchimento em Lote e Achatamento
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")?;
Perguntas Frequentes
O PDF Oxide consegue importar dados FDF/XFDF de volta para um PDF na v0.3.69?
Ainda não via importação nativa de chamada única. O C ABI declara pdf_form_import_from_file, pdf_document_import_form_data, pdf_editor_import_fdf_bytes e pdf_editor_import_xfdf_bytes, e o wrapper Swift os expõe, mas eles retornam o status Unsupported (código de erro 8) em tempo de execução. Analise o FDF/XFDF e chame set_form_field_value para cada campo — isso funciona em todos os bindings hoje.
Quais bindings expõem os métodos de importação?
Apenas o C ABI e o wrapper Swift expõem a superfície de importação. Os bindings Python, Node.js, Go e WASM não expõem. A exportação (export_form_data_fdf / export_form_data_xfdf e export_form_data) está completamente implementada em todos os bindings.
Qual a diferença entre FDF e XFDF?
FDF é um contêiner binário/texto derivado de PDF (cabeçalho %FDF-1.2, array /Fields). XFDF é o equivalente em XML (<xfdf><fields>...), mais fácil de gerar e analisar com ferramentas padrão. Ambos carregam os mesmos dados nome do campo -> valor; o PDF Oxide consegue exportar ambos os formatos.
O preenchimento é rápido o suficiente para tarefas em lote? Sim. O núcleo de extração do PDF Oxide opera a 0,8 ms de média com taxa de aprovação de 100% no corpus de benchmark, então ler campos, definir valores e re-salvar fica bem abaixo de um milissegundo de trabalho em nível de campo por documento para formulários típicos.
Páginas Relacionadas
- Visão Geral de Edição – abertura, metadados e fluxo de salvamento
- Edição de Texto – modificar conteúdo de texto diretamente
- Edição de Anotações – adicionar e gerenciar anotações
- Criptografia e Segurança – restringir edição de formulários com permissões