Laravel 10 - How to generate PDF

Touseef Afridi
03 Sep 24

Laravel 10 - How to generate PDF

In this tutorial, we are going to discuss how to generate PDFs in Laravel 10. PDF generation is useful for creating invoices, reports, and downloadable documents.


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


Quick Overview

In this guide, we walk through the complete process of generating PDF files in a Laravel 10 application using the barryvdh/laravel-dompdf package. You’ll start by setting up a clean Laravel project and preparing your environment with Vite and front-end dependencies. Then, you’ll install and configure the DOMPDF package, create a dedicated controller for handling PDF generation, and define a simple route to trigger it. After that, you’ll build a Blade view that serves as the content for the PDF. Finally, by visiting a test route, you’ll see the PDF automatically generated and downloaded, demonstrating a fully functional Laravel PDF generation flow.

Step # 1 : Start Fresh with a Clean Laravel 10 Project.

To keep things simple and focused, it's best to begin with a clean Laravel 10 project, especially when testing new features like PDF generation. You can either use an existing Laravel 10 setup or create a brand-new one. If you have Laravel globally installed use the following command to create fresh project named pdf.
laravel new pdf
Or, if you prefer using Composer, you can run.
composer create-project laravel/laravel --prefer-dist pdf
We're starting with a clean Laravel 10 project to ensure a smooth development experience. A fresh setup helps avoid leftover clutter, simplifies debugging, and lets us focus entirely on building and testing new features like PDF generation.

Step # 2 : Access the Project and Run the Vite Dev Server.

Open your terminal (such as Git Bash or Command Prompt) and navigate to your Laravel project’s root directory. For example.
cd c:xampp/htdocs/pdf
Once you're inside the project folder, install the front-end dependencies and start the Vite development server.
npm install && npm run dev
This will compile your front-end assets and enable live reloading during development. Keep this terminal window open and running. In a new terminal tab or window, navigate back to the same project directory to continue running Laravel-specific commands as needed.

Step # 3 : Install the DOMPDF Package.

To enable PDF generation in your Laravel project, install the popular barryvdh/laravel-dompdf package by running the following command in your terminal.
composer require barryvdh/laravel-dompdf
This package is a Laravel wrapper for the popular DOMPDF library. It allows you to easily convert Blade views or raw HTML into downloadable PDF files. It's widely used, actively maintained, and integrates seamlessly with Laravel's existing features, making it a reliable choice for generating invoices, reports, certificates, and more.

Step # 4 : Publish the Package Configuration.

After installing the package, publish its configuration file so you can customize its settings if needed. Run the following command.
php artisan vendor:publish --provider="Barryvdh\DomPDF\ServiceProvider"
This will create a dompdf.php config file inside the config directory. While the default settings work fine for most use cases, having the config file available allows you to tweak options like paper size, orientation, and font handling to better fit your project’s requirements.

Step # 5 : Create the PDF Controller.

To handle PDF generation logic, start by creating a dedicated controller. Run the following Artisan command.
php artisan make:controller PDFController
This will generate a new controller file at app/Http/Controllers/PDFController.php. Open the file and replace its contents with the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use PDF; // Import the DOMPDF facade
class PDFController extends Controller
{
    // Method to generate and download the PDF
    public function generatePDF()
    {
        // Sample data to be passed to the view
        $data = [
            'title' => 'Laravel 10 - Code Shotcut',
            'date' => date('m/d/Y'),
        ];
        // Load the Blade view 'myPDF' and pass the data to it
        $pdf = PDF::loadView('myPDF', $data);
        // Return the generated PDF as a downloadable file
        return $pdf->download('codeshotcut.pdf');
    }
}
In this method, we define sample data (title and date) and pass it to the myPDF Blade view using the PDF::loadView() method from the DOMPDF package. The generated PDF is then downloaded using the download() function with the filename codeshotcut.pdf. This setup is flexible, you can easily swap the sample data with dynamic content, customize the view’s layout, or generate various types of documents based on your project’s requirements.

Step # 6 : Define a Route for PDF Generation.

To make the PDF generation accessible via your browser, you'll need to create a route and link it to the controller method. First, open your routes/web.php file and add the following.
use App\Http\Controllers\PDFController;
Route::get('/generate-pdf', [PDFController::class, 'generatePDF']);
This sets up a GET route at /generate-pdf that triggers the generatePDF method in PDFController. When you visit this URL in your browser, it will generate and download the PDF file.

Step # 7 : Create the PDF View.

Now let's create the Blade view that will be converted into a PDF. Inside the resources/views directory, create a file named myPDF.blade.php. Add the following HTML content for testing purposes.
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 10 - PDF Example - Code Shotcut</title>
</head>
<body>
    <h1>{{ $title }}</h1>
    <p>Date: {{ $date }}</p>
    <p>This is a simple PDF example generated using Laravel 10 and DOMPDF.</p>
</body>
</html>
This view acts as the visual content for your PDF. The dynamic variables {{ $title }} and {{ $date }} are passed from the controller and will be rendered as part of the final output. Since DOMPDF parses standard HTML, you can use any valid HTML tags here, including tables, images, and inline styles, to design your PDF layout. For now, we're keeping it simple to test the basic functionality, but you can easily expand this template to build more complex documents like invoices, reports, or certificates.

Step # 8 : Test the PDF Generation.

Now that everything is set up, it’s time to test it out. Start the Laravel development server by running.
php artisan serve
Once the server is running, open your browser and go to: http://127.0.0.1:8000/generate-pdf. This URL will trigger the generatePDF method, render the Blade view, and automatically download a file named codeshotcut.pdf to your device.

As shown in the image above, the PDF download happens instantly, confirming the setup works perfectly.

Conclusion

By following this step-by-step guide, you’ve successfully implemented PDF generation in a Laravel 10 application using the barryvdh/laravel-dompdf package. Starting from a clean Laravel setup, you installed and configured the package, created a controller and route to handle the PDF logic, and built a Blade view that gets rendered into a downloadable PDF file. This setup provides a simple yet powerful foundation for generating invoices, reports, certificates, or any custom PDF content in your Laravel projects.
For more customization options and advanced usage, be sure to check out the official DOMPDF 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