lsongdev / node-escpos

🖨️ ESC/POS Printer driver for Node.js
https://npmjs.org/escpos
Other
1.36k stars 422 forks source link

Generating a prn file without printer initialization #134

Open ricxsar opened 6 years ago

ricxsar commented 6 years ago

Hi.

Do you have an example which creates a prn file instead of printing it directly to the printer?

I have a printer installed on TP-Link TL-WR1043N/ND v1 router running on openwrt. Since the file system of the router is too low and ram is also low, it is not ideal for nodejs applications. I can successfully print simple text to the printer inside the router however I cannot print complex styles to it since I need a library for it.

To solve the problem, the router will request the server running either local or public to generate my complex styles and send the generated prn file to router and the router print it to the printer. (Note: network printers is not my ideal solution since routers are not running on the same network as the others)

Currenly, the design of your code doesn't allow me to do so since it is tightly coupled to the Printer Instance. Could you separate the formatting and the Printer instance?

I hope you will implement this since this is an amazing feature where you will generate the prn file and print it anytime.

ricxsar commented 6 years ago

@song940 I am able to create a binary file from the Console adapter. See below code which I added to create the file:

'use strict';
var fs = require("fs");
/**
 * [stdout description]
 * @param  {[type]} data [description]
 * @param  {[type]} bit  [description]
 * @return {[type]}      [description]
 */
function stdout(data, bit){
  fs.writeFileSync("./printer.bin", data, { encoding: "binary" })
  bit = bit || 8;
  for(var i=0;i < data.length;i+= bit){
    var arr = [];
    for(var j=0;j<bit && i+j<data.length;j++) 
      arr.push(data[i + j]);
    arr = arr.map(function(b){
      return b.toString(16).toUpperCase()
    }).map(function(b){
      if(b.length == 1) b = '0' + b;
      return b;
    })

    console.log(arr.join(' '));
  }
  console.log();
}

/**
 * [Console description]
 */
function Console(handler){
  this.handler = handler || stdout;
};
/**
 * [open description]
 * @param  {Function} callback [description]
 * @return {[type]}            [description]
 */
Console.prototype.open = function(callback){
  callback && callback();
};
/**
 * [write description]
 * @param  {[type]} data [description]
 * @param  {[type]} bit  [description]
 * @return {[type]}      [description]
 */
Console.prototype.write = function(data){
  this.handler && this.handler(data);
};

/**
 * [exports description]
 * @type {[type]}
 */
module.exports = Console;

I tried to print it with the following command cat printer.bin > /dev/usb/lp0 and voila it prints perfectly.

Maybe you can redesign the Console Adapter to function like this.