Creating PDFs in Laravel with modern CSS like Tailwind used to be tricky. Traditional PDF generators often fail with Flexbox, Grid, or Tailwind classes. Spatie Browsershot uses headless Chrome to render HTML, so you can fully utilize modern CSS and JavaScript.
1. Install Browsershot and Dependencies
Install via Composer:
composer require spatie/browsershot
Browsershot needs Node.js and npm (for Puppeteer). Install Node.js with nvm:
nvm install node
nvm use node
Install Puppeteer globally:
npm install -g puppeteer
Chromium will be downloaded automatically if Puppeteer is installed.
2. Create a Blade Template with Tailwind
Create resources/views/pdf/template.blade.php
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PDF Example</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 p-10">
<div class="max-w-2xl mx-auto bg-white p-8 rounded shadow">
<h1 class="text-4xl font-bold text-center text-blue-600">Hello, PDF!</h1>
<p class="mt-4 text-gray-700">This PDF is fully styled with Tailwind CSS and modern CSS features.</p>
</div>
</body>
</html>
3. Generate PDF from Blade Template
Use Browsershot in a route or controller:
use Spatie\Browsershot\Browsershot;
Route::get('/pdf', function () {
$pdfPath = storage_path('app/public/example.pdf');
Browsershot::html(view('pdf.template')->render())
->format('A4')
->landscape()
->showBackground()
->save($pdfPath);
return response()->download($pdfPath);
});
Tips:
-
showBackground()
renders backgrounds. -
format('A4')
sets page size. -
.pdf()
outputs directly to the browser.
4. Tailwind Tips with Browsershot
- Use CDN for Tailwind in Blade.
- For custom fonts, use web fonts or inline
@font-face
. - Use absolute URLs for images.
5. Advanced: Compiled Tailwind
If using Laravel Mix or Vite:
Browsershot::html(view('pdf.template')->render())
->setNodeBinary('/usr/bin/node')
->setNpmBinary('/usr/bin/npm')
->save($pdfPath);
Conclusion
Browsershot allows Laravel to generate PDFs with full support for modern CSS, Tailwind, Flexbox, Grid, and JavaScript. Ideal for invoices, reports, certificates, or any styled PDF content.
Top comments (0)