【开源打印组件】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)

大家都在看

  • MySQL8主从复制

    环境介绍 主服务器配置 修改my.cnf配置文件 在/etc/my.cnf 添加如下信息 登录主服务器给从服务器授权 登陆mysql 创建user授权 备注:rootslave就是…

    Linux 2023年6月14日
    0146
  • linux命令之查找grep

    grep(全称:Global Regular Expression Print)是一种强大的文本搜索工具,它可以使用正则表达式搜索文本,并把匹配的行打印出来。它的使用权限是所有用户…

    Linux 2023年5月27日
    0105
  • mycat数据库集群系列之mycat读写分离安装配置

    最近在梳理数据库集群的相关操作,现在花点时间整理一下关于mysql数据库集群的操作总结,恰好你又在看这一块,供一份参考。本次系列终结大概包括以下内容:多数据库安装、mycat部署安…

    Linux 2023年6月14日
    0133
  • ArrayList中的遍历删除

    例如我们有下列数据,要求遍历列表并删除所有偶数。 List myList = new ArrayList<>(Arrays.toList(new Integer[]{2…

    Linux 2023年6月13日
    097
  • ASP.NET CORE在docker中的健康检查(healthcheck)

    在使用docker-compose的过程中,很多程序都提供了健康检查(healthcheck)的方法,通过健康检查,应用程序能够在确保其依赖的程序都已经启动的前提下启动,减少各种错…

    Linux 2023年6月6日
    0121
  • Redis (error) NOAUTH Authentication required.

    首先查看redis设置密码没 表示没有设置密码,设置redis密码 这个时候查看密码是会报错的。 需要noauth身份验证。 修改密码 Original: https://www….

    Linux 2023年5月28日
    0104
  • zabbix部署

    zabbix zabbix zabbix介绍 zabbix特点 zabbix部署 zabbix介绍 zabbix是一个基于WEB界面的提供分布式系统监视以及网络监视功能的企业级的开…

    Linux 2023年6月13日
    0141
  • centos 7 安装zabbix 4.0

    一、zabbix简介 1、简介 zabbix([`zæbiks])是一个基于WEB界面的提供分布式系统监视以及网络监视功能的企业级的开源解决方案。zabbix能监视各种网络参数如:…

    Linux 2023年6月7日
    0123
  • JavaScript json&ajax

    本博客所有文章仅用于学习、研究和交流目的,欢迎非商业性质转载。 博主的文章没有高度、深度和广度,只是凑字数。由于博主的水平不高,不足和错误之处在所难免,希望大家能够批评指出。 博主…

    Linux 2023年6月13日
    098
  • ASP已老,尚能饭否?

    我对ASP的感情,跟大海一样深。我用它实现了第一个动态网页,也用它做了毕业设计,毕业设计的名字是《毕业设计管理系统》(是不是有点绕)。在 PHP 和 ASP.NET、Java 高歌…

    Linux 2023年6月6日
    0113
  • Redis基础

    1.简介 Redis (远程字典服务器)是一 个开源的、使用C语言编写的NoSQL数据库。Redis基于内存运行并支持持久化,采用 key-value (键值对)的存储形式,是目前…

    Linux 2023年6月13日
    091
  • Linux 中 图片的产生与查看

    使用场景 当在 Linux 的控制台想要显示一张图片,使用matplotlib.plt.plot() 和matplotlib.plt.show() 会报错。此时可以曲线救国,不直接…

    Linux 2023年6月7日
    079
  • MySQL之多表查询、Navicat及pymysql

    一、多表查询 1.1 数据准备 — 建表 create table dep( id int primary key auto_increment, name varchar(20…

    Linux 2023年6月14日
    0108
  • python中的cls和self区别

    self:Always use self for the first argument to instance methods self是作为类进行实例化传递的第一个参数,也就是我…

    Linux 2023年6月14日
    097
  • ArchLinux安装-2022-01-12

    这篇教程,是我基于B站up住theCW的视频教程整理的,其中添加了一些我在安装n次之后的经验(虽然失败过几次,但我现在安装不会再出差错,所以请放心的看此教程) 当然,我认为theC…

    Linux 2023年6月13日
    0103
  • 【考研】C语言

    考研C语言 收录数据结构会用到的C语言知识,建议有基础的情况下再学习,针对性学习即可。 往后的学习要多从内存角度去学习计算机的知识 1. 数组 1.1 一维数值数组 具备相同的数据…

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