Convert HTML Table to PDF

Kailash Chandra Behera | Thursday, July 16, 2020


This blog provides a complete code example to export html table to pdf, Note that before continuing this you should have idea about HTML and javascript if don't have knowledge of HTML development and javascript. Requesting to refer some related blogs.

table html to pdf

Convert HTML Table to PDF

Getting Started

Sometimes with our busy demplopment, while developing websites. We are writing lot of code to print a page document rather than writing simple and short code.

The below code example prints an HTML table simply using JavaScript code, it creates a table with a list of 10 students details, an HTML button also created to give print command. The HTML button calls printData function which contains the javascript code to give print command.

 Print html table  
 function printData()  
   var divToPrint=document.getElementById("printTable");  
 <table id="printTable" style="border: 1px solid black;border-collapse: collapse;">  
           <th bgcolor="NAVY"><font color="white"> Student Name</font></th>  
           <th bgcolor="NAVY"><font color="white">Roll No.</font></th>  
           <th bgcolor="NAVY"><font color="white">DIV</font></th>  
           <th bgcolor="NAVY"><font color="white">STD</font></th>       
           <th bgcolor="NAVY"><font color="white">GRNO</font></th>            
           <th bgcolor="NAVY"><font color="white">Card No.</font></th>  
 <TR><TD >Kailash</TD><TD>1</TD><TD>A</TD><TD>VII</TD><TD>102751</TD><TD>0005717471</TD></TR>  
 <TR><TD>Duti Krishna</TD><TD>4</TD><TD>D</TD><TD>VII</TD><TD>102754</TD><TD>0005717474</TD></TR>  
 <br />  
 <br />  
 <button onclick="printData();">Print me</button>  

printData function

 function printData()  
   var divToPrint=document.getElementById("printTable");  

javascript print table

The above javascript code first creates object of the table using docuemtn.getElementById function. Then it creates an object of html window to popup print window and assigned the table content to the print window as print document.


The above code example printed a html table, copy the code, paste it in a new notepad file then save that file with .thml extension. Start your attached printer, open the saved file in chrome browser then click on the button print. Go to your printer and collect your prints. I hope you have enjoyed it a lot.