Laravel 11 - How to generate PDF

Touseef Afridi
24 Sep 24

Laravel 11 - How to generate PDF

In this tutorial, we are going to discuss how to generate PDFs in Laravel 11. 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

This guide walks through the process of generating PDFs in a Laravel application using the DOMPDF package. It starts by setting up a fresh Laravel project or using an existing one, with minimal installation options such as MySQL for the database and Pest for testing. After accessing the project directory, the barryvdh/laravel-dompdf package is installed to enable PDF generation from HTML content. The guide then covers publishing the package configuration for customization, creating a controller (PDFController) to handle PDF generation, and defining a route to trigger the PDF download. A view (myPDF.blade.php) is created to structure the PDF content, including dynamic data like the title and date. Finally, the Laravel development server is started, and the integration is tested by visiting a local URL, where the generated PDF is automatically downloaded. If all steps are correctly set up, the PDF will include the specified content from the view.

Step # 1 : Set Up a New Laravel Project or Use an Existing One.

If Laravel is installed globally, you can quickly create a new project by running the following command.
laravel new pdf
Alternatively, you can use Composer to create the project.
composer create-project laravel/laravel --prefer-dist pdf
During the setup, choose the following options when prompted:
  • Starter Kit: Select None to install Laravel without any authentication scaffolding.
  • Testing Framework: Choose Pest for a modern and streamlined testing setup.
  • Database: Select MySQL to configure Laravel for MySQL-based storage.
  • Migrations: Type yes to run migrations and automatically set up the default database tables.

This process will set up a new Laravel project called pdf. If Laravel is installed globally, the laravel new command will create the project instantly; otherwise, Composer will download and install Laravel. The installation is minimal, without any starter kit, and includes Pest for testing, MySQL as the database, and default database migrations.

Step # 2 : Access the project.

Open a terminal (such as Git Bash) and navigate to the root directory of your Laravel project using the following command.
cd c:xampp/htdocs/pdf
Now that you're in the root directory of your Laravel project, you can run commands and interact with the project files directly from the terminal.

Step # 3 : Install DOMPDF Package.

Run the following command to install the package.
composer require barryvdh/laravel-dompdf
The barryvdh/laravel-dompdf package is a Laravel wrapper for the DOMPDF library. DOMPDF is a PHP library that allows you to generate PDF documents from HTML content. By installing this package, you'll be able to easily create and manage PDF generation within your Laravel application.

Step # 4 : Publish DOMPDF Configuration.

Use the following command to publish the package configuration.
php artisan vendor:publish --provider="Barryvdh\DomPDF\ServiceProvider"
This command publishes the configuration file for the DOMPDF package, allowing you to customize settings such as the PDF generation options. Once published, you can modify the configuration file to suit your application's specific needs.

Step # 5 : Create a Controller.

Run the following command to create the PDFController.
php artisan make:controller PDFController
Then, update the PDFController with the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use PDF;
class PDFController extends Controller
{
    public function generatePDF()
    {
        // Prepare data to be passed to the PDF view
        $data = [
            'title' => 'Laravel 11 - Code Shotcut',
            'date' => date('m/d/Y'),
        ];
        // Load the view 'myPDF' with the specified data and create a PDF instance
        $pdf = PDF::loadView('myPDF', $data);
        // Download the generated PDF file named 'codeshotcut.pdf'
        return $pdf->download('codeshotcut.pdf');
    }
}
The PDFController is created to handle the logic for generating and downloading PDFs. In this controller, the generatePDF() method prepares the data, loads a view (myPDF), and then generates a PDF from that view. The PDF is then downloaded with the filename codeshotcut.pdf. You'll need to create the myPDF view where the PDF content will be structured.

Step # 6 : Define a Route.

Import the PDFController class.
use App\Http\Controllers\PDFController;
Create a route to trigger the PDF generation.
Route::get('/generate-pdf', [PDFController::class, 'generatePDF']);
Now we have a route set up to access the generatePDF method in the PDFController. By visiting the /generate-pdf URL, the method will be executed, generating and downloading the PDF as specified in the controller.

Step # 7 : Create a View.

Create a view file named myPDF.blade.php in the resources/views directory. Add the following code for testing purposes.
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 - PDF Example - Code Shotcut</title>
</head>
<body>
    <h1>{{ $title }}</h1>
    <p>Date: {{ $date }}</p>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</body>
</html>
Now we have created the myPDF.blade.php view, which contains the HTML structure for the PDF content. This view includes placeholders for the $title and $date variables passed from the PDFController. When generating the PDF, the content from this view will be rendered, including the dynamic data such as the title and date, and any static content like the Lorem Ipsum text.

Step # 8 : It's time to test.

Start the Laravel development server by running the following command.
php artisan serve
Access the URL below in your browser.
127.0.0.1:8000/generate-pdf
This will trigger the generatePDF method in the PDFController, where the server will process the request, generate the PDF using the data from the view, and automatically start downloading the generated file as codeshotcut.pdf. Make sure all previous steps, including the controller, route, and view, are correctly set up. If everything is configured properly, the PDF will contain the title, date, and Lorem Ipsum text as defined in your view.


Conclusion

By following this guide, you've successfully integrated PDF generation into your Laravel application using the DOMPDF package. Your project now allows users to generate and download PDFs with dynamic content such as titles and dates, all rendered from a custom Blade view. The integration is seamless, with all necessary components including the controller, route, and view set up properly. You can further customize the PDF generation process by modifying the view and configuration settings.

For more advanced features, refer to the DOMPDF documentation and explore additional options for customizing the appearance and content of your PDFs.
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