in packages, PHP, symfony

Snappy – How to create PDF with Symfony and twig

Long time ago I use FPDF to create PDF Documents and reports. FPDF allows you to define a PDF using blocks. This process is slow as you can not reuse any of the views you already code in html or your frontend components.

For a long time there has been a new player wkhtmltopdfwkhtmltopdf is a headless chrome port that generate PDF’s or Images from a website and you can use it in Symfony with Snappy bundle.

traditionrolex.com

Examples

Downloading a page as a PDF

$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="file.pdf"');
echo $snappy->getOutput('https://www.albertsola.pro');

From HTML

$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
$snappy->generateFromHtml('<h1>Bill</h1><p>You owe me money, dude.</p>', '/tmp/bill-123.pdf');

My favourite

$pdf; //Snappy Pdf
$twig;

$html=$twig->render("report.html.twig", []);
$pdfContents=$pdf->getOutputFromHtml($html);
// Send it to the browser
$response=new Response($pdfContents);
$response->headers->set('Content-type', 'application/octect-stream');
$response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', "Your report.pdf"));
$response->headers->set('Content-Transfer-Encoding', 'binary');
return $response;

More info at: https://github.com/KnpLabs/snappy

Working with wkhtmltopdf can be tricky if you have any comments, tricks or issues please comment.

Write a Comment

Comment

  1. Nice tutorial. I was looking for a pdf library for symfony. Dompdf is a nice library too and is very easy to implement.