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

You are viewing revision #3 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.

« previous (#2)

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.

<?php
/**
 * @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
 */
Yii::import('ext.tcpdf.*');
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->SetTextColor(255);
		$this->SetDrawColor(128, 0, 0);
		$this->SetLineWidth(0.3);
		$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);
		}
		$this->Ln();
		// Color and font restoration
		$this->SetFillColor(224, 235, 255);
		$this->SetTextColor(0);
		$this->SetFont('');
		// 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->Ln();
			$fill=!$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);
		spl_autoload_register(array('YiiBase','autoload'));
		                
		// set document information
		$pdf->SetCreator(PDF_CREATOR);  
		                
		$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->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
		$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
		$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
		$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
		$pdf->SetFont('helvetica', '', 8);
		$pdf->SetTextColor(80,80,80);
		$pdf->AddPage();
		                 
		//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
		$pdf->lastPage();
		
		//Close and output PDF document
		$pdf->Output('filename.pdf', 'I');
		Yii::app()->end();
		
	}

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(
            $ticketsold->ticketType->name,$ticketsold->quantity,$ticketsold->ticketType->deliveryName,
            $ticketsold->series,$ticketsold->first_number,
            isset($ticketsold->busline_id) ? $ticketsold->busline->name : "",
            isset($ticketsold->origin_id) ? $ticketsold->origin->stop->name  : "",
            isset($ticketsold->destiny_id) ? $ticketsold->destiny->stop->name  : "",
            $ticketsold->hour,$ticketsold->formatedAmount
         );
         $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'),
                                   $ticketSoldModel->getAttributeLabel('busline_id'),$ticketSoldModel->getAttributeLabel('destiny_id'),$ticketSoldModel->getAttributeLabel('origin_id'),$ticketSoldModel->getAttributeLabel('hour'),$ticketSoldModel->getAttributeLabel('amout')
                                  );

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 !!!