How to Convert HTML to PDF in PHP

INTRODUCTION

HTML TO PDF CONVERSION MAGIC

Welcome to a quick tutorial on how to convert HTML to PDF in PHP. Need to create a PDF file using HTML? Unfortunately, PHP does not support the PDF file format natively. So in order to convert HTML to PDF in PHP, we will have to download and use a third-party library such as MPDF:

  • Download and install Composer.
  • Open the command line, navigate to your project folder, and run “composer require mpdf/mpdf”.
  • Lastly, create the PHP script.
    • require ‘/vendor/autoload.php’;
    • $mpdf = new \Mpdf\Mpdf();
    • $mpdf->WriteHTML(“<p>HTML</p>”);
    • $mpdf->Output(“FILE.PDF”);

That’s all. But if you need more details, read on to find out!

ⓘ I have included a zip file with all the example code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

 

PREAMBLE

DOWNLOAD & NOTES

First, here is the download link to the source code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

  • Download and unzip into a folder.
  • The zip file does not contain a copy of MPDF. Please download and install Composer first. Then fire up the command prompt, navigate to the project folder, and run composer require mpdf/mpdf to fetch the latest version automatically.

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

STEP 1

DOWNLOAD MPDF

To do the HTML to PDF magic, we will be using a free open-source package called MPDF. But there is one small problem – I tried to download it directly from Github, and the development version doesn’t seem to work “out of the box”.

 

COMPOSER INSTALL

The best way is to get MDPF is through an application called Composer. Quite a hassle, but a one-time effort nonetheless. Once when you have Composer installed, just navigate to your project folder in the command line (or terminal), run composer require mpdf/mpdf, and watch the magic happen:

1-install.txt
D:\http\test>composer require mpdf/mpdf
Using version ^8.0 for mpdf/mpdf
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 5 installs, 0 updates, 0 removals
- Installing myclabs/deep-copy (1.10.1): Downloading (100%)
- Installing paragonie/random_compat (v9.99.99): Downloading (100%)
- Installing setasign/fpdi (v2.3.4): Downloading (100%)
- Installing psr/log (1.1.3): Loading from cache
- Installing mpdf/mpdf (v8.0.7): Downloading (100%)
paragonie/random_compat suggests installing ext-libsodium (Provides a modern crypto API that can be used to generate random bytes.)
setasign/fpdi suggests installing setasign/fpdf (FPDI will extend this class but as it is also possible to use TCPDF or tFPDF as an alternative. There's no fixed dependency configured.)
Writing lock file
Generating autoload files
3 packages you are using are looking for funding.
Use the `composer fund` command to find out more!

 

 

STEP 2

PHP CONVERSION SCRIPT

That’s it, now that you have successfully downloaded the MPDF library, all that is left is to use it in your PHP script.

 

FROM HTML TO PDF

2-html-pdf.php
<?php
// (A) INIT MPDF
require_once __DIR__ . '/vendor/autoload.php';
$mpdf = new \Mpdf\Mpdf();
// IF YOU WANT LANDSCAPE ORIENTATION
// $mpdf = new \Mpdf\Mpdf(['orientation' => 'L']);
 
// (B) OPTIONAL META DATA
$mpdf->SetTitle('Document Title');
$mpdf->SetAuthor('John Doe');
$mpdf->SetCreator('Creator');
$mpdf->SetSubject('Demo');
$mpdf->SetKeywords('Keyword 1, Keyword 2');
// SET THE PASSWORD & PERMISSIONS IF YOU WANT
// https://mpdf.github.io/reference/mpdf-functions/setprotection.html
$mpdf->SetProtection(array(), "userpass", "ownerpass");
 
// (C) THE HTML
$html = "
<html>
  <head>
    <style>
    #test{ background:#ff0000; }
    #atable{ border:1px solid #00ff00; }
    </style>
  </head>
  <body>
    <h1>Title</h1>
    <p id='test'>Hello world!</p>
    <table id='atable'>
      <tr><td>A Table</td></tr>
    </table>
  </body>
</html>";
// OPTIONALLY, JUST GRAB FROM AN ENTIRE HTML FILE
// $html = file_get_contents('file.html');
 
// (D) WRITE HTML
$mpdf->WriteHTML($html);
 
// (E) OUTPUT, SHOW IN BROWSER BY DEFAULT
$mpdf->Output();
// OR FORCE DOWNLOAD
// $mpdf->Output('file.pdf');

This conversion script should be pretty straightforward.

  • Include the MPDF library, create an MPDF object.
  • Set the PDF metadata, and maybe a password if you want to protect it.
  • Write some HTML code or read from an HTML file.
  • Finally, just use the MPDF object to convert the HTML to PDF.

 

 

EXTRA

USEFUL BITS & LINKS

That’s all for the very simple script, and here are a few small extras that may be useful to you.

 

ALTERNATIVE – PRINT TO PDF

If you do not want to write any code, here is a possible alternative “manual” solution. That is to access the webpage that you want to convert, then use the browser’s print function, and select “save as PDF”.

 

MPDF DOCUMENTATION & LIMITATIONS

Of course, MPDF is not perfect. It is not able to replicate all HTML elements and CSS styles perfectly, but it should work well enough for your basic needs. Please do check out their documentation (it’s massive) on the supported HTML and CSS.

 

RELATED LINKS

 

 

CHEAT SHEET

How To Convert HTML To PDF In PHP (click to enlarge)

 

CLOSING

WHAT NEXT?

Thank you for reading, and we have come to the end of this very short guide. I hope it has solved your PDF woes, and if you have stuff you want to add on to this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

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