API fluente DocumentBuilder
DocumentBuilder é uma API fluente para construir documentos PDF página a página com controle total sobre posicionamento de texto, fontes, anotações, campos de formulário e elementos de conteúdo.
Cobertura de bindings (v0.3.38).
DocumentBuilder+FluentPageBuilder+EmbeddedFontestão disponíveis em Rust, Python, Node/TypeScript, C#, Go e WASM. Cada binding expõe a mesma superfície: construção de múltiplas páginas, textos CJK / cirílico / grego via fontes embutidas, 15 métodos de anotação, 5 tipos de widget AcroForm, primitivas gráficas (rect,filled_rect,line), criptografia AES-256 e o pipeline HTML+CSS.
Exemplo rápido
Rust
use pdf_oxide::writer::{DocumentBuilder, PageSize, DocumentMetadata};
let mut builder = DocumentBuilder::new()
.metadata(DocumentMetadata::new().title("My Document"));
builder
.page(PageSize::Letter)
.at(72.0, 720.0)
.heading(1, "Hello, World!")
.paragraph("This is a PDF document created with DocumentBuilder.")
.done();
let bytes = builder.build()?;
std::fs::write("output.pdf", bytes)?;
Python
from pdf_oxide import DocumentBuilder, EmbeddedFont
font = EmbeddedFont.from_file("DejaVuSans.ttf")
pdf = (DocumentBuilder()
.register_embedded_font("DejaVu", font)
.a4_page()
.font("DejaVu", 12).at(72, 720).text("Hello, World!")
.highlight((1.0, 1.0, 0.0))
.done()
.build())
open("output.pdf", "wb").write(pdf)
Node / TypeScript
import { DocumentBuilder, EmbeddedFont } from "pdf-oxide";
const font = await EmbeddedFont.fromFile("DejaVuSans.ttf");
const bytes = new DocumentBuilder()
.registerEmbeddedFont("DejaVu", font)
.a4Page()
.font("DejaVu", 12).at(72, 720).text("Hello, World!")
.highlight([1.0, 1.0, 0.0])
.done()
.build();
C#
using PdfOxide;
using var font = EmbeddedFont.FromFile("DejaVuSans.ttf");
var bytes = DocumentBuilder.Create()
.RegisterEmbeddedFont("DejaVu", font)
.A4Page()
.Font("DejaVu", 12).At(72, 720).Text("Hello, World!")
.Highlight(1.0, 1.0, 0.0)
.Done()
.Build();
File.WriteAllBytes("output.pdf", bytes);
Go (caminho CGo; requer CGO_ENABLED=1)
import pdfoxide "github.com/yfedoseev/pdf_oxide/go"
font, _ := pdfoxide.EmbeddedFontFromFile("DejaVuSans.ttf")
defer font.Close()
builder := pdfoxide.NewDocumentBuilder()
builder.RegisterEmbeddedFont("DejaVu", font)
builder.A4Page().
Font("DejaVu", 12).At(72, 720).Text("Hello, World!").
Highlight(1.0, 1.0, 0.0).
Done()
bytes, _ := builder.Build()
WASM (navegador / Node / bundler — mesma API)
import init, { DocumentBuilder, EmbeddedFont } from "pdf-oxide-wasm/web";
await init();
const font = await fetch("/DejaVuSans.ttf").then(r => r.arrayBuffer());
const bytes = new DocumentBuilder()
.registerEmbeddedFont("DejaVu", EmbeddedFont.fromBytes(new Uint8Array(font), "DejaVu"))
.a4Page()
.font("DejaVu", 12).at(72, 720).text("Hello, World!")
.done()
.build();
Referência completa da API
DocumentBuilder
DocumentBuilder::new() — Criar builder
let mut builder = DocumentBuilder::new();
.metadata(metadata) — Definir metadados do documento
use pdf_oxide::writer::DocumentMetadata;
let mut builder = DocumentBuilder::new()
.metadata(
DocumentMetadata::new()
.title("Report")
.author("Jane Smith")
.subject("Q4 Analysis")
.keywords("finance, quarterly")
.creator("MyApp")
);
.page(size) — Adicionar uma página
Retorna um FluentPageBuilder para acrescentar conteúdo à página. Chame .done() ao terminar.
use pdf_oxide::writer::PageSize;
builder.page(PageSize::A4)
.at(72.0, 770.0)
.text("Hello")
.done();
.letter_page() / .a4_page() — Atalhos por tamanho de página
builder.letter_page().text("US Letter page").done();
builder.a4_page().text("A4 page").done();
.build() — Gerar bytes do PDF
let bytes: Vec<u8> = builder.build()?;
.save(path) — Construir e gravar em arquivo
builder.save("output.pdf")?;
.save_encrypted(path, user_pw, owner_pw) — Criptografia AES-256
Adicionado na v0.3.38. Disponível em todos os bindings.
DocumentBuilder::new()
.a4_page().text("secret").done()
.save_encrypted("out.pdf", "user-pw", "owner-pw")?;
(DocumentBuilder()
.a4_page().text("secret").done()
.save_encrypted("out.pdf", "user-pw", "owner-pw"))
DocumentBuilder.Create()
.A4Page().Text("secret").Done()
.SaveEncrypted("out.pdf", "user-pw", "owner-pw");
Também disponíveis: .to_bytes_encrypted(user_pw, owner_pw) para saída em memória; .save_with_encryption(path, algorithm, permissions, user_pw, owner_pw) (Rust) para escolher algoritmo e permissões individuais.
DocumentMetadata
Builder para metadados no nível do documento.
| Método | Descrição |
|---|---|
.title(s) |
Define o título do documento |
.author(s) |
Define o autor do documento |
.subject(s) |
Define o assunto do documento |
.keywords(s) |
Define as palavras-chave do documento |
.creator(s) |
Define a aplicação criadora |
FluentPageBuilder
Retornado por builder.page(size). Todos os métodos retornam self para encadeamento (exceto .done()).
Texto e posicionamento
| Método | Descrição |
|---|---|
.at(x, y) |
Define a posição do cursor (pontos a partir do canto inferior esquerdo) |
.text(s) |
Adiciona texto na posição atual do cursor |
.heading(level, s) |
Adiciona título (1–6, com fonte apropriada) |
.paragraph(s) |
Adiciona parágrafo com quebra automática |
.font(name, size) |
Define a fonte para os textos seguintes |
.text_config(config) |
Define uma configuração completa de texto |
.space(points) |
Adiciona espaço vertical |
.horizontal_rule() |
Insere uma linha divisória horizontal |
.element(elem) |
Adiciona um ContentElement bruto |
.elements(vec) |
Adiciona vários elementos de conteúdo brutos |
Anotações
| Método | Descrição |
|---|---|
.link_url(url) |
Associa o último texto a uma URL |
.link_page(page_index) |
Associa o último texto a uma página interna |
.link_named(destination) |
Associa a um destino nomeado |
.highlight(color) |
Realça o último texto (tupla RGB) |
.underline(color) |
Sublinha o último texto |
.strikeout(color) |
Risca o último texto |
.squiggly(color) |
Sublinha em zigue-zague o último texto |
.sticky_note(text) |
Adiciona uma nota adesiva na posição do cursor |
.sticky_note_with_icon(text, icon) |
Nota adesiva com ícone específico |
.sticky_note_at(x, y, text) |
Nota adesiva em posição específica |
.stamp(stamp_type) |
Adiciona um carimbo na posição do cursor |
.stamp_at(rect, stamp_type) |
Adiciona um carimbo em um retângulo específico |
.freetext(rect, text) |
Adiciona uma anotação de texto livre |
.freetext_styled(rect, text, font, size) |
Anotação de texto livre estilizada |
.watermark(text) |
Marca d’água diagonal atravessando a página |
.watermark_confidential() |
Marca d’água pronta “CONFIDENTIAL” |
.watermark_draft() |
Marca d’água pronta “DRAFT” |
.watermark_custom(watermark) |
Marca d’água personalizada |
.add_annotation(annotation) |
Adiciona qualquer tipo de anotação |
Widgets AcroForm
Adicionados em todos os bindings na v0.3.38. Todas as posições estão em pontos PDF contados a partir do canto inferior esquerdo da página.
| Método | Descrição |
|---|---|
.text_field(name, x, y, w, h, default_value=None) |
Campo de texto de linha única |
.checkbox(name, x, y, w, h, checked) |
Caixa de seleção |
.combo_box(name, x, y, w, h, options, selected=None) |
Seletor suspenso |
.radio_group(name, buttons, selected=None) |
Grupo de botões de rádio; buttons é uma lista de (export_value, x, y, w, h) |
.push_button(name, x, y, w, h, caption) |
Botão clicável com rótulo |
(DocumentBuilder()
.a4_page()
.text_field("name", 150, 680, 200, 20, "Jane Doe")
.checkbox("subscribe", 72, 650, 15, 15, True)
.combo_box("country", 150, 620, 200, 20, ["US", "UK", "DE"], "US")
.radio_group("tier", [("free", 72, 590, 15, 15), ("pro", 120, 590, 15, 15)], "pro")
.push_button("submit", 72, 540, 80, 25, "Submit")
.done()
.save("form.pdf"))
Primitivas gráficas
Adicionadas em todos os bindings na v0.3.38: rect(x, y, w, h) (somente contorno), filled_rect(x, y, w, h, color) (preenchido, com tupla RGB) e line(x1, y1, x2, y2). Tudo passa pela mesma cadeia do FluentPageBuilder e resolve fundos de formulário, separadores e bordas simples de tabela.
Para controle total de caminhos / padrões / gradientes / ExtGState, use ContentStreamBuilder (somente Rust — veja Gráficos, padrões e sombreamentos).
.done() — Finalizar página
Devolve o controle ao DocumentBuilder.
builder.page(PageSize::Letter)
.at(72.0, 720.0)
.text("Content")
.done(); // de volta ao builder
TextConfig
Configuração para renderização de texto.
use pdf_oxide::writer::TextConfig;
let config = TextConfig {
font: "Times-Roman".to_string(),
size: 14.0,
align: TextAlign::Center,
line_height: 1.5,
};
| Campo | Tipo | Padrão |
|---|---|---|
font |
String |
"Helvetica" |
size |
f32 |
12.0 |
align |
TextAlign |
Left |
line_height |
f32 |
1.2 |
PageSize
| Variante | Largura × altura (pontos) |
|---|---|
Letter |
612 × 792 |
A4 |
595 × 842 |
Legal |
612 × 1008 |
A3 |
842 × 1190 |
Custom(w, h) |
Dimensões personalizadas |
Exemplos avançados
Documento de várias páginas com anotações
use pdf_oxide::writer::{
DocumentBuilder, DocumentMetadata, PageSize, StampType
};
let mut builder = DocumentBuilder::new()
.metadata(
DocumentMetadata::new()
.title("Annotated Report")
.author("Review Team")
);
// Cover page
builder.page(PageSize::Letter)
.at(72.0, 600.0)
.font("Helvetica-Bold", 28.0)
.text("Annual Review 2025")
.font("Helvetica", 14.0)
.space(20.0)
.text("Prepared by the Review Team")
.watermark_draft()
.done();
// Content page with annotations
builder.page(PageSize::Letter)
.at(72.0, 720.0)
.heading(1, "Executive Summary")
.paragraph(
"Revenue increased 18% year-over-year, driven by expansion \
into new markets and strong retention rates."
)
.text("See full financial details")
.link_page(2) // Link to page 3 (0-indexed)
.space(12.0)
.heading(2, "Key Findings")
.text("Customer satisfaction reached an all-time high.")
.highlight((1.0, 1.0, 0.0)) // Yellow highlight
.sticky_note("Verify this claim with latest survey data")
.paragraph(
"Operating costs were reduced through automation initiatives, \
achieving a 15% improvement in operational efficiency."
)
.stamp(StampType::ForComment)
.done();
// Data page
builder.page(PageSize::Letter)
.at(72.0, 720.0)
.heading(1, "Financial Details")
.paragraph("Detailed breakdown of revenue by segment...")
.horizontal_rule()
.paragraph("North America: $82M (+12%)")
.paragraph("Europe: $41M (+28%)")
.paragraph("Asia-Pacific: $19M (+35%)")
.done();
builder.save("annotated_report.pdf")?;
Posicionamento preciso de texto
use pdf_oxide::writer::{DocumentBuilder, PageSize};
let mut builder = DocumentBuilder::new();
builder.page(PageSize::Letter)
// Title at top center area
.at(200.0, 740.0)
.font("Helvetica-Bold", 20.0)
.text("Certificate of Completion")
// Recipient name
.at(200.0, 620.0)
.font("Times-Roman", 16.0)
.text("Awarded to: Jane Smith")
// Details at specific positions
.at(72.0, 500.0)
.font("Helvetica", 12.0)
.text("For successfully completing the Advanced Rust Programming course.")
.at(72.0, 450.0)
.text("Date: November 15, 2025")
.at(350.0, 450.0)
.text("Instructor: Dr. Alan Turing")
.horizontal_rule()
.at(72.0, 380.0)
.font("Helvetica", 9.0)
.text("Certificate ID: CERT-2025-00042")
.done();
builder.save("certificate.pdf")?;
Páginas relacionadas
- API fluente PdfBuilder — criação de alto nível com
PdfBuilder - Criação de anotações — todos os tipos de anotação em detalhe
- Criação de campos de formulário — adicionando campos de formulário interativos
- Renderização de tabelas — criando tabelas