Skip to content

Instantly share code, notes, and snippets.

@ethanpil
Created August 3, 2016 20:27
Show Gist options
  • Save ethanpil/a185fef676e31a09323da320a2ae7ea8 to your computer and use it in GitHub Desktop.
Save ethanpil/a185fef676e31a09323da320a2ae7ea8 to your computer and use it in GitHub Desktop.
HTML to PDF with PHP and wkhtmltopdf
<?php
/******
I was using tcpdf then mpdf for years, and then I discovered wkhtmltopdf and it changed my life.
If you can exec() then you will enjoy super fast operation, no more memory/process time outs,
and overall easier and better PDFs... Check out http://wkhtmltopdf.org/ ... binaries for most platforms.
******/
//Setup file parameters
$cwd = getcwd();
$htmlfile = $cwd.DIRECTORY_SEPARATOR.'tmp'.DIRECTORY_SEPARATOR.date('Y-m-d-h-m-s').'.html';
$pdffile = $cwd.DIRECTORY_SEPARATOR.'tmp'.DIRECTORY_SEPARATOR.date('Y-m-d-h-m-s').'.pdf';
//Fat Free Framework code that generates a valid html file and writes to disk
$html = \Template::instance()->render('pdf/order.html');
$f3->write($htmlfile, $html);
//Convert HTML to PDF
exec('"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe" '.$htmlfile.' '.$pdffile);
//Output the file to browser
header('Content-Type: application/pdf');
header('Content-Length: ' . filesize($pdffile));
readfile($pdffile);
//Delete the junk and bye!
unlink($htmlfile);
unlink($pdffile);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment