electron+vue?實現靜默打印功能
我的electron版本:^12.0.0; vue版本:^3.2.13。
我是通過webview實現的。
實現原理:webview類似于iframe,其實是electron中的一個內嵌窗口,打印的也就是這個內嵌窗口的內容。
所以共需要兩個文件:一個是vue文件,主要承擔數據預處理工作;第二個是html文件,主要承擔顯示打印內容工作。兩個文件直接通訊,并沒有通過主進程。
唯一需要主進程和渲染進程通訊的是獲取打印機列表。
開始正式開發(fā).........................
第一步:在backgroud.js中打開webview,electron5.0后默認停用webview,所以需要在配置文件中配置為默認開啟。
const win = new BrowserWindow({ width: 1920, height: 1080, fullscreen: true,//全屏顯示 webPreferences: { nodeIntegration: true, contextIsolation: false, webviewTag: true, // 允許使用 webview 標簽 }, frame: false, //客戶端窗口頂部菜單去掉 });
第二步:vue.config.js中設置html加載器,如果不設置,項目啟動后會報無法加載html文件。
首先使用 npm install html-loader,然后再進行配置。
chainWebpack: (config) => { config.module.rule() .test(/\.html$/) .use('html-loader') .loader('html-loader') },
第三步:主進程和渲染進程通訊,獲取打印機列表。
//主進程 import {ipcMain } from "electron"; ipcMain.on("getPrintList", () => { win.webContents.send("printList", win.webContents.getPrinters()); });
//渲染進程 import { ipcRenderer } from "electron"; getPrintList() { ipcRenderer.send("getPrintList"); ipcRenderer.once("printList", (event, data) => { this.printlist = data; //printList需要在data中預定義,printlist: []。返回的data就是打印機列表 }); },
第四步:vue文件的處理,主要工作包括:數據的預處理,引用html文件,發(fā)布打印命令。
<webview :src="src" ref="webview" nodeintegration style="position: absolute;right: 200vh;top: 0;" :style="{ width: pageSize.with + 'mm', height: pageSize.height + 'mm' }" /> import raw from "@/views/components/print/print.html?raw";//此處就是html文件地址 import { ElMessage, ElMessageBox, ElNotification } from "element-plus"; import { ipcRenderer } from "electron"; data() { return { printlist: [], //上一步需要預定義的打印機列表 src: "", pageSize: { with: 210, height: 297, }, }; }, methods:{ //數據處理,注意傳遞數據的方式:$為key,后為數據。 handleData(){ this.src = URL.createObjectURL( new Blob( [ raw .replace("$1", "數據測試") ], { type: "text/html", } ) ); }, //打印,自定義一個button調用函數即可進行打印 print() { let webview = this.$refs.webview;//首先通過ref獲取webview標簽 let deviceName = "";//設置默認打印機 for (let index = 0; index < this.printlist.length; index++) { if (this.printlist[index].isDefault) { deviceName = this.printlist[index].name;//遍歷打印機集合,將默認打印機名字賦值給deviceName } } ElMessage({ message: "即將使用打印機 "+deviceName, grouping: true, type: "success", }); if (this.printlist.length) { webview.print({ silent: true,//靜默打印設置為true deviceName: deviceName, margins: { marginType: "none", }, pageRanges: [{ from: 0, to: 0 }], pageSize: "A4", }); } else { message.error("請連接打印機"); } }, }
第五步:html文件的編寫。html文件位置要放在第四步指定的位置。
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style></style> </head> <body> <div> <!--$符進行取值--> <span>$1</span> </table> </div> </body> <style type="text/css"> </style> </html>
通過以上五步,即可實現electron的靜默打印。
到此這篇關于electron+vue 實現靜默打印的文章就介紹到這了,更多相關electron+vue靜默打印內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!