Laravel 12 - How to Generate Website Screenshots with BrowserShot

Touseef Afridi
18 Jul 25

Laravel 12 - How to Generate Website Screenshots with BrowserShot

In this tutorial, we will learn how to use BrowserShot in Laravel 12 to capture screenshots, generate PDFs or images, and improve SEO in your Laravel app.


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 : Set Up Fresh Laravel 12 Project.

First, make sure you have the Laravel installer set up globally. If not, install it with the following command.
composer global require laravel/installer
This lets you quickly spin up new Laravel projects using a single command. If the Laravel installer is already set up, skip installing it. Now, create a new Laravel 12 project called browserShot.
laravel new browserShot
During the interactive setup, make the following selections.
  • Starter Kit – Select None.
  • Testing Framework – Choose Pest.
  • Database – Pick MySQL.
  • Run default migrations? – Type yes.
  • Run npm install and npm run build? – Type yes.

Once completed, you'll have a fresh Laravel 12 application scaffolded with your preferred stack, MySQL configured, migrations applied, frontend assets built, and Pest ready for testing. This gives you a solid foundation to begin working with BrowserShot.

Step # 2 : Access the browserShot Project.

Open your terminal and navigate to the project directory.
cd c:xampp/htdocs/browserShot
This puts you inside the Laravel project root, ready for the next setup steps.

Step # 3 : Install BrowserShot and Its Dependencies.

To use BrowserShot for capturing high-quality screenshots in Laravel, start by installing the package via Composer.
composer require spatie/browsershot
BrowserShot relies on Puppeteer, which controls a headless version of Chrome for rendering pages. Before installing Puppeteer, make sure Node.js and npm are installed on your system. If not, download them from: http://nodejs.org/en/. Once that’s confirmed, install Puppeteer globally.
npm install puppeteer
Your Laravel app is now ready to generate webpage screenshots using BrowserShot.

Step # 4 : Generate the BrowserShot Controller.

To handle screenshot capturing, generate a new controller.
php artisan make:controller BrowserShotController
This creates a file at: app/Http/Controllers/BrowserShotController.php. Now open that file and add the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Spatie\Browsershot\Browsershot;
class BrowserShotController extends Controller
{
    public function capture()
    {
        // Define the path to the public/Browsershot directory and set a unique filename
        $directory = public_path('Browsershot');
        $filePath = $directory . '/' . time() . 'screenshot.png';
        // Create the Browsershot directory if it doesn't already exist
        if (!file_exists($directory)) {
            mkdir($directory, 0755, true);
        }
        // Capture a screenshot of the target page at desktop resolution, waiting until the page is fully loaded
        Browsershot::url('https://getbootstrap.com/')
            ->windowSize(1920, 1080)
            ->waitUntilNetworkIdle()
            ->save($filePath);
        return "Screenshot saved at: " . $filePath;
    }
}
The BrowserShotController sets public/Browsershot/ as the destination for saved screenshots and uses time() to generate a unique filename to prevent file conflicts. Since BrowserShot doesn't handle directory creation like Laravel’s storage tools, the code manually checks and creates the folder if it doesn't exist. It then captures a 1920x1080 resolution screenshot, waiting for the page to fully load using waitUntilNetworkIdle() before saving the image.

Step # 5 : Set Up the Route.

Begin by importing the BrowserShotController at the top of your routes/web.php file.
use App\Http\Controllers\BrowserShotController;
Then, register a new route to trigger the screenshot functionality.
Route::get('/screenshot', [BrowserShotController::class, 'capture']);
This route will call the capture method in the controller whenever someone visits /screenshot in the browser.

Step # 6 : Test the BrowserShot Setup.

Start your Laravel development server by running.
php artisan serve
Once it’s running, open your browser and go to: http://127.0.0.1:8000/screenshot. If everything is working as expected, you’ll see a success message, and a screenshot will be saved in the public/Browsershot/ directory with a filename based on the current timestamp.

To generate a PDF of a webpage using Browsershot in Laravel, simply use the savePdf() method instead of save(). Update your capture() method as shown below.
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://getbootstrap.com/')
        ->waitUntilNetworkIdle()
        ->savePdf($filePath);
    return "PDF saved at: " . $filePath;
}
This will generate a PDF version of the specified webpage and store it in the public/Browsershot/ directory. Open http://127.0.0.1:8000/screenshot in your browser to trigger the capture and verify the output.

To capture a full-page screenshot using Browsershot in Laravel, include the fullPage() method in your capture() function. 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://getbootstrap.com/')
        ->windowSize(1920, 1080)
        ->waitUntilNetworkIdle()
        ->fullPage()
        ->save($filePath);
        return "Screenshot saved at: " . $filePath;
    }
The fullPage() method makes sure the screenshot includes the complete webpage, not just the visible portion. After visiting http://127.0.0.1:8000/screenshot, a full-page image will be saved in the public/Browsershot/ directory.

To generate a mobile-sized screenshot using Browsershot, simulate a mobile environment by setting a mobile user agent and adjusting the window size. 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://getbootstrap.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;
}
By using a mobile user agent and viewport size, the target site is rendered as it would appear on a smartphone. Open http://127.0.0.1:8000/screenshot in your browser, and the mobile-view screenshot will be saved to 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! 💸😄"
1

0 Comments

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