-
Notifications
You must be signed in to change notification settings - Fork 381
Expand file tree
/
Copy pathgenerator.dart
More file actions
840 lines (748 loc) · 25.8 KB
/
generator.dart
File metadata and controls
840 lines (748 loc) · 25.8 KB
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
/*
* esc_pos_utils
* Created by Andrey U.
*
* Copyright (c) 2019-2020. All rights reserved.
* See LICENSE for distribution and usage details.
*/
import 'dart:convert';
import 'dart:typed_data' show Uint8List;
import 'package:hex/hex.dart';
import 'package:image/image.dart';
import 'package:gbk_codec/gbk_codec.dart';
import 'package:esc_pos_utils/esc_pos_utils.dart';
import 'enums.dart';
import 'commands.dart';
class Generator {
Generator(this._paperSize, this._profile, {this.spaceBetweenRows = 5});
// Ticket config
final PaperSize _paperSize;
CapabilityProfile _profile;
int? _maxCharsPerLine;
// Global styles
String? _codeTable;
PosFontType? _font;
// Current styles
PosStyles _styles = PosStyles();
int spaceBetweenRows;
// ************************ Internal helpers ************************
int _getMaxCharsPerLine(PosFontType? font) {
if (_paperSize == PaperSize.mm58) {
return (font == null || font == PosFontType.fontA) ? 32 : 42;
} else {
return (font == null || font == PosFontType.fontA) ? 48 : 64;
}
}
// charWidth = default width * text size multiplier
double _getCharWidth(PosStyles styles, {int? maxCharsPerLine}) {
int charsPerLine = _getCharsPerLine(styles, maxCharsPerLine);
double charWidth = (_paperSize.width / charsPerLine) * styles.width.value;
return charWidth;
}
double _colIndToPosition(int colInd) {
final int width = _paperSize.width;
return colInd == 0 ? 0 : (width * colInd / 12 - 1);
}
int _getCharsPerLine(PosStyles styles, int? maxCharsPerLine) {
int charsPerLine;
if (maxCharsPerLine != null) {
charsPerLine = maxCharsPerLine;
} else {
if (styles.fontType != null) {
charsPerLine = _getMaxCharsPerLine(styles.fontType);
} else {
charsPerLine =
_maxCharsPerLine ?? _getMaxCharsPerLine(_styles.fontType);
}
}
return charsPerLine;
}
Uint8List _encode(String text, {bool isKanji = false}) {
// replace some non-ascii characters
text = text
.replaceAll("’", "'")
.replaceAll("´", "'")
.replaceAll("»", '"')
.replaceAll(" ", ' ')
.replaceAll("•", '.');
if (!isKanji) {
return latin1.encode(text);
} else {
return Uint8List.fromList(gbk_bytes.encode(text));
}
}
List _getLexemes(String text) {
final List<String> lexemes = [];
final List<bool> isLexemeChinese = [];
int start = 0;
int end = 0;
bool curLexemeChinese = _isChinese(text[0]);
for (var i = 1; i < text.length; ++i) {
if (curLexemeChinese == _isChinese(text[i])) {
end += 1;
} else {
lexemes.add(text.substring(start, end + 1));
isLexemeChinese.add(curLexemeChinese);
start = i;
end = i;
curLexemeChinese = !curLexemeChinese;
}
}
lexemes.add(text.substring(start, end + 1));
isLexemeChinese.add(curLexemeChinese);
return <dynamic>[lexemes, isLexemeChinese];
}
/// Break text into chinese/non-chinese lexemes
bool _isChinese(String ch) {
return ch.codeUnitAt(0) > 255;
}
/// Generate multiple bytes for a number: In lower and higher parts, or more parts as needed.
///
/// [value] Input number
/// [bytesNb] The number of bytes to output (1 - 4)
List<int> _intLowHigh(int value, int bytesNb) {
final dynamic maxInput = 256 << (bytesNb * 8) - 1;
if (bytesNb < 1 || bytesNb > 4) {
throw Exception('Can only output 1-4 bytes');
}
if (value < 0 || value > maxInput) {
throw Exception(
'Number is too large. Can only output up to $maxInput in $bytesNb bytes');
}
final List<int> res = <int>[];
int buf = value;
for (int i = 0; i < bytesNb; ++i) {
res.add(buf % 256);
buf = buf ~/ 256;
}
return res;
}
/// Extract slices of an image as equal-sized blobs of column-format data.
///
/// [image] Image to extract from
/// [lineHeight] Printed line height in dots
List<List<int>> _toColumnFormat(Image imgSrc, int lineHeight) {
final Image image = Image.from(imgSrc); // make a copy
// Determine new width: closest integer that is divisible by lineHeight
final int widthPx = (image.width + lineHeight) - (image.width % lineHeight);
final int heightPx = image.height;
// Create a black bottom layer
final biggerImage = copyResize(image, width: widthPx, height: heightPx);
fill(biggerImage, 0);
// Insert source image into bigger one
drawImage(biggerImage, image, dstX: 0, dstY: 0);
int left = 0;
final List<List<int>> blobs = [];
while (left < widthPx) {
final Image slice = copyCrop(biggerImage, left, 0, lineHeight, heightPx);
final Uint8List bytes = slice.getBytes(format: Format.luminance);
blobs.add(bytes);
left += lineHeight;
}
return blobs;
}
/// Image rasterization
List<int> _toRasterFormat(Image imgSrc) {
final Image image = Image.from(imgSrc); // make a copy
final int widthPx = image.width;
final int heightPx = image.height;
grayscale(image);
invert(image);
// R/G/B channels are same -> keep only one channel
final List<int> oneChannelBytes = [];
final List<int> buffer = image.getBytes(format: Format.rgba);
for (int i = 0; i < buffer.length; i += 4) {
oneChannelBytes.add(buffer[i]);
}
// Add some empty pixels at the end of each line (to make the width divisible by 8)
if (widthPx % 8 != 0) {
final targetWidth = (widthPx + 8) - (widthPx % 8);
final missingPx = targetWidth - widthPx;
final extra = Uint8List(missingPx);
for (int i = 0; i < heightPx; i++) {
final pos = (i * widthPx + widthPx) + i * missingPx;
oneChannelBytes.insertAll(pos, extra);
}
}
// Pack bits into bytes
return _packBitsIntoBytes(oneChannelBytes);
}
/// Merges each 8 values (bits) into one byte
List<int> _packBitsIntoBytes(List<int> bytes) {
const pxPerLine = 8;
final List<int> res = <int>[];
const threshold = 127; // set the greyscale -> b/w threshold here
for (int i = 0; i < bytes.length; i += pxPerLine) {
int newVal = 0;
for (int j = 0; j < pxPerLine; j++) {
newVal = _transformUint32Bool(
newVal,
pxPerLine - j,
bytes[i + j] > threshold,
);
}
res.add(newVal ~/ 2);
}
return res;
}
/// Replaces a single bit in a 32-bit unsigned integer.
int _transformUint32Bool(int uint32, int shift, bool newValue) {
return ((0xFFFFFFFF ^ (0x1 << shift)) & uint32) |
((newValue ? 1 : 0) << shift);
}
// ************************ (end) Internal helpers ************************
//**************************** Public command generators ************************
/// Clear the buffer and reset text styles
List<int> reset() {
List<int> bytes = [];
bytes += cInit.codeUnits;
_styles = PosStyles();
bytes += setGlobalCodeTable(_codeTable);
bytes += setGlobalFont(_font);
return bytes;
}
/// Set global code table which will be used instead of the default printer's code table
/// (even after resetting)
List<int> setGlobalCodeTable(String? codeTable) {
List<int> bytes = [];
_codeTable = codeTable;
if (codeTable != null) {
bytes += Uint8List.fromList(
List.from(cCodeTable.codeUnits)..add(_profile.getCodePageId(codeTable)),
);
_styles = _styles.copyWith(codeTable: codeTable);
}
return bytes;
}
/// Set global font which will be used instead of the default printer's font
/// (even after resetting)
List<int> setGlobalFont(PosFontType? font, {int? maxCharsPerLine}) {
List<int> bytes = [];
_font = font;
if (font != null) {
_maxCharsPerLine = maxCharsPerLine ?? _getMaxCharsPerLine(font);
bytes += font == PosFontType.fontB ? cFontB.codeUnits : cFontA.codeUnits;
_styles = _styles.copyWith(fontType: font);
}
return bytes;
}
List<int> setStyles(PosStyles styles, {bool isKanji = false}) {
List<int> bytes = [];
if (styles.align != _styles.align) {
bytes += latin1.encode(styles.align == PosAlign.left
? cAlignLeft
: (styles.align == PosAlign.center ? cAlignCenter : cAlignRight));
_styles = _styles.copyWith(align: styles.align);
}
if (styles.bold != _styles.bold) {
bytes += styles.bold ? cBoldOn.codeUnits : cBoldOff.codeUnits;
_styles = _styles.copyWith(bold: styles.bold);
}
if (styles.turn90 != _styles.turn90) {
bytes += styles.turn90 ? cTurn90On.codeUnits : cTurn90Off.codeUnits;
_styles = _styles.copyWith(turn90: styles.turn90);
}
if (styles.reverse != _styles.reverse) {
bytes += styles.reverse ? cReverseOn.codeUnits : cReverseOff.codeUnits;
_styles = _styles.copyWith(reverse: styles.reverse);
}
if (styles.underline != _styles.underline) {
bytes +=
styles.underline ? cUnderline1dot.codeUnits : cUnderlineOff.codeUnits;
_styles = _styles.copyWith(underline: styles.underline);
}
// Set font
if (styles.fontType != null && styles.fontType != _styles.fontType) {
bytes += styles.fontType == PosFontType.fontB
? cFontB.codeUnits
: cFontA.codeUnits;
_styles = _styles.copyWith(fontType: styles.fontType);
} else if (_font != null && _font != _styles.fontType) {
bytes += _font == PosFontType.fontB ? cFontB.codeUnits : cFontA.codeUnits;
_styles = _styles.copyWith(fontType: _font);
}
// Characters size
if (styles.height.value != _styles.height.value ||
styles.width.value != _styles.width.value) {
bytes += Uint8List.fromList(
List.from(cSizeGSn.codeUnits)
..add(PosTextSize.decSize(styles.height, styles.width)),
);
_styles = _styles.copyWith(height: styles.height, width: styles.width);
}
// Set Kanji mode
if (isKanji) {
bytes += cKanjiOn.codeUnits;
} else {
bytes += cKanjiOff.codeUnits;
}
// Set local code table
if (styles.codeTable != null) {
bytes += Uint8List.fromList(
List.from(cCodeTable.codeUnits)
..add(_profile.getCodePageId(styles.codeTable)),
);
_styles =
_styles.copyWith(align: styles.align, codeTable: styles.codeTable);
} else if (_codeTable != null) {
bytes += Uint8List.fromList(
List.from(cCodeTable.codeUnits)
..add(_profile.getCodePageId(_codeTable)),
);
_styles = _styles.copyWith(align: styles.align, codeTable: _codeTable);
}
return bytes;
}
/// Sens raw command(s)
List<int> rawBytes(List<int> cmd, {bool isKanji = false}) {
List<int> bytes = [];
if (!isKanji) {
bytes += cKanjiOff.codeUnits;
}
bytes += Uint8List.fromList(cmd);
return bytes;
}
List<int> text(
String text, {
PosStyles styles = const PosStyles(),
int linesAfter = 0,
bool containsChinese = false,
int? maxCharsPerLine,
}) {
List<int> bytes = [];
if (!containsChinese) {
bytes += _text(
_encode(text, isKanji: containsChinese),
styles: styles,
isKanji: containsChinese,
maxCharsPerLine: maxCharsPerLine,
);
// Ensure at least one line break after the text
bytes += emptyLines(linesAfter + 1);
} else {
bytes += _mixedKanji(text, styles: styles, linesAfter: linesAfter);
}
return bytes;
}
/// Skips [n] lines
///
/// Similar to [feed] but uses an alternative command
List<int> emptyLines(int n) {
List<int> bytes = [];
if (n > 0) {
bytes += List.filled(n, '\n').join().codeUnits;
}
return bytes;
}
/// Skips [n] lines
///
/// Similar to [emptyLines] but uses an alternative command
List<int> feed(int n) {
List<int> bytes = [];
if (n >= 0 && n <= 255) {
bytes += Uint8List.fromList(
List.from(cFeedN.codeUnits)..add(n),
);
}
return bytes;
}
/// Cut the paper
///
/// [mode] is used to define the full or partial cut (if supported by the printer)
List<int> cut({PosCutMode mode = PosCutMode.full}) {
List<int> bytes = [];
bytes += emptyLines(5);
if (mode == PosCutMode.partial) {
bytes += cCutPart.codeUnits;
} else {
bytes += cCutFull.codeUnits;
}
return bytes;
}
/// Print selected code table.
///
/// If [codeTable] is null, global code table is used.
/// If global code table is null, default printer code table is used.
List<int> printCodeTable({String? codeTable}) {
List<int> bytes = [];
bytes += cKanjiOff.codeUnits;
if (codeTable != null) {
bytes += Uint8List.fromList(
List.from(cCodeTable.codeUnits)..add(_profile.getCodePageId(codeTable)),
);
}
bytes += Uint8List.fromList(List<int>.generate(256, (i) => i));
// Back to initial code table
setGlobalCodeTable(_codeTable);
return bytes;
}
/// Beeps [n] times
///
/// Beep [duration] could be between 50 and 450 ms.
List<int> beep(
{int n = 3, PosBeepDuration duration = PosBeepDuration.beep450ms}) {
List<int> bytes = [];
if (n <= 0) {
return [];
}
int beepCount = n;
if (beepCount > 9) {
beepCount = 9;
}
bytes += Uint8List.fromList(
List.from(cBeep.codeUnits)..addAll([beepCount, duration.value]),
);
beep(n: n - 9, duration: duration);
return bytes;
}
/// Reverse feed for [n] lines (if supported by the printer)
List<int> reverseFeed(int n) {
List<int> bytes = [];
bytes += Uint8List.fromList(
List.from(cReverseFeedN.codeUnits)..add(n),
);
return bytes;
}
/// Print a row.
///
/// A row contains up to 12 columns. A column has a width between 1 and 12.
/// Total width of columns in one row must be equal 12.
List<int> row(List<PosColumn> cols) {
List<int> bytes = [];
final isSumValid = cols.fold(0, (int sum, col) => sum + col.width) == 12;
if (!isSumValid) {
throw Exception('Total columns width must be equal to 12');
}
bool isNextRow = false;
List<PosColumn> nextRow = <PosColumn>[];
for (int i = 0; i < cols.length; ++i) {
int colInd =
cols.sublist(0, i).fold(0, (int sum, col) => sum + col.width);
double charWidth = _getCharWidth(cols[i].styles);
double fromPos = _colIndToPosition(colInd);
final double toPos =
_colIndToPosition(colInd + cols[i].width) - spaceBetweenRows;
int maxCharactersNb = ((toPos - fromPos) / charWidth).floor();
if (!cols[i].containsChinese) {
// CASE 1: containsChinese = false
Uint8List encodedToPrint = cols[i].textEncoded != null
? cols[i].textEncoded!
: _encode(cols[i].text);
// If the col's content is too long, split it to the next row
int realCharactersNb = encodedToPrint.length;
if (realCharactersNb > maxCharactersNb) {
// Print max possible and split to the next row
Uint8List encodedToPrintNextRow =
encodedToPrint.sublist(maxCharactersNb);
encodedToPrint = encodedToPrint.sublist(0, maxCharactersNb);
isNextRow = true;
nextRow.add(PosColumn(
textEncoded: encodedToPrintNextRow,
width: cols[i].width,
styles: cols[i].styles));
} else {
// Insert an empty col
nextRow.add(PosColumn(
text: '', width: cols[i].width, styles: cols[i].styles));
}
// end rows splitting
bytes += _text(
encodedToPrint,
styles: cols[i].styles,
colInd: colInd,
colWidth: cols[i].width,
);
} else {
// CASE 1: containsChinese = true
// Split text into multiple lines if it too long
int counter = 0;
int splitPos = 0;
for (int p = 0; p < cols[i].text.length; ++p) {
final int w = _isChinese(cols[i].text[p]) ? 2 : 1;
if (counter + w >= maxCharactersNb) {
break;
}
counter += w;
splitPos += 1;
}
String toPrintNextRow = cols[i].text.substring(splitPos);
String toPrint = cols[i].text.substring(0, splitPos);
if (toPrintNextRow.isNotEmpty) {
isNextRow = true;
nextRow.add(PosColumn(
text: toPrintNextRow,
containsChinese: true,
width: cols[i].width,
styles: cols[i].styles));
} else {
// Insert an empty col
nextRow.add(PosColumn(
text: '', width: cols[i].width, styles: cols[i].styles));
}
// Print current row
final list = _getLexemes(toPrint);
final List<String> lexemes = list[0];
final List<bool> isLexemeChinese = list[1];
// Print each lexeme using codetable OR kanji
int? colIndex = colInd;
for (var j = 0; j < lexemes.length; ++j) {
bytes += _text(
_encode(lexemes[j], isKanji: isLexemeChinese[j]),
styles: cols[i].styles,
colInd: colIndex,
colWidth: cols[i].width,
isKanji: isLexemeChinese[j],
);
// Define the absolute position only once (we print one line only)
colIndex = null;
}
}
}
bytes += emptyLines(1);
if (isNextRow) {
row(nextRow);
}
return bytes;
}
/// Print an image using (ESC *) command
///
/// [image] is an instance of class from [Image library](https://pub.dev/packages/image)
List<int> image(Image imgSrc, {PosAlign align = PosAlign.center}) {
List<int> bytes = [];
// Image alignment
bytes += setStyles(PosStyles().copyWith(align: align));
final Image image = Image.from(imgSrc); // make a copy
const bool highDensityHorizontal = true;
const bool highDensityVertical = true;
invert(image);
flip(image, Flip.horizontal);
final Image imageRotated = copyRotate(image, 270);
const int lineHeight = highDensityVertical ? 3 : 1;
final List<List<int>> blobs = _toColumnFormat(imageRotated, lineHeight * 8);
// Compress according to line density
// Line height contains 8 or 24 pixels of src image
// Each blobs[i] contains greyscale bytes [0-255]
// const int pxPerLine = 24 ~/ lineHeight;
for (int blobInd = 0; blobInd < blobs.length; blobInd++) {
blobs[blobInd] = _packBitsIntoBytes(blobs[blobInd]);
}
final int heightPx = imageRotated.height;
const int densityByte =
(highDensityHorizontal ? 1 : 0) + (highDensityVertical ? 32 : 0);
final List<int> header = List.from(cBitImg.codeUnits);
header.add(densityByte);
header.addAll(_intLowHigh(heightPx, 2));
// Adjust line spacing (for 16-unit line feeds): ESC 3 0x10 (HEX: 0x1b 0x33 0x10)
bytes += [27, 51, 16];
for (int i = 0; i < blobs.length; ++i) {
bytes += List.from(header)
..addAll(blobs[i])
..addAll('\n'.codeUnits);
}
// Reset line spacing: ESC 2 (HEX: 0x1b 0x32)
bytes += [27, 50];
return bytes;
}
/// Print an image using (GS v 0) obsolete command
///
/// [image] is an instance of class from [Image library](https://pub.dev/packages/image)
List<int> imageRaster(
Image image, {
PosAlign align = PosAlign.center,
bool highDensityHorizontal = true,
bool highDensityVertical = true,
PosImageFn imageFn = PosImageFn.bitImageRaster,
}) {
List<int> bytes = [];
// Image alignment
bytes += setStyles(PosStyles().copyWith(align: align));
final int widthPx = image.width;
final int heightPx = image.height;
final int widthBytes = (widthPx + 7) ~/ 8;
final List<int> rasterizedData = _toRasterFormat(image);
if (imageFn == PosImageFn.bitImageRaster) {
// GS v 0
final int densityByte =
(highDensityVertical ? 0 : 1) + (highDensityHorizontal ? 0 : 2);
final List<int> header = List.from(cRasterImg2.codeUnits);
header.add(densityByte); // m
header.addAll(_intLowHigh(widthBytes, 2)); // xL xH
header.addAll(_intLowHigh(heightPx, 2)); // yL yH
bytes += List.from(header)..addAll(rasterizedData);
} else if (imageFn == PosImageFn.graphics) {
// 'GS ( L' - FN_112 (Image data)
final List<int> header1 = List.from(cRasterImg.codeUnits);
header1.addAll(_intLowHigh(widthBytes * heightPx + 10, 2)); // pL pH
header1.addAll([48, 112, 48]); // m=48, fn=112, a=48
header1.addAll([1, 1]); // bx=1, by=1
header1.addAll([49]); // c=49
header1.addAll(_intLowHigh(widthBytes, 2)); // xL xH
header1.addAll(_intLowHigh(heightPx, 2)); // yL yH
bytes += List.from(header1)..addAll(rasterizedData);
// 'GS ( L' - FN_50 (Run print)
final List<int> header2 = List.from(cRasterImg.codeUnits);
header2.addAll([2, 0]); // pL pH
header2.addAll([48, 50]); // m fn[2,50]
bytes += List.from(header2);
}
return bytes;
}
/// Print a barcode
///
/// [width] range and units are different depending on the printer model (some printers use 1..5).
/// [height] range: 1 - 255. The units depend on the printer model.
/// Width, height, font, text position settings are effective until performing of ESC @, reset or power-off.
List<int> barcode(
Barcode barcode, {
int? width,
int? height,
BarcodeFont? font,
BarcodeText textPos = BarcodeText.below,
PosAlign align = PosAlign.center,
}) {
List<int> bytes = [];
// Set alignment
bytes += setStyles(PosStyles().copyWith(align: align));
// Set text position
bytes += cBarcodeSelectPos.codeUnits + [textPos.value];
// Set font
if (font != null) {
bytes += cBarcodeSelectFont.codeUnits + [font.value];
}
// Set width
if (width != null && width >= 0) {
bytes += cBarcodeSetW.codeUnits + [width];
}
// Set height
if (height != null && height >= 1 && height <= 255) {
bytes += cBarcodeSetH.codeUnits + [height];
}
// Print barcode
final header = cBarcodePrint.codeUnits + [barcode.type!.value];
if (barcode.type!.value <= 6) {
// Function A
bytes += header + barcode.data! + [0];
} else {
// Function B
bytes += header + [barcode.data!.length] + barcode.data!;
}
return bytes;
}
/// Print a QR Code
List<int> qrcode(
String text, {
PosAlign align = PosAlign.center,
QRSize size = QRSize.Size4,
QRCorrection cor = QRCorrection.L,
}) {
List<int> bytes = [];
// Set alignment
bytes += setStyles(PosStyles().copyWith(align: align));
QRCode qr = QRCode(text, size, cor);
bytes += qr.bytes;
return bytes;
}
/// Open cash drawer
List<int> drawer({PosDrawer pin = PosDrawer.pin2}) {
List<int> bytes = [];
if (pin == PosDrawer.pin2) {
bytes += cCashDrawerPin2.codeUnits;
} else {
bytes += cCashDrawerPin5.codeUnits;
}
return bytes;
}
/// Print horizontal full width separator
/// If [len] is null, then it will be defined according to the paper width
List<int> hr({String ch = '-', int? len, int linesAfter = 0}) {
List<int> bytes = [];
int n = len ?? _maxCharsPerLine ?? _getMaxCharsPerLine(_styles.fontType);
String ch1 = ch.length == 1 ? ch : ch[0];
bytes += text(List.filled(n, ch1).join(), linesAfter: linesAfter);
return bytes;
}
List<int> textEncoded(
Uint8List textBytes, {
PosStyles styles = const PosStyles(),
int linesAfter = 0,
int? maxCharsPerLine,
}) {
List<int> bytes = [];
bytes += _text(textBytes, styles: styles, maxCharsPerLine: maxCharsPerLine);
// Ensure at least one line break after the text
bytes += emptyLines(linesAfter + 1);
return bytes;
}
// ************************ (end) Public command generators ************************
// ************************ (end) Internal command generators ************************
/// Generic print for internal use
///
/// [colInd] range: 0..11. If null: do not define the position
List<int> _text(
Uint8List textBytes, {
PosStyles styles = const PosStyles(),
int? colInd = 0,
bool isKanji = false,
int colWidth = 12,
int? maxCharsPerLine,
}) {
List<int> bytes = [];
if (colInd != null) {
double charWidth =
_getCharWidth(styles, maxCharsPerLine: maxCharsPerLine);
double fromPos = _colIndToPosition(colInd);
// Align
if (colWidth != 12) {
// Update fromPos
final double toPos =
_colIndToPosition(colInd + colWidth) - spaceBetweenRows;
final double textLen = textBytes.length * charWidth;
if (styles.align == PosAlign.right) {
fromPos = toPos - textLen;
} else if (styles.align == PosAlign.center) {
fromPos = fromPos + (toPos - fromPos) / 2 - textLen / 2;
}
if (fromPos < 0) {
fromPos = 0;
}
}
final hexStr = fromPos.round().toRadixString(16).padLeft(3, '0');
final hexPair = HEX.decode(hexStr);
// Position
bytes += Uint8List.fromList(
List.from(cPos.codeUnits)..addAll([hexPair[1], hexPair[0]]),
);
}
bytes += setStyles(styles, isKanji: isKanji);
bytes += textBytes;
return bytes;
}
/// Prints one line of styled mixed (chinese and latin symbols) text
List<int> _mixedKanji(
String text, {
PosStyles styles = const PosStyles(),
int linesAfter = 0,
int? maxCharsPerLine,
}) {
List<int> bytes = [];
final list = _getLexemes(text);
final List<String> lexemes = list[0];
final List<bool> isLexemeChinese = list[1];
// Print each lexeme using codetable OR kanji
int? colInd = 0;
for (var i = 0; i < lexemes.length; ++i) {
bytes += _text(
_encode(lexemes[i], isKanji: isLexemeChinese[i]),
styles: styles,
colInd: colInd,
isKanji: isLexemeChinese[i],
maxCharsPerLine: maxCharsPerLine,
);
// Define the absolute position only once (we print one line only)
colInd = null;
}
bytes += emptyLines(linesAfter + 1);
return bytes;
}
// ************************ (end) Internal command generators ************************
}