LLION/ PDF, print & document engineering

Generating PDFs with PHP: FPDF, TCPDF, mPDF, Dompdf and Chrome

LLION Editorial · Updated

PHP has four long-lived PDF libraries and two ways to drive a browser. They differ less in features than in approach and licence, and the licence difference is the one that bites: one of the most capable HTML renderers is GPL-only. The examples below were written against the current documentation of each project (versions in the table) and checked there for method names; PHP is not installed on the machine that built this site, so they were not executed. The executed equivalents, in JavaScript, are on the JavaScript page.

The libraries#

PHP PDF libraries. Versions and licences from Packagist and the projects' licence files, checked October 2026.
LibraryVersionLicencePHPApproachHTML and CSSBest forStatus
FPDF (with tFPDF for UTF-8)1.9Permissive ("no usage restriction"); the Composer mirror setasign/fpdf is labelled MITAny modern PHPDrawing API: cells, multi-cell text, lines, imagesNoneSmall fixed layouts, labels, receipts; no dependenciesMaintained, slow-moving; 1.9 added JSON font definition files
TCPDF7.0.20LGPL-3.0-or-later8.2 and laterDrawing API derived from FPDF, plus `writeHTML`, barcodes, forms, signatures, PDF/ALimited HTML subset with inline styles, no layout CSSExisting code bases; barcodes and signatures without extra librariesMaintenance-only by its own README; tc-lib-pdf 8.x is the successor and not a drop-in replacement
mPDF8.3.1GPL-2.0-only7.0 to 8.5HTML renderer with its own layout engineGood CSS 2 plus parts of CSS 3; `@page` with headers and footers; strong RTL and CJK supportMultilingual documents from HTML templates; running headers in CSSMaintained; GPL affects closed-source distribution
Dompdf3.1.6LGPL-2.17.1 to 8.xHTML rendererCSS 2.1 and a few CSS 3 properties, `@page`, `@media`; no Flexbox, no GridSimple HTML invoices and reports, Laravel projects (barryvdh/laravel-dompdf 3.1.2, MIT)Maintained
chrome-php/chrome1.16.1MIT7.4 to 8.5Drives a local Chrome over the DevTools protocolEverything Chrome rendersFaithful rendering of real HTML with modern CSSMaintained; needs a Chrome binary on the server
spatie/browsershot5.4.2MIT8.2 and laterWraps Puppeteer; needs Node and Puppeteer installedEverything Chrome rendersLaravel and Spatie ecosystems already running NodeMaintained

The decision usually runs: Dompdf if the HTML is simple and the licence must be permissive; mPDF if the content is multilingual or needs CSS page headers and GPL is acceptable; Chrome through chrome-php when fidelity matters and a browser can be installed; TCPDF when the project already uses it or needs its barcode and signature features; FPDF for tiny fixed documents. The engine-level trade-offs of the HTML renderers are discussed on the HTML-to-PDF page.

FPDF and the UTF-8 problem#

FPDF draws with cells and multi-cells in a coordinate system that starts top-left, in millimetres by default. Its built-in fonts expect text in Windows-1252, not UTF-8, which is why accented characters arrive as "é" when a UTF-8 string is passed straight in. The FAQ's fix is to convert with iconv; the better fix for any text beyond Western Europe is tFPDF, a small fork that accepts UTF-8 and embeds TrueType fonts.

fpdf_example.php (FPDF 1.9 with tFPDF, written against the documentation, not executed here)PHP
<?php
require __DIR__ . '/vendor/autoload.php';   // composer require setasign/tfpdf

$pdf = new tFPDF('P', 'mm', 'A4');
$pdf->AddPage();
$pdf->AddFont('Noto', '', 'NotoSans-Regular.ttf', true);   // true: Unicode TrueType, embedded as a subset
$pdf->SetFont('Noto', '', 14);
$pdf->Cell(0, 10, 'Hello, PDF. Grüße, señor, 10 €', 0, 1);  // width 0 = to the right margin; 1 = line break after
$pdf->SetFont('Noto', '', 10);
$pdf->MultiCell(0, 5, 'A long paragraph is wrapped by MultiCell to the cell width, which is the page width minus both margins when the width is 0.');
$pdf->Ln(4);
foreach ([['Design work', '960.00'], ['Hosting', '120.00']] as [$item, $total]) {
    $pdf->Cell(120, 7, $item, 'B');
    $pdf->Cell(40, 7, $total, 'B', 1, 'R');
}
$pdf->SetTitle('FPDF example', true);        // second argument: the title is UTF-8
$pdf->Output('F', 'fpdf.pdf');               // F = file; I = inline to browser; D = download; S = string

Plain FPDF without tFPDF can also use TrueType fonts: FPDF 1.9's makefont script converts a .ttf into a JSON definition plus a compressed font file, and AddFont('Name', '', 'name.json') registers it. That route is still limited to a single-byte encoding chosen at conversion time, so Greek and Latin text cannot share one font object. For anything multilingual, tFPDF or one of the HTML renderers is simpler.

TCPDF#

TCPDF grew out of FPDF and kept its drawing API, then added writeHTML, UTF-8 fonts (DejaVu is bundled), barcodes, form fields, digital signatures and PDF/A modes. The project's own README now describes it as maintenance-only and points to tc-lib-pdf, which is a rewrite rather than a drop-in replacement; new projects should weigh that before adopting it, but the install base is enormous and 7.0.x releases still ship.

tcpdf_example.php (TCPDF 7.0, written against the documentation, not executed here)PHP
<?php
require __DIR__ . '/vendor/autoload.php';   // composer require tecnickcom/tcpdf

$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);   // orientation, unit, format, unicode, encoding, diskcache
$pdf->SetCreator('Example Ltd');
$pdf->SetTitle('Invoice 1001');
$pdf->SetMargins(15, 20, 15);
$pdf->setPrintHeader(false);                 // TCPDF prints a header and footer by default
$pdf->setPrintFooter(false);
$pdf->SetFont('dejavusans', '', 10);         // bundled Unicode font; 'helvetica' is Latin only
$pdf->AddPage();

$html = '<h1>Invoice 1001</h1>
<table border="0" cellpadding="4">
  <tr style="background-color:#eeeeff;"><th width="70%">Item</th><th width="30%" align="right">Total</th></tr>
  <tr><td>Design work</td><td align="right">960.00</td></tr>
  <tr><td>Hosting</td><td align="right">120.00</td></tr>
</table>';
$pdf->writeHTML($html, true, false, true, false, '');   // html, line break after, fill, reset height, cell, align

$pdf->Output('invoice.pdf', 'I');             // I = inline; D = download; F = file; S = string

writeHTML accepts a subset of HTML with attributes and inline styles; it is not a CSS layout engine, and tables need explicit widths. Its strength is everything around the HTML: SetProtection for encryption, setSignature for signing, setPDFVersion and PDF/A mode, and a barcode API that has no equal among the free PHP libraries.

mPDF#

mPDF is the most capable pure-PHP HTML renderer. It handles @page rules with named headers and footers, page numbers through {PAGENO} and {nbpg} placeholders, bidirectional and complex-script text, and a large bundled font set. It is also GPL-2.0-only, which means a closed-source application that distributes it to customers must take the licence seriously; a web service that merely runs it on its own servers is in a different position, and that difference is worth a conversation with whoever handles licensing.

mpdf_example.php (mPDF 8.3, written against the documentation, not executed here)PHP
<?php
require __DIR__ . '/vendor/autoload.php';   // composer require mpdf/mpdf

$mpdf = new \Mpdf\Mpdf([
    'format' => 'A4',
    'margin_top' => 25, 'margin_bottom' => 25, 'margin_left' => 15, 'margin_right' => 15,
    'default_font' => 'dejavusans',
]);
$mpdf->SetTitle('Invoice 1001');
$mpdf->SetHTMLFooter('<div style="text-align:center;font-size:9pt;">Page {PAGENO} of {nbpg}</div>');

$mpdf->WriteHTML('
<style>
  @page { size: A4; }
  body { font-family: dejavusans; font-size: 11pt; }
  table { width: 100%; border-collapse: collapse; }
  thead { display: table-header-group; }
  th, td { border-bottom: 0.3mm solid #ccc; padding: 2mm 1mm; text-align: left; }
  th { background: #eef; }
</style>
<h1>Invoice 1001</h1>
<table><thead><tr><th>Item</th><th>Total</th></tr></thead>
<tbody><tr><td>Design work</td><td>960.00</td></tr><tr><td>Hosting</td><td>120.00</td></tr></tbody></table>
');

$mpdf->Output('invoice.pdf', \Mpdf\Output\Destination::INLINE);   // DOWNLOAD, FILE, STRING_RETURN

mPDF needs a writable temporary directory (tempDir in the constructor) for its font cache; on shared hosting that is the usual first error. Its CSS support is wide but not complete, and Flexbox and Grid are not implemented, so templates written for the screen need a print-specific stylesheet.

Dompdf#

Dompdf is the lightest HTML renderer and the most common choice in Laravel projects through the barryvdh wrapper. It implements CSS 2.1 with some CSS 3 and @page; the documented gaps are Flexbox and Grid, so layouts use tables and floats.

dompdf_example.php (Dompdf 3.1, written against the repository documentation, not executed here)PHP
<?php
require __DIR__ . '/vendor/autoload.php';   // composer require dompdf/dompdf

use Dompdf\Dompdf;
use Dompdf\Options;

$options = new Options();
$options->set('isRemoteEnabled', false);     // default: no http(s) fetches; keep it off for untrusted input
$options->set('chroot', __DIR__ . '/assets');   // local files are only allowed below this path
$options->set('defaultFont', 'DejaVu Sans');     // bundled Unicode font

$dompdf = new Dompdf($options);
$dompdf->loadHtml('
<!doctype html><html><head><meta charset="utf-8"><style>
  @page { margin: 20mm 15mm 25mm 15mm; }
  body { font-family: "DejaVu Sans", sans-serif; font-size: 11pt; }
  table { width: 100%; border-collapse: collapse; }
  th, td { border-bottom: 1px solid #ccc; padding: 2mm 1mm; text-align: left; }
  .page-number:after { content: counter(page); }
</style></head>
<body><h1>Invoice 1001</h1>
<table><thead><tr><th>Item</th><th>Total</th></tr></thead>
<tbody><tr><td>Design work</td><td>960.00</td></tr><tr><td>Hosting</td><td>120.00</td></tr></tbody></table>
<p style="position:fixed;bottom:0;right:0;font-size:9pt;">Page <span class="page-number"></span></p>
</body></html>');
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream('invoice.pdf', ['Attachment' => true]);   // or $pdf = $dompdf->output(); file_put_contents(...)

Dompdf's isRemoteEnabled option is the one to understand: when it is false (the default), the renderer refuses http and https resources, which closes the server-side request forgery hole that HTML renderers open; when it is true, any <img src> in the document becomes a request from your server. Keep it off and serve images as data URIs or local files under chroot.

Driving Chrome from PHP#

For real CSS, including Flexbox and Grid, the engine has to be a browser. chrome-php talks to a local Chrome binary over the DevTools protocol without Node; Browsershot wraps Puppeteer and therefore needs Node and the Puppeteer package on the same host.

chrome_example.php (chrome-php/chrome 1.16, written against the README, not executed here)PHP
<?php
require __DIR__ . '/vendor/autoload.php';   // composer require chrome-php/chrome

use HeadlessChromium\BrowserFactory;

$factory = new BrowserFactory();            // honours the CHROME_PATH environment variable
$browser = $factory->createBrowser(['noSandbox' => false, 'windowSize' => [1200, 800]]);
try {
    $page = $browser->createPage();
    $page->setHtml($html);                   // the same invoice markup as above, with a print stylesheet
    $page->pdf([
        'printBackground' => true,
        'preferCSSPageSize' => true,
        'marginTop' => 0.8, 'marginBottom' => 1.0, 'marginLeft' => 0.6, 'marginRight' => 0.6,   // inches
        'displayHeaderFooter' => true,
        'headerTemplate' => '<div></div>',
        'footerTemplate' => '<div style="font-size:9px;width:100%;text-align:center;">Page <span class="pageNumber"></span> of <span class="totalPages"></span></div>',
    ])->saveToFile(__DIR__ . '/invoice.pdf');
} finally {
    $browser->close();
}

The options mirror the DevTools Page.printToPDF command, so margins are in inches and the header and footer templates work the same way as in Puppeteer. Everything on the HTML-to-PDF page about fonts, isolation and request allowlists applies: a browser process started by PHP on a web server is a browser process that renders whatever it is given.

Checking the output#

PHP's output buffering and the libraries' own streaming make it easy to produce a file that is almost a PDF: a byte order mark or a stray newline before %PDF is the classic symptom, and some viewers tolerate it while others do not. Run qpdf --check on the generated file, confirm that the first five bytes are %PDF- as described on the file signatures page, and extract the text with pdftotext or pypdf to confirm the encoding survived. The PDF inspector shows the fonts with their embedding status, which is the fastest way to find a "é" problem before a customer does.

In a test suite, generate the document, assert the page count, assert that a known string extracts from page 1, and assert that the fonts listed are the ones you shipped. Those checks fail on the regressions that matter: an overflow onto an extra page, a substituted font, and text that lost its Unicode mapping.

Traps#

UTF-8. FPDF and plain TCPDF helvetica expect single-byte text; UTF-8 must be converted or, better, replaced by a Unicode font (tFPDF, TCPDF's dejavusans, mPDF's and Dompdf's bundled DejaVu). A PDF that shows "é" was generated with a UTF-8 string and a Windows-1252 font.

Fonts on the server. The renderers embed only fonts they can find. mPDF and Dompdf ship DejaVu; anything else must be registered in their font configuration arrays and the files placed where the library looks. The fonts page shows how to check what a file actually contains.

Memory and execution time. mPDF and Dompdf build the whole document in memory and are slow on hundreds of pages; a long report can exceed memory_limit and max_execution_time in a web request. Generate large documents in a queue worker with its own limits, write to a file, and let the web request serve the file.

Remote resources. Dompdf's isRemoteEnabled and chroot, mPDF's curlAllowUnsafeSslRequests and related options, and TCPDF's image fetching all control whether the server fetches URLs from the HTML. For documents that include any user-supplied content, keep remote fetching off and supply assets as local files or data URIs.

Output mode. All four libraries can stream the PDF to the browser (Output('name.pdf', 'I'), stream(), Destination::INLINE) or return a string. When streaming, send nothing else, not even whitespace after ?>, and set the headers the library expects; the MIME type reference covers Content-Type and Content-Disposition.

Units and page size. FPDF, tFPDF, TCPDF and mPDF default to millimetres; Dompdf takes setPaper('A4') or an array in points; chrome-php takes inches. The units reference has the conversions, and the metadata page covers what SetTitle, SetAuthor and friends write.

Licences and maintenance. mPDF is GPL-2.0-only; TCPDF is in maintenance mode with a non-compatible successor; FPDF changes rarely. None of that is a reason to avoid them, but each is a reason to decide deliberately rather than by copying the first tutorial that appears.

Sources