ironpress
Pure Rust HTML/CSS/Markdown to PDF converter. No browser, no system dependencies.
Try it in your browser — the playground runs 100% client-side via WebAssembly.
Other Rust PDF crates shell out to headless Chrome or wkhtmltopdf. ironpress does it natively with a built-in layout engine. No C libraries, no binaries to install, just cargo add ironpress.
Performance
Benchmarked on Apple M4 (release build, cargo bench):
| Document | Time | Pages/sec |
|---|---|---|
Simple HTML (<h1> + <p>) |
16 us | 62,500 |
| Styled HTML (CSS, lists, links) | 71 us | 14,000 |
| Markdown (headings, code, lists) | 141 us | 7,000 |
| Table (5 rows, styled headers) | 341 us | 2,900 |
| Full report (tables, flex, progress bars) | 587 us | 1,700 |
For comparison, Chrome headless takes ~2,500 ms per page — ironpress is 4,000x faster.
Table of Contents
- Quick Start
- CLI
- API Reference
- Markdown to PDF
- Math (LaTeX)
- HTML Elements
- CSS Support
- Images
- SVG
- Tables
- Fonts
- Streaming Output
- Async API
- Remote Resources
- Security
- How It Works
- WASM
- Testing
- License
Quick Start
use html_to_pdf;
let pdf_bytes = html_to_pdf.unwrap;
write.unwrap;
CLI
Install the CLI with Cargo:
Convert HTML or Markdown files to PDF:
With options:
Pipe from stdin:
|
|
Run ironpress --help for all options.
API Reference
One-liner functions
// HTML string to PDF bytes
let pdf = html_to_pdf.unwrap;
// Markdown string to PDF bytes
let pdf = markdown_to_pdf.unwrap;
// HTML file to PDF file
convert_file.unwrap;
// Markdown file to PDF file
convert_markdown_file.unwrap;
Builder API
use ;
let pdf = new
.page_size // default: A4
.margin // default: 72pt (1 inch)
.sanitize // default: true
.header // optional page header
.footer // optional page footer
.convert
.unwrap;
Headings (<h1> through <h6>) are automatically added as PDF bookmarks/outlines, visible in the sidebar of most PDF readers.
Custom fonts
use HtmlConverter;
let ttf_data = read.unwrap;
let pdf = new
.add_font
.convert
.unwrap;
Page sizes
use PageSize;
A4 // 595.28 x 841.89 pt (default)
LETTER // 612.0 x 792.0 pt
LEGAL // 612.0 x 1008.0 pt
new // custom
Margins
use Margin;
default // 72pt on all sides (1 inch)
uniform // same value on all sides
new // individual values in pt
Markdown to PDF
CommonMark-compliant Markdown parser powered by pulldown-cmark.
let pdf = markdown_to_pdf.unwrap;
Full CommonMark support including headings, emphasis, inline code, fenced code blocks, links, images, lists (nested), blockquotes, horizontal rules, and raw HTML passthrough. GFM extensions are enabled: tables, strikethrough (~~deleted~~), task lists, and footnotes.
Math (LaTeX)
Publication-quality mathematical typesetting with LaTeX syntax, rendered directly to PDF using TeX layout rules.
Inline math with $...$:
The equation $E = mc^2$ is famous.
Display math with $$...$$:
$$\frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$
let pdf = markdown_to_pdf.unwrap;
Also works via HTML with data-math attribute:
x^2
\frac{a}{b}
Supported LaTeX
| Category | Examples |
|---|---|
| Scripts | x^2, a_{ij}, x^{2}_{n} |
| Fractions | \frac{a}{b}, \dfrac{}{} |
| Roots | \sqrt{x}, \sqrt[3]{x} |
| Greek | \alpha ... \omega, \Gamma ... \Omega |
| Operators | \sum, \prod, \int, \oint, \bigcup, \bigcap |
| Functions | \sin, \cos, \log, \lim, \exp, \det, \min, \max |
| Relations | \leq, \geq, \neq, \approx, \equiv, \in, \subset |
| Arrows | \to, \Rightarrow, \Leftrightarrow, \mapsto |
| Delimiters | \left( \right), \left[ \right], \left\{ \right\} |
| Accents | \hat{x}, \bar{x}, \vec{v}, \dot{x}, \tilde{x} |
| Spacing | \,, \;, \quad, \qquad |
| Matrices | \begin{pmatrix}a & b \\\\ c & d\end{pmatrix} |
| Text | \text{...}, \mathrm{...} |
| Misc | \infty, \partial, \nabla, \forall, \exists, \emptyset |
Layout follows TeX conventions: 4 style levels (display, text, script, scriptscript), Knuth's inter-atom spacing matrix, proper fraction bars, and baseline alignment for inline math.
HTML Elements
| Category | Elements |
|---|---|
| Headings | <h1> through <h6> with default sizes and bold |
| Block containers | <p>, <div>, <blockquote>, <pre>, <figure>, <figcaption>, <address> |
| Semantic sections | <section>, <article>, <nav>, <header>, <footer>, <main>, <aside>, <details>, <summary> |
| Inline formatting | <strong>, <b>, <em>, <i>, <u>, <small>, <sub>, <sup>, <code>, <abbr>, <span> |
| Text decoration | <del>, <s> (strikethrough), <ins> (underline), <mark> (highlight) |
| Form controls | <input>, <select>, <textarea> with static visual rendering (borders, value/placeholder text) |
| Media | <video>, <audio> rendered as placeholder rectangles with play icon |
| Gauges | <progress>, <meter> with filled bar (meter supports low/high color thresholds) |
| Links | <a> with clickable PDF link annotations |
| Images | <img> with JPEG and PNG support (data URIs, local files, remote URLs) |
| SVG | Inline <svg> with <rect>, <circle>, <ellipse>, <line>, <polyline>, <polygon>, <path>, <g>, transforms, viewBox |
| Line breaks | <br>, <hr> |
| Lists | <ul>, <ol> with nested support, <li>, <dl>, <dt>, <dd> |
| Tables | <table>, <thead>, <tbody>, <tfoot>, <tr>, <td>, <th>, <caption> with colspan, rowspan, auto-sized columns, and cell borders |
CSS Support
Properties
| Category | Properties |
|---|---|
| Typography | font-size, font-weight, font-style, font-family, letter-spacing, word-spacing, text-indent, text-transform, white-space, vertical-align, text-overflow |
| Colors | color, background-color, opacity |
| Box model | margin (including auto), padding, border, border-top/right/bottom/left, border-width, border-color, border-radius, outline, outline-width, outline-color, box-sizing, width, height, min-width, min-height, max-width, max-height |
| Layout | text-align (left, center, right, justify), line-height, display (none, block, inline, flex, grid), float (left, right), clear, position (static, relative, absolute), z-index |
| Flexbox | flex-direction, justify-content, align-items, flex-wrap, flex-grow, flex-shrink, flex-basis, flex (shorthand), gap |
| Grid | grid-template-columns (fixed, fr, auto, repeat(), minmax(), auto-fill, auto-fit), grid-gap |
| Multi-column | column-count, columns, column-gap |
| Positioning | top, left, z-index |
| Visual effects | box-shadow, transform (rotate, scale, translate), overflow (visible, hidden), visibility |
| Backgrounds | background-color, background-position, background-size, background-repeat, linear-gradient(), radial-gradient() |
| Decoration | text-decoration (underline, line-through) |
| Lists | list-style-type (disc, circle, square, decimal, lower-alpha, upper-alpha, lower-roman, upper-roman, none), list-style-position (inside, outside) |
| Tables | border-collapse, border-spacing |
| Counters | counter-reset, counter-increment, content: counter() |
| Pseudo-elements | ::before, ::after with content property |
| Custom properties | --my-var: value, var(--my-var), var(--my-var, fallback) |
| Functions | calc() (with +, -, *, / and mixed units) |
| Page control | page-break-before, page-break-after, @page (size, margin) |
All shorthand properties are supported. Margin and padding accept 1, 2, 3, or 4 values. Border accepts width style color shorthand.
<style> blocks
Selectors
| Type | Example |
|---|---|
| Tag | p, h1, div |
| Class | .highlight, .intro |
| ID | #title, #nav |
| Combined | p.highlight, div#main |
| Comma-separated | h1, h2, h3 |
| Descendant | div p, article h2 |
| Child | div > p, ul > li |
| Adjacent sibling | h1 + p |
| General sibling | h1 ~ p |
| Attribute | [href], [type="text"] |
| Pseudo-class | :first-child, :last-child, :nth-child(), :not() |
| Pseudo-element | ::before, ::after |
Values
| Type | Examples |
|---|---|
| Colors | red, navy, darkblue, #f00, #ff0000, rgb(255, 0, 0) |
| Units | 12pt, 16px, 1.5em, 50%, 2rem, 10vw, 5vh |
| Functions | calc(100% - 20pt), var(--my-color), var(--size, 12pt) |
| Keywords | bold, italic, center, justify, none, inherit, initial, unset |
Media queries
@media print and @media all rules are applied (since PDF is print output). @media screen rules are ignored. Page-aware conditions are supported:
{ /* matches when page height > width */ }
{ /* matches when page width > height */ }
{ /* matches when page width >= 600pt */ }
{ /* compound queries with and */ }
Supported features: orientation, min-width, max-width, min-height, max-height. Units: pt, px, mm, in.
@page rule
Control page size and margins from CSS:
Supported values: A4, letter, legal, landscape, custom dimensions (210mm 297mm), and individual margins.
Images
JPEG and PNG images are supported via data URIs, local file paths, and remote URLs.
<!-- Data URI -->
<!-- Remote URL (requires "remote" feature) -->
<!-- Local file -->
Images are embedded directly in the PDF. JPEG uses DCTDecode, PNG uses FlateDecode with PNG predictors. Width and height attributes are converted from px to pt.
SVG
Inline SVG elements are rendered as vector graphics directly in the PDF (not rasterized):
Supported elements: <rect>, <circle>, <ellipse>, <line>, <polyline>, <polygon>, <path> (full path command set: M, L, H, V, C, S, Q, T, Z with relative variants), <g> groups with transform (translate, scale, rotate, matrix), and viewBox scaling.
SVG content is automatically sanitized: <script>, <foreignObject>, <use>, <image>, and event handlers are stripped.
Tables
Full table support with sections, spanning, auto-sized columns, and styling.
NameRoleStatus
Alice
Engineer
Active
On project X
Bob
Designer
Active
Column widths are automatically calculated based on content. Features: <thead>, <tbody>, <tfoot> sections, colspan and rowspan attributes, bold headers in <th>, cell borders, background colors, and padding.
Fonts
Standard fonts
ironpress includes the 14 standard PDF fonts (no embedding required). CSS font-family values are mapped to the closest match:
| PDF Font | CSS Values |
|---|---|
| Helvetica | arial, helvetica, sans-serif, verdana, tahoma, roboto, open sans, inter, system-ui, and 20+ more |
| Times-Roman | serif, times new roman, georgia, garamond, palatino, merriweather, lora, and 15+ more |
| Courier | monospace, courier new, consolas, fira code, jetbrains mono, source code pro, menlo, and 15+ more |
Each family includes regular, bold, italic, and bold-italic variants (12 fonts total).
Custom fonts (TrueType)
Embed any TTF font for pixel-perfect rendering:
use HtmlConverter;
let font = read.unwrap;
let pdf = new
.add_font
.convert
.unwrap;
The TTF parser extracts character metrics for accurate text wrapping and embeds the font directly in the PDF.
@font-face
Load fonts from CSS using local files or remote URLs (remote requires the remote feature):
Rendered with MyFont
Local files require .base_path() on the builder so the converter knows where to find font files.
Streaming Output
Write PDF output directly to any std::io::Write implementation instead of allocating a Vec<u8>:
use File;
let mut file = create.unwrap;
html_to_pdf_writer.unwrap;
Also available on the builder:
use HtmlConverter;
use File;
let mut file = create.unwrap;
new
.convert_to_writer
.unwrap;
Async API
Enable the async feature for async file I/O:
= { = "1.1", = ["async"] }
convert_file_async.await.unwrap;
convert_markdown_file_async.await.unwrap;
The HTML parsing, layout, and rendering remain synchronous (CPU-bound). Async is used for file reads and writes via tokio.
Remote Resources
Enable the remote feature to load images and fonts from HTTP/HTTPS URLs:
= { = "1.1", = ["remote"] }
Remote resources are capped at 10 MB each. Without the remote feature, remote URLs are silently ignored (no network requests are made).
Security
HTML is sanitized by default before conversion:
<script>,<iframe>,<object>,<embed>,<form>tags are stripped<style>tags are preserved but dangerous CSS (externalurl(),expression()) is removed@importand@font-faceload local files only by default (paths sandboxed inbase_dir); remote URLs require theremotefeature- Event handlers (
onclick,onload, etc.) are removed javascript:URLs are neutralized- Input size (10 MB) and nesting depth (100 levels) are limited
- SVG sanitizer strips
<script>,<foreignObject>,<use>,<image>,<style>, and event handlers inside<svg>blocks - PNG IDAT accumulation capped at 50 MB to prevent decompression bombs
- CSS
@importcumulative payload capped at 10 MB - TTF parser validates font metrics and uses checked arithmetic
Sanitization can be disabled with .sanitize(false) if you trust the input.
How It Works
graph LR
A[HTML / Markdown] --> B[Sanitize]
B --> C[Parse<br/>html5ever]
C --> D[Extract<br/>‹style›]
D --> E[Style<br/>Cascade]
E --> F[Layout<br/>Engine]
F --> G[PDF 1.4]
style A fill:#3498db,color:#fff,stroke:none
style G fill:#27ae60,color:#fff,stroke:none
- Sanitize: strip dangerous elements (
<script>,<iframe>, event handlers,javascript:URLs) - Parse: build a DOM tree using html5ever, extract
<style>blocks and@page/@font-facerules - Style cascade: resolve tag defaults,
@mediarules, stylesheet rules, inline CSS, withinherit/initial/unsetand CSS variable support - Layout: text wrapping with Adobe font metrics, flexbox, CSS grid, multi-column, tables with colspan/rowspan, margin collapsing, floats, page breaks, images, SVG, and the full CSS box model
- Render: PDF 1.4 output with bookmarks, headers/footers, shading dictionaries for gradients, per-side borders, border-radius, link annotations, embedded images, and TrueType font embedding
For Markdown input, a built-in parser converts Markdown to HTML first (no external dependencies).
WASM
ironpress compiles to WebAssembly for browser-side PDF generation with no system dependencies.
Install via npm
Build from source
Usage in JavaScript
import init from 'ironpress';
await ;
// HTML to PDF
const pdfBytes = ;
const blob = ;
// Markdown to PDF
const mdPdf = ;
// Custom page size and margins (in points, 72pt = 1 inch)
const customPdf = ;
Three functions are exported: htmlToPdf(html), markdownToPdf(md), and htmlToPdfCustom(html, pageWidth, pageHeight, marginTop, marginRight, marginBottom, marginLeft). All return a Uint8Array with the PDF bytes.
Testing
ironpress uses three layers of testing:
- Unit tests: 1690+ tests covering parsing, style computation, layout, rendering, and CLI
- Property-based tests: proptest verifies invariants across thousands of random inputs (no panics on arbitrary HTML/CSS/Markdown, valid PDF output, correct page structure)
- Fuzz targets: 6 cargo-fuzz targets — HTML parser, CSS parser, Markdown parser, full pipeline, SVG, and table/flex layout (
cargo +nightly fuzz run fuzz_html). All targets run in CI on every push.
License
MIT