Tech Verse Logo
Enable dark mode
Laravel PDF Generator: Spatie Laravel PDF vs Laravel DomPDF

Laravel PDF Generator: Spatie Laravel PDF vs Laravel DomPDF

•Updated •11 min read

Use barryvdh/laravel-dompdf for table-based invoices and reports on plain PHP hosting. Use spatie/laravel-pdf when you need flexbox, grid or Tailwind and repeating headers, rendered by a Chromium driver such as Browsershot. Spatie also has a DOMPDF driver, queueing with saveQueued() and Pdf::fake() for tests.

Laravel doesn't ship a PDF generator, so every invoice, report or certificate goes through a package that turns HTML into a PDF. The two names everyone finds are barryvdh/laravel-dompdf and spatie/laravel-pdf. The old way of framing the choice was "DomPDF if you can't install Chrome, Spatie if you can", and that no longer holds: spatie/laravel-pdf now has several drivers, and one of them is DomPDF itself. The real decision is which rendering engine you want, and the package follows from that.

Which should I pick?

Pick by how the document is laid out and what you can run on the server. If your PDFs are tables of text (invoices, receipts, payslips, exports) and you want nothing but PHP on the box, DomPDF is enough, and barryvdh/laravel-dompdf gives you the most direct access to it. If the document is designed, with flexbox or grid layouts, Tailwind classes, or a "Page 3 of 7" footer on every page, you need a real browser engine, and spatie/laravel-pdf with a Chromium-based driver is the tool.

For a new project I'd start with spatie/laravel-pdf even for simple documents. You can begin on its DOMPDF driver, switch to a Chromium driver later by changing one environment variable, and you get queueing and test fakes built in. I'd keep barryvdh/laravel-dompdf where it's already installed and working, or where you need the raw Dompdf canvas (custom page stamping, for example), which the wrapper exposes and Spatie's driver doesn't.

What each package does and which engine renders the PDF

barryvdh/laravel-dompdf is a thin Laravel wrapper around the dompdf HTML-to-PDF library. Dompdf is written in PHP, parses your HTML and CSS itself, and lays the page out with its own engine. There's no browser involved, which is why it installs anywhere Composer runs. The wrapper adds a facade, a published config/dompdf.php, Blade view loading, and download(), stream() and save() helpers.

spatie/laravel-pdf is a builder API (Pdf::view(), format(), margins(), headerView() and so on) that hands the rendered HTML to a driver. The spatie/laravel-pdf README on GitHub lists six: Browsershot (Chromium through Node and Puppeteer), chrome-php/chrome (Chromium driven from PHP, no Node), Gotenberg (a Docker service), Cloudflare Browser Run (a hosted Chromium API), WeasyPrint (a Python tool with strong CSS paged-media support) and DOMPDF (pure PHP). The default is browsershot. None of the engine packages are hard dependencies, so you install the one you want next to it.

One naming trap: both packages call their facade Pdf, and laravel-dompdf also registers a global Pdf alias. Always import the full class (Barryvdh\DomPDF\Facade\Pdf or Spatie\LaravelPdf\Facades\Pdf) so the use line, not alias order, decides which one you get.

Generating a PDF with laravel-dompdf

Install the wrapper; it pulls in dompdf and its font library:

composer require barryvdh/laravel-dompdf

A controller that renders a Blade view and sends it as a download looks like this. The page_text() call is the part people miss: CSS can print the current page number, but in my test counter(pages) came out as "0", because the total isn't known until layout finishes. Rendering first and then stamping text onto every page through the Dompdf canvas gives a correct "Page 1 of 3".

<?php

namespace App\Http\Controllers;

use App\Models\Invoice;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Response;

class InvoicePdfController extends Controller
{
    public function __invoke(Invoice $invoice): Response
    {
        $pdf = Pdf::loadView('pdf.invoice', ['invoice' => $invoice])
            ->setPaper('a4', 'portrait');

        // Page totals only exist after layout, so render first, then stamp them.
        $pdf->render();

        $dompdf = $pdf->getDomPDF();
        $font = $dompdf->getFontMetrics()->getFont('DejaVu Sans');
        $dompdf->getCanvas()->page_text(500, 810, 'Page {PAGE_NUM} of {PAGE_COUNT}', $font, 8);

        return $pdf->download("invoice-{$invoice->number}.pdf");
    }
}

The view sticks to what Dompdf handles well: a table for layout, and a position: fixed header, which Dompdf repeats on every page. The negative top pulls it up into the space the @page margin leaves free.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <style>
        @page { margin: 30mm 15mm 25mm 15mm; }
        body { font-family: "DejaVu Sans", sans-serif; font-size: 11px; }
        header { position: fixed; top: -20mm; left: 0; right: 0; height: 12mm; }
        table { width: 100%; border-collapse: collapse; }
        th, td { border-bottom: 1px solid #ddd; padding: 6px; text-align: left; }
        td.amount, th.amount { text-align: right; }
    </style>
</head>
<body>
    <header>Invoice {{ $invoice->number }} for {{ $invoice->customer_name }}</header>

    <table>
        <thead>
            <tr><th>Description</th><th class="amount">Amount</th></tr>
        </thead>
        <tbody>
            @foreach ($invoice->lines as $line)
                <tr>
                    <td>{{ $line['description'] }}</td>
                    <td class="amount">{{ number_format($line['amount'], 2) }}</td>
                </tr>
            @endforeach
        </tbody>
    </table>

    <p style="text-align: right;"><strong>Total: {{ number_format($invoice->total, 2) }}</strong></p>
</body>
</html>

With 60 line items this produced a three-page A4 PDF, the header and table heading repeated on each page, and the footer read "Page 1 of 3" through "Page 3 of 3". It rendered in about a tenth of a second on my machine.

Generating a PDF with spatie/laravel-pdf

Install the package plus the engine for the driver you want. With no engine installed, the default Browsershot driver fails with "The spatie/browsershot package is required to use the Browsershot driver", which is the first error most people hit.

composer require spatie/laravel-pdf

# Pure PHP, nothing else to install on the server
composer require dompdf/dompdf

# Or Chromium through Node and Puppeteer
composer require spatie/browsershot
npm install puppeteer

Pick the driver in .env (publish the config with php artisan vendor:publish --tag=pdf-config if you want to see every option in config/laravel-pdf.php):

LARAVEL_PDF_DRIVER=dompdf

The controller can return the builder directly, because it's Responsable. name() sends the PDF inline so the browser shows it; chain download() instead to force a download. You can also override the driver per document with ->driver('browsershot').

<?php

namespace App\Http\Controllers;

use App\Models\Invoice;
use Spatie\LaravelPdf\Facades\Pdf;
use Spatie\LaravelPdf\PdfBuilder;

class DownloadInvoiceController extends Controller
{
    public function __invoke(Invoice $invoice): PdfBuilder
    {
        return Pdf::view('pdf.invoice-modern', ['invoice' => $invoice])
            ->headerView('pdf.header', ['invoice' => $invoice])
            ->footerView('pdf.footer')
            ->format('a4')
            ->margins(25, 15, 20, 15)
            ->name("invoice-{$invoice->number}.pdf");
    }
}

Set format() explicitly. Spatie's default paper size is Letter, while laravel-dompdf defaults to A4 through default_paper_size in its config, so the same view can come out a different size depending on which package rendered it.

CSS support: flexbox, grid and Tailwind

This is where the engines really differ. Dompdf supports most of CSS 2.1 and a handful of CSS3 properties, and its README lists flexbox and grid as unsupported. It doesn't error when it meets them; it ignores them. I rendered a three-card display: flex row and a three-column grid through both engines: Chromium laid them out side by side, and Dompdf stacked every card full-width, one under another. The dompdf CSS compatibility table is the page to check before you use a property.

That's also why swapping drivers isn't free. The invoice-modern view behind that controller, a flex row for the billing details and a two-column grid for the line items, rendered cleanly through Browsershot and the chrome-php driver and fell apart under the DOMPDF driver: the two-column grid collapsed to one column, and the ✓ characters in the line items became question marks because system-ui fell back to Helvetica. If you plan to start on DOMPDF and move to Chromium later, write the view for DOMPDF (tables, floats, explicit fonts) and it will render under both.

Tailwind works with the Chromium drivers, since they're a real browser. With Dompdf, utility classes built on flex and grid won't do anything, and remote stylesheets don't load anyway: laravel-dompdf has enable_remote set to false by default, and local files must sit inside the chroot, which defaults to your project root.

Fonts and Unicode

Dompdf ships the 14 standard PDF fonts plus DejaVu. The standard fonts (Helvetica, Times, Courier) only cover basic Latin, so a name like "Zoë" prints but a ✓ or any CJK character comes out as "?". DejaVu Sans covers far more, which is why the invoice view names it first. For anything else, load a TTF with @font-face. laravel-dompdf caches font metrics in storage/fonts, and a fresh Laravel app doesn't have that folder: my first @font-face render failed with fopen(.../storage/fonts/jetbrains_mono_normal_....ufm): Failed to open stream until I created it.

Size is the other surprise. Dompdf embeds whole font files by default, and the three-page DejaVu invoice came out at 880 KB. laravel-dompdf's config sets enable_font_subsetting to false (Dompdf on its own defaults to true); switching it on under options in the published config/dompdf.php brought the same file down to 20 KB. Publish the config and create the font folder before you touch fonts:

php artisan vendor:publish --provider="Barryvdh\DomPDF\ServiceProvider"
mkdir -p storage/fonts

A gotcha with the wrapper: Pdf::setOption() called on its own does nothing to later PDFs, because the facade resolves a fresh instance on every call. Set options in the config file, or chain setOption() on the instance you're rendering. Chromium drivers use fonts installed on the machine plus any @font-face you load, so on a slim Docker image install the fonts your documents need.

Page size, headers and footers

In laravel-dompdf you set paper with setPaper('a4', 'landscape') and margins with an @page rule in CSS. Repeating headers and footers come from position: fixed elements, and page totals from the canvas, as shown earlier.

spatie/laravel-pdf has format(), paperSize(), landscape(), margins(), and headerView()/footerView(), with @pageNumber and @totalPages Blade directives. Those headers repeat on every page only on the Chromium drivers. The DOMPDF driver just prepends the header to the body and appends the footer, so they appear once, and the page directives print nothing. Worse, a <style> block in the footer becomes part of the main document: my right-aligned footer right-aligned the entire invoice.

Chromium draws headers and footers in a separate document with its own quirks, which the Spatie docs on formatting PDFs spell out: set a font size (the default is tiny), add your own horizontal padding because margins() doesn't apply to them, avoid width: 100%, and make the top and bottom margins tall enough to hold them. This footer follows those rules:

<style>
    body { margin: 0; padding: 0 15mm; font-family: Helvetica, Arial, sans-serif; font-size: 9px; text-align: right; }
</style>
<div>Page @pageNumber of @totalPages</div>

Server requirements for each driver

DomPDF (either package) needs only PHP with the dom and mbstring extensions, which most hosts have. Browsershot needs Node, the puppeteer npm package, and a Chrome or Chromium binary; Puppeteer downloads its own Chrome on install unless you tell it not to, and you can point the driver at an existing browser with LARAVEL_PDF_CHROME_PATH, plus LARAVEL_PDF_NODE_BINARY when Node isn't on the web user's PATH. The chrome driver needs composer require chrome-php/chrome and a Chrome binary but no Node. Gotenberg needs a running container, WeasyPrint needs its binary plus pontedilana/php-weasyprint, and Cloudflare needs an API token and account ID and nothing local. The laravel-pdf requirements page lists each.

Remember the queue workers. If PDFs are built in jobs, the Chrome binary and fonts have to be on the worker servers too, not just the web servers.

Queueing large PDFs

Chromium rendering takes noticeably longer than Dompdf (over a second per document in my runs, most of it starting the browser), and a long report can blow through a web request's timeout with either engine. Move it to a queue. spatie/laravel-pdf has this built in: saveQueued() renders the Blade view straight away, then dispatches a GeneratePdfJob that runs the driver and writes the file.

<?php

namespace App\Http\Controllers;

use App\Models\Invoice;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Spatie\LaravelPdf\Facades\Pdf;
use Throwable;

class QueueInvoicePdfController extends Controller
{
    public function __invoke(Invoice $invoice): JsonResponse
    {
        Pdf::view('pdf.invoice-modern', ['invoice' => $invoice])
            ->format('a4')
            ->disk('local')
            ->saveQueued("invoices/{$invoice->number}.pdf", queue: 'pdfs')
            ->then(fn (string $path, ?string $diskName) => Log::info("Invoice PDF ready at {$path}"))
            ->catch(fn (Throwable $e) => Log::error('Invoice PDF failed', ['error' => $e->getMessage()]));

        return response()->json(['status' => 'queued'], 202);
    }
}

Running php artisan queue:work --queue=pdfs picked the job up, wrote invoices/INV-8349.pdf to the local disk and logged the then message. Two limits: saveQueued() refuses to run with a withBrowsershot() closure, and to change tries or timeouts you extend GeneratePdfJob and point the job key in config/laravel-pdf.php at your class.

laravel-dompdf has no queue helper, so write an ordinary Laravel queued job. Its save() method takes a disk name as the second argument:

<?php

namespace App\Jobs;

use App\Models\Invoice;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

class GenerateInvoicePdf implements ShouldQueue
{
    use Queueable;

    public int $timeout = 120;

    public function __construct(public Invoice $invoice) {}

    public function handle(): void
    {
        Pdf::loadView('pdf.invoice', ['invoice' => $this->invoice])
            ->setPaper('a4')
            ->save("invoices/{$this->invoice->number}.pdf", 'local');
    }
}

Testing PDF generation

spatie/laravel-pdf ships fakes. After Pdf::fake() nothing is rendered and no browser starts; methods that return bytes give back a blank one-page PDF. You then assert on what would have been generated with assertRespondedWithPdf(), assertSaved(), assertQueued(), assertSee() or assertViewIs(), all listed in the laravel-pdf testing docs. laravel-dompdf has no fake, but Dompdf is fast enough to render for real in a test and check the response.

<?php

namespace Tests\Feature;

use App\Models\Invoice;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Spatie\LaravelPdf\Facades\Pdf;
use Spatie\LaravelPdf\PdfBuilder;
use Tests\TestCase;

class InvoicePdfTest extends TestCase
{
    use RefreshDatabase;

    public function test_it_downloads_the_invoice_pdf(): void
    {
        Pdf::fake();

        $invoice = Invoice::factory()->create(['number' => 'INV-1001']);

        $this->get(route('invoices.download', $invoice))->assertOk();

        Pdf::assertRespondedWithPdf(function (PdfBuilder $pdf) {
            return $pdf->downloadName === 'invoice-INV-1001.pdf'
                && $pdf->contains('INV-1001');
        });
    }

    public function test_dompdf_route_returns_a_pdf(): void
    {
        $invoice = Invoice::factory()->create(['number' => 'INV-1002']);

        $response = $this->get(route('invoices.pdf', $invoice));

        $response->assertOk()
            ->assertHeader('Content-Type', 'application/pdf')
            ->assertDownload('invoice-INV-1002.pdf');

        $this->assertStringStartsWith('%PDF-', $response->getContent());
    }
}

Both tests passed with php artisan test. The fake version is the one to copy for Chromium drivers, since it keeps Chrome out of CI entirely.

mPDF and TCPDF

People searching "mpdf vs dompdf" and "tcpdf vs dompdf" are weighing the other two pure-PHP libraries. mPDF also converts UTF-8 HTML to PDF without a browser, has its own HTML header and footer API (SetHTMLHeader(), SetHTMLFooter()), and is licensed GPL-2.0, which matters if you distribute your software. Like Dompdf it implements CSS itself, so check its documentation before relying on any modern layout feature. It has no first-party Laravel wrapper, so you'd call it directly. TCPDF is a different kind of tool: you build pages through PHP method calls rather than HTML, and its README now marks it maintenance-only and points new projects to its successor, tc-lib-pdf. I wouldn't start a Laravel project on TCPDF today unless I needed a feature only it covers.

WRITTEN BY

Full Stack Software Engineer | Laravel · Next.js · AWS

Full Stack Software Engineer with 7+ years of experience building scalable, secure web applications with Laravel, PHP, React, Next.js, and AWS for SaaS, CRM, telecom, and e-commerce companies. Specialized in cloud telephony (FreeSWITCH, SMPP, WebRTC): increased concurrent call capacity by 40% and cut report queries to under 500 ms. Author of open-source Laravel packages with 10K+ downloads on Packagist. Led a team of 4 engineers and shipped production systems for clients in the UAE, USA, India, Saudi Arabia, and Bangladesh.

How we research, write and check articles

    Latest Posts

    View All

    Next.js Middleware Authentication and Token Refresh Flows

    Next.js Middleware Authentication and Token Refresh Flows

    Livewire Performance Optimization Under High Load

    Livewire Performance Optimization Under High Load

    Configuring Nginx Upstream Keepalive for Node Backends

    Configuring Nginx Upstream Keepalive for Node Backends

    Enforcing Immutable State Patterns in React

    Enforcing Immutable State Patterns in React

    FastAPI Dependency Overrides for Integration Testing

    FastAPI Dependency Overrides for Integration Testing

    Stopping Layout Shifts in Next.js Dynamic Imports

    Stopping Layout Shifts in Next.js Dynamic Imports

    Optimizing Agentic Tool Calling Latency

    Optimizing Agentic Tool Calling Latency

    Fixing React Server Component Serialization Errors

    Fixing React Server Component Serialization Errors

    Next.js Route Handler Streaming with ReadableStream

    Next.js Route Handler Streaming with ReadableStream

    React Form Performance: Uncontrolled Inputs and FormData

    React Form Performance: Uncontrolled Inputs and FormData