1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| const { PosPrinter } = require('electron-pos-printer');
// 获取打印机列表 ipcMain.handle('get-printers', async () => { try { let printers; // 不同版本的electron获取打印机列表的api是不一样的,这里做了兼容处理 if (typeof mainWindow.webContents.getPrintersAsync === 'function') { printers = await mainWindow.webContents.getPrintersAsync(); } else if (typeof mainWindow.webContents.getPrinters === 'function') { printers = mainWindow.webContents.getPrinters(); } else { throw new Error('无法获取打印机列表'); } return printers; } catch (error) { console.error('获取打印机列表失败:', error); throw error; } });
// 打印配方处理 ipcMain.handle('print-recipe', async (event, printContent) => { try { console.log("打印内容:", printContent); const printContentObj = JSON.parse(printContent); const data = []; data.push({ type: 'text', value: printContentObj.text, style: { fontWeight: '500',textAlign: 'center' } }, { type: 'qrCode', value: printContentObj.text, position: 'center', height: 100, width: 100, })
// 打印选项 const options = { preview: false, // 打印预览,如果设为true,只会出现预览窗口,不会打印 width: '80mm', margin: '0', // 完全移除页边距 copies: 1, printerName: "Honeywell PX240S (300 dpi)", // 对应打印机的名称,详见获取打印机列表 timeOutPerLine: 3000, // 减少行间延迟,避免分页 silent: true, pageSize: { height: 150, width: 550 }, // 自定义尺寸(1/100英寸单位) };
// 执行打印 await PosPrinter.print(data, options); console.log('打印成功'); return { success: true }; } catch (error) { console.error('打印失败:', error); throw error; } });
|