Electron 收据热敏打印机

Receipt thermal printer in Electron

我需要从 Electron 中找到一种在 javascript 中打印收据的方法。我已经尝试过 QZ-TRAY 但由于 Electron,它不起作用。我也试过 node-thermal-printer 但它对我也没有用。这里有人知道如何在 javascript(电子)中不询问用户就可以打印收据吗?

编辑

Qz-tray 提供了一个非常好且难以击败的解决方案。

如果出现错误 RSVP is not defined,则需要使用此行启用本机 javascript 承诺。

qz.api.setPromiseType(resolver => new Promise(resolver));

引用相关评论...

"Well with QZ my problem was RSVP is not defined and with node-thermal-printer, the printer just never printed."

"for QZ it took all of 20secs to find this: https://qz.io/wiki/2.0-api-override"

发布评论表明它有效的解决方案。感谢@gilbert-gabriel 的帮助。

默认情况下启用 RSVP 承诺,但通过以下方式支持本机 JS 承诺:

qz.api.setPromiseType(resolver => new Promise(resolver));

更全面的例子:

// Install dependencies:
/*
   npm install qz-tray js-sha256
*/

// Provide API overrides and start talking to QZ Tray:    
import * as qz from 'qz-tray';
import { sha256 } from 'js-sha256';

qz.api.setSha256Type(data => sha256(data));
qz.api.setPromiseType(resolver => new Promise(resolver));

qz.websocket.connect()
 .then(qz.printers.getDefault)
 .then(printer => console.log("The default printer is: " + printer))
 .then(qz.websocket.disconnect)
 .catch(err => console.error(err));

尝试使用包 electron-pos-printer。 npm i electron-pos-printer .查看 documentation

演示

// In the main process
const {PosPrinter} = require("electron-pos-printer");
// or in render process
const {PosPrinter} = require('electron').remote.require("electron-pos-printer");

// each object in the data array accounts for a row or line
const print_data = [
    {
      type: 'image',                                       
      path: path.join(__dirname, 'assets/banner.png'),     // file path
      position: 'center',                                  // position of image: 'left' | 'center' | 'right'
      width: 60,                                           // width of image in px; default: auto
      height: 60,                                          // width of image in px; default: 50 or '50px'
   },
   {type: 'text', value: 'Sample text', style: 'text-align:center;font-weight: bold'},
   {type: 'text', value: 'Another text', style: 'color: #fff'},
   {type 'barCode', value: 'HB4587896', height: 12, width: 1, fontsize: 9},
   {type 'qrCode', value: 'https://google.com', height: 55, width: 55, style: 'margin: 10 20px 20 20px'}
];

// returns promise<any>
 PosPrinter.print(print_data, {
    printerName: 'XP-80C',
    preview: false,
    width: '170px',               //  width of content body
    margin: '0 0 0 0',            // margin of content body
    copies: 1,                   // The number of copies to print
  })
  .then(() => {
    // some code ...
  })
  .catch((error) => {
    console.error(error);
   });