关于Electron+Vue打印小票功能实现(最新)

在我们的工作中,在很多场景下都需要用到小票打印功能。经过不断地踩坑不断地尝试,最终终于实现了想要的效果。最终效果是这样的:

图1:

图2:

当然你也可以按照你自己需要的效果进行排版,从而实现自己想要的效果。下边就是具体的实现思路和部分代码, 话不多说直接上代码:

首先在渲染进程中,需要打印的页面数据发送到主进程:

// 测试数据
const dataDemo = {
        type: "report",
        data: {
            age: 65,
            department_id: "测试医疗科",
            doctor_name: "测试医生",
            gender: "女",
            items: [{ name: "谷丙转氨酶", result: "15.0", unit: "U/L", standard: "0-40" }, { name: "谷草转氨酶", result: "16.0", unit: "U/L", standard: "7-45" }, { name: "碱性磷酸酶", result: "97.9", unit: "U/L", standard: "42-135" }],
            patient_name: "小红",
            report_Id: 123456,
            report_code: "1000770030",
            report_name: "血清",
            report_time: "2023-11-07 00:00:00",
            unitId: "150102157",
            unitName: "测试测试测试卫生院"
        }
}

const res = ipcRenderer.sendSync("printerInfoSync", dataPrint);
console.log("返回结果:", res);

在主进程中添加监听打印事件:

这块实现的内容就是首先将渲染进程传入的数据进行格式处理,生成打印数据同时配置打印机参数。然后在打印工具类中创建打印窗口接收打印参数并配置,将传入的数据发送到打印页面中渲染,渲染完成之后向打印窗口发送消息,打印窗口接收到消息,然后打印。

register():生成打印配置参数和打印数据的处理。

printUtils(): 打印的工具函数。

// 监听打印页面发送消息
ipcMain.on('printerInfoSync', async(event, arg) => {
        console.info('接到消息', event, arg);
        // mainWindow.webContents.getPrintersAsync().then(res=>{
        //     console.log('获取打印机列表', res)
        // }).catch((err) => {
        //     console.log('err', err)
        // })
        const res = await printUtils(register(arg))
        event.returnValue = res //{ type: 'success' }
        console.log('已打印', data);
})

printUtils.js

import { BrowserWindow, ipcMain } from 'electron';
import path from "path";


export function printUtils(data) {
    return new Promise(async (resolvePrint, rejectPrint) => {
        const { printOption: options, resultData: dataList } = data

        let subMainWindow = new BrowserWindow({
            show: options.preview,
            webPreferences: {
                nodeIntegration: true,        // For electron >= 4.0.0
                contextIsolation: false,
                webSecurity: false,
                enableRemoteModule: true
            }
        });

        function renderPrintDocument(window, data) {
            return new Promise(async (resolve, reject) => {
                ipcMain.on('load-ok', (event, res) => {
                    //在这里可以添加打印的判断条件等......
                    setTimeout(() => {
                        resolve({ message: 'page-rendered', ...res });
                    }, 500)
                })
            })
        }


        // If the subMainWindow is closed, reset the `subMainWindow` var to null
        subMainWindow.on('closed', () => {
            subMainWindow = null;
        });
        // 加载打印的html文件
        const isPrdEnv = process.env.NODE_ENV === 'production'
        const staticPath = isPrdEnv ? './static' : '../../../static'
        const url = `${path.resolve(__dirname, `${staticPath}/print.html`)}`
        subMainWindow.loadFile(url);

        subMainWindow.webContents.on('did-finish-load', async (res) => {
            let data = []
            return renderPrintDocument(subMainWindow, data)
                .then(async (result) => {
                    // let width = Math.ceil((result.width) * 264.5833);
                    let height = Math.ceil((result.height + 60) * 264.5833);
                    console.info('height', result, height);
                    if (!options.preview) {
                        subMainWindow.webContents.print({
                            silent: options.silent,
                            margins: {
                                marginType: 'none'
                            },
                            printBackground: false,
                            deviceName: options.printerName,
                            copies: 1,
                            }, (success) => {

                            if (success) {
                                resolvePrint({type: 'success'})
                            }
                            subMainWindow.close();
                        })
                    }
                })
                .catch(err => console.warn(33, err))
        })
    })

}

之后需要准备一个打印页面print.html 

<!--
  ~ Copyright (c) 2023. Author Hubert Formin <2399270194@qq.com>
  -->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Print preview</title>
  <style>
    @page {
      size: auto;
    }
    html {
      background-color: #ffffff;
      margin: 0px;
    }
    body {
      margin-left: 8mm;
    }
    body,
    html {
      font-size: 10px;
    }
    table {
      width: 100%;
      border-collapse: collapse;
    }
    table th,
    table td {
      text-align: center;
      padding: 5px;
    }
    .overT {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    table th {
      border-bottom: 1px solid #000;
      border-top: 1px solid #000;
    }
    ul,
    li {
      list-style: none;
    }
  </style>
</head>

<body>
  <section id="main"></section>
    
  <script src="./utils.js"></script>
  <script type="module">
    const { ipcRenderer } = require('electron')
    window.onload = () => {
      ipcRenderer.on('webview-print-render', (event, info) => {
        // 执行渲染
        const main = document.getElementById('main')
        createEle(info.html).then(res => {
          main.appendChild(res)
          ipcRenderer.send('load-ok', { width: document.body.clientWidth, height: document.body.clientHeight })
          ipcRenderer.sendToHost('did-finish-load')
        })
      })
    }

  </script>
</body>
</html>

本次记录完毕~

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
首先需要安装一些依赖: ```bash npm install electron electron-context-menu vite vue@next vue-router@next @vue/compiler-sfc typescript tslib --save-dev ``` 然后在 `src` 目录下新建 `main.ts` 和 `renderer.ts` 两个文件。 `main.ts` 的内容如下: ```ts import { app, BrowserWindow, Menu } from 'electron'; import path from 'path'; import contextMenu from 'electron-context-menu'; // 创建窗口 function createWindow() { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { // 允许使用 node.js nodeIntegration: true, // 允许使用 Electron 的 remote 模块 enableRemoteModule: true, // 允许在渲染进程中使用上下文菜单 contextIsolation: false, }, }); // 加载页面 win.loadFile(path.join(__dirname, '../renderer/index.html')); // 打开开发者工具 win.webContents.openDevTools(); // 设置窗口菜单 const template = [ { label: '菜单1', submenu: [ { label: '子菜单1', click: () => { console.log('点击了子菜单1'); }, }, { label: '子菜单2', click: () => { console.log('点击了子菜单2'); }, }, ], }, { label: '菜单2', click: () => { console.log('点击了菜单2'); }, }, ]; const menu = Menu.buildFromTemplate(template); Menu.setApplicationMenu(menu); } // 当 Electron 初始化完成并准备好创建窗口时调用这个函数 app.whenReady().then(() => { // 注册上下文菜单 contextMenu({ window: BrowserWindow.getFocusedWindow(), showInspectElement: true, }); createWindow(); // 如果所有窗口都关闭了,退出应用 app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } }); }); // 在 macOS 上,当单击 Dock 图标并且没有其他窗口打开时,重新创建一个窗口 app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow(); } }); ``` `renderer.ts` 的内容如下: ```ts import { createApp } from 'vue'; import App from './App.vue'; createApp(App).mount('#app'); ``` 接下来在 `src` 目录下新建 `index.html` 文件,并且在里面添加一个 `div` 元素,并且指定它的 `id` 为 `app`。同时在 `body` 元素下添加如下代码: ```html <script src="./renderer.js"></script> ``` 最后在 `package.json` 中添加如下脚本: ```json { "scripts": { "start": "vite", "build": "vite build", "electron": "electron ." } } ``` 现在可以运行 `npm run start` 来启动应用程序,然后运行 `npm run electron` 来启动 Electron 应用程序。现在你应该已经能够看到一个 Electron 窗口,并且它包含一个菜单。如果你右键单击窗口,你应该能够看到一个上下文菜单。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值