I need to find a way of printing receipts in javascript from Electron. I already tried QZ-TRAY but it doesn't work because of Electron. I also tried node-thermal-printer but it also never worked for me. Does anybody here know how you can print receipts without asking the user in javascript (Electron)?
EDIT
Qz-tray offer a solution that is pretty good and hard to beat.
If you have the error RSVP is not defined
you need to enable native javascript promises with this line.
qz.api.setPromiseType(resolver => new Promise(resolver));
Quoting the relevant comments...
"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"
Posting as asolution as the comments suggest it worked. Credits to @gilbert-gabriel for the help.
The RSVP promises are enabled by default, but native JS promises are supported via:
qz.api.setPromiseType(resolver => new Promise(resolver));
A more comprehensive example:
// 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));
Try using the package electron-pos-printer. npm i electron-pos-printer
. View the documentation
Demo
// 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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With