前文
原采用ZPL已实现标签打印。但是后续模版变多,每次模版转的ZPL无法直接使用,维护麻烦。于是改用直接使用btw模版,动态替换内容后打印。该方案流程为web前端传参调用后端,后端调用打印服务,打印服务通过btw模版调用打印机打印标签。
java调用bartender通过jacob实现,jacob库作为Java与Bartender之间的桥梁。jacob是一个Java的COM桥接器,允许Java程序通过COM接口调用Windows平台下的各种COM组件,包括Bartender。
后续研究下如何动态将btw转zpl,这样没有限制,前端传参触发,后端处理,发送zpl,打印机打印。
缺陷:
- 必须安装bartender软件;
- 打印服务需部署在windows环境,且连接接打印机(直连或者共享都行)
- 需配置好触发打印终端对应打印机的关系
优点:
- 能直接使用已有模版
- 后期新增模版维护简单
一、环境准备
1、打印服务引入jacob.jar
<dependency>
<groupId>com.jacob</groupId>
<artifactId>jacob</artifactId>
<jacob.version>1.19</jacob.version>
</dependency>
2、将jacob-1.19-x64.dll放到打印终端C:\Windows\System32
3、终端安装bartender软件
二、代码编写
package org.kyland.service.impl;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import org.kyland.service.BartenderService;
import java.util.HashMap;
import java.util.Map;
/**
* @Author: zl
* @Date: 2025-03-28 17:18
* @Description:
*/
public class BartenderServiceImpl implements BartenderService {
/**
* 执行标签打印
* @param templatePath 模板路径(如C:\templates\label.btw)
* @param params 变量键值对(键需与模板变量名一致)
* @param copies 打印份数
*/
public static void printLabel(String templatePath, Map<String, String> params, int copies) {
// 初始化COM单线程单元
ComThread.InitSTA();
try {
// 1. 启动Bartender进程
ActiveXComponent btApp = new ActiveXComponent("BarTender.Application");
btApp.setProperty("Visible", new Variant(false));// 隐藏Bartender界面
// 2. 加载模板文件
Dispatch btFormats = btApp.getProperty("Formats").toDispatch();
Dispatch btFormat = Dispatch.call(btFormats, "Open", templatePath, false, "").toDispatch();
// 3. 动态替换变量
params.forEach((key, value) ->
Dispatch.call(btFormat, "SetNamedSubStringValue", key, value));
// 4. 配置打印参数
Dispatch printSetup = Dispatch.get(btFormat, "PrintSetup").toDispatch();
Dispatch.put(printSetup, "IdenticalCopiesOfLabel", copies); // 设置打印份数
Dispatch.put(printSetup, "Printer", "HP_M128_2F办公室"); // 指定打印机名称
// 5. 执行打印(true表示不显示打印对话框)
Dispatch.call(btFormat, "PrintOut", true, false);
// 6. 释放资源
// 关闭模板并退出BarTender进程
Dispatch.call(btFormat, "Close", new Variant(0)); // 0表示不保存更改
btApp.invoke("Quit", new Variant(0)); // 0表示退出时不保存
} catch (Exception e) {
throw new RuntimeException("打印失败:" + e.getMessage());
} finally {
ComThread.Release(); // 强制释放COM线程
}
}
public static void main(String[] args) {
Map<String, String> params = new HashMap<>();
params.put("number", "123456789");
printLabel("F:\\bartender_templates\\label.btw", params, 1);
}
}

438

被折叠的 条评论
为什么被折叠?



