Learn how to generate PDF files in the latest Laravel version using barryvdh/laravel-dompdf. Follow these steps to implement PDF export in Laravel.
Step 1: Install Laravel DomPDF Package
Run this command to install the package:
composer require barryvdh/laravel-dompdf
Step 2: Create a PDF Controller
Generate a new controller using:
php artisan make:controller PDFController
Edit app/Http/Controllers/PDFController.php and add:
namespace App\Http\Controllers;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request;
class PDFController extends Controller
{
public function generatePDF()
{
$data = [
'title' => 'Laravel PDF Example',
'date' => date('Y-m-d'),
'content' => 'This is a sample PDF generated in Laravel using DomPDF.'
];
$pdf = Pdf::loadView('pdf.sample', $data);
return $pdf->download('sample.pdf');
}
}
Step 3: Create a Blade View for PDF
Create a new file at resources/views/pdf/sample.blade.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ $title }}</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 20px;
}
h1 { color: #007bff; }
p { font-size: 18px; }
</style>
</head>
<body>
<h1>{{ $title }}</h1>
<p>Date: {{ $date }}</p>
<p>{{ $content }}</p>
</body>
</html>
Step 4: Define the Export Route
Open routes/web.php and add this route:
use App\Http\Controllers\PDFController;
Route::get('/generate-pdf', [PDFController::class, 'generatePDF']);
Step 5: Test the PDF Generation
Start the Laravel development server:
php artisan serve
Now, visit:
http://127.0.0.1:8000/generate-pdf
A **sample.pdf** file will be downloaded automatically.
Conclusion
By following this guide, you have successfully implemented **PDF generation** in Laravel using **Dompdf**.
Visit Developer Sahayak
0 Comments