January 2nd, 2024

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

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:

1use Spatie\LaravelPdf\Facades\Pdf;
2 
3Pdf::view('pdfs.invoice', ['invoice' => $invoice])
4 ->format('a4')
5 ->save('invoice.pdf')

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

1use Spatie\LaravelPdf\Facades\Pdf;
2 
3class DownloadInvoiceController
4{
5 public function __invoke(Invoice $invoice)
6 {
7 return Pdf::view('pdfs.invoice', ['invoice' => $invoice])
8 ->format('a4')
9 ->name('your-invoice.pdf');
10 }
11}

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

1// blade view
2<div>
3 Page 1
4</div>
5 
6@pageBreak
7 
8<div>
9 Page 2
10</div>
1// controller
2Pdf::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.

Statamic Ninja

Comments

Marian Pop

PHP / Laravel Developer. Writing and maintaining @LaravelMagazine. Host of "The Laravel Magazine Podcast". Pronouns: vi/vim.

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.