Class-based PDFs
The Laravel integration provides an abstract PDF class that lets you encapsulate PDF logic in dedicated, reusable classes. This is useful when a PDF has its own source, filename, and configuration that you want to keep together.
Creating a PDF Class
Extend WeasyPrint\Integration\Laravel\PDF and implement the source() and filename() methods:
use WeasyPrint\Integration\Laravel\PDF;
use Illuminate\Contracts\Support\Renderable;
class InvoicePdf extends PDF
{
public function __construct(
private Invoice $invoice,
) {}
public function source(): Renderable
{
return view('invoices.template', [
'invoice' => $this->invoice,
]);
}
public function filename(): string
{
return "invoice-{$this->invoice->number}.pdf";
}
}The source() method accepts the same types as prepareSource() - a string, a Renderable, or a Source object.
Returning from Controllers
The PDF class implements Laravel's Responsable interface, so you can return it directly from a controller:
class InvoiceController
{
public function show(Invoice $invoice)
{
return new InvoicePdf($invoice);
}
}By default, this displays the PDF inline in the browser.
Stream Modes
To change the default stream mode, override the defaultStreamMode() method:
use WeasyPrint\Enums\StreamMode;
class InvoicePdf extends PDF
{
// ...
public function defaultStreamMode(): StreamMode
{
return StreamMode::DOWNLOAD;
}
}You can also call the output methods directly for explicit control:
$pdf = new InvoicePdf($invoice);
return $pdf->download();
return $pdf->inline();
return $pdf->stream(StreamMode::DOWNLOAD);Custom Configuration
Override the config() method to customise configuration for a specific PDF class:
use WeasyPrint\Objects\Config;
class InvoicePdf extends PDF
{
// ...
public function config(Config $config): void
{
$config->timeout = 120;
$config->optimizeImages = true;
}
}This works like tapConfig() - you mutate specific properties and everything else retains its defaults.
Custom Headers
Override the headers() method to add custom HTTP response headers:
class InvoicePdf extends PDF
{
// ...
public function headers(): array
{
return [
'X-Invoice-Number' => $this->invoice->number,
];
}
}