Create and Download a PDF in Laravel 11

To create and download a PDF in Laravel 11, you can use a package like barryvdh/laravel-dompdf. This package provides an easy way to generate PDFs using HTML and CSS.

Here’s how to set it up and use it:

Step 1: Install the Package

First, you need to install the barryvdh/laravel-dompdf package via Composer:

composer require barryvdh/laravel-dompdf

Step 2: Configure the Package (Optional)

If needed, you can publish the configuration file to customize the settings:

php artisan vendor:publish — provider=”Barryvdh\DomPDF\ServiceProvider”

Step 3: Create a Route and Controller Method

You can create a route and a controller method to generate and download the PDF.

// routes/web.php

use App\Http\Controllers\PDFController;

Route::get(‘/download-pdf’, [PDFController::class, ‘downloadPDF’]);

Step 4: Create the Controller

Create a controller (if you don’t have one already):

php artisan make:controller PDFController

In your PDFController, you can generate the PDF like this:

// app/Http/Controllers/PDFController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use PDF; // Import the PDF facade

class PDFController extends Controller

{

public function downloadPDF()

{

// Data to pass to the view

$data = [

‘title’ => ‘Laravel PDF Example’,

‘date’ => date(‘m/d/Y’),

];

// Load the view file and pass the data

$pdf = PDF::loadView(‘pdf.example’, $data);

// Download the PDF with a specified name

return $pdf->download(‘example.pdf’);

}

}

Step 5: Create the Blade View

Create a Blade view to design the PDF content:

// resources/views/pdf/example.blade.php

<!DOCTYPE html>

<html>

<head>

<title>Laravel PDF Example</title>

<style>

body {

font-family: ‘DejaVu Sans’, sans-serif;

}

</style>

</head>

<body>

<h1>{{ $title }}</h1>

<p>Generated on {{ $date }}</p>

<p>This is an example of a PDF generated in Laravel.</p>

</body>

</html>

Step 6: Test the PDF Generation

Now, when you visit /download-pdf, it should generate a PDF and prompt you to download it.

Additional Notes:

  • You can style the PDF using CSS within the Blade view.
  • If you encounter any issues with fonts, make sure to configure the font path correctly in the dompdf.php config file.

This method should work seamlessly in Laravel 11 for generating and downloading PDFs.

Learn more Create and Download a PDF in Laravel 11

Leave a Reply