java
package org.jeecg.modules.utils;
import cn.hutool.core.io.IoUtil;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
/**
* @Description: ZebraDesigner 斑马打印机 工具类
* @Author: Wang Yuhuang
* @Date: 2025-10-24
* @Version: V1.0
*/
@Slf4j
public class ZebraDesignerUtil {
// 打印机配置
private static final String PRINTER_IP = "192.168.xx.xx";
private static final int PRINTER_PORT = 9100;
private static final int TIMEOUT_MS = 5000; // 5秒超时
/**
* 向斑马打印机发送ZPL命令
*
* @param printerIp 打印机IP地址
* @param port 端口号(通常是9100)
* @param zplCommand ZPL指令字符串
*/
public static boolean sendZplCommand(String printerIp, int port, String zplCommand) {
Socket socket = null;
OutputStream out = null;
try {
// 建立TCP连接
socket = new Socket();
socket.connect(new InetSocketAddress(printerIp, port), TIMEOUT_MS);
// 获取输出流
out = socket.getOutputStream();
// 发送ZPL命令
byte[] command = zplCommand.getBytes(StandardCharsets.UTF_8);
out.write(command);
out.flush();
return true;
} catch (SocketTimeoutException e) {
log.error("连接打印机超时 ({}ms): {}:{}", TIMEOUT_MS, printerIp, port, e);
return false;
} catch (IOException e) {
log.error("打印失败! 打印机地址: {}:{}, 错误: {}", printerIp, port, e.getMessage(), e);
return false;
} finally {
// Hutool 关闭资源
IoUtil.close(out);
IoUtil.close(socket);
}
}
public static void main(String[] args) {
// ZPL指令:打印一行文字
String zplData = "^XA\n" +
"^FX Third section with bar code.\n" +
"^BY5,2,270\n" +
"^FO100,550^BC^FD12345678^FS\n" +
"^XZ";
//发送指令
boolean success = sendZplCommand(PRINTER_IP, PRINTER_PORT, zplData);
}
}
ZPL:
- 在线 ZPL 预览工具:https://labelary.com/viewer.html