Create from HTML
Two entry points are available:
Pdf::from_html(content)— basic structural HTML (headings, paragraphs, lists, code, bold/italic). No styling. Every binding.Pdf::from_html_css(html, css, font_bytes)— full pure-Rust HTML+CSS pipeline introduced in v0.3.37. Hand-rolled CSS engine (L3 + L4 selectors subset, cascade,calc()/var(),@page/@media print), Taffy-backed block / flex / grid layout, UAX #14 line breaking, RTL shaping via rustybuzz,::before/::after,page-break-*,<a href>→ link annotation,<img>data-URI →/XObject, multi-font cascade. Zero MPL dependencies. Every binding.
Quick Example
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 pipeline (v0.3.37)
Pdf::from_html_css(html, css, font_bytes) takes HTML, a CSS stylesheet, and TTF/OTF font bytes. Returns a paginated PDF. extract_text round-trips byte-equal so produced PDFs participate in the existing test infrastructure.
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");
Multi-font cascade
Use Pdf::from_html_css_with_fonts(html, css, fonts) when your document mixes several font families. CSS font-family on any element resolves against registered families (case-insensitive, with/without quotes, multi-word unquoted). Unknown families fall back to the first registered font.
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 content is automatically subsetted on output (v0.3.38 #385) — a PDF with 5 characters from a ~17 MB CJK font typically ships under 100 KB.
Supported CSS surface
- Selectors — L3 + L4 subset:
:is/:where/:not/:has, structural pseudo-classes, attribute matchers withi/sflags. - Cascade — origin / specificity / source-order sorting, inheritance, inline-style merge, custom properties (
var()with cycle detection). - Functions —
calc(),min(),max(),clamp(). - At-rules —
@media print(always-true),(min/max-width),@page :first / :left / :right / :blankwith margin boxes,@font-face,@import,@supports. - Typed values — colour (~150 named, hex, rgb/rgba, hsl), length (every CSS Values L4 unit), display, font-size / weight / style / family, margin / padding shorthand, line-height.
- Counters —
counter/counters,counter-reset/-increment/-set, Roman / Greek / alpha numbering. - Pseudo-elements —
::before/::afterwith literal strings,attr(name),open-quote/close-quote. - Layout — block, flex, grid (all via Taffy), margin collapsing, multi-column (
column-count/column-width/column-gap), tables (auto + fixed column algorithms). - Inline — UAX #14 line breaking,
text-align,white-spacemodes, hard breaks, atomic inline boxes. - Effects —
opacity,transform: translate*(),page-break-before: always,page-break-after: always. - HTML — HTML5 tokenizer,
<style>/<link rel="stylesheet">/ inlinestyle=""extraction,<img>data-URI decode (/XObject),<a href>→/Linkannotation with/URI,<ul>/<ol>list markers.
Out of scope
CSS filters, 3D transforms, animations, SVG-in-HTML (every viable Rust SVG crate is MPL), MathML, hyphens: auto, shape-outside, JavaScript execution, full-matrix transform (scale / rotate), gradients, box-shadow.
Licence
cargo deny check licenses passes with zero MPL transitive dependencies. The Mozilla CSS stack (cssparser, selectors, html5ever, lightningcss, stylo) is all MPL-2.0; v0.3.37 hand-rolls the equivalents to keep pdf_oxide entirely under MIT/Apache.
Supported HTML Elements
| Element | Description |
|---|---|
<h1> through <h6> |
Headings (mapped to PDF heading sizes) |
<p> |
Paragraphs with automatic spacing |
<b>, <strong> |
Bold text |
<i>, <em> |
Italic text |
<ul>, <ol>, <li> |
Unordered and ordered lists |
<pre>, <code> |
Preformatted and inline code |
<blockquote> |
Block quotations |
<br> |
Line breaks |
<hr> |
Horizontal rules |
Full API Reference
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")?;
Advanced Examples
Structured Report
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 with Dynamic 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")
Reading HTML from a File
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")?;
Related Pages
- Create from Markdown – Convert Markdown to PDF
- PdfBuilder Fluent API – Full builder configuration options
- DocumentBuilder Low-Level API – Programmatic page construction