Laravel Magazine

Effortlessly Generate PDFs in Laravel Apps with spatie/laravel-pdf

Eric Van Johnson · Packages
Effortlessly Generate PDFs in Laravel Apps with spatie/laravel-pdf

Spatie just announced their new package called Laravel PDF. The package helps you generate PDFs from Blade files using Chromium under the hood. It also allows you to use a CSS framework like Tailwind to make your PDFs look beautiful.

To understand how the package works, let's render a Blade view with some data and save it as a PDF:

use Spatie\LaravelPdf\Facades\Pdf;

Pdf::view('pdfs.invoice', ['invoice' => $invoice])
    ->format('a4')
    ->save('invoice.pdf')

Or we can return the PDF as a response from a controller like so:

use Spatie\LaravelPdf\Facades\Pdf;

class DownloadInvoiceController
{
    public function __invoke(Invoice $invoice)
    {
        return Pdf::view('pdfs.invoice', ['invoice' => $invoice])
            ->format('a4')
            ->name('your-invoice.pdf');
    }
}

Another cool feature of this package is the @pageBreak directive that allows you to create a multiple pages PDF with ease:

// blade view
<div>
    Page 1
</div>

@pageBreak

<div>
    Page 2
</div>
// controller
Pdf::view('view-with-multiple-pages')->save($path);

In this article we only scratched the surface of this package but in reality you have many more options that you can use like page number, page format, page orientation and many more.

Stay Updated

Subscribe to our newsletter

Get latest news, tutorials, community articles and podcast episodes delivered to your inbox.

Weekly articles
We send a new issue of the newsletter every week on Friday.
No spam
We'll never share your email address and you can opt out at any time.