preface

Electron +vuecli3 realize setting printer, silent printing receipts function

Internet related information is relatively few, here to share with you, I hope you can step on some pit github address

It must be emphasized that the electron version must be 3.0.0. No, I tried 4 and 5, but it didn’t work

rendering

 

use

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

implementation

1. Click Print. 2. If yes, print it directly. 4. If no, a dialog box for setting printer is displayed

The first page, app.vue, introduces two components, one of which is to actively set up the printer’s pop-up printDialog

The other one is the print component, which uses the WebView to render the content you want to print to an HTML page and then print

<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=" date" width="180" column-key="date"> </el-table-column> <el-table-column Width ="180"> </el-table-column> <el-table-column prop="address" label=" address" > </el-table-column> <el-table-column label=" operation "> <template slot-scope="scope"> <el-button type="primary" @click="doPrint(scope.row)"> print </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: 'I am a fairy, address: Shanghai pudong new area, the tag:' home '}, {date: '2016-05-04', name: 'I'm a little fairy 1', address: 'Shanghai Pudong New District ', tag:' company ', {date: '2016-05-01', address: 'Shanghai Pudong New District ', tag:' home '}, {date: }}, 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>Copy the code

$refs.print. Print (row.name) printer. VUE queries the printer and calls the print method 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: GetPrintListHandle () {print(val) {this.htmldata = val this.getPrintlisthandle ()}, Ipcrenderer. send('getPrinterList') ipcrenderer. once('getPrinterList', (event, Data) => {// Filter available printers this.printList = data.filter(Element => element.status === 0) // 1. If (this.printlist. length <= 0) {this.$message({message: 'printlist. service abnormal, please try to restart the computer ', type: 'error' }) this.$emit('cancel') } else { this.checkPrinter() } }) }, // 2. Determine the printer status checkPrinter () {/ / local access to a printer const printerName = this. $electronStore. Get (' printForm ') | | 'const printer = This.printlist. find(device => device.name === printerName) if (printer && printer. Status === 0) {if (printer && printer. this.printDeviceName = printerName this.printRender() } else if (printerName === '') { this.$message({ message: 'Please set another printer first ', type: 'error', Duration: 1000, onClose: () => {this.dialogVisible = true}}) this.$emit('cancel')} else {this.$message({message: 'Printer is not available, please reset ', 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: 'printing, please wait ', duration: $refs.printWebview = this.$refs.printWebview const webview = this.$refs.printWebview  { printName: this.printDeviceName, html: this.htmlData }) } } } </script> <style scoped> .container { position: fixed; right: -500px; } </style>Copy the code

Public /print. HTML Sends printing instructions after rendering the WebView successfully

<script> const { ipcRenderer } = require('electron') ipcRenderer.on('webview-print-render', (event, Info) => {// perform render document.getelementById ('bd').innerhtml = info.html ipcrenderer.sendtohost ('webview-print-do')}) </script>Copy the code

Here we use the electron store to access local data background.js to initialize mount in global

Import ElectronStore from 'electron-store' // ElectronStore default data import electronDefaultData from './config/electron-default-data' let electronStore app.on('ready', Async () => {// Initialize the configuration file electronStore = new electronStore ({defaults: electronDefaultData, CWD: app.getPath('userData') }) global.electronStore = electronStore })Copy the code

SRC/plugins/inject $electronStore js registration

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

Get (‘printForm’) and this.electronStore.get(‘printForm’) Enclosing electronStore. Get (‘ printForm ‘) and enclosing electronStore. Set (‘ printForm, val. The name)

About me

For more technology-related articles, follow the public account “front-end girls juku”.

Return to front end to join “Front End Fairy Group”

You can scan and add wechat below and note Sol plus front-end exchange group for exchange and learning.

If it will be helpful to you, send me a little star (the better you guys will be)