Render PDFs in the browser with PdfView
masterTo automatically render PDFs for browser viewing or download:
- Templates: Place PDF templates in a
pdfsubdirectory of your controller templates (e.g.,templates/Invoices/pdf/view.php). Place layouts intemplates/layout/pdf/default.php. - Controller Setup: Register
PdfViewin your controller'sinitialize()method:$this->addViewClasses([\CakePdf\View\PdfView::class]); - Accessing: Access the PDF via URL extension (e.g.,
http://localhost/invoices/view/1.pdf) or by setting theAcceptheader toapplication/pdf. - Forced Download: To force a download instead of in-browser viewing, set
download => trueand optionally afilenamein thepdfConfig.
use CakePdf\View\PdfView;
class InvoicesController extends AppController
{
public function initialize(): void
{
parent::initialize();
$this->addViewClasses([PdfView::class]);
}
public function view($id = null): void
{
$invoice = $this->Invoice->get($id);
$this->viewBuilder()->setOption(
'pdfConfig',
[
'orientation' => 'portrait',
'filename' => 'Invoice_' . $id,
]
);
$this->set('invoice', $invoice);
}
}