How to generate PDF using jsPDF and html2canvas library
Generate PDF using jsPDF and html2canvas library
In this post we will implement how we can generate PDF file of a web page using jsPDF and html2canvas library. These libraries allow us to generate PDF of web pages having html including icons, images, text, css etc. Below is the complete implementation for the same.
Follow below steps to perform this -
1. Include jsPDF and html2canvas libraries in your html page -
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>
<div class="canvas_div_pdf">
<!--Add HTML content you want to convert to PDF-->
</div>
2. Call the below function in your JS -
function getPDF(){
var HTML_Width = $(".canvas_div_pdf").width();
var HTML_Height = $(".canvas_div_pdf").height();
var top_left_margin = 15;
var PDF_Width = HTML_Width+(top_left_margin*2);
var PDF_Height = (PDF_Width*1.5)+(top_left_margin*2);
var canvas_image_width = HTML_Width;
var canvas_image_height = HTML_Height;
var totalPDFPages = Math.ceil(HTML_Height/PDF_Height)-1;
html2canvas($(".canvas_div_pdf")[0],{allowTaint:true}).then(function(canvas) {
canvas.getContext('2d');
console.log(canvas.height+" "+canvas.width);
var imgData = canvas.toDataURL("image/jpeg", 1.0);
var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin,canvas_image_width,canvas_image_height);
for (var i = 1; i <= totalPDFPages; i++) {
pdf.addPage(PDF_Width, PDF_Height);
pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height*i)+(top_left_margin*4),canvas_image_width,canvas_image_height);
}
pdf.save("HTML-Document.pdf");
});
};
3. Call the function on any event -
$("#btnPrint").click(function() {
getPDF();
});
Great blog Rajat!
ReplyDeleteJust one question. Can this be used to export SharePoint List items individually as a PDF file.