Last active
July 3, 2022 10:00
-
-
Save sohelrana820/5b545e005f683ae29011e73e1bae91b6 to your computer and use it in GitHub Desktop.
HTML to PDF using jQuery
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>HTML to PDF</title> | |
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"> | |
</head> | |
<body> | |
<main> | |
<div class="container py-4"> | |
<div class="mb-3 text-center"> | |
<button class="btn btn-primary btn-lg" id="invoice_download_btn" type="button">Download PDF</button> | |
</div> | |
<div class="p-5 mb-4 bg-light rounded-3" id="invoice_wrapper"> | |
<div class="container-fluid py-5"> | |
<h1 class="display-5 fw-bold">HTML to PDF</h1> | |
<p class="col-md-8 fs-4">Using a series of utilities, you can create this jumbotron, just like the one in previous versions of Bootstrap. Check out the examples below for how you can remix and restyle it to your liking.</p> | |
</div> | |
</div> | |
</div> | |
</main> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.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> | |
<script> | |
/** | |
* Generate HTML to PDF | |
* | |
* @constructor | |
*/ | |
function CreatePDFfromHTML(domElement) { | |
var contentWidth = $(domElement).width(); | |
var contentHeight = $(domElement).height(); | |
var topTeftMargin = 10; | |
var pdfWidth = contentWidth+(topTeftMargin*2); | |
var pdfHeight = (pdfWidth*1.5)+(topTeftMargin*2); | |
var canvasImageWidth = contentWidth; | |
var canvasImageHeight = contentHeight; | |
var totalPDFPages = Math.ceil(contentHeight/pdfHeight)-1; | |
html2canvas($(domElement)[0],{allowTaint:true}).then(function(canvas) { | |
canvas.getContext('2d'); | |
var imgData = canvas.toDataURL("image/jpeg", 1.0); | |
var pdf = new jsPDF('p', 'pt', [pdfWidth, pdfHeight]); | |
pdf.addImage(imgData, 'JPG', topTeftMargin, topTeftMargin,canvasImageWidth,canvasImageHeight); | |
for (var i = 1; i <= totalPDFPages; i++) { | |
pdf.addPage(pdfWidth, pdfHeight); | |
pdf.addImage(imgData, 'JPG', topTeftMargin, -(pdfHeight*i)+(topTeftMargin*4),canvasImageWidth,canvasImageHeight); | |
} | |
pdf.save("html-to-pdf.pdf"); | |
}); | |
} | |
$('#invoice_download_btn').click(function () { | |
CreatePDFfromHTML("#invoice_wrapper"); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment