Generate PDFs in PHP with 4 Popular Libraries (Updated 2024)

1. Introduction

PHP is one of the most powerful server-side scripting languages available today. This programming language is used by developers to create websites that are dynamic and interactive.

PDF is an abbreviation for Portable Document Format, which captures all the elements in a file and allows people to easily present documents irrespective of the application used. PHP has some powerful libraries that can convert executable codes into PDF documents.

Imagine if you were given a task to include PDF generation in your PHP-based web application, knowing how to use PHP to create PDF documents would come in very handy.

In this article, I’ll demonstrate how to create PDF files with third-party PHP PDF libraries like FPDF, TCPDF, DOMPDF, html2PDF and’s REST API.

2. Four Popular PHP Libraries for PDF Generation

PHP provides a range of libraries that can easily assist you in converting your PHP files into PDF documents. I compiled a list of simple libraries, taking implementation, functions, and use cases into account.

2.1 FPDF

FPDF(Free Portable Document Format) is a PHP class that includes numerous functions for creating and editing PDFs for free. The FPDF class supports a variety of features like:

  • Image support (PNG, JPEG, and GIF)
  • Page headers
  • Page format
  • Footers
  • Automatic page break, and many more

However, because it is a third-party library, it requires some processes before you can use it. You will need to:

  1. Download the FPDF class for free from the FPDF website.
  2. Create a folder and extract the FPDF package into it. Let’s say that you have downloaded and extracted the FPDF package inside a folder called fpdf (or any name you like).
  1. Create a new PHP file called scriptToPDF.php inside the same folder and insert the code snippet below. Save the file and try to access it through your localhost : http://localhost/fpdf/scriptToPDF.php

class myPDF extends FPDF {
    // Page header
    function Header() {
        // Set font family to Arial bold 
        // Move to the right
        $this->Cell(276,5, 'HOW TO GENERATE PDF USING FPDF');

        //Sets the text color

        //Line break
        // Header
        $this->Cell(200,10,'FPDF DOCUMENTATION',0,0,'C');
        // Line break
    // Page footer
    function Footer() {
        // Position at 1.5 cm from bottom
        // Arial italic 8
        // Page number
        $this->Cell(0,10,'Page ' . 
            $this->PageNo() . '/{nb}',0,0,'C');
    // header Attributes
    function headerAttributes() {
        $this->SetFont('Times','B', 10);
        $this->Cell(60,10,'How to Use',1,0,'C');
        $this-the >Ln();
// Instantiation of FPDF class
$pdf = new myPDF();
// Define an alias for number of pages


This will create a PDF document with a header, header attributes, and a footer. You can also use FPDF to add a link, draw a line, and perform other functions. More information has been provided in the documentation.


The TCPDF PHP library makes it simple to generate a PDF document. You can easily accomplish this by cloning the GitHub repository. After cloning the repository, you can import this library into your PHP file. The TCPDF library also supports a variety of functions like:

  • Manage page headers and footers automatically
  • Text rendering options -Processes for publishing XHTML + CSS code, JavaScript, and Forms.
  • Supports JPEG, PNG, and SVG images natively.
  • Page breaks, line breaks, and text alignments are all automated.
  • Page grouping and automatic page numbering, and many more.

To enable it to work, it requires the following:

  1. Clone the repository
  2. Create a file called ‘myPDF.php’ (or any other name you want) inside the folder you cloned and insert the following code snippet.


	// Include the main TCPDF library (search for installation path).

	// create new PDF document

	// set document information
	$pdf->SetAuthor('Nicole Asuni');
	$pdf->SetTitle('PDF file using TCPDF');

	// set default header data

	// set header and footer fonts
	$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

	// set margins
	$pdf->SetMargins(20, 20, 20);

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

	// set image scale factor

	// add a page

	$html = <<<EOD
<h1>TCPDF PHP Library is easy!</h1>
<i>This is an example of the TCPDF library.</i>
<p>I am using the default header and footer</p>
<p>Please check the source code documentation for more examples of using TCPDF.</p>


// Print text using writeHTMLCell()
$pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);

	// $pdf->writeHTML($html, true, false, true, false, '');
        // add a page

	$html = '<h4>Second page</h4>';
	$pdf->writeHTML($html, true, false, true, false, '');

	// reset pointer to the last page
	//Close and output PDF document
	$pdf->Output('example.pdf', 'I');


This generates a PDF document using the TCPDF’s library default header and footer. You can find more examples of how to use the library on their website.


DomPDF is a PHP-based HTML to PDF converter. It is a library that reads HTML and CSS documents (including inline styles and external stylesheets) and converts them to an automatically generated PDF document. The dompdf library supports many features like:

  • CSS 2.1 and a few CSS3 properties, including @import, @media, and @page rules
  • The majority of HTML 4.0 presentational attributes
  • Compatibility with complex tables
  • Support for images (gif, png (8, 24, and 32 bit with alpha channel), bmp, and jpeg).
  • No reliance on third-party PDF libraries, among other advantages.

** Note: To enable it to function, PHP version 7.1 or higher is required.

This library can be easily installed via composer:

composer require dompdf/dompdf

Or you can choose to clone the repository on Github to your system. After cloning the repository, create a file called index.php inside the folder you cloned and insert the following code snippet.

// Include autoloader 
require_once 'dompdf/'; 
// Reference the Dompdf namespace 
use Dompdf\Dompdf; 
// Instantiate and use the dompdf class 
$dompdf = new Dompdf();

    table {
        font-family: arial;
        border-collapse: collapse;
    td, th {
        border: 1px solid black;
        text-align: left;
        padding: 8px;
    tr:nth-child(even) {
        background-color: grey;
<h1>Welcome to api.template</h1>
<h3>List of Registered users </h3>
        <th>Date of Birth</th>
        <td>Caroline White</td>
        <td>Jane Dutch</td>


// Load HTML content 
// (Optional) Setup the paper size and orientation 
$dompdf->setPaper('A4', 'landscape'); 
// Render the HTML as PDF 
// Output the generated PDF to Browser 

This code generates a PDF document with the following HTML and CSS layout.


The HTML2PDF API makes it simple to convert web pages to PDF. It reads valid HTML codes and converts them to PDF format, allowing it to generate documents such as receipts and manuals, among many others. It should be noted that specific tags must be implemented to use the html2pdf API, therefore, it is recommended that you write your own HTML code. It utilizes TCPDF.

It has a lot of cool features, such as:

  • The ability to customize the page size and margins
  • Allows you to personalize the layout by changing the fonts and colors to your liking.
  • Enables you to customize your headers, footers, and offsets.
  • Allows you to add watermarks to your PDF documents.
  • Uses encryption or passwords to protect your PDF from unauthorized printing and copying.

To use the HTML2PDF API, you will need:

  1. PHP version 5.6 or higher
  2. The mbstring or gd PHP extension installed

The recommended way to install the HTML2PDF is via composer:

composer require spipu/html2pdf

Create a new file in the root folder and paste the following code into it.

require __DIR__.'\autoload.php';

use Spipu\Html2Pdf\Html2Pdf;

$html2pdf = new Html2Pdf();
<h1>HTML2PDF is easy</h1>
<p>The HTML2PDF API makes it simple to convert web pages to PDF.</p>
<p>It should be noted that specific tags must be implemented to use the html2pdf</p>


This code converts the HTML into a PDF document.

3. The Comparison of 4 Popular Libraries

To provide a comparison of popular PHP libraries that handle PDF generation, we’ll look at four widely used ones: HTML2PDF, TCPDF, DomPDF and FPDF. Each library offers different capabilities, focuses, and interfaces, making them suitable for various use cases.

Here’s a detailed table summarizing their features, compatibility, ease of use, and specific functionalities:

Based OnTCPDFCustom PDF engineCustom PDF engineCustom PDF engine
PHP Version CompatibilityPHP 5.6 and newerPHP 5.3 and newerPHP version 7.1 or higherAt least PHP 5.1 and is compatible with PHP 7 and PHP 8
UTF-8 SupportYesYesYesNo
Ease of UseEasyModerateEasyEasy
Header/Footer ManagementSupportedSupportedSupportedManual
Image SupportYesYesYesYes
Output to file/streamYesYesYesYes
Page Orientation & SizeCustomizableHighly customizableCustomizableCustomizable
Community SupportModerateStrongStrongModerate

This comparison should help determine which library best fits specific project requirements, whether it’s comprehensive HTML rendering, support for older PHP versions, or advanced PDF customization features.

4. Generating PDF with using REST API is a robust cloud-based API platform that makes it simple to generate REST APIs as PDF documents by using already created templates. It currently supports HTML to PDF conversions and lets you preview your PDF before downloading.

It includes some great features, such as:

  • Convert HTML to PDF or using a reusable template
  • It is compatible with CSS, JavaScript, PHP, and Python
  • Integrates with Zapier, Integromat, n8n, Airtable, UiPath, and other No-code platforms
  • Custom footer and header with page number and total pages are supported.

To use, you need to do the following:

  1. Signup at to create an account
  2. In the Manage Templates page, click on Create PDF Template button to create a new template
  3. Post and manipulate your JSON data however you like along with the parameters to generate a PDF!

    function generate($template_id,$api_key, $data) {
        $url = "" . $template_id;
        $headers = array("X-API-KEY: ".$api_key);
        $curl = curl_init();
        if ($data) curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        if (!$result) {
            return null;
            $json_result = json_decode($result, 1);
                return $json_result["download_url"];
                return null;

    $tempate_id = "79667b2b1876e347";
    $api_key = "6fa6g2pdXGIyHRhVlGh7U56Ada1eF";
    $json_payload='{ "invoice_number": "INV38379", "date": "2021-09-30", "currency": "USD", "total_amount": 82542.56 }';
    echo generate($tempate_id,$api_key,$json_payload);

This endpoint generates a PDF document containing JSON data and the template.

5. Conclusion

In this article, we discussed how to generate PDF files from HTML files using PHP.

We also went over some of the libraries, including htmltopdf, tcpdf, dompdf, fpdf, and We also compared them in terms of features, implementation, functions, and use cases.

If I had to suggest a tool, I would recommend, this is because it can help you generate PDFs quickly and is compatible with CSS, JavaScript, Java, and Python.

Get started with automating your PDF generation by signing up for a free account with us today.

Table of Contents



Articles for Image Generation

Articles for PDF Generation