Welcome folks today in this blog post we will be converting two tables with headers
to pdf file using jspdf
library and download it as pdf file. All the source code of the application is given below.
Libraries Used
We are using two libraries for this project
jspdf
is the library for generating pdf documents using javascript
jspdf-autotable
is the library for converting tables to pdf using javascript
Get Started
Now in order to get started we need to make an index.html
file and copy paste the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
<button onclick="generate()">Generate PDF</button> <table id="basic-table" style="display: none;"> <thead> <tr> <th>ID</th> <th>First name</th> <th>Last name</th> <th>Email</th> <th>Country</th> <th>IP-address</th> </tr> </thead> <tbody> <tr> <td align="right">1</td> <td>Donna</td> <td>Moore</td> <td>dmoore0@furl.net</td> <td>China</td> <td>211.56.242.221</td> </tr> <tr> <td align="right">2</td> <td>Janice</td> <td>Henry</td> <td>jhenry1@theatlantic.com</td> <td>Ukraine</td> <td>38.36.7.199</td> </tr> <tr> <td align="right">3</td> <td>Ruth</td> <td>Wells</td> <td>rwells2@constantcontact.com</td> <td>Trinidad and Tobago</td> <td>19.162.133.184</td> </tr> <tr> <td align="right">4</td> <td>Jason</td> <td>Ray</td> <td>jray3@psu.edu</td> <td>Brazil</td> <td>10.68.11.42</td> </tr> <tr> <td align="right">5</td> <td>Jane</td> <td>Stephens</td> <td>jstephens4@go.com</td> <td>United States</td> <td>47.32.129.71</td> </tr> <tr> <td align="right">6</td> <td>Adam</td> <td>Nichols</td> <td>anichols5@com.com</td> <td>Canada</td> <td>18.186.38.37</td> </tr> </tbody> </table> |
Now we need to build the logic
functionality when we click the button so we need to add some javascript. So now create a file called as index.js
and copy paste the following code
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
function generate() { var doc = new jsPDF('p', 'pt'); var res = doc.autoTableHtmlToJson(document.getElementById("basic-table")); doc.autoTable(res.columns, res.data, {margin: {top: 80}}); var header = function(data) { doc.setFontSize(18); doc.setTextColor(40); doc.setFontStyle('normal'); //doc.addImage(headerImgData, 'JPEG', data.settings.margin.left, 20, 50, 50); doc.text("Testing Report", data.settings.margin.left, 50); }; var options = { beforePageContent: header, margin: { top: 80 }, startY: doc.autoTableEndPosY() + 20 }; doc.autoTable(res.columns, res.data, options); doc.save("table.pdf"); } |
So now if you execute this application you will find when you click the button a pdf file will be downloaded if you open that file you will see the following result