Welcome folks today in this blog post we will be converting multiple div's
html content with css to pdf document using the fromHTML()
method in jspdf using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://parall.ax/parallax/js/jspdf.js"></script> <body> <div style="color:red" hidden id="result"> <h1>Hello World</h1> </div> <div style="color:red" hidden id="result2"> <h1>Hello World</h1> </div> <button onclick="generatePDF()">Generate PDF</button> </body> </body> </html> |
As you can see we are importing the jspdf
library cdn and then inside the body we have two div sections which are hidden by default. We have provided the hidden attribute to them. So when we load the page they will not be shown to the user. And then we have the button to generate the pdf file. And we have attached a onclick event listener to the button.
Now we need to make the generatePDF()
method by writing some custom javascript code as shown below
script.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function generatePDF() { var doc = new jsPDF(); $("#result").removeAttr('hidden') $("#result2").removeAttr('hidden') doc.fromHTML(document.getElementById("result"),5,5) doc.fromHTML(document.getElementById("result2"),5,45) $("#result").attr('hidden', 'true') $("#result2").attr('hidden', 'true') doc.save("output.pdf") } |
As you can see in the above javascript code we are invoking a new constructor of jsPDF and then we are removing the hidden attribute and then we are using the fromHTML()
to export the html content of the div sections and add it to pdf document at x and y coordinates and then again we are attaching the hidden attribute and lastly we are saving the pdf document with custom name.
Now if you open the index.html
inside the browser you will see the below output