Skip to content

Заполнение PDF-форм в Python, Rust, Node.js, Go и C#

Читайте поля форм и заполняйте их программно — во всех поддерживаемых биндингах:

Python

from pdf_oxide import PdfDocument

doc = PdfDocument("application.pdf")

# Прочитать существующие поля
for field in doc.page(0).form_fields():
    print(f"{field.name}: {field.value}")

# Заполнить поля и сохранить
doc.set_form_field("full_name", "Jane Doe")
doc.set_form_field("email", "jane@example.com")
doc.set_form_field("agree_terms", True)
doc.save("filled-application.pdf")

WASM

import { WasmPdfDocument } from "pdf-oxide-wasm";

const doc = new WasmPdfDocument(bytes);

// Прочитать существующие поля
const fields = doc.getFormFields();
for (const field of fields) {
    console.log(`${field.name}: ${field.value}`);
}

// Экспортировать данные формы в XFDF
const xfdf = doc.exportFormData("xfdf");
console.log(xfdf);
doc.free();

Rust

use pdf_oxide::editor::{DocumentEditor, EditableDocument, FormFieldValue};

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

// Прочитать существующие поля
let fields = editor.get_form_fields()?;
for field in &fields {
    println!("{}: {:?}", field.name(), field.value());
}

// Заполнить поля и сохранить
editor.set_form_field_value("full_name", FormFieldValue::Text("Jane Doe".into()))?;
editor.set_form_field_value("email", FormFieldValue::Text("jane@example.com".into()))?;
editor.set_form_field_value("agree_terms", FormFieldValue::Boolean(true))?;
editor.save("filled-application.pdf")?;

Go

package main

import (
    "fmt"
    "log"
    pdfoxide "github.com/yfedoseev/pdf_oxide/go"
)

func main() {
    doc, err := pdfoxide.Open("application.pdf")
    if err != nil { log.Fatal(err) }
    defer doc.Close()

    // Прочитать существующие поля
    fields, _ := doc.FormFields()
    for _, f := range fields {
        fmt.Printf("%s: %s\n", f.Name, f.Value)
    }

    // Заполнить поля через редактор и сохранить
    editor, err := pdfoxide.OpenEditor("application.pdf")
    if err != nil { log.Fatal(err) }
    defer editor.Close()

    _ = editor.SetFormFieldValue("full_name", "Jane Doe")
    _ = editor.SetFormFieldValue("email", "jane@example.com")
    _ = editor.SetFormFieldValue("agree_terms", "Yes")
    _ = editor.Save("filled-application.pdf")
}

C#

using PdfOxide;

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

using var editor = DocumentEditor.Open("application.pdf");
editor.SetFormFieldValue("full_name", "Jane Doe");
editor.SetFormFieldValue("email", "jane@example.com");
editor.SetFormFieldValue("agree_terms", "Yes");
editor.Save("filled-application.pdf");

PDF Oxide поддерживает поля AcroForm (текст, флажки, радиокнопки, выпадающие списки) и анализ форм XFA. Лицензия MIT, ограничений AGPL нет.

Установка

pip install pdf_oxide

Чтение полей формы

Список всех полей

Python

from pdf_oxide import PdfDocument

doc = PdfDocument("form.pdf")
for field in doc.page(0).form_fields():
    print(f"Имя: {field.name}")
    print(f"  Тип: {field.field_type}")
    print(f"  Значение: {field.value}")
    print(f"  Область: {field.bounds}")
    print()

WASM

const doc = new WasmPdfDocument(bytes);
const fields = doc.getFormFields();
for (const field of fields) {
    console.log(`Имя: ${field.name}`);
    console.log(`  Тип: ${field.fieldType}`);
    console.log(`  Значение: ${field.value}`);
}
doc.free();

Rust

let mut editor = DocumentEditor::open("form.pdf")?;
let fields = editor.get_form_fields()?;
for field in &fields {
    println!("Имя: {}", field.name());
    println!("  Тип: {:?}", field.field_type());
    println!("  Значение: {:?}", field.value());
}

Go

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

fields, _ := doc.FormFields()
for _, f := range fields {
    fmt.Printf("Имя: %s\n  Тип: %s\n  Значение: %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}");
    Console.WriteLine($"  Тип: {f.Type}");
    Console.WriteLine($"  Значение: {f.Value}");
}

Типы полей

Тип Описание Примеры значений
Text Одно- или многострочный текст "Jane Doe"
Button Флажок или радиокнопка True / False
Choice Выпадающий список или список "Option A"
Signature Цифровая подпись (данные подписи)

Заполнение полей формы

Текстовые поля

doc = PdfDocument("form.pdf")
doc.set_form_field("first_name", "Jane")
doc.set_form_field("last_name", "Doe")
doc.set_form_field("address", "123 Main St\nApt 4B\nNew York, NY 10001")
doc.save("filled.pdf")

Флажки

doc = PdfDocument("form.pdf")
doc.set_form_field("agree_terms", True)
doc.set_form_field("opt_in_newsletter", False)
doc.save("filled.pdf")

Выпадающие списки и поля выбора

doc = PdfDocument("form.pdf")
doc.set_form_field("country", "United States")
doc.set_form_field("department", "Engineering")
doc.save("filled.pdf")

Массовое заполнение

Из файла CSV

Заполните один и тот же шаблон для каждой строки CSV:

import csv
from pdf_oxide import PdfDocument

with open("applicants.csv") as f:
    reader = csv.DictReader(f)
    for i, row in enumerate(reader):
        doc = PdfDocument("template.pdf")
        for field_name, value in row.items():
            doc.set_form_field(field_name, value)
        doc.save(f"filled_{i + 1}.pdf")

Из словаря

from pdf_oxide import PdfDocument

data = {
    "full_name": "Jane Doe",
    "email": "jane@example.com",
    "phone": "555-0123",
    "department": "Engineering",
    "start_date": "2025-03-01",
}

doc = PdfDocument("onboarding.pdf")
for name, value in data.items():
    doc.set_form_field(name, value)
doc.save("onboarding-filled.pdf")

Экспорт данных формы

Экспорт в FDF

Python

from pdf_oxide import PdfDocument

doc = PdfDocument("filled-form.pdf")
fdf_data = doc.export_fdf()
with open("form-data.fdf", "wb") as f:
    f.write(fdf_data)

WASM

const doc = new WasmPdfDocument(bytes);
const fdfData = doc.exportFormData("fdf");
// fdfData — строка или байты в зависимости от формата
doc.free();

Rust

use pdf_oxide::extractors::FormExtractor;

let mut doc = PdfDocument::open("filled-form.pdf")?;
let fields = FormExtractor::extract_fields(&mut doc)?;
let fdf_bytes = FormExtractor::export_fdf(&mut doc, fields)?;
std::fs::write("form-data.fdf", &fdf_bytes)?;

Экспорт в XFDF (XML)

Python

from pdf_oxide import PdfDocument

doc = PdfDocument("filled-form.pdf")
xfdf_data = doc.export_xfdf()
with open("form-data.xfdf", "w") as f:
    f.write(xfdf_data)

WASM

const doc = new WasmPdfDocument(bytes);
const xfdfData = doc.exportFormData("xfdf");
console.log(xfdfData);
doc.free();

Rust

let mut doc = PdfDocument::open("filled-form.pdf")?;
let fields = FormExtractor::extract_fields(&mut doc)?;
let xfdf = FormExtractor::export_xfdf(&mut doc, fields)?;
std::fs::write("form-data.xfdf", &xfdf)?;

Формы XFA

Некоторые государственные и корпоративные формы используют XFA (XML Forms Architecture) вместо привычных AcroForm. PDF Oxide умеет распознавать и разбирать формы XFA:

from pdf_oxide import PdfDocument

doc = PdfDocument("government-form.pdf")
xfa = doc.has_xfa()
if xfa:
    print(f"Обнаружена форма XFA: полей {len(xfa.fields)}")
    for field in xfa.fields:
        print(f"  {field.name} ({field.field_type})")

Подробно о работе с XFA — в руководстве по формам XFA.

Зашифрованные формы

Заполняйте формы в PDF, защищённых паролем:

Python

from pdf_oxide import PdfDocument

doc = PdfDocument("protected-form.pdf", password="secret")
doc.set_form_field("signature_date", "2025-01-15")
doc.save("signed.pdf")

WASM

const doc = new WasmPdfDocument(bytes);
doc.authenticate("secret");
const fields = doc.getFormFields();
console.log(fields);
doc.free();

Rust

let mut editor = DocumentEditor::open_with_password("protected-form.pdf", "secret")?;
editor.set_form_field_value("signature_date", FormFieldValue::Text("2025-01-15".into()))?;
editor.save("signed.pdf")?;

Редактирование защищённых PDF. В DocumentEditor для Go и C# пока нет метода для аутентификации прямо на редакторе. Чтобы заполнить поля зашифрованного PDF из Go или C#, сначала расшифруйте его через read-only-путь PdfDocument.OpenWithPassword, сохраните копию без шифрования и откройте её уже в редакторе.

Связанные страницы