In this article, we'll see how to generate a PDF file using DomPDF in laravel 11. Here We will utilize the DomPDF Composer package to generate a PDF file within Laravel 11. In this task, we'll generate ten dummy user profiles and include some placeholder text within the PDF document
Also, You can create a new DOMPDF instance and load an HTML string, file, or view name. You can save it to a file, stream it (show it in the browser), or download it.
So, let's see that laravel 11 generates PDF files using DomPDF, how to create a PDF file in laravel 11, laravel generates PDF from view.
In the first step, we'll install laravel 11 using the following command. if you already installed laravel 11 then skip this step.
composer create-project laravel/laravel laravel-11-example
Next, I will install the DomPDF package using the following Composer command.
composer require barryvdh/laravel-dompdf
In this step, I will create a PDFController with a function named generatePDF().
So, run the following command to create a controller.
php artisan make:controller PDFController
After that, I'll create dummy records using the tinker.
php artisan tinker
User::factory()->count(25)->create()
app/Http/Controllers/PDFController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use PDF;
class PDFController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function generatePDF()
{
$users = User::get();
$data = [
'title' => 'Techsolutionstuff',
'date' => date('m/d/Y'),
'users' => $users
];
$pdf = PDF::loadView('pdf-example', $data);
return $pdf->download('techsolutionstuff.pdf');
}
}
Now, I'll define the routes into the web.php file.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PDFController;
Route::get('generate-pdf', [PDFController::class, 'generatePDF']);
Then, I'll create a pdf-example.blade.php file for the PDF.
resources/views/pdf-example.blade.php
<!DOCTYPE html>
<html>
<head>
<title>How to Generate PDF File using DomPDF in Laravel 11 - Techsolutionstuff</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" >
</head>
<body>
<h1>{{ $title }}</h1>
<p>{{ $date }}</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua.</p>
<table class="table table-bordered">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
@foreach($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
</tr>
@endforeach
</table>
</body>
</html>
Now, I'll run the laravel 11 application using the following command.
php artisan serve
You might also like: