Kritim Yantra
Apr 17, 2025
Generating PDF files is a common requirement in many web applications—whether you're building invoices, reports, tickets, or receipts. In this blog, we’ll walk through how to generate PDF files in Laravel 12 using a popular package called barryvdh/laravel-dompdf.
✅ Goal: By the end of this guide, you’ll be able to generate a beautiful PDF from an HTML view in your Laravel 12 project.
If you haven’t created a Laravel 12 project yet, run:
composer create-project laravel/laravel laravel-pdf-demo
Go into your project directory:
cd laravel-pdf-demo
Run the following command to install the package:
composer require barryvdh/laravel-dompdf
This package is a wrapper around Dompdf, which converts HTML to PDF using the browser rendering engine.
You can publish the config file if you want to customize settings:
php artisan vendor:publish --provider="Barryvdh\DomPDF\ServiceProvider"
It will create a file at config/dompdf.php
.
Open your routes/web.php
and add a route to test PDF generation:
use App\Http\Controllers\PDFController;
Route::get('/generate-pdf', [PDFController::class, 'generatePDF']);
Run the Artisan command:
php artisan make:controller PDFController
Then, open the controller file (app/Http/Controllers/PDFController.php
) and add:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;
class PDFController extends Controller
{
public function generatePDF()
{
$data = [
'title' => 'Welcome to Laravel PDF',
'date' => date('m/d/Y')
];
$pdf = Pdf::loadView('pdf.invoice', $data);
return $pdf->download('invoice.pdf');
}
}
Now let’s create the Blade file that will be converted to PDF.
Create the view file:
resources/views/pdf/invoice.blade.php
Paste the following HTML:
<!DOCTYPE html>
<html>
<head>
<title>Invoice PDF</title>
<style>
body { font-family: sans-serif; }
h1 { color: #3490dc; }
.content { margin-top: 20px; }
</style>
</head>
<body>
<h1>{{ $title }}</h1>
<p class="content">This PDF was generated using Laravel 12 and DomPDF.</p>
<p>Date: {{ $date }}</p>
</body>
</html>
🎨 You can use basic HTML and inline styles. DomPDF supports most HTML tags and simple CSS (but not all modern CSS features).
Run your Laravel server:
php artisan serve
Now visit http://localhost:8000/generate-pdf in your browser. The browser should automatically download a file named invoice.pdf
.
If you want to open the PDF in the browser instead of downloading it, change the return line in the controller:
return $pdf->stream('invoice.pdf');
'isRemoteEnabled' => true
in config/dompdf.php
.In this post, you learned how to:
✅ Install and configure the barryvdh/laravel-dompdf
package
✅ Create a controller and Blade view for PDF generation
✅ Download or stream PDF files in Laravel 12
With this setup, you can easily generate PDFs for invoices, reports, tickets, or anything else your app needs!
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google