DocumentBuilder 流暢 API
DocumentBuilder は、テキスト配置・フォント・注釈・フォームフィールド・コンテンツ要素を細かく制御しながら、ページ単位で PDF を組み立てるための流暢 API です。
バインディング対応状況(v0.3.38)。
DocumentBuilder+FluentPageBuilder+EmbeddedFontは Rust、Python、Node/TypeScript、C#、Go、WASM すべてに搭載されました。どのバインディングも同じ API 面を提供します。複数ページ構築、埋め込みフォントによる CJK/キリル/ギリシャ文字対応、15 種類の注釈メソッド、5 種類の AcroForm ウィジェット、図形プリミティブ(rect、filled_rect、line)、AES-256 暗号化、そして HTML+CSS パイプラインです。
簡単な例
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(CGo パス。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(ブラウザ/Node/バンドラで共通 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();
完全な API リファレンス
DocumentBuilder
DocumentBuilder::new() — ビルダーを生成
let mut builder = DocumentBuilder::new();
.metadata(metadata) — ドキュメントメタデータを設定
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) — ページを追加
FluentPageBuilder を返します。ページにコンテンツを追加し、終わったら .done() を呼び出します。
use pdf_oxide::writer::PageSize;
builder.page(PageSize::A4)
.at(72.0, 770.0)
.text("Hello")
.done();
.letter_page() / .a4_page() — 便利なページメソッド
builder.letter_page().text("US Letter page").done();
builder.a4_page().text("A4 page").done();
.build() — PDF バイト列を生成
let bytes: Vec<u8> = builder.build()?;
.save(path) — 組み立ててファイルに保存
builder.save("output.pdf")?;
.save_encrypted(path, user_pw, owner_pw) — AES-256 暗号化
v0.3.38 で追加。全バインディングで利用できます。
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");
メモリ上に出力したい場合は .to_bytes_encrypted(user_pw, owner_pw) も使えます。Rust では .save_with_encryption(path, algorithm, permissions, user_pw, owner_pw) でアルゴリズムとパーミッションを細かく指定できます。
DocumentMetadata
ドキュメントレベルのメタデータビルダー。
| メソッド | 説明 |
|---|---|
.title(s) |
ドキュメントタイトルを設定 |
.author(s) |
ドキュメント著者を設定 |
.subject(s) |
ドキュメント件名を設定 |
.keywords(s) |
ドキュメントキーワードを設定 |
.creator(s) |
作成アプリケーションを設定 |
FluentPageBuilder
builder.page(size) が返します。.done() を除き、すべてのメソッドは self を返してチェーンできます。
テキストと位置指定
| メソッド | 説明 |
|---|---|
.at(x, y) |
カーソル位置を設定(ページ左下からのポイント) |
.text(s) |
現在のカーソル位置にテキストを追加 |
.heading(level, s) |
見出しを追加(1–6、適切なフォントを自動選択) |
.paragraph(s) |
自動折り返し付きの段落を追加 |
.font(name, size) |
以降のテキストに適用するフォントを設定 |
.text_config(config) |
フル設定のテキスト構成を設定 |
.space(points) |
垂直スペースを追加 |
.horizontal_rule() |
水平区切り線を追加 |
.element(elem) |
生の ContentElement を追加 |
.elements(vec) |
複数の生コンテンツ要素を追加 |
注釈
| メソッド | 説明 |
|---|---|
.link_url(url) |
直前のテキスト要素を URL にリンク |
.link_page(page_index) |
直前のテキストを内部ページにリンク |
.link_named(destination) |
名前付き宛先へのリンク |
.highlight(color) |
直前のテキストをハイライト(RGB タプル) |
.underline(color) |
直前のテキストに下線 |
.strikeout(color) |
直前のテキストに取消線 |
.squiggly(color) |
直前のテキストに波線 |
.sticky_note(text) |
カーソル位置に付箋を追加 |
.sticky_note_with_icon(text, icon) |
指定アイコンの付箋を追加 |
.sticky_note_at(x, y, text) |
指定位置に付箋を追加 |
.stamp(stamp_type) |
カーソル位置にスタンプを追加 |
.stamp_at(rect, stamp_type) |
指定矩形にスタンプを追加 |
.freetext(rect, text) |
フリーテキスト注釈を追加 |
.freetext_styled(rect, text, font, size) |
スタイル付きフリーテキスト注釈を追加 |
.watermark(text) |
ページ全体に斜め透かしを追加 |
.watermark_confidential() |
プリセットの “CONFIDENTIAL” 透かしを追加 |
.watermark_draft() |
プリセットの “DRAFT” 透かしを追加 |
.watermark_custom(watermark) |
カスタム透かし注釈を追加 |
.add_annotation(annotation) |
任意の注釈タイプを追加 |
AcroForm ウィジェット
v0.3.38 で全バインディングに追加。座標はすべてページ左下原点からの PDF ポイントです。
| メソッド | 説明 |
|---|---|
.text_field(name, x, y, w, h, default_value=None) |
一行テキスト入力 |
.checkbox(name, x, y, w, h, checked) |
チェックボックスウィジェット |
.combo_box(name, x, y, w, h, options, selected=None) |
ドロップダウンセレクタ |
.radio_group(name, buttons, selected=None) |
ラジオグループ。buttons は (export_value, x, y, w, h) のリスト |
.push_button(name, x, y, w, h, caption) |
ラベル付きのクリック可能ボタン |
(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"))
図形プリミティブ
v0.3.38 で全バインディングに追加。rect(x, y, w, h)(線のみ)、filled_rect(x, y, w, h, color)(RGB タプルで塗りつぶし)、line(x1, y1, x2, y2) が使えます。いずれも同じ FluentPageBuilder チェーンを通して呼び出せ、フォーム背景、区切り、シンプルなテーブル罫線には十分です。
パス/パターン/グラデーション/ExtGState を完全制御したい場合は ContentStreamBuilder を使ってください(Rust 専用、グラフィックス、パターン、シェーディング を参照)。
.done() — ページを終了
DocumentBuilder に制御を返します。
builder.page(PageSize::Letter)
.at(72.0, 720.0)
.text("Content")
.done(); // Back to builder
TextConfig
テキスト描画の設定。
use pdf_oxide::writer::TextConfig;
let config = TextConfig {
font: "Times-Roman".to_string(),
size: 14.0,
align: TextAlign::Center,
line_height: 1.5,
};
| フィールド | 型 | 既定値 |
|---|---|---|
font |
String |
"Helvetica" |
size |
f32 |
12.0 |
align |
TextAlign |
Left |
line_height |
f32 |
1.2 |
PageSize
| バリアント | 幅 × 高さ(ポイント) |
|---|---|
Letter |
612 × 792 |
A4 |
595 × 842 |
Legal |
612 × 1008 |
A3 |
842 × 1190 |
Custom(w, h) |
任意サイズ |
応用例
注釈付き複数ページドキュメント
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")?;
精密なテキスト配置
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")?;
関連ページ
- PdfBuilder 流暢 API — PdfBuilder による高レベル作成
- 注釈の作成 — 全注釈タイプの詳細
- フォームフィールドの作成 — インタラクティブなフォームフィールドを追加
- テーブルのレンダリング — テーブルの作成