Welcome folks today in this blog post we will be inserting array of json objects as rows in table in pdf document using jspdf-autotable
library in javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an index.html
file and copy paste the following code
index.html
1 2 3 4 |
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.2.3/jspdf.plugin.autotable.min.js"></script> <button id="generate">Generate PDF</button> <table id="my-table"></table> |
As you can see we are including the jspdf
and jspdf-autotable
library cdn and also we have a button of generate pdf
when we click that we will be exporting the array of json objects to the pdf document. And then we also have the table tag which is empty for now but we will be dynamically inserting table rows into it using javascript.
Now we need to write the javascript code so that we can export the array of json objects to pdf document
script.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 28 29 30 31 |
var elem = document.getElementById("generate"); var result = [ { name: "Gautam Sharma", age: 32, country: "India", }, { name: "John Williamson Latham", age: 31, country: "New Zealand", }, { name: "Adam Nicholls", age: 31, country: "South Africa", }, ]; let info = [] result.forEach((element, index, array) => { info.push([element.name, element.age, element.country]) }) elem.onclick = function () { var doc = new jsPDF(); console.log(result); doc.autoTable({ head: [["Name", "Age", "Country"]], body: info }); doc.save("table.pdf"); }; |
As you can see we are targeting the button element using it’s id. And then we have declared array of users each having three properties name,age and country. And then we are using the foreach loop to loop through each user and insert the information inside the info
array using the push() method. And then inside the onclick event we are making a new jspdf document and then we are using the autoTable()
method to insert the table headers and the actual body which is the actual array of json objects. And lastly we are saving the pdf document using the save()
method