electron实现静默打印的示例代码


Posted in Javascript onAugust 12, 2019

前言

electron+vuecli3 实现设置打印机,静默打印小票功能

网上相关的资料比较少,这里给大家分享一下,希望大家可以少踩一些坑
github地址

必须要强调一下的是electron的版本必须是3.0.0不能,我尝试了4和5都没有实现

效果图

electron实现静默打印的示例代码

electron实现静默打印的示例代码

使用

git clone https://github.com/sunnie1992/electron-vue-print-demo.git
npm install
npm run electron:serve

实现

操作思路
1.用户点击打印
2.查询本地electron-store(用来向本地存储,读取数据)是否存打印机名称
3.已经设置,直接打印
4.没有设置,弹出设置打印机框
5.用户设置好确认后打印

首页App.vue引入了两个组件,一个是主动设置打印机的弹出printDialog

electron实现静默打印的示例代码

另外一个是打印组件,打印是通过webview将需要打印的内容渲染到html页面然后就能打印了

<template>
 <div id="app">
  <el-button type="primary" @click="showPrint">设置打印机</el-button>
  <printDialog :dialog-visible="dialogVisible" @cancel="handlePrintDialogCancel" />
  <pinter ref="print" :html-data="HtmlData"></pinter>
  <el-table :data="tableData" style="width: 100%">
   <el-table-column prop="date" label="日期" width="180" column-key="date">
   </el-table-column>
   <el-table-column prop="name" label="姓名" width="180">
   </el-table-column>
   <el-table-column prop="address" label="地址">
   </el-table-column>
   <el-table-column label="操作">
    <template slot-scope="scope">
     <el-button type="primary" @click="doPrint(scope.row)">打印</el-button>
    </template>
   </el-table-column>
  </el-table>
 </div>
</template>
<script>
import { ipcRenderer } from 'electron'
import printDialog from './components/PrintDialog.vue'
import Pinter from './components/pinter.vue'
export default {
 name: 'App',
 components: {
  Pinter,
  printDialog
 },
 data() {
  return {
   dialogVisible: false,
   HtmlData: '',
   printList: [],
   tableData: [{
    date: '2016-05-02',
    name: '我是小仙女',
    address: '上海市浦东新区',
    tag: '家'
   }, {
    date: '2016-05-04',
    name: '我是小仙女1',
    address: '上海市浦东新区',
    tag: '公司'
   }, {
    date: '2016-05-01',
    name: '我是小仙女2',
    address: '上海市浦东新区',
    tag: '家'
   }, {
    date: '2016-05-03',
    name: '我是小仙女3',
    address: '上海市浦东新区',
    tag: '公司'
   }]
  }
 },
 mounted() {
 },
 methods: {
  showPrint() {
   this.dialogVisible = true
  },
  handlePrintDialogCancel() {
   this.dialogVisible = false
  },
  doPrint(row) {
   this.HtmlData = row.name
   this.$refs.print.print(row.name)
  }
 }
}
</script>

<style>
#app {
 font-family: 'Avenir', Helvetica, Arial, sans-serif;
 -webkit-font-smoothing: antialiased;
 -moz-osx-font-smoothing: grayscale;
 text-align: center;
 color: #2c3e50;
 margin-top: 60px;
}
</style>

APP.VUE 每次点击打印按钮后触发组件的print方法并将数据传过去 this.$refs.print.print(row.name)
printer.vue 查询打印机,然后调用打印方法printRender。

<template>
 <div class="container">
  <webview id="printWebview" ref="printWebview" :src="fullPath" nodeintegration />
  <printDialog :dialog-visible="dialogVisible" @cancel="handlePrintDialogCancel" @select-print="printSelectAfter" />
 </div>
</template>
<script>
import { ipcRenderer } from 'electron'
import path from 'path'
import printDialog from './PrintDialog.vue'
export default {
 name: 'Pinter',
 components: {
  printDialog
 },
 props: {
  // HtmlData: {
  //  type: String,
  //  default: '',
  // },
 },
 data() {
  return {
   printList: [],
   dialogVisible: false,
   printDeviceName: '',
   fullPath: path.join(__static, 'print.html'),
   messageBox: null,
   htmlData: ''
  }
 },

 mounted() {
  const webview = this.$refs.printWebview
  webview.addEventListener('ipc-message', (event) => {
   if (event.channel === 'webview-print-do') {
    console.log(this.printDeviceName)
    webview.print(
     {
      silent: true,
      printBackground: true,
      deviceName: this.printDeviceName
     },
     (data) => {
      this.messageBox.close()
      if (data) {
       this.$emit('complete')
      } else {
       this.$emit('cancel')
      }
     },
    )
   }
  })
 },
 methods: {
  print(val) {
   this.htmlData = val
   this.getPrintListHandle()
  },
  // 获取打印机列表
  getPrintListHandle() {
   // 改用ipc异步方式获取列表,解决打印列数量多的时候导致卡死的问题
   ipcRenderer.send('getPrinterList')
   ipcRenderer.once('getPrinterList', (event, data) => {
    // 过滤可用打印机
    this.printList = data.filter(element => element.status === 0)
    // 1.判断是否有打印服务
    if (this.printList.length <= 0) {
     this.$message({
      message: '打印服务异常,请尝试重启电脑',
      type: 'error'
     })
     this.$emit('cancel')
    } else {
     this.checkPrinter()
    }
   })
  },
  // 2.判断打印机状态
  checkPrinter() {
   // 本地获取打印机
   const printerName = this.$electronStore.get('printForm') || ''
   const printer = this.printList.find(device => device.name === printerName)
   // 有打印机设备并且状态正常直接打印
   if (printer && printer.status === 0) {
    this.printDeviceName = printerName
    this.printRender()
   } else if (printerName === '') {
    this.$message({
     message: '请先设置其他打印机',
     type: 'error',
     duration: 1000,
     onClose: () => {
      this.dialogVisible = true
     }
    })
    this.$emit('cancel')
   } else {
    this.$message({
     message: '当前打印机不可用,请重新设置',
     type: 'error',
     duration: 1000,
     onClose: () => {
      this.dialogVisible = true
     }
    })

   }
  },

  handlePrintDialogCancel() {
   this.$emit('cancel')
   this.dialogVisible = false
  },
  printSelectAfter(val) {
   this.dialogVisible = false
   this.$electronStore.set('printForm', val.name)
   this.printDeviceName = val.name
   this.printRender()
  },
  printRender(html) {
   this.messageBox = this.$message({
    message: '打印中,请稍后',
    duration: 0
   })
   // 获取<webview>节点
   const webview = this.$refs.printWebview
   // 发送信息到<webview>里的页面
   webview.send('webview-print-render', {
    printName: this.printDeviceName,
    html: this.htmlData
   })
  }
 }
}
</script>
<style scoped>
.container {
 position: fixed;
 right: -500px;
}
</style>

public/print.html渲染webview页面成功后发送打印指令

<script>
  const { ipcRenderer } = require('electron')
  ipcRenderer.on('webview-print-render', (event, info) => {
   // 执行渲染
   document.getElementById('bd').innerHTML = info.html
   ipcRenderer.sendToHost('webview-print-do')
  })
 </script>

这里用到了electron-store存取本地数据

background.js 引入 初始化挂载在global

import ElectronStore from 'electron-store'
// ElectronStore 默认数据
import electronDefaultData from './config/electron-default-data'
let electronStore
app.on('ready', async() => {
 // 初始化配置文件
 electronStore = new ElectronStore({
  defaults: electronDefaultData,
  cwd: app.getPath('userData')
 })
 global.electronStore = electronStore
})

src/plugins/inject.js

注册$electronStore

// eslint-disable-next-line
import { remote } from 'electron'
export default {
 /* eslint no-param-reassign: "error" */
 install(Vue) {
  Vue.prototype.$electronStore = remote.getGlobal('electronStore')
 
 }
}

然后你就可以在vue文件里读取了

this.$electronStore.get('printForm') 和 this.$electronStore.set('printForm', val.name)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
简单实例处理url特殊符号&amp;处理(2种方法)
Apr 02 Javascript
jQuery中 noConflict() 方法使用
Apr 25 Javascript
如何使用jquery控制CSS样式,并且取消Css样式(如背景色,有实例)
Jul 09 Javascript
text-align:justify实现文本两端对齐 兼容IE
Aug 19 Javascript
jquery实现异步加载图片(懒加载图片一种方式)
Apr 24 jQuery
JS实现汉字与Unicode码相互转换的方法详解
Apr 28 Javascript
微信小程序中实现手指缩放图片的示例代码
Mar 13 Javascript
vue2.0+koa2+mongodb实现注册登录
Apr 10 Javascript
快速解决Vue项目在IE浏览器中显示空白的问题
Sep 04 Javascript
vue使用原生js实现滚动页面跟踪导航高亮的示例代码
Oct 25 Javascript
基于iview的router常用控制方式
May 30 Javascript
Nest.js 授权验证的方法示例
Feb 22 Javascript
微信小程序 弹窗输入组件的实现解析
Aug 12 #Javascript
微信小程序 腾讯地图SDK 获取当前地址实现解析
Aug 12 #Javascript
ElementUI radio组件选中小改造
Aug 12 #Javascript
Vue 3.0 前瞻Vue Function API新特性体验
Aug 12 #Javascript
微信小程序实现页面分享onShareAppMessage
Aug 12 #Javascript
react实现antd线上主题动态切换功能
Aug 12 #Javascript
vue从一个页面跳转到另一个页面并携带参数的解决方法
Aug 12 #Javascript
You might like
精致的人儿就要挑杯子喝咖啡
2021/03/03 冲泡冲煮
通过html表格发电子邮件
2006/10/09 PHP
MySQL授权问题总结
2007/05/06 PHP
php递归删除目录下的文件但保留的实例分享
2014/05/10 PHP
php实例分享之通过递归实现删除目录下的所有文件详解
2014/05/15 PHP
简单实现PHP留言板功能
2016/12/21 PHP
详解如何在云服务器上部署Laravel
2017/06/30 PHP
php如何比较两个浮点数是否相等详解
2019/02/12 PHP
js的2种继承方式详解
2014/03/04 Javascript
使用jQuery动态加载js脚本文件的方法
2014/04/03 Javascript
JavaScript中的数组操作介绍
2014/12/30 Javascript
IE中鼠标经过option触发mouseout的解决方法
2015/01/29 Javascript
javascript实现显示和隐藏div方法汇总
2015/08/14 Javascript
javascript实现图片轮播效果
2016/01/20 Javascript
解决JS组件bootstrap table分页实现过程中遇到的问题
2016/04/21 Javascript
基于jquery插件实现拖拽删除图片功能
2020/08/27 Javascript
node网页分段渲染详解
2016/09/05 Javascript
js使用Replace结合正则替换重复出现的字符串功能示例
2016/12/27 Javascript
jQuery动画_动力节点节点Java学院整理
2017/07/04 jQuery
实例学习JavaScript读取和写入cookie
2018/01/29 Javascript
vue仿淘宝滑动验证码功能(样式模仿)
2019/12/10 Javascript
iSlider手机端图片滑动切换插件使用详解
2019/12/24 Javascript
微信小程序实现页面浮动导航
2020/01/08 Javascript
jQuery实现倒计时功能完整示例
2020/06/01 jQuery
python 利用toapi库自动生成api
2020/10/19 Python
利用HTML5的新特点实现图片文件异步上传
2014/05/29 HTML / CSS
如何给HTML标签中的文本设置修饰线
2019/11/18 HTML / CSS
购买瑞典当代设计的腕表和太阳眼镜:TRIWA
2016/10/30 全球购物
四风问题对照检查材料整改措施
2014/09/27 职场文书
2014年创卫工作总结
2014/11/24 职场文书
2015年学校工作总结范文
2015/04/20 职场文书
Nginx中break与last的区别详析
2021/03/31 Servers
jquery插件实现搜索历史
2021/04/24 jQuery
MySQL数据库中varchar类型的数字比较大小的方法
2021/11/17 MySQL
gtx1650怎么样 gtx1650显卡相当于什么级别
2022/04/08 数码科技
使用Bandicam录制鼠标指针并附带点击声音,还可以添加点击动画效果
2022/04/11 数码科技