前端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中的关键样式。
相关推荐
前端大波8 分钟前
Web Vitals 与前端性能监控实战
前端·javascript
AlienZHOU41 分钟前
从零开始,跟着写一个产品级 Coding Agent
前端
RichardZhiLi44 分钟前
大前端全栈实践课程:章节二(前端工程化建设)
前端
毕设源码-赖学姐1 小时前
【开题答辩全过程】以 基于VUE的环保网站设计为例,包含答辩的问题和答案
前端·javascript·vue.js
ZTrainWilliams1 小时前
swagger-mcp-toolkit 让 AI编辑器 更快“读懂并调用”你的接口
前端·后端·mcp
伊步沁心1 小时前
深入 useEffect:为什么 cleanup 总比 setup 先跑?顺手手写节流防抖 Hook
前端
小J听不清1 小时前
CSS 字体样式全解析:字体类型 / 大小 / 粗细 / 样式
前端·javascript·css·html·css3
500佰1 小时前
pencil on claude 让设计师和程序员少吵架的一种可能
前端
Jane-lan1 小时前
NVM安装以及可能的坑
前端·node·nvm