The spatie/browsershot
package provides an easy way to generate PDFs from HTML in Laravel applications. With just a few lines of code, you can convert blades, DOM elements, or external URLs to PDFs.
Installation
You can install the package via Composer:
composer require spatie/browsershot
This will install the package and its dependencies.
Usage
To generate a PDF from a blade template, you can do:
// Load the template
$template = (new \Spatie\Browsershot\Browsershot())
->bodyHtml('<h1>Hello World</h1>')
// Save as a PDF
$template->savePdf('hello-world.pdf');
You can also pass a view to convert the rendered HTML to PDF:
$pdf = Browsershot::html('hello-world-template', ['name' => 'John'])
->savePdf('report.pdf');
To generate a PDF from a URL:
Browsershot::url('https://www.example.com')
->savePdf('example.pdf');
There are many other options like setting paper size, margins, landscape/portrait orientation, and more.
Headers and Footers
You can add custom HTML headers and footers to the PDF using the headerHtml
and footerHtml
methods:
Browsershot::url('https://www.example.com')
->headerHtml('<p>This is my header</p>')
->footerHtml('<p>Copyright 2021</p>')
->savePdf('example.pdf');
Additional Options
Here are some other useful options:
-
setNodeBinary
- Set a custom Node binary to use for PDF generation -
setNpmBinary
- Set a custom NPM binary to use for PDF generation -
setOption
- Customize the underlying wkhtmltopdf options -
showBackground
- Show background graphics and colors -
landscape
- Orient page landscape -
margins
- Set margins (in mm) -
pages
- Convert only specific pages
Here you can more about
PDF generation via browsershot.
Demo Project
For a full demo project showing PDF generation via browsershot, check out this example Laravel app.
So in summary, the spatie/browsershot package provides a simple Laravel interface to generate PDFs from HTML, CSS, and web URLs. It can be used for many use cases like generating invoices, reports, receipts, and more.
Top comments (0)