Welcome folks today in this blog post we will be exporting html to pdf document in browser using fromHTML()
method in javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to include the cdn
of jspdf library in the index.html
file as shown below
index.html
1 2 |
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.debug.js"></script> |
As you can see we are including the jquery
and jspdf
cdn as shown above in the index.html
file
Writing the HTML
Now we will be writing the html code inside the index.html
file as shown above
1 2 3 4 5 6 7 8 9 |
<div class="zima"> <h1> Header </h1> <p>This is the paragraph</p> <p> content </p> </div> <button id="getPDF" onclick="getPDF()">Download PDF</button> |
As you can see we have the parent div which is having the class of zima
and inside it we have the h1
heading and also we have the p
element and then we have the button
element. Here in the button element we have attached the onclick event listener. And we are calling the method getPDF()
So we will define this function as shown below
Writing the Javascript Code to Export to PDF Document
Now we will be define the javascript
code to export the pdf document. So we need to copy paste the below code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
function getPDF() { var doc = new jsPDF(); // We'll make our own renderer to skip this editor var specialElementHandlers = { '#getPDF': function(element, renderer){ return true; }, '.controls': function(element, renderer){ return true; } }; // All units are in the set measurement for the document // This can be changed to "pt" (points), "mm" (Default), "cm", "in" doc.fromHTML($('.zima').get(0), 15, 15, { 'width': 170, 'elementHandlers': specialElementHandlers }); doc.save('Generated.pdf'); } |
As you can see inside this function we are initializing the jspdf
constructor and create a new document and after that we are using the fromHTML()
method and after that we are targeting the parent div which is having the class of zima
using jquery and then inside that function we are providing the width
property and then we have the second property which is called elementHandlers
we are attaching the specialElementHandlers
object
Now if you open the index.html
file inside the browser you will see the below result as shown below