Convert HTML to Image in jQuery / JavaScript [Div or Table to jpg/ png]

/ / 65 Comments

jQuery / JavaScript HTML to Image Converter: This article explains how to convert div to an image in jQuery and also in JavaScript. Yes, we are going to generate an image from our HTML page on the client-side. We can also convert a particular part of our Webpage (Asp.net C# Web project/ PHP). All we need HTML tag, and using the html2canvas javascript library we can create images .i.e converting the HTML table to Image PNG, JPG, or converting DIV, UL, LI tag into Jpg image format.

In short using, html2canvas will render HTML to Images which means now we can take the screenshot of Div or any HTML element of a web page.

Where is the use of converting HTML to an image/picture?

As we know HTML5 gives some excellent features, for example, we have a Canvas tag on our web page. Now on HTML 5 Canvas, we draw something or let's say we create a pie chart using jquery, after that, we want to save this as an Image that may be in png or jpg format.

We convert Canvas to Image on the client side and later save it on our server.

Another example, I have implemented in my Asp.net C# web project was where I had to add multiple images. Then drag/shuffle all the images inside a canvas to save them into one single image.

Later upload this image using jQuery Ajax, and give the print command to make Mug Sticker, Tshirt Sticker, and some dynamic background with hex color code.

The idea behind it is to let the user add his / her photos. Allow them to arrange or shuffle it. Later on, a button click allows the user to make an HTML canvas and save it as an image which will send for printing purposes.

Now let's head towards the coding part and see how we can convert HTML to Picture :)

Example: 


Video:

Step to render HTML to Image [PNG/JGP] using jQuery / JavaScript

  1. Download and import HTML2Canvas jquery files.
  2. Add HTML markup.
  3. JavaScript Code to convert HTML div to Image [png]
  4. jQuery Code: Button click convert HTML to Canvas.
  5. jQuery Code: Download HTML to IMAGE.

#1 Download and import HTML2Canvas files.

First, we need to download and import the latest jquery library on our web page. You can import your server-hosted jQuery file or use it from the Google-hosted site (recommended).

For converting HTML to Image, we need to import one more javascript library, and it is HTML2CANVAS download it and import it into the HTML head tag.

Now we are done with downloading, so our final head tag looks as shown below.

<script src="Scripts/jquer_latest_2.11_.min.js" type="text/javascript"></script>
<script src="Scripts/html2canvas.js" type="text/javascript"></script> 

Note: If you want to use only javascript, then no need to import the jQuery library. All you need to follow Step 2 and Step 3

#2 Add HTML markup (HTML element for which we create an image)

Let's make this article very simple, so now am adding some dummy HTML elements i.e. P tag, but you can add dynamic HTML using jQuery Ajax for which you want to generate images. Now we add a button tag that creates an Image of specific HTML and adds a download button.

On the download button click, the images get downloaded on your local drive. 1st we create a canvas of our HTML elements and then download it to the local drive as a picture, all this is done on the client-side using jquery.

HTML MARKUP:

<div id="html-content-holder" style="background-color: #F0F0F1; color: #00cc65; width: 500px;
        padding-left: 25px; padding-top: 10px;">
        <strong>Codepedia.info</strong><hr />
        <h2 style="color: #3e4b51;">
            Html to canvas, and canvas to proper image
        </h2>
        <p style="color: #3e4b51;">
            <b>Codepedia.info</b> is a programming blog. Tutorials focused on Programming ASP.Net,
            C#, jQuery, AngularJs, Gridview, MVC, Ajax, Javascript, XML, MS SQL-Server, NodeJs,
            Web Design, Software</p>
        <p style="color: #3e4b51;">
            <b>html2canvas</b> script allows you to take "screenshots" of webpages or parts
            of it, directly on the users browser. The screenshot is based on the DOM and as
            such may not be 100% accurate to the real representation as it does not make an
            actual screenshot, but builds the screenshot based on the information available
            on the page.
        </p>
    </div>
    <input id="btn-Preview-Image" type="button" value="Preview" />
    <a id="btn-Convert-Html2Image" href="#">Download</a>
    <input type="button" value="Preview & Convert" id="btnConvert" >
    <br />
    <h3>Preview :</h3>
    <div id="previewImg">
    </div>

As many of you are asking in the comment section to use a single button click, instead of two-button i.e one for preview and one for download. So below I have updated with a single button also.

#3 JavaScript Code to convert HTML to Image [png]

To save HTML as an Image in Javascript first, we need to create a button click event by using addEventListener.Then on click event, we use the html2canvas library function.

Our Javascript code looks like this as written below:

 document.getElementById("btn_convert1").addEventListener("click", function() {
	html2canvas(document.getElementById("html-content-holder")).then(function (canvas) {
var anchorTag = document.createElement("a"); document.body.appendChild(anchorTag); document.getElementById("previewImg").appendChild(canvas); anchorTag.download = "filename.jpg"; anchorTag.href = canvas.toDataURL(); anchorTag.target = '_blank'; anchorTag.click(); }); });

The above code will convert an HTML div to an image in JavaScript. Here we converted HTML to JPEG successfully, and if you want to convert HTML to PNG in Javascript.

Then we need to make a simple change in our code i.e by setting the download filename with the extension as .png in our case use filename.png  instead of filename.jpg.   

Now below code is for using jquery, you can skip further reading if you want without jquery.

View Demo


Updated latest version:  Instead of 2 buttons we use a single button to preview and download the converted image.

As we have a button that previews and converts HTML to image i.e btnConvert. On button click with the below-written code, we are able to convert HTML to an image same as shown in the above video.

  $("#btnConvert").on('click', function () {
                html2canvas(document.getElementById("html-content-holder")).then(function (canvas) {                   
                   var anchorTag = document.createElement("a");
                    document.body.appendChild(anchorTag);
                    document.getElementById("previewImg").appendChild(canvas);
                    anchorTag.download = "filename.jpg";
                    anchorTag.href = canvas.toDataURL();
                    anchorTag.target = '_blank';
                    anchorTag.click();
                });
    });

Fix issue:- Image content in HTML markup

If the HTML markup contains image tags and you try to convert HTML to an image, then the image will not get converted in some browsers.  In that case, you need to pass extra parameters to the html2canvas method.

These extra parameters are allowTaint, useCORS, and set as true by default both are false. So the final code looks like as written below: 

$("#btn_convert").on('click', function () {
		html2canvas(document.getElementById("html-content-holder"),
{ allowTaint: true, useCORS: true }).then(function (canvas) { var anchorTag = document.createElement("a"); document.body.appendChild(anchorTag); document.getElementById("previewImg").appendChild(canvas);
anchorTag.download = "filename.jpg"; anchorTag.href = canvas.toDataURL(); anchorTag.target = '_blank'; anchorTag.click(); }); });

If the image source is from another domain, then setting useCORS: true, allows us to convert image tag HTML into an image.

View Demo

Also Read:  How to export HTML table into excel in javascript.

For the older version, you can follow the below-written code, where we have two buttons. One for preview and another is the anchor tag, which downloads the image,


#4 Button click converts HTML to Canvas:

As you see, we have added a preview button. Now on the preview button click using HTML2Canvas will render our HTML to Canvas.

The code looks like this as written below:

var element = $("#html-content-holder"); // global variable
var getCanvas; // global variable

    $("#btn-Preview-Image").on('click', function () {
         html2canvas(element, {
         onrendered: function (canvas) {
                $("#previewImg").append(canvas);
getCanvas = canvas; } }); });

The above-written jQuery code will create a canvas and append it to our div container for preview purposes.

View Demo 

#5 jQuery: Download HTML to IMAGE / Screenshot of Div content

Here we are ready with our canvas now we just need to download it in Image format. On the download button click will convert canvas to png image format you can set any image format. Here's the code for downloading.

$("#btn-Convert-Html2Image").on('click', function () {
    var imgageData = getCanvas.toDataURL("image/png");
    // Now browser starts downloading it instead of just showing it
    var newData = imgageData.replace(/^data:image/png/, "data:application/octet-stream");
    $("#btn-Convert-Html2Image").attr("download", "your_pic_name.png").attr("href", newData);
});

Conclusion:  Here's an easy way to render HTML to an image like PNG. As it's easy to create an image from a canvas. But to render standard HTML elements like DIV, UL, LI, Table, and P tags to an image we use the HTML2Canvas javascript library. Using HTML2Canvas will take screenshots of our HTML web pages. I personally found this as the best javascript library to convert HTML to images.

You can also check these articles:

  1. Preview the Image before uploading it with jQuery in Asp.net.
  2. How to get the filename, size, and type count in jQuery [input file, File Api].
  3. Create a dynamic HTML table using jquery.
  4. How to remove table row tr in jquery on button click.
  5. Jquery: How to disable Button, Div, Anchor tag.

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

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

65 Comments