Install CakePDF Plugin with Cakephp 2.3.1

I've been playing around with CakePHP for a while now. I have been working on a website and I wanted to allow guests to download articles from the website in PDF format. I cam accross this plugin CakePDF and I decided to use it in my website. However, I faced some problem creating PDF using WkHTMLToPDF engine. In this article I will show how did I install the plugin with CakepPHP.

 My Environment

  • OS: Ubuntu Linux
  • PHP 5.3.10
  • CakePHP 2.3.1

Step1: Installing CakePDF

Step 2: Configuration

  • Add the following to app/Config/bootstrap.php
CakePlugin::load('CakePdf', array('bootstrap'=>true, 'routes' =>true));

Configure::write('CakePdf', array(
'engine' ='CakePdf.WkHtmlToPdf',
'margin' =array(
'bottom'=15,
'left'=50,
'right'=30,
'top'=45
),
'encoding'='UTF-8',
'download' =true
));
  • You can view the full configuration options from the plugin page at github.
  • Make sure your Controller has RequestHandler component
class ArticlesController extends AppController {

 	public $components = array('RequestHandler');
       ..
      ..
}

Step 3: Installing wkhtmltopdf

My problem was with this engine. I installed version 0.9.9 and I got the following error

WKHTMLTOPDF didn't return any data

I googled around and I found this error might be cause of wkhtmltopdf version, so i installed different version

wget https://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.11.0_rc1-static-i386.tar.bz2
tar -vxf wkhtmltopdf-0.11.0_rc1-static-i386.tar.bz2
mv wkhtmltopdf-i386 wkhtmltopdf
chmod a+x wkhtmltopdf
sudo mv wkhtmltopdf /usr/bin

You can test the installation using the following command

wkhtmltopdf www.google.com test.pdf

Step 4: Using the plugin

  • The contents on the website I am working on are handled by Article Controller. I created new view file (view.ctp) in app/View/Articles/pdf
  • Print out the contents of the article in the newly created view file
echo ($article['Article']['body']);
  • Create default.ctp layout in app/View/Layouts/pdf directory
echo $this->fetch('content');
  • Now the articles can be view/downloaded as PDF by appending .pdf to the end of the url, for example to view http://my_server/blog/articles/1 as pdf , I just use the following url :
http://my_server/blog/articles/1.pdf

I hope someone will find this article useful