vCard Contact - QR Code in Java Example

In the previous part of this series, we described how to create contact event based QR codes in Java using iText and Oracle Advanced Imaging API. We use MECARD format to generate QR code for that example. In this tutorial, we will provide examples to produce the same QR code using the vCard format. vCard is the popular format to store contact information and at the end of this section, you will see how easy it is to generate QR code with this vCard format. 

Detailed explanation of QR code functionality / program is outside the scope of this section. You should refer to the related post section at the bottom of this post, if you are keen to understand the code in depth. We will cover the following post examples in this post:

  • Create a PDF document with QR Code, the code holding contact details in vCard format.
  • Create a QR code image file holding contact details information.
  • Generate a HTTP Servlet based code that will accept user information over a form and generate the code for us. While doing this, the servlet will convert the entered information into vCard format before passing it to the code library to generate the code.
Example -1 : PDF document with QR Code
Example -2 Image file in Java based on the inputs

 1 import java.io.FileOutputStream; 
 2 import com.itextpdf.text.Document;
 3 import com.itextpdf.text.pdf.PdfWriter;
 4 import com.itextpdf.text.Paragraph; 
 5 import com.itextpdf.text.pdf.BarcodeQRCode;
 6 import com.itextpdf.text.Rectangle;
 7 import javax.imageio.ImageIO;
 8 import java.io.File;
 9 import java.io.IOException;
10 import java.awt.image.BufferedImage;
11 import java.awt.Color;
12 import java.awt.Image;
13 import javax.media.jai.operator.AWTImageDescriptor; //Java advanced Imaging library
14 import javax.media.jai.RenderedOp; // Java advanced imaging library
15 class QRCodeContactvCard {
16    public static void main (String[] args) throws Exception
17    {
18         //Create Contact QR Code in vCard format.
19         String header_info="BEGIN:VCARD";
20         //vCard format has a new line separator at the end of the code, we only need to put that later
21         String Contact_name="N:Thinktibits"; //N: is the prefix for MECARD Name
22         String Contact_company="ORG:MyCompany"; //ORG: is the prefix for company
23         String phone_number="TEL:123456";//TEL: is the prefix for telephone number
24         String website="URL:thinktibits.blogspot.com";//URL: is the prefix for website
25         String contact_email="EMAIL:123@abc.com";//EMAIL: is the prefix for email address
26         String address="ADR:Unit Street Address";//ADR: is the prefix for address
27         String notes="NOTE:General Contact notes";//NOTE: is the prefix for notes.
28         String footer="END:VCARD";
29         //Construct one final contact string in MECARD format
30         String final_vCard=String.format("%s%n%s%n%s%n%s%n%s%n%s%n%s%n%s", header_info,Contact_name, Contact_company, phone_number, website,contact_email,address,notes,footer);
31         //Create Contact event QR Code
32         BarcodeQRCode my_code = new BarcodeQRCode(final_vCard, 1, 1, null);
33         /* Add QR Code to the PDF document */
34         Document vCard_QR_Code = new Document(new Rectangle(360, 852));
35         PdfWriter writer = PdfWriter.getInstance(vCard_QR_Code, new FileOutputStream("My_contact_Info.pdf"));
36         vCard_QR_Code.open();      
37         vCard_QR_Code.add(new Paragraph("Tutorial to create QR Code for Contact Event (vCard format) in Java Using iText Library"));        
38         vCard_QR_Code.add(my_code.getImage());        
39         vCard_QR_Code.close();
40         /* Create QR Code as a PNG Image file */
41         Image qr_awt_image = my_code.createAwtImage(Color.BLACK,Color.WHITE);        
42         AWTImageDescriptor converter=new AWTImageDescriptor();
43         try {           
44         ImageIO.write(converter.create(qr_awt_image,null), "png",new File("QRCodeImage.png"));        
45         }
46          catch (IOException e) {
47                 e.printStackTrace();
48         }
49    }
50  }
This example produces the following QR code as shown below

vCard based QR Code Created in Java using iText  library
vCard based QR Code Created in Java using iText  library
The PDF document that is produced with the QR Code for the same example above is shown below:

QR Codes in PDF - vCard format
Clipped version of PDF file with QR Code created using the Example
The vCard format looks more dense when compared with the MECARD format. The general recommendation is to use the MECARD format to generate QR codes rather than using the vCard format.

Example -3: HTTP Servlet based QR Code (vCard format)

We now provide a modified version of the HTTP servlet code to generate the same code in vCard format.
 1 import java.io.IOException;
 2 import java.io.OutputStream;
 3 import javax.servlet.ServletException;
 4 import javax.servlet.http.HttpServlet;
 5 import javax.servlet.http.HttpServletRequest;
 6 import javax.servlet.http.HttpServletResponse;
 7 import java.io.FileOutputStream; 
 8 import javax.imageio.ImageIO;
 9 import java.net.URL;
10 import java.awt.image.BufferedImage;
11 import com.itextpdf.text.pdf.BarcodeQRCode;
12 import com.itextpdf.text.Document;
13 import com.itextpdf.text.Paragraph;
14 import com.itextpdf.text.pdf.PdfWriter;
15 import com.itextpdf.text.DocumentException;
16 import java.awt.Color;
17 import java.lang.Integer;
18 import java.awt.Image;
19 import javax.media.jai.operator.AWTImageDescriptor; 
20 import javax.media.jai.RenderedOp;
21 
22 public class QRCodeContactServletvCard extends HttpServlet {
23 public QRCodeContactServletvCard() {
24 /* No code here */
25 }
26 public void doGet(HttpServletRequest request, HttpServletResponse response)
27 throws ServletException, IOException {
28         OutputStream out = response.getOutputStream(); /* Get the output stream from the response object */
29         try {
30         int selectedItem;
31         //Find out if the QR code needs to be generated as a PDF file or a PNG image    
32         selectedItem=Integer.parseInt(request.getParameter("element_8"));
33                 
34         // set vCard attributes based on user inputs
35         String header_info="BEGIN:VCARD";
36         String Contact_name="N:"+request.getParameter("element_1_1")+request.getParameter("element_1_2"); //N: is the prefix for vCard Name
37         String Contact_company="ORG:"+request.getParameter("element_7"); //ORG: is the prefix for company
38         String phone_number="TEL:"+request.getParameter("element_3_1")+request.getParameter("element_3_2")+request.getParameter("element_3_3");//TEL: is the prefix for telephone number
39         String website="URL:"+request.getParameter("element_4");//URL: is the prefix for website
40         String contact_email="EMAIL:"+request.getParameter("element_5");//EMAIL: is the prefix for email address
41         String address="ADR:"+request.getParameter("element_2_1")+request.getParameter("element_2_2")+request.getParameter("element_2_3")+request.getParameter("element_2_4")+request.getParameter("element_2_5")+request.getParameter("element_2_6");//ADR: is the prefix for address
42         String notes="NOTE:"+request.getParameter("element_6");//NOTE: is the prefix for notes.
43         String footer="END:VCARD";
44         //Construct one final contact string in vCard format
45         String my_vCard=String.format("%s%n%s%n%s%n%s%n%s%n%s%n%s%n%s%n%s", header_info,Contact_name, Contact_company, phone_number, website,contact_email,address,notes,footer);
46         
47         //Invoke BarcodeQRCode class to create QR Code for the calendar
48         BarcodeQRCode my_code = new BarcodeQRCode(my_vCard, 1, 1, null);
49         
50         //PDF option is selected. Generate QR code into a PDF document and send this response to the output.
51         if (selectedItem==1) {
52                 response.setContentType("application/pdf");
53                 Document document = new Document();            
54                 PdfWriter.getInstance(document, out);
55                 document.open();
56                 document.add(new Paragraph("QR Code - vCard Contact - Java Servlet Example - PDF generation "));                
57                 document.add(my_code.getImage());
58                 document.close();
59         }
60         
61         //PNG image is selected. Generate QR Code as PNG image in Java and send this response to the output.
62         if (selectedItem==2) {
63         response.setContentType("image/png"); /* Set the HTTP Response Type */
64         java.awt.Image qr_awt_image = my_code.createAwtImage(Color.BLACK,Color.WHITE);
65         AWTImageDescriptor converter=new AWTImageDescriptor();
66         ImageIO.write(converter.create(qr_awt_image,null), "png",out);
67         }       
68                 
69         }
70         catch (Exception e) {
71                 System.err.println(e.toString()); /* Throw exceptions to log files */
72         }
73         finally {
74                 out.close();/* Close the output stream */
75         }
76         }
77 
78 public void doPost(HttpServletRequest request,
79                      HttpServletResponse response)
80       throws ServletException, IOException {
81     doGet(request, response);
82   }
83 }  
You can use the same form that we used in the previous tutorial. What more, you can even provide an option to the user to generate QR code in vCard or MECARD format and parse that response in the servlet code.

A side by side comparison of QR codes produced in vCard and MECARD  format for the same input information is provided below:

Side by Side Comparison - MeCard Vs vCard
Left- MECARD, Right - vCard format - comparison
Hope you liked the tutorial series on QR Code contact generation in various formats. In the next tutorial we will describe how to embed Wi Fi network information inside a QR code and discuss various possible options in this, and generate them in Java. If you have a comment on this post, post it in the comments section.

1 comment:

  1. I am having error BarcodeQRCode and AwtImageDescriptor can't resolve to a type in java where to obtain that library?

    ReplyDelete