Laravel Generate PDF File using DomPDF: A Complete Guide

October 07, 2024   Laravel

Laravel Generate PDF File using DomPDF: A Complete Guide

PDF generation is a common requirement in web applications, especially for generating invoices, reports, and downloadable documents. Laravel makes this easy with the DomPDF library, which allows you to generate PDF files from HTML templates. In this tutorial, we’ll explore how to install and use DomPDF in a Laravel application to create and customize PDF files.

Prerequisites

  • A Laravel application already set up.
  • Basic knowledge of Blade templating and routing in Laravel.

Step 1: Install DomPDF in Laravel

First, let’s install the barryvdh/laravel-dompdf package, which provides a wrapper for the DomPDF library to integrate it seamlessly with Laravel.

Run the following command in your terminal:

composer require barryvdh/laravel-dompdf

Once the installation is complete, the DomPDF package will be available for generating PDF files in your Laravel project.

Step 2: Configure DomPDF (Optional)

If you want to customize DomPDF settings, you can publish the configuration file by running:

php artisan vendor:publish --provider="Barryvdh\DomPDF\ServiceProvider"

This will create a config/dompdf.php file where you can adjust settings like paper size, orientation, and more. By default, DomPDF uses A4 paper in portrait mode.


Step 3: Create a Route for PDF Generation

To generate a PDF, you need a route that triggers the PDF creation process. Open the routes/web.php file and add a route for PDF generation:

use App\Http\Controllers\PDFController; Route::get('/generate-pdf', [PDFController::class, 'generatePDF']);

Step 4: Create a PDF Controller

Create a controller to handle the PDF generation logic. You can use the following command:

php artisan make:controller PDFController

In the PDFController.php file, add the generatePDF method:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PDF;

class PDFController extends Controller
{
    public function generatePDF()
    {
        $data = [
            'title' => 'Welcome to Laravel PDF Generation',
            'date' => date('m/d/Y')
        ];

        $pdf = PDF::loadView('pdf.invoice', $data);

        return $pdf->download('invoice.pdf');
    }
}

In this method:

  • $data contains the dynamic data you want to include in the PDF.
  • PDF::loadView('pdf.invoice', $data) generates a PDF from a Blade view named invoice with the provided data.
  • download('invoice.pdf') prompts the user to download the generated PDF file.

Step 5: Create a Blade View for the PDF

Now, create a Blade view to design the PDF layout. This view can contain any HTML structure and styling as needed.

In resources/views, create a new folder called pdf, and within it, create a file named invoice.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>Invoice PDF</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        .invoice-title {
            font-size: 24px;
            font-weight: bold;
            color: #4CAF50;
        }
        .invoice-date {
            font-size: 18px;
            color: #888;
        }
    </style>
</head>
<body>
    <h1 class="invoice-title">{{ $title }}</h1>
    <p class="invoice-date">Date: {{ $date }}</p>
    <table width="100%" cellpadding="10" cellspacing="0" border="1">
        <thead>
            <tr>
                <th>Item</th>
                <th>Quantity</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Product 1</td>
                <td>1</td>
                <td>$100</td>
            </tr>
            <tr>
                <td>Product 2</td>
                <td>2</td>
                <td>$200</td>
            </tr>
        </tbody>
    </table>
</body>
</html>

In this example:

  • The invoice-title and invoice-date styles are used to add some formatting.
  • The table lists sample items, but you can replace this with dynamic content.

Step 6: Test the PDF Generation

Now that everything is set up, go to http://your-app-url/generate-pdf in your browser. You should see a prompt to download the generated invoice.pdf file. When you open the file, it should display your data with the designed structure.


Step 7: Customize PDF Settings (Optional)

You can further customize the PDF settings such as paper size and orientation. Modify the generatePDF method in PDFController as follows:

$pdf = PDF::loadView('pdf.invoice', $data)->setPaper('a4', 'landscape');

In this example, we set the paper size to A4 and orientation to landscape. You can also specify letter, legal, or other supported paper sizes.

Step 8: Save PDF Files (Optional)

If you want to save the generated PDF on the server, you can use the save method instead of download:

public function generatePDF()
{
    $data = [
        'title' => 'Welcome to Laravel PDF Generation',
        'date' => date('m/d/Y')
    ];

    $pdf = PDF::loadView('pdf.invoice', $data);
    $pdf->save(public_path('pdf/invoice.pdf'));

    return "PDF has been saved to storage.";
}

Here, the PDF file is saved in the public/pdf directory. You can change the path as needed.


Conclusion

In this tutorial, you learned how to generate PDF files in Laravel using the DomPDF library. By following these steps, you can create and download PDF documents, customize the layout, and save them to the server. DomPDF makes it easy to transform HTML and Blade templates into PDF files, enabling you to generate invoices, reports, and other downloadable documents in Laravel.

With this setup, you can start creating and customizing PDFs in your Laravel applications to meet all your project needs!

 


Comments


Write a Comment