DEV Community

Harish Kumar
Harish Kumar

Posted on

10

Generating PDFs with spatie/browsershot in Laravel

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.


Laravel PDF Export Tutorial

Installation

You can install the package via Composer:



composer require spatie/browsershot


Enter fullscreen mode Exit fullscreen mode

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');


Enter fullscreen mode Exit fullscreen mode

You can also pass a view to convert the rendered HTML to PDF:



$pdf = Browsershot::html('hello-world-template', ['name' => 'John'])
    ->savePdf('report.pdf');


Enter fullscreen mode Exit fullscreen mode

To generate a PDF from a URL:



Browsershot::url('https://www.example.com')
    ->savePdf('example.pdf');


Enter fullscreen mode Exit fullscreen mode

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');

Enter fullscreen mode Exit fullscreen mode




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.

Buy Me A Coffee

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs