Convert HTML Table To JPG Image Using Javascript

xHTML Table To JPG Image

February 22, 2024

JavaScript can be really helpful in converting content that has been put together using the HTML tag. For instance, you'd like to take a dynamic table, infographic, or any other HTML content and convert them into an image to save it, download it, or even print it. JavaScript itself doesn't contain a built-in function in converting HTML directly to an image type like JPEG. This can be quite easily accomplished, however, with a little help from HTML5's <canvas> element and libraries like jQuery.

In this tutorial, we will guide you through the steps you need to undertake to convert an HTML table into a JPEG image using JavaScript and jQuery.

Why Convert HTML Content to JPEG?

We start by creating a simple HTML form that allows users to upload PNG or JPEG images. The form utilizes the enctype="multipart/form-data" attribute, which is essential when uploading files. Additionally, we are using Bootstrap for quick styling.

There are very many instances in web development where you'd be compelled to convert an HTML element, say a table, into an image format:

Share reports or charts: You might want to share a table or chart generated dynamically within a particular web application, which otherwise isn't viewable.

Snapshots: There are some web applications that demand you take a snapshot of some areas on the page.

Saving as image: A user might be required to save a section of a web page, an infographic or table as an image for later use.

Embedding into documents: Images can easily be embedded into PDFs, Word documents, or into an email message which may demand the conversions of HTML elements into formats of images.

How to Convert an HTML Table to JPEG Image

Step 1: Add the Required Libraries

Before actually starting the conversion, all the important JavaScript libraries should be added to your HTML file. In this tutorial, we are going to use jQuery and another canvas-based JavaScript library such as html2canvas which helps convert an HTML table into a JPEG image.

Here is the jQuery CDN link that has to be included in your project:

CDN Link

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Also include the html2canvas library that will render the HTML content as an image:

HTML2Canvas library

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>

Step 2: Creating the HTML Structure

You are now going to create the basic HTML table that will get converted to an image. Below is an example of a simple HTML structure comprising a form and a table with a download button. You can accordingly modify this according to your needs.

HTML Code

	

<main id="main" class="main">   <section class="section dashboard">     <div class="row">       <div class="col-12 grid-margin stretch-card">         <div class="card">           <h1 align="center">Convert HTML Table to JPG</h1>           <form method="POST">             <div class="row" style="padding:20px;">               <div class="col-md-4">                 <input type="text" name="product_title" id="model_check" class="form-control" placeholder="Search Here" autocomplete="off">               </div>               <div class="col-md-4">                 <input type="submit" name="submit" value="Convert" class="button_check">               </div>             </div>           </form>

          <div id="main_text">             <div class="row">               <div class="col-lg-12">                 <button id="download_jpg">Download to JPG</button>               </div>             </div>

            <!-- Example HTML Table -->             <div id="table_content" class="box">               <h1 class="post_title">Your Product Title Here</h1>               <div class="row">                 <div class="col-lg-6">                   <table style="width:100%">                     <tr>                       <th colspan="3" style="text-align:center">Test Data</th>                     </tr>                     <tr>                       <td>Coding India</td>                       <td>Coding India Lab</td>                     </tr>                     <tr>                       <td>Coding India</td>                       <td>Coding India Lab</td>                     </tr>                     <!-- Add more rows as needed -->                   </table>                 </div>               </div>             </div>           </div>         </div>       </div>     </div>   </section> </main>  

In this example, we use a form to input a title that will appear in the table. After we submit the form, the user sees a button that he or she can click to convert the table into a JPEG image.

Step 3: JavaScript Code to Convert HTML to JPEG

Once the basic HTML structure is laid, it is followed by the process of including the JavaScript that would help in handling the process of conversion. Below is the JavaScript code using html2canvas to take the screenshot of the HTML content and represent it as an image.

JavaScript Code:

  $(document).ready(function(){
    $('#download_jpg').click(function(){
      html2canvas(document.getElementById("table_content"), {
        onrendered: function(canvas) {
          var imgData = canvas.toDataURL("image/jpeg", 1.0);
          var link = document.createElement('a');
          link.href = imgData;
          link.download = 'table_image.jpg';
          link.click();
        }
      });
    });
  });
	

Explanation of Code:

html2canvas: It takes the content inside the element with the ID table_content and renders it as a canvas.

canvas.toDataURL(): Converts the content of the canvas to a data URL, which is an image format in this case, a JPEG.

link.click(): Generates an anchor tag with the href attribute, which is the data URL, and triggers a click event on it, asking the user to download the image.

Step 4: Customize and style the output of the image

There are also cases when you will be wanting to apply certain styles to the table, or other HTML elements before rendering them as an image. You can customize the appearance of the table in the image through applying styles that include text alignment through the usage of CSS to center text in cells and borders, as well as the padding of the table and the cell.

Font sizes and colors: Make sure the text and background colors are suitable for the image.

Example CSS

#table_content {
  background-color: #fff;
  padding: 20px;
  border: 1px solid #000;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 10px;
  border: 1px solid #ddd;
}

h1 {
  text-align: center;
  font-size: 24px;
  color: #333;
}

Step 5: Test and Debug

With all your HTML, CSS, and JavaScript in place, it is now time to test your solution. Open your browser, enter the product title, and click the "Download to JPG" button to ensure everything works as expected.

If the picture is not generated or does not look as you would have wished, the following things to check can be noted:

Cross-browser compatibility: This library should work out pretty fine in most of the browsers

CSS styling: Some styles are not supported at all in the canvas, so the image will not look exactly as you would have wanted it to.

Resolution and image quality: You can change the output resolution of the image by passing the quality parameter to the toDataURL function. Example: canvas.toDataURL("image/jpeg", 0.8); slightly reduced quality).

Step 6: Advanced Use Cases

If you are going to add a content or layout that is bigger, you may need to:

Resize or crop the canvas: this helps sometimes when large tables get a lot of overflow.

Add pagination: if your table is very large, consider splitting this into a number of images.

Compress the JPEG: you may compress the file to save space for large data or even large images.

This way, you can easily transform any HTML table or content into a JPEG image. This is useful for generating snapshots of dynamically generated web content.

Conclusion

Showing an HTML table as a JPEG image using JavaScript and html2canvas is one of the techniques that can be used effectively in quite a few web development scenarios. If you want to enable users to download reports, share content in a more visual way, or save items as images on a web page, this tutorial explains how to do it. You might further extend this solution through code tweaks and your own styling and logic to suit your particular needs.