How to generate PDF file using PHP and MPDF library

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.

<?php

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

$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML('<h1>Welcome to atcodex.com</h1>');
$mpdf->Output();
?>

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.

<?php 

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

$url="http://atcodex.in";
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);
    curl_close($ch);
}
$mpdf = new \Mpdf\Mpdf();
$mpdf->SetDisplayMode('fullwidth');

$mpdf->CSSselectMedia='mpdf';
$mpdf->setBasePath($url);
$mpdf->WriteHTML($html);

$mpdf->Output('download.pdf','D');

?>

Conclusion

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 https://mpdf.github.io/installation-setup/installation-v7-x.html.

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 .

Spread the love

One Comment on “How to generate PDF file using PHP and MPDF library”

  1. Heya i am for the first time here. I found this board and
    I in finding It really useful & it helped me
    out much. I am hoping to offer something back and aid others such as you aided me.

Leave a Reply

Your email address will not be published. Required fields are marked *