In This Post we will learn how we can generate qr code in apex .
Here are the steps
- Select Any QR Code Generator API . There are alot of api available over internet but in our example we use .https://barcode.tec-it.com
- Now You have two approaches either send http request to the api url and get qr code image as a blob or directly using apex or html image tag to show qr code.
- In this example we use html image tag to show qr code on visual force page .
- Create A visualforce page and render it as pdf like :
<apex:page controller="QRCodeController" showHeader="false" sidebar="false" renderAs="pdf"> <table> <tr> <td style='padding:10px; text-align:center; font-size:15px; font-family:Arial,Helvetica;'> // first approach <img src = '{!imageurl}'/> </td> </tr> </table> </apex:page>
5. Create QRCodeController :
In controller we create qr code image url each time .
Image url for barcodeit
<img src=’https://barcode.tec-it.com/barcode.ashx?data=ABC-abc-1234&code=Code128&dpi=96&dataseparator=’ alt=’Barcode Generator TEC-IT’/>
- data is the unique code to generate unique qr code each time.(for more info visit barcodeit)
This url can be different for different api
QRCodecontroller Code :
public class QRCodeController { public string imageurl{get;set;} public QRCodeController(){ string data = uniquecode();// each time we create unique code for barcode to generate unique barcode each time. imageurl = 'https://barcode.tec-it.com/barcode.ashx?data='+data+'&code=Code39&multiplebarcodes=false&translate-esc=false&unit=Fit&dpi=96&imagetype=Gif&rotation=0&color=%23000000&bgcolor=%23ffffff&qunit=Mm&quiet=0'; } public static string uniquecode() { final String chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; String guid = ''; while (guid.length() < 5) { Integer idx = Math.mod(Math.abs(Crypto.getRandomInteger()), chars.length()); guid += chars.substring(idx, idx+1); } return guid; } }
Example :
Visualforce Page : here is the visualforce page :
<apex:page controller="QRCodeController" showHeader="false" sidebar="false" renderAs="pdf"> <table> <tr> <td style='padding:10px; text-align:center; font-size:15px; font-family:Arial,Helvetica;'> <img src = '{!imageurl}'/> </td> </tr> </table> </apex:page>
Controller Class :
public class QRCodeController { public string imageurl{get;set;} public QRCodeController(){ // each time we create unique code for barcode to generate unique barcode each time. string data = uniquecode(); imageurl = 'https://barcode.tec-it.com/barcode.ashx?data='+data+'&code=Code39&multiplebarcodes=false&translate-esc=false&unit=Fit&dpi=96&imagetype=Gif&rotation=0&color=%23000000&bgcolor=%23ffffff&qunit=Mm&quiet=0'; } public static string uniquecode() { final String chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; String guid = ''; while (guid.length() < 5) { Integer idx = Math.mod(Math.abs(Crypto.getRandomInteger()), chars.length()); guid += chars.substring(idx, idx+1); } return guid; } }
OUTPUT :
Hits: 2407