Welcome folks today in this blog post we will be exporting div html to pdf document using jspdf 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 make a new vue.js project and install the jspdf
library using the below command as shown below
npm i jspdf
After that you need to edit the App.vue
file and copy paste the following code
App.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<template> <div ref="content"> <h1>This is the heading</h1> <p>This is a paragraph</p> <li> this is one item </li> <li> this is second item </li> </div> <button @click="generatePDF">Convert to PDF</button> </template> |
Basically we have written the above html in the template it contains a simple div section having the ref
attribute equal to content and then inside it we have the h1
heading and the paragraph
and then we have the button to export the html to pdf document.
And now we will be writing the javascript
to export the html to pdf
App.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<script> import jspdf from 'jspdf' export default { name: "App", methods:{ generatePDF(){ let html = this.$refs.content.innerHTML let doc = new jspdf() doc.fromHTML(html,10,10, { width: 170 }); doc.save("output.pdf") } } }; </script> |
As you can see we are defining the method
which we have binded as a onclick on the button. Inside this method we are getting the html from the template using the innerHTML
property. And then we are making a new pdf document and inside it we are using the fromHTML()
method to convert the html template to pdf document. And lastly we are saving the pdf document using the save()
method.