PHP Convert HTML To PDF Using Mpdf Tutorial

By : phpicoder Created : March 4, 2021

Hi Guys, In this tutorial,i will shows how you can Convert HTML To PDF Using Mpdf library in php project, In this example i will show you how to use Convert HTML To PDF Using Mpdf library, In this tutorial you will learn how to easily generate PDF file on html file in your PHP applications., So follow my esy step Convert HTML To PDF tutorial.

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>Convert HTML To PDF Using Mpdf</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 - phpicoder</td>
	</tr>
        <tr>
	    <th>name</td>
	    <th>email</td>
	</tr>
	<tr>
	    <td>vikram</td>
	    <td>phpicoder@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.....