QR Code Java Servlet Example Tutorial - PDF PNG Outputs

This is part 3 of our quest to create QR code through Java implementation. In this part, we will provide a HTTP servlet example program in Java that can generate a QR code based on user inputs. We want to create a QR code calendar object based on user inputs. In order to create a QR code servlet, we need to do the following:

Note: 
The tutorial assumes you know how to create a servlet and do the configuration in Tomcat to make it work. If not, I would suggest you to read our servlet configuration tutorial first..

I would strongly recommend you to read our part 1 and part 2 tutorials, that explained the basis of calendar based QR codes.

Create QR Code in PDF document
Create QR Code using Java

1) Create a HTML form that will accept the input for calendar fields. We need to create a form with the following fields:

a) Event Summary
b) Event Start Date
c) Event End Date
d) Event location
e) Event Description
f) Generate QR Code output as (options to create QR code into PDF file / or generate QR Code PNG image)

There are surplus of resources available on the internet to create the HTML form. This tutorial is focussed on  providing a servlet example. So, we will only provide the form that we will use for the tutorial below

HTML Form to invoke the servlet
HTML Form to invoke the servlet - to create QR Code
The form needs to have a "POST" action defined, which will invoke the servlet.

2) Use the working servlet example code below to support this HTML form. Fully working and you can use it to get the output as PDF or PNG image on the screen. We will be using iText library to create QR code and Java advanced Imaging API to generate PNG image. The code is commented for your understanding:

 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 QRCodeServlet extends HttpServlet {
23 public QRCodeServlet() {
24 /* No code in the constructor for this demonstration */
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_6"));
33                 
34         //Get Calendar QR Code attributes and construct a final calendar string     
35         String begin="BEGIN:VEVENT";
36         String summary="SUMMARY:"+request.getParameter("element_1");
37         String startdate="DTSTART;VALUE=DATE:"+request.getParameter("element_2_3")+request.getParameter("element_2_1")+request.getParameter("element_2_2");
38         String enddate="DTEND;VALUE=DATE:"+request.getParameter("element_3_3")+request.getParameter("element_3_1")+request.getParameter("element_3_2");
39         String location="LOCATION:"+request.getParameter("element_4");
40         String description="DESCRIPTION:"+request.getParameter("element_5");
41         String endevent="END:VEVENT";           
42         String finala=String.format("%s%n%s%n%s%n%s%n%s%n%s%n%s%n", begin, summary, startdate, enddate,location,description,endevent);
43                 
44         //Invoke BarcodeQRCode class to create QR Code for the calendar
45         BarcodeQRCode my_code = new BarcodeQRCode(finala, 1, 1, null);
46         
47         //PDF option is selected. Generate QR code into a PDF docuement and send this response to the output.
48         if (selectedItem==1) {
49                 response.setContentType("application/pdf");
50                 Document document = new Document();            
51                 PdfWriter.getInstance(document, out);
52                 document.open();
53                 document.add(new Paragraph("QR Code - Itext PDF - Calender - HTTP Servlet Example"));           
54                 document.add(my_code.getImage());
55                 document.close();
56         }
57         
58         //PNG image is selected. Generate QR Code as PNG image in Java and send this response to the output.
59         if (selectedItem==2) {
60         response.setContentType("image/png"); /* Set the HTTP Response Type */
61         java.awt.Image qr_awt_image = my_code.createAwtImage(Color.BLACK,Color.WHITE);
62         AWTImageDescriptor converter=new AWTImageDescriptor();
63         ImageIO.write(converter.create(qr_awt_image,null), "png",out);
64         }       
65                 
66         }
67         catch (Exception e) {
68                 System.err.println(e.toString()); /* Throw exceptions to log files */
69         }
70         finally {
71                 out.close();/* Close the output stream */
72         }
73         }
74 
75 public void doPost(HttpServletRequest request,
76                      HttpServletResponse response)
77       throws ServletException, IOException {
78     doGet(request, response);
79   }
80 }  
This code works like a charm! You will have a fully working Java Servlet code which can accept user inputs and generate QR code (calendar based one) on the output. If you want to download the HTML form code used in this example, you can get it here. Make sure you edit the form to support your server configuration
You can spend some effort to make this code more robust and handle validations as per your requirement. If you have a suggestion or found a bug on this code, please do report in the comments section so that we can look into it.

1 comment:

  1. Great tutorial. Now I know how to create QR code using servlet.

    ReplyDelete