- Install Laravel using the below command. Here I installed Laravel version 10
composer create-project laravel/laravel laravel-app
2. Configure in .env file for database connection. Now create a database named pdfdb. You can use your db name
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=pdfdb DB_USERNAME=root DB_PASSWORD=
3. Install the DomPDF package by renting the below code
composer require barryvdh/laravel-dompdf
4. Generate a route link in routes/web.php
use App\Http\Controllers\PDFController;
....
Route::get('pdfdownload',[LangController::class, 'downloadPDF'])->name('pdfdownload');
Route::get('pdfview',[LangController::class, 'pdfview']);
5. Create a controller named PDFController
php artisan make:controller PDFController
6. In the PDFController file with location app\Http\controllers\PDFController.php copy the below code
public function downloadPDF()
{
$users = DB::table('users')->get();
$data = [
'users' => $users
];
// Generate the PDF file
$pdf = PDF::loadView('PDFReport', $data);
return $pdf->download('test.pdf');
}
public function pdfview(){
return view('pdfview');
}
7. Now create a blade file named PDFReport.blade.php that will export pdf files in /resources/views. The file name will
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laravel 10 Generate Example</title>
</head>
<body>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
@foreach($users as $user)
<tbody>
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
</tr>
</tbody>
@endforeach
</table>
</body>
</html>
8. Create another blade file named pdfview.blade.php
<button><a href="{{ route('pdfdownload') }}">Download PDF</a></button>
9. Insert 1000 sample data in the user’s table using Seeders for download purposes in PDF format. Copy this code and paste it to DatabaseSeeder.php in \database\seeders\DatabaseSeeder.php
<?php
namespace Database\Seeders;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*/
public function run(): void
{
\App\Models\User::factory(1000)->create();
\App\Models\User::factory()->create([
'name' => 'Test User',
'email' => 'test@example.com',
]);
}
}
10. Now run the application and go to the localhost:8000/pdfview for downloading the pdf file
php artisan serve