Php html to jpg script

html to image php script

App or game developer always need a tool / script that convert your static or dynamic html to image . As in case if you are php developer and want to know how to convert html to jpeg image in simple way then this article is for you.

In this post you will learn how to convert html to image. I have to discover this trick when I was making a facebook game and script need to post dynamic game score on user’s wall. My client provided me the html of result webpage but all we need is just to convert this dynamic result html to jpeg.

This is the simple way and you have to compromise with its image quality.This html to image php script does not require any external api or GD Library, Most of the server does not have GD library extension.

Why we need to convert html to image.

As i told if we have some html and it is changeable html or php page and we want to capture it as snapshot.

  • Facebook application development
  • For Tutorial website
  • For development purposes

What we don’t need to convert html to image with php

We will create html to snapshot without using any php gd library or any third party API. Now we will convert html to pdf with php

  • Without using third party API.
  • Without using php GD Library.
  • Without any shell script or window command.

What we need to convert html to image

How it Works

html to image php script

The idea behind conversion is simple. We will first convert html of any webpage to pdf using HTML2PDF utility and then we will convert pdf doc to an image.

convert html to image

Load html from file or url

This is example how to convert webpage into image with php script

Источник

4 Ways To Convert HTML To Image In PHP

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.

  • 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.
Читайте также:  IE Only Style Sheet

It’s kind of roundabout, but possible – Read on for the examples!

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.

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.

PHP HTML TO IMAGE

All right, let us now get into the possible ways of converting HTML into an image in PHP.

TUTORIAL VIDEO

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 = 
  • 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

 

TEST PAGE

Hello world!

  • (B1) We are using HTML2Canvas to capture a screenshot
  • (B2) Upload the screenshot to the server.

P.S. You can create a bat (Windows) or sh (Linux/Mac) to open a web browser. For example, chrome.exe --app=http://localhost/2a-page.php . Then, set it to run on schedule, or use PHP exec() to call it on demand.

2B) PHP

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

TEST PAGE 

Hello world!

HTML; // (A2) CSS $css = 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 = TEST PAGE 

Hello world!

HTML; // (B) HTML TO PDF require "vendor/autoload.php"; $mpdf = new \Mpdf\Mpdf(); $mpdf->WriteHTML($html); $mpdf->Output("demoD.pdf"); // (C) PDF TO IMAGE $image = new Imagick("demoD.pdf"); $image->setImageFormat("jpg"); $image->writeImage("demoD.jpg");
  • 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 image”.

EXTRAS

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 image – Works as well, but inefficient.

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!

Leave a Comment Cancel Reply

Breakthrough Javascript

Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript - Check out Breakthrough Javascript!

Socials

About Me

W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.

Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Multiple html pages convert to jpg with Html2Canvas and PHP. Html2Jpg

erayakartuna/html-to-jpeg-php

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Html to Jpeg with Php and html2canvas

Multiple html pages convert to jpeg with html2canvas and PHP. You can easily convert your html or php pages to jpeg with this library.

You need to create 2 php files.I named "index.php" and "download.php". You have to define your html pages into the "index.php" and after that you should call download function on "download.php" .You can easily change file names with library config.

Define to html2canvas and jquery scripts.

script src pl-s">https://code.jquery.com/jquery-2.x-git.min.js">script> script src pl-s">http://eray.info/demo/html-to-jpeg-php/js/html2canvas.js">script>

Add these codes into to body

include('HtmlToJpeg.php'); $html2Jpeg = new HtmlToJpeg(); //Pages $html2Jpeg->renderHtml("

Page 1

");//You can write html $html2Jpeg->renderView("test.html");//you can add html or php files as a page $html2Jpeg->renderHtml("

Page 3

");//You can write html echo $html2Jpeg->output();
include "HtmlToJpeg.php"; $html2jpeg = new HtmlToJpeg(); $html2jpeg->download();//starting download
$html2Jpeg->renderView("test.php");

About

Multiple html pages convert to jpg with Html2Canvas and PHP. Html2Jpg

Источник

PHP: HTML/CSS to Image

For more details on how this works, see Creating an image.

Example API response:

Image generated with PHP. Convert HTML to an image using PHP.

Authentication with PHP

Your username is your User ID and your password is your API Key. Both of these are available from the dashboard. The PHP code sample demonstrates how to authenticate your request.

You can signup for a free API key to get started.

PHP example code

This PHP code example sends an HTTP POST to the https://hcti.io/v1/image API. Converting your HTML/CSS to an image with PHP.

 Generated from PHP ✅
EOD; $css = EOD; $google_fonts = "Roboto"; $data = array('html'=>$html, 'css'=>$css, 'google_fonts'=>$google_fonts); $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($data)); curl_setopt($ch, CURLOPT_POST, 1); // Retrieve your user_id and api_key from https://htmlcsstoimage.com/dashboard curl_setopt($ch, CURLOPT_USERPWD, "user_id" . ":" . "api_key"); $headers = array(); $headers[] = "Content-Type: application/x-www-form-urlencoded"; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $result = curl_exec($ch); if (curl_errno($ch)) < echo 'Error:' . curl_error($ch); >curl_close ($ch); $res = json_decode($result,true); echo $res['url']; // https://hcti.io/v1/image/202dc04d-5efc-482e-8f92-bb51612c84cf ?>

PHP example with Guzzle library

Using an HTTP library such as Guzzle can simplify your code even further. Here’s an example of how to use the HTML/CSS to Image API with Guzzle.

Installation instructions for Guzzle are here.

Pong ✅
"; $css = ".ping < padding: 20px; font-family: 'sans-serif'; >"; $client = new GuzzleHttpClient(); // Retrieve your user_id and api_key from https://htmlcsstoimage.com/dashboard $res = $client->request('POST', 'https://hcti.io/v1/image', [ 'auth' => ['user_id', 'api_key'], 'form_params' => ['html' => $html, 'css' => $css] ]); echo $res->getBody(); // ?>

The code turns out to be a bit more readable and less complex when using Guzzle. A great option if you’re open to adding the library to your project.

Debugging Error:SSL certificate problem: unable to get local issuer certificate

When running this script on a Windows machine, it’s possible you’ll get an SSL error. The fix for this is here.

Need help?

We’re always looking to improve this documentation. Please send us an email: support@htmlcsstoimage.com. We respond fast.

Built with extensive integration tests and serious care for developer happiness.
© 2018-2023 Code Happy, LLC.

Page last modified: Jul 23 2023 at 07:05 PM .

Источник

Оцените статью