QR Code to PDF
by Purushothaman Anbazhagan
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/davidshimjs/qrcodejs/gh-pages/qrcode.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<h1>QR to PDF</h1>
<div id="qrcode"></div>
<h4>Dynamic QR</h4>
<div id="qrcode-2"></div>
<div class="action">
<button class="btn" onClick="downloadPDF()">
Download
</button>
</div>
SCSS
.action {
margin: 100px;
text-align: center;
.btn {
min-width: 183px;
height: 50px;
padding: 8px;
box-sizing: border-box;
background: beige;
}
}
JavaScript
// 1. create QR code
var qrWidth = 300;
var qrHeight = 300;
var qrcode = new QRCode("qrcode", {
text: "https://google.com",
width: qrWidth,
height: qrHeight,
colorDark: "#000000",
colorLight: "#ffffff",
correctLevel: QRCode.CorrectLevel.H
});
var qrcode2 = new QRCode("qrcode-2", {
text: "https://youtube.com",
width: 500,
height: 500,
colorDark: "#000000",
colorLight: "#ffffff",
correctLevel: QRCode.CorrectLevel.H
});
function downloadPDF() {
var doc = new jsPDF("p", "mm", "a4");
doc.setFontSize(40);
doc.text(35, 25, 'Scan the QR - 1');
//Get qr code as base64
var imageBase64 = $("#qrcode img").attr("src");
doc.addImage(imageBase64, 'JPEG', 50, 40, pxToMM(qrWidth), pxToMM(qrHeight));
doc.text(30, 140, 'Scan the QR - 2');
var anotherImageBase64 = $("#qrcode-2 img").attr("src");
//better to use promise here
getDimensionOfBase64(anotherImageBase64, function(width, height) {
doc.addImage(anotherImageBase64, 'JPEG', 35, 150, pxToMM(width), pxToMM(height));
savePdf(doc, "test-qr-to-pdf");
});
}
function savePdf(doc, name) {
doc.save(name + ".pdf");
}
function pxToMM(unit) {
//https://www.unitconverters.net/typography/pixel-x-to-millimeter.htm
//1px = 0.2645833333mm
return unit * 0.2645833333;
}
function getDimensionOfBase64(imageString, callback) {
var i = new Image();
i.onload = function() {
callback(i.width, i.height);
};
i.src = imageString;
}