Yii 1.1: Create / Generate PDF files with TCPDF plugin (Example to generate Table with TCPDF plugin)


Few days ago i was playing with TCPF plugin to create a PDF files. Since i have checked few available extension and also checked some forum threads but still i dont get my expected result for PDF file.

SO, finally i got the solution and implemented it in my project and now everything seems to be fine for me.That's why i have decided to share my code here.So, other people can also get a benefit.

Note : I have used latest TCPDF plugin library at the time of writing this article.This article is Yii implementation for one of the example from TCPDF plugin examples.So, it would be helpful to implement other TCPDF plugin examples with this implementation.

This example is creating a colored table for Active records sets.This article is simply based on this example.

Step 1 : Download TCPDF plugin library from Official download link for TCPDF plugin

step 2 : Copy downloaded tcpdf plugin directory to protected/extensions/ folder.So, you directory will be something like this protected/extensions/tcpdf. While copying a tcpdf library you can exclude examples folder.Since its not going to use anywhere.

Step 3 : Create one component class with the name MYPDF.php in protected/extensions/ folder. And place below given code in it.

 * @abstract This Component Class is created to access TCPDF plugin for generating reports.
 * @example You can refer http://www.tcpdf.org/examples/example_011.phps for more details for this example.
 * @todo you can extend tcpdf class method according to your need here. You can refer http://www.tcpdf.org/examples.php section for 
 *       More working examples.
 * @version 1.0.0
class MYPDF extends TCPDF {
    // Load table data from file
    public function LoadData($file) {
        // Read file lines
        $lines = file($file);
        $data = array();
        foreach($lines as $line) {
            $data[] = explode(';', chop($line));
        return $data;
    // Colored table
    public function ColoredTable($header,$data) {
        // Colors, line width and bold font
        $this->SetFillColor(255, 0, 0);
        $this->SetDrawColor(128, 0, 0);
        $this->SetFont('', 'B');
        // Header
        $w = array(40, 35, 40, 45);
        $num_headers = count($header);
        for($i = 0; $i < $num_headers; ++$i) {
            $this->Cell($w[$i], 7, $header[$i], 1, 0, 'C', 1);
        // Color and font restoration
        $this->SetFillColor(224, 235, 255);
        // Data
        $fill = 0;
        foreach($data as $row) {
            $this->Cell($w[0], 6, $row[0], 'LR', 0, 'L', $fill);
            $this->Cell($w[1], 6, $row[1], 'LR', 0, 'L', $fill);
            $this->Cell($w[2], 6, number_format($row[2]), 'LR', 0, 'R', $fill);
            $this->Cell($w[3], 6, number_format($row[3]), 'LR', 0, 'R', $fill);
        $this->Cell(array_sum($w), 0, '', 'T');

Note : Here you can extend other methods from TCPDF plugin according to your need.

Step 4 : Create Action in Controller File to Generate PDF file. Use below given code to create action in controller. Later you can modify it according to your need.

public function actionCreatepdf(){
        $pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        // set document information
        $pdf->SetTitle("Selling Report -2013");                
        $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, "Selling Report -2013", "selling report for Jun- 2013");
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $pdf->SetFont('helvetica', '', 8);
        //Write the html
        $html = "<div style='margin-bottom:15px;'>This is testing HTML.</div>";
        //Convert the Html to a pdf document
        $pdf->writeHTML($html, true, false, true, false, '');
        $header = array('Country', 'Capital', 'Area (sq km)', 'Pop. (thousands)'); //TODO:you can change this Header information according to your need.Also create a Dynamic Header.
        // data loading
        $data = $pdf->LoadData(Yii::getPathOfAlias('ext.tcpdf').DIRECTORY_SEPARATOR.'table_data_demo.txt'); //This is the example to load a data from text file. You can change here code to generate a Data Set from your model active Records. Any how we need a Data set Array here.
        // print colored table
        $pdf->ColoredTable($header, $data);
        // reset pointer to the last page
        //Close and output PDF document
        $pdf->Output('filename.pdf', 'I');

Step 5 : Run your controller action to generate PDF file. And that's it. :) you will get generated PDF output something like this file.

Note :

1) In the above give code i am getting Data set to create Table from external file as it is given in the one of the example from TCPDF plugin.

data = $pdf->LoadData(Yii::getPathOfAlias('ext.tcpdf').DIRECTORY_SEPARATOR.'table_data_demo.txt');

Here you can change this data something like below given code to get records from Model Class.

$ticketSolds = $ticketSoldModel->findAll(array('condition'=>"selling_report_id=$id"));
      $ticketSoldData = array();
      foreach ($ticketSolds as $ticketsold){
         $data = array(
            isset($ticketsold->busline_id) ? $ticketsold->busline->name : "",
            isset($ticketsold->origin_id) ? $ticketsold->origin->stop->name  : "",
            isset($ticketsold->destiny_id) ? $ticketsold->destiny->stop->name  : "",
         $ticketSoldData[] = $data;

2) To get a Header for table according to above given data set you can use something like this code.

$headerForTicketSold = array($ticketSoldModel->getAttributeLabel('ticket_type_id'), $ticketSoldModel->getAttributeLabel('quantity'),$ticketSoldModel->getAttributeLabel('delivery_type'), $ticketSoldModel->getAttributeLabel('series'), $ticketSoldModel->getAttributeLabel('first_number'),

3) IMPORTANT: Make sure that number of header column and number of data set fields are same.and accordingly you have to change a code in ColoredTable() in MYPDF Component class. This method is used to create a nice colored table.Also you can modify this method according to your need.

4) Reference : For Further Implementation and examples you can refer This Link.

Since i have checked few extension before doing this implementation.But there was lots of difficulty to handle css and all.SO,its was better to use inbuilt functionality of this plugin.That is why i have decided to go with this implementation.Which gives lots of possibility to use TCPDF plugin with Yii. I hope this article would be helpful to implement TCPDF plugin.

Any suggestion, thoughts would be appreciated. :)

Thanks !!!

Total 11 comments

#17127 report it
sandeep malu at 2014/05/06 06:53am
For Digital Signature

Hi, Can you please help me to add digital signature to created pdf file using same plugin since TCPDF provides to add digital signature, but i need to implement in yii.

thanks & regards sandeep

#16677 report it
km994 at 2014/03/18 06:50am
Solved PHP Error.. include(MYPDF.php): failed to open stream: No such file or directory

Just wanted to share that I have solved the error .I imported the extensions in config/main.php file. Added 'application.extensions.*' in import array .

#16669 report it
km994 at 2014/03/17 03:49pm
PHP Error .. include(MYPDF.php): failed to open stream: No such file or directory

Hi I followed the same steps but i am receiving the error that is "include(MYPDF.php): failed to open stream: No such file or directory" . Can you please suggest the solution of this error ?

#15453 report it
Nisanth thulasi at 2013/11/11 09:58am
using CActiveDataProvider to create pdf

create pdf from CActiveDataProvider results

In controller action the $data array taken from CActiveDataProvider

$dataProvider = new CActiveDataProvider('Post',array('Pagination'=>false));
$arrays = $dataProvider->getData();
foreach($arrays as $array)

and pass $data as below

$pdf->ColoredTable($header, $data);
#15191 report it
Taufik at 2013/10/16 06:13am
different filename with class

I had some problems, especially when installing on linux (CentOS), maybe because of case sensitive on linux, the file name is different to the class, eg tcpdf.php contains TCPDF class. Yii import failed because it try to include (TCPDF.php), but the file name is tcpdf.php.

sorry about my english language

edit: I have solution, I change the code:



#14175 report it
codesutra at 2013/07/24 01:21pm
RE: @mcnally486

It would be permissions error.Apart from that i dont think so you will get any kind of error.

If there is any error then please share Error message.

#14166 report it
mcnally486 at 2013/07/24 08:37am
Server error

hi, thanks for the work, i am trying to implement the example and i am getting a server error any ideas ?

#14016 report it
codesutra at 2013/07/12 12:34am

Yes you can export the data from Cgrid view also. from model search.

As i have explained above in this article that. you get data set from Model class also. So, basically what you have to do is.

$ticketSolds = $ticketSoldModel->findAll(array('condition'=>"selling_report_id=$id"));
      $ticketSoldData = array();
      foreach ($ticketSolds as $ticketsold){
         $data = array(
            isset($ticketsold->busline_id) ? $ticketsold->busline->name : "",
            isset($ticketsold->origin_id) ? $ticketsold->origin->stop->name  : "",
            isset($ticketsold->destiny_id) ? $ticketsold->destiny->stop->name  : "",
         $ticketSoldData[] = $data;

You have to change code in

$ticketSolds = $ticketSoldModel->findAll(array('condition'=>"selling_report_id=$id"));

In your view file clone the dataProvider and save it into the session variable.

Yii::app()->session['export_agentlist_search'] = clone $model->search() ;

And use this session variable into the controller file. to access the Data set.Then again the same process to loop through with the Data set to create an Array.Same as i have explained above.

#14015 report it
mahdi1986 at 2013/07/11 08:26pm

yes, I want export from cgridview and used filter in search form,

Sorry for bad english ;)

#14010 report it
codesutra at 2013/07/11 10:59am

Sorry but i didn't get your point.Could you please explain a bit more.Are you talking to get data export from Cgridview. Is it what you are expecting ??

#14009 report it
mahdi1986 at 2013/07/11 10:40am
Complate Code

Hi, Thx for wiki,

Can you write complate code for getting data from model->search use in Cgridview,

Leave a comment

Please to leave your comment.

Write new article