We use PDF to generate
various kinds of reports and in most of the report we have fixed header and
footer representing company’s information.
I will show you how to
create a common header and footer function with CodeIgniter Library which
extends Tcpdf library
Prerequisites:
- CodeIgniter Installed
- TCPDF library
To create a library in
CodeIgniter, create a new php file under application/libraries
folder. I will call it Pdfheaderfooter.php [first letter capital]. You can use
whatever name you want.
Add tcpdf library where
you have them added. I have added it under application/libraries folder. So in
my Pdfheaderfooter.php file I will have below line:
require_once('tcpdf/tcpdf.php');
require_once('tcpdf/tcpdi.php');
If you do not have tcpdf library, you can get it from http://sourceforge.net/projects/tcpdf/files
Next is to
create class that extends this library. Create a class with same name as php
file:
class Pdfheaderfooter extends TCPDI {
}
Under this class
you can define your header and footer functions:
<?php
if ( ! defined('BASEPATH')) exit('No direct
script access allowed');
require_once('tcpdf/tcpdf.php');
require_once('tcpdf/tcpdi.php');
class Pdfheaderfooter extends TCPDI {
//Page header
public function Header() {
$html = 'Some Header';
$this->SetFontSize(8);
$this->WriteHTML($html, true, 0, true, 0);
}
// Page footer
public function Footer() {
// Position at 15 mm from bottom
$this->SetY(-15);
$html = 'Some Footer';
$this->SetFontSize(8);
$this->WriteHTML($html, true, 0, true, 0);
}
}
/* End of file
Pdfheaderfooter.php */
This will use
custom header and footer defined in Pdfheaderfooter.php
file when pdf is generated.
Now to generate a pdf with this custom header and footer, you need to load this library maybe in the controller.
$this->load->library('Pdfheaderfooter');
// create new PDF document
$pdf = new Pdfheaderfooter(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set font
$pdf->SetFont('times', 'BI', 12);
// add a page
$pdf->AddPage();
// set some text to print
$txt = "This is some HTML"
// print a block of text using Write()
$pdf->WriteHTML(0, $txt, '', 0, 'C', true, 0, false, false, 0);
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example.pdf', 'I');
$pdf = new Pdfheaderfooter(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set font
$pdf->SetFont('times', 'BI', 12);
// add a page
$pdf->AddPage();
// set some text to print
$txt = "This is some HTML"
// print a block of text using Write()
$pdf->WriteHTML(0, $txt, '', 0, 'C', true, 0, false, false, 0);
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example.pdf', 'I');
No comments:
Post a Comment