jsPDF Library & jsPDF AutoTable Library Crash Course in Javascript 2020

jsPDF Library & jsPDF AutoTable Library Crash Course in Javascript 2020

In this post we will talk about the jspdf and jspdf autotable so in this library will be converting HTML documents to PDF documents and also we will be converting the HTML tables to PDF tables with the help of these two libraries so let’s get started

 

Include jQuery and jsPDF Library

Include the jQuery and jsPDF library files to use the jsPDF class.

<!-- jQuery library -->
<script src="js/jquery.min.js"></script>

<!-- jsPDF library -->
<script src="js/jsPDF/dist/jspdf.min.js"></script>

 

Instantiate jsPDF Class

 

var doc = new jsPDF();

 

Generate PDF File using JavaScript

 

  • Specify the content in text() method of jsPDF object.
  • Use the addPage() method to add new page to PDF.
  • Use the save() method to generate and download PDF file.
See also  How to get Full Path of Uploaded Image in Electron Application

 

var doc = new jsPDF();

doc.text(20, 20, 'Hello world!');
doc.text(20, 30, 'This is client-side Javascript to generate a PDF.');

// Add new page
doc.addPage();
doc.text(20, 20, 'Visit CodexWorld.com');

// Save the PDF
doc.save('document.pdf');

 

Convert HTML Content to PDF using JavaScript

 

<div id="content">
    <!-- HTML contnet goes here -->
</div>

<div id="elementH"></div>

 

var doc = new jsPDF();
var elementHTML = $('#contnet').html();
var specialElementHandlers = {
    '#elementH': function (element, renderer) {
        return true;
    }
};
doc.fromHTML(elementHTML, 15, 15, {
    'width': 170,
    'elementHandlers': specialElementHandlers
});

// Save the PDF
doc.save('sample-document.pdf');

 

Change Paper Orientation:

var doc = new jsPDF({
    orientation: 'landscape'
});

doc.text(20, 20, 'Hello world!');
doc.text(20, 30, 'This is client-side Javascript to generate a PDF.');

// Add new page
doc.addPage();
doc.text(20, 20, 'Visit CodexWorld.com');

// Save the PDF
doc.save('document.pdf');

 

Installation jsPDF-Autotable

 

See also  How to Redirect to Another Page on Button Click in AngularJS Full Project For Beginners

 

import jsPDF from 'jspdf'
import 'jspdf-autotable'

const doc = new jsPDF()

// It can parse html:
// <table id="my-table"><!-- ... --></table>
doc.autoTable({ html: '#my-table' })

// Or use javascript directly:
doc.autoTable({
  head: [['Name', 'Email', 'Country']],
  body: [
    ['David', 'david@example.com', 'Sweden'],
    ['Castille', 'castille@example.com', 'Spain'],
    // ...
  ],
})

doc.save('table.pdf')

Leave a Reply