forked from treh1966/ESCPOS-Printing-in-Node.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathescpos_printing.js
1015 lines (872 loc) · 51.7 KB
/
escpos_printing.js
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//======================================================================================================================================================
// escpos_printing.js Version: 1.0.0 by Thomas Höbelt
// Modified to Support chrome.serial in NW.js (PA)
//------------------------------------------------------------------------------------------------------------------------------------------------------
// This is my implementation of ESCPOS Printing from within node nw.js applications
// ADVANTAGE nothing else needed i.e. no dependencies except built in modules:
//'fs' , 'os' ( in fact only needed when using on multiple platforms), and 'child process'
// CEAVEAT: as its based on copying files to the printer-queue biderectional commands are not supported
// Tried to implement all basically necessary (and common betweeen printer models ) commands in an easy usable fashion
// FEEL FREE TO USE/MODIFY THE CODE IN ANY FASHION YOU LIKE
// comments and 'requests' as well as feedback or appreciation might be send to registrierkassa@ad-min.at
// TODO: improve error tracking & implement more of the full command list implement OSX
//------------------------------------------------------------------------------------------------------------------------------------------------------
// Prerequisites:
// At least one RAW-printer needs to be installed on the system :
// Under WINDOWS : just use the printer driver to install, most modern printers support both modes (driver and RAW) automatically
// and !!! share the printer using a NAME which will be listed when network shares are ealuated
// On LINUX (and OSX): just install a (driverless) RAW Printer it will be listed by lp
//------------------------------------------------------------------------------------------------------------------------------------------------------
// Usage:
// Printer = require('escpos_printing.js');
// Printer.ESCPOS_INIT();
// Printer.append(put commands and functions here);
// var sucess = Printer.ESCPOS_PRINT(currentPrinter);
// if(!sucess){
// alert(Printer.ESCPOS_LASTERROR);
// }
//------------------------------------------------------------------------------------------------------------------------------------------------------
// Functions summary:
// ESCPOS_INIT : Initialize globals and lists printers to array
// append : adds commands and Text to the "Print Buffer"
// ESCPOS_CMD : submit a command (as defined in the set)
// ESCPOS_PRINT : collect "Printer Buffer" write it to a prt file and send the file to the printer-queue
// ESCPOS_IMAGEFILE : print image from a file
// ESCPOS_BARCODE : Print Barcodes
// ESCPOS_QRCODE : Print QR-Codes
// ESCPOS_CPBYNUMBER : Select a codepage ( Named Versions available as extra command sets)
// ESCPOS_CP_EPSON : Select codepage as defined by epson
// ESCPOS_CP_STAR : Select Codepage as defined by STAR using standard ESCPOS Command
// STAR_CP : Select codepage using a special command used by star printers
// ESCPOS_CHARSET : select international characterset
//------------------------------------------------------------------------------------------------------------------------------------------------------
// for more examples of usage look at main.js in the zip-file
//=======================================================================================================================================================
//=======================================================================================================================================================
// MODULES "GLOBAL" SECTION
var fileSys = require('fs');
var operatingSys = require('os');
var stream = require('stream');
var PNG = require('pngjs').PNG;
var buffer = null;
function append(buff) {
if (buffer) buffer = Buffer.concat([buffer, buff]);
else buffer = buff;
}
var serialPorts;
var SendingData;
var printQ = [];
//defaulting OS to whatever you like init function will detect appropriately
// this one is needed and must be set to whatever the language of your Win (cmd output) puts out for the Word "Printer"
// as mine is German i set it to the German Expression for Printer which is "Drucker"
// nOt necessary anymore as we use power shell now which is hopefully always in english
//var OS_PRINTERKEYWORD = "Drucker";
// this array will contain shared printers on Win and all lp printers on cups Systems
//exports.ESCPOS_PRINTERLIST = [];
// needs to be filled with the calling mains window object which is done in the init function
// might skip this when using node 13 by using mixed context
var ESCPOS_MOTHER ="";
// Just in Case
exports.ESCPOS_LASTERROR = "";
// The thing we want to create: a fully formatted ESC/POS String
var ESCPOS_RESULT = "";
var Printer; // will be passed in on init.
//=======================================================================================================================================================
//=======================================================================================================================================================
//ESCPOS_INIT
// Initialitiation of Output and printerlist
// should be called before every use because the require will cache code AND values
//-------------------------------------------------------------------------------------------------------------------------------------------------------
exports.ESCPOS_INIT = function (port,CB) {
typeof CB != 'function' && ( CB = () => {} );
log('ESCPOS_INIT Start port '+port);
var listCommand = "";
var listResult = "";
var listResultLines = [];
var listLineParts = [];
var detailParts = [];
// resetting the output to empty string
ESCPOS_RESULT = "";
// and the Errorstring
ESCPOS_LASTERROR = "";
exports.ESCPOS_PRINTERLIST && ( exports.ESCPOS_PRINTERLIST.length = 0 );
CB('ESCPOS_INIT port ' + port);
if ( port ) {
serialPorts = [
{ com: port, device: 'Printer', connected: false, addListener: function(cB) { return this._listen.push(cB); }, _listen: [] }
]
serialPorts.forEach(port => {
CB('Connect Request '+port.com);
chrome.serial.connect(port.com,(resp) => {
CB('Conntected '+port.com+' connectionId '+resp.connectionId);
CB(resp);
port.connected = resp;
serialPorts[port.device] = port;
serialPorts[resp.connectionId] = port;
port.send = (buffer,cB) => {
CB('chrome.serial.send '+resp.connectionId);
chrome.serial.send(resp.connectionId,buffer,(resp) => cB(resp));
}
});
})
}
}
//=======================================================================================================================================================
//=======================================================================================================================================================
//append
// simply adds whatever we like to the modules output string
// used this (notation) because originally i used qz plugin and dindnt want to change the whole code of the mother app
//------------------------------------------------------------------------------------------------------------------------------------------------------
exports.append = function (value) {
ESCPOS_RESULT = ESCPOS_RESULT + value;
}
//=======================================================================================================================================================
//=======================================================================================================================================================
//ESCPOS_PRINT (thats what is all about *fg)
// Parameter:
//the printername which you can get out of the printer list array exports.ESCPOS_PRINTERLIST after initialization
// What is printed is the current content of ESCPOS_RESULT
// only change is the correction of the character Code for the Currency symbol
//--------------------------------------------------------------------------------------------------------------------------------------------------------
// Printing is understood as a one way process in this context, and will simply copy a raw (.prt) File to the printer(queue)
// no check if the printer is online or offline or whether it really is a raw printer
// only errorcheck by result of copy operation
// sucess means the os has copied the file
//-------------------------------------------------------------------------------------------------------------------------------------------------------
log = () => {};
exports.log = function(cB) {
log = (data) => cB(data);
}
exports.ESCPOS_PRINT = function(cB) {
// we use tempdir as it should be available and read/writeble in all Systems
var filename = operatingSys.tmpdir() + "\\escpos-"+Date.now()+".prt";
printQ.push({ sending: false, filename: filename });
// manual correction for the currency Symbol in my case the Euro Sign:
//ESCPOS_RESULT = ESCPOS_RESULT.replace("€",String.fromCharCode(128));
// and just in case you forgot it add a final printit/newline
ESCPOS_RESULT = ESCPOS_RESULT + String.fromCharCode(10);
// write our content to the RAW printer file
cB('ESCPOS_RESULT.length '+ESCPOS_RESULT.length);
fileSys.appendFileSync(filename, ESCPOS_RESULT,'binary');
//We are more or less printed so reinitialize our result string
ESCPOS_RESULT = "";
send();
function send() {
if ( !printQ[0] ) { return; }
if ( printQ[0].sending == true ) { return; }
cB('printQ[0].sending = true');
printQ[0].sending = true;
var file = fileSys.readFileSync(printQ[0].filename);
var unlink = fileSys.unlinkSync(printQ[0].filename);
cB('typeof serialPorts.Printer.send ' + typeof serialPorts.Printer.send);
cB('file.buffer.length '+file.length);
serialPorts.Printer.send(file.buffer,(resp) => { printQ.splice(0,1); send(); typeof cB == 'function' && cB({ result: resp, ESCPOS_RESULT: ESCPOS_RESULT, file }); });
}
}
//=======================================================================================================================================================
//=====================================================================================================================================
// Various Commandsets named appropriately for easy use
//=====================================================================================================================================
//=====================================================================================================================================
//ESCPOS_IMAGEFILE
// Delivers a well formatted ESCPOS String containing all necessary command and the image data from a given fully qualified filename jpg,bmp,gif,svg supported
//-------------------------------------------------------------------------------------------------------------------------------------
// Parameters are the following
// mothetcontext : VERY IMPORTANT !! here you have to supply the calling functions Browser-context window (this.window)
// this is necessary to be able to create an image and a canvas to draw on, even if they are not visible
// FILENAME: STRING fully qualified name of the image file ( Dimensions should fit the max printer width)
// IMGMODE: INTEGER really only 33 makes sense as it wont strech the image in one or the other direction
// 0: 8 dots single density ×2 horizontal ×3 vertical
// 1: 8 dots double density ×1 horizontal ×3 vertical
// 32: 24 dots single density ×2 horizontal×1 vertical
// 33: 24 dots double density ×1 horizontal×1 vertical
//DITHER: BOOLEAN wheather or not to dither (convert to quasi grayscale )the image
//IMGTHRESHOLD: INTEGER (1 to255 practical value is 127) used for simple b/w decision and as a threshold in the dithering part
//-------------------------------------------------------------------------------------------------------------------------------------
exports.appendCanvas = function(canvas,ESCPOS_IMGMODE = 33,ESCPOS_DITHER = true,ESCPOS_IMGTHRESHOLD = 127) {
if ( typeof ESCPOS_IMGMODE == 'object' ) {
ESCPOS_DITHER = ESCPOS_IMGMODE.dither;
ESCPOS_IMGTHRESHOLD = ESCPOS_IMGMODE.threshold;
ESCPOS_IMGMODE = ESCPOS_IMGMODE.mode;
}
ESCPOS_RESULT = ESCPOS_RESULT + exports.ESCPOS_IMAGEFILE(null,canvas,ESCPOS_IMGMODE,ESCPOS_DITHER,ESCPOS_IMGTHRESHOLD)
}
exports.ESCPOS_IMAGEFILE = function (mothercontext,ESCPOS_FILENAME,ESCPOS_IMGMODE,ESCPOS_DITHER,ESCPOS_IMGTHRESHOLD) {
if ( typeof ESCPOS_FILENAME == 'string' ) {
// as we are dealing with a canvas we need to prefix it with the correspondant mime-string
var ESCPOS_extension = ESCPOS_FILENAME.substr(ESCPOS_FILENAME.lastIndexOf('.')+1)
switch (ESCPOS_extension.toUpperCase()) {
case "JPG" :
case "JPEG" :
var ESCPOS_mimestring = "data:image/jpeg;base64,";
break;
case "BMP" :
var ESCPOS_mimestring = "data:image/bmp;base64,";
break;
case "GIF" :
var ESCPOS_mimestring = "data:image/gif;base64,";
break;
case "PNG" :
var ESCPOS_mimestring = "data:image/png;base64,";
break;
case "SVG" :
var ESCPOS_mimestring = "data:image/svg+xml;base64,";
break;
default :
var ESCPOS_mimestring = "data:image/jpeg;base64,";
}
// now we load the file synchronously !!! and draw it to an canvas of the calling i.e. mother context
var ESCPOS_canvas = mothercontext.document.createElement('canvas');
var ESCPOS_context = ESCPOS_canvas.getContext('2d');
var ESCPOS_imagesource = new mothercontext.Image();
ESCPOS_imagesource.onload = () => {
ESCPOS_canvas.width = ESCPOS_imagesource.width;
ESCPOS_canvas.height = ESCPOS_imagesource.height;
ESCPOS_context.drawImage(ESCPOS_imagesource,0,0);
}
ESCPOS_imagesource.src = ESCPOS_mimestring + fileSys.readFileSync(ESCPOS_FILENAME).toString("base64");
} else {
switch ( ESCPOS_FILENAME.tagName ) {
case 'CANVAS':
ESCPOS_canvas = ESCPOS_FILENAME;
ESCPOS_context = ESCPOS_canvas.getContext('2d');
ESCPOS_imagesource = { width: ESCPOS_canvas.width, height: ESCPOS_canvas.height }
break;
case 'IMG':
var ESCPOS_imagesource = ESCPOS_FILENAME;
var ESCPOS_canvas = mothercontext.document.createElement('canvas');
var ESCPOS_context = ESCPOS_canvas.getContext('2d');
ESCPOS_canvas.width = ESCPOS_imagesource.width;
ESCPOS_canvas.height = ESCPOS_imagesource.height;
//ESCPOS_canvas.setAttribute('width', ESCPOS_imagesource.width);
//ESCPOS_canvas.setAttribute('height', ESCPOS_imagesource.height);
ESCPOS_context.drawImage(ESCPOS_imagesource,0,0);
break;
}
// ESCPOS_FILENAME is CANVAS
/*
ESCPOS_canvas = ESCPOS_FILENAME;
ESCPOS_context = ESCPOS_canvas.getContext('2d');
ESCPOS_imagesource = { width: ESCPOS_canvas.width, height: ESCPOS_canvas.height }
*/
// ESCPOS_FILENAME is IMG
}
// for the actual processing we need to split the image into lines of the given ( 8 or 24 pixels) height i.e. vertical slizesize
// all the fuss is necessary because imagedata from canvas is supplied in rows of single pixels
// so we need to iterate properly
// holds the canvas data transfered into pixel color information
var ESCPOS_imagedata = "";
// a simple representation of black or white info in a zero or one based string representing one or three bytes
var ESCPOS_bytestring = "";
// the b/w data for one printhead movement
var ESCPOS_onelinedata ="";
// this helps us to move to the right pixel information as the color information has other sequence than we need
var ESCPOS_pixeldataoffset = 0;
// by this we make the decision to print black or white pixels
// dont worry about the same variable used for dithering
// if you first dither its more or less irrelevant because the dithered image already contains only b/w pixels which wil be calculated right alsmost no matter what is used
var ESCPOS_pixeltreshold = ESCPOS_IMGTHRESHOLD;
// what we want to produce
var ESCPOS_output = "";
//create the appropriate command and set the line height (internal parameter) in pixels;
switch (ESCPOS_IMGMODE) {
case 0:
var ESCPOS_verticalslicesize = 8;
var ESCPOS_modepraefix = '00';
break;
case 1:
var ESCPOS_verticalslicesize = 8;
ESCPOS_modepraefix = '01';
break;
case 32:
var ESCPOS_verticalslicesize = 24;
var ESCPOS_modepraefix = '20';
break;
case 33:
var ESCPOS_verticalslicesize = 24;
var ESCPOS_modepraefix = '21';
break;
default:
var ESCPOS_verticalslicesize = 24;
var ESCPOS_modepraefix = '21';
}
// calculate hibyte and lowbyte as hex starings
var ESCPOS_HHSTRING = ("00"+ Math.floor(ESCPOS_canvas.width/256).toString(16)).slice(-2);
var ESCPOS_HLSTRING = ("00"+ Math.floor(ESCPOS_canvas.width%256).toString(16)).slice(-2);
// the actual printig command which needs to be filled with parameters for every pass
var ESCPOS_imagepraefix = new Buffer('1B2A'+ESCPOS_modepraefix+ESCPOS_HLSTRING+ESCPOS_HHSTRING,'hex');
// calculate how many rows we need for the given image rounded up so we dont loose any anformation but fill up with white space
var ESCPOS_linecount = Math.ceil(ESCPOS_canvas.height/ESCPOS_verticalslicesize)
// create a (hex) Buffer which will hold exactly one vertical line of printer dots in x bytes
var ESCPOS_pixeldata = new Buffer(ESCPOS_verticalslicesize/8);
// now we transfer the canvas data into an array containing four values per pixel i.e. the color information
ESCPOS_imagedata = ESCPOS_context.getImageData(0, 0, ESCPOS_canvas.width,ESCPOS_canvas.height );
// on that array we might apply the dithering algorithm
if (ESCPOS_DITHER) {
ESCPOS_imagedata = monochrome(ESCPOS_imagedata,ESCPOS_IMGTHRESHOLD,"");
}
// outer iteration is one line of 8 or 24 pixels of the image (printhead movement )
for(var lines = 0;lines < ESCPOS_linecount; lines++){
ESCPOS_onelinedata = ESCPOS_imagepraefix.toString('binary');
// finally evaluate the pixel values vor every 8 or 24 pixel column of 127 or less columns
for ( var pixelcolumn = 0 ; pixelcolumn< ESCPOS_imagesource.width; pixelcolumn ++) {
// each pixels evaluation end up in a 0 or 1 literal
ESCPOS_bytestring = "";
// iterate through a single (of 127 or less ) column of 8 or 24 pixels
for(var zeile = 0; zeile < ESCPOS_verticalslicesize; zeile++){
// one ugly line of code to evaluate the pixel data i.e. use a standard algorithm to decide black or white from the first three pixel color informations
// comparing them to the threshold value and converting it to a 0 or 1 literal
//adding that one to the bytestring initialized before the loop
ESCPOS_bytestring = ESCPOS_bytestring + ((((ESCPOS_imagedata.data[ESCPOS_pixeldataoffset]*0.3) + (ESCPOS_imagedata.data[ESCPOS_pixeldataoffset+1]*0.59)+(ESCPOS_imagedata.data[ESCPOS_pixeldataoffset+2]*0.11))< ESCPOS_pixeltreshold)*1).toString();
// a few lines more but better readable to do just the same
//BlackOrWhite = (imgData.data[ESCPOS_pixeldataoffset]*0.3) + (imgData.data[ESCPOS_pixeldataoffset+1]*0.59)+(imgData.data[ESCPOS_pixeldataoffset+2]*0.11);
//if (BlackOrWhite < ESCPOS_pixeltreshold) {
// ESCPOS_bytestring = ESCPOS_bytestring +"1";
//}else{
// ESCPOS_bytestring = ESCPOS_bytestring+ "0";
//}
// VERY IMPORTANT
// if we advance one times the full width multiplied by 4 ( remember each pixel has four colour values in the image data)
// we get exactly to the position of the pixel below the last one
ESCPOS_pixeldataoffset = ESCPOS_pixeldataoffset + (ESCPOS_canvas.width*4)
}
// finally convert our bitwise literals into bytes
//if we are in 8 pixel mode one byte is enough
ESCPOS_pixeldata[0] = parseInt(ESCPOS_bytestring.substring(0,7),2);
// if we process 24 pixels we need three bytes and have initialized the buffer to 3 instead of 1
if (ESCPOS_pixeldata.length>1) {
ESCPOS_pixeldata[1] = parseInt(ESCPOS_bytestring.substring(8,15),2);
ESCPOS_pixeldata[2] = parseInt(ESCPOS_bytestring.substring(16,23),2);
}
// add this column of pixels to the line result string
ESCPOS_onelinedata = ESCPOS_onelinedata + ESCPOS_pixeldata.toString('ascii');
// now we have to move back the whole way minus one pixel to get to the top of the next column
ESCPOS_pixeldataoffset = ESCPOS_pixeldataoffset -((ESCPOS_canvas.width*4*ESCPOS_verticalslicesize)-4);
}
// add the single line result to the general result
ESCPOS_output = ESCPOS_output + ESCPOS_onelinedata;
// we are done with what ? one line of printer data so we need to tell the printer to print and go to the next line
ESCPOS_output = ESCPOS_output + String.fromCharCode(10);
// as we already moved back to the next, but not to be processed pixel( as it would not be the next column in the row )
// we move foreward one full line of data i.e. one pixelrow (width * 4) * lines in a line
ESCPOS_pixeldataoffset = ESCPOS_pixeldataoffset+(ESCPOS_canvas.width*4*ESCPOS_verticalslicesize);
}
return ESCPOS_output;
}
//=====================================================================================================================================
//=======================================================================================================================================================
// monochrome only used internally (called by ESCPOS_IMAGEFILE )
// Dithering image data
// thanks to http://meemoo.org
// http://stackoverflow.com/questions/12422407/monochrome-dithering-in-javascript-bayer-atkinson-floyd-steinberg
//-------------------------------------------------------------------------------------------------------------------------------------------------------
// I use an empty value for the type parameter which makes use of Bill Atkinson's dithering algorithm which made best results with my test images
// If you want to use different ones you have to adopt the function call
// using "none" doesnt make sense because the default b/w decision is included in ESCPOS_IMAGEFILE
//-------------------------------------------------------------------------------------------------------------------------------------------------------
function monochrome(imageData, threshold, type){
var bayerThresholdMap = [
[ 15, 135, 45, 165 ],
[ 195, 75, 225, 105 ],
[ 60, 180, 30, 150 ],
[ 240, 120, 210, 90 ]
];
var lumR = [];
var lumG = [];
var lumB = [];
for (var i=0; i<256; i++) {
lumR[i] = i*0.299;
lumG[i] = i*0.587;
lumB[i] = i*0.114;
}
var imageDataLength = imageData.data.length;
// Greyscale luminance (sets r pixels to luminance of rgb)
for (var i = 0; i <= imageDataLength; i += 4) {
imageData.data[i] = Math.floor(lumR[imageData.data[i]] + lumG[imageData.data[i+1]] + lumB[imageData.data[i+2]]);
}
var w = imageData.width;
var newPixel, err;
for (var currentPixel = 0; currentPixel <= imageDataLength; currentPixel+=4) {
if (type === "none") {
// No dithering
imageData.data[currentPixel] = imageData.data[currentPixel] < threshold ? 0 : 255;
} else if (type === "bayer") {
// 4x4 Bayer ordered dithering algorithm
var x = currentPixel/4 % w;
var y = Math.floor(currentPixel/4 / w);
var map = Math.floor( (imageData.data[currentPixel] + bayerThresholdMap[x%4][y%4]) / 2 );
imageData.data[currentPixel] = (map < threshold) ? 0 : 255;
} else if (type === "floydsteinberg") {
// Floyd–Steinberg dithering algorithm
newPixel = imageData.data[currentPixel] < 129 ? 0 : 255;
err = Math.floor((imageData.data[currentPixel] - newPixel) / 16);
imageData.data[currentPixel] = newPixel;
imageData.data[currentPixel + 4 ] += err*7;
imageData.data[currentPixel + 4*w - 4 ] += err*3;
imageData.data[currentPixel + 4*w ] += err*5;
imageData.data[currentPixel + 4*w + 4 ] += err*1;
} else {
// Bill Atkinson's dithering algorithm
newPixel = imageData.data[currentPixel] < threshold ? 0 : 255;
err = Math.floor((imageData.data[currentPixel] - newPixel) / 8);
imageData.data[currentPixel] = newPixel;
imageData.data[currentPixel + 4 ] += err;
imageData.data[currentPixel + 8 ] += err;
imageData.data[currentPixel + 4*w - 4 ] += err;
imageData.data[currentPixel + 4*w ] += err;
imageData.data[currentPixel + 4*w + 4 ] += err;
imageData.data[currentPixel + 8*w ] += err;
}
// Set g and b pixels equal to r
imageData.data[currentPixel + 1] = imageData.data[currentPixel + 2] = imageData.data[currentPixel];
}
return imageData;
}
// thanks to http://meemoo.org
// http://stackoverflow.com/questions/12422407/monochrome-dithering-in-javascript-bayer-atkinson-floyd-steinberg
//=======================================================================================================================================================
//=====================================================================================================================================
//ESCPOS_BARCODE
// Deliveres a well formatted string containing commands and barcode data
//-------------------------------------------------------------------------------------------------------------------------------------
// Parameters as follows
// BARCONTENT: STRING self expaining, but what is acceptes depends on the code type ( Aplphanumeric or numeric only , number of characters )
// BARTYPE: INTEGER 65: UPC-A 66: UPC-B 67: EAN-13 68: EAN-8 69: Code39 70: Interleaved 2of5 71: Codabar 72: Code-39 73: Code-128 74: UCC/Ean-128
// BARWIDTH: INTEGER range 2 to 6
// BARHEIGHT: INTEGER range 1 to 255 (dots)
// HRFONT 0 for Printerfont A, 1 for Printerfont B
// HRIPOSITION INTEGER 0: not printed , 1: above Code, 2: below Code, 3 above and below
//-------------------------------------------------------------------------------------------------------------------------------------
exports.ESCPOS_BARCODE = function barcode(ESCPOS_BARCONTENT,ESCPOS_BARTYPE,ESCPOS_BARWIDTH,ESCPOS_BARHEIGHT,ESCPOS_HRIFONT,ESCPOS_HRIPOSITION) {
var output = "";
var parametercommands = new Buffer(12);
//barcode Height
parametercommands[0]='0x1D';
parametercommands[1]='0x68';
parametercommands[2]=ESCPOS_BARHEIGHT;
// barcode width
parametercommands[3]='0x1D';
parametercommands[4]='0x77';
parametercommands[5]=ESCPOS_BARWIDTH;
//Human readable charcters size
parametercommands[6]='0x1D';
parametercommands[7]='0x66';
parametercommands[8]=ESCPOS_HRIFONT;
// human readable position
parametercommands[9]='0x1D';
parametercommands[10]='0x48';
parametercommands[11]=ESCPOS_HRIPOSITION;
var printcommand = new Buffer(4);
printcommand[0] = '0x1D';
printcommand[1] = '0x6B';
//codetyp
printcommand[2] = ESCPOS_BARTYPE;
printcommand[3] = ESCPOS_BARCONTENT.length;
output = parametercommands.toString('utf8')+printcommand.toString('utf8')+ESCPOS_BARCONTENT+String.fromCharCode(10);
return output;
}
//=====================================================================================================================================
//=====================================================================================================================================
//ESCPOS_QRCODE
// Delivers a well formatted ESCPOS String containing all necessary command and content information for QR Codes
// Thanks to http://stackoverflow.com/users/1599609/josue-ibarra
// Answers section of : http://stackoverflow.com/questions/23577702/printing-qr-codes-through-an-esc-pos-thermal-printer
//-------------------------------------------------------------------------------------------------------------------------------------
// Parameters as follows
// QRDATA STRING ---self explaining
// QRMODEL INTEGER 49: Model 1 , 50: Model 2 , 51: Micro QR
// QRSIZE: INTEGER 1 - 16 depends on Printer up to which size this will work default in ESCPOS is 3
// QRERRORC: INTEGER 48: 7%, 49: 15% , 50: 25%, 51: 30%
//-------------------------------------------------------------------------------------------------------------------------------------
exports.ESCPOS_QRCODE = function (ESCPOS_QRDATA,ESCPOS_QRMODEL,ESCPOS_QRSIZE, ESCPOS_QRERRORC){
var output = "";
var store_len = ESCPOS_QRDATA.length+ 3;
var sizebytes = new Buffer(2);
sizebytes[0] = store_len % 256 ;
sizebytes[1] = store_len / 256;
// QR Code: Select the model
// Hex 1D 28 6B 04 00 31 41 n1(x32) n2(x00) - size of model
// set n1 [49 x31, model 1] [50 x32, model 2] [51 x33, micro qr code]
// https://reference.epson-biz.com/modules/ref_escpos/index.php?content_id=140
var modelQR = new Buffer('1d286b04003141'+("00"+ESCPOS_QRMODEL.toString(16)).slice(-2)+'00','hex');
// QR Code: Set the size of module
// Hex 1D 28 6B 03 00 31 43 n
// n depends on the printer
// https://reference.epson-biz.com/modules/ref_escpos/index.php?content_id=141
var sizeQR = new Buffer('1d286b03003143'+("00"+ESCPOS_QRSIZE.toString(16)).slice(-2),'hex');
// QR Code: Set the errorcorrection level // Hex 1D 28 6B 03 00 31 45 n
// Set n for error correction [48 x30 -> 7%] [49 x31-> 15%] [50 x32 -> 25%] [51 x33 -> 30%]
// https://reference.epson-biz.com/modules/ref_escpos/index.php?content_id=142
var errorQR = new Buffer('1d286b03003145'+("00"+ESCPOS_QRERRORC.toString(16)).slice(-2),'hex');
// QR Code: Store the data in the symbol storage area
// Hex 1D 28 6B pL pH 31 50 30 d1...dk
// https://reference.epson-biz.com/modules/ref_escpos/index.php?content_id=143
// 1D 28 6B pL pH cn(49->x31) fn(80->x50) m(48->x30) d1…dk
//needed to do this in three parts to include the appropriate two bites with the length information
var storeQR1 = new Buffer('1d286b','hex');
var storeQR2 = new Buffer('315030','hex');
var storeQR = storeQR1.toString('ascii')+sizebytes.toString('ascii')+storeQR2.toString('ascii');
// QR Code: Print the symbol data in the symbol storage area
// Hex 1D 28 6B 03 00 31 51 m
// https://reference.epson-biz.com/modules/ref_escpos/index.php?content_id=144
var printQR = new Buffer('1d286b0300315130','hex');
output = output + modelQR.toString('utf8');
output = output + sizeQR.toString('utf8');
output = output + errorQR.toString('utf8');
output = output + storeQR;
//output = output + ESCPOS_QRDATA;
output = output + new Buffer(ESCPOS_QRDATA,'binary').toString('utf8');
output = output + printQR.toString('utf8');
//output = output + String.fromCharCode(10);
return output;
}
// Thanks to http://stackoverflow.com/users/1599609/josue-ibarra
// Answers section of : http://stackoverflow.com/questions/23577702/printing-qr-codes-through-an-esc-pos-thermal-printer
//=====================================================================================================================================
//=====================================================================================================================================
// Named Constants for selecting the characterset
// had to tryout a lot to get the right characterset and codepage settings for my printer and language
//-------------------------------------------------------------------------------------------------------------------------------------
exports.ESCPOS_CHARSET = {
USA: new Buffer('1B5200','hex').toString('utf8'),
FRANCE: new Buffer('1B5201','hex').toString('utf8'),
GERMANY: new Buffer('1B5202','hex').toString('utf8'),
UK: new Buffer('1B5203','hex').toString('utf8'),
DENMK_1: new Buffer('1B5204','hex').toString('utf8'),
SWEDEN: new Buffer('1B5205','hex').toString('utf8'),
ITALY: new Buffer('1B5206','hex').toString('utf8'),
SPAIN_1: new Buffer('1B5207','hex').toString('utf8'),
JAPAN: new Buffer('1B5208','hex').toString('utf8'),
NORWAY: new Buffer('1B5209','hex').toString('utf8'),
DENMK_2: new Buffer('1B520A','hex').toString('utf8'),
SPAIN_2: new Buffer('1B520B','hex').toString('utf8'),
LATINAMERICA: new Buffer('1B520C','hex').toString('utf8'),
KOREAN: new Buffer('1B520D','hex').toString('utf8'),
SLOVENIA_CROATIA: new Buffer('1B520E','hex').toString('utf8'),
CHINA: new Buffer('1B520F','hex').toString('utf8'),
VIETNAM: new Buffer('1B5210','hex').toString('utf8'),
ARABIA: new Buffer('1B5211','hex').toString('utf8')
}
//=====================================================================================================================================
//=====================================================================================================================================
// Function to select Codepage by Number
// i.e. if You know your printers understanding of the "Ecc J" Parameter
// had to tryout a lot to get the right characterset and codepage settings for my printer and language
//-------------------------------------------------------------------------------------------------------------------------------------
exports.ESCPOS_CPBYNUMBER = function(pagenumber) {
return new Buffer ('1B74'+("00"+pagenumber.toString(16)).slice(-2),'hex').toString('utf8');
}
//=====================================================================================================================================
//=====================================================================================================================================
// Named Constants for selecting the codepages as defined by EPSON using the standard ESCPOS Command
// had to tryout a lot to get the right characterset and codepage settings for my printer and language
//-------------------------------------------------------------------------------------------------------------------------------------
exports.ESCPOS_CP_EPSON = {
USA_437 : exports.ESCPOS_CPBYNUMBER(0),
KATAKANA : exports.ESCPOS_CPBYNUMBER(1),
MULTILINGUAL_850 : exports.ESCPOS_CPBYNUMBER(2),
PORTUGUESE_860 : exports.ESCPOS_CPBYNUMBER(3),
CANADIANFRENCH_863 : exports.ESCPOS_CPBYNUMBER(4),
NORDIC_865 : exports.ESCPOS_CPBYNUMBER(5),
SIPLIFIEDKANJI_HIRAKANA : exports.ESCPOS_CPBYNUMBER(6),
SIPLIFIEDKANJI_II : exports.ESCPOS_CPBYNUMBER(7),
SIPLIFIEDKANJI_III : exports.ESCPOS_CPBYNUMBER(8),
LATINI_1252 : exports.ESCPOS_CPBYNUMBER(16),
CYRILLIC2_866 : exports.ESCPOS_CPBYNUMBER(17),
LATINII_852 : exports.ESCPOS_CPBYNUMBER(18),
EURO_858 : exports.ESCPOS_CPBYNUMBER(19),
HEBREW_862 : exports.ESCPOS_CPBYNUMBER(21),
ARABIC_864 : exports.ESCPOS_CPBYNUMBER(22),
THAI_42 : exports.ESCPOS_CPBYNUMBER(23),
GREEK_1253 : exports.ESCPOS_CPBYNUMBER(24),
TURKISH_1254 : exports.ESCPOS_CPBYNUMBER(25),
BALTIC_1257 : exports.ESCPOS_CPBYNUMBER(26),
FARSI : exports.ESCPOS_CPBYNUMBER(27),
CYRILLIC_1251 : exports.ESCPOS_CPBYNUMBER(28),
GREEK_737 : exports.ESCPOS_CPBYNUMBER(29),
BALTIC_775 : exports.ESCPOS_CPBYNUMBER(30),
THAI_14 : exports.ESCPOS_CPBYNUMBER(31),
HEBREWNEW_1255 : exports.ESCPOS_CPBYNUMBER(33),
THAI11 : exports.ESCPOS_CPBYNUMBER(34),
THAI8 : exports.ESCPOS_CPBYNUMBER(35),
CYRILLIC_855 : exports.ESCPOS_CPBYNUMBER(36),
TURKISH_857 : exports.ESCPOS_CPBYNUMBER(37),
GREEK_928 : exports.ESCPOS_CPBYNUMBER(38),
THAI_16 : exports.ESCPOS_CPBYNUMBER(39),
ARABIC_1256 : exports.ESCPOS_CPBYNUMBER(40),
VIETNAM_1258 : exports.ESCPOS_CPBYNUMBER(41),
KHMER : exports.ESCPOS_CPBYNUMBER(42),
CZECH_1250 : exports.ESCPOS_CPBYNUMBER(47)
}
//=====================================================================================================================================
//=====================================================================================================================================
// Named Constants for selecting the codepages as defined by STAR using the standard ESCPOS Command
// had to tryout a lot to get the right characterset and codepage settings for my printer and language
//-------------------------------------------------------------------------------------------------------------------------------------
exports.ESCPOS_CP_STAR = {
USA_437 : exports.ESCPOS_CPBYNUMBER(0),
KATAKANA : exports.ESCPOS_CPBYNUMBER(1),
MULTILINGUAL_850 : exports.ESCPOS_CPBYNUMBER(2),
PORTUGUESE_860 : exports.ESCPOS_CPBYNUMBER(3),
CANADIANFRENCH_863 : exports.ESCPOS_CPBYNUMBER(4),
NORDIC_865 : exports.ESCPOS_CPBYNUMBER(5),
LATINI_1252 : exports.ESCPOS_CPBYNUMBER(16),
CYRILLIC2_866 : exports.ESCPOS_CPBYNUMBER(17),
LATINII_852 : exports.ESCPOS_CPBYNUMBER(18),
EURO_858 : exports.ESCPOS_CPBYNUMBER(19),
THAICC_42 : exports.ESCPOS_CPBYNUMBER(20),
THAICC_11 : exports.ESCPOS_CPBYNUMBER(21),
THAICC_13 : exports.ESCPOS_CPBYNUMBER(22),
THAICC_14 : exports.ESCPOS_CPBYNUMBER(23),
THAICC_16 : exports.ESCPOS_CPBYNUMBER(24),
THAICC_17 : exports.ESCPOS_CPBYNUMBER(25),
THAICC_18 : exports.ESCPOS_CPBYNUMBER(26)
}
//=====================================================================================================================================
//=====================================================================================================================================
// Named Constants for selecting the codepages as defined by STAR using the SPECIAL COMMAND for STAR PRINTERS (only?)
// had to tryout a lot to get the right characterset and codepage settings for my printer and language
//-------------------------------------------------------------------------------------------------------------------------------------
exports.STAR_CP ={
Default : new Buffer('1B1D7400','hex').toString('utf8'),
USA_437 : new Buffer('1B1D7401','hex').toString('utf8'),
Katakana : new Buffer('1B1D7402','hex').toString('utf8'),
StdEurope_437 : new Buffer('1B1D7403','hex').toString('utf8'),
Multilingual_858 : new Buffer('1B1D7404','hex').toString('utf8'),
Latin2_852 : new Buffer('1B1D7405','hex').toString('utf8'),
Portuguese_860 : new Buffer('1B1D7406','hex').toString('utf8'),
Icelandic_861 : new Buffer('1B1D7407','hex').toString('utf8'),
CanadianFrench_863 : new Buffer('1B1D7408','hex').toString('utf8'),
Nordic_865 : new Buffer('1B1D7409','hex').toString('utf8'),
CyrillicRussian_866 : new Buffer('1B1D740A','hex').toString('utf8'),
CyrillicBulgarian_855 : new Buffer('1B1D740B','hex').toString('utf8'),
Turkish_857 : new Buffer('1B1D740C','hex').toString('utf8'),
Hebrew_862 : new Buffer('1B1D740D','hex').toString('utf8'),
Arabic_864 : new Buffer('1B1D740E','hex').toString('utf8'),
Greek_737 : new Buffer('1B1D740F','hex').toString('utf8'),
Greek_851 : new Buffer('1B1D7410','hex').toString('utf8'),
Greek_869 : new Buffer('1B1D7411','hex').toString('utf8'),
Greek_928 : new Buffer('1B1D7412','hex').toString('utf8'),
Lithuanian_772 : new Buffer('1B1D7413','hex').toString('utf8'),
Lithuanian_774 : new Buffer('1B1D7414','hex').toString('utf8'),
Thai_874 : new Buffer('1B1D7415','hex').toString('utf8'),
WindowsLatin1_1252 : new Buffer('1B1D7420','hex').toString('utf8'),
WindowsLatin2_1250 : new Buffer('1B1D7421','hex').toString('utf8'),
WindowsCyrillic_1251 : new Buffer('1B1D7422','hex').toString('utf8'),
IBMRussian_3840 : new Buffer('1B1D7440','hex').toString('utf8'),
Gost_3841 : new Buffer('1B1D7441','hex').toString('utf8'),
Polish_3843 : new Buffer('1B1D7442','hex').toString('utf8'),
CS2_3844 : new Buffer('1B1D7443','hex').toString('utf8'),
Hungarian_3845 : new Buffer('1B1D7444','hex').toString('utf8'),
Turkish_3846 : new Buffer('1B1D7445','hex').toString('utf8'),
BrazilABNT_3847 : new Buffer('1B1D7446','hex').toString('utf8'),
BrazilABICOMP_3848 : new Buffer('1B1D7447','hex').toString('utf8'),
Arabic_1001 : new Buffer('1B1D7448','hex').toString('utf8'),
LithuanianKBL_2001 : new Buffer('1B1D7449','hex').toString('utf8'),
Estonian1_3001 : new Buffer('1B1D744A','hex').toString('utf8'),
Estonian2_3002 : new Buffer('1B1D744B','hex').toString('utf8'),
Latvian1_3011 : new Buffer('1B1D744C','hex').toString('utf8'),
Latvian2_3012 : new Buffer('1B1D744D','hex').toString('utf8'),
Bulgarian_3021 : new Buffer('1B1D744E','hex').toString('utf8'),
Maltese_3041 : new Buffer('1B1D744F','hex').toString('utf8'),
Thai_CC42 : new Buffer('1B1D7460','hex').toString('utf8'),
Thai_CC11 : new Buffer('1B1D7461','hex').toString('utf8'),
Thai_CC13 : new Buffer('1B1D7462','hex').toString('utf8'),
Thai_CC14 : new Buffer('1B1D7463','hex').toString('utf8'),
Thai_CC16 : new Buffer('1B1D7464','hex').toString('utf8'),
Thai_CC17 : new Buffer('1B1D7465','hex').toString('utf8'),
Thai_CC18 : new Buffer('1B1D7466','hex').toString('utf8')
}
exports.ESCPOS_CMD = {
RESET: new Buffer('1B40','hex').toString('utf8'),
FONTA: new Buffer('1B4D00','hex').toString('utf8'),
FONTB: new Buffer('1B4D01','hex').toString('utf8'),
NORMAL: new Buffer('1B4500','hex').toString('utf8'),
BOLD: new Buffer('1B4501','hex').toString('utf8'),
NOUNDERLINE: new Buffer('1B2D00','hex').toString('utf8'),
THINUNDERLINE: new Buffer('1B2D01','hex').toString('utf8'),
THICKUNDERLINE: new Buffer('1B2D02','hex').toString('utf8'),
SETSIZE: function(width,height){
var command = new Buffer('1D21'+("00"+((width-1)*16)+(height-1).toString(16)).slice(-2),'hex').toString('utf8');
return command
},
SMOOTH_ON: new Buffer('1D62FF','hex').toString('utf8'),
SMOOTH_OFF: new Buffer('1D6200','hex').toString('utf8'),
DOUBLE_ON: new Buffer('1B4701','hex').toString('utf8'),
DOUBLE_OFF: new Buffer('1B4700','hex').toString('utf8'),
UPSDOWN_ON: new Buffer('1B7B01','hex').toString('utf8'),
UPSDOWN_OFF: new Buffer('1B7B00','hex').toString('utf8'),
TURN90_ON: new Buffer('1B5601','hex').toString('utf8'),
TURN90_OFF: new Buffer('1B5600','hex').toString('utf8'),
INVERT_ON: new Buffer('1D4201','hex').toString('utf8'),
INVERT_OFF: new Buffer('1D4200','hex').toString('utf8'),
LEFT: new Buffer('1B6100','hex').toString('utf8'),
CENTER: new Buffer('1B6101','hex').toString('utf8'),
RIGHT: new Buffer('1B6102','hex').toString('utf8'),
PAGE_MODE: new Buffer('1B4C','hex').toString('utf8'),
OPEN_DRAWER: new Buffer('1B70301919').toString('utf8'),
// mere cutting command will cut paper in the middle of your text due to different positions of print- and cuthead
// looks like not all printers support different cutting modes
CUT_FULL: new Buffer('1D5630','hex').toString('utf8'),
CUT_PARTIAL: new Buffer('1D5631','hex').toString('utf8'),
// feed x motionunits and cut
FEEDCUT_FULL: function(units){
command = new Buffer('1D5641'+("00"+units.toString(16)).slice(-2),'hex').toString('utf8');
return command
},
FEEDCUT_PARTIAL: function(units){
command = new Buffer('1D5642'+("00"+units.toString(16)).slice(-2),'hex').toString('utf8');
return command
},
FEEDUNITS_ANDPRINT: function(units){
var command = new Buffer('1B4A'+("00"+units.toString(16)).slice(-2),'hex').toString('utf8');
return command;
},
FEEDLINES_ANDPRINT: function(units){
var command = new Buffer('1B64'+("00"+units.toString(16)).slice(-2),'hex').toString('utf8');
return command;
},
// not supported by all printers
PRINT_GOBACK: function(units){
var command = new Buffer('1B65'+("00"+units.toString(16)).slice(-2),'hex').toString('utf8');
return command;
},
RIGHT_SPACE: function(units){
var command = new Buffer('1B20'+("00"+units.toString(16)).slice(-2),'hex').toString('utf8');
return command;
},
LINE_SPACE: function(units){
var command = new Buffer('1B33'+("00"+units.toString(16)).slice(-2),'hex').toString('utf8');
return command;
},
LINE_SPACE_DEFAULT: new Buffer('1B32','hex').toString('utf8')
}
exports.openDrawer = function(cB) {
serialPorts.Printer.send(new Buffer('','hex').buffer,(resp) => { cB(resp) });
}
exports.printBuffer = function(buffer,cB) {
serialPorts.Printer.send(buffer,resp => { cB(resp) });
}
exports.printCanvas = function(canvas, cB){
let png = new PNG({
filterType: 4
});
var image = canvas.toDataURL();
var filename = __dirname+'\\print-canvas-'+Date.now()+'.png';
fileSys.appendFileSync(filename, new Buffer(image.replace(/^data:image\/\w+;base64,/, ""),'base64') ,'binary');
log('Printing - '+filename);
fileSys.createReadStream(filename)
.pipe(png)
.on('parsed', function() {
log('on parsed - '+filename);
exports._printImageBufferEpson(this.width, this.height, this.data, function(buff){
log('_printImageBufferEpson '+this.width+' '+this.height);
serialPorts.Printer.send(buff.buffer,(resp) => { log('Completed - '+filename); typeof cB == 'function' && cB({ result: resp }); });
});
})
.on('error', function(err) {
log('printBuff Error');
log(err);
});
},
exports._printImageBufferEpson = function(width, height, data, callback){
var buffer = null;
function append(buff) {
if (buffer) buffer = Buffer.concat([buffer, buff]);
else buffer = buff;
}
// Get pixel rgba in 2D array
var pixels = [];
for (var i = 0; i < height; i++) {
var line = [];
for (var j = 0; j < width; j++) {
var idx = (width * i + j) << 2;
line.push({
r: data[idx],
g: data[idx + 1],
b: data[idx + 2],
a: data[idx + 3]
});
}
pixels.push(line);
}
var imageBuffer_array=[];
for (var i = 0; i < height; i++) {
for (var j = 0; j < Math.ceil(width/8); j++) {
var byte = 0x0;
for (var k = 0; k < 8; k++) {
var pixel = pixels[i][j*8 + k];
// Image overflow
if(pixel === undefined){
pixel = {
a: 0,
r: 0,
g: 0,
b: 0
};
}
if(pixel.a > 126){ // checking transparency
var grayscale = parseInt(0.2126 * pixel.r + 0.7152 * pixel.g + 0.0722 * pixel.b);
if(grayscale < 128){ // checking color
var mask = 1 << 7-k; // setting bitwise mask
byte |= mask; // setting the correct bit to 1
}
}
}
imageBuffer_array.push(byte);
// imageBuffer = Buffer.concat([imageBuffer, new Buffer([byte])]);
}
}
let imageBuffer = Buffer.from(imageBuffer_array);
// Print raster bit image
// GS v 0
// 1D 76 30 m xL xH yL yH d1...dk
// xL = (this.width >> 3) & 0xff;
// xH = 0x00;
// yL = this.height & 0xff;
// yH = (this.height >> 8) & 0xff;
// https://reference.epson-biz.com/modules/ref_escpos/index.php?content_id=94
// Check if width/8 is decimal
if(width%8 != 0) {
width += 8;
}
append(new Buffer ([0x1d, 0x76, 0x30, 48]));
append(new Buffer ([(width >> 3) & 0xff]));
append(new Buffer ([0x00]));
append(new Buffer ([height & 0xff]));
append(new Buffer ([(height >> 8) & 0xff]));
// append data
append(imageBuffer);
// Add Feed & Cut.
append(new Buffer ([0x1d, 0x56, 0x42, 0x40 ]));
// Don't forget to clean the buffer
let buff = buffer;
buffer = null;
callback(buff);
log('callback(buff)');
return buff;
}
//=====================================================================================================================================
//LICENSE =============================================================================================================================
//MIT License
//
//Copyright (c) [2016] [Thomas Höbelt]
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//