Laravel 11 - BrowserShot

Touseef Afridi
18 Feb 25

Laravel 11 - BrowserShot

In this tutorial, we will discuss how to capture high-quality screenshots and generate PDFs in Laravel 11 using BrowserShot for efficient visual content generation in your Laravel application.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

This guide walks you through integrating Browsershot into a Laravel project for capturing high-quality screenshots and PDFs of web pages. It covers the entire setup process, starting with creating a fresh Laravel project and installing the necessary dependencies, including the spatie/browsershot package and Puppeteer for rendering pages. The guide then shows how to create a dedicated controller for managing screenshot and PDF generation, ensuring proper directory setup before saving the files. It explores various methods for capturing screenshots, such as full-page captures, mobile-sized views using custom user agents, and saving webpages as PDFs.

Step # 1 : Create a fresh Laravel project or use an existing one.

To create a new Laravel project named browserShot, run the following command if Laravel is installed globally.
laravel new browserShot
Or
If Laravel is not installed globally, use Composer.
composer create-project laravel/laravel --prefer-dist browserShot
Once the command is executed, you will be prompted with the following options.
  1. Would you like to install the starter kit? — Choose none.
  2. Select the testing framework. — Choose Pest.
  3. Select the database for your application. — Choose mysql.
  4. Run the default database migration? — Choose yes.

Now, we have a fresh Laravel project named browserShot" set up with Pest as the testing framework, MySQL as the database, and the default database migration has been successfully run. The project is now ready for further development and integration.

Step # 2 : Access the project.

Next, open a terminal (e.g., Git Bash) and navigate to the root directory of your Laravel project by running the following command.
cd c:xampp/htdocs/browserShot
This will bring you to the root folder of your newly created Laravel project, where you can begin further setup and configurations.

Step # 3 : Install BrowserShot and Dependencies.

To integrate BrowserShot into your Laravel project, first install the spatie/browsershot package via Composer. This allows you to capture high-quality screenshots of web pages, useful for generating visual previews or thumbnails from dynamic content. You’ll also need Puppeteer, a headless browser automation tool, which is required for BrowserShot to render pages accurately.
Run the following command to install BrowserShot.
composer require spatie/browsershot
Next, install Puppeteer using npm as a project dependency. Puppeteer is used to control headless Chrome for rendering the pages.
npm install puppeteer
Important: Ensure that Node.js and npm are installed on your system before running the above command. If you don’t have them installed, visit the Node.js website (link : http://nodejs.org/en/) to download and install them.

Step # 4 : Create BrowserShot Controller.

To manage screenshot capture, we need to create a dedicated controller. Run the following Artisan command to generate BrowserShotController.
php artisan make:controller BrowserShotController
This will create a new controller file inside the app/Http/Controllers directory. Now, open BrowserShotController.php and add the following code to capture a screenshot of a webpage.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Spatie\Browsershot\Browsershot;
class BrowserShotController extends Controller
{
    public function capture()
    {
    // Define directory and file path
        $directory = public_path('Browsershot');
        $filePath = $directory . '/' . time() . 'screenshot.png';
    // Ensure the directory exists before saving the file (Browsershot doesn't create directories like Laravel's storage helper)
        if (!file_exists($directory)) {
            mkdir($directory, 0755, true);
        }
    // Capture a screenshot of the given URL with a specific window size, ensuring the page is fully loaded before saving the image
        Browsershot::url('https://www.codeshotcut.com/')
        ->windowSize(1920, 1080)
        ->waitUntilNetworkIdle()
        ->save($filePath);
        return "Screenshot saved at: " . $filePath;
    }
}
The BrowserShotController defines the public/Browsershot/ directory as the storage location for screenshots and generates a unique filename using time() to avoid overwriting existing images. Since Browsershot doesn’t automatically create directories like Laravel’s storage helper, the code checks if the directory exists and creates it if necessary. It then captures a screenshot at 1920x1080 resolution for a desktop view and ensures the page is fully loaded using waitUntilNetworkIdle() before taking the screenshot.

Step # 5 : Define a Route.

First, import the BrowserShotController class at the top of your routes/web.php file.
use App\Http\Controllers\BrowserShotController;
Next, define a route in your routes/web.php to handle the screenshot generation.
Route::get('/screenshot', [BrowserShotController::class, 'capture']);

Step # 6 : It's time to test BrowserShot.

Start the Laravel development server by running the following command.
php artisan serve
Now, visit the following URL in your browser: http://127.0.0.1:8000/screenshot. If everything is set up correctly, you should see a success message, and the screenshot will be saved in public/Browsershot/timingscreenshot.png.



To capture a PDF of the webpage using Browsershot in Laravel, use the savePdf() method. Here's the updated code
    public function capture()
    {
    // Define directory and file path
    $directory = public_path('Browsershot');
    $filePath = $directory . '/' . time() . 'document.pdf';
    // Ensure the directory exists before saving the file (Browsershot doesn't create directories like Laravel's storage helper)
    if (!file_exists($directory)) {
        mkdir($directory, 0755, true);
    }
    // Capture a PDF of the given URL, ensuring the page is fully loaded before saving the document
    Browsershot::url('https://www.placeholder.com/')
        ->waitUntilNetworkIdle()
        ->savePdf($filePath);
    return "PDF saved at: " . $filePath;
    }
This will generate a PDF of the specified webpage and save it in the defined path. The savePdf() method captures the webpage as a PDF, preserving the full content in the page. Visit 127.0.0.1:8000/screenshot, and upon success, a PDF of the webpage will be saved in public/Browsershot/.

To capture a full-page screenshot using Browsershot in Laravel, use the fullPage() method. Here's the updated code.
    public function capture()
    {
    // Define directory and file path
        $directory = public_path('Browsershot');
        $filePath = $directory . '/' . time() . 'screenshot.png';
    // Create directory if not exists
        if (!file_exists($directory)) {
            mkdir($directory, 0755, true);
        }
    // Ensures the entire page is captured (Desktop Size)
        Browsershot::url('https://www.placeholder.com/')
        ->windowSize(1920, 1080)
        ->waitUntilNetworkIdle()
        ->fullPage()
        ->save($filePath);
        return "Screenshot saved at: " . $filePath;
    }
The fullPage() method captures the entire webpage, including sections beyond the visible viewport. Visit 127.0.0.1:8000/screenshot, and upon success, a full-page screenshot will be saved in public/Browsershot/.

To capture a mobile-sized screenshot, use a mobile user agent to ensure the website loads its mobile version correctly. Here's the updated method.
    public function capture()
    {
    // Define directory and file path
        $directory = public_path('Browsershot');
        $filePath = $directory . '/' . time() . 'screenshot.png';
    // Create directory if not exists
        if (!file_exists($directory)) {
            mkdir($directory, 0755, true);
        }
    // Alternatively, for mobile size, use a mobile user agent to ensure the website loads the mobile version for accurate capture.
        Browsershot::url('https://codeshotcut.com/')
        ->windowSize(375, 667)
        ->userAgent('Mozilla/5.0 (Linux; Android 10; Pixel 3 XL) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.120 Mobile Safari/537.36')
        ->waitUntilNetworkIdle()
        ->save($filePath);
        return "Screenshot saved at: " . $filePath;
    }
This ensures the website loads as it would on a mobile device. Visit 127.0.0.1:8000/screenshot, and a mobile-sized screenshot will be saved in public/Browsershot/.

Conclusion

By following this guide, you've integrated Browsershot into your Laravel project to capture high-quality screenshots and PDFs. This solution enables custom captures, including full-page and mobile-sized screenshots, making it ideal for generating visual previews or PDFs of webpages. With this setup, you can easily enhance your application’s functionality.
For more details, refer to the Browsershot documentation.
Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering