How to generate PDF file using PHP and MPDF library

There are several situations when a single PDF (Portable Document Format) is the most perfect solution for any digital document. For example, generate an invoice or generate an ebook in PDF files. Using PHP you can create dynamic PDF files easily. There are several PDF libraries you can use with PHP to generate PDF. For creating dynamic PDF you can fetch data from a database or from any web form. So friends, in this tutorial, I will show you how easily you can generate PDF file using PHP and MPDF. Also, using MPDF you can convert HTML to PDF files. In this tutorial, the MPDF version is 7.1.0.

How to generate PDF file using PHP and MPDF

Generate PDF file using PHP and MPDF Library

Before proceeding to the actual code implementation one important thing you need to know that you have to download the MPDF library using composer to your project folder. If you don’t have composer installed in your system then download it from the following link — Download Composer and install in your system. Also, you can download MPDF 7.1.0 from my software repository if you do not want to install the composer . After that open command prompt and set the path to your project folder. For more information about MPDF please visit the official website.

Note: One thing you have to keep in your mind that if you download the MPDF 7.x package from GitHub then you will can’t find the vendor folder within it. Only installing via the composer you will get the full package or download it from my software repository.

Command prompt

Now run the below command in the command prompt —

composer require mpdf/mpdf

Next, you will see that a folder named vendor is created in your project folder.

Now let’s start the coding. Here in this tutorial, I created a web form where users will give their information and it will generate the dynamic PDF based containing that information.

HTML Form – Generate PDF file using PHP and MPDF

index.php

<form action="generate-pdf.php" method="post">
          <div class="form-row">
            <div class="form-group col-md-6">
              <label for="name">Name</label>
              <input type="text" class="form-control" id="name" name="name">
            </div>
            <div class="form-group col-md-6">
              <label for="email">Email</label>
              <input type="text" class="form-control" id="email" name="email">
            </div>
          </div>
          <div class="form-group">
            <label for="address">Address</label>
            <input type="text" class="form-control" id="address" name="address">
          </div>
          <div class="form-group">
            <label for="address">Profile Picture Link</label>
            <input type="text" class="form-control" id="picture_link" name="picture_link">
            <label>Example, http://www.mitrajit.com/wp-content/uploads/2019/02/mitrajit.jpg</label>
          </div>
          <button type="submit" class="btn btn-primary">Submit & Generate PDF</button>
        </form>

In the above code apart from the name, email, and address, there is another field that is for paster your profile picture or any other image link. That image will be displayed in the PDF.

PHP Code – Generate PDF file using PHP and MPDF

generate-pdf.php

<?php
if(!isset($_POST)) {
  header('location:index.php');
  exit();
}

$name         = $_POST['name'];
$email        = $_POST['email'];
$address      = $_POST['address'];
$picture_link = $_POST['picture_link'];

$html = '
<style>
    @page {
      size: auto;
      sheet-size: A4;
      header: myHTMLHeader1;
      footer: myHTMLFooter1;
    }
</style>

<htmlpageheader name="myHTMLHeader1">
<table width="100%" style="border-bottom: 1px solid #000000; vertical-align: bottom; font-family: serif; font-size: 15pt; color: #000088;"><tr>
<td width="8%"><img src="images/webtechnology.png" height="60" /></td>
<td width="59%"><div align="left">Mitrajit\'s Tech Blog</div><div align="left" style="font-size:14.5px;">Generate PDF</div></td>
<td width="33%" style="text-align: right;">&nbsp;</td>
</tr></table>
<table width="100%" style="vertical-align: bottom; font-family: serif; font-size: 11pt;">
  <tr>
    <th align="right">Dated : '.date("d-m-Y H:i:s").'</th>
  </tr>
</table>
</htmlpageheader>
<htmlpagefooter name="myHTMLFooter1">
    <table width="100%" style="border-top: 1px solid #000000;font-size:11px;">
        <tr>
            <th align="left">&copy; Mitrajit\'s Tech Blog</th>
            <td align="right">Printed on : {DATE d-m-Y} | Page {PAGENO} of {nb}</td>
        </tr>
    </table>
</htmlpagefooter>


<table width="100%" style="vertical-align: bottom; font-family: serif; font-size: 11pt;">
  <tr>
    <th rowspan="3">'.($picture_link != "" ? '<img src="'.$picture_link.'" style="padding:3px; border:2px solid #ccc; border-radious:5px; margin-right:5px;">' : '').'</th>
    <th align="left">Name : '.$name.'</th>
  </tr>
  <tr><th align="left">Email : '.$email.'</th></tr>
  <tr><th align="left">Address : '.$address.'</th></tr>
</table>
<pagebreak/>';

The code in details —

@page — It sets the page size that is a4header and footer attributes set the header and footer in each and every page and for that take the contents from the <htmlpageheader name=”myHTMLHeader1″> and <htmlpagefooter name=”myHTMLFooter1″>.

{DATE d-m-Y} — Prints the  current date.

{PAGENO} — Prints the current page number.

{nb} — Prints the total number of pages.

MPDF Code – Generate PDF file using PHP and MPDF

try {
  $filename = date("d-m-Y H:i:s");
  require_once("vendor/autoload.php");

  $mpdf = new \Mpdf\Mpdf([
  	'mode' => 'c',
  	'margin_top' => 35,
  	'margin_bottom' => 17,
  	'margin_header' => 10,
  	'margin_footer' => 10,
  ]);

  $mpdf->showImageErrors = true;
  $mpdf->mirrorMargins = 1;
  $mpdf->SetTitle('Generate PDF file using PHP and MPDF | Mitrajit\'s Tech Blog');
  $mpdf->WriteHTML($html);
  $mpdf->Output($filename, 'I');
} catch(\Mpdf\MpdfException $e) {
  echo $e->getMessage();
}

Include the autoload.php file before creating the object of the mpdf class. Set margins top, bottom, left, and right for the contents in between header and footer.

$mpdf->showImageErrors=true — It displays any error regarding images.

$mpdf->mirrorMargins=1 — If it is set to 1 or true the document will mirror the left and right margin values on ODD and EVEN pages.

$mpdf->SetTitle() — Sets title for your PDF document and for page title also.

$mpdf->WriteHTML($html) — Rrites the html content in the PDF file.

$mpdf->Output($filename, ‘I’) — Generates and force to download the PDF file to the user system.

That’s all friends, Hope you enjoyed the tutorial. If you face any problem feel free to inform me in the comment section below. Please like and share this tutorial on how to generate PDF file using PHP and MPDF library with others. Kindly subscribe Mitrajit’s Tech Blog to keep yourself updated with the upcoming tutorials.

1 thought on “How to generate PDF file using PHP and MPDF library

Leave a Reply

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