Just another WordPress.com weblog

Archive for May, 2011

How to generate html to pdf using tcpdf?

To generate pdf from html using tcpdf, follow the below steps:

Step1: Download tcpdf library from below link
http://sourceforge.net/projects/tcpdf/files/

Step2: Add tcpdf folder in your project at path :: Your_project/lib/tcpdf

Step3: Create html file at any place you wants.. Than create one function in model file.. to generate pdf like below:


public function generatePdf($couponIds)
{
$filename = " HERE PATH OF HTML FILE WILL COME" ; //EG: Mage::getBaseDir().'/app/locale/en_US/template/email/coupon.html' this will return file coupon.html
$logoImage = Mage::getBaseDir().'/skin/frontend/default/default/images/logo_pdf.jpg'; //logo image path
$ptemplate = file_get_contents($filename);
$couponFindReplace = array(
'##LOGO_IMAGE##' =>$logoImage ,
'##FOOTER_TEXT_IMAGE##' =>$footertextImage
}
//Above array is to change content dynamically.
$after_replace = strtr($ptemplate, $couponFindReplace);
$pdf_html = $after_replace;
require_once(Mage::getBaseDir().'/lib/tcpdf/config/lang/eng.php');
require_once(Mage::getBaseDir().'/lib/tcpdf/tcpdf.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetTitle('PDF Title');
$pdf->SetAuthor('Author');
$pdf->SetKeywords('PDF','tcpdf','html');
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
//set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
//set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
//set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$lg = Array();
$lg['a_meta_charset'] = 'UTF-8';
$lg['a_meta_dir'] = 'ltr';
$lg['a_meta_language'] = 'en';
$lg['w_page'] = 'page';
$pdf->SetFont('times','',20); //set font of pdf and default font size is 20
//set some language-dependent strings
$pdf->setLanguageArray($lg);

// add a page
$pdf->AddPage();
$pdf->writeHTML($coupon_pdf_html, true, 0, true, true);
//$pdf->Output('test.pdf','D'); //this will create pdf and download at a time..
/*START:: To create pdf at particular location in server*/
$file_name = 'test.pdf';
$file_name_path = Mage::getBaseDir().'/media/coupons/'.'test.pdf';
if(file_exists($file_name_path))
{
unlink($file_name_path);
}
$pdf->Output($file_name_path,'F');
@chmod($file_name_path, 0777);
/*END:: To create pdf at particular location in server*/
return $file_name;
}

above function will generate pdf

The above are the steps to create simple pdf..

If the above code is helpful to you than do reply….

Thanks,
Bijal Bhavsar:)

Advertisements