Generating QR Codes in Java Applications

To create QR codes in Java applications, you can utilize the ZXing library, which provides comprehensive support for barcode generation and scanning. Below are two implementations: one for standalone applications and another suitable for web environments.

Standalone Application Implementation

First, include the ZXing library in your project. For manual dependency management, download the core library jar file and add it to your classpath.

import java.io.File;
import java.nio.file.Path;
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 QRGenerator {

    public static void main(String[] args) {
        String data = "https://www.example.com/catalog.html";
        String outputFile = "F:\\qr_output.png";
        
        if (generateQR(data, outputFile)) {
            System.out.println("QR code generated successfully");
        } else {
            System.out.println("Failed to generate QR code");
        }
    }
    
    private static boolean generateQR(String textData, String filePath) {
        int imgWidth = 300;
        int imgHeight = 300;
        String imageFormat = "png";
        
        Map<EncodeHintType, Object> configHints = new HashMap<>();
        configHints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        configHints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        configHints.put(EncodeHintType.MARGIN, 2);
        
        try {
            BitMatrix matrix = new MultiFormatWriter()
                .encode(textData, BarcodeFormat.QR_CODE, imgWidth, imgHeight, configHints);
            
            Path outputFilePath = new File(filePath).toPath();
            MatrixToImageWriter.writeToPath(matrix, imageFormat, outputFilePath);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }
}

Web Application Implementation

For web-based applications, integrate the ZXing dependencies through Maven:

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

In a web controller method, you can dynamically genearte and serve QR codes:

public void generateAndDownload(Long projectId, HttpServletRequest req, HttpServletResponse resp) throws Exception {
    Project selectedProject = JSON.parseObject(
        JSONObject.toJSONString(fetchProjectDetails(projectId).getData(), true), 
        Project.class
    );
    
    String qrContent = selectedProject.getPageUrl() + "&" + selectedProject.getProjectID();
    
    Map<EncodeHintType, Object> encodingParams = new HashMap<>();
    encodingParams.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    encodingParams.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
    
    BitMatrix qrMatrix = new MultiFormatWriter()
        .encode(qrContent, BarcodeFormat.QR_CODE, 200, 200, encodingParams);
    
    resp.setHeader("Content-Type", "application/octet-stream");
    resp.setHeader("Content-Disposition", 
        "attachment;filename=" + selectedProject.getProjectID() + ".png");
    
    OutputStream responseStream = resp.getOutputStream();
    MatrixToImageWriter.writeToStream(qrMatrix, "png", responseStream);
    responseStream.flush();
    responseStream.close();
}

Tags: java zxing qr-code barcode-generation Maven

Posted on Sun, 10 May 2026 02:50:33 +0000 by ignite