#依赖 <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.3.3</version> </dependency>
@RequestMapping(value = "/BarCode", method = RequestMethod.GET)
public void BarCode(HttpServletResponse response) {
try {
BufferedImage bufferedImage = barCode("DQ101000012303230002", 8, 20);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "PNG", baos);
// Image instance = Image.getInstance(baos.toByteArray());
// PdfPCell cellell = new PdfPCell(instance);
OutputStream out = response.getOutputStream();
out.write(baos.toByteArray());
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 生成条形码
public BufferedImage barCode(String contents, int width, int height) {
int codeWidth = 3 + // start guard
(7 * 6) + // left bars
(7 * 6) + // right bars
3; // end guard
codeWidth = Math.max(codeWidth, width);
try {
//配置条码参数
Map<EncodeHintType,Object> hints = new HashMap<>();
//设置条码两边空白边距为0,默认为10,如果宽度不是条码自动生成宽度的倍数则MARGIN无效
hints.put(EncodeHintType.MARGIN, 0);
// 字符集
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");// Constant.CHARACTER);
// 容错质量
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.CODE_128, codeWidth, height, hints);
BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
return bufferedImage;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}