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

Harish Kumar · · 4812 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:

Building a Real-Time Chat App with Laravel Reverb and Nuxt 3

Building a real-time chat application is a great way to understand the power of WebSockets and real-time communication. In this tutorial, we will walk through creating a Real-Time (...)
Harish Kumar

How to Set Up Nuxt 3 Authentication with Laravel Sanctum (Step-by-Step Guide)

In modern web development, securing your application’s authentication process is a top priority. For developers building Single Page Applications (SPA) or Server-Side Rendered (...)
Harish Kumar

Laracon US 2024: Laravel 11 Minor Features That Enhance Performance

At Laracon US 2024, Taylor Otwell and the Laravel team introduced a series of "minor" features for Laravel 11 that are anything but minor. These enhancements, while not headline-grabbing (...)
Harish Kumar

PHP OPCache: The Secret Weapon for Laravel Performance Boost

OPCache, a built-in PHP opcode cache, is a powerful tool for significantly improving Laravel application speed. This guide will demonstrate how to effectively utilize OPCache to (...)
Harish Kumar

How to Use DTOs for Cleaner Code in Laravel, Best Practices and Implementation Guide

When developing APIs in Laravel, ensuring your responses are clear, concise, and consistent is crucial for creating a maintainable and scalable application. One effective way to (...)
Harish Kumar

Data Type Validation in Laravel Collections with the `ensure()` Method

Before moving on to the ensure() method, let us first know what Laravel Collections actually are. These are wrappers of PHP arrays, offering a fluent and helpful interface in interacting (...)
Harish Kumar