Generating PDF files is a common requirement in modern web applications. Whether you need invoices, reports, or downloadable documents, Laravel makes this task simple with the help of the DomPDF library. In this tutorial, we will walk through the complete process of generating a PDF file in Laravel using DomPDF.
What is DomPDF?
DomPDF is a PHP library that converts HTML and CSS into PDF documents. It is lightweight, easy to use, and integrates seamlessly with Laravel. By writing standard HTML and CSS, you can quickly create professional-looking PDFs.
Step 1: Install DomPDF in Laravel
The easiest way to install DomPDF in Laravel is via Composer. Run the following command in your project directory:
composer require barryvdh/laravel-dompdf
Laravel will automatically register the package thanks to package auto-discovery.
Step 2: Create a Route
Next, define a route that will trigger the PDF generation.
Open the routes/web.php file and add the following code:
use App\Http\Controllers\PDFController;
Route::get('/generate-pdf', [PDFController::class, 'generatePDF']);
Step 3: Create a Controller
Now, create a controller to handle the PDF logic:
php artisan make:controller PDFController
Open the generated controller and add the following method:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use PDF;
class PDFController extends Controller
{
public function generatePDF()
{
$data = [
'title' => 'Welcome to Laravel PDF',
'date' => date('m/d/Y')
];
$pdf = PDF::loadView('pdf.sample', $data);
return $pdf->download('sample.pdf');
}
}
Step 4: Create a Blade View for the PDF
Create a new Blade file at resources/views/pdf/sample.blade.php.
This view will contain the HTML structure of your PDF.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sample PDF</title>
<style>
body {
font-family: DejaVu Sans, sans-serif;
}
</style>
</head>
<body>
<h1>{{ $title }}</h1>
<p>Date: {{ $date }}</p>
<p>
This PDF was generated using Laravel and DomPDF.
</p>
</body>
</html>
Step 5: Download or Stream the PDF
DomPDF provides multiple options for handling PDFs:
- Download:
$pdf->download('file.pdf'); - Stream in Browser:
$pdf->stream('file.pdf');
Common Tips and Best Practices
- Use simple CSS for better rendering results.
- Avoid heavy JavaScript, as DomPDF does not support it.
- Use embedded fonts like
DejaVu Sansfor UTF-8 support. - Test your HTML layout in the browser before converting to PDF.
Conclusion
Generating PDF files in Laravel using DomPDF is straightforward and powerful. With just a few steps, you can convert your HTML views into downloadable or viewable PDF documents. This approach is ideal for invoices, reports, certificates, and more.
If you found this tutorial helpful, feel free to share it with other Laravel developers. Happy coding!
Comments
Post a Comment