前端VUE项目实现静默打印,无需用户手动确认

一、基础环境配置

  1. 安装核心依赖

    lua 复制代码
    npm install vue-plugin-hiprint socket.io-client jquery --save

    需同时安装socket.io-client实现静默打印通信,jquery用于DOM操作。

  2. 全局引入插件

    main.js中配置:

    javascript 复制代码
    javascriptCopy Code
    import { hiPrintPlugin } from 'vue-plugin-hiprint'
    import $ from 'jquery'
    
    Vue.use(hiPrintPlugin, '$hiprint')
    Vue.prototype.$ = $
    hiPrintPlugin.disAutoConnect() // 禁用自动连接客户端:ml-citation{ref="4,5" data="citationList"}
  3. 样式文件配置

    复制node_modules/vue-plugin-hiprint/dist/print-lock.css到项目public目录,并在index.html添加:

    ruby 复制代码
    htmlCopy Code
    <link rel="stylesheet" href="<%= BASE_URL %>print-lock.css" media="print">:ml-citation{ref="3,5" data="citationList"}

二、静默打印实现

  1. 客户端安装

    下载electron-hiprint客户端并以管理员身份安装,配置默认打印机和TOKEN(如TEST_PRINT)。

  2. 打印模板初始化

    php 复制代码
    javascriptCopy Code
    const template = new this.$hiprint.PrintTemplate({
      settingContainer: '#printSettings'
    })
    const panel = template.addPrintPanel({
      width: 210,
      height: 297,
      paperFooter: 340
    })
    panel.addPrintText({
      options: {
        width: 100,
        height: 20,
        title: '产品条码',
        textType: 'barcode' // 支持条形码/二维码:ml-citation{ref="13,19" data="citationList"}
      }
    })
  3. 静默打印触发

    php 复制代码
    javascriptCopy Code
    // 连接打印客户端
    const socket = io("http://localhost:17521", {
      transports: ["websocket"],
      auth: { token: "TEST_PRINT" }
    })
    
    // 发送打印指令
    socket.emit("news", {
      html: template.getHtml(),
      pageSize: 'A4',
      printer: '打印机名称' // 不填则使用默认打印机:ml-citation{ref="4,6" data="citationList"}
    })

三、企业级优化方案

  1. 批量打印处理

    ini 复制代码
    javascriptCopy Code
    const batchData = [{id:1}, {id:2}]
    batchData.forEach(item => {
      panel.updateElement('barcode', { title: item.id })
      socket.emit("news", { html: template.getHtml() })
    }):ml-citation{ref="16,19" data="citationList"}
  2. PDF静默打印

    php 复制代码
    javascriptCopy Code
    this.$hiprint.hiwebSocket.send({
      type: 'url_pdf',
      pdf_path: 'http://example.com/file.pdf',
      copies: 2 // 打印份数:ml-citation{ref="6,8" data="citationList"}
    })

四、常见问题解决

  1. 跨域问题
    需确保客户端和前端项目同域名或配置HTTPS。
  2. Node版本兼容
    推荐使用Node 16.x版本,高版本可能出现兼容性问题11。
  3. 样式冲突
    如遇UI框架样式干扰,需重写print-lock.css中的关键样式。
相关推荐
爱喝白开水a28 分钟前
前端AI自动化测试:brower-use调研让大模型帮你做网页交互与测试
前端·人工智能·大模型·prompt·交互·agent·rag
董世昌4129 分钟前
深度解析ES6 Set与Map:相同点、核心差异及实战选型
前端·javascript·es6
吃杠碰小鸡2 小时前
高中数学-数列-导数证明
前端·数学·算法
kingwebo'sZone2 小时前
C#使用Aspose.Words把 word转成图片
前端·c#·word
xjt_09012 小时前
基于 Vue 3 构建企业级 Web Components 组件库
前端·javascript·vue.js
我是伪码农2 小时前
Vue 2.3
前端·javascript·vue.js
夜郎king3 小时前
HTML5 SVG 实现日出日落动画与实时天气可视化
前端·html5·svg 日出日落
夏幻灵4 小时前
HTML5里最常用的十大标签
前端·html·html5
Mr Xu_4 小时前
Vue 3 中 watch 的使用详解:监听响应式数据变化的利器
前端·javascript·vue.js
未来龙皇小蓝4 小时前
RBAC前端架构-01:项目初始化
前端·架构