Browsershot Laravel: Complete Guide to Effortless PDF Generation

In today’s digital space, where information flows seamlessly across the web, there arises a need to capture and preserve valuable web content. Whether it’s archiving web pages, generating dynamic reports, or creating invoices, the ability to convert web content into PDFs is a vital feature for many web applications.

Considering this need, Browsershot – a popular Laravel package enables developers to generate PDFs and screenshots of web pages using Headless Chrome or Puppeteer. This convenient tool can also conduct tasks like generating PDF invoices, reports and capturing website screenshots in your Laravel application.

In this guide, I’ll walk you through the steps to set up and use the Browsershot package in a Laravel project to generate PDFs with Headless Chrome. Let’s dive right in!

Introduction to Browsershot Laravel

Before we delve into the programming terms of PDF generation, let’s familiarize ourselves with Browsershot Laravel.

Browsershot Laravel is a remarkable fusion of two powerful technologies: Laravel, a widely-used open source PHP framework, and Browsershot, a JavaScript library that leverages the Headless version of Chromium browser to render web pages.

This combination offers a seamless and efficient way to convert web pages into PDFs and capture browser screenshots within the Laravel ecosystem.

Browsershot enhances the capabilities of Laravel by allowing server-side coders to perform multiple tasks, such as creating PDF invoices from HTML templates, capturing website previews, or generating reports much more quickly.

Benefits of Adding Browsershot Laravel

Now we know that ‘What is Browsershot Laravel?‘. Moving ahead, we are about to cover the ‘Benefits of Adding Browsershot Laravel‘ which will help you with a deep understanding of why adding Browsershot Laravel to your Laravel Application is a game-changer:

Effortless PDF Generation

Browsershot Laravel streamlines the process of creating PDFs by rendering the entire web page, including all HTML elements, CSS styles, and JavaScript-generated content, into a PDF document.

Whether your Laravel web page contains forms, tables, text, image, or any other HTML elements, Browsershot can be used to generate a PDF representation of the web page , including each component.

Rather than building complex PDF generation functionality from scratch, developers can utilize Browsershot to simplify this task.

Customization Control

With Browsershot Laravel, you gain complete control over PDF customization. You can specify various aspects, including page size, orientation (portrait or landscape), headers, and footers.

Unlike standard browser screenshot, Browsershot Laravel can also offer to fine-tune margins, ensuring that the content gets appropriately spaced. This level of customization empowers developers to tailor the PDF output as per specific requirements and branding.

Seamless Integration

Browsershot seamlessly integrates even in existing Laravel projects. It aligns with Laravel’s conventions and structures, making it straightforward to incorporate PDF generation capabilities into your web applications.

This Browsershot integration in the Laravel app can be seamlessly conducted through the composer, serving as a readily available package.

The entire integration results in a Laravel-friendly API, ensuring that developers can smoothly incorporate Browsershot into their projects for capturing web page screenshots and generating PDFs within the Laravel ecosystem.

Precise Rendering with Headless Chrome

Browsershot Laravel leverages the power of Headless Chrome, a headless web browser, to achieve accurate rendering of web pages, including those with JavaScript-generated content.

This means that PDFs will exactly represent the web content, preserving complex layouts and interactive elements. Browsershot ensures precise rendering of web pages, making it a reliable choice for capturing web content as images or PDF documents within the Laravel application.

Automation Potential

Here, you can’t neglect that rather than default options Browsershot is better for generating screenshots of web pages. By integrating Browsershot into a Laravel application, developers can automate various PDF generation tasks efficiently.

Also, scheduled tasks allow you to generate PDFs at predefined intervals, making it ideal for tasks like producing weekly reports or archiving important documents automatically. Thus, this automation potential of Browsershot is one of its significant strengths.

Moreover, these capabilities are massively valuable during automating routine tasks such as generating weekly reports, archiving essential documents, or producing dynamic PDF files based on user interactions.

Prerequisites to Generate PDF Using Browsershot Laravel

Eager to add a Browsershot package in Laravel? We are about to move on that, but let’s first ensure we have the necessary tools in place:

  • Laravel Installation: Laravel should be installed and set up in your development environment. This includes having a Laravel project in place. You can also create using Composer by running composer ‘create-project laravel/laravel‘.
  • Node.js and NPM: As Browsershot relies on these tools for underlying dependencies and for executing JavaScript in web pages, having Node.js and npm (Node Package Manager) installed on the system is a must. If your system environment doesn’t include it currently, you can install it from the official site of Nodejs.
  • PHP 8+ Version: Ensure you are using higher than PHP version 8 – Browsershot and its dependencies may require features and capabilities available in PHP 8.
  • Composer Dependencies: Including the Browsershot package, make sure you have other necessary Composer dependencies such as Process, Ziggy, and Panther. You can install these dependencies using Composer with the command require:
    • spatie/browsershot
    • symfony/process
    • tightenco/ziggy
    • symfony/panther
  • Server Dependencies: Depending on the server environment you are using, you need to ensure that certain dependencies – for example, Chromium (for Headless Chrome), are available and properly configured. This is especially relevant if planning to deploy your Laravel application to a production server.

Step by Step Guide to Generate PDF Using Browsershot Laravel

Here are the steps to generate PDFs using Browsershot in Laravel:

Step 1: Install Browsershot

Install the Browsershot package via Composer:

composer require spatie/browsershot

Step 2: Install Puppeteer

Browsershot relies on Puppeteer, so you need to install it using NPM:

npm install puppeteer

Step 3: Configure Browsershot

Browsershot requires you to set the path to the Puppeteer executable. You can add this configuration in your config/services.php file:

'browsershot' => [
   'node' => env('BROWSERSHOT_NODE_BINARY', null),
   'npm' => env('BROWSERSHOT_NPM_BINARY', null),
   'bin' => env('BROWSERSHOT_CHROME_BIN', null),
],

You can set these values in your .env file as well:

BROWSERSHOT_NODE_BINARY=/path/to/node
BROWSERSHOT_NPM_BINARY=/path/to/npm
BROWSERSHOT_CHROME_BIN=/path/to/chrome

Make sure to replace /path/to/node, /path/to/npm, and /path/to/chrome with the actual paths to your Node.js, NPM, and Chrome executables.

Step 4: Generate PDFs

You can now use Browsershot to generate PDFs in your Laravel application. Here’s an example of how to use it in a controller method:

use Spatie\Browsershot\Browsershot;
public function generatePdf()
{
   Browsershot::url('https://example.com')
       ->save('/path/to/save/pdf.pdf');
}

In this example, we’re generating a PDF from the “https://example.com” URL and saving it to a specified file path.

Step 5: Generate PDF Using Laravel View

public function printPdf()
   {           
       $view =  view('welcome')->render();        
       $path = public_path("/pdf_temp/");
       if (!File::exists($path)) {
           File::makeDirectory($path, 0755, true);
       }
       Browsershot::html($view)->save($path.'htmlToPdf.pdf');       
         
   }

Step 6: Route and Access

Create a route in routes/web.php to access your PDF generation method:

Route::get('/generate-pdf', 'YourControllerName@generatePdf');
Route::get('/printPdf', 'YourControllerName@printPdf');

You can then access the PDF generation page by visiting “/generate-pdf” and “/printPdf” in your browser.

That’s it! You’ve successfully set up Browsershot in your Laravel project to generate PDFs using Headless Chrome. You can customize the Browsershot options further to capture specific elements of web pages or adjust the PDF generation settings as needed for your application.

FAQs About Generating PDF Using Browsershot Laravel

What customization options does Browsershot offer for PDF generation?
Browsershot allows you to customize PDFs by specifying:
  • Page size
  • Orientation (portrait or landscape)
  • Margins
  • Headers and footers
  • Custom styling
  • Overall PDFs layout
How can I automate PDF generation with Browsershot in Laravel?
You can automate PDF generation with Browsershot in Laravel through:
  • Scheduled tasks or cron jobs to generate PDFs at predefined intervals.
  • Event-driven automation by triggering PDF generation based on user interactions or specific application events. You can use submissions or user actions as an example.
How can I trigger PDF generation with Browsershot in response to specific user actions in my Laravel application?
  • To trigger PDF generation with Browsershot in response to specific user actions in your Laravel application, incorporating Browsershot commands into your application's logic would be best.
  • For example, when a user submits a form, use Laravel's event handling or controller methods to call Browsershot and generate a PDF based on the form data or other user-specific content.
  • This event-driven automation allows you to dynamically create PDFs tailored to user interactions, providing personalized and timely documents.

Conclusion

In this blog post, we’ve covered a step-by-step guide of PDF generation using Browsershot Laravel. We’ve explored its benefits, discussed prerequisites, and detailed steps that can get you started even if you are a complete Laravel beginner.

Besides that, as you continue exploring, and experimenting with different customization options and use cases – will definitely unlock the full potential of PDF generation within your Laravel application.

If you need any further assistance regarding Laravel development or Browsershot setup feel free to get in touch with us.

author
Mayur Upadhyay is a tech professional with expertise in Shopify, WordPress, Drupal, Frameworks, jQuery, and more. With a proven track record in web development and eCommerce development.

Leave a comment