ferri-pdf 0.3.0

HTML and CSS to PDF renderer for print, in pure Rust
Documentation

Ferri PDF

An HTML and CSS to PDF renderer for print, written in pure Rust. It needs no browser and runs no JavaScript.

It supports paged media, page-margin boxes, named pages, fragmentation, floats, flex, grid, tables, multi-column, text shaping, bidi, SVG and raster images (PNG, JPEG, GIF, WebP, AVIF, HEIC).

Command line

cargo install ferri-pdf
ferri-pdf input.html output.pdf

Use - for stdin or stdout.

Option Effect
--data DATA.json Render the input and every part as a Jinja template with this JSON object
--part INPUT.html Append another document to the same PDF (repeatable)
--headings HEADINGS.json Write heading page numbers as JSON
--file-root DIR Read local files inside this folder instead of the input's
--image-dpi DPI Downsample raster images to this resolution
--jpeg-quality 1..100 Re-encode opaque photos as JPEG at this quality
--font-serif, --font-sans-serif, --font-monospace FAMILY Choose the family for a generic font
--font-fallback FAMILY Family used for missing glyphs
--system-fonts Allow fonts installed on the system
--font-dir DIR Also use the fonts in this folder (repeatable)
--trace Write the measured layout next to the PDF
--allow-content-loss Write the PDF even when a resource limit left content out

Local files are read only inside the input's folder, or the current directory for stdin. Content fetched over HTTP(S), templates included, never reads a local file.

Invalid markup, unsupported CSS and missing resources print warnings instead of failing the render. If a resource limit leaves content out, the render fails unless --allow-content-loss is given.

Library

[dependencies]
ferri-pdf = "0.3"
use ferri_pdf::{render_html, RenderOptions};

let options = RenderOptions {
    base: std::path::Path::new("assets").into(),
    ..Default::default()
};
let output = render_html("<h1>Hello</h1>", &options)?;
std::fs::write("hello.pdf", output.pdf)?;

Relative URLs resolve against base, and local files are read only inside its folder, or inside file_root when set, and never by content fetched over HTTP(S). HTTP(S) fetching is behind the default http feature. Pass your own resolver to render_with_resolver to control loading.

Only @font-face fonts and the bundled Liberation and DejaVu fonts are used, unless options.print.fonts.system_fonts is set or font_dirs lists folders.

Recovered problems are listed in output.diagnostics. If a resource limit leaves content out, rendering returns Error::ContentLost; set content_loss: ContentLoss::Render to get the PDF anyway.

Templates

render_template expands a Jinja template with any Serialize data and renders the result:

use ferri_pdf::{render_template, RenderOptions};

#[derive(serde::Serialize)]
struct Quote<'a> {
    customer: &'a str,
}

let options = RenderOptions {
    base: std::path::Path::new("templates").into(),
    ..Default::default()
};
let output = render_template(
    "{% extends 'layout.html' %}{% block body %}<h1>Quote for {{ customer }}</h1>{% endblock %}",
    &Quote { customer: "Ada" },
    &options,
)?;

Values are HTML-escaped unless marked |safe. Names in include, extends and import resolve against base, not the including template, and load under the same file rules as other resources. Template errors return Error::Template; use ignore missing for optional includes. HtmlPart::from_template adds a template to a multipart render.

Python

pip install ferri-pdf
import ferri_pdf

output = ferri_pdf.render("<h1>Hello</h1>", ferri_pdf.RenderOptions(base="assets"))
open("hello.pdf", "wb").write(output.pdf)

# With data, the input is a Jinja template.
output = ferri_pdf.render("<h1>Hello {{ name }}</h1>", data={"name": "Ada"})

See python/README.md for options, multipart rendering and the fetch callback.

JavaScript

Runs as WebAssembly in browsers and Node 18 or later.

npm install ferri-pdf
import { render } from 'ferri-pdf';

// In a browser, relative URLs resolve against the page and load through fetch.
const output = await render('<h1>Hello</h1><img src="/logo.png">');
const url = URL.createObjectURL(new Blob([output.pdf], { type: 'application/pdf' }));
// In Node, local files are read only inside base.
const output = await render(html, { base: 'templates/invoice' });
await writeFile('invoice.pdf', output.pdf);

// With data, the input is a Jinja template.
const quote = await render('<h1>Quote for {{ customer }}</h1>', { data: { customer: 'Ada' } });

In a browser, resources from another origin need CORS headers or a proxy passed as the fetch option. See wasm/README.md for options, workers and multipart rendering.

Development

Requires Rust 1.97 or newer.

cargo test --workspace
cargo fmt --check
cargo clippy --workspace --all-targets -- -D warnings
  • Python bindings: pip install maturin pytest && maturin develop && pytest python/tests
  • JavaScript package: rustup target add wasm32-unknown-unknown && cargo install wasm-bindgen-cli --version 0.2.129, then npm run build && npm test in wasm/
  • The PDF checks in tests/*.py and the standards oracle also need Python with Pillow and fontTools, Poppler and GNU FriBidi; see tests/oracle/README.md

Licence

MIT. Forked dependencies in vendor/, the SVG libraries inlined under src/svg/, the bundled fonts in assets/fonts/ and the specification data in spec/ keep their original licences; see vendor/FORKS.md.