Convert HTML To PDF In PHP (Simple Examples)

Welcome to a quick tutorial on how to convert HTML to PDF in PHP. Need to generate a PDF report or document from HTML? Unfortunately, PHP does not support the PDF file format natively.

In order to convert HTML to PDF in PHP, we have to download and use a third-party library. MPDF is a good choice, and the easiest way is to get it via Composercomposer require mpdf/mpdf. Thereafter, a short code snippet to create PDF file from HTML:

  • require "/vendor/autoload.php";
  • $mpdf = new \Mpdf\Mpdf();
  • $mpdf->WriteHTML("<p>HTML</p>");
  • $mpdf->Output("FILE.PDF");

That covers the basics, but let’s walk through detailed examples in this guide – Read on!

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

 

CONVERT HTML TO PDF WITH PHP

All right, let us now get into examples of how to convert HTML to PDF in PHP.

 

TUTORIAL VIDEO

 

DOWNLOAD MDPF

  • The easiest way to get MDPF is through a package manager called Composer. Quite a hassle to download and install, but a one-time effort nonetheless.
  • Once when you have Composer installed, navigate to your project folder in the command line cd HTTP/FOLDER/.
  • Run composer require mpdf/mpdf, Composer will automatically download the latest version into the vendor/ folder.

Take note, 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 check out the MPDF official documentation (it’s massive) on the supported HTML and CSS.

 

 

CONVERT FROM HTML STRING/FILE TO PDF

1-html-pdf.php
<?php
// (A) LOAD MPDF
require "vendor/autoload.php";
$mpdf = new \Mpdf\Mpdf();
// $mpdf = new \Mpdf\Mpdf(["orientation" => "L"]); // if you want landscape orientation
 
// (B) OPTIONAL META DATA + PASSWORD PROTECTION
$mpdf->SetTitle("Document Title");
$mpdf->SetAuthor("Jon Doe");
$mpdf->SetCreator("Code Boxx");
$mpdf->SetSubject("Demo");
$mpdf->SetKeywords("Demo", "Testing");
// $mpdf->SetProtection([], "user", "password");
 
// (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>";
// $html = file_get_contents("PAGE.HTML"); // or read from file
 
// (D) WRITE HTML TO PDF
$mpdf->WriteHTML($html);
 
// (E) OUTPUT
$mpdf->Output(); // directly show in browser
// $mpdf->Output("demo.pdf", "D"); // force download
// $mpdf->Output("demo.pdf"); // save to file on server

This conversion script should be pretty straightforward. Not going to explain line-by-line, but a quick summary:

  1. Include the MPDF library, and create an MPDF object.
  2. Optional. Set the PDF metadata and password-protect it if required.
  3. Write an HTML string or read from an HTML file.
  4. Finally, just use the MPDF object to convert the HTML string to PDF.
  5. Directly show the PDF file in the browser, force a download, or save it on the server.

 

 

CONVERT FROM URL TO PDF

2b-scrape.php
<?php
// (A) LOAD MPDF
require "vendor/autoload.php";
$mpdf = new \Mpdf\Mpdf();
 
// (B) CURL FETCH HTML FROM WEBPAGE
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost/2a-dummy.html");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$html = curl_exec($ch);
curl_close($ch);
 
// (C) OUTPUT TO PDF
$mpdf->WriteHTML($html);
$mpdf->Output();

If you want to convert a webpage, we can use CURL to fetch the webpage HTML and feed it into MPDF. But a reminder once again, MPDF may not be able to fully replicate the webpage.

 

ALTERNATIVE – HEADLESS MODE CHROME

3-chrome.php
<?php
// (A) CHANGE TO YOUR OWN!
$chrome = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe";
$output = "D:\\http\\demo.pdf";
$url = "https://en.wikipedia.org/wiki/Koto_(instrument)";
$cmd = <<<EOF
"$chrome" --headless --disable-gpu --print-to-pdf="$output" $url
EOF;
 
// (B) RUN COMMAND
$result = shell_exec($cmd);
echo $result;

If you can install Chrome (or any Chromium-based browser) on the server, a possible alternative is to run the web browser in the command line. The above command will:

  • Open Chrome in “Headless mode” (no window).
  • Access Wikipedia.
  • Print/save the page to a PDF file.

 

 

EXTRAS

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

 

MANUAL PRINT TO PDF

It’s not a secret, most modern browsers can directly print to PDF files. If you don’t want to write any code, this is the possible “manual solution”.

 

LINKS & REFERENCES

 

THE END

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 to this guide, please feel free to comment below. Good luck and happy coding!

2 thoughts on “Convert HTML To PDF In PHP (Simple Examples)”

  1. From the ‘Comments’, it is obvious your code works. But I downloaded your package and installed as per directions – it did not work. Dreamweaver CS6 is telling me “There is a syntax error on line 14 ” [3-ajax-search.html] . This the code portion.
    I was hoping to gain an understanding of how this process (php “LIKE”) operates. BUT not know enough to determine if it is something I have done wrong or if in fact the code is defective, I am stuck.
    Thanks
    Warren

    1. There is nothing wrong with the code. Don’t use Dreamweaver – It is outdated and does not support PHP 8 properly; Adobe is pretty much pulling out of web development.

Leave a Comment

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