The code posted below will convert the specified HTML file to PDF using DOMPdf (http://www.digitaljunkies.ca/dompdf/) code is documented with examples below.
<?php
/**
* HTMLPDF This will use the DOMPdf class to convert a HTML to PDF with templating
* @author Michael Baker
*/
class HTMLPDF extends DOMPdf {
proctected $input = null;
protected $pdf = null;
public function __construct() {
$this->pdf = new DOMPDF();
}
/**
* inputFile - The input file name for the html file to be parsed
*
* @param string $filename The filename to parse for the template
* @return bool False if we hit an error but an exception will be thrown
* @throws I/O Errors
*/
public function inputFile($filename) {
if(!file_exists($filename)) {
throw new Exception(“Input file not found!”);
return false;
}
if(!is_readable($filename)) {
throw new Exception(“Input file found but not readable!”);
return false;
}
$file = fopen($filename, “r”);
while(!feof($file)) {
$this->input .= fread($file,8192);
}
fclose($file);
return true;
}
/**
* parseTemplate - This will parse a set of key => value array pairs into the PDF
*
* @param array $template
* @return boll False on I/O error
* @throws I/O exception is output is not writable
*/
public function parseTemplate($template) {
if(!is_array($template)) {
throw new Exception(“Variable passed is not an array k => v array required”);
return false;
}
foreach ($template as $k => $v) {
$this->input = str_replace(“[$k]“, $v, $this->input);
}
$this->pdf->load_html($this->input);
return true;
}
/**
* documentSize - This will set the document size for the output of the PDF see the PDF lib config for sizes
*
* @param string $paper Paper size
* @param string $orientation Paper orientation
* @return bool If the paper size or orientation is null it will return false
* @throws Null exception errors
*/
public function documentSize($paper,$orientation) {
if(is_null($paper) || is_null($orientation)) {
throw new Exception(“Paper and orientation cannot be null!”);
return false;
}
$this->pdf->set_paper($paper, $orientation);
}
/**
* renderPDF - This will render the PDF to a specifed outfile
*
* @param string $output Outpu file name
* @return bool False on I/O error
* @throws I/O Exceptions
*/
public function renderPDF($output) {
if(!is_writeable($output)) {
throw new Exception(“Output file is not writeable exiting”);
return false;
}
$this->pdf->render();
$this->pdf>stream($output);
return true;
}
public function __destruct() {
unset($this->input);
}
}
$pdf = new HTMLPDF();
$pdf->inputFile(“Test.html”);
$template['NAME'] = “Michael”;
$pdf->parseTemplate($template);
$pdf->documentSize(“a4″, “portrait”);
$pdf->renderPDF(“Test.pdf”);
$pdf->renderPDF(“/tmp/out.pdf”);
?>