In this tutorial, we will show you how to create a PDF helper using TCPDF library. Our focus will be how to create the helper class, if you want to find out more about TCPDF library as well as its usage. Please visit its official site at http://www.tcpdf.org.
Create "pdf.php" and place it to directory "app/views/helpers/pdf.php". Below is the code for the class:
<?php
App::import('Vendor','TCPDF',array('file' => 'tcpdf/tcpdf.php')); //1
class PdfHelper extends AppHelper //2
{
var $core;
function PdfHelper() {
$this->core = new TCPDF(); //3
}
}
?>
From the code above, we can tell PdfHelper class is actually just a wrapper class for TCPDF. Whenever you want to use TCPDF's functions, you simply do:
$pdf->core->TCPDFfunction()
Let us test out this helper class.
Create a layout file "app/views/layouts/pdf.ctp":
<?php
header("Content-type: application/pdf");
echo $content_for_layout;
?>
<?php
class PdfsController extends AppController {
var $uses = null;
var $helpers = array('Pdf');
function index() {
$this->layout='pdf';
}
}
?
<?php
$pdf->core->addPage('', 'USLETTER');
$pdf->core->setFont('helvetica', '', 12);
$pdf->core->cell(30, 0, 'Hello World');
$pdf->core->Output('example_001.pdf', 'D');
?>
Hopefully this simple tutorial helped you with your development. If you like our post, please follow us on Twitter and help spread the word. We need your support to continue. If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.