Welcome folks I am back with another blog post. In this post I will be talking about Generating Pdf with jsPDF & AutoTable.So let’s get started with the application.
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 |
<table border="1" id="example" class="sfc_table"> <thead> <tr> <th>PART NUMBER</th> <th>COST</th> </tr> </thead> <tbody> <tr> <td colspan="2" class="innerHeader March">March</td> </tr> <tr> <td>ThisEXAMPLE</td> <td>£40.00</td> </tr> <tr> <td align="right">Your spend this month:</td> <td>£40.00</td> </tr> <tr class="total"> <td align="right">Your total spend</td> <td>£40.00</td> </tr> </tbody> </table> <div class="grid_24 footer"> <hr> <div class="grid_6 push_18"> <a class="btn" id="export" href="summary.html">Export</a> </div> </div> |
Now we add some Javascript code to the table so that we can export it to the pdf format to download.
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 65 66 67 68 |
function generate() { var doc = new jsPDF('p', 'pt', 'a4'); var elem = document.getElementById('example'); var data = doc.autoTableHtmlToJson(elem); doc.autoTable(data.columns, data.rows, { tableLineColor: [189, 195, 199], tableLineWidth: 0.75, styles: { font: 'Meta', lineColor: [44, 62, 80], lineWidth: 0.55 }, headerStyles: { fillColor: [0, 0, 0], fontSize: 11 }, bodyStyles: { fillColor: [216, 216, 216], textColor: 50 }, alternateRowStyles: { fillColor: [250, 250, 250] }, startY: 100, drawRow: function (row, data) { // Colspan doc.setFontStyle('bold'); doc.setFontSize(10); if ($(row.raw[0]).hasClass("innerHeader")) { doc.setTextColor(200, 0, 0); doc.setFillColor(110,214,84); doc.rect(data.settings.margin.left, row.y, data.table.width, 20, 'F'); doc.autoTableText("", data.settings.margin.left + data.table.width / 2, row.y + row.height / 2, { halign: 'center', valign: 'middle' }); /* data.cursor.y += 20; */ }; if (row.index % 5 === 0) { var posY = row.y + row.height * 6 + data.settings.margin.bottom; if (posY > doc.internal.pageSize.height) { data.addPage(); } } }, drawCell: function (cell, data) { // Rowspan console.log(cell); if ($(cell.raw).hasClass("innerHeader")) { doc.setTextColor(200, 0, 0); doc.autoTableText(cell.text + '', data.settings.margin.left + data.table.width / 2, data.row.y + data.row.height / 2, { halign: 'center', valign: 'middle' }); return false; } } }); doc.save("table.pdf"); } $('#export').click(function (e) { e.preventDefault(); generate(); }); |
Thanks for reading this post and if you like reading this and wants to read more of this please subscribe the blog below to get all the notications.