CakePHP Generate PDF with DOMPDF

PDF is a most common document type for printing digital content. DOMPDF is an open source HTML to PDF converter where it enable developer to convert any HTML page to PDF format. For example if developer need to work on application that required to generate correspondence or invoice in PDF, so DOMPDF is one of the best HTML to PDF converter without using the Command Line Interface (CLI). To use the DOMPDF, you need at least PHP 5.4 and MBString extension and CAKEPHP 2.2.X and above.


To integrate DOMPDF in CakePHP, download DOMPDF from here (Currently used in this tutorial) or the official web at here. After download, extract and move the file to ...app/Vendor/dompdf

Next, navigate to .../app/Config/routes.php and add the following codes:

Router::parseExtensions('pdf');


Next, navigate to your controller where you need the PDF function to load the RequestHandler component codes so that CakePHP can parse .pdf extension. The RequestHandler component should integrated as follows:

public $components = array('Paginator','RequestHandler'); 

*Note: If you have search function, the 'Search.Prg' should be in the same public components.

Load the CakePDF Plugin in bootstrap.php at .../app/config as shown below:

CakePlugin::load('CakePdf', array(
    'routes' => true,
    'bootstrap' => true, ));

Configure::write('CakePdf', array(
		'engine' => 'CakePdf.dompdf',
		'pageSize' => 'A4',
        'options' => array(
            'print-media-type' => false,
            'outline' => true,
            'dpi' => 125,
        ),
        'margin' => array(
            'bottom' => 0,
            'left' => 0,
            'right' => 0,
            'top' => 0
        ),
        'orientation' => 'portrait',
        
    ));


Create a default layout setting (default.ctp) for DOMPDF at .../app/View/Layouts/pdf/default.ctp which contain 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();
?>


Next, developer need to create new public function for PDF generating for example if the page is required to generate an invoice, so name it as public function invoice_pdf and disable the layout as follows:

public function invoice_pdf($id = null) {
	$this->layout = false;
    if (is_null($id)) {
			$this->cakeError('error404');
		} else {
			$invoice = $this->Invoice->findById($id);
			$this->set(compact('invoice'));
		}
}

*Note: The layout need to disable to remove all theme (eg: bootstrap) from PDF view. Developer are recommended to create new CSS for the PDF. Developer also can find by $slug instead of $id to enhance the SEO and naming the PDF.

Create a pdf folder in ...app/View/<controllerName>/pdf. Next, create a invoice_pdf.ctp inside the pdf folder which contain this code:

<!DOCTYPE html>
<html>
    <head>
<meta charset="UTF-8">
<title>My Invoice</title>
<?php //echo $this->Html->css('yourCSS'); ?>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
    </head>
    <body>
	Your Variables Here
    </body>
</html>


Once complete the settings, now, it is time to create the button to call the PDF. The function should be call in view as as follows:

<?php echo $this->Html->link('<i class="far fa-file-pdf"></i> Download PDF', 
    array('controller' => 'invoices', 'action' => 'invoice_pdf','ext' => 'pdf',$invoice['Invoice']['id']),
    array('class'=>'btn btn-info',  'escape' => false, 'target' => '_blank', 'title' => 'Download PDF')); ?>


Congratulation. You've completed the process. Test your PDF function and enjoy the function :)