Convert HTML to PDF jQuery Plugin – jsPDF

If you are looking for client-side solution to generate PDF document form your html content, then jQuery is the easiest way to convert HTML to PDF. There are various Jquery library is available for generating PDF from HTML. jsPDF is one of the best library to convert HTML to PDF using JavaScript. In this tutorial, we will show you how to generate PDF document and convert HTML to PDF using jQuery and jsPDF library.
html2pdf-javascript

Libraries

The easiest way to get started is to drop the CDN hosted library into your page along with jQuery Library

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js" integrity="sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/" crossorigin="anonymous"></script>

Or Install Plugin via NPM

npm install jspdf --save

Then you’re ready to start making your document:

// Default export is a4 paper, portrait, using milimeters for units
var doc = new jsPDF()
 
doc.text('Hello world!', 10, 10)
doc.save('a4.pdf')

If you want to change the paper size, orientation, or units, you can do:

// Landscape export, 2×4 inches
var doc = new jsPDF({
  orientation: 'landscape',
  unit: 'in',
  format: [4, 2]
})
 
doc.text('Hello world!', 1, 1)
doc.save('two-by-four.pdf')


Convert HTML Content to PDF

Here is sample html code which need to convert into PDF

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

JS

var doc = new jsPDF();
var elementHTML = $('#contnet').html();
var specialElementHandlers = {
    '#toPdf': function (element, renderer) {
        return true;
    }
};
doc.fromHTML(elementHTML, 15, 15, {
    'width': 170,
    'elementHandlers': specialElementHandlers
});
 
// Save the PDF
doc.save('sample-document.pdf');

See live demo and download source code.

DEMO | DOWNLOAD | FULL DOCUMENTATION

This awesome script developed by MrRio, Visit their official github repository for more information and follow for future updates.


Don’t forget to Subscribe My Public Notebook for more useful free scripts, tutorials and articles.