ferri-pdf 0.2.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. No browser and no JavaScript.

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

## Command line

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

Use `-` for stdin or stdout. Options:

| Option | Effect |
|---|---|
| `--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` | Let documents and the font options use the fonts installed on the system |
| `--font-dir DIR` | Also use the fonts in this folder and its subfolders (repeatable) |
| `--part INPUT.html` | Append another document to the same PDF (repeatable) |
| `--headings HEADINGS.json` | Write heading page numbers as JSON |
| `--trace` | Write the measured layout next to the PDF |
| `--allow-content-loss` | Write the PDF even when a resource limit left content out |
| `--file-root DIR` | Read local files inside this folder instead of the input's |

A document reads local files only inside the folder of its input file, or the current directory when the input is stdin. `--file-root DIR` names another folder, for example a shared assets folder above the input. Content fetched over HTTP(S) never reads a local file.

Invalid markup, unsupported CSS and missing resources never fail a render; they are recovered as the specifications say and printed as warnings. Input that exceeds a resource limit so that content is left out fails with the losses listed, unless `--allow-content-loss` is given.

## Library

```toml
[dependencies]
ferri-pdf = "0.2"
```

```rust
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`. HTTP(S) fetching is behind the default `http` feature. To control resource loading, pass your own resolver to `render_with_resolver`.

Local files are read only inside the folder `base` names: the directory itself, or the one holding a `file:` document. Without a `base` no local file is read, and neither a document with an `http(s)` base nor a stylesheet fetched from one ever reads a local file. Set `file_root` to read inside another folder instead, for example a shared assets folder above the base:

```rust
let options = RenderOptions {
    base: std::path::Path::new("templates/invoice").into(),
    file_root: Some("templates".into()),
    ..Default::default()
};
```

Besides `@font-face` web fonts, only the bundled Liberation and DejaVu fonts are used unless `options.print.fonts.system_fonts` is set or `font_dirs` lists folders; then `font-family`, `local()` and the generic and fallback preferences can also name the fonts installed there. Installed fonts are read only from the system font folders and the folders you give, never from a path the document chooses.

Recovered input is reported in `output.diagnostics`. When a resource limit leaves content out, rendering returns `Error::ContentLost` with those diagnostics; set `content_loss: ContentLoss::Render` to get the PDF anyway.

## Python

```sh
pip install ferri-pdf
```

```python
import ferri_pdf

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

Local files are read only inside `base`; without it none is read. Pass `file_root` to read inside another folder, such as `RenderOptions(base="templates/invoice", file_root="templates")`.

The bindings live in `python/`; see [python/README.md](python/README.md) for options, multipart rendering and the `fetch` callback for loading remote resources yourself.

## JavaScript

The renderer also runs as WebAssembly, in browsers and in Node 18 or later.

```sh
npm install ferri-pdf
```

```js
import { render } from 'ferri-pdf';

// In a browser: relative URLs resolve against the page and resources 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' }));
```

```js
// In Node, with import or require: local files are read only inside the base directory.
const output = await render(html, { base: 'templates/invoice' });
await writeFile('invoice.pdf', output.pdf);
```

Without a `base` Node reads no local file. Pass `fileRoot` to read inside another folder, such as `{ base: 'templates/invoice', fileRoot: 'templates' }`.

In a browser, resources from another origin need CORS headers that allow the page to read them, or a proxy on your own origin passed as the `fetch` option. A resource that cannot be fetched never fails the render; it is reported in `output.diagnostics`.

The bindings live in `wasm/`; see [wasm/README.md](wasm/README.md) for options, the `fetch` function, rendering in a worker and multipart rendering.

## Development

Requires Rust 1.97 or newer.

```sh
cargo test --workspace
cargo fmt --check
cargo clippy --workspace --all-targets -- -D warnings
```

To build and test the Python bindings: `pip install maturin pytest && maturin develop && pytest python/tests`.

To build and test the 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 in `tests/oracle` also need Python with Pillow and fontTools, Poppler and GNU FriBidi. See [tests/oracle/README.md](tests/oracle/README.md).

## Licence

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