Thursday 12 November 2009

HTML to PDF, generate PDF with HTML data,

To generate the HTML contents in PDF datatype or .pdf file format. Use the following steps:

1. Download the dompdf from
    http://code.google.com/p/dompdf/
or http://sourceforge.net/projects/dompdf/

2. Upzip(if necessary) and keep the dompdf/ folder at your's project root directory.

then, make a function to generate pdf file for download or write a file to the disk as;

/* function to generate the .pdf file for download. */

function get_generate_pdf ($htmlContent, $filename)
{
require_once ("../dompdf/dompdf_config.inc.php");

$dompdf = new DOMPDF();
$dompdf -> load_html($htmlContent);
$dompdf -> render();

$dompdf -> stream($filename);
}

/* function to write the .pdf file with HTML Contents. */
function get_write_pdf_file ($htmlContent, $filename)
{
require_once ("../dompdf/dompdf_config.inc.php");

$dompdf = new DOMPDF();
$dompdf -> load_html($htmlContent);
$dompdf -> render();

$pdfContent = $dompdf -> output();
file_put_contents($filename, $pdfContent);
}

/* function to write the file Contents. */
function get_write_file ($content, $filename, $mode="w")
{
$fp = @fopen ($file, $mode);

if ( ! is_resource($fp)) { return false; }

fwrite ($fp, $content);
fclose ($fp);
}

$htmlContent = "< html >< head >< title >SamplePDF file< /title >< /head >
< body >< strong >You can include any kinda html content in this body format.< /strong >< /body >< /html >";

$filename = "sample_pdf_file.pdf";

/* Calling above function for html content in pdf attachment file format. */
get_generate_pdf ($htmlContent, $filename)

/* Calling above function for html content in pdf attachment file format. */
get_generate_pdf ($htmlContent, $filename);

No comments:

Post a Comment

Please post any queries and comments here.