Get Started generating PDF’s today! Part 3 – extending/reuse

Extending FPDF

If you are new to FPDF you may want to start by reading Part 1: Installation and Part 2: Playing with the options.

We can extend the core FPDF library and set up some functions that we can reuse. For example, we want to present a report in a table. The table will need column headings so that we know what each column of data represents. We could build that into the file for this one report, but say we want another report, different heading names but the same basic structure. We can either replicate the entire file from the other report and change the heading values or we can extend FPDF and create a tableHeader function that accepts an array of heading values and creates the header on the fly. This approach will save us time as we add new reports.

//include the core fpdf library
include 'fpdf/fpdf.php';

//create our custom class
class Myfpdf extends FPDF
{
	//takes an array of values and prints them as text headers with a black border around each one
       function tableHeader($header)
	{
		foreach($header as $col)
		{
			$this->Cell(38,7,$col,1,0,'L',0);
		}
		$this->Ln();
	}
}

Now we want to use this to create a pdf. So in our index.php file we need to set up some values and generate the pdf.

//include our custom fpdf class
include 'my.fpdf.php';

//instantiate the class
$myFPDF = new Myfpdf();

//create the pdf
$myFPDF->AddPage();
$myFPDF->setTitle('Title');
$myFPDF->setFont('Arial', 'B', 15);

//set up the Header values and call it
$myFPDF->tableHeader(array('Header 1', 'Header 2', 'Header 3', 'Header 4'));

echo $myFPDF->Output('test_header.pdf','I');

There you have it, a reusable table head builder. Now you can use the same concept as above to output the table data.

Leave a Reply

Your email address will not be published. Required fields are marked *