3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SpringBootでバーコードを生成

Last updated at Posted at 2019-11-26

やること

フォームに入力した値で一次元バーコードをつくりたい
ZXing(ゼブラクロッシング)というライブラリを使うとバーコードとかQRコードが作れる
https://github.com/zxing/zxing

今回は詳細画面に一次元のバーコード(CODE_39)を出力する想定

ZXingライブラリの追加

pom.xmlにZXingライブラリを追加する
Java SEでの開発の場合はjavaseを指定
Androidでの開発の場合はandroidを指定
Zxingライブラリとは別に、Base64エンコードを行うためにcommons-codecを利用します

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>

下準備

Entityと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>{
}

Controllerを記載

一覧画面と詳細画面が存在していて、詳細画面にバーコードを出力する想定です

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();
		}
	}

ビューの記載

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})}">詳細</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>

参考にさせていただいた内容

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

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?