I can spend all day heaping praise on CakePHP, but that won't tell you how to get DOMPDF (a 3rd party PHP library that creates PDF documents from HTML source) working inside the CakePHP framework will it?
So here's how I did it:
Download DOMPDF and extract the library into your /app/vendors/ directory.
Now comes the bit that took me two days to work out...
Your action in your controller should look something like this:
function action() {
$html = /* your code to generate the HTML you want to turn into a PDF
// turn off debugging output as this interferes with the PDF
Configure::write('debug', '0');
ini_set("display_errors", 0);
// create the pdf
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream("sample.pdf");
The important bit is switching off the errors (marked in bold red). Usually this is a *Bad Thing(TM)* but in this case it's critical.You see, CakePHP squirts out debugging information into the output stream (usually your HTML) and it looks like DOMPDF has some warning error messages that also get squirted into the stream too.
This is the LAST thing you want while you are in the middle of streaming out a PDF document. It renders the finished PDF invalid and unreadable.
I finally cracked this nasty nut by trawling through the generated (and corrupt) PDF document until I spotted some PHP error messages and then a little later, CakePHP's debug info.
3 comments:
Thank you ;)
I've found other issue. When locale has set to anything different to "en" , dompdf will produce a corrupted pdf due a decimal dots.
Add
setlocale(LC_ALL,"en");
instead of (in example):
setlocale(LC_ALL,"es_ES@euro","es_ES","esp");
and all works fine.
Thx man for your help!
Be sure to check this out also:
http://phpjunkie.wordpress.com/2009/08/06/hello-world/
It's an improved version of your own, and it also includes the code on how to *correctly* load up your Vendor from your vendor directory.
This meaning you should include the config file instead of the dompdf.php file, unlike most cases.
greets,
Kim
Post a Comment