So, our goal is to generate a PDF using the jsPDF library. In the PDF, we need to have a QR code. When the QR code is scanned it takes the user to a particular URL. Let us see how we can accomplish all this.
Part A: Generating A QR Code In JavaScript
To do this, we will be using the QRCode.js library. It's maintained by davidshimjs.
Below is a github gist with everything you need to do:
Add the JS file to your code. Here is the CDN URL: https://cdn.jsdelivr.net/gh/davidshimjs/qrcodejs/qrcode.min.js
Might be a good idea to add it to your project folder instead of simply linking.
<script src="https://cdn.jsdelivr.net/gh/davidshimjs/qrcodejs/qrcode.min.js"></script>
<div id="qr_code">
</div>
Put in the text you need to convert into your QR code instead of "###REPLACE MEEEE###"
var qrcode = new QRCode("qr_code", {
text: "###REPLACE MEEEE###",
width: 128,
height: 128,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
});
Thats it. You should see the QR code in the div.
Here is a link to a JS fiddle so that you can see it in action.
Part B: Using jsPDF to Generate A PDF With The Generated QR Code
The plan is simple:
- We add the jsPDF CDN url.
- Create a new JS document.
- Get the "base64version" of the generated QR code using some Javascript.
- Use the "addImage" method to add the QR Code to the desired location in the document.
Let's look at some code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.debug.js"></script>
<script src="https://cdn.jsdelivr.net/gh/davidshimjs/qrcodejs/qrcode.min.js"></script>
<div id="qr_code">
</div>
var qrcode = new QRCode("qr_code", {
text: "https://cravecookie.com/",
width: 128,
height: 128,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
});
var pdf = new jsPDF({
orientation: "landscape",
unit: "mm",
format: [84, 41]
});
pdf.setFontSize(15);
pdf.text('Crave Cookie', 43, 20);
pdf.setFontSize(10);
pdf.text('Scan For Menu', 43, 25);
let base64Image = $('#qr_code img').attr('src');
pdf.addImage(base64Image, 'png', 0, 0, 40, 40);
Let us look at a working codepen.
Part C: There is a better way than all this!
We have developed a better way to generate PDFs. It's a simple drag and drop builder with QR Code support and many other things.
Top comments (2)
have you tried pdfmake?