Cover Image for Generate PDF from html view file and download using dompdf in Laravel
199 views

Generate PDF from html view file and download using dompdf in Laravel

To generate a PDF from an HTML view file and download it using the dompdf library in Laravel, follow these steps:

Step 1: Install the Dompdf Package

In your Laravel project, you can install the dompdf package using Composer:

Bash
composer require barryvdh/laravel-dompdf

Step 2: Publish the Configuration File

Publish the package configuration file to customize the settings. Run the following command:

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

This command will create a config/dompdf.php file that you can modify to set PDF generation options.

Step 3: Create a Route and Controller

Create a route that will trigger the PDF generation and download. In your routes/web.php file, add a route definition like this:

PHP
Route::get('/generate-pdf', 'PDFController@generatePDF');

Next, create a controller using Artisan:

Bash
php artisan make:controller PDFController

In your PDFController.php file, add the following code to generate the PDF:

Bash
use PDF;

public function generatePDF()
{
    $data = [
        'title' => 'Sample PDF Title',
        'content' => 'This is the content of the PDF file.',
    ];

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

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

This code loads a Blade view named pdf.view.blade.php and passes data to it.

Step 4: Create the HTML View

Create a Blade view file for your PDF content. In this example, create a file named pdf.view.blade.php in the resources/views directory:

PHP
<!DOCTYPE html>
<html>
<head>
    <title>{{ $title }}</title>
</head>
<body>
    <h1>{{ $title }}</h1>
    <p>{{ $content }}</p>
</body>
</html>

This is a simple HTML view for the PDF content. You can customize it as needed.

Step 5: Generate and Download the PDF

Now, when you visit the /generate-pdf route in your browser, it will trigger the generatePDF method in your controller. This method generates the PDF and initiates the download.

Make sure your web server is running (php artisan serve) and visit http://localhost:8000/generate-pdf to download the generated PDF.

That’s it! You have successfully generated a PDF from an HTML view file and downloaded it using dompdf in Laravel. You can customize the PDF layout and styling by modifying the Blade view and the controller logic as per your requirements.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS