Laravel 11 Generate PDF File using DomPDF Example

Integrating DomPDF in Laravel 11: A Complete Guide to PDF Generation

In this article you will learn about, Laravel 11 Generate PDF using DomPDF.

Generating PDF files is a common requirement for web applications, whether for reports, invoices, or custom documents. With Laravel 11, this process becomes even more efficient thanks to seamless integration with the DomPDF library. In this guide, we’ll walk through implementing this functionality step-by-step, from initial setup to advanced customization.


Why Use DomPDF?

DomPDF excels at converting HTML and CSS into high-quality PDFs while preserving layout fidelity. Its integration with Laravel allows you to leverage Blade templates, simplifying component reuse and dynamic styling. Key features include:

  • Custom fonts and CSS3 styling.
  • Landscape or portrait orientation support.
  • Compatibility with images and complex tables.

Technical Prerequisites

Ensure your environment meets these requirements:

  1. PHP 8.2 or higher: Required for modern typing and performance optimizations.
  2. Composer 2.x: Dependency manager for installing Laravel packages.
  3. Laravel 11: The latest framework version with API and async task enhancements.

Tip: Use php -v and composer --version to verify installed versions.


Step 1: Setting Up a Laravel 11 Project

Create a new project using Composer:

composer create-project laravel/laravel laravel-pdf-app 

Explanation:

  • This command downloads Laravel’s base scaffold, including authentication, routes, and default configurations.
  • laravel-pdf-app folder will be generated with the necessary structure.

Navigate to the project directory:

cd laravel-pdf-app

Step 2: Installing the DomPDF Package

Add DomPDF to your project via Composer:

composer require barryvdh/laravel-dompdf  

What This Does:

  • Installs the DomPDF library and auto-registers its service provider.
  • Makes the PDF facade available for direct document generation in controllers.

Step 3: Creating a PDF Controller

Generate a dedicated controller for PDF logic:

php artisan make:controller PDFController 

In app/Http/Controllers/PDFController.php, add the generatePDF() method:

<?php  

namespace App\Http\Controllers;  

use Illuminate\Http\Request;  
use PDF;  // DomPDF facade  

class PDFController extends Controller  
{  
    public function generatePDF()  
    {  
        $data = [  
            'title' => 'PDF Generated with Laravel 11 and DomPDF',  
            'date' => now()->format('m/d/Y'),  
            'users' => \App\Models\User::all() // Dynamic data (optional)  
        ];  

        $pdf = PDF::loadView('pdf.template', $data);  
        return $pdf->download('document.pdf');  
    }  
}  

Details:

  • PDF::loadView() renders the Blade view pdf.template with provided data.
  • download() forces the browser to download the PDF immediately.

Step 4: Defining the Route

In routes/web.php, add a route to trigger PDF generation:

use App\Http\Controllers\PDFController;  

// Simple test route  
Route::get('/generate-pdf', [PDFController::class, 'generatePDF']);  

Alternatives:

  • Protect the route with the auth middleware for restricted access.
  • Use named routes (Route::name('pdf.generate')) for better organization.

Step 5: Developing the Blade View

Create a resources/views/pdf folder and add template.blade.php:

<!DOCTYPE html>  
<html>  
<head>  
    <title>{{ $title }}</title>  
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">  
</head>  
<body class="p-4">  
    <h1 class="text-primary">{{ $title }}</h1>  
    <p class="text-muted">Date: {{ $date }}</p>  

    @if(isset($users))  
        <table class="table table-striped mt-4">  
            <thead>  
                <tr>  
                    <th>Name</th>  
                    <th>Email</th>  
                </tr>  
            </thead>  
            <tbody>  
                @foreach($users as $user)  
                    <tr>  
                        <td>{{ $user->name }}</td>  
                        <td>{{ $user->email }}</td>  
                    </tr>  
                @endforeach  
            </tbody>  
        </table>  
    @else  
        <p>No data available.</p>  
    @endif  
</body>  
</html> 

Optimizations:

  • Use Bootstrap classes for responsive styling.
  • Conditionals (@if) prevent errors when $users is undefined.

Step 6: Generating Test Data (Optional)

Simulate real-world data using Laravel factories:

php artisan tinker  
\App\Models\User::factory()->count(15)->create();  

Benefits:

  • Creates mock records without affecting production databases.
  • Tests layouts with varying data volumes.

Step 7: Advanced PDF Customization

Adjust settings like paper size and orientation:

$pdf = PDF::loadView('pdf.template', $data)  
          ->setPaper('A4', 'landscape')  
          ->setOptions([  
              'defaultFont' => 'sans-serif',  
              'isRemoteEnabled' => true // Allows external images  
          ]);  

Troubleshooting Common Issues

  1. Fonts Not Loading:
    • Install custom fonts on the server or use @font-face in CSS.
  2. Blocked External Images:
    • Enable isRemoteEnabled in DomPDF options.
  3. Memory Errors:
    • Increase memory_limit in php.ini for large files.

Conclusion

With Laravel 11 and DomPDF, generating PDFs becomes a swift and highly customizable task. This guide covers everything from basic setup to advanced techniques, enabling you to produce professional documents for diverse use cases, such as:

  • Financial Reports: Featuring dynamic charts and tables.
  • Certificates: With decorative borders and digital signatures.
  • Labels: Multi-column layouts for bulk printing.

Experiment with margin adjustments, custom headers, or batch PDF generation to streamline repetitive workflows. Next step? Explore cloud storage integration (e.g., Amazon S3) to auto-save documents post-generation.

Thanks for reading, Laravel 11 Generate PDF using DomPDF 😊.

Rolar para cima