Welcome folks today in this blog post we will be taking screenshot of canvas and export it to pdf document using jspdf and html2canvas library in 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 |
<div id="content"> <h1>JSPDF html2canvas with multiple pages</h1> <img src='image.png' width="500" height="500" /> </div> <button onclick="takeScreenshot()">Take Screenshot</button> <script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script> |
As you can see in the above html we have the img
that we are loading from a local file and displaying it and also we have another h1
heading and then we have a button to take the screenshot. Also we have binded a onclick event listener to the button. And we are executing the method called takeScreenshot()
which we now have to define inside the javascript
script.js
1 2 3 4 5 6 7 8 |
function takeScreenshot() { html2canvas(document.getElementById('content')).then((canvas) => { let image = canvas.toDataURL('image/jpeg') let doc = new jsPDF() doc.addImage(image, 0, 0) doc.save("output.pdf") }) } |
As you can see we are executing the function of takeScreenshot() inside this we are first of all taking the screenshot of the particular section of the DOM. Here we are targeting the DIV section which has got the id
called content and then it captures the screenshot and stores it inside the canvas. And then we are exporting the screenshot to base64 jpeg image and then we are adding that image inside the pdf document using the jspdf library and we are using the addImage()
method to add the image.
Now if you open the index.html
file inside the browser you will see the below result