Skip to content

API fluida de DocumentBuilder

DocumentBuilder es una API fluida que permite construir documentos PDF página a página con control total sobre la colocación de texto, las fuentes, las anotaciones, los campos de formulario y los elementos de contenido.

Cobertura por binding (v0.3.38). DocumentBuilder + FluentPageBuilder + EmbeddedFont se entregan en Rust, Python, Node/TypeScript, C#, Go y WASM. Todos los bindings exponen la misma superficie: construcción multipágina, texto CJK / cirílico / griego mediante fuentes embebidas, 15 métodos de anotación, 5 tipos de widget AcroForm, primitivas gráficas (rect, filled_rect, line), cifrado AES-256 y el pipeline HTML+CSS.

Ejemplo 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 (ruta CGo; requiere 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 — misma 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();

Referencia completa de la API

DocumentBuilder

DocumentBuilder::new() – Crear builder

let mut builder = DocumentBuilder::new();

.metadata(metadata) – Establecer metadatos del 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) – Agregar una página

Devuelve un FluentPageBuilder para añadir contenido a la página. Llama a .done() al terminar.

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 conveniencia

builder.letter_page().text("US Letter page").done();
builder.a4_page().text("A4 page").done();

.build() – Generar bytes de PDF

let bytes: Vec<u8> = builder.build()?;

.save(path) – Compilar y guardar en archivo

builder.save("output.pdf")?;

.save_encrypted(path, user_pw, owner_pw) – Cifrado AES-256

Añadido en la v0.3.38. Disponible en todos los 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");

También disponibles: .to_bytes_encrypted(user_pw, owner_pw) para salida en memoria; .save_with_encryption(path, algorithm, permissions, user_pw, owner_pw) (Rust) para algoritmo personalizado y permisos por flag.

DocumentMetadata

Builder para metadatos a nivel de documento.

Método Descripción
.title(s) Título del documento
.author(s) Autor del documento
.subject(s) Asunto del documento
.keywords(s) Palabras clave
.creator(s) Aplicación creadora

FluentPageBuilder

Lo devuelve builder.page(size). Todos los métodos retornan self para encadenamiento (excepto .done()).

Texto y posicionamiento

Método Descripción
.at(x, y) Posición del cursor (puntos desde la esquina inferior izquierda)
.text(s) Añadir texto en la posición actual del cursor
.heading(level, s) Añadir encabezado (1-6, con fuente adecuada)
.paragraph(s) Añadir párrafo con ajuste automático
.font(name, size) Fuente para el texto siguiente
.text_config(config) Configuración de texto completa
.space(points) Espacio vertical
.horizontal_rule() Línea divisoria horizontal
.element(elem) Añadir un ContentElement en crudo
.elements(vec) Añadir varios elementos de contenido en crudo

Anotaciones

Método Descripción
.link_url(url) Vincular el último texto a una URL
.link_page(page_index) Vincular el último texto a una página interna
.link_named(destination) Vincular a un destino con nombre
.highlight(color) Resaltar el último texto (tupla RGB)
.underline(color) Subrayar el último texto
.strikeout(color) Tachar el último texto
.squiggly(color) Subrayado ondulado sobre el último texto
.sticky_note(text) Nota adhesiva en la posición del cursor
.sticky_note_with_icon(text, icon) Nota adhesiva con un icono concreto
.sticky_note_at(x, y, text) Nota adhesiva en una posición concreta
.stamp(stamp_type) Sello en la posición del cursor
.stamp_at(rect, stamp_type) Sello dentro de un rectángulo
.freetext(rect, text) Anotación de texto libre
.freetext_styled(rect, text, font, size) Anotación de texto libre con estilo
.watermark(text) Marca de agua diagonal sobre la página
.watermark_confidential() Marca de agua predefinida “CONFIDENTIAL”
.watermark_draft() Marca de agua predefinida “DRAFT”
.watermark_custom(watermark) Marca de agua personalizada
.add_annotation(annotation) Añadir cualquier tipo de anotación

Widgets AcroForm

Incorporados a todos los bindings en la v0.3.38. Las posiciones van en puntos PDF desde la esquina inferior izquierda de la página.

Método Descripción
.text_field(name, x, y, w, h, default_value=None) Campo de texto de una línea
.checkbox(name, x, y, w, h, checked) Casilla de verificación
.combo_box(name, x, y, w, h, options, selected=None) Selector desplegable
.radio_group(name, buttons, selected=None) Grupo de radios; buttons es una lista de (export_value, x, y, w, h)
.push_button(name, x, y, w, h, caption) Botón clicable con etiqueta
(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

Incorporadas a todos los bindings en la v0.3.38: rect(x, y, w, h) (solo trazo), filled_rect(x, y, w, h, color) (relleno con una tupla RGB) y line(x1, y1, x2, y2). Se encadenan a través del mismo FluentPageBuilder y bastan para fondos de formularios, separadores y bordes de tabla sencillos.

Para control total de trazados / patrones / gradientes / ExtGState, usa ContentStreamBuilder (solo Rust — consulta Gráficos, patrones y sombreados).

.done() – Terminar página

Devuelve el control al DocumentBuilder.

builder.page(PageSize::Letter)
    .at(72.0, 720.0)
    .text("Content")
    .done();  // Back to builder

TextConfig

Configuración para el renderizado 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 Valor por defecto
font String "Helvetica"
size f32 12.0
align TextAlign Left
line_height f32 1.2

PageSize

Variante Ancho × Alto (puntos)
Letter 612 × 792
A4 595 × 842
Legal 612 × 1008
A3 842 × 1190
Custom(w, h) Dimensiones personalizadas

Ejemplos avanzados

Documento multipágina con anotaciones

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")?;

Posicionamiento 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