HTML から作成
エントリーポイントは 2 つあります。
Pdf::from_html(content)— 基本的な構造 HTML(見出し、段落、リスト、コード、太字/斜体)に対応。スタイルなし。全バインディング。Pdf::from_html_css(html, css, font_bytes)— v0.3.37 で導入された純 Rust の完全 HTML+CSS パイプライン。手書きの CSS エンジン(L3 + L4 セレクタのサブセット、カスケード、calc()/var()、@page/@media print)、Taffy ベースの block / flex / grid レイアウト、UAX #14 ライン分割、rustybuzz による RTL シェイピング、::before/::after、page-break-*、<a href>→ リンク注釈、<img>data-URI →/XObject、マルチフォントカスケードに対応。MPL 依存ゼロ。全バインディング。
簡単な例
Python
from pdf_oxide import Pdf
pdf = Pdf.from_html("<h1>Hello</h1><p>World</p>")
pdf.save("out.pdf")
WASM
import { WasmPdf } from "pdf-oxide-wasm";
import { writeFileSync } from "fs";
const pdf = WasmPdf.fromHtml("<h1>Hello</h1><p>World</p>");
writeFileSync("out.pdf", pdf.toBytes());
Rust
use pdf_oxide::api::Pdf;
let pdf = Pdf::from_html("<h1>Hello</h1><p>World</p>")?;
pdf.save("out.pdf")?;
Go
package main
import (
"log"
pdfoxide "github.com/yfedoseev/pdf_oxide/go"
)
func main() {
pdf, err := pdfoxide.FromHtml("<h1>Hello</h1><p>World</p>")
if err != nil { log.Fatal(err) }
defer pdf.Close()
if err := pdf.Save("out.pdf"); err != nil { log.Fatal(err) }
}
C#
using PdfOxide;
using var pdf = Pdf.FromHtml("<h1>Hello</h1><p>World</p>");
pdf.Save("out.pdf");
HTML + CSS パイプライン (v0.3.37)
Pdf::from_html_css(html, css, font_bytes) は HTML、CSS スタイルシート、TTF/OTF フォントバイト列を受け取り、ページ分割された PDF を返します。extract_text でバイト単位で往復するため、生成された PDF は既存のテストインフラストラクチャーにそのまま乗せられます。
Rust:
use pdf_oxide::api::Pdf;
let font = std::fs::read("DejaVuSans.ttf")?;
let pdf = Pdf::from_html_css(
"<h1>Hello</h1><p>World</p>",
"h1 { color: blue; font-size: 24pt } p { line-height: 1.5 }",
font,
)?;
pdf.save("out.pdf")?;
Python:
from pdf_oxide import Pdf
with open("DejaVuSans.ttf", "rb") as f:
font = f.read()
pdf = Pdf.from_html_css(
"<h1>Hello</h1><p>World</p>",
"h1 { color: blue; font-size: 24pt }",
font,
)
pdf.save("out.pdf")
Node / TypeScript:
import { Pdf } from "pdf-oxide";
import { readFileSync } from "fs";
const font = readFileSync("DejaVuSans.ttf");
const pdf = Pdf.fromHtmlCss(
"<h1>Hello</h1><p>World</p>",
"h1 { color: blue; font-size: 24pt }",
font,
);
pdf.save("out.pdf");
Go:
font, _ := os.ReadFile("DejaVuSans.ttf")
pdf, err := pdfoxide.FromHtmlCss(
"<h1>Hello</h1><p>World</p>",
"h1 { color: blue; font-size: 24pt }",
font,
)
if err != nil { log.Fatal(err) }
defer pdf.Close()
_ = pdf.Save("out.pdf")
C#:
var font = File.ReadAllBytes("DejaVuSans.ttf");
using var pdf = Pdf.FromHtmlCss(
"<h1>Hello</h1><p>World</p>",
"h1 { color: blue; font-size: 24pt }",
font);
pdf.Save("out.pdf");
マルチフォントカスケード
複数のフォントファミリーを組み合わせる場合は Pdf::from_html_css_with_fonts(html, css, fonts) を使います。任意の要素に付けた CSS font-family は、登録済みファミリー名(大文字小文字を区別せず、引用符あり/なし、複数単語の裸書きも許容)と照合されます。未知のファミリーは最初に登録したフォントにフォールバックします。
from pdf_oxide import Pdf
fonts = [
("DejaVu Sans", open("DejaVuSans.ttf", "rb").read()),
("Noto Sans CJK", open("NotoSansCJKtc-Regular.otf", "rb").read()),
]
pdf = Pdf.from_html_css_with_fonts(
'<h1 style="font-family: DejaVu Sans">English</h1>'
'<p style="font-family: \'Noto Sans CJK\'">中文段落</p>',
"h1 { font-size: 24pt }",
fonts,
)
pdf.save("multilang.pdf")
CJK コンテンツは出力時に自動でサブセット化されます(v0.3.38 #385)。~17 MB の CJK フォントから 5 文字だけを使った PDF は通常 100 KB 未満に収まります。
サポートする CSS の範囲
- セレクタ — L3 + L4 のサブセット:
:is/:where/:not/:has、構造系擬似クラス、i/sフラグ付き属性マッチャ。 - カスケード — オリジン/詳細度/ソース順のソート、継承、インラインスタイルのマージ、カスタムプロパティ(循環検出付き
var())。 - 関数 —
calc()、min()、max()、clamp()。 - At ルール —
@media print(常に真)、(min/max-width)、マージンボックス付きの@page :first / :left / :right / :blank、@font-face、@import、@supports。 - 型付きプロパティ値 — 色(~150 の色名、16 進、rgb/rgba、hsl)、長さ(CSS Values L4 の全単位)、display、font-size / weight / style / family、margin / padding ショートハンド、line-height。
- カウンター —
counter/counters、counter-reset/-increment/-set、ローマ字/ギリシャ/アルファ番号。 - 擬似要素 — リテラル文字列、
attr(name)、open-quote/close-quoteに対応した::before/::after。 - レイアウト — Taffy による block / flex / grid、マージンの相殺、多段組(
column-count/column-width/column-gap)、テーブル(自動・固定アルゴリズム)。 - インライン — UAX #14 ライン分割、
text-align、white-spaceモード、ハードブレーク、原子的インラインボックス。 - エフェクト —
opacity、transform: translate*()、page-break-before: always、page-break-after: always。 - HTML — HTML5 トークナイザ、
<style>/<link rel="stylesheet">/ インラインstyle=""の抽出、<img>data-URI デコード(/XObject)、<a href>→/URI付き/Link注釈、<ul>/<ol>のリストマーカー。
対象外
CSS フィルタ、3D トランスフォーム、アニメーション、HTML 内 SVG(実用的な Rust SVG クレートはすべて MPL)、MathML、hyphens: auto、shape-outside、JavaScript の実行、フル行列 transform(scale / rotate)、グラデーション、box-shadow。
ライセンス
cargo deny check licenses は ゼロ の MPL 推移的依存でパスします。Mozilla の CSS スタック(cssparser、selectors、html5ever、lightningcss、stylo)はすべて MPL-2.0 ですが、v0.3.37 は同等機能を手書きで実装して pdf_oxide 全体を MIT/Apache のみに保っています。
サポートされる HTML 要素
| Element | 説明 |
|---|---|
<h1> through <h6> |
Headings (mapped to PDF heading sizes) |
<p> |
自動間隔付き段落 |
<b>, <strong> |
太字テキスト |
<i>, <em> |
斜体テキスト |
<ul>, <ol>, <li> |
箇条書きと番号付きリスト |
<pre>, <code> |
整形済みとインラインコード |
<blockquote> |
ブロック引用 |
<br> |
改行 |
<hr> |
水平線 |
完全な API リファレンス
Pdf::from_html(content) (Static Method)
Creates a PDF from HTML content using default settings (Letter page, 72pt margins, 12pt Helvetica).
Rust:
use pdf_oxide::api::Pdf;
let html = r#"
<h1>Product Specification</h1>
<p>This document describes the <strong>technical requirements</strong>
for the new product line.</p>
<h2>Requirements</h2>
<ul>
<li>Operating temperature: -20C to 60C</li>
<li>Power consumption: <5W</li>
<li>Weight: <200g</li>
</ul>
"#;
let pdf = Pdf::from_html(html)?;
pdf.save("spec.pdf")?;
JavaScript:
import { WasmPdf } from "pdf-oxide-wasm";
import { writeFileSync } from "fs";
const html = `
<h1>Product Specification</h1>
<p>This document describes the <strong>technical requirements</strong>
for the new product line.</p>
`;
const pdf = WasmPdf.fromHtml(html);
writeFileSync("spec.pdf", pdf.toBytes());
Python:
from pdf_oxide import Pdf
html = """
<h1>Product Specification</h1>
<p>This document describes the <strong>technical requirements</strong>
for the new product line.</p>
"""
pdf = Pdf.from_html(html)
pdf.save("spec.pdf")
Python Signature:
Pdf.from_html(
content: str,
title: str | None = None,
author: str | None = None
) -> Pdf
PdfBuilder::new().from_html(content) (Builder Pattern)
Use PdfBuilder for control over page size, margins, font size, and document metadata.
Rust:
use pdf_oxide::api::PdfBuilder;
use pdf_oxide::writer::PageSize;
let pdf = PdfBuilder::new()
.title("Technical Specification")
.author("Engineering")
.page_size(PageSize::A4)
.margin(54.0)
.font_size(11.0)
.from_html("<h1>Spec</h1><p>Version 2.0</p>")?;
pdf.save("spec_a4.pdf")?;
応用例
構造化レポート
use pdf_oxide::api::Pdf;
let html = r#"
<h1>Incident Report</h1>
<h2>Summary</h2>
<p>On <em>2025-11-15</em>, a service disruption was detected in the
<strong>payment processing</strong> pipeline.</p>
<h2>Timeline</h2>
<ol>
<li>14:32 UTC - Alert triggered for elevated error rates</li>
<li>14:35 UTC - On-call engineer acknowledged</li>
<li>14:48 UTC - Root cause identified: database connection pool exhaustion</li>
<li>15:02 UTC - Fix deployed, services recovering</li>
<li>15:15 UTC - Full recovery confirmed</li>
</ol>
<h2>Root Cause</h2>
<p>A configuration change deployed at 14:00 UTC reduced the maximum
connection pool size from 100 to 10.</p>
<h2>Code Reference</h2>
<pre><code>max_connections: 10 # Should be 100
timeout_seconds: 30
</code></pre>
<h2>Action Items</h2>
<ul>
<li>Add validation for connection pool configuration</li>
<li>Implement canary deployment for config changes</li>
<li>Add alerting for connection pool utilization</li>
</ul>
"#;
let pdf = Pdf::from_html(html)?;
pdf.save("incident_report.pdf")?;
Python で動的 HTML を使用
from pdf_oxide import Pdf
rows = [
("Widget A", "$12.99", 150),
("Widget B", "$24.50", 89),
("Widget C", "$7.25", 312),
]
html = "<h1>Inventory Report</h1>"
html += "<p>Generated on 2025-11-20</p>"
html += "<h2>Current Stock</h2><ul>"
for name, price, qty in rows:
html += f"<li><strong>{name}</strong> - {price} ({qty} units)</li>"
html += "</ul>"
pdf = Pdf.from_html(html, title="Inventory Report")
pdf.save("inventory.pdf")
ファイルから HTML を読み込む
from pdf_oxide import Pdf
with open("report.html") as f:
html = f.read()
pdf = Pdf.from_html(html, title="Report")
pdf.save("report.pdf")
import { WasmPdf } from "pdf-oxide-wasm";
import { readFileSync, writeFileSync } from "fs";
const html = readFileSync("report.html", "utf-8");
const pdf = WasmPdf.fromHtml(html);
writeFileSync("report.pdf", pdf.toBytes());
use pdf_oxide::api::Pdf;
let html = std::fs::read_to_string("report.html")?;
let pdf = Pdf::from_html(&html)?;
pdf.save("report.pdf")?;
関連ページ
- Create from Markdown – Convert MarkdownからPDFへ
- PdfBuilder Fluent API – フルビルダー設定オプション
- DocumentBuilder Low-Level API – プログラム的ページ構築