Electron實現靜默打印小票的流程詳解
更新時間:2024年06月11日 09:28:53 作者:彷徨的耗子
很多情況下程序中使用的打印都是用戶無感知的,并且想要靈活的控制打印內容,往往需要借助打印機給我們提供的api再進行開發(fā),這種開發(fā)方式非常繁瑣,并且開發(fā)難度較大,本文給大家介紹了Electron實現靜默打印小票的流程,感興趣的朋友可以參考下
Electron實現靜默打印小票
靜默打印流程
1.渲染進程通知主進程打印
//渲染進程 data是打印需要的數據 window.electron.ipcRenderer.send('handlePrint', data)
2.主進程接收消息,創(chuàng)建打印頁面
//main.ts /* 打印頁面 */ let printWindow: BrowserWindow | undefined /** * @Author: yaoyaolei * @Date: 2024-06-07 09:27:22 * @LastEditors: yaoyaolei * @description: 創(chuàng)建打印頁面 */ const createPrintWindow = () => { return new Promise<void>((resolve) => { printWindow = new BrowserWindow({ ...BASE_WINDOW_CONFIG, title: 'printWindow', webPreferences: { preload: join(__dirname, '../preload/index.js'), sandbox: false, nodeIntegration: true, contextIsolation: false } }) printWindow.on('ready-to-show', () => { //打印頁面創(chuàng)建完成后不需要顯示,測試時可以調用show查看頁面樣式(下面有我處理的樣式圖片) // printWindow?.show() resolve() }) printWindow.webContents.setWindowOpenHandler((details: { url: string }) => { shell.openExternal(details.url) return { action: 'deny' } }) if (is.dev && process.env['ELECTRON_RENDERER_URL']) { printWindow.loadURL(`${process.env['ELECTRON_RENDERER_URL']}/print.html`) } else { printWindow.loadFile(join(__dirname, `../renderer/print.html`)) } }) } ipcMain.on('handlePrint', (_, obj) => { //主進程接受渲染進程消息,向打印頁面?zhèn)鬟f數據 if (printWindow) { printWindow!.webContents.send('data', obj) } else { createPrintWindow().then(() => { printWindow!.webContents.send('data', obj) }) } })
3.打印頁面接收消息,拿到數據渲染頁面完成后通知主進程開始打印
<!doctype html> <html> <head> <meta charset="UTF-8" /> <title>打印</title> <style> </style> </head> <body> </body> <script> window.electron.ipcRenderer.on('data', (_, obj) => { //這里是接受的消息,處理完成后將html片段放在body里面完成后就可以開始打印了 //樣式可以寫在style里,也可以內聯 console.log('event, data: ', obj); //這里自由發(fā)揮 document.body.innerHTML = '處理的數據' //通知主進程開始打印 window.electron.ipcRenderer.send('startPrint') }) </script> </html>
這個是我處理完的數據樣式,這個就是print.html
4.主進程接收消息開始打印,并且通知渲染進程打印狀態(tài)
ipcMain.on('startPrint', () => { printWindow!.webContents.print( { silent: true, margins: { marginType: 'none' } }, (success) => { //通知渲染進程打印狀態(tài) if (success) { mainWindow.webContents.send('printStatus', 'success') } else { mainWindow.webContents.send('printStatus', 'error') } } ) })
完畢~
以上就是Electron實現靜默打印小票的流程詳解的詳細內容,更多關于Electron靜默打印小票的資料請關注腳本之家其它相關文章!
相關文章
vue.js頁面加載執(zhí)行created,mounted的先后順序說明
這篇文章主要介紹了vue.js頁面加載執(zhí)行created,mounted的先后順序說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11Vue $attrs & inheritAttr實現button禁用效果案例
這篇文章主要介紹了Vue $attrs & inheritAttr實現button禁用效果案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12vue3父組件異步props傳值子組件接收不到值問題解決辦法
這篇文章主要給大家介紹了關于vue3父組件異步props傳值子組件接收不到值問題的解決辦法,需要的朋友可以參考下2024-01-01