Browsershot Laravel: Generate PDFs Effortlessly

Creating PDFs directly from a web application can be incredibly useful—whether it’s for generating reports, invoices, or other downloadable documents. Laravel makes this easier with Browsershot, a package that uses headless Chrome to capture screenshots or generate PDFs from web pages.

In this guide, we’ll see how Laravel experts generate PDFs easily with the help of Browsershot. Let’s get started!

What is Browsershot?

Browsershot is a Laravel package that makes it easy to capture screenshots or generate PDFs from web pages using a headless Chrome browser. By leveraging headless Chrome, Browsershot can render web pages just like a real browser, ensuring an accurate representation of HTML, CSS, and JavaScript.

Here are some top benefits of using Browsershot in Laravel:

  • Quickly convert web pages or HTML content to PDF format, perfect for reports, invoices, and downloadable documents.
  • Uses headless Chrome to render pages just like a real browser, ensuring that CSS and JavaScript elements display correctly in screenshots and PDFs.
  • Integrates smoothly with Laravel, allowing you to generate PDFs and screenshots without complex configurations.
  • Offers options for setting page sizes, margins, and even custom headers and footers, giving you full control over the PDF output.
  • Ideal for applications needing automated document generation, like reporting systems or e-commerce platforms creating invoices.

Need custom PDF solutions in Laravel? We can help!

How to Use Browsershot Laravel for PDF Generation?

Now that we understand what Browsershot is and the benefits it brings, let’s dive into the steps to set it up and start generating PDFs in Laravel. Follow this straightforward process to integrate Browsershot into your application and quickly begin creating PDFs directly from your web content.

Prerequisites

  • Laravel Project: Have a Laravel project ready. Or create a new Laravel project.
  • PHP 7.3+: Ensure your PHP version is 7.3 or higher.
  • Composer: Needed to install Browsershot.
  • Node.js and npm: Verify they’re installed by running node -v and npm -v.
  • Basic Laravel Skills: Familiarity with models, controllers, and views.
  • Chrome or Chromium: Browsershot uses headless Chrome; Puppeteer will handle this.

Step 1: Set Up Browsershot in Laravel

First, ensure you have Browsershot installed:

composer require spatie/browsershot

Next, install Node.js and Puppeteer (if you haven’t already):

npm install puppeteer

Step 2: Create the Model

In this example, we’ll create a simple Order model with dummy data.

  • Generate the Order Model and Migration:
php artisan make:model Order -m

Open the migration file in database/migrations and define the columns for our orders table:

public function up()
{
    Schema::create('orders', function (Blueprint $table) {
        $table->id();
        $table->string('product_name');
        $table->integer('quantity');
        $table->decimal('price', 8, 2);
        $table->unsignedBigInteger('user_id');
        $table->timestamps();
    });
}
  • Run the Migration:
php artisan migrate
  • Define Relationships (Optional):

If you have a User model, you can add a relationship between Order and User:

// In Order.php
public function user()
{
    return $this->belongsTo(User::class);
}

Step 3: Create the Controller

Next, let’s create a controller to handle the PDF generation logic.

  • Generate the OrderController:
php artisan make:controller OrderController
  • Add the generatePDF Method:

In the newly created OrderController, add a method to generate the PDF. This method will pull order data, load it into a view, and use Browsershot to convert it to PDF.

use Spatie\Browsershot\Browsershot;
use App\Models\Order;
use Illuminate\Support\Facades\View;

class OrderController extends Controller
{
    public function generatePDF($orderId)
    {
        // Retrieve the order by ID
        $order = Order::with('user')->findOrFail($orderId);

        // Pass data to the view
        $htmlContent = View::make('orders.invoice', compact('order'))->render();

        // Generate PDF with Browsershot
        $pdfPath = public_path("invoices/order-{$orderId}.pdf");
        Browsershot::html($htmlContent)
            ->format('A4')
            ->margins(10, 10, 10, 10)
            ->save($pdfPath);

        return response()->download($pdfPath);
    }
}

Step 4: Create the Blade View

Now, let’s create a Blade view for the invoice that will be rendered as HTML and converted into a PDF.

  • Create the View File:

In resources/views/orders, create a new file called invoice.blade.php.

  • Design the Invoice HTML:

Here’s a basic structure for an invoice:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Order Invoice</title>
    <style>
        body { font-family: Arial, sans-serif; }
        .invoice-box { max-width: 800px; margin: auto; padding: 30px; border: 1px solid #eee; }
        .invoice-header { font-size: 24px; font-weight: bold; margin-bottom: 20px; }
        .invoice-table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        .invoice-table th, .invoice-table td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        .total { font-weight: bold; }
    </style>
</head>
<body>
    <div class="invoice-box">
        <div class="invoice-header">Order Invoice</div>
        <p><strong>Customer:</strong> {{ $order->user->name }}</p>
        <p><strong>Date:</strong> {{ $order->created_at->format('Y-m-d') }}</p>
        <table class="invoice-table">
            <thead>
                <tr>
                    <th>Product</th>
                    <th>Quantity</th>
                    <th>Price</th>
                    <th>Total</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>{{ $order->product_name }}</td>
                    <td>{{ $order->quantity }}</td>
                    <td>${{ $order->price }}</td>
                    <td>${{ $order->quantity * $order->price }}</td>
                </tr>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="3" class="total">Total:</td>
                    <td class="total">${{ $order->quantity * $order->price }}</td>
                </tr>
            </tfoot>
        </table>
    </div>
</body>
</html>
  • Style Adjustments:

Customize the CSS in the view file to create a more detailed and stylized PDF as needed.

Step 5: Define a Route for PDF Generation

Add a route in routes/web.php that maps to the generatePDF method:

use App\Http\Controllers\OrderController;

Route::get('/order/{id}/pdf', [OrderController::class, 'generatePDF'])->name('order.pdf');

Step 6: Testing PDF Generation

  • Seed the Database (Optional):

You may want to seed the Laravel database and orders table to test the PDF generation.

  • Access the Route:

Visit the route with an order ID in your browser:

http://localhost:8000/order/1/pdf

If everything is set up correctly, this route should generate and download a PDF named order-1.pdf.

Step 7: Automate PDF Creation and Storage (Optional)

You can modify the generatePDF method to store the PDF in storage rather than downloading it, which is useful for record-keeping or batch generation:

use Illuminate\Support\Facades\Storage;

public function generatePDF($orderId)
{
    $order = Order::with('user')->findOrFail($orderId);
    $htmlContent = View::make('orders.invoice', compact('order'))->render();
    $pdfContent = Browsershot::html($htmlContent)
        ->format('A4')
        ->margins(10, 10, 10, 10)
        ->pdf();

    // Store the PDF in the storage directory
    Storage::put("invoices/order-{$orderId}.pdf", $pdfContent);

    return response()->json(['message' => 'PDF generated successfully.']);
}

This method will store the PDF at storage/app/invoices/order-{orderId}.pdf.

Conclusion

With Browsershot, generating PDFs in Laravel becomes quick and hassle-free. By following these steps, you can create polished, downloadable documents like invoices and reports straight from your app.

Whether for personal projects or professional needs, Browsershot makes PDF creation easy and reliable. Give it a try and see how it enhances your Laravel application!

For advanced customizations, consider hiring professional Laravel developers to avoid future errors.

Optimize your Laravel app’s performance with expert solutions!

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