Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate QR code with some text using Java?

Tags:

java

text

qr-code

I want to generate a QR code with some text (user name and event name) using Java like this:

QR code with text on top and below

This is my code and this generates only the QR code, without any additional text.

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class Create_QR {
    public static void main(String[] args) {
        try {
            String qrCodeData = "This is the text";
            String filePath = "C:\\Users\\Nirmalw\\Desktop\\Projects\\QR\\test\\test_img\\my_QR.png";
            String charset = "UTF-8"; // or "ISO-8859-1"

            Map < EncodeHintType, ErrorCorrectionLevel > hintMap = new HashMap < EncodeHintType, ErrorCorrectionLevel > ();

            hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);

            BitMatrix matrix = new MultiFormatWriter().encode(new String(qrCodeData.getBytes(charset), charset),
                    BarcodeFormat.QR_CODE, 500, 500, hintMap);

            MatrixToImageWriter.writeToFile (matrix, filePath.substring(filePath.lastIndexOf('.') + 1), new File(filePath));

            System.out.println("QR Code created successfully!");
        } catch (Exception e) {
            System.err.println(e);
        }
    }
}

If anyone knows how to generate a QR code with text above and below the code, please help me.

like image 586
Thilinna Nirmal Avatar asked Sep 29 '26 14:09

Thilinna Nirmal


2 Answers

You can generate a QR code with text in Java using Free Spire.Barcode for Java API. First, download the API's jar from this link or install it from Maven Repository:

    <repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.barcode.free</artifactId>
        <version>5.1.1</version>
    </dependency>
</dependencies>

Next, refer to the following code sample:

import com.spire.barcode.BarCodeGenerator;
import com.spire.barcode.BarCodeType;
import com.spire.barcode.BarcodeSettings;
import com.spire.barcode.QRCodeECL;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class GenerateQRCode {
    public static void main(String []args) throws IOException {
        //Instantiate a BarcodeSettings object
        BarcodeSettings settings = new BarcodeSettings();
        //Set barcode type
        settings.setType(BarCodeType.QR_Code);
        //Set barcode data
        String data = "https://stackoverflow.com/";
        settings.setData(data);
        //Set barcode module width
        settings.setX(2);
        //Set error correction level
        settings.setQRCodeECL(QRCodeECL.M);

        //Set top text
        settings.setTopText("User Name");
        //Set bottom text
        settings.setBottomText("Event Name");

        //Set text visibility
        settings.setShowText(false);
        settings.setShowTopText(true);
        settings.setShowBottomText(true);

        //Set border visibility
        settings.hasBorder(false);

        //Instantiate a BarCodeGenerator object based on the specific settings
        BarCodeGenerator barCodeGenerator = new BarCodeGenerator(settings);
        //Generate QR code image
        BufferedImage bufferedImage = barCodeGenerator.generateImage();
        //save the image to a .png file
        ImageIO.write(bufferedImage,"png",new File("QR_Code.png"));
    }
}

The following is the generated QR code image with text:

Generate QR Code with Text in Java

like image 129
Dheeraj Malik Avatar answered Oct 02 '26 05:10

Dheeraj Malik


To generate a QR code in Java, we need to use a third-party library named ZXing (Zebra Crossing). It is a popular API that allows us to process with QR code. With the help of the library, we can easily generate and read the QR code. Before moving towards the Java program, we need to add the ZXing library to the project. We can download it from the official site.

  • zxing core-3.3.0.jar
  • zxing javase-3.3.0.jar

After downloading, add it to the classpath. Or add the following dependency in pom.xml file.

<dependencies>  
<dependency>  
<groupId>com.google.zxing</groupId>  
<artifactId>core</artifactId>  
<version>3.3.0</version>  
</dependency>  
<dependency>  
<groupId>com.google.zxing</groupId>  
<artifactId>javase</artifactId>  
<version>3.3.0</version>  
</dependency>  
</dependencies>  

Let's create a Java program that generates a QR code.

GenerateQrCode.java

import java.io.File;  
import java.io.IOException;  
import java.util.HashMap;  
import java.util.Map;  
import com.google.zxing.BarcodeFormat;  
import com.google.zxing.EncodeHintType;  
import com.google.zxing.MultiFormatWriter;  
import com.google.zxing.NotFoundException;  
import com.google.zxing.WriterException;  
import com.google.zxing.client.j2se.MatrixToImageWriter;  
import com.google.zxing.common.BitMatrix;  
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;  
public class GenerateQRCode  
{  
//static function that creates QR Code  
public static void generateQRcode(String data, String path, String charset, Map map, int h, int w) throws WriterException, IOException  
{  
//the BitMatrix class represents the 2D matrix of bits  
//MultiFormatWriter is a factory class that finds the appropriate Writer subclass for the BarcodeFormat requested and encodes the barcode with the supplied contents.  
BitMatrix matrix = new MultiFormatWriter().encode(new String(data.getBytes(charset), charset), BarcodeFormat.QR_CODE, w, h);  
MatrixToImageWriter.writeToFile(matrix, path.substring(path.lastIndexOf('.') + 1), new File(path));  
}  
//main() method  
public static void main(String args[]) throws WriterException, IOException, NotFoundException  
{  
//data that we want to store in the QR code  
String str= "THE HABIT OF PERSISTENCE IS THE HABIT OF VICTORY.";  
//path where we want to get QR Code  
String path = "C:\\Users\\Anubhav\\Desktop\\QRDemo\\Quote.png";  
//Encoding charset to be used  
String charset = "UTF-8";  
Map<EncodeHintType, ErrorCorrectionLevel> hashMap = new HashMap<EncodeHintType, ErrorCorrectionLevel>();  
//generates QR code with Low level(L) error correction capability  
hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);  
//invoking the user-defined method that creates the QR code  
generateQRcode(str, path, charset, hashMap, 200, 200);//increase or decrease height and width accodingly   
//prints if the QR code is generated   
System.out.println("QR Code created successfully.");  
}  
}  
like image 26
Ngirimana Safari Schadrack Avatar answered Oct 02 '26 04:10

Ngirimana Safari Schadrack