Create PDF using mPDF in core PHP

mPDF is a library built in PHP for creating PDFs easily. As a PHP developer it is not something new to create PDFs. If you are here that means you are about to create PDF in PHP or you might have already created and looking for another library. In this article I will guide you how to create PDF using mPDF in core PHP.

To install this library in my project I am going to use Composer. If you don’t have composer installed on your system, follow this articles based on your system OS Ubuntu , Windows to install composer. Even mPDF does not recommend using this library without composer.

Without any further ado lets begin, Open terminal in your project directory and type the following command to install mPDF.

composer require mpdf/mpdf

Generate PDF

Once installation completed, you’ll see a vendor folder in your directory. Yes, that’s where the mPDF library is installed. There is also one more important file in the vendor you should know that is autoload.php. Why it is important because this file instantiate all libraries of the vendor folder so that you can use directly use the instance of mPDF or any library.

To instantiate mPDF you gonna need to add the first autoload.php in your file. Add the following line in your file where you will create PDF

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

This line should be on top of file.

Next step is to add the following code to the same file.

$htmlData = '<h1>Hello world!</h1>';
$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML($htmlData);
$mpdf->Output();

Note: If you are running on this project on Linux/Ubuntu, you might get a fatal error about permission like

 Fatal errorUncaught Mpdf\MpdfException: Temporary files directory “/opt/lampp/htdocs/codekill/vendor/mpdf/mpdf/src/Config/../../tmp” is not writable 

The solution is to just give the tmp folder write permission. Open the terminal in your project directory and type the following command.

sudo chmod 777 ./vendor/mpdf/mpdf/tmp/

Save PDF in folder

Until now we were creating and displaying the PDF in browser but sometime we have save this PDF file. To do that we need to change something in our previous code. Lets see what is the change and how does it work.

require_once __DIR__ . '/vendor/autoload.php';
$htmlData = '<h1>Hello world!</h1>';
$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML($htmlData);
$nameWithLocation = 'pdfFiles/filename.pdf'; //location where pdf will be saved with filename.pdf
$mpdf->Output($nameWithLocation);

The above code is self explanatory I guess, but still let me tell you, Now we are passing one parameter to $mpdf->Output($nameWithLocation). The parameter is nothing but the filename with folder name.

So that was all about the Create PDF using mPDF in core PHP. Hope this article helped you.In case of some doubt feel free to leave comment in below comment box.