# Fagus documentation Fagus turns HTML and CSS into PDF for PHP and Laravel, the way Chrome prints them, without a browser. Start with [Getting started](getting-started.md); the other pages are references to look things up in. ## Using Fagus - [Getting started](getting-started.md): requirements, installing the Composer package, the first PDF in PHP and in Laravel. - [PHP API](php.md): documents, the PDF they render to, the engine, diagnostics and exceptions. - [Laravel](laravel.md): the facade, Blade views, responses, disks, queues, Octane and the configuration. - [Resources](resources.md): where images, style sheets, fonts and frames come from, and what Fagus never loads. - [Deployment](deployment.md): Docker, Alpine, servers without access to GitHub, binaries of your own, worker processes, speed and memory. - [Troubleshooting](troubleshooting.md): error messages, diagnostics, differences from Chrome, and moving from Dompdf, mPDF, Browsershot or Snappy. ## Writing documents - [CSS reference](css.md): what Fagus supports, what it does differently from Chrome and what it does not support. - [Paged media](paged-media.md): page sizes and margins, headers and footers, page numbers, page breaks, tables across pages, tables of contents, print shop marks. - [Fonts](fonts.md): the built-in font, font directories, `@font-face`, system fonts, fallback, OpenType features and languages. - [Extensions](extensions.md): what Fagus adds where CSS has no way, such as carry-over rows in tables that break across pages. ## The PDF - [The PDF](pdf.md): metadata, links and the outline, tagged and accessible PDF (PDF/UA), PDF/A, attachments, electronic invoices (ZUGFeRD, Factur-X, XRechnung), reproducible output. ## Without PHP - [Command line](cli.md): the `fagus` binary. - [Rust library](rust.md): the engine as a Rust crate. - [Worker protocol](protocol.md): how PHP talks to the binary. ## The project - [Releasing](releasing.md): how a release reaches GitHub and Composer. - [Architecture decision records](adr/): why Fagus is built the way it is. # Getting started Fagus turns HTML and CSS into PDF the way Chrome prints them. It is one Composer package, `nforst/fagus`, with a native engine that Composer downloads for your platform. There is no browser, Node or Docker image to install. ## Requirements - PHP 8.3 or newer, with `proc_open()` allowed (it is unless `disable_functions` lists it). - One of these platforms: | System | Architectures | |---|---| | Linux with glibc (2.17 or newer) | x64, arm64 | | Linux with musl (Alpine) | x64, arm64 | | macOS | x64 (Intel), arm64 (Apple silicon) | | Windows | x64 | - For the Laravel integration: Laravel 13. Older versions of Laravel conflict with the package. Every platform prints the same PDF from the same input. ## Install the package ```sh composer require nforst/fagus ``` The package contains a Composer plugin. Composer asks once whether you trust it: ```text Do you trust "nforst/fagus" to execute code and wish to enable it now? (writes "allow-plugins" to composer.json) [y,n,d,?] ``` Answer `y`. Composer then writes this to your `composer.json`, which you commit: ```json "config": { "allow-plugins": { "nforst/fagus": true } } ``` After every `composer install` and `composer update`, the plugin installs the `fagus` binary of the package's release for the platform Composer runs on: 1. It works out the target, such as `x86_64-unknown-linux-gnu`, `aarch64-unknown-linux-musl` or `aarch64-apple-darwin`. 2. It downloads `fagus-` from the GitHub release of the package's version, or takes it from Composer's cache if it was downloaded before. 3. It checks the file's SHA-256 against the sum the package lists for that release (`php/fagus/src/Internal/Release.php`). A file with another sum is not installed. 4. It writes the binary into the package (`vendor/nforst/fagus/php/fagus/bin/fagus`), where the engine looks for it. If the binary cannot be installed, Composer does not fail: it prints a warning that starts with `fagus:` and goes on. Run `vendor/bin/fagus-install` (in Laravel: `php artisan fagus:install`) to try again; [troubleshooting.md](troubleshooting.md) lists the messages. Servers without access to GitHub, Docker builds and binaries of your own are covered in [deployment.md](deployment.md). ## Your first PDF in PHP ```php Invoice 2026-0042

Invoice 2026-0042

ItemAmount
Consulting1,200.00 EUR
HTML; $pdf = Fagus::html($html)->save('invoice.pdf'); echo $pdf->pages(); // 1 print_r($pdf->diagnostics()); // CSS that was ignored, resources that are missing ``` The document describes itself, as in a browser: the page size and margins come from `@page`, the PDF's title from `` and its language from `<html lang>`. Without an `@page` rule, pages are A4 (Chrome uses the paper size of its printer settings, often Letter). The first document starts the engine's worker process, which takes a few milliseconds; the following documents of the same PHP process render on the running worker. ### Images, stylesheets and fonts from files Fagus reads no files unless you name a directory. Relative URLs resolve against the base directory, and only files inside it are read: ```php $pdf = Fagus::html($html) ->baseDirectory(__DIR__.'/resources/pdf') // <img src="logo.png">, <link href="invoice.css"> ->render(); ``` URLs with `http:` or `https:` are never fetched. [resources.md](resources.md) describes where resources come from and how to hand them over. ## Your first PDF in Laravel Laravel 13 discovers the package on its own: the `Fagus` facade, Blade views, responses and filesystem disks work after `composer require`. Write the document as a Blade view, for example `resources/views/invoices/show.blade.php`: ```blade <!doctype html> <html lang="en"> <head> <title>Invoice {{ $invoice->number }} ACME

Invoice {{ $invoice->number }}

``` and return it from a controller: ```php use App\Models\Invoice; use Fagus\Laravel\Facades\Fagus; class InvoicePdfController { public function __invoke(Invoice $invoice) { return Fagus::view('invoices.show', ['invoice' => $invoice]) ->name("invoice-{$invoice->number}.pdf"); // shown in the browser } } ``` The browser shows the PDF. `->download()` sends it as a download, and `->store()` writes it to a filesystem disk: ```php Fagus::view('invoices.show', ['invoice' => $invoice])->download('invoice.pdf'); Fagus::view('invoices.show', ['invoice' => $invoice])->store('invoices/2026-0042.pdf', 's3'); ``` In Laravel, relative URLs resolve against `public/`, so `/images/logo.png` is `public/images/logo.png`. Publish the configuration to change this and the fonts: ```sh php artisan vendor:publish --tag=fagus-config ``` Use the facade `Fagus\Laravel\Facades\Fagus` in Laravel, not the class `Fagus\Fagus`: the facade renders with the engine and the settings of `config/fagus.php`. ## Where to go next - [php.md](php.md): every method of the PHP API. - [laravel.md](laravel.md): views, responses, disks, queues, Octane and the configuration. - [resources.md](resources.md): images, stylesheets, fonts and frames, and what Fagus never reads. - [paged-media.md](paged-media.md): page sizes, margins, headers, footers and page numbers. - [css.md](css.md): the CSS that Fagus renders. - [fonts.md](fonts.md): web fonts, font directories and system fonts. - [pdf.md](pdf.md): PDF/A, PDF/UA, attachments and ZUGFeRD/Factur-X invoices. - [deployment.md](deployment.md): Docker, Alpine, servers without GitHub access and worker processes. - [troubleshooting.md](troubleshooting.md): error messages, diagnostics and differences from Chrome. # PHP API The PHP API lives in the namespace `Fagus\` (`php/fagus/src`). It has four parts: - `Fagus`: static entry points and the shared engine. - `Document`: a document to render, built step by step. - `Pdf`: the rendered PDF with its page count, diagnostics and timings. - `Engine`: the `fagus` binary, running as a worker process. In Laravel, use the facade described in [laravel.md](laravel.md); it offers the same document methods and renders with the engine of `config/fagus.php`. ```php use Fagus\Conformance; use Fagus\Fagus; use Fagus\Relationship; $pdf = Fagus::html($html) ->baseDirectory(__DIR__.'/resources/pdf') // relative URLs and the files they may read ->root(__DIR__.'/resources') // a larger directory files may come from (../fonts/…) ->stylesheet($css) // after the document's own styles ->resource('logo.png', $logo) // data the document refers to ->resolver(fn (string $url): ?string => $cache->get($url)) ->pdfA(Conformance::PdfA3b) ->attach('data.csv', $csv, 'text/csv', Relationship::Supplement, 'Raw data') ->facturX($invoiceXml) // ZUGFeRD / Factur-X; the profile comes from the XML ->created(new DateTimeImmutable('2026-11-02 12:00')) // a fixed date makes the PDF reproducible ->strict() // diagnostics become exceptions ->render(); $pdf->bytes(); $pdf->pages(); $pdf->diagnostics(); // CSS that was ignored, resources that are missing, with their position $pdf->timings(); // milliseconds per phase: parse, style, layout, paint, pdf $pdf->save('invoice.pdf'); ``` ## `Fagus` `Fagus\Fagus` is a final class with static methods only. ### `Fagus::html(string $html): Document` Starts a document from HTML, parsed as browsers parse HTML. Same as `Document::html()`. ```php Fagus::html('

Invoice

')->save('invoice.pdf'); ``` ### `Fagus::xhtml(string $xml): Document` Starts a document from XHTML, parsed as XML as browsers parse `.xhtml` files: CDATA sections and empty-element tags (`
`) work, names are case-sensitive and nothing is implied (no `` added, no tags closed for you). Same as `Document::xhtml()`. ```php Fagus::xhtml('

Invoice

') ->save('invoice.pdf'); ``` ### `Fagus::engine(): Engine` The engine that documents render with unless one is passed to `render()` or `save()`: the one set with `useEngine()`, else one created on first use with the default settings (the binary from `FAGUS_BINARY`, the installed one or the `PATH`, no font directories, no system fonts). ```php Fagus::engine()->version(); // "0.1.0" ``` ### `Fagus::useEngine(?Engine $engine): void` Sets the shared engine, for example to configure fonts once at bootstrap. `null` drops it; the next call to `engine()` creates a new default engine. ```php use Fagus\Engine; use Fagus\Fagus; Fagus::useEngine(new Engine( fontDirectories: [__DIR__.'/resources/fonts'], locale: 'de-DE', )); ``` ## `Document` `Fagus\Document` is immutable: every method returns a changed copy and the document itself never changes. You can build a base document once and derive variants from it. ```php $base = Fagus::html($html)->baseDirectory(__DIR__.'/resources/pdf'); $base->save('invoice.pdf'); $base->pdfA('3b')->save('invoice-archive.pdf'); ``` ### `Document::html(string $html): Document` A document from HTML. The constructor is private; use this or `Fagus::html()`. ### `Document::xhtml(string $xml): Document` A document from XHTML, parsed as XML (see `Fagus::xhtml()`). ### `baseDirectory(string $directory): Document` The directory that relative URLs (stylesheets, images, fonts, frames) resolve against. Only files inside it are read, unless `root()` allows a larger directory. Without a base directory, Fagus reads no files at all. See [resources.md](resources.md). ```php Fagus::html('ACME') ->baseDirectory(__DIR__.'/resources/pdf'); // reads resources/pdf/images/logo.png ``` ### `root(string $directory): Document` The directory that files may be read from. It must contain the base directory. Use it when the document's URLs lead out of the base directory (`../fonts/Inter.woff2`). URLs that start with `/` resolve against the root, as on a web server. Without `root()`, the root is the base directory. ```php Fagus::html($html) ->baseDirectory(__DIR__.'/resources/pdf/invoices') ->root(__DIR__.'/resources/pdf'); // allows ../fonts/… and /images/logo.png ``` ### `stylesheet(string $css, string $name = 'stylesheet'): Document` Adds a stylesheet after the document's own stylesheets, so its rules win over the document's rules of the same specificity. It can be called several times; the stylesheets apply in that order. `$name` is the source that diagnostics name for it. ```php Fagus::html($html)->stylesheet(file_get_contents(__DIR__.'/pdf.css'), 'pdf.css'); ``` Relative URLs in it resolve against the base directory. ### `resource(string $url, string $data): Document` Hands over the data of a resource that the document refers to, by its URL exactly as written in the document. Use it for data that is not in a file, such as a logo from a database or a chart generated in PHP. A later call with the same URL replaces the data. ```php Fagus::html('ACMERevenue') ->resource('logo.png', $tenant->logo) ->resource('chart.svg', $chartSvg); ``` URLs in stylesheets are resolved against the stylesheet first: `url(img/bg.png)` in `css/main.css` asks for `css/img/bg.png`. See [resources.md](resources.md). ### `resolver(callable $resolver): Document` Sets a callback that answers requests for resources that are not handed over with `resource()`. It gets the URL (resolved as described for `resource()`) and returns the data, or `null` when it does not have it. Fagus asks the callback before it looks for a file inside the root; after `null`, it tries the file. The engine waits while the callback runs. ```php Fagus::html($html)->resolver(function (string $url): ?string { if (str_starts_with($url, 'media://')) { return Storage::get('media/'.substr($url, 8)); } return null; }); ``` Fagus itself never goes to the network. A resolver may, under your own rules. Only one resolver is kept; a second call replaces the first. ### `pdfA(Conformance|string $level = Conformance::PdfA3b): Document` Writes the PDF as PDF/A. `$level` is a `Conformance` case or its value: `'2b'`, `'2u'`, `'2a'`, `'3b'`, `'3u'` or `'3a'` (case-insensitive). Any other string throws a `Fagus\Exception\InvalidArgumentException` that lists the levels ("Unknown PDF/A level '4z'. The levels are '2b', '2u', '2a', '3b', '3u', '3a'."). The levels ending in `a` are tagged for accessibility. See [pdf.md](pdf.md). ```php Fagus::html($html)->pdfA(); // PDF/A-3b Fagus::html($html)->pdfA('2u'); ``` ### `tagged(bool $tagged = true): Document` Whether the PDF is tagged with the logical structure of the document (headings, paragraphs, lists, tables, images and links in reading order), which screen readers read. Tagging is on by default. Without it, a PDF with many table cells is somewhat smaller and faster to write. `accessible()` and the PDF/A levels ending in `a` tag the PDF whatever `tagged()` says. ```php Fagus::html($html)->tagged(false); ``` ### `accessible(bool $accessible = true): Document` Writes the PDF as PDF/UA-1, the standard for accessible PDF. The document needs a ``, a language (`<html lang>`), alternative text for every image (`alt`, empty for decoration) and headings that start at `<h1>` and skip no level. Without them, `render()` throws a `RenderException` that lists what is missing: ```text the document does not meet PDF/UA-1: the document has no title (add a <title>); the image `logo.png` in line 12 has no alternative text (add `alt`, empty if it is decoration) ``` `accessible()` also works together with PDF/A-2a, PDF/A-3a and Factur-X. See [pdf.md](pdf.md). ### `attach(string $name, string $data, string $mime = 'application/octet-stream', Relationship $relationship = Relationship::Unspecified, ?string $description = null): Document` Attaches a file to the PDF. `$relationship` says how the file relates to the document (PDF 2.0 `AFRelationship`, see `Relationship` below). PDF/A-3 and PDF/UA require a description of every attached file; without `$description`, the file name describes it. Call it once per file. ```php use Fagus\Relationship; Fagus::html($html) ->pdfA('3b') ->attach('timesheet.csv', $csv, 'text/csv', Relationship::Supplement, 'Hours worked'); ``` PDF/A-2 allows only PDF/A files as attachments: with `pdfA('2b')` and a CSV attachment, `render()` throws a `RenderException` ("the document does not meet PDF/A-2b: PDF/A-2 allows only PDF/A files as attachments; attach `timesheet.csv` to a PDF/A-3 document instead"). Use PDF/A-3 for other files. ### `facturX(string $xml, ?InvoiceProfile $profile = null): Document` Makes the PDF an electronic invoice of ZUGFeRD or Factur-X: the XML is attached under the name its profile requires (`factur-x.xml`, or `xrechnung.xml` for XRechnung), described in the XMP metadata, and the PDF conforms to PDF/A-3 (PDF/A-3b unless another PDF/A-3 level is chosen). The profile is the one the XML declares in its guideline parameter (EN 16931 if it declares none), unless `$profile` is given. ```php use Fagus\InvoiceProfile; Fagus::html($html)->facturX($xml); // profile from the XML Fagus::html($html)->facturX($xml, InvoiceProfile::XRechnung); // profile given ``` Diagnostics report a profile that differs from the XML's (`invoice.profile-mismatch`), an XML without a profile (`invoice.profile-unknown`) and a PDF/A-2 level raised to PDF/A-3 (`pdf.conformance-raised`). See [pdf.md](pdf.md). ### `created(DateTimeInterface $date): Document` The creation date written into the PDF; the current time by default. Fagus converts it to UTC. A fixed date makes the output reproducible: the same document, fonts and binary give the same bytes. ```php Fagus::html($html)->created(new DateTimeImmutable('2026-11-02 12:00', new DateTimeZone('Europe/Berlin'))); ``` ### `strict(bool $strict = true): Document` Fails with a `RenderException` when the PDF has diagnostics (CSS that is ignored, resources that are missing), instead of returning it. Useful in tests and CI. ```php Fagus::html($html)->strict()->render(); ``` ```text 2 diagnostics in strict mode: <style> 1:3:5: warning[css.unknown-property]: unknown property `colr`; the declaration is ignored resources: warning[resource.not-loaded]: image `logo.png` could not be loaded ``` ### `render(?Engine $engine = null): Pdf` Renders the document with `$engine`, or with `Fagus::engine()`. Throws a `RenderException` when the document cannot be rendered (or has diagnostics in strict mode) and an `EngineException` when the engine cannot be started or stops. ```php $pdf = Fagus::html($html)->render(); $pdf = Fagus::html($html)->render($myEngine); ``` ### `save(string $path, ?Engine $engine = null): Pdf` Renders the document and writes the PDF to `$path`. Returns the `Pdf`, so you can still read its page count and diagnostics. ```php $pdf = Fagus::html($html)->save(storage_path('invoices/2026-0042.pdf')); ``` ### What comes from the document There are no methods for page size, margins, headers, footers or metadata. As in a browser, they come from the document: | PDF | From | |---|---| | Page size and margins | `@page { size: A4; margin: 20mm }` ([paged-media.md](paged-media.md)) | | Headers, footers, page numbers | `@page` margin boxes | | Title | `<title>` | | Language | `<html lang>`, else the engine's `locale` | | Author | `<meta name="author" content="…">` | | Subject | `<meta name="description" content="…">` | | Keywords | `<meta name="keywords" content="…">`, separated by commas | | Outline (bookmarks) | the headings (`bookmark-level`, `bookmark-label`, `bookmark-state`) | ## `Pdf` `Fagus\Pdf` is a final readonly class: a rendered PDF with what Fagus noticed while rendering it. | Method | Returns | |---|---| | `bytes(): string` | The PDF file. | | `pages(): int` | The number of pages. | | `diagnostics(): list<Diagnostic>` | CSS that was ignored, resources that could not be loaded, and other notes, in the order they were found. Empty for a clean document. | | `timings(): array<string, float>` | Milliseconds per phase, with the keys `parse`, `style`, `layout`, `paint` and `pdf`. | | `save(string $path): void` | Writes the PDF to `$path`. Throws a `FagusException` ("The PDF could not be written to `…`.") if it cannot. | ```php $pdf = Fagus::html($html)->render(); file_put_contents('invoice.pdf', $pdf->bytes()); echo array_sum($pdf->timings()), " ms\n"; foreach ($pdf->diagnostics() as $diagnostic) { error_log((string) $diagnostic); } ``` The constructor is public, `new Pdf(string $bytes, int $pages, array $diagnostics = [], array $timings = [])`, so tests can make a `Pdf` without rendering. ## `Engine` `Fagus\Engine` is the `fagus` binary, running as a worker process. Configure one when the defaults do not fit and make it the shared engine with `Fagus::useEngine()`, or pass it to `render()`. ```php use Fagus\Engine; use Fagus\Fagus; Fagus::useEngine(new Engine( binary: '/usr/local/bin/fagus', // FAGUS_BINARY, the installed binary or the PATH if null fontDirectories: [__DIR__.'/resources/fonts'], sansSerif: 'Inter', // the families of sans-serif, serif and monospace serif: 'Source Serif 4', monospace: 'JetBrains Mono', timeout: 60.0, // seconds to wait for each answer of the worker systemFonts: false, locale: 'de-DE', )); ``` ### Constructor All arguments are optional and named as below. | Argument | Type, default | Meaning | |---|---|---| | `binary` | `?string`, `null` | The path of the `fagus` binary. If `null`: `FAGUS_BINARY`, else the binary the plugin installed into the package, else `fagus` (`fagus.exe` on Windows) on the `PATH`. A binary that is given here or in `FAGUS_BINARY` must exist and be executable. | | `fontDirectories` | `list<string>`, `[]` | Directories with fonts for every document: TTF, OTF, TTC, OTC, WOFF and WOFF2 files, in the directory and its subdirectories. Each directory must exist: before it starts the worker, the engine throws an `EngineException` that names a missing one ("The font directory `…` does not exist."). | | `sansSerif` | `?string`, `null` | The family that `sans-serif` names. | | `serif` | `?string`, `null` | The family that `serif` names. | | `monospace` | `?string`, `null` | The family that `monospace` names. | | `timeout` | `float`, `60.0` | Seconds to wait for each answer of the worker. A worker that does not answer in time is stopped and an `EngineException` is thrown. Not on Windows, where PHP cannot wait for a pipe with a time limit. | | `systemFonts` | `bool`, `false` | Whether the fonts installed on the machine serve too, as in Chrome. The output then depends on the machine. | | `locale` | `?string`, `null` | The language of the texts that form controls show of their own (button labels, date formats) and of the PDF where a document has no `lang`, such as `'de-DE'`. American English if `null`. | Form controls write their texts (the labels of submit and reset buttons, "Choose File", the placeholders and formats of date and time fields, the decimal separator of number fields) as Chrome does, but in the language of the control: its `lang` (inherited, as from `<html lang="de">`), else `locale`, else American English. Chrome itself takes the language of its user interface. Fagus has Chrome's texts for English (`en-US`, `en-GB`), German, French, Spanish, Italian, Dutch, Portuguese (`pt-BR`, `pt-PT`) and Polish. Text without `lang` is shaped in the `locale` language too. Fonts, generic families and system fonts are described in [fonts.md](fonts.md). The constructor does not start the worker. The worker starts with the first call that needs it (`render()`, `addFont()`, `version()`). ### `render(Document $document): Pdf` Renders a document. `$document->render($engine)` calls this. ### `addFont(string $data): int` Adds a font (TTF, OTF, TTC, OTC, WOFF or WOFF2 data) for all later documents of this engine and returns the number of faces in it. The engine keeps the data and hands it to every new worker it starts. Data that is not a font throws an `EngineException` ("the data is not a supported font"). ```php Fagus::engine()->addFont(file_get_contents(__DIR__.'/resources/fonts/CorporateSans.otf')); ``` ### `version(): string` The version of the running binary, such as `0.1.0`. Starts the worker if it is not running. ### `close(): void` Stops the worker process. It ends when its input closes; one that has not ended after two seconds is terminated. The next document starts a new worker, which gets the fonts of `addFont()` again. The destructor calls `close()`. ### `Engine::PROTOCOL` The version of the worker protocol this package speaks: `1`. A binary that speaks another protocol is refused ([protocol.md](protocol.md)). ### The worker's lifetime The worker process starts with the first document and keeps running, with its fonts and caches warm, until the engine is closed or destroyed: - Under PHP-FPM, the shared engine lives as long as the request, so the worker serves the documents of one request. - In queue workers, under Octane or FrankenPHP's worker mode and in long-running scripts, it serves every document of the process. When a render fails with an `EngineException` (a timeout, a worker that exited), the worker is stopped and the next document starts a new one. A `RenderException` leaves the worker running. More in [deployment.md](deployment.md#worker-processes). ## `Diagnostic` and `Severity` `Fagus\Diagnostic` is a final readonly class with public properties: | Property | Type | Meaning | |---|---|---| | `severity` | `Severity` | `Severity::Info`, `Severity::Warning` or `Severity::Error`. | | `code` | `string` | A stable code, such as `css.unknown-property` or `resource.not-loaded`. | | `message` | `string` | What happened, in English. | | `source` | `string` | Where: `<style> 1` (the first `<style>` element), the URL of a linked stylesheet, the name given to `stylesheet()`, `html`, `resources` or `pdf`. | | `line` | `int` | 1-based line in the source, 0 if unknown. | | `column` | `int` | 1-based column, 0 if unknown. | Cast it to a string for one line in the format `source:line:column: severity[code]: message`: ```php foreach ($pdf->diagnostics() as $diagnostic) { if ($diagnostic->code === 'resource.not-loaded') { $logger->warning((string) $diagnostic); } } // resources: warning[resource.not-loaded]: image `logo.png` could not be loaded ``` `Fagus\Severity` is a string-backed enum: `Info = 'info'`, `Warning = 'warning'`, `Error = 'error'`. The codes are listed in [troubleshooting.md](troubleshooting.md#read-diagnostics). ## `Conformance` `Fagus\Conformance` is a string-backed enum of PDF/A levels, for `pdfA()`: | Case | Value | Level | |---|---|---| | `Conformance::PdfA2b` | `'2b'` | PDF/A-2b | | `Conformance::PdfA2u` | `'2u'` | PDF/A-2u | | `Conformance::PdfA2a` | `'2a'` | PDF/A-2a | | `Conformance::PdfA3b` | `'3b'` | PDF/A-3b | | `Conformance::PdfA3u` | `'3u'` | PDF/A-3u | | `Conformance::PdfA3a` | `'3a'` | PDF/A-3a | PDF/A-3 allows attachments of any type, as ZUGFeRD and Factur-X need. The levels ending in `a` are tagged for accessibility. ## `InvoiceProfile` `Fagus\InvoiceProfile` is a string-backed enum of ZUGFeRD and Factur-X profiles, for `facturX()`: | Case | Value | |---|---| | `InvoiceProfile::Minimum` | `'minimum'` | | `InvoiceProfile::BasicWl` | `'basicwl'` | | `InvoiceProfile::Basic` | `'basic'` | | `InvoiceProfile::En16931` | `'en16931'` | | `InvoiceProfile::Extended` | `'extended'` | | `InvoiceProfile::XRechnung` | `'xrechnung'` | ## `Relationship` `Fagus\Relationship` is a string-backed enum of how an attached file relates to the document (PDF 2.0 `AFRelationship`), for `attach()`: | Case | Value | Use for | |---|---|---| | `Relationship::Source` | `'source'` | The source the document was made from. | | `Relationship::Data` | `'data'` | Data the document shows, such as a table as CSV. | | `Relationship::Alternative` | `'alternative'` | Another representation of the same content. | | `Relationship::Supplement` | `'supplement'` | Additional material. | | `Relationship::Unspecified` | `'unspecified'` | None of these; the default. | ## Exceptions All exceptions extend `Fagus\Exception\FagusException`, which extends PHP's `RuntimeException`. Catch `FagusException` to handle anything that goes wrong in Fagus. ```php use Fagus\Exception\EngineException; use Fagus\Exception\RenderException; try { $pdf = Fagus::html($html)->accessible()->render(); } catch (RenderException $exception) { // The document cannot be rendered as asked, or has diagnostics in strict mode. report($exception); foreach ($exception->diagnostics() as $diagnostic) { // those strict mode refused, or those found before rendering failed } } catch (EngineException $exception) { // The binary was not found, could not be started, timed out or stopped. } ``` | Exception | Thrown when | |---|---| | `FagusException` | Base class. Thrown itself by `Pdf::save()` when the file cannot be written. | | `RenderException` | The document cannot be rendered (for example PDF/UA requirements that are not met), or has diagnostics in strict mode. `diagnostics(): list<Diagnostic>` returns the diagnostics strict mode refused, or those found before rendering failed (CSS that was ignored, resources that are missing), which often explain the failure. | | `EngineException` | The binary was not found or could not be started, a font directory does not exist, the worker did not answer within the timeout, it stopped, it speaks another protocol, or a font passed to `addFont()` cannot be read. When the worker has exited, the message ends with its exit code and what it wrote to its error output. | | `InvalidArgumentException` | A value Fagus does not know, such as a PDF/A level passed to `pdfA()` as a string that is not one. | | `InstallException` | The binary could not be installed: a development version without binaries, an unsupported platform, a failed download, a checksum mismatch, or a directory that cannot be written. Thrown by `Installer`, `vendor/bin/fagus-install` and `php artisan fagus:install`; the Composer plugin turns it into a warning. | The exact messages are listed in [troubleshooting.md](troubleshooting.md). ## `Installer` `Fagus\Installer` installs the binary of the package's release for the platform PHP runs on. The Composer plugin, `vendor/bin/fagus-install` and `php artisan fagus:install` use it; you need it only to install from your own code. ```php use Fagus\Installer; $path = (new Installer( token: null, // GitHub token for a private repository; FAGUS_GITHUB_TOKEN or GITHUB_TOKEN if null source: null, // a directory or URL with the files of the release; FAGUS_DOWNLOAD_URL if null cacheDirectory: null, // where downloaded binaries are kept for the next installation ))->install(); // or ->install('/opt/fagus') for another directory Installer::target(); // "x86_64-unknown-linux-musl" on Alpine on x64 Installer::asset('x86_64-pc-windows-msvc'); // "fagus-x86_64-pc-windows-msvc.exe" ``` `install(?string $directory = null): string` returns the path of the binary. A binary that is already there with the right SHA-256 is kept. See [deployment.md](deployment.md). <!-- Source: https://fagus.niklasforst.de/docs/laravel --> # Laravel The package `nforst/fagus` includes its Laravel integration (`Fagus\Laravel\`, in `php/laravel/src`). Laravel 13 discovers it on its own: `composer require nforst/fagus` registers the service provider, the `Fagus` facade, the configuration and the `fagus:install` command. ```php use Fagus\Laravel\Facades\Fagus; // In a controller: shown in the browser. return Fagus::view('invoices.show', ['invoice' => $invoice])->name('invoice.pdf'); // As a download, on a disk, or as bytes. return Fagus::view('invoices.show', $data)->download('invoice.pdf'); Fagus::view('invoices.show', $data)->pdfA('3b')->store('invoices/2026-0042.pdf', 's3'); $bytes = Fagus::html($html)->render()->bytes(); ``` Installation is described in [getting-started.md](getting-started.md). ## The facade `Fagus\Laravel\Facades\Fagus` (also registered as the alias `Fagus`) resolves the service `fagus`, an instance of `Fagus\Laravel\PdfFactory`. It has four methods: | Method | Returns | |---|---| | `Fagus::view(string $view, array $data = [], array $mergeData = [])` | A `PendingPdf` from a Blade view, rendered with `view()->make($view, $data, $mergeData)`. | | `Fagus::html(string $html)` | A `PendingPdf` from HTML. | | `Fagus::xhtml(string $xml)` | A `PendingPdf` from XHTML, parsed as XML (see [php.md](php.md#fagus)). | | `Fagus::engine()` | The application's `Fagus\Engine`, for `addFont()` and `version()`. | Every `PendingPdf` starts with the base directory, the root and the tagging of the configuration. Do not confuse the facade with the plain PHP class `Fagus\Fagus`. The class does not read `config/fagus.php` and renders with an engine of its own; in Laravel, import `Fagus\Laravel\Facades\Fagus`. You can inject the factory instead of using the facade: ```php use Fagus\Laravel\PdfFactory; final class InvoiceMailer { public function __construct(private PdfFactory $pdfs) {} public function attachment(Invoice $invoice): string { return $this->pdfs->view('invoices.show', ['invoice' => $invoice])->render()->bytes(); } } ``` `Fagus\Engine` is bound as a singleton too, so `app(Engine::class)` is the same engine as `Fagus::engine()`. ## `PendingPdf` `Fagus\Laravel\PendingPdf` wraps a `Fagus\Document` together with the engine. Like the document, it is immutable: every method returns a changed copy. ### Document methods These forward to `Fagus\Document` and take the same arguments; [php.md](php.md#document) describes each one: `baseDirectory()`, `root()`, `stylesheet()`, `resource()`, `resolver()`, `pdfA()`, `tagged()`, `accessible()`, `attach()`, `facturX()`, `created()`, `strict()`. ```php use Fagus\Conformance; use Illuminate\Support\Facades\Vite; Fagus::view('invoices.show', ['invoice' => $invoice]) ->stylesheet(Vite::content('resources/css/pdf.css')) ->resource('logo.png', $invoice->company->logo) ->pdfA(Conformance::PdfA3b) ->facturX($invoice->toFacturX()); ``` ### `name(string $filename): PendingPdf` The file name for the browser and for downloads. `document.pdf` by default. ### `inline(?string $filename = null): Response` Renders the PDF and returns a response that shows it in the browser (`Content-Disposition: inline`). The file name is `$filename`, else the one from `name()`. ### `download(?string $filename = null): Response` Renders the PDF and returns a response that downloads it (`Content-Disposition: attachment`). ```php return Fagus::view('invoices.show', $data)->download("invoice-{$invoice->number}.pdf"); ``` Both responses are `Illuminate\Http\Response` with `Content-Type: application/pdf`. File names with characters outside ASCII are sent as `filename*=utf-8''…` with an ASCII fallback, so `Übersicht März.pdf` arrives as written. ### `toResponse($request): Response` `PendingPdf` implements `Responsable`: returned from a controller or route, it renders the PDF and shows it inline, as `inline()` does. ```php Route::get('/invoices/{invoice}/pdf', fn (Invoice $invoice) => Fagus::view('invoices.show', [ 'invoice' => $invoice, ])->name("invoice-{$invoice->number}.pdf")); ``` ### `store(string $path, ?string $disk = null): Pdf` Renders the PDF and writes it to a filesystem disk, the default disk if `$disk` is `null`. Returns the `Fagus\Pdf`. ```php $pdf = Fagus::view('invoices.show', $data)->store("invoices/{$invoice->number}.pdf", 's3'); $pdf->pages(); ``` ### `save(string $path): Pdf` Renders the PDF and writes it to a local path. ### `render(): Pdf` Renders the PDF and returns the `Fagus\Pdf` with its bytes, page count, diagnostics and timings (see [php.md](php.md#pdf)). ```php $pdf = Fagus::view('reports.monthly', $data)->render(); Mail::to($customer)->send(new MonthlyReport($pdf->bytes())); ``` ### `document(): Document` The underlying `Fagus\Document`, for code that works with the plain PHP API. ## Queues Render PDFs in a job when they take long or when nobody waits for them: ```php use Fagus\Laravel\Facades\Fagus; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; final class StoreInvoicePdf implements ShouldQueue { use Queueable; public function __construct(public Invoice $invoice) {} public function handle(): void { Fagus::view('invoices.show', ['invoice' => $this->invoice]) ->pdfA('3b') ->store("invoices/{$this->invoice->number}.pdf", 's3'); } } ``` The engine is a singleton. In `php artisan queue:work` (and in Horizon's workers), the worker process starts with the first PDF and serves every following job of that queue worker, so a job pays only for rendering. `php artisan queue:listen` boots the application for every job, which starts a new worker process each time. After deploying a new version of the package, restart the queue workers (`php artisan queue:restart`) so that they use the new binary. ## Octane and FrankenPHP Under PHP-FPM, the engine lives as long as the request: the first PDF of each request starts the worker process (a few milliseconds), and the request's end stops it. Under Octane (Swoole, RoadRunner or FrankenPHP), the application boots once per Octane worker. Octane gives each request a copy of the application's container and throws away what a request resolved when it ends: an engine resolved in a request would start a worker process and stop it again at the request's end. So when Octane is installed, the service provider adds `Fagus\Engine` to the `warm` services of `config/octane.php`, which Octane resolves when its worker boots and shares with every request. One engine, and its worker process, then serves every PDF of the Octane worker; there is nothing to configure. Listing `\Fagus\Engine::class` in `warm` yourself does no harm. More on worker processes, memory and timeouts: [deployment.md](deployment.md#worker-processes). ## Configuration Publish the configuration file to change it: ```sh php artisan vendor:publish --tag=fagus-config ``` This writes `config/fagus.php`. Every key, with its environment variable and default: | Key | Environment variable | Default | Meaning | |---|---|---|---| | `binary` | `FAGUS_BINARY` | `null` | The path of the `fagus` binary. If `null`: the one the package installed (with Composer or `php artisan fagus:install`), else the one on the `PATH`. A path that is set must exist. | | `fonts` | – | `[resource_path('fonts')]` | Directories with fonts for every document: TTF, OTF, TTC, OTC, WOFF and WOFF2 files, in the directory and its subdirectories. Directories that do not exist are skipped, so the default works without a `resources/fonts`; a plain `Fagus\Engine` throws an `EngineException` for them instead. | | `system_fonts` | `FAGUS_SYSTEM_FONTS` | `false` | Whether the fonts installed on the machine serve too, as in Chrome. Off, so that documents look the same on every machine. | | `locale` | `FAGUS_LOCALE` | `null` | The language of the texts that form controls show of their own (button labels, date formats) and of the PDF where a document gives no `lang`, such as `de-DE`. American English if `null`. | | `families` | – | `['sans-serif' => null, 'serif' => null, 'monospace' => null]` | The families that the generic families name. | | `base_directory` | – | `public_path()` | The directory that relative URLs in documents resolve against. Only files inside it, or inside `root`, are read. | | `root` | – | `null` | A larger directory that contains `base_directory`, for documents whose URLs lead out of it (`../fonts/…`). URLs that start with `/` resolve against it. | | `tagged` | – | `true` | Whether PDFs are tagged with the logical structure that screen readers read. Single documents can say otherwise with `tagged()` or ask for PDF/UA with `accessible()`. | | `timeout` | – | `60` | Seconds to wait for each answer of the worker before it is stopped. Not on Windows, where PHP cannot wait for a pipe with a time limit. | `binary`, `fonts`, `system_fonts`, `locale`, `families` and `timeout` configure the engine; `base_directory`, `root` and `tagged` apply to each new `PendingPdf`. ```php // config/fagus.php return [ 'binary' => env('FAGUS_BINARY'), 'fonts' => [resource_path('fonts')], 'system_fonts' => env('FAGUS_SYSTEM_FONTS', false), 'locale' => env('FAGUS_LOCALE', 'de-DE'), 'families' => [ 'sans-serif' => 'Inter', 'serif' => null, 'monospace' => 'JetBrains Mono', ], 'base_directory' => resource_path('pdf'), 'root' => resource_path(), 'tagged' => true, 'timeout' => 30, ]; ``` With `base_directory` at `public_path()`, a view refers to files of `public/` as a page of the site would: `<img src="/images/logo.png">` reads `public/images/logo.png`. Absolute URLs from `asset()`, `url()` or `@vite` start with `http` and are not loaded; see [resources.md](resources.md#laravel-assets-and-vite) for how to use them. ## `php artisan fagus:install` Installs the `fagus` binary of the package's release for the platform PHP runs on, as the Composer plugin does after `composer install`: ```sh php artisan fagus:install # where the engine finds it php artisan fagus:install /opt/fagus # into another directory ``` It takes `FAGUS_DOWNLOAD_URL` and `FAGUS_GITHUB_TOKEN` (or `GITHUB_TOKEN`) from the environment, like `vendor/bin/fagus-install`. A binary installed into another directory must be named in `FAGUS_BINARY` (or the `binary` key) or lie on the `PATH`. See [deployment.md](deployment.md). ## Diagnostics and errors `render()`, `store()` and `save()` return the `Fagus\Pdf`, whose `diagnostics()` lists CSS that was ignored and resources that were not found. Log them while you build a template: ```php $pdf = Fagus::view('invoices.show', $data)->render(); foreach ($pdf->diagnostics() as $diagnostic) { Log::warning((string) $diagnostic); } ``` `inline()` and `download()` render and discard the diagnostics. Errors are exceptions (`Fagus\Exception\RenderException`, `EngineException`), which Laravel reports as usual. A `RenderException` keeps the diagnostics found before the document was refused in its `diagnostics()`. See [troubleshooting.md](troubleshooting.md). ## Testing The package has no fake. PDFs render in a few milliseconds, so tests can render them with the real binary: the Composer plugin installs it with `composer install` on the developer's machine and in CI, as long as `allow-plugins` permits it. Assert on the response of a route: ```php public function test_the_invoice_pdf_is_shown(): void { $invoice = Invoice::factory()->create(); $response = $this->get("/invoices/{$invoice->id}/pdf"); $response->assertOk(); $response->assertHeader('Content-Type', 'application/pdf'); $this->assertStringStartsWith('%PDF-', $response->getContent()); } ``` Fake the disk to check `store()`: ```php Storage::fake('s3'); StoreInvoicePdf::dispatchSync($invoice); Storage::disk('s3')->assertExists("invoices/{$invoice->number}.pdf"); ``` Make a template fail on every ignored declaration and missing resource with `strict()`: ```php public function test_the_invoice_template_is_clean(): void { $pdf = Fagus::view('invoices.show', ['invoice' => Invoice::factory()->make()]) ->strict() ->render(); $this->assertSame(1, $pdf->pages()); } ``` To render with a binary of your own in tests, set `FAGUS_BINARY` in `phpunit.xml`: ```xml <php> <env name="FAGUS_BINARY" value="/usr/local/bin/fagus"/> </php> ``` <!-- Source: https://fagus.niklasforst.de/docs/resources --> # Resources A document refers to other files: images, stylesheets, fonts, SVG sprites, the documents of frames. Fagus loads them only from places you allow. It never goes to the network, never reads a file outside the directory you name, and runs no scripts. This page describes where resources come from, and so the security model. ## Where a resource comes from For every URL in a document, Fagus tries these sources in this order and takes the first that has the resource: 1. **A `data:` URL**: the data in the URL itself, base64 or percent-encoded. 2. **The resources handed over** with `resource($url, $data)`. 3. **The resolver** set with `resolver()`, a PHP callback. 4. **A file inside the root directory**, if a base directory is set. If none has it, the resource is missing: the document renders without it and the PDF's diagnostics say so (`resource.not-loaded`). ```php $pdf = Fagus::html($html) ->baseDirectory(__DIR__.'/resources/pdf') ->resource('logo.png', $tenant->logo) ->resolver(fn (string $url): ?string => $media->find($url)) ->render(); ``` ## Read files from a base directory Without a base directory, Fagus reads no files at all. With one, relative URLs resolve against it, and only files inside it are read: ```php Fagus::html('<link rel="stylesheet" href="css/invoice.css"><img src="images/logo.png" alt="ACME">') ->baseDirectory(__DIR__.'/resources/pdf'); // reads resources/pdf/css/invoice.css and resources/pdf/images/logo.png ``` A query or fragment (`logo.png?v=2`, `icons.svg#check`) is not part of the file name. Percent escapes are decoded (`my%20logo.png` is `my logo.png`). In Laravel the base directory is `public/` unless `base_directory` in `config/fagus.php` says otherwise. ## Allow a larger directory with `root()` The root is the directory that files may come from. It is the base directory unless you set it with `root()`, and it must contain the base directory. Use it when the document's URLs lead out of its own directory: ```php Fagus::html($html) ->baseDirectory(__DIR__.'/resources/pdf/invoices') ->root(__DIR__.'/resources/pdf'); ``` ```html <!-- resources/pdf/invoices/invoice.html --> <link rel="stylesheet" href="../shared/base.css"> <!-- resources/pdf/shared/base.css --> ``` Anything that leads outside the root is refused: `..` past the root, absolute file paths (`/etc/passwd` is looked up as `<root>/etc/passwd`), and symbolic links that point outside it. ## URLs that start with `/` A URL that starts with `/` resolves against the root, as on a web server: ```php Fagus::html('<img src="/images/logo.png" alt="ACME">') ->baseDirectory(__DIR__.'/public/invoices') ->root(__DIR__.'/public'); // reads public/images/logo.png ``` Without `root()`, it resolves against the base directory. In Laravel, with the base directory at `public/`, the same markup works in a page of the site and in the PDF. ## Hand over data with `resource()` `resource($url, $data)` gives Fagus the data for a URL, so it does not have to be a file: a logo from the database, a chart drawn in PHP, a stylesheet built at runtime. ```php Fagus::html('<img src="logo.png" alt="ACME"><img src="chart.svg" alt="Revenue by month">') ->resource('logo.png', $company->logo_png) ->resource('chart.svg', $chart->toSvg()); ``` The URL must match the URL that Fagus asks for: - In the document, that is the URL as written in the attribute: `<img src="logo.png">` asks for `logo.png`, `<img src="./logo.png">` for `./logo.png`. - In a stylesheet that was loaded from a URL (`<link href="css/main.css">`, `@import`), relative URLs are resolved against the stylesheet first, as in browsers: `url(img/bg.png)` in `css/main.css` asks for `css/img/bg.png`, and `@import "more.css"` there for `css/more.css`. - In a frame's document (`<iframe src="frames/page.html">`), relative URLs are resolved against the frame's URL: `style.css` in `frames/page.html` asks for `frames/style.css`. Resources handed over work without a base directory. They are also the only way, besides `data:` URLs and the resolver, to provide resources for a document that has no files. ## Answer requests with `resolver()` A resolver is a callback that gets each URL that was not handed over, as described above, and returns its data or `null`: ```php Fagus::html($html) ->baseDirectory(resource_path('pdf')) ->resolver(function (string $url): ?string { if (! str_starts_with($url, 'media://')) { return null; // let Fagus look for a file } return Storage::disk('media')->get(substr($url, strlen('media://'))); }); ``` Fagus asks the resolver before it looks for a file; after `null`, it tries the file in the root. The resolver sees every URL the document refers to that is not a `data:` URL or handed over, including `https://…` URLs. It decides what to hand out. Fagus does not go to the network, but your resolver may, under your own rules: check the host against a list, set a timeout, and keep in mind that a document from user input can name any URL. The engine waits while the callback runs; the [timeout](deployment.md#timeouts) does not count that time, as it limits the wait for the worker's answers. ## `data:` URLs `data:` URLs work everywhere a URL does, base64 or percent-encoded: ```html <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA…" alt=""> <link rel="stylesheet" href="data:text/css,p%20%7B%20color%3A%20navy%20%7D"> ``` In PHP: ```php $src = 'data:image/png;base64,'.base64_encode($png); ``` A document of a frame that comes from a `data:` URL loads nothing else. ## Images `<img>`, `<picture>` and `srcset`, CSS backgrounds, `mask`, `list-style-image`, `border-image`, `content: url()`, and SVG clip paths, masks, filters and `<use href="sprite.svg#id">` in other files load as resources. | Format | Notes | |---|---| | PNG | Also with `gAMA`, converted to sRGB as Chrome converts them. | | JPEG | CMYK JPEGs without a profile are converted to sRGB as in Chrome. | | GIF | | | WebP | | | SVG | Drawn as vector graphics. An SVG image does not see the document's `@font-face` fonts; its own `@font-face` rules load fonts only from `data:` URLs, as in Chrome. | JPEG, PNG and WebP photos stand as their EXIF orientation says. `<picture>` sources and `srcset` are chosen as Chrome chooses them; AVIF and JPEG XL sources are skipped, as Fagus cannot decode them. An image that cannot be used is left out, and a diagnostic says why: | Code | Message | |---|---| | `resource.not-loaded` | image `…` could not be loaded | | `image.unsupported` | image `…` is not a PNG, JPEG, GIF, WebP or SVG image | | `image.unsupported` | image `…` is not a valid SVG image | | `image.too-large` | image `…` has more than 200 megapixels | | `image.broken` | image `…` could not be decoded and is left out | ## Stylesheets Stylesheets come from `<style>` elements, `<link rel="stylesheet" href="…">`, `@import` and `stylesheet()`: ```html <link rel="stylesheet" href="css/invoice.css"> <style> @import url("css/print.css") print; @import "css/theme.css" layer(theme); </style> ``` - A linked stylesheet loads as a resource. One that cannot be loaded is reported: `html:4: warning[resource.not-loaded]: stylesheet `css/missing.css` could not be loaded`. - `@import` loads its stylesheet as a resource, with the media queries, `supports()` condition and `layer()` of its rule, up to eight levels deep. One that cannot be loaded is reported as "stylesheet `…` could not be imported". - Relative URLs in a linked or imported stylesheet resolve against the stylesheet's URL. - `stylesheet($css)` adds CSS from PHP after the document's stylesheets. Its relative URLs resolve against the base directory. ## Fonts `@font-face` rules load their fonts as resources: TTF, OTF, WOFF and WOFF2, with variable fonts and `unicode-range`. ```css @font-face { font-family: "Corporate Sans"; src: url("fonts/CorporateSans.woff2") format("woff2"); font-weight: 100 900; } ``` Fagus loads the first source that Chrome would load and passes over formats and technologies Chrome does not load. A font that cannot be loaded is reported ("font `…` could not be loaded"), one that is not a font Fagus can read too ("`…` is not a font Fagus can read", `font.unsupported`). Fonts from directories, generic families and system fonts are described in [fonts.md](fonts.md). ## Frames: `<iframe>`, `<object>` and `<embed>` An `<iframe>` (its `srcdoc`, else its `src`), and an `<object>` or `<embed>` whose resource is an HTML document, shows that document as Chrome prints it: laid out at the frame's size, not paginated, cut off at the frame's edges. ```html <iframe src="frames/terms.html" style="width: 100%; height: 120mm; border: 0"></iframe> <iframe srcdoc="<p>Inline document</p>"></iframe> ``` A frame's document loads like any other resource: a `data:` URL, the resources handed over, the resolver, or a file inside the root. Its own relative URLs resolve against its URL. Scripts in it do not run. Frames nest at most 8 deep, and one render lays out at most 256 documents in frames with 8 MiB of markup together; past that limit, frames show nothing and a `frame.limit` warning says so. The diagnostics of documents in frames are not reported. Text files and images in frames show as Chrome shows them. ## What is never loaded - **The network.** URLs with `http:`, `https:`, `ftp:` or a host (`//cdn.example.com/…`) are never fetched by Fagus. Only a resolver of yours can answer them. - **Files outside the root**, through `..`, absolute paths or symbolic links. A URL with a scheme (`file:///etc/passwd`) is never read as a file. - **Files at all**, when no base directory is set. - **Scripts.** `<script>` does not run, and neither do event handlers or `javascript:` URLs. Content that a script would create in a browser, such as a chart drawn by JavaScript, is missing. Render it on the server as SVG or an image and hand it over. Links (`<a href="https://…">`) are different: they become links in the PDF and load nothing. ## Diagnostics for missing resources Every resource that is missing shows in `$pdf->diagnostics()`: ```php $pdf = Fagus::html($html)->baseDirectory(__DIR__.'/assets')->render(); foreach ($pdf->diagnostics() as $diagnostic) { echo $diagnostic, "\n"; } ``` ```text html:4: warning[resource.not-loaded]: stylesheet `css/missing.css` could not be loaded resources: warning[resource.not-loaded]: image `https://example.com/a.png` could not be loaded resources: warning[resource.not-loaded]: image `../outside/x.png` could not be loaded ``` With `strict()`, any diagnostic makes `render()` throw a `RenderException` instead, which helps to catch missing files in tests. Long `data:` URLs are cut short in the messages. ## Laravel: assets and Vite `asset()`, `url()`, `Vite::asset()` and `@vite` write absolute URLs with the host of the application (`https://example.com/build/assets/app-4ed993c7.css`), which Fagus does not fetch. Use one of these instead: - Root-relative URLs in the view, which resolve against `public/`: ```blade <img src="/images/logo.png" alt="ACME"> ``` - The built CSS, handed over as a stylesheet: ```php use Illuminate\Support\Facades\Vite; Fagus::view('invoices.show', $data)->stylesheet(Vite::content('resources/css/pdf.css')); ``` - A resolver that maps the application's URLs to files in `public/`, and only to those: ```php Fagus::view('invoices.show', $data)->resolver(function (string $url): ?string { $prefix = rtrim(config('app.url'), '/').'/'; if (! str_starts_with($url, $prefix)) { return null; } $public = realpath(public_path()); $file = realpath(public_path(parse_url($url, PHP_URL_PATH) ?? '')); return $file !== false && str_starts_with($file, $public.DIRECTORY_SEPARATOR) && is_file($file) ? file_get_contents($file) : null; }); ``` <!-- Source: https://fagus.niklasforst.de/docs/deployment --> # Deployment Fagus needs its `fagus` binary next to PHP on every server that renders PDFs. The Composer plugin installs it with `composer install`; this page covers builds, servers and processes where that needs a thought. ## Install the binary in CI and Docker builds The plugin runs after `composer install` and `composer update` and installs the binary for the platform Composer runs on, checked against the SHA-256 that the package lists for its release. Builds run Composer without asking, so two things must be in place: 1. **The plugin is allowed in `composer.json`.** Composer asks interactively the first time; in a build it fails instead: ```text nforst/fagus contains a Composer plugin which is blocked by your allow-plugins config. You may add it to the list if you consider it safe. ``` Commit the entry that answering `y` writes, or add it yourself: ```sh composer config allow-plugins.nforst/fagus true ``` 2. **The build can reach GitHub**, where the binaries are attached to the release. Installing from a private fork also needs a token that can read it: Composer's (`github-oauth.github.com` in `auth.json` or `COMPOSER_AUTH`), else `FAGUS_GITHUB_TOKEN` or `GITHUB_TOKEN`. `--no-scripts` does not stop the plugin; `--no-plugins` does. After `--no-plugins`, run `vendor/bin/fagus-install`. The plugin keeps downloaded binaries in Composer's cache directory (`<cache-dir>/fagus/<version>/`), so a build with a cached Composer directory downloads each binary once. ### Docker Run Composer in the image that runs the application, or install the binary there afterwards. A binary installed in another image is for that image's platform, which may differ in architecture or C library from the image that runs PHP. ```dockerfile FROM php:8.4-fpm COPY --from=composer:2 /usr/bin/composer /usr/bin/composer WORKDIR /app COPY . . RUN composer install --no-dev --no-interaction --optimize-autoloader ``` With a multi-stage build, where Composer runs in a stage of its own, install the binary in the final stage: ```dockerfile FROM composer:2 AS vendor WORKDIR /app COPY composer.json composer.lock ./ RUN composer install --no-dev --no-interaction --no-plugins --optimize-autoloader FROM php:8.4-fpm-alpine WORKDIR /app COPY --from=vendor /app/vendor ./vendor COPY . . RUN vendor/bin/fagus-install ``` `vendor/bin/fagus-install` keeps a binary that is already there with the right SHA-256 and replaces one of another platform. ## Alpine and other musl systems Linux with musl has binaries of its own (`x86_64-unknown-linux-musl`, `aarch64-unknown-linux-musl`), linked statically. The installer picks them when it finds `/lib/ld-musl-*.so.1` or `/etc/alpine-release`; nothing needs to be configured. The glibc binaries are linked against glibc 2.17, so they run on every maintained glibc distribution. The binary needs no system libraries and no installed fonts. With `systemFonts: true`, it reads the font directories that fontconfig's configuration lists, else `/usr/share/fonts`, `/usr/local/share/fonts` and `~/.local/share/fonts`; install the font packages you want there (see [fonts.md](fonts.md)). ## Servers without access to GitHub Put the files of the release somewhere the server can reach and point `FAGUS_DOWNLOAD_URL` at it: a directory or a URL that holds the files under their names in the release, `fagus-<target>`: ```text fagus-x86_64-unknown-linux-gnu fagus-aarch64-unknown-linux-gnu fagus-x86_64-unknown-linux-musl fagus-aarch64-unknown-linux-musl fagus-x86_64-apple-darwin fagus-aarch64-apple-darwin fagus-x86_64-pc-windows-msvc.exe ``` ```sh FAGUS_DOWNLOAD_URL=https://artifacts.example.com/fagus/0.1.0 composer install FAGUS_DOWNLOAD_URL=/mnt/artifacts/fagus/0.1.0 vendor/bin/fagus-install ``` The binary is installed only if its SHA-256 is the one the package lists for its release, whatever its source. `FAGUS_DOWNLOAD_URL` applies to the plugin, `vendor/bin/fagus-install` and `php artisan fagus:install`. `vendor/bin/fagus-install` takes a directory as its argument to install somewhere else than into the package; name that path in `FAGUS_BINARY` then: ```sh vendor/bin/fagus-install /opt/fagus # The fagus binary is installed at /opt/fagus/fagus. ``` ## Use a binary of your own `FAGUS_BINARY` names a binary that the engine uses instead of the installed one, for example one built from source: ```sh cargo build --release -p fagus-cli export FAGUS_BINARY=/path/to/fagus/target/release/fagus ``` The engine looks for the binary in this order: 1. The `binary` argument of `Engine` (in Laravel, the `binary` key of `config/fagus.php`). 2. `FAGUS_BINARY`. 3. The binary the installer put into the package (`vendor/nforst/fagus/php/fagus/bin/fagus`, `fagus.exe` on Windows). 4. `fagus` (`fagus.exe`) on the `PATH`. A binary named in the first two must exist and be executable, otherwise the engine does not fall back but throws: ```text The fagus binary `/usr/local/bin/fagus` could not be started. It does not exist or is not executable. ``` The binary must speak the package's protocol; use the one of the same release. Under PHP-FPM the pool's environment is cleared by default (`clear_env = yes`), so a `FAGUS_BINARY` from the shell does not reach PHP. Set it in the pool (`env[FAGUS_BINARY] = /usr/local/bin/fagus`) or pass the path to the engine. In Laravel, `FAGUS_BINARY` in `.env` works, also with a cached configuration, as it is read into `config('fagus.binary')`. ## Windows - The binary is `fagus.exe` for x64; Windows on ARM is not supported. - There is no timeout: PHP cannot wait for a pipe with a time limit on Windows, so the engine waits for each answer as long as it takes. - A running binary is locked. Stop the processes that run it (queue workers, Octane) before `composer update` replaces it; otherwise the installer reports that it could not write the binary. ## Worker processes The PHP package starts the binary as a worker process with the first document and talks to it through pipes ([protocol.md](protocol.md)). The worker keeps fonts and caches warm and renders one document after another until its engine is closed or destroyed. HTML, fonts and PDFs travel through the pipes as they are, of any size. | Runtime | The worker serves | |---|---| | PHP-FPM, mod_php, FrankenPHP's classic mode | the documents of one request; the first document of each request starts it | | Queue workers (`queue:work`, Horizon) | every document of the queue worker process | | Octane (Swoole, RoadRunner, FrankenPHP) | every document of the Octane worker: the Laravel integration warms the engine ([laravel.md](laravel.md#octane-and-frankenphp)) | | FrankenPHP's worker mode without Laravel, long-running scripts | every document, as long as the engine (for example `Fagus::engine()`) is kept | | CLI scripts | the documents of the script | Each PHP process that renders has its own worker process. One worker renders one document at a time, as PHP sends them one after another. `Engine::close()` stops the worker; the next document starts a new one, which gets the fonts of `addFont()` again. When a worker times out or exits, the engine stops it and throws an `EngineException`; the next document starts a new worker. ## Speed and memory Rendering times of invoices on an Apple M3, once the worker runs, unless noted: | Document | Time | |---|---| | One-page invoice, tagged | about 1.5 ms | | Ten-page invoice, tagged | about 12 ms | | First document of a process, including the start of the worker | about 8 ms | On an Apple M2 Pro, `fagus render` of the repository's corpus invoices peaks at about 22 MB of resident memory for the one-page invoice and 34 MB for the ten-page invoice. The macOS binary itself is about 25 MB on disk. Large images, many fonts and long documents need more. Under PHP-FPM, every request that renders pays the start of the worker once. Where many requests render PDFs, a queue worker or Octane keeps the worker running. ## Threads The binary compresses the PDF on two threads of its own while it draws the pages, which makes large documents a few percent faster. `RAYON_NUM_THREADS` sets how many there are: ```sh RAYON_NUM_THREADS=1 php artisan queue:work ``` More than two gain nothing. With many workers side by side on few cores, one thread each saves processor time. The worker inherits the environment of the PHP process that starts it; under PHP-FPM, set the variable in the pool (`env[RAYON_NUM_THREADS] = 1`). ## Timeouts The engine waits up to `timeout` seconds (60 by default) for each answer of the worker. A worker that does not answer in time is stopped, and the engine throws: ```text The fagus worker did not answer within 60 seconds and was stopped. ``` ```php new Engine(timeout: 120.0); // in Laravel: 'timeout' => 120 in config/fagus.php ``` The limit applies to each answer, not to the whole document: time spent in your resolver callback does not count. There is no timeout on Windows. For requests, keep the timeout below the limits of PHP-FPM (`request_terminate_timeout`) and of your web server, or render long documents in a queue. ## Reproducible PDFs The same document gives the same bytes when: - the creation date is fixed with `created()` (the current time otherwise), - the fonts are the same, which they are with fonts from `@font-face`, font directories and the built-in fonts, and not necessarily with `systemFonts: true`, - the binary is the same release. ```php $pdf = Fagus::html($html) ->created(new DateTimeImmutable('2026-11-02 12:00:00', new DateTimeZone('UTC'))) ->render(); ``` Every platform prints the same PDF from the same input, so a PDF made on a Mac matches the one made on a Linux server. <!-- Source: https://fagus.niklasforst.de/docs/troubleshooting --> # Troubleshooting ## Installing the binary ### The plugin is blocked ```text nforst/fagus contains a Composer plugin which is blocked by your allow-plugins config. You may add it to the list if you consider it safe. ``` Composer runs without asking (in CI, in Docker builds, with `--no-interaction`) and `composer.json` does not allow the plugin. Allow it and commit the change: ```sh composer config allow-plugins.nforst/fagus true ``` If you answered `n` when Composer asked, `composer.json` has `"nforst/fagus": false`; the plugin then never runs and the engine reports that the binary was not found. Change it to `true`, or install the binary with `vendor/bin/fagus-install`. ### The binary was not found ```text The fagus binary was not found. Install it with `vendor/bin/fagus-install` (in Laravel: `php artisan fagus:install`), set its path in the Engine or in the FAGUS_BINARY environment variable, or put it on the PATH. ``` There is no binary in the package, `FAGUS_BINARY` is not set and there is no `fagus` on the `PATH`. Usually the plugin did not run (`--no-plugins`, blocked) or could not install the binary; `composer install` then printed a warning that starts with `fagus:`. Run the installer to see why: ```sh vendor/bin/fagus-install php artisan fagus:install ``` Copying `vendor/` from a machine of another platform also leaves the wrong binary behind; run the installer on the target ([deployment.md](deployment.md#docker)). ### A binary that is given does not exist ```text The fagus binary `/usr/local/bin/fagus` could not be started. It does not exist or is not executable. ``` The path in `FAGUS_BINARY`, in `new Engine(binary: …)` or in `config/fagus.php` is wrong, or the file is not executable (`chmod +x`). A binary that is given is never replaced by another one. ### `proc_open()` is disabled ```text The fagus binary `/app/vendor/nforst/fagus/php/fagus/bin/fagus` could not be started. PHP does not allow proc_open() (disable_functions). ``` Remove `proc_open` (and `proc_get_status`, `proc_close`, `proc_terminate`) from `disable_functions` in `php.ini`. Fagus runs the binary as a process and needs them. ### A development version without binaries ```text This version of nforst/fagus (0.0.1) is a development version without built binaries. Build the binary with `cargo build --release` and set FAGUS_BINARY to it. ``` You installed a branch (such as `dev-main`) rather than a release. Only releases list the binaries to install; the plugin installs nothing for a branch. Require a release, or build the binary from source and set `FAGUS_BINARY` ([deployment.md](deployment.md#use-a-binary-of-your-own)). ### An unsupported platform ```text There is no fagus binary for Linux on armv7l. Build it from source with `cargo build --release` and set FAGUS_BINARY to it. ``` Releases have binaries for Linux (x64, arm64, glibc and musl), macOS (x64, arm64) and Windows (x64). Other platforms need a binary built from source. ### The download failed ```text The fagus binary could not be downloaded from https://github.com/nforst/fagus/releases/download/v0.1.0/fagus-x86_64-unknown-linux-gnu. The server answered 404. ``` - **From a private fork**, downloads without a token fail with 404. Give Composer a token (`composer config --global github-oauth.github.com <token>`) or set `FAGUS_GITHUB_TOKEN`. - **Without access to GitHub**, point `FAGUS_DOWNLOAD_URL` at a directory or URL with the files of the release ([deployment.md](deployment.md#servers-without-access-to-github)). - With `FAGUS_DOWNLOAD_URL` set to a directory, the message ends in "The file cannot be read." when the file `fagus-<target>` is not there. ### The checksum does not match ```text The downloaded fagus-x86_64-unknown-linux-gnu is not the binary of this release: its SHA-256 is 3f1c…, expected 9a07…. It was not installed. ``` The file is not the binary of the package's release: a file of another release in `FAGUS_DOWNLOAD_URL`, a proxy that changed the download, or a broken download. Nothing was installed. Put the files of the matching release into `FAGUS_DOWNLOAD_URL`, or use `FAGUS_BINARY` for a binary of your own. ### The binary cannot be written ```text The fagus binary could not be written to `/app/vendor/nforst/fagus/php/fagus/bin/fagus`. Check that the directory is writable; on Windows, also stop the processes that run the binary (queue workers, Octane), which keep it locked. ``` The user that runs Composer cannot write into `vendor/`, or, on Windows, a running worker locks the old binary. ### Another protocol ```text The fagus binary speaks protocol 2, this package needs protocol 1. Install the binary of the same release. ``` `FAGUS_BINARY` or the `PATH` points to a binary of another release. Use the binary of the package's release. ## Rendering ### The worker did not answer in time ```text The fagus worker did not answer within 60 seconds and was stopped. ``` A document took longer than the engine's `timeout` (60 seconds by default) between two answers. The worker was stopped; the next document starts a new one. Raise the timeout (`new Engine(timeout: 120.0)`, `'timeout'` in `config/fagus.php`), render the document in a queue, or find what makes it slow with `$pdf->timings()` on a smaller version of it. Windows has no timeout. ### A font directory does not exist ```text The font directory `/app/resources/fonts` does not exist. Create it or remove it from the engine's font directories. ``` A directory in the `fontDirectories` of `new Engine(…)` does not exist. The engine checks them before it starts the worker. Create the directory (in a container image too) or leave it out. Laravel skips the directories of its `fonts` configuration that do not exist, so this does not happen there. ### The worker stopped ```text The fagus worker stopped. It exited with code 1. Error: reading fonts in /app/resources/fonts ``` The worker process ended. The message carries its exit code and the end of what it wrote to its error output. Common causes: - A font directory cannot be read (its permissions), as in the message above. - The process was killed from outside, for example by the kernel's out-of-memory killer. A process ended by a signal has no exit code in the message. The engine stops the worker; the next document starts a new one. If a document makes the worker stop every time, please report it with the document. ### Strict mode ```text 2 diagnostics in strict mode: <style> 1:3:5: warning[css.unknown-property]: unknown property `colr`; the declaration is ignored resources: warning[resource.not-loaded]: image `logo.png` could not be loaded ``` `strict()` turns every diagnostic into a `RenderException`, whose `diagnostics()` lists them. Fix them, or drop `strict()` for documents whose diagnostics you accept. ### PDF/UA requirements ```text the document does not meet PDF/UA-1: the document has no title (add a <title>); the document has no language (add `lang` to <html>); the image `logo.png` in line 12 has no alternative text (add `alt`, empty if it is decoration); the first heading, an <h2> in line 14, is not an <h1> (headings start at h1) ``` `accessible()` checks what PDF/UA-1 requires of the document and throws a `RenderException` that lists everything missing. Its `diagnostics()` hold what was found before, such as an image that could not be loaded: | Problem | Fix | |---|---| | the document has no title | `<title>Invoice 2026-0042` | | the document has no language | `` | | the image `…` has no alternative text | `alt="…"`, or `alt=""` for decoration | | the SVG in line … has no alternative text | a `` or `aria-label` in the `<svg>`, or `aria-hidden="true"` for decoration | | the formula in line … has no alternative text | `alttext` on `<math>` | | the first heading … is not an `<h1>` | start with `<h1>` | | the `<h3>` in line … follows an `<h1>` | headings skip no level: use an `<h2>` | ### PDF/A requirements ```text the document does not meet PDF/A-2b: PDF/A-2 allows only PDF/A files as attachments; attach `timesheet.csv` to a PDF/A-3 document instead ``` The PDF cannot meet the PDF/A level that was asked for. PDF/A-2 allows only PDF/A files as attachments; use PDF/A-3 (`pdfA('3b')`) for other files. See [pdf.md](pdf.md). The exception's `diagnostics()` hold what was found before the PDF was refused. ### An unknown PDF/A level ```text Unknown PDF/A level '4z'. The levels are '2b', '2u', '2a', '3b', '3u', '3a'. ``` `pdfA()` got a string that is not a level. It throws a `Fagus\Exception\InvalidArgumentException` when it is called, before anything is rendered. Pass one of the levels, or a `Conformance` case. ### The PDF cannot be saved ```text The PDF could not be written to `/var/www/storage/invoices/2026-0042.pdf`. ``` The directory does not exist or is not writable. `save()` does not create directories. ### An internal error ```text internal error while rendering: … ``` Fagus stopped where it should not. This is a bug; please report it with the document. ## Read diagnostics Every `Pdf` carries the diagnostics of its document: what Fagus ignored or could not load, with the position in the source. ```php $pdf = Fagus::html($html)->baseDirectory(__DIR__.'/assets')->render(); foreach ($pdf->diagnostics() as $diagnostic) { echo $diagnostic, "\n"; } ``` ```text html:4: warning[resource.not-loaded]: stylesheet `css/missing.css` could not be loaded <style> 1:1:34: warning[css.unknown-property]: unknown property `colr`; the declaration is ignored resources: warning[resource.not-loaded]: image `https://example.com/a.png` could not be loaded ``` Each line reads `source:line:column: severity[code]: message`. The source is `<style> 1` for the first `<style>` element, the URL of a linked or imported stylesheet, the name given to `stylesheet()`, `html` for the markup, `resources` for loaded files and `pdf` for the output. | Code | Meaning | |---|---| | `css.unknown-property` | A property Fagus does not know; the declaration is ignored. | | `css.invalid-value` | A value the property does not take; the declaration is ignored. | | `css.parse-error` | A rule or declaration that cannot be parsed; it is ignored. | | `css.unparsable` | Rules or declarations the CSS parser cannot handle are left out. | | `css.too-deep` | Blocks or functions nest too deep; the stylesheet is ignored. | | `html.too-deep` | Elements nest hundreds of levels deep; the rest of the document is left out (severity `error`). | | `resource.not-loaded` | A stylesheet, image, font or SVG reference could not be loaded ([resources.md](resources.md)). | | `image.unsupported` | An image is not PNG, JPEG, GIF, WebP or SVG, or not a valid SVG. | | `image.too-large` | An image has more than 200 megapixels. | | `image.broken` | An image could not be decoded and is left out. | | `font.unsupported` | A file is not a font Fagus can read, or an installed font has no glyphs it can draw. | | `font.missing-glyph` | No font has a glyph for some characters; they are drawn as empty boxes ([fonts.md](fonts.md)). | | `frame.limit` | The documents in frames reach their limit; later frames show nothing. | | `layout.too-many-pages` | The document reaches the limit of 10,000 pages; what follows is left out. | | `pdf.conformance-raised` | Factur-X needs PDF/A-3; a PDF/A-2 level was raised to the PDF/A-3 level of the same letter. | | `invoice.profile-mismatch` | The invoice XML declares another profile than the one given. | | `invoice.profile-unknown` | The invoice XML declares no Factur-X profile. | Declarations in `style` attributes are not reported. Diagnostics of documents in frames are not reported either. ## It looks different from Chrome Fagus aims to print like Chrome on Linux. When a PDF differs from Chrome's, check these first. - **Fonts.** Chrome uses the fonts installed on the machine; Fagus does not by default, so that every machine prints the same. A family Fagus does not have falls back, in the end to the built-in Inter. Load the fonts with `@font-face`, put them in a font directory, or turn on `systemFonts` ([fonts.md](fonts.md)). Look for `resource.not-loaded` diagnostics of fonts. - **Paper size.** Without `@page { size }`, Fagus prints A4; Chrome uses the paper size of its print settings, which is Letter in the United States. Set the size in the document: `@page { size: A4 }` or `@page { size: letter }`. - **Margins.** Chrome's print dialog has its own margin settings. Set `@page { margin: … }` in the document and choose "Default" margins in Chrome to compare. - **Print media.** Fagus applies `@media print` rules and never `@media screen` ones, as Chrome does when it prints. A page that looks right in the browser window can differ in print: compare with Chrome's print preview, not with the window. Tailwind's `print:` variants apply. - **Width of the page.** Media queries and viewport units see the page area, not a browser window: A4 with Fagus's default margins is about 720 px wide, below Tailwind's `md` breakpoint (768 px). In Chrome's print preview, the page area is below it too. - **Backgrounds.** Fagus prints backgrounds and shadows. Turn on "Background graphics" in Chrome's print dialog to compare. - **Headers and footers.** Chrome adds the date, title and URL in its own headers and footers; turn them off in the print dialog. Fagus prints only the margin boxes of `@page`. - **Scripts.** Fagus runs no JavaScript. Content that scripts create in the browser (charts, client-side templates) is missing; render it on the server. - **Remote resources.** Images, fonts and stylesheets with `https://` URLs are not loaded ([resources.md](resources.md)). - **Form controls.** Fagus writes the texts of form controls (button labels, date formats) in the language of the control's `lang`, else the engine's `locale`; Chrome writes them in the language of its user interface. [css.md](css.md) lists where Fagus deliberately differs from Chrome, and [paged-media.md](paged-media.md) describes pages, margins and headers. ## FAQ ### How do I add page numbers, headers and footers? With `@page` margin boxes in the document. A running element repeats an element of the document in a margin box: ```css @page { @top-left { content: element(letterhead); } @bottom-right { content: "Page " counter(page) " of " counter(pages); } } .letterhead { position: running(letterhead); } ``` See [paged-media.md](paged-media.md). ### How do I force a page break? ```css .page-break { break-before: page; } ``` ### Can I fetch images from a URL? Not through Fagus. Hand them over with `resource()`, or answer the URLs with a `resolver()` that fetches what you allow ([resources.md](resources.md#answer-requests-with-resolver)). ### Can Fagus render a page of my running site? No. Fagus renders HTML that you give it. Render the view on the server (in Laravel, `Fagus::view()`), and make its files available through the base directory. ### Migrating from Dompdf Dompdf supports CSS 2.1 with some additions, without flex or grid. With Fagus, layouts with flex, grid, `calc()` and custom properties work as in Chrome, so the table-based workarounds can go. | Dompdf | Fagus | |---|---| | `$dompdf->loadHtml($html); $dompdf->render(); $dompdf->output()` | `Fagus::html($html)->render()->bytes()` | | `$dompdf->setPaper('A4', 'landscape')` | `@page { size: A4 landscape }` | | `$dompdf->stream('invoice.pdf')` | `Fagus::html($html)->name('invoice.pdf')->inline()` (Laravel), or send `bytes()` | | `chroot` | `baseDirectory()` and `root()` | | `isRemoteEnabled` | not available; `resource()` or `resolver()` | | `<script type="text/php">` for page numbers | `counter(page)` and `counter(pages)` in `@page` margin boxes | | `isPhpEnabled`, `isJavascriptEnabled` | not available | | barryvdh/laravel-dompdf: `Pdf::loadView('invoice', $data)->download('invoice.pdf')` | `Fagus::view('invoice', $data)->download('invoice.pdf')` | | `->stream()` | `->inline()`, or return the `PendingPdf` | | `->save($path)` | `->save($path)`, or `->store($path, $disk)` | Fonts that Dompdf loaded from `@font-face` load the same way; fonts registered in its font cache go into a font directory. ### Migrating from mPDF mPDF has its own HTML and CSS support, with page features written as custom tags and placeholders. Fagus uses standard CSS for them. | mPDF | Fagus | |---|---| | `new Mpdf(['format' => 'A4', 'margin_left' => 20, …])` | `@page { size: A4; margin: 20mm }` | | `$mpdf->WriteHTML($html); $mpdf->Output('invoice.pdf', 'F')` | `Fagus::html($html)->save('invoice.pdf')` | | `$mpdf->Output('', 'S')` | `Fagus::html($html)->render()->bytes()` | | `SetHTMLHeader()`, `SetHTMLFooter()`, `<htmlpageheader>` | `@page` margin boxes with running elements | | `{PAGENO}`, `{nbpg}` | `counter(page)`, `counter(pages)` | | `<pagebreak>` | `break-before: page` | | `PDFA`, `PDFAauto` | `pdfA('3b')` | | `SetAssociatedFiles()` | `attach()` or `facturX()` | | `fontDir`, `fontdata` | `@font-face`, or `fontDirectories` on the engine | | `SetTitle()`, `SetAuthor()` | `<title>`, `<meta name="author">` | | `SetWatermarkText()` | a positioned element or a background in the document | ### Migrating from Browsershot, Snappy or other browser-based tools Browsershot (and spatie/laravel-pdf on top of it) runs Chrome through Puppeteer and Node; Snappy runs wkhtmltopdf, an old WebKit. Fagus needs neither. HTML and CSS that print well in Chrome print the same in Fagus; what changes is everything around them: | Browsershot / laravel-pdf / Snappy | Fagus | |---|---| | `Browsershot::html($html)->format('A4')->margins(…)->save('x.pdf')` | `@page { size: A4; margin: … }` and `Fagus::html($html)->save('x.pdf')` | | `Pdf::view('invoice', $data)->format('a4')->name('invoice.pdf')` | `Fagus::view('invoice', $data)->name('invoice.pdf')` | | `->showBackground()` | not needed: backgrounds always print | | `->headerHtml()`, `->footerHtml()`, `--header-html` with `pageNumber` and `totalPages` | `@page` margin boxes with `counter(page)` and `counter(pages)` | | `->emulateMedia('screen')` | not available: Fagus applies print styles; move rules out of `@media screen` | | `->waitUntilNetworkIdle()`, `->setDelay()`, JavaScript | not available: no network, no scripts | | `Browsershot::url('https://…')`, `$snappy->generate($url, …)` | render the HTML yourself and pass it to `Fagus::html()` | | `$snappy->getOutputFromHtml($html)` | `Fagus::html($html)->render()->bytes()` | | Assets loaded from the running site | files through `baseDirectory()`, or `resource()` and `resolver()` | Remove Chrome, Node, Puppeteer or wkhtmltopdf from the servers once nothing else needs them. <!-- Source: https://fagus.niklasforst.de/docs/css --> # CSS reference Fagus lays out HTML and CSS the way Chrome prints it (Chrome 157 on Linux is the reference). This page lists what Fagus supports, grouped by topic, with the details that matter in print and the places where Fagus differs from Chrome or has no support. Page size, margins, headers, footers and page breaks have a page of their own: [Paged media](paged-media.md). Fonts are described in [Fonts](fonts.md). A rule of thumb: if Chrome's print preview shows it, Fagus renders it the same way. Where this page says "as in Chrome", Fagus follows Chrome's behavior in print, which is not always what the specification says. ## Find out what was ignored A declaration that Fagus cannot use is dropped and reported as a diagnostic with its position in the stylesheet, like the console of a browser. Declarations in `style` attributes are reported too, with the line of the element in the HTML, once for each different attribute: ```php use Fagus\Fagus; $pdf = Fagus::html($html)->render(); foreach ($pdf->diagnostics() as $diagnostic) { echo $diagnostic, "\n"; // <style> 1:12:3: warning[css.unknown-property]: unknown property `paint-order`; the declaration is ignored // html:40: warning[css.unknown-property]: `style` attribute of <p>: unknown property `colr`; the declaration is ignored } ``` `->strict()` turns these warnings into a `RenderException`, which is useful in tests. The codes you will see for CSS: | Code | Meaning | |---|---| | `css.unknown-property` | A property Fagus does not know. | | `css.invalid-value` | A known property with a value Fagus does not accept (as Chrome would not either). | | `css.parse-error` | A rule or at-rule that does not parse, such as an unknown at-rule. | | `css.unparsable` | A value that could not be read safely and was left out. | | `css.too-deep` | A stylesheet nested more than 256 levels deep. | | `resource.not-loaded` | A stylesheet, image or font that could not be loaded. | Properties that have no effect in print are dropped without a diagnostic: `transition-*`, `animation-*` (see [Animations](#animations-and-transitions)), `cursor`, `pointer-events`, `user-select`, `touch-action`, `resize`, `caret-color`, `scroll-*`, `overscroll-*`, `scrollbar-*`, `view-transition-*`, `text-size-adjust`, Microsoft Office's `mso-*` properties, and vendor-prefixed properties (`-webkit-`, `-moz-`, `-ms-`, `-o-`) other than the ones listed on this page. ## Stylesheets - `<style>` elements, `style` attributes and `<link rel="stylesheet">`. - `@import`, also with media queries, `supports()` conditions and `layer()`, up to eight levels deep. A stylesheet that cannot be loaded is reported. - Relative URLs in a linked or imported stylesheet resolve against that stylesheet, as in browsers. - Stylesheets passed with `->stylesheet($css)` in PHP apply after the document's own styles. Stylesheets, fonts and images come only from the places a document may read: `data:` URLs, resources handed over with `->resource()`, the `->resolver()` callback, and files inside the base directory or root. Fagus never loads anything from the network (see [Resources](resources.md)). ### HTML and its presentational attributes Documents are parsed as HTML5, as browsers parse them. A document without a doctype is rendered in quirks mode, with the quirks Chrome applies (line height quirk, table and form rules, full-height `html` and `body`, hashless colors and unitless lengths where Chrome takes them). XHTML is parsed as XML with `Fagus::xhtml()` (or a `.xhtml` file on the command line). The presentational attributes of older templates work as in Chrome and lose against any CSS: `width`, `height`, `align`, `valign`, `bgcolor` and `nowrap` on tables and their parts; `cellspacing`, `cellpadding`, `border`, `bordercolor`, `frame` and `rules` on tables; `color`, `face` and `size` on `<font>`; `size`, `width`, `color` and `noshade` on `<hr>`; `align`, `border`, `hspace` and `vspace` on images; `align` on blocks and `<center>`; `type` on lists; `bgcolor`, `text` and the margin attributes of `<body>`; `<br clear>`. Templates written for dompdf or mPDF with table layouts render as in Chrome. ## Selectors and the cascade **Works:** - All selectors of CSS Selectors 4 that make sense in a static document: type, class, id, universal, attribute selectors with all operators and the `i`/`s` flags, all combinators, `:is()`, `:where()`, `:not()`, `:has()` (also with sibling and child relations), `:nth-child(… of S)`, `:nth-last-child()`, `:nth-of-type()`, `:first-child`, `:last-child`, `:only-child`, `:empty`, `:root`, `:scope`, `:lang()`, `:dir()`, `:link`, `:any-link`, `:defined`. - Form states: `:checked`, `:default`, `:disabled`, `:enabled`, `:required`, `:optional`, `:read-only`, `:read-write`, `:placeholder-shown`, `:indeterminate`, `:open`, `:closed`, and `:valid`, `:invalid`, `:in-range`, `:out-of-range` with real constraint validation (including `pattern`). - Pseudo-elements: `::before`, `::after`, `::marker`, `::first-letter`, `::first-line`, `::placeholder`, the `::-webkit-` parts of progress bars, meters and range sliders, and `::scroll-marker`, `::scroll-marker-group` and `::scroll-button()` as far as Chrome prints them. - CSS nesting (`&`, nested rules and nested at-rules). - The cascade with origins, `!important`, specificity, order, inline styles, cascade layers (`@layer`, also anonymous and nested, with `revert-layer`) and `@scope` (with `:scope`, limits, proximity, and the implicit scope of a `<style>` element). - CSS-wide keywords `initial`, `inherit`, `unset`, `revert`, `revert-layer`, and `all`. **Differs or not supported:** - User-action and time states never match: `:hover`, `:focus`, `:focus-visible`, `:active`, `:visited`, `:target` (except in SVG fragments), `:playing` and the like. - Shadow DOM selectors (`:host`, `::slotted()`, `::part()`) match nothing; there is no shadow DOM without scripts. ## Values and units **Works:** - Custom properties and `var()` with fallbacks; `@property` with syntax checking of registered properties, `inherits` and `initial-value`. - Math functions: `calc()`, `min()`, `max()`, `clamp()`, `round()` (with `nearest`, `up`, `down`, `to-zero`), `mod()`, `rem()`, `abs()`, `sign()`, `hypot()`, `pow()`, `sqrt()`, `exp()`, `log()`, trigonometric functions, division of typed values, and `progress()`. A calculation that comes to NaN is 0. - `calc-size()` for widths and heights, and the sizing keywords `min-content`, `max-content`, `fit-content`, `stretch` (also `-webkit-fill-available`). - Newer functions computed per element: `if()` with `media()`, `supports()` and `style()`; typed `attr()`; `sibling-index()`, `sibling-count()`; `env()`. - Absolute units: `px`, `pt`, `pc`, `in`, `cm`, `mm`, `Q`. One CSS pixel is 1/96 inch. - Font-relative units: `em`, `rem`, `ex`, `rex`, `ch`, `rch`, `cap`, `rcap`, `ic`, `ric`, `lh`, `rlh`, measured in the first available font of the element's language, as in Chrome. - Viewport units (`vw`, `vh`, `vmin`, `vmax`, `vi`, `vb` and the `s`, `l`, `d` variants) refer to the page area of the first page. - Container query units (`cqw`, `cqh`, `cqi`, `cqb`, `cqmin`, `cqmax`). - `zoom`, as Chrome implements it, including on the root element. **Details:** Lengths are cut to Chrome's layout unit of 1/64 pixel and border widths to whole pixels, so a border of `0.5pt` is drawn 1px wide and `1.5px` is 1px, as in Chrome. A unitless zero next to lengths in `min()`, `max()` and `clamp()` is invalid, as in Chrome. More than eight nested math functions make a value invalid. ## Colors **Works:** - Named colors, hex notation, `rgb()`, `hsl()`, `hwb()`, `lab()`, `lch()`, `oklab()`, `oklch()` and `color()` with the predefined spaces (`srgb`, `display-p3`, `display-p3-linear`, `a98-rgb`, `prophoto-rgb`, `rec2020`, `xyz` …). - `color-mix()`, relative colors (`oklch(from var(--brand) l c h / 50%)`, also with `calc()` on the channels), `currentcolor`, `light-dark()`, `contrast-color()`, and the system colors. - `color-scheme` (including `<meta name="color-scheme">`): a dark root gives a dark page and dark form controls, as in Chrome. **Details:** Colors outside sRGB are clipped to sRGB channel by channel, as Chrome clips them for print. `prefers-color-scheme` is `light`. ## The box model **Works:** `margin`, `padding`, `border`, `width`, `height` with their minimums and maximums, `box-sizing`, `aspect-ratio`, logical properties (`margin-inline`, `inset-block-start`, `border-start-end-radius` …) in every writing mode, margin collapsing, `margin-trim` for block containers, `outline` with `outline-offset` (and `outline-style: auto` as Chrome's focus ring), `visibility` (including `collapse` on table rows and columns), `opacity`. **Details:** Percentage heights resolve against the containing block where its height does not depend on the content: the page area for the root element, so a page laid out with `html, body { height: 100% }` fills the page. `border-style: solid` without a width is `medium` (3px), as in Chrome. ## Display and layout ### Block and inline **Works:** block and inline formatting contexts, `inline-block`, `flow-root`, `display: contents`, `list-item` (also `inline list-item`), every `vertical-align` value, inline boxes with padding, borders and backgrounds across lines, `box-decoration-break: clone` (and its `-webkit-` alias), `justify-self`/`justify-items` on block-level boxes, and `display: -webkit-box` with the old `-webkit-box-*` properties as Blink lays it out. **Not supported:** `display: run-in` is invalid, as in Chrome. ### Floats **Works:** `float` (`left`, `right`, `inline-start`, `inline-end`) and `clear` as in CSS 2.1, floats that break across pages and columns, and `shape-outside` (basic shapes, `path()`, `xywh()`, `rect()`, `shape()`, box keywords, images and gradients with `shape-image-threshold`, and `shape-margin`). **Not supported:** `float: footnote` (an invalid value, as in Chrome, which leaves an earlier `float` in force) and the other footnote properties (see [Paged media](paged-media.md#footnotes)). ### Flexbox **Works:** all of CSS Flexbox: direction and wrapping (with `row-reverse`, `column-reverse`, `wrap-reverse`), `flex-grow`, `flex-shrink`, `flex-basis` (with `content` and keywords), `order`, `gap`, every alignment property with `safe` and `unsafe`, `baseline` and `last baseline` alignment, auto margins, the automatic minimum size of items, and `flex-wrap: balance`. Flex containers break across pages between lines and inside items. ### Grid **Works:** CSS Grid 1 and 2: explicit and implicit tracks, `fr`, `minmax()`, `fit-content()`, `repeat()` with `auto-fill` and `auto-fit`, named lines and areas (`grid-template-areas`, `grid-template`, `grid`), auto-placement with `dense` and `grid-auto-flow: column`, `subgrid` (with line names), gaps (also the old `grid-gap`), alignment including baselines, and absolutely positioned items placed by grid lines. Grids break across pages between rows and inside items. **Limits:** at most 1000 explicit tracks, line numbers and spans are clamped to 1000 (browsers clamp too), and items are placed in at most 10,000 rows. **Not supported:** `display: grid-lanes` (masonry) is invalid, as in Chrome 157 without experimental features. ### Multi-column layout **Works:** `columns`, `column-count`, `column-width`, `column-gap`, `column-rule`, `column-fill` (balanced by default), `column-span: all`, `break-before`/`break-after: column`, `column-height` and `column-wrap` (rows of columns), and nested multi-column containers. Columns continue on the next page when they are full. ### Tables **Works:** `table-layout: auto` and `fixed` with Chrome's column width algorithm, `rowspan` and `colspan`, `<col>` and `<colgroup>` widths and backgrounds, `border-collapse` (collapsed borders resolved as Chrome resolves them) and `border-spacing`, captions (`caption-side`), `empty-cells`, `vertical-align` in cells, anonymous table boxes as Chrome generates them, and CSS table displays on any element. **In print:** `<thead>` and `<tfoot>` repeat on every page where the table breaks; rows that do not fit break inside their cells; `counter-increment` and `string-set` on rows work. See [Paged media](paged-media.md#repeat-table-headers-on-every-page) and the carry-over rows of [Extensions](extensions.md). **Differs:** cells with `vertical-align: baseline` sit at the top of their row, as in Chrome's print of tables that may break across pages. ### Positioning **Works:** `relative`, `absolute`, `fixed`, `sticky`, `z-index` and stacking contexts, inset properties, `clip: rect()`, and anchor positioning (`anchor-name`, `position-anchor`, `anchor()`, `anchor-size()`, `position-area`, `anchor-center`, `anchor-scope`, `@position-try`, `position-try-fallbacks`, `position-try-order`, `position-visibility`). **In print:** a `position: fixed` box repeats on every page, as in Chrome. Absolutely positioned boxes break across pages. Sticky boxes stick in Chrome's print window. ### Overflow and containment **Works:** `overflow` (`visible`, `hidden`, `clip`, `scroll`, `auto`, also per axis), `overflow-clip-margin`, `text-overflow` (`ellipsis` and a string), `-webkit-line-clamp` (Tailwind's `line-clamp-*`), `contain`, `content-visibility: hidden`, `contain-intrinsic-size`, `container-type`, `container-name`, `will-change`. **Details:** content of a scroll container is printed as far as the box shows it, without scrolling. Content wider than the page area makes Fagus lay the page out again and scale it down, as Chrome's shrink-to-fit does (to at most 1.5 times the page width). **Not supported:** the unprefixed `line-clamp` is ignored, as Chrome 157 ignores it; use `-webkit-line-clamp` with `display: -webkit-box`. ### Container queries `@container` with size features (`width`, `height`, `inline-size`, `block-size`, `aspect-ratio`, `orientation`, ranges) and style queries (`style(--x: y)`). Fagus finds the container sizes in a first layout and lays the document out again with them. ## Backgrounds, borders and shadows **Works:** - Several background layers with `background-image`, `-size`, `-position`, `-repeat` (`space` and `round` too), `-origin`, `-clip` (including `text` and `border-area`), `-attachment` (`fixed` is placed as Chrome places it in print, `local` in the scrollable overflow) and `background-blend-mode`. - Gradients: `linear-gradient()`, `radial-gradient()`, `conic-gradient()` and their repeating forms, with color hints and interpolation methods (`in oklch longer hue`); `image()`, `image-set()` (and `-webkit-image-set()`), and `light-dark()` images. - Borders in all styles (`solid`, `dashed`, `dotted`, `double`, `groove`, `ridge`, `inset`, `outset`), drawn with Chrome's dash patterns, miters and 3D shades; `border-radius` with elliptical corners; `corner-shape` (with `superellipse()`); `border-shape`; `border-image` with all its longhands. - `box-shadow` (outer and inset, blur and spread) and `text-shadow`. **Details:** gradients are written as vector shadings in the PDF and stay sharp at any zoom. As in Chrome's PDF output, the colors between two stops are interpolated in sRGB whatever color space the gradient names, while color hints follow the named space. A background on the root element (or on `body` when the root has none) covers the whole canvas on every page. Backgrounds of boxes broken across pages continue where the page before left off; with `box-decoration-break: clone` each part starts anew. ## Effects **Works:** - 2D and 3D transforms: `transform` with all functions, the individual `translate`, `rotate` and `scale`, `transform-origin`, `transform-box`, `transform-style: preserve-3d`, `perspective` and `perspective-origin`. 3D transforms are flattened onto the page as Chrome prints them. - `filter` with all CSS filter functions and SVG filter references (`url(#filter)`). - `mix-blend-mode`, `isolation`, `background-blend-mode`, as PDF blend modes. - `mask` and its longhands (also `-webkit-mask-*`): gradient, raster and SVG image layers, `mask-mode`, `mask-composite`, `mask-type`, and SVG `<mask>` references. - `clip-path` with `inset()`, `circle()`, `ellipse()`, `polygon()`, `path()`, `xywh()`, `rect()`, `shape()`, a box keyword, or an SVG `<clipPath>` reference. **Differs from Chrome:** Chrome prints filtered content as an image; Fagus keeps text and shapes as vectors where the filter allows it (color filters, `drop-shadow()`, `opacity()`), so the text stays searchable. Blurs and SVG filter primitives without a CSS equivalent (turbulence, lighting, morphology, displacement) are rasterized at 300 ppi, as Chrome prints them. **Not supported:** `backdrop-filter` does not filter what lies behind the box; the box is only drawn as an isolated group. ## Images and replaced content **Works:** - `<img>` with PNG, JPEG, GIF, WebP and SVG. SVG stays vector graphics. JPEG, PNG and WebP are turned as their EXIF orientation says (`image-orientation: none` turns this off). - `srcset`, `sizes` and `<picture>` with `media` and `type`, chosen as Chrome chooses them when it loads the page (on screen, before printing). `(min-resolution)` queries see 300 dpi. - `object-fit` and `object-position`, `image-rendering: pixelated` and `crisp-edges`. - Inline `<svg>`, drawn as vectors in the text's color (`currentColor`) and font, styled by the document's CSS (`fill`, `stroke`, Tailwind's `fill-current`), with `<use>` across documents, `<foreignObject>` HTML, masks, clips, filters, text on paths and `vector-effect`. - `content: url(…)` on an element replaces it with the image (as print stylesheets swap logos); in `::before` and `::after` it shows the image. - `<iframe>` (`srcdoc` or `src`), `<object>` and `<embed>` showing an HTML document, an image or a text file; frames are laid out at their own size, unpaginated and clipped, as Chrome prints them, at most 8 levels deep. `frame-sizing: content-height` sizes a frame to its document. - `<video>` shows its poster, `<canvas>` is a transparent box. - MathML Core: `<math>` with fractions, roots, scripts, operators stretched through the font's MATH table, and tables. The generic family `math` finds a math font. **Differs:** AVIF and JPEG XL are skipped in `<picture>` and `image-set()`; use one of the formats above. An image that does not load shows its alt text after Chrome's broken-image icon. An image whose data does not decode is left out with an `image.broken` warning. **Not supported:** scripts in SVG and in frames do not run. Fagus loads no media other than images. ## Text ### White space and line breaking **Works:** `white-space` with its longhands `white-space-collapse` and `text-wrap-mode`, `text-wrap` (`wrap`, `nowrap`, `balance`, `pretty`, `stable`) with Chrome's line breakers, `overflow-wrap` (`anywhere`, `break-word`, also as `word-wrap`), `word-break` (`break-all`, `keep-all`, `auto-phrase` for Japanese, and the old `break-word`), `line-break`, `<wbr>`, soft hyphens (`­`), `tab-size`, and `hanging` and `each-line` in `text-indent`. **Details:** lines break where Chrome breaks them: between ASCII characters by Blink's own table (after `-` and `?`, not after the slashes and dots of a URL), elsewhere by the Unicode line breaking algorithm. Thai, Lao, Khmer and Myanmar break between dictionary words. ### Hyphenation `hyphens: auto` hyphenates with Chrome's dictionaries and rules on Linux, the same on every system, in the language of the text's `lang` attribute. Without `lang` nothing is hyphenated. There are dictionaries for Afrikaans, Assamese, Belarusian, Bengali, Bulgarian, Czech, Church Slavonic, Welsh, Danish, German (1901, 1996 and Swiss), Greek, English (US and UK), Spanish, Estonian, Basque, French, Irish, Galician, Gujarati, Hindi, Croatian, Italian, Georgian, Kannada, Latin, Lithuanian, Malayalam, Mongolian, Marathi, Ethiopic scripts, Norwegian (Bokmål and Nynorsk), Dutch, Odia, Punjabi, Portuguese, Slovak, Slovenian, Albanian, Swedish, Tamil, Telugu, Turkmen and Ukrainian. Hungarian, Armenian, Latvian and Russian are left out for their licenses. `hyphenate-character` and `hyphenate-limit-chars` work. As in Chrome, capitalized English words and the last word of a paragraph are not hyphenated. The hyphen at a break is a soft hyphen in the text of the PDF, so copied text and screen readers get the whole word. ### Alignment and spacing **Works:** `text-align` (including `justify`, `start`, `end`, `match-parent`), `text-align-last`, `text-justify` (`auto`, `none`, `inter-word`, `inter-character`), `text-indent`, `letter-spacing` and `word-spacing` (also as percentages), `text-transform` (with language rules for Greek and Turkish, and `math-auto`), `initial-letter`, `text-box-trim`, `text-box-edge` and `text-box`, `text-fit`. **Not supported:** `text-align: justify-all` is invalid, as in Chrome; use `text-align: justify` with `text-align-last: justify`. `text-justify: distribute` is invalid. ### Decorations and emphasis **Works:** `text-decoration` with `-line`, `-style` (`solid`, `double`, `dotted`, `dashed`, `wavy`), `-color`, `-thickness`, `text-underline-offset`, `text-underline-position`, `text-decoration-skip-ink`; `-webkit-text-fill-color`; emphasis marks (`text-emphasis` and its longhands). **Not supported:** `-webkit-text-stroke` and `paint-order` for HTML text. ### Writing modes and bidirectional text **Works:** `writing-mode` (`horizontal-tb`, `vertical-rl`, `vertical-lr`, `sideways-rl`, `sideways-lr`, the SVG names and `-webkit-writing-mode`), `text-orientation`, `text-combine-upright: all`, `direction`, `unicode-bidi`, `dir` and `dir=auto`, `<bdi>` and `<bdo>`. Logical properties, tables, flex, grid and columns follow right-to-left and vertical text. Hebrew and Arabic copy out of the PDF in reading order. ### East Asian text and ruby **Works:** `<ruby>`, `<rt>` and `<rp>` with `ruby-position` and `ruby-align`, nested and double-sided ruby; `text-spacing-trim`, `text-autospace`, and justification between ideographs and kana, as in Chrome. Japanese and Chinese stand upright in vertical text with the vertical forms of the font. **Not supported:** `ruby-overhang`, `text-spacing`. ### Scripts Text is shaped with HarfBuzz rules in its script and language: Arabic and other joining scripts join (also across inline elements), Indic scripts form their clusters, and the `lang` attribute selects a font's localized forms. Emoji sequences use a color font where one is available. ## Fonts `@font-face` (TTF, OTF, WOFF, WOFF2, variable fonts, `unicode-range`, `local()`, `size-adjust` and the metric overrides), `font-family`, `font-weight`, `font-style` (italic and oblique angles), `font-stretch`, `font-size` (with `math`), `font-size-adjust`, `font-synthesis`, `font-kerning`, `font-optical-sizing`, `font-variation-settings`, `font-feature-settings`, `font-variant` with all its longhands, `font-palette` with `@font-palette-values`, and `text-rendering`. See [Fonts](fonts.md) for where fonts come from and how fallback works. **Not supported:** `@font-feature-values` (so `font-variant-alternates: styleset(name)` has no named sets). ## Lists and counters **Works:** `list-style-type` with all of Chrome's predefined counter styles, `list-style-position`, `list-style-image`, `::marker`, `@counter-style` (all systems and descriptors), `counter-reset`, `counter-increment`, `counter-set`, `counter()` and `counters()`, and the `start`, `reversed` and `value` attributes. **Details:** `disc`, `circle`, `square` and the disclosure markers are drawn as Chrome's shapes, not as glyphs, at Chrome's distance from the text. ## Generated content **Works:** `content` on `::before`, `::after` and `::marker` with strings, `attr()`, `counter()`, `counters()`, `open-quote`/`close-quote` (with `quotes`, and `auto` quotes by language), images (`url()`, gradients) and alternative text after `/`. In print, `content` also takes the functions of CSS Generated Content for Paged Media: `string()`, `element()`, `target-counter()`, `target-counters()`, `target-text()` and `leader()` (see [Paged media](paged-media.md)). `<q>` shows quotation marks of the language around it. ## Form controls Form controls print as Chrome prints them: text, password, number, email, date and time fields, checkboxes and radio buttons (with `accent-color`), buttons, `<select>` and list boxes, `<textarea>`, `<progress>`, `<meter>`, range sliders, color and file inputs, `<fieldset>` with `<legend>`, `<details>` and `<summary>`, `<dialog>`. `appearance: none` or author borders and backgrounds give the CSS look instead of the native one, as in Chrome. `field-sizing: content` works. **Differs from Chrome:** the texts controls show of their own (the labels of submit and reset buttons, "Choose File", date placeholders such as `mm/dd/yyyy`, the decimal separator) are written in the language of the control's `lang`, else the engine's `locale`, else American English. Chrome writes them in the language of its user interface. See [Fonts](fonts.md#the-language-of-form-controls). ## Media queries and feature queries Media queries are evaluated for print: | Feature | Value in Fagus | |---|---| | media type | `print` (`screen` rules do not apply) | | `width`, `height`, `aspect-ratio`, `orientation` | the page area of the first page | | `resolution` | 300 dpi (96 dpi while choosing `<picture>` sources, as Chrome chooses them on screen) | | `color` | 8; `monochrome`, `color-index` and `grid` are 0 | | `color-gamut` | `srgb` | | `dynamic-range` | `standard` | | `overflow-block` | `paged` | | `prefers-color-scheme` | `light` | | `prefers-reduced-motion`, `prefers-contrast`, `prefers-reduced-transparency` | `no-preference` | | `hover`, `any-hover` | `hover` | | `pointer`, `any-pointer` | `fine` | | `scripting`, `update`, `overflow-inline`, `forced-colors` | `none` | | `display-mode` | `browser` | A Tailwind document with `print:` variants or a stylesheet with `@media print { … }` therefore gets its print styles. `@supports` knows the properties and values Fagus parses (also its own, such as `-fagus-repeat`), and answers `selector()`, `font-tech()`, `font-format()` and `at-rule()` as Chrome does. ## Animations and transitions Scripts do not run, so nothing moves. CSS animations print at time zero as in Chrome: a fade-in prints transparent, a slide-in where it starts, a negative `animation-delay` that far into the animation, with fill modes, direction and easing. Transitions have no effect. If a page uses animations to reveal content, turn them off for print: ```css @media print { * { animation: none !important; } } ``` ## Not supported A short list of what Fagus does not do. Most of it is also absent in Chrome's print. - **Scripts:** `<script>` does not run, in the document, in SVG or in frames. `<noscript>` content is shown. Content that JavaScript would build (charts, client-side rendering) must be rendered on the server first, for example as inline SVG. - **Network:** nothing is loaded from `http:` or `https:` URLs; hand resources over instead (see [Resources](resources.md)). - **Interaction:** `:hover`, `:focus`, `:active`, `:visited` never match; transitions do nothing; animations print their state at time zero. - **Footnotes:** `float: footnote`, `@footnote`, `footnote-display`, `footnote-policy` and `float-reference` (see [Paged media](paged-media.md#footnotes)). - **Pages:** `@page :nth()` (see [Paged media](paged-media.md)). - **Layout:** `display: grid-lanes` (masonry), `display: run-in`, unprefixed `line-clamp`, `shape-inside`, `block-step`. - **Text:** `text-align: justify-all`, `-webkit-text-stroke`, `paint-order` for HTML text, `text-spacing`, `ruby-overhang`, `hanging-punctuation`, `@font-feature-values`. - **Effects:** `backdrop-filter` (no filtering of the backdrop), `cross-fade()`, `element()` as an image. - **Images:** AVIF, JPEG XL, BMP, TIFF and ICO. - **At-rules:** `@function`, `@starting-style` and `@view-transition` have no effect. <!-- Source: https://fagus.niklasforst.de/docs/paged-media --> # Paged media Fagus takes the page size, margins, headers, footers and page breaks from the document's CSS, as a browser does when it prints. There are no PHP options for them: everything on this page goes into the stylesheet. This keeps the layout in one place and lets you check a template in Chrome's print preview, which shows the same result for nearly everything here. Where Fagus differs from Chrome, this page says so. All examples are complete documents. Render one with: ```php use Fagus\Fagus; Fagus::html(file_get_contents('example.html'))->save('example.pdf'); ``` ## Set the page size and margins ```html <!doctype html> <html lang="en"> <head> <style> @page { size: A4; margin: 20mm 18mm 25mm; } @page :first { margin-top: 45mm; } </style> </head> <body> <h1>Invoice</h1> </body> </html> ``` `size` takes: - a name: `A5`, `A4`, `A3`, `B5`, `B4`, `JIS-B5`, `JIS-B4`, `letter`, `legal`, `ledger`, optionally with `portrait` or `landscape` (`size: A4 landscape`); - one length for a square page, or two for width and height (`size: 80mm 200mm` for a receipt); `calc()`, `min()`, `max()`, `clamp()`, `em` and viewport units work; - `auto`, the default page. Fagus parses `size` with Chrome's grammar: values Chrome does not accept keep the size that applied before, without a warning. `A6` is one of them, as are `80mm auto` and three lengths. For A6, write `size: 105mm 148mm`. **Defaults.** A page without `size` is A4. Chrome takes the paper size of the printer or of the system's region (Letter in the United States). A server has neither, so Fagus uses A4, so that a document prints the same on every machine. Write `size: letter` for US documents. A page without `margin` has Chrome's default margins of 28pt (about 1cm) on every side. The `body` element keeps its default margin of 8px inside the page area, as in a browser; most print stylesheets set `body { margin: 0 }`. **Details:** - Percentage margins refer to the page width for left and right and to the page height for top and bottom. - `em` and `rem` in `@page` refer to the root element's font size. - As in Chrome, each side of the PDF page is rounded to whole points and then to a 1/300 inch grid: A4 is 594.96 × 841.92pt. - `width`, `height`, their minimums and maximums, `padding` and `border` of `@page` size the page box as in Chrome; `padding` and `border` lie inside the page margins. - `@page` and its margin boxes take only the properties Chrome allows there. `transform`, `opacity`, `font-variant-*` and `font-feature-settings` are ignored. - Content that reaches outside the page area is cut off at the page margins. Content wider than the page area makes Fagus lay the page out again on a wider area and scale it down, as Chrome's print does, by at most 1.5 times. ## Use different first, left and right pages `:first` matches the first page of the document. `:left` and `:right` match the pages of a two-sided document: a left-to-right document starts on a right page, a right-to-left one on a left page, as in Chrome. ```html <!doctype html> <html lang="en"> <head> <style> @page { size: A5; margin: 20mm; } @page :left { margin-left: 25mm; margin-right: 15mm; } @page :right { margin-left: 15mm; margin-right: 25mm; } @page :left { @bottom-left { content: counter(page); } } @page :right { @bottom-right { content: counter(page); } } section { break-before: page; } </style> </head> <body> <section>Page one is a right page.</section> <section>Page two is a left page.</section> <section>Page three is a right page.</section> </body> </html> ``` The more specific rule wins: a named page beats `:first` and `:blank`, which beat `:left` and `:right`. ### Start chapters on a right page `break-before: right` (or `left`, `recto`, `verso`, and the same values of `break-after`) starts a new page on that side. Where the next page would be on the other side, Fagus inserts a blank page first, and `@page :blank` matches it: ```css .chapter { break-before: right; } @page :blank { @top-center { content: none; } @bottom-center { content: "This page is intentionally left blank."; } } ``` - `recto` is a right page and `verso` a left page in a left-to-right document, the other way round in a right-to-left one. - A blank page has no content, but it counts: `counter(page)` and `counter(pages)` include it, and its margin boxes show what the `@page` rules for it say. It has the page name of the page after it. - Where the content starts with such a break (`break-before: left` on the first element), the first page is on that side, and the pages after alternate from there. This follows CSS Fragmentation and CSS Paged Media, as WeasyPrint does. Chrome treats these values like `page` and inserts no blank page, and it ignores `@page :blank` rules, so a template that relies on them prints differently in Chrome. **Not supported:** `@page :nth()`, as in Chrome. The rule is ignored and reported as a `css.parse-error` diagnostic. ## Give sections pages of their own The `page` property puts an element on pages with a name, which `@page name` rules style. Where the page name changes, a new page starts. ```html <!doctype html> <html lang="en"> <head> <style> @page { size: A4; margin: 20mm; } @page wide { size: A4 landscape; margin: 15mm; } .wide { page: wide; } </style> </head> <body> <p>Portrait text.</p> <section class="wide"> <table><!-- a wide table --></table> </section> <p>Portrait again.</p> </body> </html> ``` Named pages work with `:first`, `:left` and `:right` (`@page wide:left`). Page names keep their case, so `page: WordSection1` matches `@page WordSection1`, as in documents exported from Word. To print a landscape page turned onto a portrait sheet, so that all sheets of the PDF have the same orientation, add `page-orientation: rotate-left` (or `rotate-right`) to the named page. Links and bookmarks on the page turn with it. ```css @page wide { size: A4 landscape; page-orientation: rotate-left; } ``` ## Add a header and a footer The page margins hold 16 margin boxes: `@top-left-corner`, `@top-left`, `@top-center`, `@top-right`, `@top-right-corner`, `@right-top`, `@right-middle`, `@right-bottom`, `@bottom-right-corner`, `@bottom-right`, `@bottom-center`, `@bottom-left`, `@bottom-left-corner`, `@left-bottom`, `@left-middle` and `@left-top`. A margin box shows only when its `content` is not `none`. ```html <!doctype html> <html lang="en"> <head> <style> @page { margin: 25mm 20mm; @top-left { content: "ACME Inc."; font-size: 9pt; color: #555; } @top-right { content: "Annual report 2026"; font-size: 9pt; color: #555; } @bottom-center { content: "Page " counter(page) " of " counter(pages); font-size: 9pt; border-top: 0.5pt solid #999; } } @page :first { @top-left { content: none; } @top-right { content: none; } } section { break-before: page; } </style> </head> <body> <h1>Annual report 2026</h1> <section><h2>Revenue</h2></section> <section><h2>Outlook</h2></section> </body> </html> ``` Margin boxes are laid out as Chrome lays them out: - The boxes of an edge share its length by their content, as CSS Paged Media describes; `width`, `height` and margins of a margin box are honored. - Text is aligned as in Chrome's user agent stylesheet: `@top-left` to the left, `@top-center` to the center, `@top-right` to the right, and vertically in the middle. `text-align` and `vertical-align` change it. - Margin boxes take padding, borders, backgrounds and images (`content: url(logo.svg)`). - The font of a margin box does not inherit from `body`: set it in the margin box or on `@page`. The font family, size and color of `@page` are inherited by its margin boxes. **Fonts in margin boxes.** Chrome loads the faces of `@font-face` rules only while it lays out the document, so a face that the document's content never uses is missing in the margin boxes, and their text falls back to the next family. Fagus does the same. If your running head is set in an italic that the body text does not use, either use that face somewhere in the content or load the font from a font directory (see [Fonts](fonts.md#fonts-in-headers-and-footers)). ## Number the pages `counter(page)` is the number of the current page, `counter(pages)` the number of pages. Both take a counter style: ```html <!doctype html> <html lang="en"> <head> <style> @page { @bottom-right { content: counter(page); } } @page front { @bottom-right { content: counter(page, lower-roman); } } .preface { page: front; } section { break-before: page; } </style> </head> <body> <div class="preface"> <section>Preface</section> <section>Contents</section> </div> <section>Chapter 1</section> </body> </html> ``` This prints i, ii and 3. `counter-reset`, `counter-set` and `counter-increment` of the `page` counter in `@page` rules work as in Chrome: - `counter-increment: page 2` counts the page as two pages, and the pages after go on from there. `counter-increment: none` still counts the page as one. - `counter-set: page 1` sets the counter to 1 on the page, and the pages after go on from there: this is the way to start the numbering again. - `counter-reset: page 1` sets the counter only on the pages it matches: the pages after go on from the pages before, as if it had not been there. This is how Chrome does it. - In a margin box, these properties change the number that box shows. - On an element of the document, `counter-reset: page` and `counter-increment: page` do not change the page numbers. `counter(pages)` is always the number of pages. `counter(page)` in the content and `target-counter(..., page)` show the same number as the margin boxes. Use `counter(pages)` in margin boxes and in running elements (below). In the normal flow of the document and in `position: fixed` boxes, the number of pages is not known while the content is laid out, and `counter(pages)` comes out as 0 or empty. `counter(page)` works everywhere, also in `::before` and `::after` of content and in repeated table headers. ## Put HTML in the header and footer A margin box can show an element of the document: `position: running(name)` takes the element out of the flow, and `content: element(name)` places it in a margin box on every page. The element keeps its own styles, so it can be a flex or grid container, hold images and links, and show page numbers. ```html <!doctype html> <html lang="en"> <head> <style> @page { margin: 30mm 20mm 25mm; @top-center { content: element(letterhead); } @bottom-center { content: element(footer); } } .letterhead { position: running(letterhead); display: flex; justify-content: space-between; align-items: end; width: 100%; border-bottom: 1pt solid #1e3a8a; } .footer { position: running(footer); display: grid; grid-template-columns: 2fr 2fr 1fr; gap: 6mm; width: 100%; font-size: 7.5pt; color: #555; } .footer .page { text-align: right; } .footer .page::after { content: "Page " counter(page) " of " counter(pages); } section { break-before: page; } </style> </head> <body> <header class="letterhead"> <strong>ACME Inc.</strong> <span>1 Main Street, Springfield</span> </header> <footer class="footer"> <div>ACME Inc. · 1 Main Street · Springfield</div> <div>IBAN DE00 0000 0000 0000 0000 00</div> <div class="page"></div> </footer> <h1>Letter</h1> <section>Second page</section> </body> </html> ``` Place running elements at the start of the document, before the content of the first page: a running element shows on the page where it appears and on the pages after it. Several elements with the same running name can follow each other; `element(name, first)` (the default), `start`, `last` and `first-except` choose which one a page shows, as for `string()` below. A running element is laid out again on every page, with that page's number: a column sized by its content (`auto`) is as wide as "Page 10 of 12" on page 10. Chrome does not support running elements; it shows the element where it is in the document. ## Repeat a chapter title in the header Named strings copy text from the document into the margin boxes. `string-set` on an element sets the string, `string()` shows it. ```html <!doctype html> <html lang="en"> <head> <style> @page { @top-left { content: string(chapter); } @top-right { content: string(section, last); } } @page :first { @top-left { content: none; } } h2 { string-set: chapter content(); break-before: page; } h3 { string-set: section content(); } </style> </head> <body> <h1>Handbook</h1> <h2>Receiving</h2> <h3>Checking deliveries</h3> <h3>Storing goods</h3> <h2>Shipping</h2> <h3>Packing</h3> </body> </html> ``` `string-set` takes strings, `content()` (the element's text; also `content(before)`, `content(after)`, `content(first-letter)` and `content(marker)`), `attr()` and counters. `string()` takes a second argument for the case that the string is set several times on a page: | Value | Shows | |---|---| | `first` (default) | the first value set on the page, else the value from the pages before | | `start` | the value at the top of the page | | `last` | the last value set on the page | | `first-except` | nothing on the page where the value is set, the value on the pages after | `string()` also works in the generated content of the document, such as a table footer that shows a subtotal per page (see [Extensions](extensions.md)). ## Control page breaks ```html <!doctype html> <html lang="en"> <head> <style> h1, h2, h3 { break-after: avoid; } figure, blockquote, .address { break-inside: avoid; } p { orphans: 3; widows: 3; } .chapter { break-before: page; } </style> </head> <body> <h1>Offer</h1> <div class="address">ACME Inc.<br>1 Main Street<br>Springfield</div> <section class="chapter"><h2>Scope</h2><p>…</p></section> <section class="chapter"><h2>Terms and conditions</h2><p>…</p></section> </body> </html> ``` - `break-before` and `break-after`: `page` forces a break; `left`, `right`, `recto` and `verso` force one to a page of that side, after a blank page where needed (see [Start chapters on a right page](#start-chapters-on-a-right-page)); `avoid` and `avoid-page` avoid one; `column` and `avoid-column` do the same in columns. - `break-inside: avoid` keeps a box on one page if it fits. A box taller than a page breaks anyway. - `orphans` and `widows` (2 by default) set how many lines of a paragraph stay at the bottom and the top of a page. - The older `page-break-before`, `page-break-after` and `page-break-inside` work as aliases, and an empty `<div style="page-break-after: always"></div>` breaks the page, as in browsers. **Keep headings with their text.** Headings do not stay with what follows them by themselves. `h1, h2, h3 { break-after: avoid; }` moves a heading that would end a page to the next page together with the start of its paragraph. A `break-before` of a first child and a `break-after` of a last child pass on to the parent, since breaks fall between siblings. Fagus breaks pages where Chrome breaks them, including inside table rows, flex and grid items, floats and positioned boxes, so a template that paginates well in Chrome's print preview paginates the same way in Fagus. ## Repeat table headers on every page `<thead>` and `<tfoot>` repeat on every page a table breaks across. `tr { break-inside: avoid; }` keeps rows whole. ```html <!doctype html> <html lang="en"> <head> <style> @page { size: A5; margin: 15mm; } table { width: 100%; border-collapse: collapse; } th, td { padding: 1mm 2mm; border-bottom: 0.5pt solid #ccc; text-align: left; } .num { text-align: right; } tr { break-inside: avoid; } </style> </head> <body> <table> <thead> <tr><th>#</th><th>Item</th><th class="num">Amount</th></tr> </thead> <tfoot> <tr><td colspan="3">Prices in EUR</td></tr> </tfoot> <tbody> <tr><td>1</td><td>Item 1</td><td class="num">7.00</td></tr> <!-- … many more rows … --> </tbody> </table> </body> </html> ``` As in Chrome: - A header or footer group repeats only if it avoids breaks inside, which `<thead>` and `<tfoot>` do by default. A `display: table-header-group` of your own needs `break-inside: avoid` to repeat. - Headers and footers taller than a quarter of the page do not repeat. - A row that does not fit breaks inside its cells unless it has `break-inside: avoid`; the rest of its cells continue below the repeated header. - `counter-increment` and `string-set` work on rows, so `tbody tr { counter-increment: position; }` numbers the positions of an invoice. To show the running total at the bottom of each page and bring it forward on the next (*Übertrag*), use the carry-over rows of [Extensions](extensions.md). ## Break flex, grid and multi-column layouts across pages Flex containers, grids and multi-column containers break across pages like other boxes, as in Chrome: - Flex rows break between their lines, column flex containers inside their items. - Grids break between rows and inside items; items in the same row continue together. - Multi-column containers fill their columns, continue on the next page when the columns are full, and balance the last page. `column-span: all` elements span the columns. - `break-before`, `break-after` and `break-inside` work on flex and grid items. ```html <!doctype html> <html lang="en"> <head> <style> @page { size: A5; margin: 15mm; } .cards { display: grid; grid-template-columns: repeat(2, 1fr); gap: 5mm; } .card { border: 0.5pt solid #999; padding: 4mm; height: 40mm; } </style> </head> <body> <div class="cards"> <div class="card">1</div><div class="card">2</div> <div class="card">3</div><div class="card">4</div> <div class="card">5</div><div class="card">6</div> <div class="card">7</div><div class="card">8</div> <div class="card">9</div><div class="card">10</div> </div> </body> </html> ``` The first page holds the cards 1 to 8, the second page 9 and 10. ## Build a table of contents `target-counter()` shows a counter at the place a link points to, `leader()` fills the rest of the line. Together they make a table of contents with page numbers: ```html <!doctype html> <html lang="en"> <head> <style> .toc a { display: block; color: inherit; text-decoration: none; } .toc a::after { content: leader(dotted) target-counter(attr(href), page); } .xref::after { content: " (page " target-counter(attr(href), page) ")"; } h2 { break-before: page; } </style> </head> <body> <nav class="toc"> <h1>Contents</h1> <a href="#installation">Installation</a> <a href="#configuration">Configuration</a> <a href="#upgrading">Upgrading</a> </nav> <h2 id="installation">Installation</h2> <p>Read <a class="xref" href="#upgrading">Upgrading</a> before you update.</p> <h2 id="configuration">Configuration</h2> <h2 id="upgrading">Upgrading</h2> </body> </html> ``` ```text Contents Installation ............................................ 2 Configuration ........................................... 3 Upgrading ............................................... 4 ``` - `target-counter(attr(href), page)` is the page the target starts on. Other counters give their value at the target, such as `target-counter(attr(href), chapter)` or `list-item`. `target-counters()` gives all levels of a nested counter with a separator. - `target-text(attr(href))` is the target's text; `before`, `after` and `first-letter` select its generated content or first letter. - `leader()` takes `dotted`, `solid`, `space` or a string. A document that uses these functions is laid out twice: once to find the targets and once with their numbers. Chrome supports neither function, so a table of contents built this way shows no page numbers in Chrome's print preview. The links of the table of contents are links in the PDF too. Headings also make the PDF's outline (bookmarks): `bookmark-level`, `bookmark-label` and `bookmark-state` change it, and `bookmark-level: none` leaves a heading out. See [PDF output](pdf.md). ## Fill the whole page A page with `margin: 0` lets content reach the edge of the sheet. The background of `@page` covers the whole sheet, margins included. ```html <!doctype html> <html lang="en"> <head> <style> @page { margin: 20mm; } @page cover { margin: 0; background: #1d3557; } body { margin: 0; } .cover { page: cover; height: 297mm; box-sizing: border-box; padding: 60mm 20mm; color: white; } </style> </head> <body> <div class="cover"><h1>Product catalog 2027</h1></div> <h2>Introduction</h2> </body> </html> ``` - The background of the root element, or of `body` if the root has none, covers the canvas of every page (the page area and the page box's padding), as in browsers. - The background of `@page` takes colors and images, but no gradients, as in Chrome 157. Put a gradient on an element that fills the page instead. - A `position: fixed` element repeats on every page, placed relative to the page area, which makes watermarks easy. Marks in the page margins, such as fold marks, belong in a margin box (`content: url(fold-mark.svg)`), since content outside the page area is cut off. ## Prepare a document for a print shop `bleed` adds room around the page for content that runs off the edge, and `marks` draws crop marks and registration crosses outside it. Chrome ignores both. ```html <!doctype html> <html lang="en"> <head> <style> @page { size: A5; margin: 15mm; bleed: 3mm; marks: crop cross; } html { background: #e8f0ff; } </style> </head> <body><h1>Flyer</h1></body> </html> ``` The PDF page grows by the bleed and the room for the marks. Its TrimBox is the A5 page, its BleedBox the page with the bleed, so a print shop's software knows where to cut. Without a `bleed` of its own, a page with `marks` gets a bleed of 6pt, as CSS Paged Media specifies. ## Footnotes Fagus has no footnotes, as Chrome has none: `float: footnote` is an invalid value, and `footnote-display`, `footnote-policy` and `float-reference` are unknown properties. Each is reported as a diagnostic and ignored, so a `float: footnote` leaves an earlier `float` value in force. `@footnote` rules have no effect. The text of a "footnote" stays where it is in the flow. Endnotes work with links and `target-counter()`. The note references show the numbers of the list items they point to: ```html <!doctype html> <html lang="en"> <head> <style> a.note { text-decoration: none; } a.note::after { content: target-counter(attr(href), list-item); vertical-align: super; font-size: 70%; } </style> </head> <body> <p>Delivery within 14 days<a class="note" href="#n1"></a> at a flat rate<a class="note" href="#n2"></a>.</p> <h2>Notes</h2> <ol> <li id="n1">Within Germany.</li> <li id="n2">Up to 30 kg.</li> </ol> </body> </html> ``` ## Differences from Chrome | Topic | Chrome | Fagus | |---|---|---| | Default page size | the printer's or region's (Letter in the US) | A4 | | `bleed`, `marks` | ignored | supported | | `target-counter()`, `target-text()`, `leader()` | not supported | supported | | `break-before: left`, `right`, `recto`, `verso` | like `page` | a blank page where needed | | `@page :blank` | rule ignored | matches the inserted blank pages | | Running elements (`position: running()`) | not supported | supported | | Fonts | installed fonts of the machine | only the fonts you configure, unless system fonts are on (see [Fonts](fonts.md)) | | Texts of form controls | the language of Chrome's user interface | the control's `lang`, else the engine's `locale` | Everything else on this page, including the parts that are not supported, behaves as in Chrome's print. <!-- Source: https://fagus.niklasforst.de/docs/fonts --> # Fonts Fagus uses only the fonts you give it. It does not look at the fonts installed on the machine unless you ask it to, so a document prints the same on your laptop, in CI and on the production server. This page describes where fonts come from, how CSS finds them, and what Fagus embeds in the PDF. Fonts come from four places, in this order: 1. `@font-face` rules of the document. 2. Fonts you configure: font directories and fonts added with `addFont()`. 3. The fonts installed on the system, only if you turn them on. 4. Inter, built into Fagus, for anything no other font covers. ## The built-in font Fagus brings Inter in regular and bold (SIL Open Font License 1.1). A document renders without any fonts of your own: text in a family that no font has, and characters that no other font covers, are set in Inter. Italics are made up by slanting the regular face. Inter covers Latin, Greek and Cyrillic. Characters it lacks (Chinese, Japanese, Arabic, emoji …) show as a "no glyph" box unless you add a font that has them. A normal PDF gets no warning for this; PDF/A refuses such a document ("Inter has no glyph for `日`, and no other font has one"). A font of the family Inter that you add (in a font directory, with `addFont()` or `@font-face`) replaces the built-in faces. ## Add font directories A font directory makes its fonts available to every document by their family names, as installed fonts are in a browser. ```php use Fagus\Engine; use Fagus\Fagus; Fagus::useEngine(new Engine( fontDirectories: [__DIR__.'/resources/fonts'], )); ``` ```html <style> body { font-family: "Source Sans 3", sans-serif; } </style> ``` In Laravel, list the directories under `fonts` in `config/fagus.php`. The default is `resources/fonts`, so fonts you put there work without configuration. Directories that do not exist are skipped. ```php // config/fagus.php 'fonts' => [ resource_path('fonts'), storage_path('app/fonts'), ], ``` On the command line, `--font-dir` adds a directory and can be repeated: ```sh fagus render invoice.html -o invoice.pdf --font-dir resources/fonts ``` Details: - Fagus reads files ending in `.ttf`, `.otf`, `.ttc`, `.otc`, `.woff` and `.woff2`, in the directory and its subdirectories. Files that are not fonts are skipped. - The family name is the one stored in the font file (the name your operating system's font viewer shows), not the file name. All weights and styles of a family can be in one directory; CSS font matching picks the right face. - The worker reads the directories when it starts. Fonts added to a directory later are seen by the next worker (after `close()`, a deploy, or a restart of the queue worker). - In PHP, every directory in `fontDirectories` must exist: before it starts the worker, the engine throws an `EngineException` that names a missing one ("The font directory `…` does not exist."). The Laravel integration skips directories of its `fonts` configuration that do not exist, since its default, `resources/fonts`, is optional. ## Add a font from memory `addFont()` adds a font from its bytes, for all later documents of the engine. It returns the number of faces in the file (a collection has several). ```php use Fagus\Fagus; $faces = Fagus::engine()->addFont(file_get_contents(__DIR__.'/resources/fonts/HouseFont.otf')); ``` In Laravel, use the facade's engine: `Fagus::engine()->addFont($bytes)`. The engine keeps the font and hands it to a new worker whenever one starts. Prefer font directories for fonts you always need: `addFont()` sends the font through the pipe to the worker each time a worker starts. ## Load fonts with @font-face A document can bring its own fonts. The URLs resolve like those of images: against the base directory, from resources handed over, or through the resolver (see [Resources](resources.md)). Fagus never loads fonts from the network, so a `<link>` to Google Fonts does not work; download the font files and serve them locally. ```html <style> @font-face { font-family: "Brand"; src: url(fonts/Brand-Regular.woff2) format("woff2"); font-weight: 400; } @font-face { font-family: "Brand"; src: url(fonts/Brand-Bold.woff2) format("woff2"); font-weight: 700; } body { font-family: "Brand", sans-serif; } </style> ``` ```php Fagus::html($html) ->baseDirectory(__DIR__.'/resources/pdf') // fonts/Brand-Regular.woff2 is read from here ->save('invoice.pdf'); ``` What works, as in Chrome: - **Formats:** TrueType, OpenType, WOFF, WOFF2 and collections. Sources are tried in order, and sources whose `format()` or `tech()` Chrome does not load (EOT, SVG fonts, Graphite, incremental) are skipped. - **`local()`** finds a face by its PostScript or full name among the fonts of your font directories (and the system's, if system fonts are on). - **Descriptors:** `font-weight`, `font-style` (`italic`, `oblique` with angles and ranges), `font-stretch` (with ranges), `unicode-range`, `size-adjust`, `ascent-override`, `descent-override`, `line-gap-override` and `font-feature-settings`. `font-display` has no effect on a document that is rendered once. - **`unicode-range`:** rules of one family with the same descriptors make one face whose files cover characters by their ranges, as Google Fonts serves its fonts in pieces. - **Variable fonts:** text is set at the coordinates its style asks for: the weight on `wght`, the width on `wdth`, the size on `opsz` (`font-optical-sizing`), then `font-variation-settings`. A weight range in the rule (`font-weight: 100 900`) limits the weights, without one the font's axis does. A font that cannot be loaded is reported as `resource.not-loaded`, a file that is not a font Fagus can read as `font.unsupported`; the next source or the next family in `font-family` takes over. Fonts are cached by the engine, so a template that loads the same font for every document reads it once. ## Fonts in headers and footers Chrome loads the faces of `@font-face` rules while it lays out the document, and not again for the page margins. A face that the content of the document never uses is therefore missing in the margin boxes, and their text falls back to the next family in its `font-family`. Fagus does the same, so that headers and footers look as they do in Chrome. ```html <style> @font-face { font-family: Brand; src: url(fonts/Brand-Regular.woff2); } @font-face { font-family: Brand; src: url(fonts/Brand-Italic.woff2); font-style: italic; } @page { @top-center { content: "Annual report"; font-family: Brand; font-style: italic; } } body { font-family: Brand; } /* no italic text in the content */ </style> ``` Here the running head is not set in Brand Italic. To fix it, either use the face somewhere in the document's content, or load the font from a font directory or with `addFont()` instead of `@font-face`: those fonts are always available, also in margin boxes. Running elements (`position: running()`) are part of the content and are not affected. ## Set the generic families The generic families `serif`, `sans-serif` and `monospace` have no fonts of their own in Fagus. Tell Fagus which families they stand for: ```php use Fagus\Engine; use Fagus\Fagus; Fagus::useEngine(new Engine( fontDirectories: [__DIR__.'/resources/fonts'], sansSerif: 'Inter', serif: 'Source Serif 4', monospace: 'JetBrains Mono', )); ``` ```php // config/fagus.php (Laravel) 'families' => [ 'sans-serif' => 'Inter', 'serif' => 'Source Serif 4', 'monospace' => 'JetBrains Mono', ], ``` On the command line, `fagus render` takes `--sans-serif`; the worker that PHP starts also takes `--serif` and `--monospace`. Where a family is not set, Fagus chooses: | CSS | Font | |---|---| | no `font-family` at all | the `serif` family, as browsers use their serif font by default | | `serif` | the `serif` family, else the first family added, else Inter | | `sans-serif`, `system-ui` | the `sans-serif` family, else the first family added, else Inter | | `monospace` | the `monospace` family, else Menlo, Consolas, DejaVu Sans Mono or Liberation Mono if added, else any fixed-pitch font added, else the first family added | | `cursive`, `fantasy` | nothing; the next family in the list | | `math` | a font with a MATH table (STIX Two Math, Cambria Math, Latin Modern Math …), else the default font | | a family no font has | the `sans-serif` family, else the first family added, else Inter | "The first family added" is the family of the first font file read from the font directories (in alphabetical order of their paths), else of the first `addFont()`. Two consequences: - Text without `font-family` is set in the `serif` family. If you set only `sansSerif`, give your `body` a `font-family` too. - With several fonts in your directories, name the family in your CSS or set the generic families, rather than relying on the first family added. Text in exactly `font-family: monospace` gets Chrome's default size of 13px instead of 16px, as in every browser. ## Use the fonts installed on the system With system fonts on, the fonts installed on the machine serve too, as in Chrome: ```php new Engine(systemFonts: true); ``` ```php // config/fagus.php, or FAGUS_SYSTEM_FONTS=true in .env 'system_fonts' => true, ``` ```sh fagus render page.html -o page.pdf --system-fonts ``` Fagus then finds fonts where Chrome finds them: - **macOS:** `/System/Library/Fonts`, `/Library/Fonts` and `~/Library/Fonts`. - **Linux:** the directories fontconfig lists, else `/usr/share/fonts`, `/usr/local/share/fonts` and `~/.local/share/fonts`. - **Windows:** `%WINDIR%\Fonts` and the fonts installed for the user. With system fonts: - Families that documents name come from the system. Your font directories and `@font-face` still come first for their families; faces from a font directory join the installed faces of the same family. - The generic families are those of Chrome on macOS where they are installed (Times, Helvetica, Menlo, San Francisco for `system-ui`, Apple Chancery, Papyrus), else those of Windows and Linux (Times New Roman, Arial, Consolas, Liberation, DejaVu, Noto …). For Japanese, Korean and Chinese text (by `lang`) they are the fonts Chrome takes for these languages (Hiragino, Apple SD Gothic Neo, PingFang, Yu Gothic, Malgun Gothic, Microsoft YaHei, Noto CJK …). - Text without `font-family` is set in the standard font of its language, as in Chrome. - `ui-sans-serif`, `ui-serif`, `ui-monospace`, `ui-rounded` and `-apple-system` match nothing, as in Chrome, so Tailwind's default `font-sans` stack gets the system font. - The built-in Inter no longer answers to the name Inter unless Inter is installed or added. - Installed fonts are indexed when the worker starts and read only when a document uses them. - A face whose glyphs Fagus cannot draw is passed over for the next font, with a `font.unsupported` warning. The output then depends on the fonts of the machine. Leave system fonts off on servers, and use it where documents must look like Chrome on the same machine, or for scripts that no font of yours covers. ## Fall back for missing characters When the font of the text lacks a character, Fagus looks for it as Chrome does: 1. in the other families of the element's `font-family` list, in order; 2. with system fonts on: in the standard font of the text's language, then in the fonts the system falls back to for the character's script (PingFang or Songti for Chinese, Hiragino for Japanese, Geeza Pro for Arabic, Apple Symbols for symbols … on macOS); 3. in the other fonts you added; 4. in the built-in Inter. Spaces take the first font of the list that has them, and a letter with combining accents stays in one font that can draw the whole cluster. With `line-height: normal`, a line with glyphs from a fallback font grows to make room for them, as in Chrome. A character that no font has is drawn as the empty box (`.notdef`) of the first font. Its text stays in the PDF, so that it is copied and found as the character it is. The warning `font.missing-glyph` names such characters, up to eight and the count of the rest, how often they occur and the line of the element of the first: ```text html:12: warning[font.missing-glyph]: no font has glyphs for 2 characters in 3 places: `漢` (U+6F22), `字` (U+5B57); they are drawn as empty boxes (add a font that has them) ``` PDF/A and PDF/UA do not allow such characters: the document is refused instead (see [pdf.md](pdf.md)). To print a script reliably, add a font for it and name it in the font list: ```css body { font-family: "Inter", "Noto Sans JP", sans-serif; } ``` ## Bold, italic and small capitals Fagus picks the closest face of a family by width, style and weight, as CSS font matching describes. Where a family has no bold or italic face, Fagus makes one up as Chrome does: bold by stroking the outlines, italic by slanting them. `font-synthesis` controls this: ```css .logo { font-synthesis: none; } /* never make up bold, italic or small caps */ .label { font-synthesis: weight; } /* only bold */ ``` `font-variant-caps: small-caps` uses the font's small capitals (`smcp`); where the font has none, Fagus makes them from capitals at 70 % of the size, as Chrome does. ## OpenType features CSS controls the font's OpenType features as in Chrome: - `font-variant-numeric`: `tabular-nums` (columns of amounts that line up), `oldstyle-nums`, `lining-nums`, `slashed-zero`, `diagonal-fractions`, `ordinal`. - `font-variant-ligatures`, `-caps`, `-east-asian`, `-position`, and `font-variant-alternates: historical-forms`. - `font-kerning`, `font-optical-sizing`, `font-variation-settings`. - `font-feature-settings` for anything else (`"ss01"`, `"cv11"`), applied last, also as an `@font-face` descriptor. - `font-palette` and `@font-palette-values` for color fonts. ```css td.amount { font-variant-numeric: tabular-nums; text-align: right; } ``` As in Chrome, `letter-spacing` other than 0 turns off common and contextual ligatures. ## Languages The `lang` attribute matters for fonts and text: - Text is shaped in its language, so a font's localized forms (`locl`) apply: Bulgarian or Serbian Cyrillic letter forms, or EB Garamond's German `f`, which takes no `fi` ligature. - `hyphens: auto` needs `lang` to hyphenate. Fagus has Chrome's hyphenation dictionaries for 48 languages (see [CSS reference](css.md#hyphenation)). - Quotation marks of `<q>` follow the language. - With system fonts on, the generic families and fallback fonts depend on it. Set the language on the root element. It also becomes the language of the PDF. ```html <html lang="de"> ``` ## The language of form controls Form controls show texts of their own: the labels of submit and reset buttons, "Choose File" and "No file chosen" of file inputs, the placeholders and formats of date and time fields (`mm/dd/yyyy`, 12-hour time), the decimal separator of number fields, and the "Details" of a `<details>` without a summary. Chrome writes these in the language of its user interface. Fagus writes them as Chrome does in the language of the control instead: its `lang` (inherited, as from `<html lang="de">`), else the engine's `locale`, else American English. ```php new Engine(locale: 'de-DE'); ``` ```php // config/fagus.php, or FAGUS_LOCALE=de-DE in .env 'locale' => env('FAGUS_LOCALE'), ``` ```sh fagus render form.html -o form.pdf --locale de-DE ``` Fagus has Chrome's texts and formats for English (`en-US`, `en-GB`, `en-AU`, `en-IN`), German, French (`fr`, `fr-CA`), Spanish (`es`, `es-419` and `es-MX`), Italian, Dutch, Portuguese (`pt-BR`, `pt-PT`) and Polish. A `lang` of another language leaves the choice to the `locale`. The `locale` also sets the language that text without `lang` is shaped in, as Chrome shapes text in the language of its user interface. It does not turn on hyphenation: that needs `lang`. The PDF's language falls back to the `locale` where the document has no `lang`. ## Fonts in the PDF Every font a document uses is embedded in the PDF as a subset that holds only the glyphs used, so a PDF with a large font stays small. Make sure the license of your fonts allows embedding: Fagus embeds fonts whatever their license flags say, except in PDF/A, which refuses a font whose flags restrict embedding. - An instance of a variable font is embedded as a static font with the font's PostScript name, so every PDF viewer shows it. - Text stays text: it can be searched, copied and read by screen readers. A hyphen added at a line break is a soft hyphen in the text, so copied words come out whole. - Glyphs that a clip hides entirely are left out, so text extraction finds only what is visible. Embedded subsets are also what PDF/A requires, so PDF/A needs no extra font settings (see [PDF output](pdf.md)). ## Make output reproducible With system fonts off (the default), the fonts of a document are exactly the built-in Inter, your font directories, the fonts added with `addFont()` and the document's `@font-face` rules. Hyphenation dictionaries and line breaking rules are built into Fagus. A document therefore renders the same PDF on Linux, macOS and Windows, as long as the fonts and the document are the same. For byte-identical files, also fix the creation date: ```php Fagus::html($html)->created(new DateTimeImmutable('2026-11-02 12:00'))->save('invoice.pdf'); ``` Commit your fonts with the application (for example in `resources/fonts`) rather than relying on fonts installed on the server. <!-- Source: https://fagus.niklasforst.de/docs/extensions --> # Extensions Fagus renders standard CSS. Where a document needs something that no CSS specification offers, Fagus has an extension. Its name starts with `-fagus-`, browsers ignore it, and `@supports` tells whether it is there (see [ADR 4](adr/0004-extensions-only-where-css-has-no-way.md)). ## Carry-over rows at page breaks An invoice whose table of positions breaks across pages often shows the running total at the bottom of the page and brings it forward at the top of the next one (*Übertrag*). Fagus does this with three pieces: - **`-fagus-repeat: at-break`** on a row of the table's header (`<thead>`) or footer (`<tfoot>`), or on the row group: the row shows only where the table breaks. In the header, it shows on the pages after the first page of the table; in the footer, on the pages before the last. The value `auto` (the initial value) repeats the row on every page, as the header and footer are. - **`string()`** in the content of a cell of such a row shows the value the named string has where the row is placed: in the footer after the last row of the page, in the header after the last row of the page before. The rows of the body set the string with `string-set`. - **`counter(-fagus-next-page)`** and **`counter(-fagus-previous-page)`** show the numbers of the next and of the previous page, as `counter(page)` shows the current one. The running totals come from the code that writes the HTML, for example as an attribute of each row. Fagus does not add up numbers, so amounts keep the format, currency and rounding of the application. ```html <style> .lines tbody tr { string-set: carried attr(data-carried); } .lines .carry { -fagus-repeat: at-break; } .lines .carry .amount::after { content: string(carried); } .lines .continued::after { content: "Continued on page " counter(-fagus-next-page); } .lines .forward::after { content: "Brought forward from page " counter(-fagus-previous-page); } /* Browsers would show the carry-over rows on every page. */ @supports not (-fagus-repeat: at-break) { .lines .carry { display: none; } } </style> <table class="lines"> <thead> <tr><th>Item</th><th>Amount</th></tr> <tr class="carry"><td class="forward"></td><td class="amount"></td></tr> </thead> <tfoot> <tr class="carry"><td class="continued"></td><td class="amount"></td></tr> </tfoot> <tbody> <tr data-carried="120.00 €"><td>Consulting</td><td>120.00 €</td></tr> <tr data-carried="215.50 €"><td>Travel</td><td>95.50 €</td></tr> … </tbody> </table> ``` A footer row without `-fagus-repeat` shows `string()` on every page, with the final value on the last one: a subtotal per page and the total at the end. The table's columns are measured with the values at the end of the table, usually the widest totals. Keep carry-over rows to one line: their height is that of the row as measured. [`tests/corpus/quittio/many-lines.html`](../tests/corpus/quittio/many-lines.html) shows Quittio's invoice with its carry-over rows. <!-- Source: https://fagus.niklasforst.de/docs/pdf --> # The PDF This page describes the PDF file Fagus writes and the options that change it: metadata, links and bookmarks, tagged and accessible PDF, PDF/A, attachments and electronic invoices. How the pages look is up to the HTML and CSS (see [css.md](css.md) and [paged-media.md](paged-media.md)); the methods of the document builder are described in [php.md](php.md). Every PDF Fagus writes is a PDF 1.7 file with: - the fonts the text uses, embedded as subsets; - the title, language, author, subject and keywords of the document; - links and the document outline (bookmarks) from the headings; - the logical structure for screen readers (tagged PDF), unless you turn it off; - compressed streams and object streams. ```php use Fagus\Conformance; use Fagus\Fagus; $pdf = Fagus::html($html) ->pdfA(Conformance::PdfA3b) // PDF/A ->accessible() // PDF/UA-1 ->attach('timesheet.csv', $csv, 'text/csv', description: 'Timesheet') // attachments ->facturX($invoiceXml) // ZUGFeRD / Factur-X ->created(new DateTimeImmutable('2026-11-01 09:00')) // reproducible output ->render(); ``` ## Set the title, language and other metadata Fagus takes the metadata from the document, as a browser does. There is no method to set it separately: write it into the HTML. | PDF field | Comes from | |---|---| | Title | `<title>`, its white space collapsed | | Language (`Lang`) | `<html lang>`, else the engine's `locale` (see [php.md](php.md)) | | Author | `<meta name="author" content="…">` | | Subject | `<meta name="description" content="…">` | | Keywords | `<meta name="keywords" content="…">`, split at commas | | Producer | `Fagus` | | Creation and modification date | `created()`, else the current time | ```html <html lang="de"> <head> <title>Rechnung RE-2026-0042 ``` The same values go into the document information dictionary and the XMP metadata. With a title, the PDF asks viewers to show the title instead of the file name (`DisplayDocTitle`), as Chrome's PDFs do. ## Links An `` becomes a link in the PDF when it leads to: - an element of the document: `href="#total"` leads to the element with `id="total"` or to an ``; `href="#"` and `href="#top"` lead to the top of the first page; - a URL with the scheme `http:`, `https:`, `mailto:`, `tel:` or `ftp:`. Other links are dropped: relative URLs (`page.html`), `javascript:`, `file:` and any other scheme. A web address without a path gets one (`https://example.com` becomes `https://example.com/`), as in the URLs Chrome writes. Each inline box of a link gets its own link area, and so do images and inline blocks inside a link. Links in margin boxes (headers and footers) work on every page. Links that are hidden or fully transparent make no link area. Page numbers of link targets, such as a table of contents with `target-counter()` and `leader()`, are described in [paged-media.md](paged-media.md). ## Control the document outline The document outline, the bookmarks a PDF viewer shows beside the pages, comes from the headings. The default style sheet gives `

` to `

` the levels 1 to 6; an element with `role="heading"` is an entry at its `aria-level` (2 without one), as in Chrome, unless its `bookmark-level` is set: `bookmark-level: none` leaves it out too. An entry's title is the heading's text as it is shown: hidden text is left out and `text-transform` applies. Entries point at the top left of their element. Three properties from CSS Generated Content for Paged Media change the outline: | Property | Values | Effect | |---|---|---| | `bookmark-level` | `none` or an integer from 1 | Makes an element an entry at that level, or none | | `bookmark-label` | `content(text)` (initial), strings, `attr()` | The title of the entry | | `bookmark-state` | `open` (initial), `closed` | Whether the entry shows its children | ```css /* Chapters are entries, their headings are not. */ section.chapter { bookmark-level: 1; bookmark-label: "Chapter " attr(data-number); } section.chapter h1 { bookmark-level: none; } /* Leave the invoice's headings out of the outline. */ .invoice h2, .invoice h3 { bookmark-level: none; } /* Show appendices collapsed. */ .appendix h1 { bookmark-state: closed; } ``` Deeper levels nest under the entry before them. Elements in margin boxes make no entries, and an entry with an empty title is left out. A document without entries has no outline, except in PDF/UA, which asks for one. ## Tagged PDF A tagged PDF contains the logical structure of the document: what is a heading, a paragraph, a list or a table, in reading order. Screen readers read it, and PDF viewers use it to reflow text and to copy tables. Fagus tags every PDF by default. What Fagus tags: - headings (`

` to `

`, `role="heading"`) and paragraphs; - lists with their labels (the markers) and bodies; - data tables, with header cells and their scope, row and column spans, captions, and header and footer groups; a header repeated on every page counts once; - images (``, inline ``) as figures with their alternative text, MathML formulas with their `alttext` (or TeX annotation, or text); - links, with their annotations and a description (their `aria-label`, `title`, text, or the `alt` of their images); - `
`, ``, `
`, `
`, `
`, ``, ``, ``, ``, ``, and `` with its expansion; - changes of language (`lang` on an element); - other blocks: a paragraph when they hold only text, a division when they hold blocks. What Fagus marks as artifacts, content a reader skips: - backgrounds, borders and other decoration; - margin boxes (headers, footers, page numbers) and running elements; - the copies of repeated content: fixed boxes on every page after the first, table headers and footers repeated on later pages; - layout tables: tables without ``, ``, ``, ``, `summary` or a `role` of `table` or `grid` are divisions, their cells are not table cells; - images with `alt=""` or `role="presentation"` (or `none`), and elements with `aria-hidden="true"`. ### Turn tagging off A PDF without tags is somewhat smaller and faster to write, which shows with documents that have many table cells. Turn tagging off with `tagged(false)`: ```php Fagus::html($html)->tagged(false)->save('report.pdf'); ``` In Laravel, the configuration key `tagged` sets the default for all documents. On the command line, the flag is `--untagged`. `tagged(false)` has no effect when the PDF must be tagged: with `accessible()` and with PDF/A-2a and PDF/A-3a. ## Make an accessible PDF (PDF/UA-1) `accessible()` writes a PDF that conforms to PDF/UA-1 (ISO 14289-1), the standard for accessible PDF. The PDF is tagged, has an outline, and Fagus checks what the standard requires of the document itself: - a title: a `` with text; - a language: `<html lang>`, or the engine's `locale`; - alternative text for every image: `alt` (or `aria-label`) on `<img>`, a `<title>` or `aria-label` in an inline `<svg>`; images that are decoration take `alt=""`, `role="presentation"` or `aria-hidden="true"`; - headings that start at `<h1>` and skip no level on the way down (an `<h3>` may follow an `<h1>` only after an `<h2>`). ```php use Fagus\Exception\RenderException; use Fagus\Fagus; try { $pdf = Fagus::html($html)->accessible()->render(); } catch (RenderException $exception) { // the document does not meet PDF/UA-1: the document has no language (add `lang` to // <html>); the image `logo.png` in line 12 has no alternative text (add `alt`, empty if it // is decoration) echo $exception->getMessage(); } ``` A document that does not meet the standard is refused: rendering fails with a `RenderException` whose message lists every problem, separated by semicolons. The messages are: | Problem | Message | |---|---| | No title | `the document has no title (add a <title>)` | | No language | ``the document has no language (add `lang` to <html>)`` | | Image without alternative text | ``the image `logo.png` in line 12 has no alternative text (add `alt`, empty if it is decoration)`` | | SVG without alternative text | ``the SVG in line 30 has no alternative text (add a <title> or `aria-label`, or `aria-hidden="true"` if it is decoration)`` | | Formula without alternative text | ``the formula in line 41 has no alternative text (add `alttext`)`` | | First heading not an `<h1>` | `the first heading, an <h2> in line 5, is not an <h1> (headings start at h1)` | | Skipped heading level | `the <h3> in line 9 follows an <h1> (headings skip no level: use an <h2>)` | The PDF itself is checked as it is written, for PDF/UA as for PDF/A. These problems end in the same exception: - ``Inter has no glyph for `☃`, and no other font has one``: a character that no font has, which other PDFs show as an empty box, with the warning `font.missing-glyph`. Add a font that has it (see [fonts.md](fonts.md)). - `text in … cannot be mapped to Unicode` and `… shows U+E000 from the private use area, which has no meaning`: glyphs without a meaning as text, as in icon fonts. - `the license of … does not allow embedding it`: the font's license forbids embedding it. - Attached files that do not qualify (see [Attach files](#attach-files)), for example ``the attached file `notes` has no valid MIME type (like `text/csv`), which PDF/A-3 requires``. `accessible()` works together with PDF/A and with electronic invoices: ```php Fagus::html($html)->pdfA(Conformance::PdfA3a)->accessible()->facturX($xml)->save('invoice.pdf'); ``` ## Write PDF/A PDF/A (ISO 19005) is the standard for archiving. Fagus writes PDF/A-2 and PDF/A-3 in their levels b, u and a: | Level | `Conformance` | Name | Requires | |---|---|---|---| | PDF/A-2b | `PdfA2b` | `'2b'` | a reliable appearance: fonts embedded, colors defined | | PDF/A-2u | `PdfA2u` | `'2u'` | 2b, and all text mapped to Unicode | | PDF/A-2a | `PdfA2a` | `'2a'` | 2u, tagged, with a language and alternative text for images | | PDF/A-3b | `PdfA3b` | `'3b'` | like 2b, and allows attachments of any type | | PDF/A-3u | `PdfA3u` | `'3u'` | 3b, and all text mapped to Unicode | | PDF/A-3a | `PdfA3a` | `'3a'` | 3u, tagged, with a language and alternative text for images | ```php use Fagus\Conformance; use Fagus\Fagus; Fagus::html($html)->pdfA(Conformance::PdfA2b)->save('archive.pdf'); Fagus::html($html)->pdfA('3a')->save('archive.pdf'); // the name, in any case Fagus::html($html)->pdfA()->save('archive.pdf'); // PDF/A-3b ``` A name that is not a level throws a `Fagus\Exception\InvalidArgumentException` that lists the levels. On the command line, the flag is `--pdfa 3b`. What changes in a PDF/A file: - The XMP metadata names the part and level (`pdfaid`). - An sRGB ICC profile is the output intent, and colors are written in that color space. Without PDF/A, colors are plain RGB. - Every character must have a glyph in a font. A character no font has (shown as an empty box in other PDFs) makes the document fail: ``Inter has no glyph for `☃`, and no other font has one``. The other checks of the written file are listed under PDF/UA above. - Transparency, blend modes and masks are kept: PDF/A-2 and PDF/A-3 allow them. - What would need a PostScript function, which PDF/A forbids, is drawn another way: conic gradients become images, and repeating linear gradients are written out period by period (one with more than 2000 periods in its box becomes its average color). Blurred shadows are images that viewers must not smooth. - PDF/A-2 allows only PDF/A files as attachments, which Fagus does not check, so it refuses every attachment: ``PDF/A-2 allows only PDF/A files as attachments; attach `timesheet.csv` to a PDF/A-3 document instead``. Use PDF/A-3, which requires a description for each attached file (see below). - The levels a are tagged whatever `tagged()` says, and fail without a language or with an image without alternative text. A document that does not meet the level is refused with a `RenderException`, as with PDF/UA: ```text the document does not meet PDF/A-3a: an image has no alternative text (add `alt`, empty for decoration); the document has no language (add `lang` to <html>) ``` ## Attach files `attach()` adds a file to the PDF, which PDF viewers list in their attachments panel: ```php use Fagus\Fagus; use Fagus\Relationship; Fagus::html($html) ->pdfA('3b') ->attach('timesheet.csv', $csv, 'text/csv', Relationship::Supplement, 'Stundenzettel') ->save('invoice.pdf'); ``` | Argument | Default | Meaning | |---|---|---| | `$name` | | The file name in the PDF | | `$data` | | The content | | `$mime` | `'application/octet-stream'` | The MIME type | | `$relationship` | `Relationship::Unspecified` | How the file relates to the document | | `$description` | `null` | A description viewers show; the file name if `null` | The relationship (PDF 2.0 `AFRelationship`, required by PDF/A-3) is one of `Source` (the file the document was made from), `Data` (data the document shows), `Alternative` (another form of the same content), `Supplement` (additional information) or `Unspecified`. The file's modification date is the document's creation date. PDF/A-3 and PDF/UA require a description for every attached file. Without `$description`, the file name describes it, in PHP, in Laravel and on the command line alike. PDF/A-3 also requires a MIME type of the form `type/subtype`; ``the attached file `notes` has no valid MIME type (like `text/csv`), which PDF/A-3 requires`` names a file without one. Attachments work in plain PDF and in PDF/A-3, not in PDF/A-2. On the command line, `--attach file` attaches a file as a supplement, with its name as description and a MIME type from its extension (see [cli.md](cli.md)). ## Make an electronic invoice (ZUGFeRD, Factur-X, XRechnung) ZUGFeRD 2 and Factur-X are the same standard for hybrid invoices: a PDF/A-3 file that people read, with the invoice as XML (UN/CEFACT Cross Industry Invoice) attached for machines. `facturX()` makes such a file from your HTML and the XML your application writes: ```php Fagus::html($html)->facturX($invoiceXml)->save('invoice.pdf'); ``` Fagus then: - attaches the XML as `factur-x.xml` (as `xrechnung.xml` for the XRechnung profile), with the MIME type `text/xml`, the description "Factur-X/ZUGFeRD invoice" and the relationship `Alternative` (`Data` for the profiles Minimum and Basic WL, whose XML is not a complete invoice); - writes the Factur-X properties into the XMP metadata, with their PDF/A extension schema: `DocumentType` `INVOICE`, `DocumentFileName`, `Version` `1.0` and `ConformanceLevel`; - writes PDF/A-3b, or the PDF/A-3 level you chose with `pdfA()`. A PDF/A-2 level is raised to the PDF/A-3 level of the same letter, with the warning `pdf.conformance-raised` ("PDF/A-2b is written as PDF/A-3b because Factur-X attaches its XML, which only PDF/A-3 allows"). ### The profile The profile is read from the XML, from the `ID` in its `GuidelineSpecifiedDocumentContextParameter`: | `InvoiceProfile` | `ConformanceLevel` | Guideline ID | |---|---|---| | `Minimum` | `MINIMUM` | ends in `minimum` | | `BasicWl` | `BASIC WL` | ends in `basicwl` | | `Basic` | `BASIC` | ends in `basic` | | `En16931` | `EN 16931` | starts with `urn:cen.eu:en16931:2017` | | `Extended` | `EXTENDED` | ends in `extended` | | `XRechnung` | `XRECHNUNG` | contains `xrechnung` | An XML that declares none is treated as EN 16931, with the warning `invoice.profile-unknown`. You can name the profile yourself; if the XML declares another one, the warning `invoice.profile-mismatch` says so: ```php use Fagus\InvoiceProfile; Fagus::html($html)->facturX($xml, InvoiceProfile::XRechnung)->save('invoice.pdf'); ``` Fagus does not check the content of the XML, and it does not compare it with the HTML. Your application writes both from the same data; validate the result as described below. ### A complete example This renders an invoice and its XML to a PDF/A-3b file that veraPDF and Mustang accept. The XML is [tests/corpus/invoice/factur-x.xml](../tests/corpus/invoice/factur-x.xml), an EN 16931 invoice. `invoice.html`: ```html <!doctype html> <html lang="de"> <head> <meta charset="utf-8"> <title>Rechnung RE-2026-0042

Rechnung RE-2026-0042

Muster GmbH
Hauptstraße 1
12345 Musterstadt

Kunde AG
Bahnhofstraße 5
54321 Beispielstadt

Rechnungsdatum: 01.11.2026 · Leistungsdatum: 30.09.2026 · Fällig: 15.11.2026

Pos.LeistungMengePreisBetrag
1Webentwicklung Sprint 12 h95,00 €190,00 €
2Webentwicklung Sprint 22 h95,00 €190,00 €
3Webentwicklung Sprint 32 h95,00 €190,00 €
Nettobetrag570,00 €
Umsatzsteuer 19 %108,30 €
Gesamtbetrag678,30 €

Bitte überweisen Sie den Betrag bis zum 15.11.2026 auf DE02 1203 0000 0000 2020 51.

```
invoice.xml ```xml urn:cen.eu:en16931:2017 RE-2026-0042 380 20261101 1 Webentwicklung Sprint 1 95.00 2 VATS19 190.00 2 Webentwicklung Sprint 2 95.00 2 VATS19 190.00 3 Webentwicklung Sprint 3 95.00 2 VATS19 190.00 K-1007 Muster GmbH 12345Hauptstraße 1MusterstadtDE DE123456789 Kunde AG 54321Bahnhofstraße 5BeispielstadtDE 20260930 EUR 58 DE02120300000000202051 108.30VAT570.00S19 20261115 570.00 570.00 108.30 678.30 678.30 ```
`render.php`: ```php facturX(file_get_contents(__DIR__.'/invoice.xml')) ->created(new DateTimeImmutable('2026-11-01 09:00', new DateTimeZone('Europe/Berlin'))) ->render(); $pdf->save(__DIR__.'/invoice.pdf'); foreach ($pdf->diagnostics() as $diagnostic) { echo $diagnostic, "\n"; } ``` The result is a one-page PDF/A-3b file of about 23 KB with `factur-x.xml` attached and the profile EN 16931 in its metadata. For an invoice that is also accessible, ask for PDF/A-3a and PDF/UA-1; the HTML above meets both: ```php use Fagus\Conformance; Fagus::html($html) ->pdfA(Conformance::PdfA3a) ->accessible() ->facturX($xml) ->save('invoice.pdf'); ``` In Laravel, the same methods follow the view: ```php use Fagus\Laravel\Facades\Fagus; return Fagus::view('invoices.show', ['invoice' => $invoice]) ->facturX($xml) ->download("{$invoice->number}.pdf"); ``` On the command line: ```sh fagus render invoice.html -o invoice.pdf --factur-x invoice.xml ``` ### Validate the result Fagus checks PDF/A and PDF/UA while it writes the file, but not the invoice XML. Two free tools check the result: - [veraPDF](https://verapdf.org) checks PDF/A and PDF/UA. It reads the PDF/A level from the file's metadata: ```sh verapdf --format text invoice.pdf # PDF/A verapdf --format text -f ua1 invoice.pdf # PDF/UA-1 ``` - [Mustang](https://www.mustangproject.org) checks the PDF/A file and the attached XML against the rules of ZUGFeRD, Factur-X and XRechnung: ```sh java -jar Mustang-CLI.jar --action validate --source invoice.pdf ``` A valid invoice reports ``. The repository's script `tools/validate.sh` renders every document of the test corpus as PDF/A-2b, 2u, 3b and 3a, as PDF/UA-1 and as Factur-X invoices, and checks them with both tools: ```sh VERAPDF=/path/to/verapdf MUSTANG=/path/to/Mustang-CLI.jar tools/validate.sh /tmp/validate ``` It uses `target/release/fagus`, or the binary in `FAGUS`. With veraPDF 1.30.3 and Mustang 2.26.0 every file passes. ## Make the output reproducible A PDF contains its creation date, by default the current time, so two renderings of the same document differ. With a fixed date, the same input gives a byte-identical file: ```php Fagus::html($html) ->created(new DateTimeImmutable('2026-11-01 09:00', new DateTimeZone('Europe/Berlin'))) ->save('invoice.pdf'); ``` `created()` takes any `DateTimeInterface`; the PHP package converts it to UTC. On the command line, `--created` takes a date in UTC (`2026-11-01T08:00:00Z`) or with an offset (`2026-11-01T09:00:00+01:00`), which is converted to UTC (see [cli.md](cli.md)). The PDF holds the date in UTC. The output is the same for the same HTML, resources, fonts, options and version of Fagus, on every platform. Fonts installed on the machine (`systemFonts: true`) make it depend on the machine. ## File size and compression Fagus keeps files small without options to set: - fonts are embedded as subsets, with only the glyphs the document uses; - page contents, fonts and images are compressed (Flate); all other objects go into compressed object streams with a cross-reference stream; - an image used many times is embedded once, and a background of more than 4096 tiles is one tiling pattern; - JPEG images are embedded as they are, without decoding and compressing them again. The invoice above is 16 KB as a tagged PDF, 15 KB without tags and 23 KB as PDF/A-3 with its XML (which also carries an ICC profile). The tags grow with the number of elements, most with large tables; `tagged(false)` leaves them out where accessibility is not needed. The binary compresses on two threads of its own while it draws the pages; the environment variable `RAYON_NUM_THREADS` sets how many. ## Images in the PDF Fagus reads PNG, JPEG, GIF, WebP and SVG images. Other formats (AVIF, JPEG XL, BMP …) report `image.unsupported` and are left out; `` and `srcset` skip AVIF and JPEG XL sources, as Chrome chooses among the formats it can show. An image of more than 200 megapixels reports `image.too-large`, one that does not decode `image.broken`. How images go into the PDF: - JPEG as it is, compressed as JPEG. A CMYK JPEG without an ICC profile is converted to sRGB as Chrome draws it, instead of leaving the conversion to the viewer. - PNG, GIF and WebP as their pixels, compressed without loss; transparency becomes a soft mask. A PNG whose `gAMA` chunk Chrome corrects for is corrected the same way. An animated GIF shows its first frame. - SVG as vector graphics, with their text, gradients and patterns. Filtered SVG and SVG filters that PDF cannot express are drawn as pixels at 300 dpi, as Chrome prints them. - At their full resolution: Fagus does not scale images down. Scale large photos before you hand them to the document. - Without interpolation (`/Interpolate`), as Chrome writes them: viewers decide how to smooth. ## Gradients, filters and differences from Chrome Fagus draws what it can as vectors, which stay sharp at any zoom and print resolution: - Linear, radial and conic gradients are PDF shadings. They interpolate between their stops in sRGB as Chrome's PDF output does, whatever color space the gradient names, with color hints mixed in the named space. Where Chrome prints a gradient with translucent stops in another color space (`in oklch`) as an image, Fagus samples it into a shading. A conic gradient with more than 96 stops (a repeating one of short periods) and every conic gradient in PDF/A is an image. - `filter`: Chrome prints filtered content as an image. Fagus applies color filters to the colors of what the box draws and keeps text and shapes as vectors where they stay sharp; `blur()` and SVG filters without a vector form are drawn as pixels. - `mix-blend-mode`, `background-blend-mode` and `isolation` are PDF blend modes in transparency groups; `mask` and `clip-path` are soft masks and clipping paths. - `@page` backgrounds paint their colors and images but no gradients, as in Chrome. Other places where Fagus deliberately prints differently from Chrome (the A4 default page size, the language of form controls, fonts in margin boxes) are listed in [css.md](css.md), [paged-media.md](paged-media.md) and [fonts.md](fonts.md). # Command line The `fagus` binary renders HTML files to PDF on the command line. It is the same binary the PHP package runs as its worker, so it renders exactly as the PHP package does. Use it to try a template, in shell scripts and build jobs, or from languages other than PHP. ```sh fagus render invoice.html -o invoice.pdf ``` ## Get the binary Composer installs the binary of the package's release into the package's `bin` directory (`vendor/nforst/fagus/php/fagus/bin/fagus`, `fagus.exe` on Windows); see [getting-started.md](getting-started.md). A checkout of the repository builds it with `cargo build --release` as `target/release/fagus`. ```sh fagus --version # fagus 0.1.0 fagus --help fagus render --help ``` ## Render an HTML file ```sh fagus render --output [OPTIONS] ``` `fagus render` reads the HTML file `INPUT` and writes the PDF to `OUTPUT`. Relative URLs in the document (style sheets, images, fonts) resolve against the directory of the input file, and files are only read from inside that directory, or from inside `--root`. Nothing is loaded from the network. A file ending in `.xhtml` or `.xht` is parsed as XML, as browsers parse XHTML files; any other file as HTML. | Option | Default | Description | |---|---|---| | `-o`, `--output ` | required | The PDF file to write | | `--font-dir ` | none | A directory with font files (TTF, OTF, TTC, OTC, WOFF, WOFF2), read with its subdirectories; repeatable | | `--system-fonts` | off | Use the fonts installed on the machine too, as Chrome does; the output then depends on the machine | | `--locale ` | none | The language of the texts form controls show (button labels, date formats) where the document gives no `lang`, e.g. `de-DE`; without it they are American English. Text without `lang` is shaped in it, and it is the PDF's language when `` has no `lang` | | `--sans-serif ` | none | The family used for `sans-serif` | | `--serif ` | none | The family used for `serif` | | `--monospace ` | none | The family used for `monospace` | | `--root ` | the input's directory | A larger directory the document may read files from, which contains the input's directory; URLs starting with `/` resolve against it | | `--pdfa ` | none | Write PDF/A: `2b`, `2u`, `2a`, `3b`, `3u` or `3a` | | `--untagged` | off | Write a PDF without tags (the logical structure screen readers read) | | `--accessible` | off | Write PDF/UA-1; needs a title, a language and alternative text for images | | `--attach ` | none | Attach a file; repeatable | | `--factur-x ` | none | Make a ZUGFeRD / Factur-X invoice with this XML | | `--profile ` | the XML's | The invoice profile: `minimum`, `basicwl`, `basic`, `en16931`, `extended` or `xrechnung` | | `--created ` | now | The creation date, e.g. `2026-11-13T12:00:00Z` or `2026-11-13T14:00:00+02:00`, for reproducible files | | `--strict` | off | Fail on any diagnostic (not only warnings), without writing the PDF | | `--timings` | off | Print the page count and the time of each phase | | `--repeat ` | `1` | Render N times and report the median time (for benchmarks) | | `-h`, `--help` | | Print help | The options mean what the methods of the PHP package mean; [pdf.md](pdf.md) describes PDF/A, PDF/UA, attachments, invoices and reproducible output in detail. Some details of the command line: - `--attach` attaches the file under its file name, with the file name as description and the relationship `Supplement`. The MIME type comes from the extension: `xml` (`text/xml`), `pdf`, `csv`, `json`, `txt`, `png`, `jpg` and `jpeg`; any other file is `application/octet-stream`. - `--profile` only applies together with `--factur-x`. - `--created` reads the date, the time and an offset from UTC (`Z`, `+01:00`, `-0530`) and writes the date in UTC: `2026-11-13T12:00:00+02:00` becomes `2026-11-13T10:00:00Z`. A date without an offset is taken as UTC; a fraction of a second is dropped. Anything else after the seconds makes the date invalid. - `--untagged` has no effect with `--accessible` or with `--pdfa 2a` and `3a`, which need tags. - With `--repeat`, the PDF of the last run is written. ## Read and write The input is a file path; `fagus render` does not read from standard input. Write the HTML to a file first, or use the worker or the PHP package. On Linux and macOS, the PDF can go to standard output through `/dev/stdout`: ```sh fagus render invoice.html -o /dev/stdout | aws s3 cp - s3://invoices/2026-0042.pdf ``` Diagnostics and timings go to standard error, one per line: ```text