Programmatically Creating PDF files from HTML using PHP

I don’t truly like Adobe PDF files, their negative attributes such as being slow to open, clumsy to edit if-at-all, inadequate and in-the-way security features, outweigh their positive attributes like being formatted, cross-platform, and transmittable.

Since they are the de-facto standard for formatted documents they are in-demand and remain useful.   It’s often the case with complex operational systems that clients request and web application end-users would like to have access to PDF’s of internal reports as well as client/partner-destined documents like invoices,  quotes, or sales reports.   The reasons include the ability to email or print the document with the formatting intact – not always the case with a web page sent directly to the printer.

There are two approaches that I’m aware of for generating PDF’s from within an interactive web application:

  1. Create the entire PDF programmatically. An example of doing this using the TCPDF library might look like this:
    // create new PDF document
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    // set document information
    $pdf->SetAuthor('Nicola Asuni');
    $pdf->SetTitle('TCPDF Example 001');
    // set default header data
    // set default monospaced font
    //set margins
    // Add a page
    // Set some content to print
    $html = <<
 Freelance Vancouver Contract Programming.

    This is an example of printing PDF's from PHP without PDFLib. EOD; // --------------------------------------------------------- // Close and output PDF document $pdf->Output('example_001.pdf', 'I');
  2. Another means is to create an HTML page (or take an existing one) and render it into a PHP buffer (ob_start()) or save to a temporary file, and then pass this rendered HTML to a PHP class that generates PDF’s from HTML.  An example using the TUFAT HTML2PS library follows:
    PDF conversion with default settings
     * Warning: if you have any files (like CSS stylesheets and/or images referenced by this file,
     * use absolute links (like
     * @param $path_to_html String path to source html file.
     * @param $path_to_pdf  String path to file to save generated PDF to.
    function convert_to_pdf($path_to_html, $path_to_pdf) {
       * Handles the saving generated PDF to user-defined output file on server
      class MyDestinationFile extends Destination {
         * @var String result file name / path
         * @access private
        var $_dest_filename;
        function MyDestinationFile($dest_filename) {
          $this->_dest_filename = $dest_filename;
        function process($tmp_filename, $content_type) {
          copy($tmp_filename, $this->_dest_filename);
      class MyFetcherLocalFile extends Fetcher {
        var $_content;
        function MyFetcherLocalFile($file) {
          $this->_content = file_get_contents($file);
        function get_data($dummy1) {
          return new FetchedDataURL($this->_content, array(), "");
        function get_base_url() {
          return "";
      $pipeline = PipelineFactory::create_default_pipeline("", // Attempt to auto-detect encoding
      // Override HTML source
      $pipeline->fetchers = array(new MyFetcherLocalFile($path_to_html));
      // Override destination to local file
      $pipeline->destination = new MyDestinationFile($path_to_pdf);
      $baseurl = "";
      $media = Media::predefined("A4");
      $media->set_margins(array('left'   => 0,
                                'right'  => 0,
                                'top'    => 0,
                                'bottom' => 0));
      global $g_config;
      $g_config = array(
                        'cssmedia'     => 'screen',
                        'renderimages' => true,
                        'renderlinks'  => true,
                        'renderfields' => true,
                        'renderforms'  => false,
                        'mode'         => 'html',
                        'encoding'     => '',
                        'debugbox'     => false,
                        'pdfversion'    => '1.4',
                        'draw_page_border' => false
      global $g_px_scale;
      $g_px_scale = mm2pt($media->width() - $media->margins['left'] - $media->margins['right']) / $media->pixels;
      global $g_pt_scale;
      $g_pt_scale = $g_px_scale * 1.43; 
      $pipeline->process($baseurl, $media);
    // The all-important call to convert the saved HTML file to PDF.
    convert_to_pdf("forms.html", "forms.pdf");

There are a number of PHP class libraries that don’t require the commercial PDFLib PECL extension in order to generate PDF’s in your PHP-based web application, here are some of the ones I’ve found that work.

  • DOMPDF – Support UTF8. Supports headers and footers.  Choice for creating PDF’s programmatically as in the first example above.
  • HTML2PS – Works well for generating PDF’s from rendered HTML as in example two.  Can be difficult to get the headers/footers to align as needed.  Large number of support forums answers. Can generate PostScript or PDFs as output. Font configuration and support is somewhat under-documented/complicated.
  • FPDF – perhaps the original free alternative to  the commercial PDFLib.   HTML2PS library is based on a modified version of this.
  • Zend_PDF – A  Zend Framework module that can programmatically create PDF files.  No personal experience, others have commented that it’s not as powerful as DOMPDF.

Tags: , ,

One Response to “Programmatically Creating PDF files from HTML using PHP”