【开源打印组件】vue-plugin-hiprint初体验

vue-plugin-hiprint的学习与应用

😄 生命不息,写作不止
🔥 继续踏上学习之路,学之分享笔记
👊 总有一天我也能像各位大佬一样
🏆 一个有梦有戏的人 @怒放吧德德
🌝分享学习心得,欢迎指正,大家一起学习成长!

生命不息,写作不止,养成良好的学习精神!

简介

本文介绍对vue-plugin-hiprint部分重要代码的解析,这是一个很好的开源插件,能够自己自定义打印模板,通过后端传来的数据进行渲染打印,官方也提供了许多的api供开发者使用。界面采用了antdesign。实现了免预览的直接打印。

github:https://github.com/CcSimple/vue-plugin-hiprint
print.io官网:http://hiprint.io/demo

引入插件:

【开源打印组件】vue-plugin-hiprint初体验

jsbarcode:

npm install jsbarcode --save

socket.io:

npm install socket.io

jspdf:

npm install jspdf --save

代码简单介绍

面板

分别是:拖拽组件、画布、属性栏


初始化

在挂载中调用初始化

mounted() {
  this.init()
  this.otherPaper()
},

其中初始化方法:

init() { // 左边设计模板的选择
  this.modeList = providers.map((e) => {
    return {type: e.type, name: e.name, value: e.value}
  })
  this.changeMode()
},
changeMode() { // 数据渲染
  let {mode} = this
  let provider = providers[mode]
  console.log("provider", provider)
  hiprint.init({
    providers: [provider.f]
  });
  $('.hiprintEpContainer').empty()
  hiprint.PrintElementTypeManager.build('.hiprintEpContainer', provider.value);
  $('#hiprint-printTemplate').empty()
  let templates = this.$ls.get('KEY_TEMPLATES', {}) // 从本地获取数据
  console.log("getTemplates", templates)
  let template = templates[provider.value] ? templates[provider.value] : {}
  hiprintTemplate = new hiprint.PrintTemplate({
    template: template, // panels: [{...}]
    dataMode: 1, // 1:getJson 其他:getJsonTid 默认1
    history: true, // 是否需要 撤销重做功能
    onDataChanged: (type, json) => {
      console.log(type); // 新增、移动、删除、修改(参数调整)、大小、旋转
      console.log(json); // 返回 template
      // 更新模板
      hiprintTemplate.update(json)
      // console.log(hiprintTemplate.historyList)
    },
    settingContainer: '#PrintElementOptionSetting',
    paginationContainer: '.hiprint-printPagination'
  });
  hiprintTemplate.design('#hiprint-printTemplate');
  console.log('hiprintTemplate', hiprintTemplate);
  // 获取当前放大比例, 当zoom时传true 才会有
  this.scaleValue = hiprintTemplate.editingPanel.scale || 1;
},

设置纸张大小

otherPaper() {
  let value = {}
  value.width = this.paperWidth
  value.height = this.paperHeight
  this.paperPopVisible = false
  this.setPaper('other', value)
},
/**
 * 设置纸张大小
 * @param type [A3, A4, A5, B3, B4, B5, other]
 * @param value {width,height} mm
 */
setPaper(type, value) {
  try {
    if (Object.keys(this.paperTypes).includes(type)) {
      this.curPaper = {type: type, width: value.width, height: value.height}
      hiprintTemplate.setPaper(value.width, value.height)
    } else {
      this.curPaper = {type: 'other', width: value.width, height: value.height}
      hiprintTemplate.setPaper(value.width, value.height)
    }
  } catch (error) {
    this.$message.error(操作失败: ${error})
  }
},

通过生命周期activated来解决切换模板的时候还能拖拽,并且不会被清除

activated() {
  // 重新再实例化, 处理切换demo, 无法拖拽问题
  if (this.deactivated) {
    this.changeMode();
    this.deactivated = false;
  }
},
deactivated() {
  this.deactivated = true;
},

预览

封装的预览vue界面
将模板和数据用HTML的方法转化赋值 $(‘#preview_content_custom’).html(hiprintTemplate.getHtml(printData))


        打印预览
        打印
        pdf

        关闭

export default {
  name: "printPreview",
  props: {},
  data() {
    return {
      visible: false,
      spinning: true,
      waitShowPrinter: false,
      // 纸张宽 mm
      width: 0,
      // 模板
      hiprintTemplate: {},
      // 数据
      printData: {}
    }
  },
  computed: {},
  watch: {},
  created() {
  },
  mounted() {
  },
  methods: {
    hideModal() {
      this.visible = false
    },
    show(hiprintTemplate, printData, width = '210') {
      this.visible = true
      this.spinning = true
      this.width = width
      this.hiprintTemplate = hiprintTemplate
      this.printData = printData
      setTimeout(() => {
        // eslint-disable-next-line no-undef
        $('#preview_content_custom').html(hiprintTemplate.getHtml(printData))
        this.spinning = false
      }, 500)
    },
    print() {
      this.waitShowPrinter = true
      this.hiprintTemplate.print(this.printData, {}, {
        callback: () => {
          this.waitShowPrinter = false
        }
      })
    },
    toPdf() {
      this.hiprintTemplate.toPdf(this.printData, '打印预览pdf');
    },
  }
}

/deep/ .ant-modal-body {
  padding: 0px;
}

/deep/ .ant-modal-content {
  margin-bottom: 24px;
}

直接打印

直接打印需要安装桌面插件,window.hiwebSocket.opened是为了判断socketIo是否打开,hiprintTemplate中的print2是直接打印,print是会显示预览的打印。直接打印在printIo底层会自动去连接客户端,以及传输数据。

print() {
  if (window.hiwebSocket.opened) {
    const printerList = hiprintTemplate.getPrinterList();
    console.log(printerList) // 打印机列表数据
    console.log('printData', printData) // 数据源
    hiprintTemplate.print2(printData, {printer: '', title: 'hiprint测试直接打印'});
    return
  }
  this.$message.error('客户端未连接,无法直接打印')
},

批量打印

批量打印就是采用队列打印的方式,通过TaskRunner 任务进程管理,在通过for循环收集数据去打印。

batPrint() { // 批量打印
  if (window.hiwebSocket.opened) {
    const printerList = hiprintTemplate.getPrinterList();
    console.log(printerList) // 打印机列表
    this.tasksPrint()
    return
  }
  this.$message.error('客户端未连接,无法直接打印')
},
tasksPrint() { // 队列打印
  const runner = new TaskRunner();
  runner.setConcurrency(1); // 同时执行数量
  const task = []
  let that = this
  const tasksKey = open${Date.now()};
  for (let i = 0; i < testDatas.table.length; i++) { // 循环数据
    // done -> 任务完成回调
    let key = task${i};
    task.push(done => {
      let printData = {
        testChinese: testDatas.table[i].testChinese,
        testEnglish: testDatas.table[i].testEnglish
      } // 动态数据
      console.log('printData', printData)
      that.realPrint(runner, done, key, i, printData, tasksKey)
    })
  }
  runner.addMultiple(task)
  this.openNotification(runner, tasksKey)
},
realPrint(runner, done, key, i, printData, tasksKey) {
  let that = this
  that.$notification.info({
    key: key,
    placement: 'topRight',
    duration: 2.5,
    message: 正在准备打印第 ${i} 张,
    description: '队列运行中...',
  });
  let template = that.$ls.get('KEY_TEMPLATES', {}) // 外層還有個模板名包裹
  let hiprintTemplate = new hiprint.PrintTemplate({
    template: template.aProviderModule,
  });
  hiprintTemplate.print2(printData, {printer: '', title: key});
  hiprintTemplate.on('printSuccess', function () {
    let info = runner.tasks.list.length > 1 ? '准备打印下一张' : '已完成打印'
    that.$notification.success({
      key: key,
      placement: 'topRight',
      message: key + ' 打印成功',
      description: info,
    });
    done()
    if (!runner.isBusy()) {
      that.$notification.close(tasksKey)
    }
  })
  hiprintTemplate.on('printError', function () {
    that.$notification.close(key)
    done()
    that.$message.error('打印失败,已加入重试队列中')
    runner.add(that.realPrint(runner, done, key, i, printData))
  })
},
openNotification(runner, tasksKey) {
  let that = this;
  that.$notification.open({
    key: tasksKey,
    message: '队列运行中...',
    duration: 0,
    placement: 'topLeft',
    description: '点击关闭所有任务',
    btn: h => {
      return h(
          'a-button',
          {
            props: {
              type: 'danger',
              size: 'small',
            },
            on: {
              click: () => {
                that.$notification.close(tasksKey);
                // 详情请查阅文档
                runner.removeAll();
                that.$message.info('已移除所有任务');
              },
            },
          },
          '关闭任务',
      );
    },
  });
}

保存JSON数据

只要调用apihiprintTemplate.getJson()

saveJson() {
  if (hiprintTemplate) {
    const jsonOut = JSON.stringify(hiprintTemplate.getJson() || {})
    console.log(jsonOut)
  }
},

自定义组件

封装js中,使用addPrintElementTypes方法添加自定义的组件,可以查看print.io官方文档来配置参数。通过控制台输入window.HIPRINT_CONFIG可以查看配置参数名。

new hiprint.PrintElementTypeGroup("自定义表格1", [
  {
    tid: 'aProviderModule.customText1',
    title: '表格标题',
    customText: '自定义文本',
    custom: true,
    width: 120,
    type: 'text',
    options: {
      height: 31.5,
      hideTitle: true,
      field: 'testEnglish',
      fontSize: 20.25,
      color: '#000000',
      backgroundColor: '#ffffff',
      textAlign: 'center',
      textContentVerticalAlign: 'middle',
      lineAlign: 'center',
      borderLeft: 'solid',
      borderTop: 'solid',
      borderRight: 'solid',
      borderBottom: 'solid'
    }
  },
  {
    tid: 'aProviderModule.customText2',
    title: '表格内容',
    customText: '自定义文本',
    custom: true,
    width: 120,
    type: 'text',
    options: {
      hideTitle: true,
      field: 'testChinese',
      height: 31.5,
      fontSize: 20.25,
      color: '#000000',
      backgroundColor: '#ffffff',
      textAlign: 'center',
      textContentVerticalAlign: 'middle',
      lineAlign: 'center',
      borderLeft: 'solid',
      borderTop: 'solid',
      borderRight: 'solid',
      borderBottom: 'solid'
    }
  },
]),

👍创作不易,如有错误请指正,感谢观看!记得点个赞哦!👍

Original: https://www.cnblogs.com/lyd-code/p/16687626.html
Author: 怒放吧德德
Title: 【开源打印组件】vue-plugin-hiprint初体验

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/574016/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • Jq 手机端输入框防止底部菜单被小键盘弹起

    var winHeight = $(window).height(); //获取当前页面高度 $(window).resize(function () { var thisHeig…

    Linux 2023年6月7日
    078
  • [极客大挑战 2019]Secret File

    0x01 寻找做题信息 打开环境,查看源代码,发现可疑链接,/Archive_room.php,action.php打开action.php会发生302跳转,查找302跳转无果,百…

    Linux 2023年6月8日
    086
  • QT程序自启动

    故事背景:最近涉及到客户端更新自启动的一个问题,客户端检测到自己要更新,弹出一个更新界面,然后退出旧版本,启动新版本 技术调研:QProcess 直接上代码吧 这个代码的效果就是退…

    Linux 2023年6月13日
    087
  • Fastadmin前台Getshell漏洞复现

    Fastadmin前台Getshell漏洞复现 一、简介 FastAdmin是一款基于ThinkPHP5+Bootstrap开发的极速后台开发框架。FastAdmin基于Apach…

    Linux 2023年5月28日
    0108
  • Linux 下 xargs 命令

    xargs 常常被大家忽略的一个命令,对它的一些用法很多人可能不熟悉,其实它是一个功能强大的命令,特别是在结合管道进行批量处理方面 语法 xargs 语法格式如下 xargs [O…

    Linux 2023年6月13日
    0107
  • 五分钟通俗理解自动驾驶

    大家好,我是良许。 这几年,自动驾驶这个概念非常火热,无论是百度还是谷歌,都做出了还不错的原型机,但是你真的知道什么是自动驾驶吗? 本文就花 5 分钟左右的时间,向大家科普一下什么…

    Linux 2023年6月14日
    098
  • windows版本rabbitmq安装及日志level设置

    1.DirectX Repair 安装缺失的C++组件,不安装缺失的组件会造成第二部安装erl文件夹缺少bin文件夹2.安装otp_win64_23.1 1.配置 ERLANG_H…

    Linux 2023年6月7日
    0172
  • Ubuntu18.04安装/卸载NVIDIA显卡驱动

    1 显卡驱动下载 官网:NVIDIA 搜索适合本机的驱动 获取最新版本驱动 立即下载 文件 上面,显卡驱动程序下载已完成。 [En] Above, the video card d…

    Linux 2023年5月27日
    0222
  • 015 Linux 标准输入输出、重定向、管道和后台启动进程命令

    1 三种标准输入输出 2 什么是重定向?如何重定向? (1)什么是重定向? (2)如何重定向? 3 管道符以及和它容易混淆的一些符号使用 (1)管道符 | (2)&和&am…

    Linux 2023年5月27日
    099
  • 008 Linux 文件查找 find

    在 Linux 系统,find 毫无疑问是最强的文件查找工具。find 一般会与其他命令结合,将查找到的结果作为参数传入到后置命令中,进行删除、统计、复制迁移等操作。 find /…

    Linux 2023年5月27日
    089
  • 脚本安装lamp

    脚本安装lamp [root@localhost ~]# mkdir lamp [root@localhost ~]# cd lamp/ [root@localhost lamp]…

    Linux 2023年6月6日
    0112
  • 【Redis】缓存穿透、缓存击穿、缓存雪崩产生原因及解决方案

    一. 本文对Redis中[缓存穿透]、[缓存击穿]、[缓存雪崩]三种现象产生原因、解决方法进行说明 二. 缓存穿透 1. 原因 2. 解决方法 三. 缓存击穿 1. 原因 2. 解…

    Linux 2023年5月28日
    096
  • Centos 7 上安装 jdk 及问题小记

    yum 下载安装 使用 yum -y list jav 或者 yum search jdk 查找 java 相关安装包的列表 yum -y list &#x641C;&am…

    Linux 2023年5月27日
    099
  • 数据转换-16进制字符

    任务详情 在openEuler(推荐)或Ubuntu或Windows(不推荐)中完成下面任务 在utils.h和utils.c中完成16进制字符’0′-&#…

    Linux 2023年6月8日
    084
  • 初学ajax

    ajax出现无疑改变了web应用:从开始的整体页面的刷新到局部页面的数据显示,不用刷新页面就可以与服务器交互; 1 function ajaxPost(data){ 2 3 var…

    Linux 2023年6月14日
    077
  • short, int, long, long long各个类型的范围

    类型名称 字节数 取值范围 signed char 1 -2^7 ~ 2^7-1 -128~+127 short int 2 -2^14 ~ 2^14-1 -32768~+3276…

    Linux 2023年6月8日
    074
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球