1.引入pom依赖包
net.sf.barcode4j barcode4j-light 2.0
2.java代码实现生产条形码
package cn.itcast.myprintl;
import org.krysalis.barcode4j.HumanReadablePlacement;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import java.awt.image.BufferedImage;
import java.io.*;
public class BarcodeUtilsA {
public static File generateFile(String msg, String path) {
File file = new File(path);
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
generateBarCode128(msg, 10.0, 0.3, true, false, outputStream);
} catch (Exception e) {
throw new RuntimeException(e);
}
return file;
}
public static void generateBarCode128(String message, Double height, Double width, boolean withQuietZone, boolean hideText, OutputStream outputStream) {
Code128Bean bean = new Code128Bean();
// 分辨率,越大条形码就越大
int dpi = 150;
// 设置两侧是否留白
bean.doQuietZone(withQuietZone);
// 设置条形码高度和宽度
bean.setBarHeight(height);
if (width != null) {
bean.setModuleWidth(width);
}
// 设置文本位置(包括是否显示)
if (hideText) {
bean.setMsgPosition(HumanReadablePlacement.HRP_NONE);
}
// 设置图片类型
String format = "image/png";
BitmapCanvasProvider canvas = new BitmapCanvasProvider(outputStream, format, dpi,
BufferedImage.TYPE_BYTE_BINARY, false, 0);
bean.generateBarcode(canvas, message);
try {
canvas.finish();
} catch (IOException e) {
//ByteArrayOutputStream won't happen
}
}
public static void main(String[] args) {
String msg = "20220602ZXY";
//生成条形码路径
String path = "C:\Users\jkl\Desktop\tesst\barcode1.png";
generateFile(msg, path);
}
}
3.效果图



