指令打印 plugin-api-command
约 2129 字大约 7 分钟
...
2026-11-10
插件说明
@sv-print/plugin-api-command 把打印模板转换成打印机指令,或把已有指令直接交给本地客户端,注册后模板实例新增四个 API:
| API | 作用 |
|---|---|
template.toCommand(printData, options) | 模板转指令,返回每页的指令字节与可读指令文本 |
template.toBinaryImage(printData, options) | 模板逐页转单色位图,不拼接任何协议头尾 |
template.printCommand(printData, options) | 请求本地客户端生成指令并提交打印机队列 |
template.printRaw(command, options) / 具名导出 printRaw | 原始指令文本或字节直打,不渲染模板 |
转换策略:ZPL / TSPL / CPCL 优先使用原生文本、线条、条码、二维码指令,无法用指令表达的元素自动截图、二值化后嵌入;ESC/POS 只有满足标准行布局(203 DPI、独立非重叠行)时才走原生,否则整页位图;EPL 默认整页位图。每个元素实际采用的策略见返回值的 diagnostics。
npm install @sv-print/plugin-api-command示例代码
唯一注册入口 hiprint.register(异步),须在创建模板之前注册:
import pluginApiCommand from '@sv-print/plugin-api-command';
await hiprint.register({
// 须在创建模板之前注册
plugins: [pluginApiCommand()], // 工厂函数,可传插件 config
});
const template = new hiprint.PrintTemplate(options); // 须在 register 之后创建模板toCommand 生成指令(不打印):
const pages = await template.toCommand(printData, {
protocol: 'zpl', // escpos | zpl | tspl | cpcl | epl
dpi: 203,
copies: 1,
mode: 'auto', // auto: 原生指令优先; raster: 整页截图二值化
preview: true, // 生成整页二值化预览图
previewType: 'url', // blob | url; url 为可直接展示的 data URL
onProgress: (current, total) => console.log(current, total),
});
pages.forEach((page) => {
console.log(page.panelIndex, page.pageIndex, page.text, page.bytes, page.diagnostics);
if (typeof page.preview === 'string') {
const img = new Image();
img.src = page.preview;
document.body.appendChild(img);
}
});
console.log(pages[0].bytes); // 发送打印机请使用 bytes
console.log(pages[0].text); // 可读指令文本; 二进制部分用 \xNN 展示toCommand 模板转指令
const pages = await template.toCommand(printData, { protocol: 'tspl' });返回 CommandPage[]:
interface CommandPage {
protocol: 'escpos' | 'zpl' | 'tspl' | 'cpcl' | 'epl';
panelIndex: number;
pageIndex: number;
bytes: Uint8Array; // 指令字节流,可直接发送给打印机
text: string; // 可读指令文本,二进制部分用 \xNN 展示
diagnostics: {
elementIndex: number;
type: string;
strategy: 'native' | 'raster'; // 原生指令 / 截图位图
reason?: string; // 回退原因
}[];
preview?: Blob | string; // previewType=blob 为 Blob; url 为 data URL
}toCommand 参数
template.toCommand(printData, options),protocol 必填:
| 参数 | 默认 | 说明 |
|---|---|---|
protocol | - | escpos / zpl / tspl / cpcl / epl |
dpi | 203 | 打印机分辨率,取值 72 ~ 1200 |
copies | 1 | 份数,取值 1 ~ 999 |
mode | 'auto' | auto 优先原生指令;raster 整页截图二值化 |
dither | 'threshold' | threshold / otsu / floyd-steinberg / atkinson |
threshold | 128 | 二值化阈值 |
invert | false | 黑白反色 |
backgroundColor | #fff | 截图背景色 |
fontTimeoutMs | 3000 | 等待字体加载超时(ms) |
preview | false | 是否生成整页二值化预览图 |
previewType | 'blob' | blob / url(data URL) |
rotation | 0 | 顺时针旋转,0 / 90 / 180 / 270 |
mirror | false | 旋转后水平镜像 |
gapMm | 0 | 标签间隙(mm),TSPL / EPL 支持,其他协议非 0 报错 |
rasterChunkRows | 256 | 每个图像指令最多包含的行数,1 ~ 65535 |
onProgress | - | 进度回调 (current, total) => void |
toBinaryImage 模板转单色位图
不拼接协议指令,直接得到 MSB 在左的单色位图,适合自行封装协议或做打印前预览:
const pages = await template.toBinaryImage(printData, {
dpi: 203,
dither: 'threshold',
preview: true,
previewType: 'url',
});
pages.forEach((page) => {
console.log(page.width, page.height, page.bytesPerRow, page.data);
});interface BinaryPage {
panelIndex: number;
pageIndex: number;
width: number; // 打印机点数
height: number;
bytesPerRow: number; // ceil(width / 8)
data: Uint8Array; // MSB 在左的单色位图,1=黑
preview?: Blob | string;
}参数与 toCommand 相同(不含 protocol / copies / mode / gapMm / rasterChunkRows),另支持 rotation / mirror。
printCommand 发送指令打印到本地客户端
由客户端根据模板、数据与协议生成指令并提交打印队列:
const result = await template.printCommand(printData, {
protocol: 'zpl',
printer: 'Zebra ZD421', // 留空使用客户端默认打印机
commandDpi: 203,
copies: 1,
mode: 'auto',
waitForCompletion: true, // 等待打印完成
buffer: true, // 回执返回 commandText / buffer
templateId: 'order-001',
replyId: 'order-001',
timeoutMs: 60000,
});
if (result.success) {
console.log(result.jobIds, result.commandText);
} else {
console.error(result.msg);
}| 参数 | 默认 | 说明 |
|---|---|---|
protocol | - | 必填,同 toCommand |
printer | 客户端默认打印机 | 系统打印队列名 |
commandDpi / dpi | 203 | 打印分辨率 |
copies | 1 | 份数 |
mode | 'auto' | auto / raster |
dither / threshold / invert | - | 二值化参数,同 toCommand |
rotation / mirror / gapMm / rasterChunkRows | 同 toCommand | 统一排版属性 |
commandOptions | - | 覆盖客户端的 toCommand 参数 |
template / tempId | - | 模板对象或 JSON 字符串 / 客户端本地模板 ID;都不传时使用当前模板 getJson() |
jobName | - | 系统打印队列作业名 |
buffer | false | 回执是否返回 commandText / buffer |
templateId / replyId | 自动 | 回执关联标识 |
event | 'print' | 客户端 socket 事件名,旧版客户端可用 news |
timeoutMs | 60000 | 等待回执超时(ms),0 表示不超时 |
waitForCompletion | - | 透传客户端,实际完成语义由客户端决定 |
返回 PrintCommandResult:success、msg、jobIds、commandText、buffer、timeout 等。超时只结束等待,不会取消已提交的打印作业。
printRaw 原始指令直打
不渲染模板,把文本或字节直接交给客户端打印。支持具名导出与模板实例两种调用方式:
import { printRaw } from '@sv-print/plugin-api-command';
const result = await printRaw(
'SIZE 60 mm,40 mm\r\nCLS\r\nTEXT 10,10,"0",0,12,12,"Hello"\r\nPRINT 1,1\r\n',
{
printer: 'XP-P326B', // 不传使用客户端默认打印机
protocol: 'tspl', // 可选,仅用于回传指令文本展示
waitForCompletion: true,
jobName: '原始指令',
buffer: true,
},
);
console.log(result.success, result.jobIds, result.msg);
// 模板实例上同样可用;也可通过 pluginApiCommand.printRaw 调用
await template.printRaw(pages[0].bytes, { printer: 'XP-P326B' });三种输入方式:
// 普通文本: 默认 UTF-8,保留实际换行与反斜杠,不追加任何打印/切纸/走纸指令
await printRaw(commandText, { printer: 'XP-P326B' });
// 显式转义: 仅 \xNN 还原为一个字节
await printRaw(String.raw`\x1B@Hello\x0A`, { format: 'escaped', printer: 'XP-P326B' });
// 字节: 优先发送 bytes,任意二进制不丢失
await printRaw(pages[0].bytes, { printer: 'XP-P326B' });| 参数 | 默认 | 说明 |
|---|---|---|
printer | 客户端默认打印机 | 系统打印队列名 |
format | 'text' | text 原样编码;escaped 解码 \xNN(不完整的转义会报错) |
encoding | 'utf8' | utf8 / latin1(单字符须 ≤255);GBK 等设备编码请自行转成字节后传入 |
protocol | - | 可选,仅用于回执中的指令文本展示 |
jobName | - | 作业名 |
waitForCompletion | - | 透传客户端 |
buffer | false | 回执是否返回指令内容 |
templateId / replyId | 自动 | 回执关联标识 |
event | 'print' | 客户端 socket 事件名 |
timeoutMs | 60000 | 等待回执超时(ms),0 表示不超时 |
printRaw 不做重新排版:旋转、镜像、间隙、份数等全部由传入指令本身控制;空指令、非法转义、超范围字节会直接报错。
常见问题
toCommand 和 printCommand 有什么区别?
toCommand 在浏览器端把模板转换成指令并返回字节,不发送打印;printCommand 只把模板、数据与参数发给本地客户端,由客户端生成指令并提交打印队列。需要自己保存或转发指令时用 toCommand,直接出纸用 printCommand。
为什么生成的指令里部分元素变成了图片?
原生指令只覆盖部分场景,例如 ZPL / TSPL / CPCL 的简单文本、线条、条码、二维码,ESC/POS 仅标准行布局。复杂样式、富文本、图表、图片、旋转 90° / 270° 或整页栅格模式都会触发截图二值化,具体原因见 diagnostics 中的 strategy 与 reason。
page.text 里的 \xNN 能直接发送给打印机吗?
不能。text 中的 \xNN 只是二进制字节的可读展示,直接按文本发送会变成四个 ASCII 字符。请发送 page.bytes,或用 printRaw(page.text, { format: 'escaped' }) 显式解码。
printCommand 回执超时怎么处理?
先确认页面已连接客户端、客户端版本支持指令打印且打印机名称正确。超时只表示未在 timeoutMs 内收到回执,作业可能仍在队列中,不要直接自动重发;可查询客户端打印队列或任务状态后再决定。
版权所有
版权归属:sv-print
