Generate Qr Code in Spring boot + Thymeleaf application with ZXing - Example

Hello everyone, today we will learn how to generate the Qr Code in Spring boot + Thymeleaf sample application with ZXing.

Technology Used

  • JDK 17
  • Spring Boot 2.7.0
  • Thymeleaf
  • ZXing library 3.5.0
  • Maven


Final Project Directory



Maven[Pom.xml]

ZXing Core: Core barcode encoding/decoding library
ZXing Java SE extensions: Java SE-specific extensions to the core ZXing library
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath />
</parent>
<groupId>com.knf.dev.demo</groupId>
<artifactId>spring-boot-thymeleaf-zxing-qrcode</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-thymeleaf-zxing-qrcode</name>

<properties>
<java.version>17</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.5.0</version>
</dependency>

</
dependencies>

<
build>
<
plugins>
<
plugin>
<
groupId>org.springframework.boot</groupId>
<
artifactId>spring-boot-maven-plugin</artifactId>
</
plugin>
</
plugins>
</
build>
</
project>



Create QR code service

package com.knf.dev.demo.service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

public class QRCodeService {

public static byte[] getQRCode(String text, int width, int height)
throws WriterException, IOException {

QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter
.encode(text, BarcodeFormat.QR_CODE,
width, height);
ByteArrayOutputStream pngOutputStream =
new ByteArrayOutputStream();
MatrixToImageConfig con = new MatrixToImageConfig
(0xFF000002, 0xFF04B4AE);
MatrixToImageWriter.writeToStream(bitMatrix,
"PNG", pngOutputStream, con);
byte[] pngData = pngOutputStream.toByteArray();

return pngData;
}
}



Create QR Code Controller

package com.knf.dev.demo.controller;

import java.io.IOException;
import java.util.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.google.zxing.WriterException;
import com.knf.dev.demo.service.QRCodeService;

@Controller
public class QRCodeController {

@GetMapping("/")
public String home(Model model) {

return "index";
}

@PostMapping("/generate")
public String getQRCode(Model model,
@RequestParam(value = "text",defaultValue = "Knf") String text) {

byte[] image = new byte[0];

try {
// Generate and Return Qr Code in Byte Array
image = QRCodeService.getQRCode(text, 250, 250);

} catch (WriterException | IOException e) {
e.printStackTrace();
}
// Convert Byte Array into Base64 Encode String
String qrcode = Base64.getEncoder()
.encodeToString(image);
model.addAttribute("qrcode", qrcode);

return "index";
}
}



index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Knf</title>
<link rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
<script
src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js">

</script>

</head>
<body>
<h2 style="text-align: center;">Generate Qr Code with
ZXing + Spring boot + Thymeleaf</h2>

<div class="container my-5">
<form method="POST" action="/generate">
<div class="form-group row">
<label for="exampleFormControlInput1">Text</label>
<input name="text" type="text" class="form-control"
id="exampleFormControlInput1"
placeholder="Enter the text here">

</div>
<div class="form-group row">
<input class="btn btn-info" type="submit"
value="Generate QR Code>>" />
</div>

</form>
<div th:if="${qrcode}">

<div class="d-flex justify-content-center">
<div class="card" >
<div style="text-align: center;" class="card-header">
<h5>Scan the QR Code</h5></div>
<div class="card-body">
<img th:src="${'data:image/png;base64,
' + qrcode}" alt=""
height="200" width="200">
</div>
</div>
</div>
</div>
</div>

</body>
</html>



Spring Boot Main Driver

package com.knf.dev.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class QRCodeDemoApplication {

public static void main(String[] args) {
SpringApplication.run(QRCodeDemoApplication.class, args);
}
}


Download the complete source code - click here                               

Local Setup and Run the application

Step1: Download or clone the source code from GitHub to the local machine - Click here

Step 2: mvn clean install

Step 3: Run the Spring Boot application - mvn spring-boot:run

From the browser call the endpoint http://localhost:8080

All the best!

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Custom Exception Handling in Quarkus REST API

ReactJS, Spring Boot JWT Authentication Example

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring Webflux File Download Example

Node JS mini projects with source code - free download