electron+vue静默打印傻瓜式教程


项目中有大量electron的api,大家可以多去翻翻官方文档,本方案适合electron>=5.0.0

第一步

配置electron的主线程文件background.js

win = new BrowserWindow({ 
    webPreferences:{
      nodeIntegration:true,	//允许渲染线程使用node模块
      webSecurity: false,	//允许跨域
      webviewTag :true		//允许使用webview标签
    }
  })

 ipcMain.on('getPrinterDefaultName', (event) => {
    //监听获取获取默认打印机名称
    const list = win.webContents.getPrinters();
    let name = ''
    for(let item of list){
      item.isDefault && (name = item.name)
    }
    //console.log(name)
    event.returnValue = name;
  });

第二步

在项目中创建一个js文件,作为写一个vue插件

export default {
    install(Vue, options) {
        Vue.prototype.$Printer = {
          webview:null,         //webview的dom对象
          bindIpcMessage:function(){
              Vue.nextTick(() => {
                  //界面渲染完成后获取dom对象,并绑定ipc-message监听事件
                this.webview = document.querySelector("webview")
                this.webview.addEventListener("ipc-message",async event => {
                    if (event.channel == "pong") {
                        //调用静默打印
                        await this.webview.print({
                            //是否是静默打印,true为静默打印,false会弹出打印设置框
                            silent: true,
                            printBackground: true,
                            deviceName: require('electron').ipcRenderer.sendSync('getPrinterDefaultName')
                        });
                    }
                });
              });
              
          },
          printPage(printHtml){
              //发起打印api,printHtml为打印的dom
            this.webview.send("ping", printHtml)
          }
      }
    }
}

第三步

在main.js引入第二步插件

import Printer from './print/xxxxx.js';
Vue.use(Printer);

第四步

在app.vue中使用

<template>
  <div id="app">
    <router-view/>
    <webview style="width:0;height:0;" :src="html" nodeintegration></webview>
  </div>
</template>
export const absPath = fileNameOrFolder => {
	//获取根目录,开发环境与安装环境区别
  const path = require('path')
  return path.join(process.resourcesPath,
    (process.env.NODE_ENV == 'development' ?
      `../../../../${fileNameOrFolder}` : `../${fileNameOrFolder}`))
}

 data() {
    return {
      html:absPath('print/print.html')
    }
  },
created(){
	//初始化监听,然后在你想用的地方调用this.$Printer.printPage()传入你想打印的dom结构
    this.$Printer.bindIpcMessage()
  }

第五步

在项目根目录下创建存放webview使用的print.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>print</title>
    <script>
    const { ipcRenderer } = require('electron')
    ipcRenderer.on('ping', (e, ele) => { //接收响应
        document.querySelector('body').innerHTML = ele;
        ipcRenderer.sendToHost('pong','ok') //向webview所在页面的进程传达消息
    })        
    </script>
</head>
<body></body>
</html>

如果文章对你有帮助,请希望你能随手点个赞支持下!

  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,以下是一个简单的 Electron + Vue.js 的 Demo: 首先,你需要安装 Node.jsVue CLI。然后,创建一个空的 Vue.js 项目: ``` vue create my-electron-app ``` 然后进入项目目录: ``` cd my-electron-app ``` 接着,安装 Electron: ``` npm install electron --save-dev ``` 然后在项目根目录下创建一个 `main.js` 文件,这是 Electron 的主进程代码: ```javascript const { app, BrowserWindow } = require('electron') function createWindow () { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true, contextIsolation: false, enableRemoteModule: true } }) // 加载 Vue.js 应用 win.loadURL('http://localhost:8080') } app.whenReady().then(() => { createWindow() app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow() } }) }) app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) ``` 其中,`createWindow()` 函数创建了一个 Electron 窗口,并加载了 `http://localhost:8080` 这个地址,这是后面我们要启动的 Vue.js 应用的地址。 接下来,修改 `package.json` 文件,增加以下内容: ```json { "name": "my-electron-app", "version": "0.1.0", "main": "main.js", "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "electron": "electron ." }, "dependencies": { "vue": "^2.6.11" }, "devDependencies": { "electron": "^11.1.1", "vue-cli-plugin-electron-builder": "^2.0.0-rc.3" }, "electronBuilder": { "nodeIntegration": true, "builderOptions": { "appId": "com.example.my-electron-app", "productName": "My Electron App", "win": { "target": "nsis" } } } } ``` 其中,`electron` 命令启动了 Electron,`vue-cli-plugin-electron-builder` 是一个 Vue.js 插件,可以帮助我们打包 Electron 应用。 最后,运行以下命令启动 Vue.js 应用: ``` npm run serve ``` 然后在另外一个终端窗口中,运行以下命令启动 Electron: ``` npm run electron ``` 这样,一个简单的 Electron + Vue.js 的应用就创建好了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值