Welcome to a tutorial on how to convert HTML to an image in PHP. So you have a PHP project that needs to convert HTML into an image? Bad news, there are no free “HTML to image” libraries at the time of writing.
There are 4 possible ways to convert HTML to an image in PHP:
- Use the browser headless mode to open a URL and capture a screenshot.
- Open the HTML in a browser, capture a screenshot, then send it to PHP for processing.
- Use an online conversion service.
- Convert HTML to PDF first, then save the PDF as an image.
It’s kind of roundabout, but possible – Read on for the examples!
TABLE OF CONTENTS
PHP HTML TO IMAGE
All right, let us now get into the possible ways of converting HTML into an image in PHP.
1) HEADLESS MODE SCREENSHOT
// (A) SETTINGS
$chrome = "C:\Program Files\Google\Chrome\Application\chrome.exe"; // path to chrome
$saveas = __DIR__ . DIRECTORY_SEPARATOR . "demoA.png"; // save screenshot
$size = "1080,1920"; // height, width
$url = "https://code-boxx.com"; // url to access
// (B) HEADLESS CHROME
$cmd = <<<CMD
"$chrome" --headless --screenshot="$saveas" --window-size=$size "$url"
CMD;
exec($cmd);
- This snippet simply runs
chrome --headless --screenshot="demoA.png" --window-size=1080,1920 "https://code-boxx.com"
in the command line. - “Headless mode” will open the browser but does not show it on the screen.
- That is, silently open
https://code-boxx.com
and take a screenshot.
For those who are lost – Create your own HTML file, for example, http://localhost/foo.html
. Use headless mode to access that HTML file and take a screenshot, that’s your “HTML to image” conversion.
P.S. Both Opera and Edge are also Chromium-based, capable of running in headless mode. Firefox can also run in headless mode. Not too sure about the half-eaten apple.
2) BROWSER SCREENSHOT
2A) HTML & JAVASCRIPT
<!-- (A) HTML CONTENT -->
<h1>TEST PAGE</h1>
<p>Hello world!</p>
<!-- (B) SCREENSHOT & UPLOAD -->
<script src="html2canvas.min.js"></script>
<script>
window.onload = () => html2canvas(document.body).then(canvas => {
// (B1) CANVAS TO FORM DATA
var data = new FormData();
data.append("img", canvas.toDataURL("image/png"));
// (B2) UPLOAD TO 1B-SAVE.PHP
fetch("2b-save.php", { method:"post", body:data })
.then(res => res.text())
.then(txt => console.log(txt));
});
</script>
This is an alternative to support browsers that don’t do headless mode. Look no further, this is just a “normal HTML page”. But take note:
- (B1) We are using HTML2Canvas to capture a screenshot
- (B2) Upload the screenshot to the server.
2B) PHP
<?php
$file = fopen("demoB.png", "w");
$data = explode(",", $_POST["img"]);
$data = base64_decode($data[1]);
fwrite($file, $data);
fclose($file);
echo "OK";
In this example, we simply save the uploaded screenshot to a PNG file. In your project, you can pretty much do whatever you want – Save into a database, save into a cloud drive, send via email, etc…
3) ONLINE HTML TO IMAGE SERVICE
<?php
// (A) CONTENT
// (A1) HTML
$html = <<<HTML
<h1>TEST PAGE</h1>
<p>Hello world!</p>
HTML;
// (A2) CSS
$css = <<<CSS
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
p { color: red; }
CSS;
// (B) USE API TO CREATE PNG
// (B1) CURL INIT
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://hcti.io/v1/image");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
"html" => $html,
"css" => $css
]));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, "user_id" . ":" . "api_key"); // CHANGE TO YOUR OWN!
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/x-www-form-urlencoded"]);
// (B2) CURL EXEC
$result = curl_exec($ch);
if (curl_errno($ch)) { echo curl_error($ch); }
curl_close($ch);
$result = json_decode($result, true);
// (C) FETCH & SAVE PNG
$fh = fopen("demoC.png", "w");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $result["url"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $fh);
curl_exec($ch);
curl_close($ch);
fclose($fh);
echo "OK";
Nobody has released a free PHP HTML to image library, but there are plenty of such conversion services online. A free one that I found is HCTI.
- (A & B) Create your HTML/CSS as usual.
- (B) Send the HTML/CSS to HCTI, create a PNG image.
- (C) Fetch the generated image, do whatever is required – We simply save it in this example.
P.S. Remember to sign up for a free account and change the user/password to your own in (B1).
4) HTML TO PDF, PDF TO IMAGE
// (A) HTML CONTENT
$html = <<<HTML
<h1>TEST PAGE</h1>
<p>Hello world!</p>
HTML;
// (B) HTML TO PDF
require "/vendor/autoload.php";
$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML($html);
$mpdf->Output("demoD.pdf");
// (C) PDF TO PNG
$image = new Imagick("demoD.pdf");
$image->setResolution(300, 300);
$image->setImageFormat("png");
$image->writeImage("demoD.png");
Finally, yet another roundabout method. For this method to work, you will need to install:
- MPDF – The easiest way is to use Composer
composer require mpdf/mpdf
. - ImageMagick – The installation is kind of confusing, and cannot be explained in a paragraph… You will need to do some research on your own.
But yep, this is pretty much “HTML to PDF”, then “PDF to PNG”.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a "paid scripts and courses" business, so every little bit of support helps.
Buy Me A Meal Code Boxx eBooks
EXAMPLE CODE DOWNLOAD
Click here for the 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.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
WHICH IS THE BEST METHOD?
- Browser Screenshot (headless or not) – I am personally leaning towards this method, simply because it’s the most accurate and free.
- Online Service – Works if you are running a command line PHP, but probably need to pay if you need to process many of such images.
- HTML to PDF to PNG – Works as well, but inefficient.
P.S. You can create a bat
(Windows) or sh
(Linux/Mac) to open a web browser. For example, chrome.exe --app=http://localhost/1a-page.html
. Then, set it to run on schedule, or use PHP exec()
to call it on demand.
LINKS & REFERENCES
- Convert HTML To PDF – Code Boxx
- Take Screenshot with Javascript – CodeBoxx
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!