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 210</div>
1// controller2Pdf::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.
Read about all features in this blog post: https://freek.dev/2625-easily-create-pdfs-in-laravel-apps
Check out the docs: https://spatie.be/docs/laravel-pdf/v1/introduction
The GitHub Repo: https://github.com/spatie/laravel-pdf
Written by
Writing and maintaining @LaravelMagazine. Host of "The Laravel Magazine Podcast". Pronouns: vi/vim.
Get latest news, tutorials, community articles and podcast episodes delivered to your inbox.