Convert HTML To PDF In PHP Using Mpdf

By : PHPErrorCode July 18, 2017 1283 Views php

In this tutorial you will learn how to easily generate PDF file on html file in your PHP applications.

I need to generate a pdf file in PHP. There are several PHP libraries which can be used to generate PDF. But after a little research I found an interesting library, mPDF which can convert HTML code to PDF keeping the structure.

mPDF is a PHP class which generates PDF files from UTF-8 encoded HTML. It is based on FPDF and HTML2FPDF with a number of enhancements.

mPDF is a smart library which consider the CSS attached to the HTML. Not only CSS, mPDF takes care of almost all the HTML tags like, form tags, tables, images, lists etc...

Step 1 download mPDF library on this Link... Download

Extract the download mPDF60.zip file into your folder

Step 2 Create A New File test.php And Place The Code Below Into It.

<?php
ob_start();
error_reporting(0);

$pdfFileName = 'demo.pdf';
?>
<!DOCTYPE html>
<html>
<head>
    <title>html 2 PDF</title>
    <style type="text/css">
        table,td,th{
	    text-align: center;
	    border: 1px solid
	}
    </style>
</head>
<body>
    <table>
        <tr>
	    <td colspan="2">html to pdf demo</td>
	</tr>
        <tr>
	    <th>name</td>
	    <th>email</td>
	</tr>
	<tr>
	    <td>vikram</td>
	    <td>vikraminphp@gmail.com</td>
        </tr>
    </table>
</body>
</html>
<?php
$HTMLoutput = ob_get_contents();
ob_end_clean();

include("mpdf60/mpdf.php");
$mpdf = new mPDF();
$mpdf->WriteHTML($HTMLoutput);
$mpdf->Output($pdfFileName,'F');
?>

In this tutorial, If you need any kind of assistance regarding generating PDF using mPDF about the code or would like to contribute to the discussion, please leave a comment below.

Thanks.....