How to generate PDF in CakePHP 2.x with dompdf
13 November 2012

For some applications, generating PDF file is crucial. Let's imagine invoicing applications, created with CakePHP, generating PDF is a must. But how to do this? How to generate the file without using CLI?We will be using dompdf for this task. You can get it free and licensed under LGPL.
Make sure your meet the requirement:
- Using latest version of CakePHP 2.2.x
- Running server with PHP 5.3.x (never tested with PHP 5.2)
- Latest version of dompdf 0.6.0 Beta 3
Let's get started!
Step 1
Download dompdf, extract and move the folder to our app/Vendor. Make sure the folder name is dompdf.

Step 2
Open our app/Config/routes.php and add the following code:
Router::parseExtensions('pdf');
Step 3
On our controller, we have to load RequestHandler component so CakePHP can parse .pdf extension.
class PostsController extends AppController {
public $components = array('RequestHandler');
// the rest of the codes
}
We can load it in our AppController as well so it will be available to other controllers.
Step 4
Create new folder, pdf, in app/View/Layouts, then create a file, default.ctp and add the following codes:
<?php
require_once(APP . 'Vendor' . DS . 'dompdf' . DS . 'dompdf_config.inc.php');
spl_autoload_register('DOMPDF_autoload');
$dompdf = new DOMPDF();
$dompdf->set_paper = 'A4';
$dompdf->load_html(utf8_decode($content_for_layout), Configure::read('App.encoding'));
$dompdf->render();
echo $dompdf->output();
Step 5
For better control on the output for PDF file, we will create new action in our controller.
public function view_pdf($id = null) {
$this->Post->id = $id;
if (!$this->Post->exists()) {
throw new NotFoundException(__('Invalid post'));
}
// increase memory limit in PHP
ini_set('memory_limit', '512M');
$this->set('post', $this->Post->read(null, $id));
}
By doing this, we can performs additional task for the output, for example increasing PHP memory limit, generating invoice numbers and so on.
Step 6
Duplicate our view.ctp and rename it to view_pdf.ctp to reflect our action name. You can add CSS codes inside this files since linking to external CSS files is not working for me at the moment.
Step 7
Now we can create a link to generate the PDF file using these code:
<?php echo $this->Html->link(__('PDF'), array('action' => 'view_pdf', 'ext' => 'pdf', $post['Post']['id'])); ?>
Done!
Now you can easily generate PDF file in your CakePHP application.
Credit:
- http://www.dereuromark.de/2011/11/21/serving-views-as-files-in-cake2/
- http://stackoverflow.com/questions/8158129/loading-vendor-files-in-cakephp-2-0
- Tags: Tutorial
Comments (6)
karim
Syahril Zulkefli
karim
cedric
thanks again
Kapil Bhagchandani
header function in my action to indicate the content type as pdf instead of html . might be a fix is needed . Is there any better way of doing so .
Jason
[CODE]$this->response->type('pdf');[/CODE]
in the controller before "render"
to avoid scrambled output in the browser