jsPDF Tutorial to Convert Two Tables with Headers with jspdf-autotable Library and Download it as PDF File

jsPDF Tutorial to Convert Two Tables with Headers with jspdf-autotable Library and Download it as PDF File


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



<button onclick="generate()">Generate PDF</button>

<table id="basic-table" style="display: none;">
      <th>First name</th>
      <th>Last name</th>
      <td align="right">1</td>
      <td align="right">2</td>
      <td align="right">3</td>
      <td>Trinidad and Tobago</td>
      <td align="right">4</td>
      <td align="right">5</td>
      <td>United States</td>
      <td align="right">6</td>


See also  Javascript Tutorial to Add Live Webcam Filter Effects to Video Using WebRTC API in Browser Full Project For Beginners

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





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.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);



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



See also  Build a Simple JSON Prettier Viewer or Editor in Browser Using Vanilla Javascript Full Project For Beginners



Leave a Reply