Export HTML Table to PDF using jQuery
Today I will give you an Example of Export HTML Table to PDF using jQuery. In this tutorial, I will show you Export an HTML Table to PDF using jQuery. you will learn to Export HTML Table to PDF using jQuery. Converting or Exporting HTML tables to PDF using jQuery is a big problem for Web Developers and every time they look for appropriate solutions. So In this post, You will not take more than 3 minutes to export an HTML table to PDF using jQuery. And also you don’t need to download fpdf library file and include it in your file.
Here I am explaining an easy way to export an HTML table to PDF using jQuery with an example.
We will use two libraries html2canvas and pdfmake to complete our requirement.
Example
<html>
<head>
<title>Export HTML Table to PDF using jQuery</title>
<style type="text/css">
table
{
border: 1px solid #ccc;
border-collapse: collapse;
}
table th
{
background-color: #F7F7F7;
color: #333;
font-weight: 600;
}
table th, table td
{
padding: 5px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<h1>Export HTML Table to PDF using jQuery</h1>
<table id="employee" cellspacing="0" cellpadding="0">
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Age</th>
</tr>
<tr>
<td>1</td>
<td>Raj</td>
<td>raj@gmail.com</td>
<td>20</td>
</tr>
<tr>
<td>2</td>
<td>John</td>
<td>John@gmail.com</td>
<td>21</td>
</tr>
<tr>
<td>3</td>
<td>Lark</td>
<td>lark@gmail.com</td>
<td>24</td>
</tr>
<tr>
<td>4</td>
<td>Emely</td>
<td>emely@gmail.com</td>
<td>24</td>
</tr>
<tr>
<td>5</td>
<td>kel</td>
<td>kel@gmail.com</td>
<td>27</td>
</tr>
</table>
<br />
<input type="button" id="export" value="Export"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.22/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script type="text/javascript">
$("body").on("click", "#export", function () {
html2canvas($('#employee')[0], {
onrendered: function (canvas) {
var dataUrl = canvas.toDataURL();
var data = {
content: [{
image: dataUrl,
width: 450
}]
};
pdfMake.createPdf(data).download("employee.pdf");
}
});
});
</script>
</body>
</html>
Output
Export HTML Table to PDF using jQuery
Id | Name | Age | |
---|---|---|---|
1 | Raj | raj@gmail.com | 20 |
2 | John | John@gmail.com | 21 |
3 | Lark | lark@gmail.com | 24 |
4 | Emely | emely@gmail.com | 24 |
5 | kel | kel@gmail.com | 27 |