Yesterday I was trying to generate some PDFs using CakePHP and awesome CakePDF plugin. After some reading around and testing I concluded WkHtmlToPdf should be the best PDF engine to use.
So I installed it on my Debian system running
sudo apt-get install wkhtmltopdf
It installed successfully and I was able to execute the example code from wkhtmltopdf website without any errors
wkhtmltopdf https://google.com google.pdf
But when I was trying to run it from CakePHP, I was greeted by an error message “WKHTMLTOPDF didn’t return any data”.
Stack trace was showing this:
CakePdf\Pdf\Engine\WkHtmlToPdfEngine->output ROOT/vendor/friendsofcake/cakepdf/src/Pdf/CakePdf.php, line 257
Closer inspection showed the actual error returned from wkhtmltopdf command was:
wkhtmltopdf: cannot connect to X server
So after some fiddling around I was able to find a working solution – you need to install program called xvbf:
sudo apt-get install xvfb
And modify the output() method’s line calling the wkhtmltopdf executable, located in cakepdf/src/Pdf/Engine/WkHtmlToPdfEngine.php
Replace the line:
$content = $this->_exec($this->_getCommand(), $this->_Pdf->html());
With the following:
$content = $this->_exec('xvfb-run -a -s "-screen 0 640x480x16" ' . $this->_getCommand(), $this->_Pdf->html());
All done 🙂
Note: you cannot just add this part to the “binary” parameter in the config without modifications on the class itself, because it will fail with “wkhtmltopdf binary is not found or not executable” message.