Monday, May 24, 2010

Generate PDF using html2pdf Zip.

Hi Developer,
I got a requirement to generate pdf using php... Luckily with the help of my Innocent Boy i finished the task & posting blog to all.

Generating PDF:

There are many pdf libraries which can be used to generate pdf files.
Here I have used html2fpdf which internally uses fpdf library to convert html to pdf. We will add header and footer to the generated pdf also.

A sample project can be downloaded here http://www.macronimous.com/resources/html2pdf_sample.zip

First Let us generate basic pdf file.

Please find the index.php file in the extracted zip.

require('html2fpdf.php');
$pdf=new HTML2FPDF();
$pdf->AddPage();

$html = “Your HTML HERE”;
$output=($html);
$pdf->WriteHTML($output);
$pdf->Output("sample.pdf");
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=download.pdf");
readFile("sample.pdf");
?>

Above sample code will generate a pdf with text “Your HTML HERE” and prompt user to download the generated pdf.

To add header and footer you can use already available functions.They are called automatically. They already exist in the FPDF class but do nothing, therefore we have to extend the class and override them.


require('html2fpdf.php');
class PDF extends HTML2FPDF
{
function Header()
{
$this->Image('header.gif',10,8);
}

function Footer()
{
$this->Image('ourpeople.jpg',10,250,33);
}

}

$pdf=new PDF();
$pdf->AddPage();
$html = “Your HTML HERE”;
$output=($html);
$pdf->WriteHTML($output);
$pdf->Output("sample.pdf");
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=download.pdf");
readFile("sample.pdf");
?>

Now header and footer will be added to the generated pdf.

There are lot more functions in FPDF and we cannot cover all those.
To learn FPDF, please browse http://www.fpdf.org.


NOTE : GIF image solution
I think you face problem while using gif image in the pdf generation.so to avoid use link
http://code.google.com/p/html2pdf/issues/detail?id=2#c5 and download the gif.php and replace gif.php in html2pdf directory.

Gud Luck Developers.

4 comments:

  1. Thanks for the sharing of such information.This is a great stuff of reading.CMS Solutions .

    ReplyDelete
  2. Thank You Boss .... app ager ase info shiar kerte ho to app students aur fresher ki indirectly bahut help kerte ho koi help nhi kerta ajj kal to ...

    Thank TO Admin for That

    ReplyDelete
  3. thanks

    but when i compile php code then that code is not work perfectly

    ReplyDelete