Export web page to pdf using jsPDF

jsPDF is a client side Javascript PDF generator. This makes it very easy to export a web page on the fly or on an event (like on button click).

In this example, we will show a simple example to export a web page on button click.  A demo is also available on JSFiddle. We have the below html code to create a web page with a button to ‘export to pdf’

<head>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js" integrity="sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/" crossorigin="anonymous"></script>
</head>
<body>
<div id="banner-message">
<div id="demo">This is a demo of jsPDF</div>
<div>Click on the button below to export me</div>
<button>Export to PDF</button></div>
</body>

The html looks as shown below:

jsPDF
The webpage with Export to PDF button.

Create a JavaScript function to write the jsPDF logic.

button.on("click", function(){
     var doc = new jsPDF()
     doc.setFontSize(22);
     doc.setTextColor(0, 0, 255);
     doc.setFont("helvetica");
     doc.setFontStyle("bold");
     doc.text(demo, 105, 10, null, null, 'center');
     // doc.save will export a pdf file with name export and above text.
     doc.save('export.pdf')
})

The attached file will be exported on click of export.

Join Discussion

This site uses Akismet to reduce spam. Learn how your comment data is processed.