How to generate PDF from HTML using Javascript
In this tutorial, we are going to learn about How to generate PDF from HTML using Javascript.
So, let's get started...
Generate PDF from HTML
Step:1: Add Jquery, JsPDF, and html2Canvas library, using the below links:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>
Step:2 : Add HTML Code
<button id="clickbind">Click</button>
<div id="content" class="html-content">
<table>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
</table>
</div>
Step:3 Add Javascript code to generate and download PDF:
<script>
function CreatePDFfromHTML() {
var HTML_Width = $(".html-content").width();
var HTML_Height = $(".html-content").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($(".html-content")[0], {
allowTaint: true,
useCORS: true
}).then(function (canvas) {
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("Your_PDF_Name.pdf");
});
}
var element = document.getElementById("clickbind");
element.addEventListener("click", CreatePDFfromHTML);
</script>