参考文章:https://blog.csdn.net/scholar_man/article/details/78784163
打印机使用的是斑马打印机
条码样式
工具类ZplPrinter
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import javax.print.*;
import javax.print.attribute.standard.PrinterName;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
/**
* @description: 条形码工具类
* @author: haoxueyang
* @create: 2021-05-17 16:13
*/
@Configuration //使用@Configuration是为了setEnvironment环境变量的注入
public class ZplPrinter implements EnvironmentAware {
private String printerModelNumber = null;//打印机型号
private PrintService printService = null;//打印机服务
private byte[] dotFont;
private String begin = "^XA"; //标签格式以^XA开始
private String end = "^XZ"; //标签格式以^XZ结束
private String content = "";
/**
* tr接口发送给SAP数据所调用的SAP的接口地址
*/
private static String ZPL_PRINTER_FONT_FILE;
@Override
public void setEnvironment(Environment environment) {
this.ZPL_PRINTER_FONT_FILE = environment.getProperty("zpl.printer.file");
}
public ZplPrinter() {
}
/**
* 构造方法
*
* @param printerModelNumber 打印机型号
*/
public ZplPrinter(String printerModelNumber) {
this.printerModelNumber = printerModelNumber;
//加载字体
File file = new File(this.ZPL_PRINTER_FONT_FILE);
if (file.exists()) {
FileInputStream fis;
try {
fis = new FileInputStream(file);
dotFont = new byte[fis.available()];
fis.read(dotFont);
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("ts24.lib文件不存在");
}
//初始化打印机
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
System.out.println("默认的打印机" + defaultService.getName());
if (services != null && services.length > 0) {
for (PrintService service : services) {
if (printerModelNumber.equals(service.getName())) {
printService = service;
break;
}
}
}
if (printService == null) {
System.out.println("没有找到打印机:[" + printerModelNumber + "]");
//循环出所有的打印机
if (services != null && services.length > 0) {
System.out.println("可用的打印机列表:");
for (PrintService service : services) {
System.out.println("[" + service.getName() + "]");
}
}
} else {
System.out.println("找到打印机:[" + printerModelNumber + "]");
System.out.println("打印机名称:[" + printService.getAttribute(PrinterName.class).getValue() + "]");
}
}
/**
* 设置条形码
*
* @param barcode 条码字符
* @param zpl 条码样式模板
*/
public void setBarcode(String barcode, String zpl) {
content += zpl.replace("${data}", barcode);
}
/**
* 中文字符、英文字符(包含数字)混合
*
* @param str 中文、英文
* @param x x坐标
* @param y y坐标
* @param eh 英文字体高度height
* @param ew 英文字体宽度width
* @param es 英文字体间距spacing
* @param mx 中文x轴字体图形放大倍率。范围1-10,默认1
* @param my 中文y轴字体图形放大倍率。范围1-10,默认1
* @param ms 中文字体间距。24是个比较合适的值。
*/
public void setText(String str, int x, int y, int eh, int ew, int es, int mx