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

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 APITemplate.io’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:

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
SetFont('Times','B',14); // Move to the right $this->Cell(276,5, 'HOW TO GENERATE PDF USING FPDF'); //Sets the text color $this->SetTextColor(0,0,255); //Line break $this->Ln(20); // Header $this->Cell(200,10,'FPDF DOCUMENTATION',0,0,'C'); // Line break $this->Ln(20); > // Page footer function Footer() < // Position at 1.5 cm from bottom $this->SetY(-25); // Arial italic 8 $this->SetFont('Arial','I',8); // Page number $this->Cell(0,10,'Page ' . $this->PageNo() . '/',0,0,'C'); > // header Attributes function headerAttributes() < $this->SetFont('Times','B', 10); $this->Cell(30,10,'Attributes',1,0,'C'); $this->Cell(45,10,'Description',1,0,'C'); $this->Cell(60,10,'How to Use',1,0,'C'); $this->Cell(40,10,'Tutorials',1,0,'C'); $this-the >Ln(); > > // Instantiation of FPDF class $pdf = new myPDF(); // Define an alias for number of pages $pdf->AliasNbPages(); $pdf->AddPage(); $pdf->headerAttributes(); $pdf->SetFont('Times','',14); $pdf->Output(); ?>

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.

2.2 TCPDF

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:

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.
SetCreator(PDF_CREATOR); $pdf->SetAuthor('Nicole Asuni'); $pdf->SetTitle('PDF file using TCPDF'); // set default header data $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 006', PDF_HEADER_STRING); // 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 $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); // set margins $pdf->SetMargins(20, 20, 20); $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); // add a page $pdf->AddPage(); $html = TCPDF PHP Library is easy! This is an example of the TCPDF library. 

I am using the default header and footer

Please check the source code documentation for more examples of using TCPDF.

EOD; // Print text using writeHTMLCell() $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true); // $pdf->writeHTML($html, true, false, true, false, ''); // add a page $pdf->AddPage(); $html = '

Second page

'; $pdf->writeHTML($html, true, false, true, false, ''); // reset pointer to the last page $pdf->lastPage(); //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.

2.3 DOMPDF

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:

** 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.

 table < font-family: arial; width:400px; border-collapse: collapse; >td, th < border: 1px solid black; text-align: left; padding: 8px; >tr:nth-child(even) 

Welcome to api.template

List of Registered users

Name Age Date of Birth Country
Caroline White 50 20-12-1960 Germany
Jane Dutch 35 20-12-1978 Kenya
'; // Load HTML content $dompdf->loadHtml($html); // (Optional) Setup the paper size and orientation $dompdf->setPaper('A4', 'landscape'); // Render the HTML as PDF $dompdf->render(); // Output the generated PDF to Browser $dompdf->stream(); ?>

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

2.4 HTML2PDF

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:

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.

HTML2PDF is easy 

The HTML2PDF API makes it simple to convert web pages to PDF.

It should be noted that specific tags must be implemented to use the html2pdf

' $html2pdf->writeHTML($html); $html2pdf->output(); ?>

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:

FeatureHTML2PDFTCPDFDomPDFFPDF
Based OnTCPDFCustom PDF engineCustom PDF engineCustom PDF engine
HTML/CSS SupportFull HTML/CSSExtensive HTML/CSSLimited HTML/CSSNo HTML/CSS
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
PerformanceModerateHighModerateHigh
Ease of UseEasyModerateEasyEasy
Header/Footer ManagementSupportedSupportedSupportedManual
Image SupportYesYesYesYes
JavaScriptNoNoNoNo
Output to file/streamYesYesYesYes
Page Orientation & SizeCustomizableHighly customizableCustomizableCustomizable
DocumentationGoodExtensiveAdequateAdequate
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 APITemplate.io using REST API

APITemplate.io 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:

To use APITemplate.io, you need to do the following:

  1. Signup at app.apitemplate.io/accounts/signup/ 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!
else< $json_result = json_decode($result, 1); if($json_result["status"]=="success")< return $json_result["download_url"]; >else < 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 APITemplate.io. We also compared them in terms of features, implementation, functions, and use cases.

If I had to suggest a tool, I would recommend APITemplate.io, 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.