@lemon-nb/label-print
v0.1.0
Published
PDA 标签打印通用组件:数据 + 格式 → 指令生成与发送,支持 BLE/自定义传输
Maintainers
Readme
pda-label-print
PDA 标签打印通用组件:根据数据源和格式配置生成 CPCL/TSPL 指令,并通过可插拔的传输适配器(默认 BLE)发送到打印机。适用于多端复用(React Native PDA、Web、Node 服务等)。
安装
npm install pda-label-print
# 或
yarn add pda-label-print设计要点
- 与业务解耦:不依赖 Redux、不依赖具体 UI 库;格式配置与数据由调用方准备并传入。
- 传输可插拔:默认提供 BLE 适配器(需注入
BluetoothManager);可自定义适配器对接网络打印、本地服务等。 - 仅生成指令:支持只生成指令字符串(
buildLabelCommand),便于预览或走其他通道发送。
使用方式
1. 仅生成打印指令(不连接打印机)
import { buildLabelCommand } from "pda-label-print";
const cmd = buildLabelCommand({
template: {
type: "cpcl",
newReport: true,
jasperReport: printStyle.jasperReport,
},
data: [
{
itemName: "商品A",
lotNum: "20250101",
userName: "张三",
printTime: "2025-03-06 12:00:00",
},
],
formatMap: myFormatMap,
copies: 1,
});2. 在 React Native 中连接 BLE 并打印
应用启动时注入 BluetoothManager(可选):
import { setDefaultBleManager } from "pda-label-print";
setDefaultBleManager(global.BluetoothManager);调用打印:
import { printLabels } from "pda-label-print";
printLabels({
connection: this.props.bleDevice,
template: {
type: "cpcl",
newReport: !!printStyle.newReport,
jasperReport: printStyle.jasperReport,
},
data: printList,
formatMap: this.state.formatMap,
copies: printNum,
callbacks: {
onPrinting: () => Toast.loading("打印中...", 0),
onSuccess: () => Toast.success("打印成功", 1.5),
onError: (msg) => Toast.fail(msg, 1.5),
},
});3. 自定义传输适配器
const httpAdapter = {
async isConnected() {
return true;
},
async write(connection, rawCommand) {
await fetch(connection.printServiceUrl, {
method: "POST",
body: rawCommand,
});
},
};
await printLabels({
connection: { printServiceUrl: "https://your-print-service/send" },
template: { type: "cpcl", jasperReport, newReport: true },
data: printList,
transport: httpAdapter,
callbacks: { onSuccess: () => {}, onError: (m) => {} },
});4. 默认模板(容器签 / 箱码)
printLabels({
connection: bleDevice,
template: { type: "default_container" },
data: { containerNumber: "CTN001" },
transport: createBleAdapter(global.BluetoothManager),
callbacks: { onSuccess: () => {}, onError: (m) => {} },
});API
buildLabelCommand(options)仅生成指令字符串。printLabels(options)生成并发送,需connection与transport(或已setDefaultBleManager)。setDefaultBleManager(bluetoothManager)设置默认 BLE。createBleAdapter(bluetoothManager)创建 BLE 传输适配器。getCPCL/getCPCLNewReport/getDefaultCPCL/getContainerDefaultCPCL可直接用于生成 CPCL。
template 类型
type: 'cpcl'+jasperReport,可选newReport: true。type: 'tspl'+jasperReport(TSPL 打印机如 D45BT),可选tsplParams: { flip: true }。type: 'raw'+cpclOrTspl预生成字符串。type: 'default_container'/type: 'default_box'使用内置默认格式。type: 'default_receive_cpcl'/type: 'default_receive_tspl'收货任务标签无模板时的默认格式(data 需含printTag、itemName)。
License
MIT
