Dompdf - MiguelFieira/AMO-HANDBOEK GitHub Wiki
Dompdf is a PHP library that you can use for PDF generation. It does not have dependencies on Symfony, so you can use it outside of Symfony too. It can use Twig files to generate a PDF, but it does not support CSS flex or grid, so unfortunately you cannot use complex markup.
Installation
You can install Dompdf via Composer.
composer require dompdf/dompdf
Usage
The following namespaces are commonly used in Dompdf usage:
// Import-ant hahaha, see what I did?
use Dompdf\Dompdf;
use Dompdf\Options;
The main class that Dompdf uses is the Dompdf class. You can pass a Dompdf Options object to the constructor of your Dompdf object.
$pdfOptions = new Options();
$pdfOptions->set('defaultFont', 'Arial');
$dompdf = new Dompdf($pdfOptions);
If you want to get a PDF from Twig, you'll have to get the twig view first.
// look familiar?
$html = $this->renderView('default/index.html.twig', [
'name' => 'Regula van Hydrus'
]);
Then you can give it to your Dompdf.
$dompdf->loadHtml($html);
Optionally, you can set the paper size of the PDF
$dompdf->setPaper('A4', 'portrait');
Now render the PDF by calling the render() method on the Dompdf.
$dompdf->render();
Direct download
If you want to immediately download the PDF, set the attachment to true when you stream the PDF.
$dompdf->stream("ffxiv.pdf", [
"Attachment" => true
]);
Symfony may complain about a Responseobject that is not being returned, but we can fix that by just returning an empty response.
// Take that!
return new Response();
Display in browser
if you want to display the PDF in the browser, you could use this approach.
Instead of a stream, we use output
$output = $dompdf->output();
And then we create a response and fill it with our PDF.
$response = new Response($output);
$response->headers->set('Content-type' , 'application/pdf');
return $response;
Save file to server (and then display it in browser)
To save the file to the server, you can use Symfony's BinaryFileResponse object. Be careful with security as this example just throws them into the public folder.
// import
use Symfony\Component\HttpFoundation\BinaryFileResponse;
Get the output instead of a stream
$output = $dompdf->output();
Get your public directory and your file name.
$publicDirectory = $this->getParameter('kernel.project_dir') . '/public';
$filename = 'ffxiv.pdf';
$pdfFilepath = $publicDirectory . '/' . $filename;
Put it in a file
file_put_contents($pdfFilepath, $output);
Now return a BinaryFileResponse object.
return new BinaryFileResponse($pdfFilepath);