| 模板编码 | 模板名称 | 版本 | 备注 | 更新时间 | 操作 |
|---|
下面按钮会用示例模板编码 ORDER_A4,调用 api/templates/ORDER_A4 取模板 JSON,并模拟获取业务数据后触发打印。
详细请查看打印插件vue-plugin-hiprint官方仓库:
https://gitee.com/CcSimple/vue-plugin-hiprint
或 jQuery 版官网:http://hiprint.io/
// 1) 引入依赖:print-lock.css、jquery.js、socket.io.min.js、bwip-js.js、vue-plugin-hiprint.js
console.log("vue-plugin-hiprint");
console.log(window["vue-plugin-hiprint"]);
console.log("hiprint");
// hiprint 以注入 全局
console.log(hiprint);
var autoConnect = window["vue-plugin-hiprint"].autoConnect,
disAutoConnect = window["vue-plugin-hiprint"].disAutoConnect,
defaultElementTypeProvider = window["vue-plugin-hiprint"].defaultElementTypeProvider;
// 2) 取模板并实例化(示例模板编码为 ORDER_A4,实际可按需修改;只需一次,可缓存)
var templateCode = 'ORDER_A4';
var hiprintTemplate = null;
function getTemplate(code) {
if(hiprintTemplate){
return hiprintTemplate;
}
return $.getJSON('api/templates/' + encodeURIComponent(code))
.then(function (res) {
var json = JSON.parse(res.data.templateJson); // 后端返回的是 JSON 字符串
hiprintTemplate = new hiprint.PrintTemplate({ template: json });
return hiprintTemplate;
});
}
// 3) 获取业务数据后触发打印(业务数据来自你自己的接口,下面以订单为例)
function printOrder(orderId) {
// —— 真实业务数据获取代码(按你的接口与字段替换)——
return $.getJSON('/api/order/detail?id=' + orderId)
.then(function (order) {
return getTemplate(templateCode).then(function (tpl) {
tpl.print(order); // order 即业务数据,字段需与模板占位符对应
});
});
}
// 示例:点击按钮触发
$('#btnPrint').on('click', function () {
printOrder('123');
});
Vue3 打印插件 vue-plugin-hiprint 官方仓库: https://gitee.com/CcSimple/vue-plugin-hiprint
// 在index.html 文件中添加打印所需样式print-lock.css、main.ts组件内
import { hiprint } from 'vue-plugin-hiprint'
// 业务数据来自你自己的接口(下面以订单为例),字段需与模板占位符对应
// 1) 模板编码为 ORDER_A4,实际可放配置(只需实例化一次,可缓存)
const templateCode = 'ORDER_A4';
let hiprintTemplate = null;
async function getTemplate(code) {
const res = await fetch(`api/templates/${encodeURIComponent(code)}`)
const json = await res.json()
const template = JSON.parse(json.data.templateJson)
hiprintTemplate = new hiprint.PrintTemplate({ template })
return hiprintTemplate
}
// 2) 获取业务数据后触发打印(真实业务数据获取代码)
async function printOrder(orderId) {
// —— 按需替换为你的接口与字段 ——
const res = await fetch(`/api/order/detail?id=${orderId}`)
const order = await res.json()
if (!hiprintTemplate) await getTemplate(templateCode)
hiprintTemplate.print(order)
}
// 3) 打印按钮
<template>
<button @click="printOrder('123')">打印</button>
</template>