Export HTML Table to PDF using jQuery
In this tutorial, we will learn how to export an HTML table to PDF using jQuery. Many web developers struggle with converting HTML tables into PDF files and often think they must install heavy PHP libraries like FPDF. The good news is: you can do it directly on the client side using JavaScript.
We will use two popular libraries:
- html2canvas – to capture the HTML table as a canvas/image
- pdfMake – to generate a PDF document from that image
No server-side PDF library is required.
What We Are Going to Build
- A simple HTML table
- A button labeled “Export to PDF”
- When the button is clicked, the table will be captured and downloaded as a PDF file
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 |