package org.hengyi.modules.tdmMonthPlan.utils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import net.sourceforge.barbecue.Barcode;
import net.sourceforge.barbecue.BarcodeFactory;
import net.sourceforge.barbecue.BarcodeImageHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Hashtable;
@Component
public class BarcodeGenerator {
private static final String router = "data:image/png;base64,";
private static String upLoadPath;
@Value("${jeecg.path.upload}")
public void setConfigValue(String value) {
this.upLoadPath = value;
}
/**
* 生成Base64的条形码
* @param code 转工单_提交单号
* @return
*/
public static String generateBarcode(String code) {
int width = 200;
int height = 50;
Hashtable<EncodeHintType, String> hintMap = new Hashtable<>();
hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
try {
BitMatrix bitMatrix = new Code128Writer().encode(code, BarcodeFormat.CODE_128, width, height, hintMap);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? Color.BLACK.getRGB() : Color.WHITE.getRGB());
}
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(image, "png", byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
return router + Base64.getEncoder().encodeToString(byteArray);
} catch (WriterException | IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 生成打印条形码
* @param code
* @return
*/
public static String generateReportBarCode(String code){
byte[] data = null;
try {
// 生成条形码
Barcode barcode = BarcodeFactory.createCode128(code);
String signImgUrl = upLoadPath + "/monthImg/barcode.png";
barcode.setDrawingText(true);
File file = new File(signImgUrl);
BarcodeImageHandler.savePNG(barcode, file);
FileInputStream fileInputStream = new FileInputStream(file);
int available = fileInputStream.available();
data = new byte[available];
fileInputStream.read(data);
fileInputStream.close();
return router + Base64.getEncoder().encodeToString(data);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
生成条形码和打印条形码
最新推荐文章于 2024-04-11 09:37:35 发布