SpringBoot中生成条形码的方案实战
在Spring Boot中生成条形码可以使用第三方库如Barcode4J
或Google Chart API
。以下是使用Google Chart API生成条形码的示例:
- 添加依赖(如果使用Maven):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- 创建一个控制器来生成并响应条形码图像:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
@RestController
public class BarcodeController {
@GetMapping("/barcode")
public void generateBarcode(
@RequestParam("text") String text,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
String googleChartUrl = "https://chart.googleapis.com/chart?" +
"cht=bar&" +
"chs=300x100&" +
"choe=UTF-8&" +
"chld=L|4&" +
"chl=" + URLEncoder.encode(text, "UTF-8");
URL url = new URL(googleChartUrl);
try (InputStream in = url.openStream()) {
response.setContentType("image/png");
response.setContentLength(in.available());
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = in.read(buffer)) != -1) {
response.getOutputStream().write(buffer, 0, bytesRead);
}
}
}
}
- 访问
/barcode
端点并提供text
参数,例如:http://localhost:8080/barcode?text=1234567890
,将
评论已关闭