How to generate PDF file using PHP and MPDF library

There are several situations when we need to save the data in PDF in the application. For example, generate an invoice or generate a book in PDF files. In this post, we will learn How to generate PDF files using PHP and MPDF library.

Using PHP we can generate PDF file easily. There are many PDF libraries we can use to generate PDF. But in this tutorial we will show you how you can generate PDF file using PHP and mpdf library.

The mpdf is one of the best libraries in PHP to convert text into pdf. This help to generate PDF file from UTF-8 encoded HTML. let’s start How to generate PDF files using PHP and MPDF library.

First install the mpdf library using composer with the following command.

$ composer require mpdf/mpdf

Basic use of mpdf

After installing mpdf library using the composer. Print anything with the following code, you need to use the below code and write the data in $mpdf->WriteHTML() method, whatever you will write inside this function that, PDF will get generated for that.


require_once __DIR__ . '/vendor/autoload.php';

$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML('<h1>Welcome to</h1>');

Convert PHP webpage into PDF file

In this example, you can print the content from the URL. You only need to put the URL in $url variable and you are ready to go. $mpdf->Output('download.pdf','D') method will force pdf to download with download.pdf name.


require_once __DIR__ . '/vendor/autoload.php';

if (ini_get('allow_url_fopen')) {
    $html = file_get_contents($url);

} else {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt ( $ch , CURLOPT_RETURNTRANSFER , 1 );
    $html = curl_exec($ch);
$mpdf = new \Mpdf\Mpdf();





MPDF library is very easy to use, We personally loved this plugin, very easy to use.

In the above code, we have tried to explain How to generate PDF files using PHP and MPDF library . If you want to explore this plugin more for other features and enhancement, you can visit

You can also check the article about How to Convert PDF to JPEG Image using PHP which is very easy to use and understandable.

If you have any query related to this article do please comment below and let me know .