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.
-
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