PDF generation in Laravel
Blade gives you the HTML and Laravel’s HTTP client gives you a timeout and retries in one line, which is most of what a production integration needs.
The code
<?php
// app/Http/Controllers/InvoiceController.php
use Illuminate\Support\Facades\Http;
public function pdf(Invoice $invoice)
{
$html = view('invoices.show', compact('invoice'))->render();
$response = Http::withToken(config('services.pdfcraft.key'))
->timeout(60)
->retry(2, 500)
->post('https://api.pdfcraft.dev/v1/render', [
'html' => $html,
'options' => [
'printBackground' => true,
'margin' => ['top' => '20mm', 'bottom' => '20mm'],
],
]);
abort_if($response->failed(), 502, $response->json('error.message'));
return response($response->body(), 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="invoice-'.$invoice->id.'.pdf"',
]);
}What to watch for
- `Http::withToken()` writes the `Authorization: Bearer` header for you — there is no need to build it by hand.
- `->retry(2, 500)` retries on connection failures and 5xx, which is right. Do not retry a 4xx: a 400 will be a 400 again.
- Put the key in `config/services.php` and read it with `config()`, not `env()` — `env()` returns null once the config is cached in production.
Why not run the browser yourself
You can. Puppeteer and Playwright both work, and for a script you run by hand they are the right answer. The cost arrives at the point it becomes a service someone depends on: one long-lived browser per process rather than one per request, a semaphore so four renders do not become forty, a hard timeout that force-closes a hung page before it holds a slot forever, a scheduled restart because Chromium leaks, and a Chromium version you are now responsible for patching.
None of that is hard. All of it is work that has nothing to do with your product, and it fails under concurrency rather than in testing — which is the worst time to discover it.
Other frameworks
- PDF generation in Next.js
- PDF generation in Django
- PDF generation in Ruby on Rails
- PDF generation in AWS Lambda
- PDF generation in Cloudflare Workers
- PDF generation in Supabase Edge Functions
- PDF generation in Spring Boot
- PDF generation in FastAPI
- PDF generation in Express
- PDF generation in ASP.NET Core
- PDF generation in n8n