Back to Blog

Generate PDFs with PHP: The Best 5 Libraries Compared

Learn about the best PHP libraries for generating PDFs, including FPDF, TCPDF, Dompdf, mPDF, and Browsershot. Compare canvas-based, HTML rendering, and browser-based approaches.

By Alex Cooney |

Introduction

PHP is a popular server-side programming language used to build dynamic websites and web applications. In many PHP projects, a common need is to generate PDF files such as invoices for online stores, reports for businesses, or downloadable documents for users.

With PHP's robust ecosystem, there are several mature libraries available to handle PDF generation, each with its own strengths tailored to different use cases. This guide aims to help you navigate these options by comparing five top libraries to help you choose the one that works best for your needs.

Generally, PHP PDF libraries can be grouped into three main categories based on how they generate documents:

  • Canvas-based: These libraries treat the PDF like a blank canvas where you manually position text, images, and shapes using coordinates. Examples include FPDF and TCPDF.
  • Browser-based: This approach uses tools like Browsershot, which leverage headless browsers (Chrome via Puppeteer) to convert web pages into PDFs. They offer very accurate results because they support modern HTML, CSS, and JavaScript, but they usually need more system resources.
  • HTML rendering engines: These libraries let you parse HTML and CSS directly into PDFs using PHP-based engines. Popular options include Dompdf and mPDF.

1. FPDF

FPDF (Free PDF) is perhaps the oldest and most minimal PHP PDF library. It's a pure PHP solution that doesn't rely on any external binaries or extensions beyond the basics. It also gives developers complete control over PDF creation through a straightforward coordinate-based API.

To install FPDF, you can use Composer:

bash
composer require setasign/fpdf:^1.8

Alternatively, you can download the zip file containing a single PHP script file to run FPDF directly.

The following example creates a simple receipt with a table:

php
<?php
require 'vendor/autoload.php';
 
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial', 'B', 16);
$pdf->Cell(40, 10, 'Receipt');
$pdf->Ln(20);
 
// Header
$pdf->SetFont('Arial', 'B', 12);
$pdf->Cell(80, 10, 'Item');
$pdf->Cell(40, 10, 'Quantity');
$pdf->Cell(40, 10, 'Price');
$pdf->Cell(40, 10, 'Total');
$pdf->Ln();
 
// Line items
$pdf->SetFont('Arial', '', 12);
$items = [
    ['Product A', 2, 10.00, 20.00],
    ['Product B', 1, 15.00, 15.00],
    ['Product C', 3, 5.00, 15.00]
];
$total = 0;
foreach ($items as $item) {
    $pdf->Cell(80, 10, $item[0]);
    $pdf->Cell(40, 10, $item[1]);
    $pdf->Cell(40, 10, '$' . number_format($item[2], 2));
    $pdf->Cell(40, 10, '$' . number_format($item[3], 2));
    $pdf->Ln();
    $total += $item[3];
}
 
// Total
$pdf->SetFont('Arial', 'B', 12);
$pdf->Cell(160, 10, 'Grand Total');
$pdf->Cell(40, 10, '$' . number_format($total, 2));
 
$pdf->Output('fpdf-receipt.pdf', 'F');

Pros

  • Extremely lightweight with no external binaries, ensuring it runs on virtually any PHP setup.
  • Simple API that's easy to grasp for basic tasks, with a gentle learning curve.
  • Highly stable and battle-tested over 20+ years, with minimal bugs.
  • Excellent portability, ideal for environments with restrictions on extensions.

Cons

  • Lacks native Unicode support, requiring add-ons for international characters.
  • Everything must be positioned manually, leading to verbose code for complex layouts.
  • No built-in HTML-to-PDF conversion, so it's not suited for templated web content.

Best for

Simple PDF generation where minimal overhead and maximum portability are priorities — think basic invoices, reports, or labels where you have complete control over the content structure.

For more information, see FPDF documentation.

2. TCPDF

TCPDF is an open source PHP class for generating PDF documents. It builds upon FPDF's foundation but transforms it into an enterprise-grade PDF generation suite. While maintaining the canvas-based approach, it adds extensive features, including Unicode support, barcodes, QR codes, digital signatures, encryption, and even basic HTML parsing.

You can install the library via Composer:

bash
composer require tecnickcom/tcpdf

Here's an example creating a shipping label with barcodes and QR codes:

php
<?php
require 'vendor/autoload.php';
 
$pdf = new TCPDF();
$pdf->SetMargins(15, 15, 15);
$pdf->AddPage();
 
/* Title */
$pdf->SetFont('helvetica', 'B', 16);
$pdf->Cell(0, 10, 'SHIPPING LABEL', 0, 1, 'C');
 
/* Divider line */
$pdf->Line(15, $pdf->GetY(), 195, $pdf->GetY());
$pdf->Ln(6);
 
/* Address Box */
$pdf->SetFont('helvetica', 'B', 11);
$pdf->Cell(0, 8, 'Recipient', 0, 1);
 
$pdf->SetFont('helvetica', '', 10);
$pdf->SetFillColor(245, 245, 245);
$pdf->MultiCell(
    0,
    20,
    "John Doe\n123 Main St\nCity, State 12345",
    1,
    'L',
    true
);
 
$pdf->Ln(8);
 
/* Barcode Section */
$pdf->SetFont('helvetica', 'B', 11);
$pdf->Cell(0, 8, 'Tracking Number', 0, 1);
 
$pdf->write1DBarcode(
    '123456789',
    'C128',
    '',
    '',
    120,
    25,
    0.4,
    [
        'border' => false,
        'padding' => 2,
        'text' => true,
        'font' => 'helvetica',
        'fontsize' => 9
    ],
    'N'
);
 
$pdf->Ln(5);
 
/* QR Code */
$pdf->SetFont('helvetica', 'B', 11);
$pdf->Cell(0, 8, 'Scan for Tracking', 0, 1);
 
$pdf->write2DBarcode(
    'https://example.com/tracking/123',
    'QRCODE,H',
    '',
    '',
    35,
    35
);
 
$pdf->Output(__DIR__ . '/shipping_label.pdf', 'F');

Pros

  • Feature-rich, including barcodes, QR codes, digital signatures, and encryption out of the box.
  • Outstanding Unicode and multilingual support, handling RTL languages flawlessly.
  • No external binaries needed. It runs purely in PHP with common extensions.
  • It has thorough documentation, many examples, and a large existing community.

Cons

  • Slower performance and higher memory usage compared to FPDF, especially for large files.
  • Steep learning curve due to the sheer volume of options and methods.
  • Output PDFs often have larger file sizes because of embedded features.

Best for

Enterprise documents like invoices or labels requiring barcodes, multilingual text, or security features.

You can explore the library's documentation at https://tcpdf.org/.

3. Dompdf

Dompdf is a popular PHP library that converts HTML documents into PDF files. It works by rendering HTML and CSS directly, making it especially useful for generating PDFs from existing web pages or templates without rewriting layouts from scratch.

At its core, Dompdf is a largely CSS 2.1-compliant rendering engine written entirely in PHP. For PDF generation, Dompdf can use either PDFLib or a bundled version of the R&OS CPDF library.

To install the library using Composer, run:

bash
composer require dompdf/dompdf

Dompdf requires common PHP extensions, such as mbstring for Unicode handling and gd for image processing, but these are typically available on modern PHP installations.

Here's an example creating an event ticket using HTML:

php
<?php
require 'vendor/autoload.php';
 
use Dompdf\Dompdf;
use Dompdf\Options;
 
$options = new Options();
$options->set('defaultFont', 'Helvetica');
$options->set('isRemoteEnabled', true);
 
$dompdf = new Dompdf($options);
 
$html = '
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
@page {
    size: A4;
    margin: 20mm;
}
 
* {
    box-sizing: border-box;
}
body {
    font-family: Helvetica, Arial, sans-serif;
    font-size: 12px;
    margin: 0;
}
.ticket {
    width: 100%;
    border: 1px solid #ddd;
}
.header {
    background: #1a237e;
    color: #fff;
    padding: 18px;
    text-align: center;
}
.header h1 {
    margin: 0;
    font-size: 18px;
}
.header p {
    margin: 4px 0 0;
}
table {
    width: 100%;
    border-collapse: collapse;
}
td {
    vertical-align: top;
    padding: 18px;
}
.left {
    width: 65%;
    border-right: 1px dashed #ccc;
}
.right {
    width: 35%;
}
h2 {
    font-size: 13px;
    margin: 0 0 10px;
    border-bottom: 1px solid #1a237e;
    padding-bottom: 4px;
}
.row {
    margin-bottom: 6px;
}
.label {
    font-weight: bold;
}
.qr {
    text-align: center;
    margin-top: 12px;
}
.qr img {
    width: 110px;
    height: 110px;
}
.footer {
    background: #f5f5f5;
    padding: 12px;
    text-align: center;
    font-size: 10px;
}
</style>
</head>
<body>
<div class="ticket">
    <div class="header">
        <h1>TECH CONFERENCE 2024</h1>
        <p>Premium Access Ticket</p>
    </div>
    <table>
        <tr>
            <td class="left">
                <h2>Event Information</h2>
                <div class="row"><span class="label">Date:</span> Oct 15-17, 2024</div>
                <div class="row"><span class="label">Venue:</span> SF Convention Center</div>
                <div class="row"><span class="label">Address:</span> 747 Howard St</div>
                <div class="row"><span class="label">Type:</span> 3-Day VIP Pass</div>
            </td>
            <td class="right">
                <h2>Attendee</h2>
                <div class="row"><span class="label">Name:</span> Alex Johnson</div>
                <div class="row"><span class="label">ID:</span> TC2024-VIP-789012</div>
                <div class="qr">
                    <img src="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=TC2024-VIP-789012">
                    <p>Scan to check in</p>
                </div>
            </td>
        </tr>
    </table>
    <div class="footer">
        <p>Present at registration · Non-transferable</p>
        <p>contact@techconference2024.com</p>
    </div>
</div>
</body>
</html>
';
 
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
 
file_put_contents(__DIR__ . '/event_ticket.pdf', $dompdf->output());

Pros

  • Dompdf uses a familiar HTML/CSS workflow that allows web developers to reuse existing templates and speed up PDF generation.
  • It supports external stylesheets, basic SVG, complex tables, including row and column spans, separate and collapsed border models, and individual cell styling.
  • It has a strong integration with Laravel and support from an active developer community.
  • It's actively maintained to remain compatible with modern PHP versions.

Cons

  • Limited CSS support (handles most CSS 2.1 and a few CSS3 properties) and lack of modern layout features such as Flexbox or CSS Grid.
  • It doesn't allow JavaScript execution, restricting usage to static HTML content.
  • Performance can degrade when rendering complex documents or high-resolution images.

Best for

Web developers converting HTML templates into PDFs, particularly within Laravel applications.

For more information on examples and guides, see Dompdf documentation.

4. mPDF

mPDF is another popular library that started as an extension of FPDF and HTML2FPDF but has grown into a robust HTML-to-PDF engine with a strong emphasis on Unicode and RTL languages. It allows developers to convert UTF-8 encoded HTML content into high-quality PDF documents on the fly and is written entirely in PHP.

It offers better CSS handling than Dompdf for print-oriented and multilingual layouts, including built-in support for headers, footers, page numbers, and watermarks.

You can install the library using Composer:

bash
composer require mpdf/mpdf

The following example creates a business letter with a header and watermark:

php
<?php
require 'vendor/autoload.php';
 
$mpdf = new \Mpdf\Mpdf([
    'margin_top' => 35,
    'margin_bottom' => 25
]);
 
// Header
$mpdf->SetHTMLHeader('
<div style="
    text-align:left;
    font-size:14pt;
    font-weight:bold;
    padding-bottom:6px;
">
    Company Name
</div>
<div style="
    border-bottom:1px solid #cccccc;
    margin-bottom:10px;
"></div>
');
 
// Watermark (native mPDF)
$mpdf->SetWatermarkText('CONFIDENTIAL');
$mpdf->showWatermarkText = true;
$mpdf->watermark_font = 'DejaVuSansCondensed';
$mpdf->watermarkTextAlpha = 0.1;
 
$html = '
<style>
    body {
        font-family: Arial, sans-serif;
        font-size: 12pt;
        line-height: 1.6;
        color: #333;
    }
    .letterhead {
        font-size: 20pt;
        font-weight: bold;
        margin-bottom: 25px;
    }
    .content p {
        margin: 0 0 14px;
    }
    .signature {
        margin-top: 30px;
    }
</style>
 
<div class="letterhead">Business Correspondence</div>
 
<div class="content">
    <p>Dear Recipient,</p>
 
    <p>
        This letter demonstrates a modern, clean business document layout generated
        using mPDF. It includes a structured header, consistent typography, and a
        subtle watermark for document classification.
    </p>
 
    <p>
        Please review the information provided and reach out if you need further
        clarification.
    </p>
 
    <div class="signature">
        <p>
            Best regards,<br>
            Sender
        </p>
    </div>
</div>
';
 
$mpdf->WriteHTML($html);
$mpdf->Output('business_letter.pdf', 'F');

Pros

  • Excellent multilingual support, including right-to-left (RTL) scripts and CJK characters.
  • Advanced CSS handling for layouts, with built-in support for headers, footers, and barcodes.
  • Simple to use for generating HTML-based PDFs without requiring external tools.
  • Reliable handling of watermarks, page numbering, and other page elements.

Cons

  • Higher memory usage can affect performance with very large documents.
  • No JavaScript execution, so dynamic content or scripts are not supported.
  • Limited support for modern layout features such as Flexbox and CSS Grid. In fact, mPDF is referred to as "a quite dated software" on its own website.

Best for

Applications that require multilingual PDF generation, especially RTL or complex character support.

For more information, see mPDF documentation.

5. Browsershot

Browsershot, developed by Spatie, is a PHP package that lets you generate PDFs or images from web pages using a real browser engine (Headless Chrome or Puppeteer). Unlike libraries like Dompdf or mPDF, which render HTML with PHP and limited CSS support, Browsershot uses an actual browser under the hood, so modern CSS, JavaScript, and even animations work correctly in the output.

To install the library, run:

bash
composer require spatie/browsershot

Browsershot also requires Node.js and Puppeteer to work. You can find installation instructions on the requirements page.

The following example creates a PDF of a website using its URL:

php
<?php
require 'vendor/autoload.php';
 
use Spatie\Browsershot\Browsershot;
 
Browsershot::url('https://openclaw.ai/')
    ->setOption('landscape', false)
    ->waitUntilNetworkIdle()
    ->setChromePath('/usr/bin/chromium')   // Path to Chrome/Chromium
    ->save(__DIR__ . '/website.pdf');

And this creates a PDF from HTML and CSS:

php
<?php
require 'vendor/autoload.php';
 
use Spatie\Browsershot\Browsershot;
 
// HTML content
$html = '
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        body {
            font-family: Arial, sans-serif;
            font-size: 14px;
            line-height: 1.6;
            color: #333;
            padding: 20px;
        }
        h1 {
            color: #1a237e;
        }
        p {
            margin-bottom: 12px;
        }
        .box {
            padding: 10px;
            background: #f5f5f5;
            border-left: 4px solid #1a237e;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <h1>Sample PDF</h1>
    <p>This PDF is generated from HTML and CSS using Browsershot.</p>
    <div class="box">
        <p>This box uses simple CSS styling to demonstrate layout.</p>
    </div>
</body>
</html>
';
 
// Generate PDF
Browsershot::html($html)
    ->setNodeBinary('/usr/bin/node') // path to Node.js
    ->waitUntilNetworkIdle()
    ->save(__DIR__ . '/sample.pdf');

Pros

  • High-fidelity rendering using a real browser engine.
  • Supports JavaScript, modern CSS, and dynamic content.
  • Can convert existing web pages directly from a URL.
  • Well-maintained with excellent documentation from Spatie.

Cons

  • Requires Node.js and Puppeteer, which may add complexity to server and deployment setups.
  • Higher resource usage (CPU and memory) compared to PHP-only PDF libraries.

Best for

JavaScript-heavy pages or scenarios where browser-like rendering is essential.

You can learn more about Browsershot in its documentation. Also, for more insights about Puppeteer, see How to Generate PDFs with Puppeteer: The Complete Guide.

Note on Snappy: Snappy is another browser-based solution that wraps wkhtmltopdf, which uses an older WebKit engine. While simple and once popular, wkhtmltopdf has seen minimal upstream maintenance in recent years, resulting in outdated support for modern CSS and JavaScript. For new projects, Browsershot with headless Chrome is generally recommended over Snappy.

Comparison Table

Choosing the best PDF tool for your PHP projects can be daunting. To give you a clear overview, the table below summarizes the key differences between each library. Canvas-based options prioritize control and lightweight performance, HTML rendering engines make it easy to leverage existing web skills, and browser-based solutions provide the highest visual accuracy.

LibraryApproachDependenciesBest ForLearning Curve
FPDFCanvas-basedNone (pure PHP)Simple PDFs, maximum portabilityEasy
TCPDFCanvas-basedNone (pure PHP; optional GD, OpenSSL)Barcodes, multilingual support, digital signaturesMedium
DompdfHTML enginePHP extensions (mbstring, GD)Web developers, Laravel projectsEasy
mPDFHTML enginePHP extensions (mbstring, GD)RTL languages, multilingual documentsMedium
BrowsershotBrowser-basedNode.js, Puppeteer, ChromeJavaScript-heavy pages, modern CSS layoutsMedium

Generating PDFs with DocuPotion

The libraries above give you powerful options for generating PDFs in PHP. But as your project grows, you may run into operational headaches: provisioning servers, managing memory for large documents, juggling dependency updates, and ensuring consistent output across different environments.

DocuPotion takes a different approach by handling all of that for you:

  • Visual template editor — Build polished PDF layouts with a drag-and-drop interface, no coordinate math or HTML required
  • Straightforward REST API — Send your data to a template endpoint and get a PDF back in seconds
  • Fully managed infrastructure — No servers to provision, no libraries to install, no memory tuning to worry about

Here's an example of generating a PDF with the DocuPotion API in PHP:

php
<?php
 
$apiKey = 'your_api_key';
$templateId = 'your_template_id';
 
$payload = json_encode([
    'templateId' => $templateId,
    'output' => 'url',
    'expiration' => 60,
    'data' => [
        'customer_name' => 'Jane Smith',
        'invoice_number' => 'INV-2026-001',
        'total' => '$1,250.00',
    ],
]);
 
$ch = curl_init('https://api.docupotion.com/v1/create');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => $payload,
]);
 
$response = curl_exec($ch);
curl_close($ch);
 
$result = json_decode($response, true);
echo 'PDF URL: ' . $result['url'];

A single API call returns a hosted PDF URL you can share or embed directly. DocuPotion takes care of rendering, hosting, and delivery behind the scenes.

Why consider it:

  • Spend your time on application logic, not PDF plumbing
  • Get pixel-consistent output without worrying about server or browser differences
  • Go from generating a handful of PDFs to thousands with no code changes

Learn more:

Conclusion

When choosing a PDF library for PHP, there are three main approaches. Canvas-based libraries like FPDF and TCPDF give you full control over layout and are lightweight. HTML engines such as Dompdf and mPDF let you generate PDFs from HTML and CSS, making them a suitable choice if you're experienced in web development. Browser-based tools like Browsershot use a real browser to render PDFs, supporting JavaScript and modern CSS.

For beginners, Dompdf is a good choice if you are already comfortable with HTML and CSS, while FPDF is better suited for creating very simple PDFs with minimal layout. If your project requires enterprise-level features such as barcodes, QR codes, or digital signatures, TCPDF remains the industry-standard option. For documents that need strong multilingual support or RTL text, mPDF is the most reliable choice. When working with JavaScript-heavy or highly dynamic content, Browsershot is your best bet.

Ultimately, the easiest way to find the right tool is to try a few libraries and choose the one that best matches your workflow and project requirements.