Spring Boot Web Generate and Display QR Code as Base64 String

Tags: zxing zxing QRCodeWriter generate QR code QR code base64 Base64 QR Code Spring Boot QR Code Java QR Code

In this Java Spring Boot tutorial we learn how implement a web application which generate QR code as a base64 string using Spring Boot with ZXing Core and ZXing Java SE Extensions libraries.

Table of contents

  1. Create New Spring Boot Web Project To Generate Base64 QR Code
  2. Add ZXing Core and ZXing Java SE Extensions libraries to the Spring Boot project
  3. Implement QR Code Generator Service Java Class
  4. Implement Controller to Generate and Display Base64 QR Code
  5. Implement HTML to View Base64 QR Code String
  6. Complete Source Code and Running Web Application
  7. Download Complete Source Code

Create New Spring Boot Web Project To Generate Base64 QR Code

Open IntelliJ IDEA, select the menu File > New > Project. (or click on New Project button at IntelliJ Welcome dialog)

On the New Project dialog, select Spring Initializr and click Next button.

Spring Boot Web Generate and Display QR Code as Base64 String

On the Spring Initializr Project Settings dialog input the new project information as below and click Next button.

  • Group: dev.simplesolution
  • Artifact: spring-boot-web-qr-code-base64
  • Type: Gradle
  • Language: Java
  • Version: 1.0.0
  • Name: spring-boot-web-qr-code-base64
  • Description: Spring Boot Web Generate QR Code Base64 String
  • Package: dev.simplesolution.webqrcodebase64

Spring Boot Web Generate and Display QR Code as Base64 String

On the Dependencies dialog, select below dependencies and click Next button.

  • Spring Web
  • Thymeleaf

Spring Boot Web Generate and Display QR Code as Base64 String

Select the location for your project and click Finish button to create new Spring Boot project.

Spring Boot Web Generate and Display QR Code as Base64 String

Add ZXing Core and ZXing Java SE Extensions libraries to the Spring Boot project

To generate the QR code image we use the ZXing library.

To use ZXing library in the Gradle project, add the following dependency to the build.gradle file.

implementation group: 'com.google.zxing', name: 'core', version: '3.4.1'
implementation group: 'com.google.zxing', name: 'javase', version: '3.4.1'

If you are using Maven build, add the following dependency to the pom.xml file.

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

Implement QR Code Generator Service Java Class

At this step we create Java classes to generate QR code and encode it to a Base64 String.

Create a new Java package named dev.simplesolution.webqrcodebase64.service and create a new Java interface named QRCodeGeneratorService as following code.

java/dev/simplesolution/webqrcodebase64/service/QRCodeGeneratorService.java

package dev.simplesolution.webqrcodebase64.service;

public interface QRCodeGeneratorService {
    String generateQrCodeBase64(String qrCodeContentToGenerate, int width, int height);
}

Create a new Java package named dev.simplesolution.webqrcodebase64.service.impl and implement a new class named QRCodeGeneratorServiceImpl as below Java code.

java/dev/simplesolution/webqrcodebase64/service/impl/QRCodeGeneratorServiceImpl.java

package dev.simplesolution.webqrcodebase64.service.impl;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import dev.simplesolution.webqrcodebase64.service.QRCodeGeneratorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

@Service
public class QRCodeGeneratorServiceImpl implements QRCodeGeneratorService {

    private Logger logger = LoggerFactory.getLogger(QRCodeGeneratorServiceImpl.class);

    @Override
    public String generateQrCodeBase64(String qrCodeContentToGenerate, int width, int height) {
        try {
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(qrCodeContentToGenerate, BarcodeFormat.QR_CODE, width, height);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", byteArrayOutputStream);
            String qrCodeBase64 = Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
            return qrCodeBase64;
        } catch (WriterException ex) {
            logger.error("Error during generate QR Code", ex);
        } catch (IOException ex) {
            logger.error("Error during generate QR Code", ex);
        }
        return null;
    }

}

Implement Controller to Generate and Display Base64 QR Code

At this step we implement a new controller to expose a GET endpoint which show a form which allow user input content to generate QR Code, and a POST endpoint to handle generating Base64 String QR Code and display it to HTML view.

Create a new Java package named dev.simplesolution.webqrcodebase64.controller

Add a new Java class named QRCodeController as following code.

java/dev/simplesolution/webqrcodebase64/controller/QRCodeController.java

package dev.simplesolution.webqrcodebase64.controller;

import dev.simplesolution.webqrcodebase64.service.QRCodeGeneratorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class QRCodeController {
    private static final int WIDTH = 500;
    private static final int HEIGHT = 500;

    @Autowired
    private QRCodeGeneratorService qrCodeGeneratorService;

    @GetMapping("/")
    public String index() {
        return "index";
    }

    @PostMapping("/generateQrCode")
    public String generateQrCode(String contentToGenerate, Model model) {
        String qrCodeBase64 = qrCodeGeneratorService.generateQrCodeBase64(contentToGenerate, WIDTH, HEIGHT);
        model.addAttribute("qrCodeBase64", qrCodeBase64);
        return "qr-code";
    }
}

Implement HTML to View Base64 QR Code String

At this step we add new HTML views below under resources/templates/ directory.

  • index.html to show the the form which allow user input a string to encode into QR code.
  • qr-code.html to show the base64 QR code string as well as the image of QR code.

resources/templates/index.html

<html xmlns:th="https://www.thymeleaf.org">
<head>
    <title>Spring Boot Web Generate QR Code Base64 String</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <h1>Generate QR Code Base64 String</h1>
    <form method="POST" enctype="multipart/form-data" action="/generateQrCode">
        <div class="mb-3">
            <label for="contentToGenerate" class="form-label">Enter your content to generate QR code base64 string</label>
            <input type="text" class="form-control form-control-lg" id="contentToGenerate" name="contentToGenerate" required>
        </div>
        <div class="mb-3">
            <button type="submit" class="btn btn-primary">Generate QR Code Base64</button>
        </div>
    </form>
</div>
</body>
</html>

resources/templates/qr-code.html

<html xmlns:th="https://www.thymeleaf.org">
<head>
    <title>Spring Boot Web Generate QR Code Base64 String</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <a href="/" class="btn btn-link">Back to home</a>
    <br />
    <h1>QR Code in Base64 String</h1>
    <p th:text="${qrCodeBase64}" style="word-break: break-all"></p>
    <h1>Show Image of QR Code Base64 String</h1>
    <img th:src="'data:image/png;base64, ' + ${qrCodeBase64}" />
</div>
</body>
</html>

Complete Source Code and Running Web Application

We have finished the Spring Boot web application with the source code structure as below screenshot.

Spring Boot Web Generate and Display QR Code as Base64 String

Run the Spring Boot application and open the URL http://localhost:8080/ on your browser to access the web page as the screenshot below.

Spring Boot Web Generate and Display QR Code as Base64 String

Input the text you want to generate base64 QR code string, and click the button Generate QR Code Base64 to get the result as the following screenshot.

Spring Boot Web Generate and Display QR Code as Base64 String

Download Complete Source Code

The source code in this article can be found at: github.com/simplesolutiondev/spring-boot-web-qr-code-base64

or clone at:

git clone https://github.com/simplesolutiondev/spring-boot-web-qr-code-base64.git

or download at:

Download Source Code

Happy Coding 😊

Spring Boot Rest API Generate QR Code

Spring Boot Generate QR Code as Base64 String

Spring Boot Generate QR Code Image Files

Spring Boot Web Upload and Read QR Code Image

Spring Boot Web Generate and Display QR Code

Read QR Code from Image File or Base64 String in Java using ZXing

Generate QR Code in Java using ZXing