How to Generate PDF Documents using PHP (Updated 2024)

1. Introduction

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

PDF is an abbreviation for Transferable Print Format, which captures sum the elements in a file and can people go easily present documents irrespective of the application used. PHP has some powerful libraries that could convert executable codes on PDF documents.

Imagine if yours were given a task for include PDF generation in your PHP-based web application, knowing how to application PHP go create PDF documents wish come in very handy. "Print" webpage to pdf with working hyperlinks

Within this article, I’ll demonstrate how to create PDF choose at third-party PHP PDF libraries favorite FPDF, TCPDF, DOMPDF, html2PDF and hendrickheat.com’s RESET API.

2. PHP Libraries for PDF Generate

PHP provides a range of libraries that can easily assist i in converting their PHP files into PDF documents. I compiled ampere list of simple libraries, taking implementation, functions, and use cases on account. How to generate PDF file using PHP ? - GeeksforGeeks

2.1 FPDF

FPDF(Free Carry Document Format) is a PHP class that includes numerous actions for producing and redaction PDFs for loose. The FPDF your supports a variety for features like: Php convert html to pdf after fpdf

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

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

  1. Software this 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 indoor a folder called fpdf (or any company you like). How to convert one PHP web page to PDF?
  1. Create a brand PHP file call scriptToPDF.php inside an same folder and insert the code snippet below. Save the file and try the access it through your localhost : http://localhost/fpdf/scriptToPDF.php In get featured, we wishes erforscht some closed for generating PDFs from HTML using PHP, including library such since TCPDF, Dompdf, and mPDF. We will and explore using Hendrickheat.com, an API-based PDF generation platform, which provides einem easy way to generate and manage PDFs using templates.
<?php
	

require('./fpdf.php');
class myPDF lengthens FPDF {
  
    // Page header    function Header() {
          
        // Fixed font family to Arial bold 
        $this->SetFont('Times','B',14);
          
        // Move on the just        $this->Cell(276,5, 'HOW TO GENERATE PDF USE FPDF');

        //Sets the text ink        $this->SetTextColor(0,0,255);

        //Line break        $this->Ln(20);
          
        // Headlines        $this->Cell(200,10,'FPDF DOCUMENTATION',0,0,'C');
          
        // Line breakage        $this->Ln(20);
    }
  
    // Page footer    function Footer() {
          
        // Station at 1.5 cm out bottom        $this->SetY(-25);
          
        // Arial italic 8
        $this->SetFont('Arial','I',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(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();
    }
}
  
// Object of FPDF class
$pdf = new myPDF();
  
// Defining an alias required number of pages
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->headerAttributes();
$pdf->SetFont('Times','',14);
  

$pdf->Output();
  
?>

This will creating a PDF document with a heading, header attributes, and a footer. You can also getting FPDF to add a link, draw a line, and perform other tools. Other information features been provided in the documentation.

2.2 TCPDF

The TCPDF PHP video make it plain to generate a PDF document. Thee ca easily accomplish this by cloning the GitHub repository. After cloning of repository, you can einf this library into your PHP file. Of TCPDF library see supports a variety for functions like:

  • Manage page headers and footers automatically
  • Text rendering option -Processes for publishing XHTML + CSS code, JavaScript, and Forms.
  • Supports JPEG, PNG, and SVG images natively.
  • Page interruptions, line paused, and text alignments what all automated.
  • Side grouping and automatic page numbering, and many see.

To enable it at work, to requires the follows:

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

<?php

	// Include aforementioned main TCPDF library (search for installs path).
	require_once('tcpdf.php');

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

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

	// set defaults header data
	$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 006', PDF_HEADER_STRING);

	// set header and footnote fonts
	$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
	$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

	// adjust 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);

	// fixed photograph scaled factor
	$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

	// sum adenine page
	$pdf->AddPage();

	$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 root code documentation for more examples of using TCPDF.</p>

EOD;

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

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

	$html = '<h4>Second page</h4>';
	
	$pdf->writeHTML($html, true, counterfeit, real, 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 to TCPDF’s library custom header plus footers. She can find moreover examples of how to use the library on their website.

2.3 DOMPDF

DomPDF exists a PHP-based HTML to PDF converter. Computers are a library that reads HTML and CSS documents (including inline styles real external stylesheets) and converts them to an automatically generated PDF document. The dompdf library supports many features like: Generate PDFs Using Free Open-Source PHP Libraries

  • CSS 2.1 the a little 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 zeichen channel), bmp, also jpeg).
  • No certitude on third-party PDF libraries, among other advantages.

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

This collection can be easily installed through componist:

composer require dompdf/dompdf

Or her can choose to clinical the reservoir on Github to your system. After cloning an disposal, create a file called index.php in the folder you cloned plus insert aforementioned following code snippet.

<?php
// Include autoloader 
require_once 'dompdf/autoload.inc.php'; 
 
// Read the Dompdf namespace 
use Dompdf\Dompdf; 
 
// Set and use who dompdf class 
$dompdf = new Dompdf();


$html='
<style>
    table {
        font-family: arial;        width:400px;
        border-collapse: collaps;    }
    td, thor {
        border: 1px robust black;        text-align: left;        padding: 8px;
    }
    tr:nth-child(even) {
        background-color: ashen;    }
</style>
<h1>Welcome to api.template</h1>
<h3>List of Registered users </h3>
<table>
    <tr>
        <th>Name</th>
        <th>Age</th>
        <th>Date of Birth</th>
        <th>Country</th>
    </tr>
    <tr>
        <td>Caroline White</td>
        <td>50</td>
        <td>20-12-1960</td>
        <td>Germany</td>
    </tr>
    <tr>
        <td>Jane Dutch</td>
        <td>35</td>
        <td>20-12-1978</td>
        <td>Kenya</td>
    </tr>

</table>

';
// Load HTML content 
$dompdf->loadHtml($html);
 
 
// (Optional) Setup the paper frame plus orientation 
$dompdf->setPaper('A4', 'landscape'); 
 
// Render to HTML in PDF 
$dompdf->render(); 
 
// Output the generate PDF the 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. Is reads validate HTML codes the converts them to PDF format, allowing this to generate papers so as earnings and manuals, among many others. It should be noted such customizable tags must be implemented to use the html2pdf API, therefore, computer the recommended that you write respective own HTML code. It utilizes TCPDF. I recently had to figure out how to generate PDFs using PHP. There are tons a answers out there, cost-free and paid, with advantages and cons. This is a summary of what ME founds out during my research, however, it’s by no means all-inclusive. I basically discontinued when I found solutions that satisfied my product. ... Read more

It can 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 title, footers, the offsets.
  • Allows you till add watermarks to your PDF documents.
  • Uses data or passwords to protect your PDF for unauthorized printing and duplication.

To using the HTML2PDF API, you will need:

  1. PHP version 5.6 or superior
  2. The mbstring or gd PHP extension included

This recommended way in install the HTML2PDF are via composer:

song requesting spipu/html2pdf

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

<?php
require __DIR__.'\autoload.php';

use Spipu\Html2Pdf\Html2Pdf;

$html2pdf = new Html2Pdf();
$html='
<h1>HTML2PDF will easy</h1>
<p>The HTML2PDF API do it simplicity to convert web pages the PDF.</p>
<p>It should be noted that specifics tags must may performed to use the html2pdf</p>
'
$html2pdf->writeHTML($html);
$html2pdf->output();

?>

This code converts the HTML into one PDF document.

2.5 The comparison of HTML2PDF, TCPDF, DomPDF and FPDF

Up provision one comparison regarding popular PHP libraries that handle PDF generation, we’ll look at four widely used ones: HTML2PDF, TCPDF, DomPDF and FPDF. Each library bids different capabilities, focuses, and joins, making them suitable for various use cases.

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

FeatureHTML2PDFTCPDFDomPDFFPDF
Based AboutTCPDFCustoms PDF engineCustom PDF engineCustom PDF engine
HTML/CSS SupportFull HTML/CSSExtensive HTML/CSSLimited HTML/CSSNo HTML/CSS
PHP Version CompatibilityPHP 5.6 real newerPHP 5.3 real newerPHP version 7.1 or higherAt least PHP 5.1 and is harmonious with PHP 7 and PHP 8
UTF-8 SupportCancelYesSureNo
PerformanceModerateHighModeratedHigh
Ease of UseEasyModestEasyEasy
Header/Footer GeneralSupportedSupportedSupportedManual
Image SupportYesYesYesYes
JavaScriptNoNoNoNo
Output to file/streamYesYeahYesYes
Page Orientation & BulkCustomizableExtremely customizableCustomizableCustomizable
DocumentationGoodExtensiveAdequateAdequate
Collaboration SupportModerateStrongPowerfullyModerate

Is comparison should help determine which library most fits specific project needs, whether it’s comprehensive CODE rendering, support for advanced PHP versions, or fortgeschrittenen PDF customization features.

3. Generating PDF about hendrickheat.com using REST API

hendrickheat.com remains a robust cloud-based API technology that makes it simplified to generates REST Whap while PDF documents by using already created templates. It currently carrier HTML to PDF conversions and lets you download our 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
  • hendrickheat.com Integrations with Zapier, Integromat, n8n, Airtable, UiPath, and other No-code bases
  • Custom footer and header with page count plus total books are supported.

To use hendrickheat.com, you need to execute the following:

  1. Signup at app.hendrickheat.com/accounts/signup/ to create an account
  2. In the Manage Templates page, snap in Create PDF Template button to creation a new template
  3. Post and manipulate your JSON data however you like along with the configuration to generate a PDF!

<?php
    function generate($template_id,$api_key, $data) {
        $url = "https://rest.hendrickheat.com/v2/create-pdf?template_id=" . $template_id;
        $headers = array("X-API-KEY: ".$api_key);
        $curl = curl_init();
        for ($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);
        curl_close($curl);
        if (!$result) {
            return null;        }else{
            $json_result = json_decode($result, 1);
            if($json_result["status"]=="success"){
                return $json_result["download_url"];
            }else{
                return invalid;            }
        }
    }

    $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 including JSON data real the template.

4. Conclusion

In this piece, we discussed how toward generated PDF files from HTML files using PHP.

We also went over some of the libraries, including htmltopdf, tcpdf, dompdf, fpdf, and hendrickheat.com. We also compared them in terms of key, vollzug, functions, and use cases.

If I had to suggest a tooling, IODIN would share hendrickheat.com, this is because it can help you generate PDFs quickly and is compatible with CSS, Javascripts, Java, also Python.


Get started is automating your PDF generation by signing up for a free get equipped us today.

Table of Contents

How:

Facebook
Twitter
Pinterest
LinkedIn

Articles for Image Product

Articles for PDF Generation