[JAVA] Generate barcode with Spring Boot

things to do

I want to create a one-dimensional barcode with the values entered in the form You can create barcodes and QR codes using a library called ZXing. https://github.com/zxing/zxing

This time, it is assumed that a one-dimensional barcode (CODE_39) will be output on the detail screen.

Addition of ZXing library

Add ZXing library to pom.xml Specify javase when developing with Java SE Specify android for development on Android Use commons-codec for Base64 encoding separately from Zxing library

pom.xml



<dependencies>
	<dependency>
		<groupId>com.google.zxing</groupId>
		<artifactId>javase</artifactId>
		<version>3.4.0</version>
	</dependency>
	<devendency>
		<groupId>com.google.zxing</groupId>
		<artifactId>core</artifactId>
		<version>3.4.0</version>		
	</devendency>
	<devendency>
		<groupId>commons-codec</groupId>
		<artifactId>commons-codec</artifactId>
		<version>1.10</version>
	</devendency>
</dependencies>

Preparation

Prepare Entity and Repository

UsersEntity.java


@Entity
@Table(name="Users")
public class UsersEntity{
  @Id
  private Integer id;
  private String name;

  public Integer getId(){
    return id;
  }

  public String getName(){
    return name;
  }
}

UsersRepository.java


import com.example.entities.UsersEntity;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UsersRepository extends JpaRepository<UsersEntity, Integer>{
}

Describe Controller

It is assumed that there is a list screen and a detail screen, and a barcode is output on the detail screen.

UsersController.java


Controller
public class UsersController {
	@Autowired
	private UsersRepository usersRepository;

	@RequestMapping("/user/index")
	public String index(Model model) {
		List<UsersEntity> users = usersRepository.findAll();
		model.addAttribute("userlist",users);
		return "view/user/index";
	}

	@GetMapping("/user/{id}")
	public String show(@PathVariable Integer id, Model model) {
		UsersEntity user = usersRepository.findById(id).get();
		model.addAttribute("user",user);
		barcode(String.valueOf(id), model);
		return "/view/user/show";
	}

	@GetMapping
	public String barcode(@PathVariable(value="id") String id, Model model) {
		try {
			byte[] res = toByteArray(id);
			String encodedStr64 = Base64.encodeBase64String(res);
			model.addAttribute("dataUrl", encodedStr64);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "Image/data";
	}

	private byte[] toByteArray(String contents) throws IOException, WriterException{
		BarcodeFormat format = BarcodeFormat.CODE_39;
		int width = 180;
		int height = 40;	
		Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);

		try (ByteArrayOutputStream output = new ByteArrayOutputStream()){
			Code39Writer writer = new Code39Writer();
			BitMatrix bitMatrix = writer.encode(contents, format, width, height, hints);
			MatrixToImageWriter.writeToStream(bitMatrix,  "png",  output);
			return output.toByteArray();
		}
	}

View description

index.html


<tr th:each="users : ${userlist}">
	<td th:text="${users.id}"></td>
	<td th:text="${users.name}"></td>
	<td><a th:href="@{/user/{id}(id=${users.id})}">Details</a></td>
</tr>

show.html


<tr th:object="${user}">
	<td th:text="*{id}"></td>
	<td th:text="*{name}"></td>
	<td><img th:src="|data:image/png;base64, ${dataUrl}|" class="barcode"></td>
</tr>

Contents that I was allowed to refer to

https://qiita.com/rubytomato@github/items/187e277b964b14f77179 https://weblabo.oscasierra.net/java-zxing-2/

Recommended Posts

Generate barcode with Spring Boot
Download with Spring Boot
Hello World with Spring Boot
Implement GraphQL with Spring Boot
Get started with Spring boot
Hello World with Spring Boot!
Run LIFF with Spring Boot
SNS login with Spring Boot
File upload with Spring Boot
Spring Boot starting with copy
Spring Boot starting with Docker
Hello World with Spring Boot
Set cookies with Spring Boot
Use Spring JDBC with Spring Boot
Add module with Spring Boot
Getting Started with Spring Boot
Create microservices with Spring Boot
Send email with spring boot
Use Basic Authentication with Spring Boot
gRPC on Spring Boot with grpc-spring-boot-starter
Create an app with Spring Boot 2
Hot deploy with Spring Boot development
Database linkage with doma2 (Spring boot)
Spring Boot programming with VS Code
Until "Hello World" with Spring Boot
Inquiry application creation with Spring Boot
Get validation results with Spring Boot
(Intellij) Hello World with Spring Boot
Create an app with Spring Boot
Google Cloud Platform with Spring Boot 2.0.0
Check date correlation with Spring Boot
I tried GraphQL with Spring Boot
[Java] LINE integration with Spring Boot
Beginning with Spring Boot 0. Use Spring CLI
I tried Flyway with Spring Boot
Message cooperation started with Spring Boot
Spring Boot gradle build with Docker
Processing at application startup with Spring Boot
Hello World with Eclipse + Spring Boot + Maven
Send regular notifications with LineNotify + Spring Boot
Perform transaction confirmation test with Spring Boot
HTTPS with Spring Boot and Let's Encrypt
Challenge Spring Boot
Try using Spring Boot with VS Code
Start web application development with Spring Boot
Launch Nginx + Spring Boot application with docker-compose
I tried Lazy Initialization with Spring Boot 2.2.0
Spring Boot Form
Implement CRUD with Spring Boot + Thymeleaf + MySQL
Asynchronous processing with Spring Boot using @Async
Implement paging function with Spring Boot + Thymeleaf
Spring Boot Memorandum
gae + spring boot
(IntelliJ + gradle) Hello World with Spring Boot
Use cache with EhCashe 2.x with Spring Boot
Form class validation test with Spring Boot
Run WEB application with Spring Boot + Thymeleaf
Achieve BASIC authentication with Spring Boot + Spring Security
Spring Boot environment construction with Docker (January 2021 version)
Create a website with Spring Boot + Gradle (jdk1.8.x)
Configure Spring Boot application with maven multi module