Effortless PDF Generation in Laravel: A Guide to Using Spatie/Browsershot Package

Harish Kumar · · 1434 Views

Looking to generate or export PDF files using Laravel? Look no further! In this article, we'll guide you through using the Laravel spatie/browsershot package to seamlessly convert your web pages into downloadable PDFs. The browsershot package, a popular Laravel wrapper for the powerful Puppeteer library, provides a simple and intuitive way to generate PDFs with minimal effort. Whether you need to generate invoices, reports, or any other printable documents, this package has got you covered. With its straightforward syntax and extensive customization options, the spatie/browsershot package allows you to capture web pages as PDFs with just a few lines of code. You can easily set the paper size, margins, headers, footers, and even emulate mobile devices if needed. Don't let the complexity of PDF generation bog you down. Join us as we explore the ins and outs of the Laravel BrowserShot package and unlock the full potential of generating or exporting PDFs in your Laravel applications. Stay tuned for our step-by-step tutorial, where we'll walk you through the process, providing practical examples and tips along the way.

Why Choose Spatie/BrowserShot?

Spatie/BrowserShot offers several advantages over pure PHP solutions:

  1. Dynamic content: Render dynamic web pages and elements like charts and forms accurately.

  2. Styling flexibility: Leverage the power of CSS to style your PDFs as you please.

  3. HTML conversion: Generate PDFs from existing HTML templates or URLs.

  4. Headless magic: Work behind the scenes without opening a browser window.

  5. Customizable options: Fine-tune PDF settings like margins, page size, and headers/footers.

Setting up Laravel and Installing the spatie/browsershot Package

To get started with generating PDFs in Laravel, we first need to set up a Laravel project and install the spatie/browsershot package. Begin by creating a new Laravel project using the Laravel installer or composer. Once your project is set up, navigate to its root directory and open a terminal or command prompt.

composer require spatie/browsershot

This command will download and install the package along with its dependencies. After the installation is complete, Laravel will automatically discover the package and make its features available throughout your application.

Now that the spatie/browsershot package is installed, we can proceed to generate our first PDF using this powerful Laravel wrapper for Puppeteer.

Generating a Basic PDF Using spatie/browsershot

Generating a basic PDF using the spatie/browsershot package is incredibly easy. To begin, open a new route or controller method where you want to generate the PDF. In this example, we'll use a simple route.

php Route::get('/generate-pdf', function () { 
    return Browsershot::url('https://example.com')
             ->save('path/to/save/pdf.pdf');
});

In the above code, we use the Browsershot class provided by the spatie/browsershot package to generate a PDF. We specify the URL of the web page we want to convert to a PDF using the url() method, and then call the save() method to generate the PDF.

In this example, we save the PDF to the path/to/save/pdf.pdf location. Feel free to change the file path according to your needs.

That's it! With just a few lines of code, we have successfully generated a basic PDF using the spatie/browsershot package. Next, let's explore how we can customize the appearance and layout of our PDFs.

Customizing the PDF Appearance and Layout

The spatie/browsershot package provides a range of customization options to tailor the appearance and layout of your PDFs. Let's take a look at some of the most commonly used options.

Setting Paper Size and Orientation

By default, the spatie/browsershot package generates PDFs in the A4 paper size. However, you can easily change the paper size and orientation according to your requirements. To set a specific paper size, you can use the paperSize() method with the appropriate arguments.

Browsershot::url('https://example.com')
    ->paperSize($width = '210mm', $height = 297mm')
    ->save('example.pdf');

 In the above code, we set the paper size to a custom width of 210mm and height of 297mm, which corresponds to the A4 size. You can modify these values to match any desired paper size.

You can use the format() method and provide a predefined format size:

Browsershot::url('https://example.com')
    ->format('A4')
    ->save('example.pdf');

Adjusting Margins

The spatie/browsershot package allows you to adjust the margins of your PDFs. You can set the margin values individually for each side (top, right, bottom, left) using the margins() method.

Browsershot::html($someHtml)
   ->margins($top, $right, $bottom, $left)
   ->save('example.pdf');

Exporting Dynamic Content from a Laravel View to a PDF

The spatie/browsershot package allows you to export dynamic content from a Laravel view to a PDF, making it easy to generate printable versions of your dynamically generated web pages. Let's see how we can achieve this.

Rendering a Laravel View to PDF

To export dynamic content from a Laravel view to a PDF, we can use the Browsershot class and the html() method. The html method allows us to pass the HTML content of a view to generate the PDF.

$data = [ 'invoiceNumber' => 'INV-001', 'customerName' => 'John Doe', 'totalAmount' => 100.00];

$html = view('pdf.invoice', $data)->render();

Browsershot::html($html)->save('example.pdf');

In the above code, we render the pdf.invoice view with the provided $data and pass the resulting HTML content to the html() method of the Browsershot class. This will generate a PDF based on the content of the view.

You can customize the view and pass any necessary data to it using the view helper function. Make sure to replace pdf.invoice with the actual name of your view.

Adding Headers, Footers

By default a PDF will not show the header and a footer. Here's how you can make the header and footer appear. You can also provide a custom HTML template for the header and footer.

Browsershot::html($someHtml)
   ->showBrowserHeaderAndFooter()
   ->headerHtml($someHtml)
   ->footerHtml($someHtml)
   ->save('example.pdf');

Conclusion

In this article, we've explored the process of generating and exporting PDFs using the Spatie/Browsershot package in Laravel. Leveraging the power of Puppeteer, this package provides a seamless and efficient way to convert HTML views into PDF documents. With the provided steps, you can easily integrate this functionality into your Laravel applications, enhancing their capabilities to handle PDF generation requirements.

0

Please login or create new account to add your comment.

0 comments
You may also like:

Laravel Pint & VS Code: Automate Your Code Formatting

Laravel Pint is an opinionated PHP code style fixer built on top of PHP-CS-Fixer, designed to simplify the process of ensuring clean and consistent code style in Laravel projects. (...)
Harish Kumar

Laravel Clockwork: A Deep Dive into Debugging, Profiling Skills and Best Practices

In the world of web development, building complex applications often comes with the challenge of identifying and resolving performance bottlenecks. This is where a reliable debugging (...)
Harish Kumar

Part #3: Rule objects based custom validation in Laravel

Laravel comes with multiple ways to add custom validation rules to validate form request inputs. I have already explained some of the ways in the following article links:
Harish Kumar

Part #2: How to use Laravel's Validator::extend method for custom validation

Validation is important in any application as it validates a form before performing actions on it. It allows the user to know their input is accurate and confident about the operation (...)
Harish Kumar

Part #1: Closure-based Custom Laravel Validation

While I was working with Laravel, validation using closure came to my mind, and I know it will be helpful to you. This tutorial assists you with all what is the difference between (...)
Harish Kumar

How to use the enumerations(Enums) of PHP 8.1 in Laravel?

The release of PHP 8.1 brings native enumerations to PHP. There is no more requirement for custom solutions in your Laravel projects since the Laravel v8.69 release has you back. (...)
Harish Kumar