generating pdf files from html in php

Generating PDF Files From Html Using TCPDF

In this article i will illustrate how to generate pdf files from html in PHP using the open source TCPDF library.

 

 

There are a lot of open source libraries in php that can be used to generate pdf files from html, but most of them lack some pdf features such as how to manipulate text written in Right to Left languages, also handling the different font types.

 

TCPDF in the other hand is a powerful open source library that has almost all the features needed to generate a well working pdf files, from these features:

  • all standard page formats, custom page formats, custom margins and units of measure.
  • UTF-8 Unicode and Right-To-Left languages
  • TrueTypeUnicode, OpenTypeUnicode, TrueType, OpenType, Type1 and CID-0 fonts.
  • methods to publish some XHTML + CSS code, Javascript and Forms.
  • images (PNG, JPG, GIF), graphic (geometric figures) and transformation methods.
  • automatic page header and footer management.
  • document encryption up to 256 bit and digital signature certifications.

Check out TCPDF official website to figure the rest of the available features.

 

Download & Usage

Go to the github repository of TCPDF and clone or download it.

You need to add the library in your project folder and then include it like this:

include_once('TCPDF/tcpdf.php');

By including the main tcpdf.php you have access to all classes and methods.

 

Configuration

The main configuration file located in TCPDF/config/tcpdf_config.php. This file contains the general configuration that applies as per document basis when generating pdf files. Try to uncomment and change the configuration values to suite your needs.

Adjust these configurations values:

// Installation path (/var/www/html/project folder/TCPDF/)
define ('K_PATH_MAIN', '/var/www/html/pdf-tutorial/TCPDF/');

// URL path to tcpdf installation folder (http://localhost/tcpdf/).
define ('K_PATH_URL', 'http://localhost/pdf-tutorial/tcpdf/');

// Path for PDF fonts.
define ('K_PATH_FONTS', K_PATH_MAIN.'fonts/');

// Default images directory for example used for logos
define ('K_PATH_IMAGES', K_PATH_MAIN.'../images/');

// Default image logo used be the default Header() method.
define ('PDF_HEADER_LOGO', 'my_logo.png');

// Header logo image width in user units.
define ('PDF_HEADER_LOGO_WIDTH', 30);

// Cache directory for temporary files (full path).
define ('K_PATH_CACHE', '/tmp/');

The above configurations is the basic configurations needed but there more you can explore them by yourself as we don’t cover them in this tutorial.

As shown i have created a new folder for images in the project root folder, this will be used to store the header logo:

define ('K_PATH_IMAGES', K_PATH_MAIN.'../images/');

define ('PDF_HEADER_LOGO', 'my_logo.png');



Example:

Let’s create a new file in the project root directory called index.php with the following contents:

index.php

include_once('TCPDF/tcpdf.php');

// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

$pdf->SetCreator("Wael Salah");
$pdf->SetAuthor('Wael Salah');
$pdf->SetTitle('Demonstrating pdf with php');

$pdf->setHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING, array(0, 6, 255), array(0, 64, 128));
$pdf->setFooterData(array(0,64,0), array(0,64,128));

$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);

$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// ---------------------------------------------------------

// set default font subsetting mode

$pdf->setFont('dejavusans', '', 14, '', true);

$pdf->AddPage();

$html = <<<EOD
<h1 style="text-decoration:none;background-color:#CC0000;color:black;">Demonstrating pdf with php</h1>
<p>In this simple example i show how to generate pdf documents using TCPDF</p>
EOD;

$pdf->writeHTML($html);

$pdf->Output('test.pdf', 'I');

Run this example you should see the pdf document opened in the browser itself. Now let’s explain the code below.

At first when generating pdf documents there are two steps. In the first step we setup the overall document appearance, this include setting fonts, colors, document title, header, footer, and the margins.

In the second step we begin by creating the pages by calling method AddPage(), then prepare the html to display, then call writeHtml() method and finally output the file.

 

In the above code we begin the first step by creating a new instance of TCPDF using the TCPDF() constructor like this:

$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

The constructor accepts a list of arguments like the page orientation, page format in that case it’s “A4“, the encoding, here it’s “UTF-8” which supports RTL languages.

Then i set the metadata for the document like creator and author:

$pdf->SetCreator("Wael Salah");
$pdf->SetAuthor('Wael Salah');
$pdf->SetTitle('Demonstrating pdf with php');

Then i set the header and footer data:

$pdf->setHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING, array(0, 6, 255), array(0, 64, 128));
$pdf->setFooterData(array(0,64,0), array(0,64,128));

The setHeaderData() method accepts the header logo, the logo width, the header title, the header string text, all of these constants defined in the configuration file we described above. The other  two arguments represents the RGB color for the text and line.

After that i set the header and footer fonts as shown:

$pdf->setHeaderFont(array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

Those two methods accepts an array with the font family and font size.

It’s important also to set margins for the document, this achieved by calling those methods:

$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

Then i enabled the option of auto page break by calling SetAutoPageBreak(). Also for the images i set the scale ratio to be 1.25 by calling setImageScale(). Finally i set the font for the document text by calling setFont() method which takes the font family, style, size, and the font file.



The second step i added a new page like this:

$pdf->AddPage();

When ever you need to add a new page you must call this method. Next i specified the html text to be written to pdf file then we called writeHtml() method to write the html to the pdf page:

$html = <<<EOD
<h1 style="text-decoration:none;background-color:#CC0000;color:black;">Demonstrating pdf with php</h1>
<p>In this simple example i show how to generate pdf documents using TCPDF</p>
EOD;

$pdf->writeHTML($html);

Finally to generate the file:

$pdf->Output('test.pdf', 'I');

The Output() method takes the file name and a second parameter that defines a character that represent the destination to send the document to:

  • The “I” option means send the file to be displayed in the browser.
  •  “D” which send the file to the browser and force a file download.
  • “F” save to a local server file.
  • “S” return the document as a string.

 

Adding new pages:

Adding new pages is done easily by calling AddPage() method, let’s add two more pages to the above example, add this code after $pdf->writeHTML($html):

$pdf->AddPage();

$html = <<<EOD
<h1 style="text-decoration:none;background-color:#CC0000;color:black;">Second page</h1>
<p>This is the second page on this tutorial</p>
EOD;

$pdf->writeHTML($html);

$pdf->AddPage();

$html = <<<EOD
<h1 style="text-decoration:none;background-color:#CC0000;color:black;">Third page</h1>
<p>This is the third page on this tutorial</p>
EOD;

$pdf->writeHTML($html);

$pdf->Output('test.pdf', 'I');

 

Adding images:

You can add images easily in html and TCPDF will handle the hard work to display those images, let’s add a new page which has an img tag:

$pdf->AddPage();

$html = <<<EOD
<h1 style="text-decoration:none;background-color:#CC0000;color:black;">Page with image</h1>
<p><img src="https://i.ebayimg.com/thumbs/images/g/pDUAAOSwcXhcWU4H/s-l225.jpg" />
 </p>
EOD;

$pdf->writeHTML($html);

 

Html & CSS:

This library comes with ability to apply css code to the html text then it will transform this to the corresponding pdf styling like in this example:

$pdf->AddPage();

$html = <<<EOF
<!-- EXAMPLE OF CSS STYLE -->
<style>
    h1 {
        color: navy;
        font-family: times;
        font-size: 24pt;
        text-decoration: underline;
    }
    p.first {
        color: #003300;
        font-family: helvetica;
        font-size: 12pt;
    }
    p.first span {
        color: #006600;
        font-style: italic;
    }
    p#second {
        color: rgb(00,63,127);
        font-family: times;
        font-size: 12pt;
        text-align: justify;
    }
    p#second > span {
        background-color: #FFFFAA;
    }
    table.first {
        color: #003300;
        font-family: helvetica;
        font-size: 8pt;
        border-left: 3px solid red;
        border-right: 3px solid #FF00FF;
        border-top: 3px solid green;
        border-bottom: 3px solid blue;
        background-color: #ccffcc;
    }
    td {
        border: 2px solid blue;
        background-color: #ffffee;
    }
    td.second {
        border: 2px dashed green;
    }
    div.test {
        color: #CC0000;
        background-color: #FFFF66;
        font-family: helvetica;
        font-size: 10pt;
        border-style: solid solid solid solid;
        border-width: 2px 2px 2px 2px;
        border-color: green #FF00FF blue red;
        text-align: center;
    }
    .lowercase {
        text-transform: lowercase;
    }
    .uppercase {
        text-transform: uppercase;
    }
    .capitalize {
        text-transform: capitalize;
    }
</style>

<h1 class="title">Example of <i style="color:#990000">XHTML + CSS</i></h1>

<p class="first">Example of paragraph with class selector. <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sed imperdiet lectus. Phasellus quis velit velit, non condimentum quam. Sed neque urna, ultrices ac volutpat vel, laoreet vitae augue. Sed vel velit erat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Cras eget velit nulla, eu sagittis elit. Nunc ac arcu est, in lobortis tellus. Praesent condimentum rhoncus sodales. In hac habitasse platea dictumst. Proin porta eros pharetra enim tincidunt dignissim nec vel dolor. Cras sapien elit, ornare ac dignissim eu, ultricies ac eros. Maecenas augue magna, ultrices a congue in, mollis eu nulla. Nunc venenatis massa at est eleifend faucibus. Vivamus sed risus lectus, nec interdum nunc.</span></p>

<p id="second">Example of paragraph with ID selector. <span>Fusce et felis vitae diam lobortis sollicitudin. Aenean tincidunt accumsan nisi, id vehicula quam laoreet elementum. Phasellus egestas interdum erat, et viverra ipsum ultricies ac. Praesent sagittis augue at augue volutpat eleifend. Cras nec orci neque. Mauris bibendum posuere blandit. Donec feugiat mollis dui sit amet pellentesque. Sed a enim justo. Donec tincidunt, nisl eget elementum aliquam, odio ipsum ultrices quam, eu porttitor ligula urna at lorem. Donec varius, eros et convallis laoreet, ligula tellus consequat felis, ut ornare metus tellus sodales velit. Duis sed diam ante. Ut rutrum malesuada massa, vitae consectetur ipsum rhoncus sed. Suspendisse potenti. Pellentesque a congue massa.</span></p>

<div class="test">example of DIV with border and fill.
<br />Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<br /><span class="lowercase">text-transform <b>LOWERCASE</b> Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
<br /><span class="uppercase">text-transform <b>uppercase</b> Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
<br /><span class="capitalize">text-transform <b>cAPITALIZE</b> Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
</div>

<br />

<table class="first" cellpadding="4" cellspacing="6">
 <tr>
  <td width="30" align="center"><b>No.</b></td>
  <td width="140" align="center" bgcolor="#FFFF00"><b>XXXX</b></td>
  <td width="140" align="center"><b>XXXX</b></td>
  <td width="80" align="center"> <b>XXXX</b></td>
  <td width="80" align="center"><b>XXXX</b></td>
  <td width="45" align="center"><b>XXXX</b></td>
 </tr>
 <tr>
  <td width="30" align="center">1.</td>
  <td width="140" rowspan="6" class="second">XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX</td>
  <td width="140">XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td width="80">XXXX</td>
  <td align="center" width="45">XXXX<br />XXXX</td>
 </tr>
 <tr>
  <td width="30" align="center" rowspan="3">2.</td>
  <td width="140" rowspan="3">XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td align="center" width="45">XXXX<br />XXXX</td>
 </tr>
 <tr>
  <td width="80">XXXX<br />XXXX<br />XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td align="center" width="45">XXXX<br />XXXX</td>
 </tr>
 <tr>
  <td width="80" rowspan="2" >XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td align="center" width="45">XXXX<br />XXXX</td>
 </tr>
 <tr>
  <td width="30" align="center">3.</td>
  <td width="140">XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td align="center" width="45">XXXX<br />XXXX</td>
 </tr>
 <tr bgcolor="#FFFF80">
  <td width="30" align="center">4.</td>
  <td width="140" bgcolor="#00CC00" color="#FFFF00">XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td align="center" width="45">XXXX<br />XXXX</td>
 </tr>
</table>
EOF;

// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');



Right to Left languages:

As we mentioned earlier that TCPDF has a full support of RTL languages using the “UTF-8” encoding that we passed when we initialized the TCPDF() constructor, so let’s add a new page which has Arabic text.

$pdf->AddPage();

$html = <<<EOF
<p style="color: red">
لوريم إيبسوم(Lorem Ipsum) هو ببساطة نص شكلي (بمعنى أن الغاية هي الشكل وليس المحتوى) ويُستخدم في صناعات المطابع ودور النشر. كان لوريم إيبسوم ولايزال المعيار للنص الشكلي منذ القرن الخامس عشر عندما قامت مطبعة مجهولة برص مجموعة من الأحرف بشكل عشوائي أخذتها من نص، لتكوّن كتيّب بمثابة دليل أو مرجع شكلي لهذه الأحرف. خمسة قرون من الزمن لم تقضي على هذا النص، بل انه حتى صار مستخدماً وبشكله الأصلي في الطباعة والتنضيد الإلكتروني. انتشر بشكل كبير في ستينيّات هذا القرن مع إصدار رقائق "ليتراسيت" (Letraset) البلاستيكية تحوي مقاطع من هذا النص، وعاد لينتشر مرة أخرى مؤخراَ مع ظهور برامج النشر الإلكتروني مثل "ألدوس بايج مايكر" (Aldus PageMaker) والتي حوت أيضاً على نسخ من نص لوريم إيبسوم. 
</p>
EOF;

$pdf->writeHTML($html);

As seen above i have added some arabic text and it should display them correctly. The library has a lot more more other functions for formatting and manipulating pdf unfortunately i will not cover all of these in this tutorial but i encourage you to explore them in the TCPDF official website.

5 1 vote
Article Rating
Share this: