Add QR Code to PDF Java Itext Example

In this tutorial, we will provide a simple example that uses Java iText library to create a QR(Quick Response) Code for an input string.The PDF document will contain an image which can be read by any reader that supports such codes. The PDF file will contain the code for "Example QR Code Creation in Itext" string.

The basic tutorial consists of eight main steps as provided below:

1) Create a Document object which will support adding the code to the PDF document.
2) Create a PdfWriter object attaching to the Document object created in (1)
3) Open the Document object
4) Add a paragraph that summarizes the objective (This step is optional)
5) Use BarcodeQRCode class to construct the code for the input string
6) Get the QR code image created in step 5 into an Image object
7) Add the Image into the PDF document
8) Close the Document object.

The complete Java code example for creating and adding the QR code to a PDF document is provided below:

 1 import; 
 2 import com.itextpdf.text.Document;
 3 import com.itextpdf.text.pdf.PdfWriter;
 4 import com.itextpdf.text.Paragraph; 
 5 import com.itextpdf.text.Image;
 6 import com.itextpdf.text.pdf.BarcodeQRCode;
 7 import com.itextpdf.text.Rectangle;
 8 class EmbedQRCode {
 9    public static void main (String[] args) throws Exception
10    {
11         //Step - 1 :Create Document object that will hold the code
12         Document qr_code_Example = new Document(new Rectangle(360, 852));
13         // Step-2: Create PdfWriter object for the document
14         PdfWriter writer = PdfWriter.getInstance(qr_code_Example, new FileOutputStream("QR_PDF_Output.pdf"));
15         // Step -3: Open document for editing
17         //Step-4: Create New paragraph for QR Summary
18         qr_code_Example.add(new Paragraph("Wow, we created a QR Code in PDF document using iText Java"));
19         //Step-5: Create QR Code by using BarcodeQRCode Class
20         BarcodeQRCode my_code = new BarcodeQRCode("Example QR Code Creation in Itext", 1, 1, null);
21         //Step-6: Get Image corresponding to the input string
22         Image qr_image = my_code.getImage();
23         //Step-7: Stamp the QR image into the PDF document
24         qr_code_Example.add(qr_image);
25         //Step-8: Close the PDF document
26         qr_code_Example.close();
27    }
28  }

When you run this sample code, it creates a PDF document with the QR Code embedded in it. This is shown in the diagram below
QR Code Created Using iText Java Library
QR Code Created Using iText Java Library
This is a basic example for adding a QR code in PDF document. In the subsequent tutorials, we will see more advanced examples, like creating a contact object, QR code with hyperlinks etc. 

Do you have a suggestion to improve this code? Post it in the comments section of this blog. Help us to improve this code.

1 comment:

  1. how to give size and also define specific position in pdf