Render your HTML page as a PDF
Why another PDF tutorial?
This tutorial is based on the PHP Class HTML 2 (F)PDF. This class converts HTML tags to PDF.
You don’t have total control over PDF, and not all HTML tags are supported, but it permits render a .thtml directly to a PDF!
If you need total PDF control by code, you have to use the other PDF tutorial creating_pdfs
Installation
It is only tested on CakePHP RC3 on Linux
1. Download the classes from http://sourceforge.net/projects/html2fpdf
2, Uncompress into vendors/html2fpdf
3. Create the component. Copy the following code to app/controllers/components/pdf.php
<?php /** * PDF component. Uses html2fpdf library (http://html2fpdf.sourceforge.net/) * * @author RosSoft * @version 0.2 * @license MIT * */ define('RELATIVE_PATH',VENDORS . 'html2fpdf' . DS); vendor('html2fpdf/html2fpdf'); class PdfComponent extends Object { var $helpers = array('Html'); var $layout='pdf'; var $controller; //capture output from view function _content($thtml) { ob_start(); $layout_backup=$this->controller->layout; $this->controller->layout=$this->layout; $this->controller->render($thtml); $content = ob_get_clean(); return $content; } function startup(&$controller) { $this->controller =& $controller; } function render($thtml=null) { $buffer=$this->_content($thtml); $buffer=utf8_decode($buffer);//I use utf8, need decoding to ISO-8859-1 $pdf=new HTML2FPDF(); $pdf->AddPage(); $pdf->WriteHTML($buffer); $pdf->Output(); //Read the FPDF.org manual to know the other options } } ?>
4. Create a layout for PDF. Copy the following code to app/layouts/pdf.thtml
<?php header("Content-type: application/pdf"); ?> <html> <head> <?php echo $html->charset('UTF-8')?> </head> <body> <?php echo $content_for_layout; ?> </body> </html>
How to use
Include the PdfComponent in your controller (var $components=array(’pdf’) )
file: /app/controllers/tests_controller.php
<?php class TestsController extends AppController { var $name = 'Tests'; var $components = array('pdf'); function index() { $this->pdf->render(); } } ?>
It will render its action view by default, which is /app/views/tests/index.thtml. You can render another view by passing its name as an argument to render: $this→pdf→render(’another);
The next example not uses dynamic data, but you can use it just like another view (it IS a normal view)
file: /app/views/tests/index.thtml
<center> <h2>CakePHP List</h2> <table> <tr> <td>Code</td> <td>Description</td> <td>Price</td> </tr> <tr> <td>102</td> <td>CakePHP Manual</td> <td>30.42</td> </tr> <tr> <td>202</td> <td>CakePHP is Great!</td> <td>230.42</td> </tr> </table> </center>
See is believe
Go to http://your_host/your_base_cake/tests/
Hey! Not too bad, for two lines of code... Rectification, 0 lines of code, all the rest is Copy&Paste™.
Contribute
This tutorial is not 100% error-free (and my English is very bad). If you find bugs or typos (or a lot of typos...), please correct them!
Author: RosSoft