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

jQuery HTML to Image Converter: This article explains how to convert div to an image in jquery. Yes, we are going to generate an image from our HTML page on client-side using jQuery. We can also convert a particular part of our Webpage (Asp.net C# Web project/ PHP). All we need HTML tag, and using html2canvas js library we can create images .i.e converting 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 the use of converting HTML to image/picture?

As we know HTML5 gives some excellent feature, for example, we have a Canvas tag on our web page. Now on HTML 5 Canvas, we draw something or let say we create a pie chart using jquery, after that, we want to save this as an Image may be in png or jpg format. We convert Canvas to Image at client-side and later save it on our server. Another example, which I have implemented in my Asp.net C# web project where I had to add multiple images and then drag/shuffle all the images inside a canvas then save and upload this image using jQuery ajax, and give the print command to make Mug Sticker, Tshirt Sticker. The idea behind it is to let the user add his / her photos. Allow them to arrange or to shuffle it. Later on, save button click using Jquery HTML canvas save the image which will send for printing purpose. Now let’s head towards the coding part and see how we can convert HTML to Picture 🙂

Example: Render HTML to Image in JQuery


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

  1. Download and import HTML2Canvas jquery files.
  2. Add HTML markup.
  3. jQuery Code: Button click convert HTML to Canvas.
  4. jQuery Code: Download HTML to IMAGE.

# Download and import HTML2Canvas files.

First, we need to download and import latest jquery library in our web page. You can import your server hosted jQuery file, or you can also use from the Google-hosted site (recommended). For converting HTML to Image, we need to import one more js library, and it is HTML2CANVAS download it and import into the HTML head tag. Now we are done with downloading, so our final head tag looks like 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>
//*

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

Let 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 button tag which creates Image of specific HTML and a download button. On download button click 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 done at 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>
    <br />
    <h3>Preview :</h3>
    <div id="previewImage">
    </div>

#Button click converts HTML to Canvas:

As you see, we have added a preview button. Now on preview button click using HTML2Canvas will render our HTML to Canvas. The code looks like 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) {
                $("#previewImage").append(canvas);
                getCanvas = canvas;
             }
         });
    });
//*

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

Try It Yourself ⇒

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

Here we are ready with our canvas now we just need to download it as Image format. On 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);
});
//*
Try It Yourself ⇒

 

Conclusion:  Here’s an easy way to render HTML to 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, P tags to an image we use HTML2Canvas Js library. Using HTML2Canvas will take the screenshot of our HTML web pages.

You can also check these articles:

  1. An easy way to upload bulk images in Asp.net c#.
  2. Upload and resize the image in Asp.net using dropzone js.
  3. Preview Image before uploads it with jQuery in Asp.net.

Hope you enjoyed this tutorial. If you have any recommendations, please let us know what you think in the comment section below! See you again next time!

Share:    
Satinder Singh

Hi all, am Founder and Author of Codepedia.info, also atypical polyglot programmer from Bombay, India. I have a passion to create, solve, and deploy software applications.
       ForEach ( minute in MyLife ) { myExperience++ ; }


40 comments on “Convert HTML to Image in Jquery [Div or Table to jpg/ png]”

  1. vivek singh

    i see your code ..excellent . how my create image automatic save in my specific folder with my genret name.

  2. Vikram Singh

    Is this possible to download image directly on clicking download button without preview(with out clickig preview button)

  3. Bhuvana

    Sir,

    Excellent Tutorial But I have an issue in I need to download an image without previewing. As you said I have copied both button code into one function and comment this line $(“#previewImage”).append(canvas); Its working. But when clicking the download its not working . In second click only its downloading the corresponding image. Can you help me ASAP???

  4. Ghazi Anwer

    Very nicely explained. can you please help me out how to export an HTML page containing highcharts along with some HTML table into pdf. please help as I have struck in it.

    Regards
    Ghazi

  5. Maynard

    Amazing code and tutorial. Thank you so much. Has anyone tried using it live? Does it work? I thought I had found exactly what I needed and it worked on my local server, but my instructor tried to shoot me down by saying it wouldn’t work on a live server for security reasons (?).

  6. Azeem

    Thanks for the tutorial Satinder!

    But what if I want to download it directly without having the preview step, is that possible?

  7. Daniel

    Is it possible to change the image resolution or size of the image in this example? The problem is that when I download the image it’s very blurry and the resolution of the image is low, so when I zoom in it gets pixelated. What can I do?

  8. ronx

    Hi Satinder,

    How can I just make image download on click of download button, I don’t want user to first press preview and then download,

    I just want to click download and image download.

  9. monica

    Thanks for the explanation! Just wondering does this code works on iOS? Cause i am trying to make a mobile application where there’s this button and the button can save image and save it to camera roll.
    Many thanks!

  10. Nelson

    Excellent Tutorial. Its working great in chrome and firefox, but In safari9.1, I’m not able to download the png., it get base64. Please help me how to solve this issue….

  11. Madhu

    It’s working fine for text. But when i use images it’s not showing. Can anyone give a solution for an tag

  12. venkat

    Excellent Tutorial. Its working great in chrome and firefox, but In Internet Explorer 11 I’m not able to download the image… Please help me how to solve this issue…..

  13. venkat

    Excellent Tutorial. Its working great in chrome and firefox, but In Internet Explorer 11 I’m not able to download the image… Please help me how to solve this issue….


Post Comment


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