API Fluente do DocumentBuilder
O DocumentBuilder é uma API fluente para construir documentos PDF página por página, com controle total sobre o posicionamento do texto, fontes, anotações, campos de formulário e elementos de conteúdo.
Cobertura nas bindings (v0.3.38).
DocumentBuilder+FluentPageBuilder+EmbeddedFontestão disponíveis em Rust, Python, Node/TypeScript, C#, Go e WASM. Todas as bindings expõem o mesmo conjunto de recursos: construção de várias páginas, texto em CJK / cirílico / grego por meio de fontes incorporadas, 15 métodos de anotação, 5 tipos de widget do 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();
C++
#include <pdf_oxide/pdf_oxide.hpp>
auto font = pdf_oxide::EmbeddedFont::from_file("DejaVuSans.ttf");
auto builder = pdf_oxide::DocumentBuilder::create();
builder.register_embedded_font("DejaVu", font);
builder.a4_page()
.font("DejaVu", 12).at(72, 720).text("Hello, World!")
.highlight(1.0, 1.0, 0.0)
.done();
std::vector<std::uint8_t> bytes = builder.build();
Swift
import PdfOxide
let font = try EmbeddedFont.fromFile("DejaVuSans.ttf")
let builder = try DocumentBuilder.create()
try builder.registerEmbeddedFont("DejaVu", font)
let page = try builder.a4Page()
try page.font("DejaVu", 12).at(72, 720).text("Hello, World!")
.highlight(1.0, 1.0, 0.0)
.done()
let bytes = try builder.build()
Dart
import 'package:pdf_oxide/pdf_oxide.dart';
final font = EmbeddedFont.fromFile('DejaVuSans.ttf');
final builder = DocumentBuilder.create();
builder.registerEmbeddedFont('DejaVu', font);
builder.a4Page()
.font('DejaVu', 12.0).at(72.0, 720.0).text('Hello, World!')
.highlight(1.0, 1.0, 0.0)
.done();
final bytes = builder.build();
R
library(pdfoxide)
font <- pdf_embedded_font_from_file("DejaVuSans.ttf")
b <- pdf_builder_create()
pdf_builder_register_embedded_font(b, "DejaVu", font)
pg <- pdf_builder_a4_page(b)
pdf_page_font(pg, "DejaVu", 12)
pdf_page_at(pg, 72, 720)
pdf_page_builder_text(pg, "Hello, World!")
pdf_page_highlight(pg, 1.0, 1.0, 0.0)
pdf_page_done(pg)
bytes <- pdf_builder_build(b)
Julia
using PdfOxide
emb = embedded_font_from_file("DejaVuSans.ttf")
b = DocumentBuilder()
register_embedded_font(b, "DejaVu", emb)
pg = a4_page(b)
font(pg, "DejaVu", 12)
at(pg, 72, 720)
text(pg, "Hello, World!")
highlight(pg, 1.0, 1.0, 0.0)
done(pg)
bytes = build(b)
Zig
const pdf_oxide = @import("pdf_oxide");
const a = std.heap.page_allocator;
var font = try pdf_oxide.EmbeddedFont.fromFile("DejaVuSans.ttf");
var builder = try pdf_oxide.DocumentBuilder.create();
try builder.registerEmbeddedFont("DejaVu", &font);
var page = try builder.a4Page();
try page.font("DejaVu", 12);
try page.at(72, 720);
try page.text("Hello, World!");
try page.highlight(1.0, 1.0, 0.0);
try page.done();
const bytes = try builder.build(a);
Objective-C
#import "POXPdfOxide.h"
NSError *err = nil;
POXEmbeddedFont *font = [POXEmbeddedFont fromPath:@"DejaVuSans.ttf" error:&err];
POXDocumentBuilder *builder = [POXDocumentBuilder createWithError:&err];
[builder registerEmbeddedFont:@"DejaVu" font:font error:&err];
POXPageBuilder *page = [builder a4PageWithError:&err];
[page font:@"DejaVu" size:12 error:&err];
[page at:72 y:720 error:&err];
[page text:@"Hello, World!" error:&err];
[page highlightR:1.0 g:1.0 b:0.0 error:&err];
[page done:&err];
NSData *bytes = [builder buildWithError:&err];
Elixir
{:ok, font} = PdfOxide.font_from_file("DejaVuSans.ttf")
{:ok, db} = PdfOxide.builder()
:ok = PdfOxide.builder_register_embedded_font(db, "DejaVu", font)
{:ok, page} = PdfOxide.builder_a4_page(db)
:ok = PdfOxide.page_font(page, "DejaVu", 12)
:ok = PdfOxide.page_at(page, 72, 720)
:ok = PdfOxide.page_text(page, "Hello, World!")
:ok = PdfOxide.page_highlight(page, 1.0, 1.0, 0.0)
:ok = PdfOxide.page_done(page)
{:ok, bytes} = PdfOxide.builder_build(db)
Referência Completa da API
DocumentBuilder
DocumentBuilder::new() – Criar o 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 adicionar conteúdo à página. Chame .done() ao finalizar.
use pdf_oxide::writer::PageSize;
builder.page(PageSize::A4)
.at(72.0, 770.0)
.text("Hello")
.done();
.letter_page() / .a4_page() – Métodos de Página de Conveniência
builder.letter_page().text("US Letter page").done();
builder.a4_page().text("A4 page").done();
.build() – Gerar os Bytes do PDF
let bytes: Vec<u8> = builder.build()?;
.save(path) – Construir e Salvar em Arquivo
builder.save("output.pdf")?;
.save_encrypted(path, user_pw, owner_pw) – Criptografia AES-256
Adicionado na v0.3.38. Disponível em todas as 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 algoritmo personalizado e flags por permissão.
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 o aplicativo criador |
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 a fonte apropriada) |
.paragraph(s) |
Adiciona parágrafo com quebra de linha automática |
.font(name, size) |
Define a fonte para o texto seguinte |
.text_config(config) |
Define a configuração completa de texto |
.space(points) |
Adiciona espaçamento vertical |
.horizontal_rule() |
Adiciona 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) |
Vincula o último elemento de texto a uma URL |
.link_page(page_index) |
Vincula o último texto a uma página interna |
.link_named(destination) |
Vincula 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) |
Sublinhado ondulado no último texto |
.sticky_note(text) |
Adiciona nota adesiva na posição do cursor |
.sticky_note_with_icon(text, icon) |
Adiciona nota adesiva com ícone específico |
.sticky_note_at(x, y, text) |
Adiciona nota adesiva em posição específica |
.stamp(stamp_type) |
Adiciona carimbo na posição do cursor |
.stamp_at(rect, stamp_type) |
Adiciona carimbo em retângulo específico |
.freetext(rect, text) |
Adiciona anotação de texto livre |
.freetext_styled(rect, text, font, size) |
Adiciona anotação de texto livre estilizada |
.watermark(text) |
Adiciona marca d’água diagonal na página |
.watermark_confidential() |
Adiciona marca d’água predefinida “CONFIDENTIAL” |
.watermark_draft() |
Adiciona marca d’água predefinida “DRAFT” |
.watermark_custom(watermark) |
Adiciona anotação de marca d’água personalizada |
.add_annotation(annotation) |
Adiciona qualquer tipo de anotação |
Widgets do AcroForm
Adicionados em todas as bindings na v0.3.38. Todas as posições são em pontos PDF a partir da origem no canto inferior esquerdo da página.
| Método | Descrição |
|---|---|
.text_field(name, x, y, w, h, default_value=None) |
Entrada de texto de linha única |
.checkbox(name, x, y, w, h, checked) |
Widget de 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 opção; 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 todas as bindings na v0.3.38: rect(x, y, w, h) (apenas contorno), filled_rect(x, y, w, h, color) (preenchido com uma tupla RGB) e line(x1, y1, x2, y2). Elas passam pela mesma cadeia do FluentPageBuilder e são suficientes para fundos de formulário, separadores e bordas simples de tabela.
Para controle completo de caminhos / padrões / gradientes / ExtGState, use o ContentStreamBuilder (apenas Rust — consulte Gráficos, Padrões e Sombreamentos).
.done() – Finalizar a Página
Devolve o controle ao DocumentBuilder.
builder.page(PageSize::Letter)
.at(72.0, 720.0)
.text("Content")
.done(); // Back to builder
TextConfig
Configuração para a 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 x Altura (pontos) |
|---|---|
Letter |
612 x 792 |
A4 |
595 x 842 |
Legal |
612 x 1008 |
A3 |
842 x 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 do PdfBuilder – Criação de alto nível com o 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