Normally, when we work on large project on laravel then we require to generate PDF file of database table. So, In this tutorial we will learn about Laravel pdf package ( laravel dompdf ) using which we can download pdf file .
Here, we use laravel dompdf for create pdf and this package also provide the function of download.
Now follow all the below steps to download pdf using laravel 8 .
Run this command in your cmd terminal –
composer require barryvdh/laravel-dompdf
'providers' => [
....
Barryvdh\DomPDF\ServiceProvider::class,
],
'aliases' => [
....
'PDF' => Barryvdh\DomPDF\Facade::class,
]
php artisan make:controller PdfController
app\Http\Controllers\PdfController.php
<?php
namespace App\Http\Controllers;
Use PDF;
use Illuminate\Http\Request;
class PdfController extends Controller
{
public function downloadPDF(){
$data = [
"full_name"=> "john do",
"email"=> "john@example.com",
"age"=>"23",
"phone"=>"998877XXXX",
];
$pdf = PDF::loadView('Sample_pdf',$data);
return $pdf->download('teknowize.pdf');
}
}
use App\Http\Controllers\PdfController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/
Route::get('download-pdf', [PdfController::class, 'downloadPDF']);
In this step , Create Sample_pdf.blade.php in resources\views .
resources\views\Sample_pdf.blade.php
<!DOCTYPE html>
<html>
<head>
<title>laravel-pdf</title>
<style>
table tr th{
background-color:#04AA6D;
color:white;
border: 1px solid #ddd;
padding: 8px;
}
table tr td{
border: 1px solid #ddd;
padding: 8px;
}
</style>
</head>
<body>
<h3>Laravel 8 PDF Example Using dompdf </h3>
<table>
<tr>
<th>Full Name</th>
<th>Email Id</th>
<th>Age</th>
<th>Phone Number</th>
</tr>
<tr>
<td>{{ $full_name }}</td>
<td>{{ $email }}</td>
<td>{{ $age }}</td>
<td>{{ $phone }}</td>
</tr>
</table>
</body>
</html>
php artisan serve
Finally , run this url in your browser
http://127.0.0.1:8000/download-pdf