Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 Generate PDF File using DomPDF Example Tutorial

Last Updated on May 11, 2024 by

DomPDF is a PHP library that provides flexibility to create PDF files that helps users to create PDF files from HTML for various purposes like invoices, reports, documents, etc.

Now, I will show you an example of creating pdf file from html using dompdf package in laravel 11:

Step 1: Install DomPDF Package

Run the following composer command to install the DomPDF package in laravel application:

composer require dompdf/dompdf

Step 2: Create a Route

Open routes/web.php file and create routes in it to handle pdf generation requests:

use App\Http\Controllers\PDFController;

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

Step 3: Create a Controller

Create a controller named PDFController using the following Artisan command:

php artisan make:controller PDFController

Edit app/Http/Controllers/PDFController.php file and create method to handle pdf generation proccess in it:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Dompdf\Dompdf;

class PDFController extends Controller
{
    public function generatePDF()
    {
        // Fetch data or prepare HTML content for PDF
        $data = [
            'title' => 'Sample PDF Document - ITCODSTUFF.COM',
            'content' => 'This is just a sample PDF document generated using DomPDF in Laravel.'
        ];

        // Load HTML content
        $html = view('pdf.document', $data)->render();

        // Instantiate Dompdf
        $dompdf = new Dompdf();
        $dompdf->loadHtml($html);

        // Set paper size and orientation
        $dompdf->setPaper('A4', 'portrait');

        // Render PDF (important step!)
        $dompdf->render();

        // Output PDF to browser
        return $dompdf->stream('document.pdf');
    }
}

Step 4: Create a Blade View

Create a Blade View file named document.blade.php in the resources/views/pdf directory. This file will contain the HTML structure you want to convert to PDF:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ $title }}</title>
</head>
<body>
    <h1>{{ $title }}</h1>
    <p>{{ $content }}</p>
</body>
</html>

Step 5: Test Application

Hit the http://127.0.0.1:8000/generate-pdf url on your browser to test this application.

Leave a Comment