← Tous les articles

Generating PDF invoices in PHP with Dompdf: fonts, images and page breaks without surprises

Dompdf turns HTML into PDF, but question marks instead of accented letters, missing images and table rows split across pages show up fast. The configuration and template we use for reliable invoices.

Generating PDF invoices in PHP with Dompdf: fonts, images and page breaks without surprises

Key points

  • Dompdf understands simple HTML and CSS: build templates with tables and fixed positioning, not flexbox or grid.
  • Accented characters and the € sign need a font that contains them, such as the bundled DejaVu Sans or your own TTF via @font-face.
  • Keep isRemoteEnabled off, escape every value, and archive each issued invoice instead of regenerating it.

Invoices, quotes, purchase orders, certificates: nearly every application we build ends up needing to produce a PDF. In PHP, Dompdf is a natural first pick. It installs with Composer, needs no external binary, and starts from an HTML template any developer can write. Your first PDF comes out in ten minutes. Then the real problems arrive: question marks where accented names should be, a logo that won’t show up, a table row sliced between two pages, a forty-page report that takes the server down. Here is the configuration and the habits that keep us out of trouble, using a real case: a multi-page invoice.

Installing Dompdf and producing a first PDF

Install Dompdf with Composer and configure it through an Options object. We set three things from the start because they head off most issues: the default font, a ban on remote resources, and the allowed folder (the “chroot”):

<?php
// composer require dompdf/dompdf
require __DIR__ . '/vendor/autoload.php';

use DompdfDompdf;
use DompdfOptions;

$options = new Options();
$options->set('defaultFont', 'DejaVu Sans');   // covers accented characters and the € sign
$options->set('isRemoteEnabled', false);        // never fetch external URLs
$options->setChroot(__DIR__ . '/templates');    // only these local files can be read

$dompdf = new Dompdf($options);
$dompdf->loadHtml(render_invoice($invoice), 'UTF-8');
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();

// Show in the browser (Attachment => true forces a download)
$dompdf->stream("invoice-{$invoice->number}.pdf", ['Attachment' => false]);

The HTML comes from a plain PHP template captured with ob_start(). Every value goes through htmlspecialchars(): a product name containing < or & would otherwise break the layout, and customer-entered data could inject HTML.

stream() sends the PDF to the browser with the right headers. To save it or attach it to an email, use output(), which returns the binary content as a string.

Accented characters, the € sign and custom fonts

The classic symptom: “Billed to Mr Lef?vre”, or empty boxes where the € sign should be. The cause is almost never the file encoding; it’s the font. The PDF base fonts (Helvetica, Times, Courier) don’t cover every accented character or the euro sign. Dompdf ships the DejaVu family, which does, so making it the default font fixes most cases.

Two other conditions matter: pass 'UTF-8' to loadHtml(), and declare the charset in the template’s <head>. If your data comes from an old Latin-1 database, convert it before it reaches the template.

To use your brand font, declare a TTF file with @font-face, as in the template below. Dompdf converts the font on first render and caches it, so the font cache directory (the fontCache option) must be writable by PHP. On our deployments this is the most common miss: everything works locally, then production silently ignores the font because the folder belongs to a different user. Always keep DejaVu Sans as a fallback in your font-family stack for characters your font lacks.

One note on file size: Dompdf embeds fonts in the PDF, so a full family with bold and italic weighs down every document. Only load the weights you actually use.

Images and CSS: what Dompdf really supports

Dompdf mostly implements CSS 2.1 with a few additions. Flexbox and grid aren’t supported, so a template built on display: flex will render stacked or misaligned. For invoices, go back to what works: tables for columns (sender details on the left, invoice details on the right, line items, totals), explicit widths, and position: fixed for anything repeated on every page.

For images, with isRemoteEnabled set to false, a URL like https://yoursite.com/logo.png won’t load. That’s intentional: allowing remote resources lets user-controlled content make your server request arbitrary addresses, internal ones included. We reference images by a relative path inside the chroot folder, or as a base64 data: URI for anything generated on the fly, such as a payment QR code.

This is the invoice template we start from:

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
  @page { margin: 90px 40px 70px; }
  @font-face {
    font-family: 'Inter';
    src: url('fonts/Inter-Regular.ttf') format('truetype');
  }
  body { font-family: 'Inter', 'DejaVu Sans', sans-serif; font-size: 10pt; }
  header { position: fixed; top: -70px; left: 0; right: 0; height: 50px; }
  footer { position: fixed; bottom: -50px; left: 0; right: 0; font-size: 8pt; color: #666; }
  table.lines { width: 100%; border-collapse: collapse; }
  table.lines th, table.lines td { padding: 6px; border-bottom: 1px solid #ddd; }
  table.lines tr { page-break-inside: avoid; }
  .num { text-align: right; white-space: nowrap; }
  .totals { page-break-inside: avoid; margin-top: 20px; }
</style>
</head>
<body>
  <header><img src="img/logo.png" height="40" alt=""></header>
  <footer>Example Ltd · Company no. 00000000 · hello@example.com</footer>

  <h1>Invoice <?= e($invoice->number) ?></h1>
  <table class="lines">
    <thead><tr><th>Description</th><th class="num">Qty</th><th class="num">Net total</th></tr></thead>
    <tbody>
    <?php foreach ($invoice->lines as $line): ?>
      <tr>
        <td><?= e($line->label) ?></td>
        <td class="num"><?= e($line->quantity) ?></td>
        <td class="num"><?= e(money($line->total)) ?></td>
      </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
  <div class="totals">…</div>
</body>
</html>

The @page margins reserve room for the header and footer, which are fixed-positioned with negative offsets. They repeat on every page without overlapping the content.

Multi-page invoices: headers, breaks and page numbers

An invoice with many lines spills onto several pages, and that’s where layouts fall apart. Three settings keep it together:

  • The <thead> repeats at the top of every page the table continues on, so keep column titles in a real thead, not in the first row of the tbody.
  • page-break-inside: avoid on rows stops a two-line description from being split across pages. Apply it to the totals block too, so it never gets separated from the table.
  • page-break-before: always forces a new page, handy for putting terms and conditions at the end.

For “Page 2 / 3” numbering, the total page count only exists after rendering. Dompdf lets you write on every page once rendering is done, with placeholders it fills in:

$dompdf->render();

// After render(), the total page count is known
$canvas = $dompdf->getCanvas();
$font   = $dompdf->getFontMetrics()->getFont('DejaVu Sans');

// A4 portrait = 595 x 842 points; coordinates start at the top-left corner
$canvas->page_text(500, 815, 'Page {PAGE_NUM} / {PAGE_COUNT}', $font, 8, [0.4, 0.4, 0.4]);

// Archive the PDF instead of regenerating it every time it's viewed
file_put_contents($storage . "/invoices/{$invoice->number}.pdf", $dompdf->output());

Coordinates are in points, so adjust them if you change paper size or margins. Always test with a one-line invoice and a multi-page one; those two cases expose most layout bugs.

In production: performance, security and archiving

Dompdf works entirely in memory, in pure PHP. A few-page invoice renders quickly. A report running to dozens of pages with large tables takes noticeably more time and memory. In that case we generate the document in a background job and notify the user when it’s ready, rather than holding a request open until it hits the execution time limit.

For invoicing there’s one simple rule: an issued invoice must never change. If your PDF is rebuilt from current data each time it’s viewed, a customer’s new address or a changed tax rate will silently rewrite old invoices. Generate the PDF once, when the invoice is issued, store it, and always serve that file.

Finally, if a document needs modern layout (complex grids, elaborate SVG charts), headless Chrome reproduces current CSS faithfully, at the cost of heavier infrastructure. For invoices, quotes and certificates, a well-configured Dompdf remains the easiest option to maintain.

FAQ

Why doesn’t my logo appear in the PDF?

Usually the image is referenced by URL while remote resources are disabled, or by a path outside the chroot folder. Put the file inside the allowed folder and use a relative path, or embed it as base64.

Does Dompdf support flexbox or CSS grid?

No. Build the layout with tables, fixed widths and positioning. If your document truly depends on modern CSS, consider rendering with headless Chrome.

Should the PDF be generated on every download?

Not for invoices: generate once when issued and archive the file. For documents that must reflect changing data, such as a statement, on-demand generation is fine.

Need reliable PDF invoices, quotes or reports in your application? We build PHP applications and SaaS products that generate clean, archived documents, tested against real-world cases.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →