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.
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 Composer – composer require mpdf/mpdf
. Thereafter, a short code snippet to create a 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
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 converting HTML to PDF in PHP.
TUTORIAL VIDEO
DOWNLOAD MDPF
- First, download and install a package manager called Composer.
- 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 thevendor/
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 on the supported HTML and CSS.
METHOD 1) CONVERT HTML STRING/FILE TO PDF
<?php
// (A) LOAD MPDF
require "vendor/autoload.php";
$mpdf = new \Mpdf\Mpdf();
/*
$mpdf = new \Mpdf\Mpdf([
"mode" => "utf-8",
"orientation" => "L",
"format" => "A4-L"
]);
*/
// (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"); // load from html file
// (D) WRITE HTML TO PDF
$mpdf->WriteHTML($html);
// (E) OUTPUT
// $mpdf->Output(); // directly show in browser
// $mpdf->Output("demoA.pdf", "D"); // force download
$mpdf->Output("demoA.pdf"); // save to file on server
This conversion script should be pretty straightforward. Not going to explain line-by-line, but a quick summary:
- Load the MPDF library, and create an MPDF object.
- Optional. Set the PDF metadata and password-protect if required.
- Write an HTML string or read from an HTML file.
- Finally, just use MPDF to convert the HTML string to PDF.
- Directly show the PDF file in the browser, force a download, or save it on the server.
METHOD 2) CONVERT FROM URL TO PDF
<?php
// (A) 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);
// (B) OUTPUT TO PDF
require "vendor/autoload.php";
$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML($html);
$mpdf->Output("demoB.pdf");
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.
METHOD 3) HEADLESS MODE CHROME
<?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”.
INFOGRAPHIC CHEATSHEET
LINKS & REFERENCES
- Convert HTML to PDF With Javascript – Code Boxx
- Simple PHP Web Scraper – Code Boxx
- Check out my other guides if you need to generate in other document formats – HTML to DOCX | Excel Spreadsheet
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!
I know you have to pay the bills but why do the ads have to be so bad that they cause 2020 my MacBook Pro fans to scream and everything to lag?
It is super impossible to get through and even see the ads let alone read the article without an adblocker on.
If the ads are per click, you would get more clicks if you didn’t chase people way from your site by crashing their computers. If the ads are per view… well that sux… but I had to turn on adblocking just to get to this form here.
https://code-boxx.com/faq/#ads
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
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.