Welcome To ITSolutionsGuides,
In this it solutions guides tutorial we will see How To Generate PDF File In Laravel 11 using DomPDF with the help of the barryvdh/laravel-dompdf composer package. barryvdh/laravel-dompdf composer package helps to convert the blade view to the pdf file . In this example we will generate the pdf file using the DomPDF with the help of PDF::loadView() and the download the loaded pdf using the ->download() the name of the pdf should be provided there with the hep of use PDF; trait. Lets see how to create pdf using DomPDF.
Lets install the barryvdh/laravel-dompdf package using the following artisan command,
composer require barryvdh/laravel-dompdf
In the controller file we will create the using the PDF::loadView to load the pdf ie; converting the blade view to the pdf, after creating the pdf we need to download the pdf using the ->download(pdf-name)
with the help of the use PDF; trait in the controller.
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' => 'Welcome to ItSolutionStuff.com',
'date' => date('m/d/Y'),
'users' => $users
];
$pdf = PDF::loadView('myPDF', $data);
return $pdf->download('itsolutionstuff.pdf');
}
}
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PDFController;
Route::get('generate-pdf', [PDFController::class, 'generatePDF']);
Lets create the blade file for creating the PDF
resources/views/myPDF.blade.php
<!DOCTYPE html>
<html>
<head>
<title>How To Generate PDF File In Laravel 11 using DomPDF</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>
Lets run the laravel application using the following artisan command,
php artisan serve
We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.
Be the first to know about releases and tutorial news and solutions.
We care about your data in our privacy policy.
ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.
Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides