How to generate a PDF file using mPDF in PHP
In this article, you will learn how to generate a PDF file or convert HTML into PDF using the mPDF library of the PHP programming language.
PDF is a read-only document that cannot be modified by users until they have the right electronic footprint. Today, document security is the most important concern for sharing information over the internet. By using PDF, organisations can put their username and password on a PDF level to secure document information. There is also a demand for dynamically increasing PDF files by organizations, like generating an invoice, salary receipt, e-book, ID card, etc. with a single click.
There are several PHP libraries available to generate PDF. In this article, we are using 'mPDF' to generate a PDF. This PHP library is used to generate PDF from UTF-8 encoded HTML. The mPDF contains a number of enhancements over FPDF and HTML2FPDF. This library was written by Lan Back and released under the GNU GPL v2 License. This library provides lots of features to generate PDFs, like watermark, CSS styles, password protection, barcodes, page numbering, text-justification, hyphenation and much more. PHP 7.3 is supported since mPDF v7. 1.7. PHP 7.4 is supported since mPDF v8.
These are the steps to generate a PDF from HTML dynamically-
Install mPDF with Composer
First, we need mPDF library to generate a PDF file. You can either download this from Github or install it using Composer. Let's know how to install the mPDF library using composer.
If your system does not have installed composer, then first download the latest composer version from its official website -
https://getcomposer.org/download/You can check a successful installation using the following command on cmd-
c:\>composer
The above command returns output like this-
Now, go to your project directory on the command prompt and run the following command to install mPDF library.
E:\wamp\www\mpdfproj> composer require mpdf/mpdf
After this, you have noticed that Composer has downloaded all libraries under the 'vendor' directory of your project root.
Now, let's create a main PHP file 'index.php', that we will call in the browser. At the top of this page, we include the mPDF library file.
require_once __DIR__ . '/vendor/autoload.php';
$mpdf = new \Mpdf\Mpdf();
After this, write the MySQL database connection code, make sure to replace 'hostname', 'username', 'password' and 'database' with your database credentials and name.
// Database Connection
$conn = new mysqli('hostname', 'username', 'password', 'database');
//Check for connection error
if($conn->connect_error){
die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error);
}
Next, take a PHP variable and assign the HTML content within it. The WriteHTML() method writes the HTML content to a PDF file.
$mpdf->WriteHTML($pdfcontent);
With the help of SetDisplayMode() function, we can define the way the document is to be displayed by the viewer. Like, we can set 'fullpage', 'fullwidth', 'real', 'default', 'none' or specify the magnification(zoom) level of the display.
$mpdf->SetDisplayMode('fullpage');
We can set the watermark on PDF using SetWatermarkText() function and show it on the PDF using showWatermarkText() function.
$mpdf->SetWatermarkText('etutorialspoint');
$mpdf->showWatermarkText = true;
$mpdf->watermarkTextAlpha = 0.1;
Complete Code: Generate a PDF file using mPDF
Here, we have merged all the codes that were explained in detail above to generate PDF dynamically from HTML using the PHP mPDF library. You can replace the HTML content and PHP variables assigned in '$pdfcontent' with whatever you want to print.
index.php<?php
// Include mpdf library file
require_once __DIR__ . '/vendor/autoload.php';
$mpdf = new \Mpdf\Mpdf();
// Database Connection
$conn = new mysqli('hostname', 'username', 'password', 'database');
//Check for connection error
if($conn->connect_error){
die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error);
}
// Select data from MySQL database
$select = "SELECT * FROM `empdata`";
$result = $conn->query($select);
$data = array();
while($row = $result->fetch_object()){
$data .= '<tr>'
.'<td>'.$row->name.'</td>'
.'<td>'.$row->address.'</td>'
.'<td>'.$row->phone.'</td></tr>';
}
// Take PDF contents in a variable
$pdfcontent = '<h1>Welcome to etutorialspoint.com</h1>
<h2>Employee Details</h2>
<table autosize="1">
<tr>
<td style="width: 33%"><strong>NAME</strong></td>
<td style="width: 36%"><strong>ADDRESS</strong></td>
<td style="width: 30%"><strong>PHONE</strong></td>
</tr>
'.$data.'
</table>';
$mpdf->WriteHTML($pdfcontent);
$mpdf->SetDisplayMode('fullpage');
$mpdf->list_indent_first_level = 0;
//call watermark content and image
$mpdf->SetWatermarkText('etutorialspoint');
$mpdf->showWatermarkText = true;
$mpdf->watermarkTextAlpha = 0.1;
//output in browser
$mpdf->Output();
?>
We will get a generated PDF in the output, as shown in the below screenshot.
Related Articles
PHP sanitize input for MySQLPHP random quote generator
PHP String Contains
PHP calculate percentage of total
PHP Fix: invalid argument supplied for foreach
Locking files with flock()
How to display PDF file in PHP from database
How to read CSV file in PHP and store in MySQL
Create And Download Word Document in PHP
PHP SplFileObject Standard Library
Simple File Upload Script in PHP
PHP code to send email using SMTP
Simple pagination in PHP
Simple PHP File Cache
PHP Connection and File Handling on FTP Server
Sending form data to an email using PHP
Preventing Cross Site Request Forgeries(CSRF) in PHP
PHP7.3 New Features, Functions and Deprecated Functions
Create pie chart using google api