In this tutorial, you will learn how to download pdf file using jspdf and html2canvas package. We will explain you how to convert HTML div content to PDF using JavaScript with css preferably.
Html2Canvas to take the image and then save pdf using Jspdf. Html2canvas captures the content of a div tag then send the canvas to jspdf to export as pdf. So, let’s follow the step by step guide on how to generate a html view page (content, table or graph) to pdf file using html2canvas and jsPdf.
Step 1: Add a Button in Blade File
First, you just add a button to download html view page which you want to download pdf file full or div id.
<div id="pdf-btns"> <button type="button" class="btn btn-primary" id="get-pdf" onclick="getPDF();">Save as PDF</button> </div>
Step 2: Update JavaScript Code
Now put the javascript code to download your html page to pdf in blade file and set your width and height to download.
function getPDF () { return html2canvas($('#budgeting-pdf'), { background: "#ffffff", onrendered: function(canvas) { var myImage = canvas.toDataURL("image/jpeg,1.0"); // Adjust width and height var imgWidth = (canvas.width * 60) / 240; var imgHeight = (canvas.height * 70) / 240; // jspdf changes var pdf = new jsPDF('p', 'mm', 'a4'); pdf.addImage(myImage, 'png', 15, 2, imgWidth, imgHeight); // 2: 19 pdf.save(`Budgeting ${$('.pdf-title').text()}.pdf`); } }); }
Step 3: Add Cdn
Now you need to add two cdn one for html2Canvas cdn and other is jspdf cdn inside body tag;
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"> </script><script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
If you want to download the html part to pdf using dompdf then click the below link:
See Also: Generate HTML to PDF in Laravel 7 Using domPdf
So, today you have learn How to generate PDF file using jsPDF library. I hope you enjoy with this tutoria;
I have fetched some inages from s3 bucket and then drawn on canvas , on pressing download button that gets added to pdf , i have used the same method but the issue after the images are loaded on page when i export pdf it is empty and after few minutes if press download it gets downloaded as desired the issue here is with dom, how to check that
Hey there are you store the images in your local matchine which you are uploaded in S3? Its easy if you download or upload any images to s3 must to update in your public or storage folder for future if the s3 server have any issue…