Skip to content

Coding Shiksha

Menu
  • Home
  • Youtube Channel
  • Online Store
  • Online Tools
  • Donate Us
  • Sitemap
  • Privacy Policy
Menu

jsPDF-Autotable Tutorial to Insert Array of JSON Objects Data in Table inside PDF in Javascript

Posted on October 30, 2022

Welcome folks today in this blog post we will be inserting array of json objects data in table inside pdf document using 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 jspdf and jspdf-autotable cdn library as shown below

 

 

1
2
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.debug.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.2.3/jspdf.plugin.autotable.js"></script>  

 

 

And now we need to define the button to generate the pdf document. And we will be attaching the onclick attribute to the button. We are calling the generatePDF() method as shown below

 

 

1
<button onclick="generatePDF()">Generate PDF</button>

 

 

And now we will be defining the generatePDF() method in this first of all we will be initializing the users array of objects we will be a series of records and then we are initializing a new jspdf doc. And then we are using the foreach loop to iterate all the users records to construct a new info array of objects which contains the actual information which is the name,age and country of the user. And then we are using the autoTable() method to insert the information of the user.

 

 

JavaScript
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
function generatePDF(){
        let doc = new jsPDF()
 
        let users = [
            {
                name:'John',
                age:25,
                country:'New Zealand'
            },
            {
                name:'Smith',
                age:30,
                country:'Australia'
            }
        ]
 
        let info = []
 
        users.forEach((element,index,array) => {
            info.push([element.name,element.age,element.country])
        });
 
        doc.autoTable({
            head:[['Name','Age','Country']],
            body:info
 
        })
 
        doc.save("output.pdf")
    }

 

 

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

©2023 Coding Shiksha | Design: Newspaperly WordPress Theme