jsPDF Tutorial Part 3: Exactly Capture HTML page to PDF – Howtoshtab – how to, lifehacks, tips and tricks

In this video, we’re going to capture the html page and generate the PDF for user to download when clicking the link The goal is to make our page appear exactly on the PDF file. This can be accomplished by using html2canvas to take the screenshot of our page and place the image in the PDF file This is HTML file of the earlier page which I’ve put some simple text box, button and image. And we have a PDF download link that will call the javascript genPDF() function when clicked I’ve also included jsPDF and html2canvas js files. You can find the link to the libraries in the video description section below The first step is to call html2canvas. We need to pass an element that we’d like to take a screenshot. I’m going to pass document.body to capture the entire page Next step is to define a callback event after the screenshot has been taken.

The event name is “onrendered” The canvas object will be provided to the calback function. (Our captured screenshot) We’ll use “toDataURL” function to retrieve the screenshot We’ll specifiy the image type as “image/png” Next, we’ll create a jsPDF object as usual And we’ll use “addImage” to add the screenshot to the jsPDF object with 20px margin. And the final step is the save the PDF file. Success! It’s also possible if you only need to capture some part of the HTML page or some element Just pass the needed element instead of the entire body in the html2canvas I’ll pass our “testDiv” this time You’ll see that the header and download link are not included in the PDF file. Please noted that the html2canvas can’t capture any that are hotlink or not hosted in the same url of your site.

Thank you for watching! Subscribe us for more tutorial!.

You may also like