How To Download HTML Content as PDF File Using JavaScript

How To Download HTML Content as PDF File Using JavaScript  | In this article I’m going to explain you one the most interesting and useful tutorial, that is download the HTML content as in the PDF format onclick using jsPDF jquery file.

Using jsPDF library, you can download the div contents as a PDF file. This is a HTML5 client-side solution for generating PDFs.

Simply include library in your <head>, generate your PDF using the many built-in functions, then create a button to trigger the download.


<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/0.9.0rc1/jspdf.min.js"></script>

HTML Code


<div id="print">
     <h3>Welcome To Veewom</h3>
     <p>This is a Sample Pararaph</p>
</div>
<div id="print-btn"></div>
<button id="submit">Download PDF File</button>

JavaScript Code


var doc = new jsPDF();
var specialElementHandlers = {
    '#print-btn': function (element, renderer) {
        return true;
    }
};

$('#submit').click(function () {
    doc.fromHTML($('#print').html(), 15, 15, {
        'width': 170,
            'elementHandlers': specialElementHandlers
    });
    doc.save('pdf-version.pdf');
});

Final Code


<!DOCTYPE html>
<html lang="en-US">
<head>
<title>How To Download a DIV in a HTML Page as PDF File Using JavaScript</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/0.9.0rc1/jspdf.min.js"></script>
</head>
<body>
<!-- Content Area -->
<div id="print">
     <h3>Welcome To Veewom</h3>
     <p>This is a Sample Pararaph</p>
</div>
<div id="print-btn"></div>
<button id="submit">Download PDF File</button>
<!-- Script -->
 
var doc = new jsPDF();
var specialElementHandlers = {
    '#print-btn': function (element, renderer) {
        return true;
    }
};

$('#submit').click(function () {
    doc.fromHTML($('#print').html(), 15, 15, {
        'width': 170,
            'elementHandlers': specialElementHandlers
    });
    doc.save('pdf-version.pdf');
});
 
</body>
</html>

We hope this article helped you to easily learn how to download html content as pdf file using javascript. You may also want to see – How To Change The Default WordPress Email Address.

If you liked this article, then please share to social networking site. You can also find us on Twitter,Facebook and Instagram.

Share Share on Facebook Share on Twitter Share on Google+ Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

Bharat Makwana is a Founder of Veewom. He is Content creator and Web Developer from past three years. He loves to read and get in touch with the latest technology, he also have YouTube Channel ” Veewom ” ,for more info contact - bharat@veewom.com.