NativeTemplateCommandBuilder.java
52 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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
package com.foodlabel.nativeprinter.template;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Typeface;
import android.util.Base64;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class NativeTemplateCommandBuilder {
private static final double DESIGN_DPI = 96.0;
/**
* 与 JS 光栅路径 clearTopRasterRows 等效:热敏头可印区相对模板顶边常有一小段空白,
* 全部为 0 时顶部中文位图/TEXT 易被裁切;略下移与整页光栅观感一致。
*/
private static final int LABEL_TOP_MARGIN_DOTS = 18;
private static final int TEXT_PADDING_DOTS = 6;
private static final int RIGHT_SAFE_MARGIN_DOTS = 8;
private static final int DEFAULT_THRESHOLD = 180;
private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\{\\{\\s*([\\w.-]+)\\s*\\}\\}");
private static final String[][] NUTRITION_FIXED_ITEMS = new String[][]{
{"fat", "Total Fat"},
{"saturatedFat", "Saturated Fat"},
{"transFat", "Trans Fat"},
{"cholesterol", "Cholesterol"},
{"sodium", "Sodium"},
{"carbs", "Total Carbohydrates"},
{"dietaryFiber", "Dietary Fiber"},
{"totalSugar", "Total Sugar"},
{"protein", "Protein"},
{"vitaminA", "Vitamin A"},
{"vitaminC", "Vitamin C"},
{"calcium", "Calcium"},
{"iron", "Iron"}
};
private NativeTemplateCommandBuilder() {
}
public static byte[] build(String templateJson, String dataJson, int dpi, int printQty) throws Exception {
JSONObject template = new JSONObject(templateJson);
JSONObject data = (dataJson == null || dataJson.trim().isEmpty()) ? new JSONObject() : new JSONObject(dataJson);
return buildWithStats(template, data, dpi, printQty).bytes;
}
public static byte[] build(JSONObject template, JSONObject data, int dpi, int printQty) throws Exception {
return buildWithStats(template, data, dpi, printQty).bytes;
}
public static BuildResult buildWithStats(String templateJson, String dataJson, int dpi, int printQty) throws Exception {
JSONObject template = new JSONObject(templateJson);
JSONObject data = (dataJson == null || dataJson.trim().isEmpty()) ? new JSONObject() : new JSONObject(dataJson);
return buildWithStats(template, data, dpi, printQty);
}
public static BuildResult buildWithStats(JSONObject template, JSONObject data, int dpi, int printQty) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int nativeTextCount = 0;
int rasterTextCount = 0;
int qrCodeCount = 0;
int barcodeCount = 0;
int imagePatchCount = 0;
int lineCount = 0;
String unit = getString(template, "unit", "inch");
double widthMm = round1(toMillimeter(getDouble(template, "width", 0), unit));
double heightMm = round1(toMillimeter(getDouble(template, "height", 0), unit));
double pageWidthPx = widthMm / 25.4 * DESIGN_DPI;
addLine(out, "SIZE " + formatMm(widthMm) + " mm," + formatMm(heightMm) + " mm");
addLine(out, "GAP 0 mm,0 mm");
addLine(out, "CODEPAGE 1252");
addLine(out, "DENSITY 14");
addLine(out, "SPEED 5");
addLine(out, "CLS");
JSONArray elements = template.optJSONArray("elements");
if (elements != null) {
for (int i = 0; i < elements.length(); i++) {
JSONObject element = elements.optJSONObject(i);
if (element == null) continue;
JSONObject config = element.optJSONObject("config");
if (config == null) config = new JSONObject();
String type = getString(element, "type", "").toUpperCase();
if (type.startsWith("TEXT_")) {
String text = resolveElementText(type, config, data);
if (text.isEmpty()) continue;
String align = resolveElementAlign(element, config, pageWidthPx);
if (shouldRasterizeText(text, type, config)) {
rasterTextCount++;
BitmapPatch patch = createTextPatch(element, type, config, text, dpi, align);
writeBitmapPatch(out, patch);
} else {
nativeTextCount++;
int scale = resolveTextScale(getDouble(config, "fontSize", 14), dpi);
if ("TEXT_PRICE".equals(type)) {
// 价格行与普通文案保持接近视觉粗细,避免看起来偏“粗黑”。
scale = Math.max(1, scale - 1);
}
int x = resolveTextX(align, getDouble(element, "x", 0), getDouble(element, "width", 0), dpi, text, scale);
int y = yDots(getDouble(element, "y", 0), dpi);
int rotation = "vertical".equalsIgnoreCase(getString(element, "rotation", "horizontal")) ? 90 : 0;
String fontName = getString(config, "tscFont", "TSS24.BF2");
addLine(out, "TEXT " + x + "," + y + ",\"" + escapeTscString(fontName) + "\"," + rotation + "," + scale + "," + scale + ",\"" + escapeTscString(text) + "\"");
}
continue;
}
if ("QRCODE".equals(type)) {
String sourceLike = getString(
config,
"src",
getString(
config,
"Src",
getString(
config,
"data",
getString(config, "Data", getString(config, "url", getString(config, "Url", "")))
)
)
);
if (isImageLikeSource(sourceLike)) {
BitmapPatch patch = createImagePatch(element, config, dpi, sourceLike);
if (patch != null) {
imagePatchCount++;
writeBitmapPatch(out, patch);
}
continue;
}
String value = resolveElementDataValue(type, config, data);
if (value.isEmpty()) continue;
if (isImageLikeSource(value)) {
BitmapPatch patch = createImagePatch(element, config, dpi, value);
if (patch != null) {
imagePatchCount++;
writeBitmapPatch(out, patch);
}
continue;
}
qrCodeCount++;
String level = normalizeQrLevel(getString(config, "errorLevel", "M"));
int x = pxToDots(getDouble(element, "x", 0), dpi);
int y = yDots(getDouble(element, "y", 0), dpi);
int size = resolveQrModuleSize(getDouble(element, "width", 0), getDouble(element, "height", 0), dpi, value, level);
addLine(out, "QRCODE " + x + "," + y + "," + level + "," + size + ",A,0,\"" + escapeTscString(value) + "\"");
continue;
}
if ("NUTRITION".equals(type)) {
BitmapPatch patch = createNutritionPatch(element, config, dpi);
if (patch != null) {
imagePatchCount++;
writeBitmapPatch(out, patch);
}
continue;
}
if ("BARCODE".equals(type)) {
String value = resolveElementDataValue(type, config, data);
if (value.isEmpty()) continue;
barcodeCount++;
int x = pxToDots(getDouble(element, "x", 0), dpi);
int y = yDots(getDouble(element, "y", 0), dpi);
int height = Math.max(20, pxToDots(getDouble(element, "height", 0), dpi));
int readable = getBoolean(config, "showText", true) ? 1 : 0;
String orientation = getString(config, "orientation", getString(element, "rotation", "horizontal"));
if ("vertical".equalsIgnoreCase(orientation)) {
BitmapPatch patch = createVerticalBarcodePatch(element, config, dpi, value);
if (patch != null) {
imagePatchCount++;
writeBitmapPatch(out, patch);
}
continue;
}
int rotation = "vertical".equalsIgnoreCase(orientation) ? 90 : 0;
/** narrow/wide 为点阵单位;须用 px→dots 后的条宽,勿用设计 px,否则与 xScale/安全区收窄叠加会异常缩条 */
int barWidthDots = Math.max(48, pxToDots(getDouble(element, "width", 0), dpi));
int len = Math.max(1, value.length());
int narrow = clamp(barWidthDots / Math.max(48.0, len * 11.0), 2, 8);
int wide = clamp(barWidthDots / Math.max(28.0, len * 6.5), 3, 12);
if (wide <= narrow) wide = Math.min(12, narrow + 1);
String symbology = normalizeBarcodeType(getString(config, "barcodeType", "CODE128"));
addLine(out, "BARCODE " + x + "," + y + ",\"" + symbology + "\"," + height + "," + readable + "," + rotation + "," + narrow + "," + wide + ",\"" + escapeTscString(value) + "\"");
continue;
}
if ("IMAGE".equals(type)) {
BitmapPatch patch = createImagePatch(element, config, dpi);
if (patch != null) {
imagePatchCount++;
writeBitmapPatch(out, patch);
}
continue;
}
if ("BLANK".equals(type) && "line".equalsIgnoreCase(getString(element, "border", ""))) {
lineCount++;
int x = pxToDots(getDouble(element, "x", 0), dpi);
int y = yDots(getDouble(element, "y", 0), dpi);
int width = Math.max(1, pxToDots(getDouble(element, "width", 0), dpi));
int height = Math.max(1, pxToDots(getDouble(element, "height", 1), dpi));
addLine(out, "BAR " + x + "," + y + "," + width + "," + height);
}
}
}
addLine(out, "PRINT 1," + Math.max(1, printQty));
return new BuildResult(
out.toByteArray(),
nativeTextCount,
rasterTextCount,
qrCodeCount,
barcodeCount,
imagePatchCount,
lineCount,
elements == null ? 0 : elements.length()
);
}
private static String resolveElementText(String type, JSONObject config, JSONObject data) {
String configText = getString(config, "text", "");
boolean hasText = !configText.isEmpty();
if ("TEXT_PRICE".equals(type)) {
String bindingKey = resolveBindingKey(type, config);
String boundValue = resolveTemplateValue(data, bindingKey);
String raw = !boundValue.isEmpty() ? boundValue : (hasText ? applyTemplateData(configText, data) : "");
if (raw.isEmpty()) return "";
String prefix = getString(config, "prefix", "");
String suffix = getString(config, "suffix", "");
int decimal = (int) getDouble(config, "decimal", -1);
if (decimal >= 0) {
try {
double value = Double.parseDouble(raw);
raw = String.format(java.util.Locale.US, "%1$." + decimal + "f", value);
} catch (Exception ignored) {
}
}
raw = trimLeadingCurrencyIfPrefixed(raw, prefix);
return normalizePriceCurrencySymbol(prefix + raw + suffix);
}
if (hasText && "TEXT_STATIC".equals(type)) {
return applyTemplateData(configText, data);
}
if (hasText && configText.contains("{{")) {
return applyTemplateData(configText, data);
}
String bindingKey = resolveBindingKey(type, config);
String boundValue = resolveTemplateValue(data, bindingKey);
if (!boundValue.isEmpty()) return boundValue;
return hasText ? applyTemplateData(configText, data) : "";
}
private static String resolveElementDataValue(String type, JSONObject config, JSONObject data) {
String raw = getString(
config,
"data",
getString(
config,
"Data",
getString(
config,
"value",
getString(config, "Value", getString(config, "src", getString(config, "Src", getString(config, "url", getString(config, "Url", "")))))
)
)
);
if (!raw.isEmpty()) return applyTemplateData(raw, data);
return resolveTemplateValue(data, resolveBindingKey(type, config));
}
private static String resolveBindingKey(String type, JSONObject config) {
String[] keys = new String[]{"dataKey", "field", "bindField", "key", "valueKey"};
for (String key : keys) {
String value = getString(config, key, "");
if (!value.isEmpty()) return value;
}
switch (type) {
case "TEXT_PRODUCT": return "productName";
case "TEXT_LABEL_ID": return "labelId";
case "TEXT_CATEGORY": return "category";
case "TEXT_PRICE": return "price";
case "TEXT_DATE": return "date";
case "TEXT_TIME": return "time";
case "QRCODE": return "qrCode";
case "BARCODE": return "barcode";
default:
String pureType = type.replace("TEXT_", "").replace("FIELD_", "").replace("VALUE_", "");
return pureType.isEmpty() ? "" : toCamelCase(pureType);
}
}
private static String resolveTemplateValue(JSONObject data, String key) {
if (key == null || key.isEmpty()) return "";
String[] candidates;
switch (key) {
case "productName": candidates = new String[]{"productName", "product"}; break;
case "product": candidates = new String[]{"product", "productName"}; break;
case "qrCode": candidates = new String[]{"qrCode", "labelId", "barcode"}; break;
case "barcode": candidates = new String[]{"barcode", "labelId", "qrCode"}; break;
default: candidates = new String[]{key};
}
for (String candidate : candidates) {
Object value = data.opt(candidate);
if (value != null) return String.valueOf(value);
}
return "";
}
private static String applyTemplateData(String text, JSONObject data) {
Matcher matcher = PLACEHOLDER_PATTERN.matcher(text == null ? "" : text);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
String key = matcher.group(1);
Object value = data.opt(key);
matcher.appendReplacement(buffer, Matcher.quoteReplacement(value == null ? "" : String.valueOf(value)));
}
matcher.appendTail(buffer);
return buffer.toString();
}
private static String toCamelCase(String value) {
String[] parts = value.toLowerCase().split("[_\\s-]+");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
if (parts[i].isEmpty()) continue;
if (builder.length() == 0) {
builder.append(parts[i]);
} else {
builder.append(Character.toUpperCase(parts[i].charAt(0))).append(parts[i].substring(1));
}
}
return builder.toString();
}
private static String resolveElementAlign(JSONObject element, JSONObject config, double pageWidthPx) {
String align = getString(config, "textAlign", "").toLowerCase();
if ("left".equals(align) || "center".equals(align) || "right".equals(align)) return align;
double centerX = getDouble(element, "x", 0) + getDouble(element, "width", 0) / 2.0;
if (centerX <= pageWidthPx * 0.33) return "left";
if (centerX >= pageWidthPx * 0.67) return "right";
return "center";
}
private static boolean shouldRasterizeText(String text, String type, JSONObject config) {
if (getBoolean(config, "forceRasterText", false)) {
return true;
}
if (text == null || text.isEmpty()) return false;
if ("TEXT_PRICE".equals(type) && isSimplePriceLikeText(text)) {
// 价格行优先走原生 TEXT:避免位图二值化导致的糊边/左侧杂点。
return false;
}
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c < 32 || c > 126) {
return true;
}
}
CharsetEncoder encoder = getPrinterEncoder();
if (encoder == null) return true;
try {
return !encoder.canEncode(text);
} catch (Exception e) {
return true;
}
}
private static boolean isSimplePriceLikeText(String text) {
String s = text == null ? "" : text.trim();
if (s.isEmpty()) return false;
// 允许货币符号 + 数字/小数点/逗号/空格,统一按原生字体输出。
return s.matches("^[¥¥$€£]?\\s*[-+]?\\d+(?:[.,]\\d{1,2})?\\s*$");
}
private static String normalizePriceCurrencySymbol(String value) {
if (value == null || value.isEmpty()) return "";
return value.replace('¥', '¥');
}
private static String trimLeadingCurrencyIfPrefixed(String raw, String prefix) {
if (raw == null || raw.isEmpty()) return "";
String p = prefix == null ? "" : prefix.trim();
if (p.isEmpty()) return raw;
char c = p.charAt(0);
if (c != '¥' && c != '¥' && c != '$' && c != '€' && c != '£') return raw;
String s = raw.trim();
while (!s.isEmpty()) {
char ch = s.charAt(0);
if (ch == '¥' || ch == '¥' || ch == '$' || ch == '€' || ch == '£') {
s = s.substring(1).trim();
continue;
}
break;
}
return s;
}
private static BitmapPatch createTextPatch(JSONObject element, String type, JSONObject config, String text, int dpi, String align) {
String nativeSrc = text != null ? getString(config, "nativeSourceType", "") : "";
boolean dateLikeTime =
"DATE".equalsIgnoreCase(nativeSrc)
|| "TIME".equalsIgnoreCase(nativeSrc)
|| "DURATION".equalsIgnoreCase(nativeSrc);
if (text != null && dateLikeTime) {
/** 预览里日期与时间之间多空格,measure + 折行易把尾部数字挤到下一行;打印前压成单空格 */
text = text.replaceAll("\\s{2,}", " ").trim();
}
int contentWidth = Math.max(8, pxToDots(getDouble(element, "width", 0), dpi));
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setDither(true);
paint.setSubpixelText(true);
paint.setColor(Color.BLACK);
int fontSizeDots = Math.max(14, pxToDots(getDouble(config, "fontSize", 14), dpi));
paint.setTextSize(fontSizeDots);
/** 不再对 TEXT_PRICE 强制加粗:fakeBold + 粗体会糊边、measureText 偏窄,右对齐时左侧易出现杂点 */
boolean bold = "bold".equalsIgnoreCase(getString(config, "fontWeight", ""));
paint.setFakeBoldText(bold);
paint.setTypeface(bold ? Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD) : Typeface.SANS_SERIF);
java.util.List<String> lines;
if (dateLikeTime && text != null && text.indexOf('\n') < 0) {
/** 与画布单行日期/时间一致:禁止按字符宽度硬切,避免出现「12: 00 5」类残缺行 */
int wNeed = (int) Math.ceil(paint.measureText(text)) + 24;
contentWidth = Math.max(contentWidth, wNeed);
lines = new java.util.ArrayList<>();
lines.add(text);
} else {
if (text != null && text.indexOf('\n') < 0) {
int singleLineWidth = (int) Math.ceil(paint.measureText(text)) + 8;
contentWidth = Math.max(contentWidth, singleLineWidth);
}
lines = splitTextLines(text == null ? "" : text, paint, Math.max(8, contentWidth));
}
Paint.FontMetrics metrics = paint.getFontMetrics();
int lineHeight = Math.max(fontSizeDots + 2, (int) Math.ceil(Math.abs(metrics.top) + Math.abs(metrics.bottom) + 2));
int totalHeight = lines.size() * lineHeight;
float maxLineWidth = 0;
for (String line : lines) {
maxLineWidth = Math.max(maxLineWidth, paint.measureText(line));
}
int horizontalPadding = TEXT_PADDING_DOTS * 2;
int verticalPadding = TEXT_PADDING_DOTS * 2;
int width = ensureMultipleOf8(Math.max(contentWidth + horizontalPadding * 2, (int) Math.ceil(maxLineWidth) + horizontalPadding * 2 + 4));
int height = Math.max(16, Math.max(pxToDots(getDouble(element, "height", 0), dpi) + verticalPadding * 2, totalHeight + verticalPadding * 2 + 4));
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
int topOffset = "TEXT_PRICE".equals(type)
? Math.max(verticalPadding, (height - totalHeight) / 2)
: verticalPadding;
int drawableWidth = width - horizontalPadding * 2;
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
float lineWidth = paint.measureText(line);
float drawX = horizontalPadding;
float baseline = topOffset + i * lineHeight - metrics.top;
if ("center".equals(align)) {
String eid = getString(element, "id", "");
/** 条码下方人读数字:用 CENTER 对齐条区中心,避免 measure 偏差导致「差一截才居中」 */
if (eid.contains("barcode") && eid.endsWith("_label")) {
Align saved = paint.getTextAlign();
paint.setTextAlign(Align.CENTER);
float cx = horizontalPadding + drawableWidth / 2f;
canvas.drawText(line, cx, baseline, paint);
paint.setTextAlign(saved);
continue;
}
drawX = horizontalPadding + Math.max(0, (drawableWidth - lineWidth) / 2f);
} else if ("right".equals(align)) {
/** ¥ 等字符 measureText 常偏窄;日期时间含空格时末字符也易被裁,统一略加余量并留右内边距 */
float w = lineWidth;
if ("TEXT_PRICE".equals(type)) {
w += Math.max(2f, paint.getTextSize() * 0.12f);
} else {
w += Math.max(3f, paint.getTextSize() * 0.14f);
}
float rightPad = 4f;
drawX = horizontalPadding + Math.max(0, drawableWidth - w - rightPad);
}
canvas.drawText(line, drawX, baseline, paint);
}
BitmapPatch patch = new BitmapPatch(Math.max(0, pxToDots(getDouble(element, "x", 0), dpi) - horizontalPadding),
Math.max(0, yDots(getDouble(element, "y", 0), dpi) - verticalPadding),
invertMonochrome(bitmapToMonochrome(bitmap, DEFAULT_THRESHOLD)));
bitmap.recycle();
return patch;
}
private static BitmapPatch createImagePatch(JSONObject element, JSONObject config, int dpi) {
return createImagePatch(element, config, dpi, null);
}
private static BitmapPatch createVerticalBarcodePatch(JSONObject element, JSONObject config, int dpi, String value) {
int width = ensureMultipleOf8(Math.max(8, pxToDots(getDouble(element, "width", 0), dpi)));
int height = Math.max(12, pxToDots(getDouble(element, "height", 0), dpi));
Bitmap outputBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(outputBitmap);
canvas.drawColor(Color.WHITE);
int pad = 2;
boolean showText = getBoolean(config, "showText", true);
int textBandWidth = (showText && value != null && !value.isEmpty()) ? Math.max(10, (int) Math.round(width * 0.18)) : 0;
int barAreaWidth = Math.max(8, width - textBandWidth - pad * 2);
int innerHeight = Math.max(10, height - pad * 2);
int[] modules = barcodeModulesFromValue(value);
Paint barPaint = new Paint();
barPaint.setAntiAlias(false);
barPaint.setColor(Color.BLACK);
if (modules.length > 0) {
double moduleH = (double) innerHeight / (double) modules.length;
double cursorY = pad;
for (int i = 0; i < modules.length; i++) {
if (modules[i] == 1) {
float top = (float) cursorY;
float bottom = (float) (cursorY + Math.max(0.7, moduleH * 0.86));
canvas.drawRect(pad, top, pad + barAreaWidth, bottom, barPaint);
}
cursorY += moduleH;
}
}
if (showText && value != null && !value.isEmpty() && textBandWidth > 0) {
Paint txt = new Paint();
txt.setAntiAlias(true);
txt.setColor(Color.BLACK);
int font = Math.max(9, Math.min(11, (int) Math.floor(textBandWidth * 0.75)));
txt.setTextSize(font);
txt.setTextAlign(Paint.Align.CENTER);
float cx = width - textBandWidth / 2f;
float cy = height / 2f;
canvas.save();
// 竖排文本按模板端习惯:从下到上
canvas.rotate(-90f, cx, cy);
Paint.FontMetrics fm = txt.getFontMetrics();
float baseline = cy - (fm.ascent + fm.descent) / 2f;
canvas.drawText(value, cx, baseline, txt);
canvas.restore();
}
BitmapPatch patch = new BitmapPatch(
pxToDots(getDouble(element, "x", 0), dpi),
yDots(getDouble(element, "y", 0), dpi),
bitmapToMonochrome(outputBitmap, (int) getDouble(config, "threshold", DEFAULT_THRESHOLD))
);
outputBitmap.recycle();
return patch;
}
private static int[] barcodeModulesFromValue(String value) {
String s = value == null ? "" : value.trim();
if (s.isEmpty()) return new int[0];
java.util.ArrayList<Integer> m = new java.util.ArrayList<>();
// quiet + start
int[] start = new int[]{1, 0, 1, 0, 1, 0, 1, 0};
for (int v : start) m.add(v);
for (int i = 0; i < s.length(); i++) {
int code = s.charAt(i) & 0xFF;
int key = (code ^ (i * 13) ^ (s.length() * 7)) & 0x1F;
for (int b = 4; b >= 0; b--) {
m.add((key >> b) & 1);
}
m.add(0);
}
int[] stop = new int[]{1, 0, 1, 1, 0, 1, 0, 1};
for (int v : stop) m.add(v);
int[] out = new int[m.size()];
for (int i = 0; i < m.size(); i++) out[i] = m.get(i);
return out;
}
private static BitmapPatch createNutritionPatch(JSONObject element, JSONObject config, int dpi) {
int width = ensureMultipleOf8(Math.max(32, pxToDots(getDouble(element, "width", 0), dpi)));
int height = Math.max(32, pxToDots(getDouble(element, "height", 0), dpi));
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
Paint borderPaint = new Paint();
borderPaint.setAntiAlias(false);
borderPaint.setColor(Color.BLACK);
borderPaint.setStyle(Paint.Style.STROKE);
/** 1px 贴边矩形在二值化后易整条丢失;用略粗描边 + 内缩,保证上下左右边框都可见 */
borderPaint.setStrokeWidth(2f);
/** 左右、底部对称内缩:避免头端裁切导致「只有左边框、右边框/底边整条没了」 */
float borderL = 6f;
float borderR = width - 6f;
float borderT = 3f;
float borderB = height - 6f;
canvas.drawRect(borderL, borderT, borderR, borderB, borderPaint);
borderPaint.setStrokeWidth(1.5f);
int pad = 4;
int innerRight = Math.max(pad + 8, (int) Math.floor(borderR - pad));
int contentLeft = Math.max(pad, (int) Math.ceil(borderL + pad));
int right = innerRight;
/** 正文不得画进底框描边区,避免最后一行与底边重叠后二值化像「无底边」 */
int maxY = (int) Math.floor(borderB - pad);
int titleSize = clamp(pxToDots(getDouble(config, "nutritionTitleFontSize", 16), dpi), 12, 28);
int bodySize = clamp(titleSize * 0.72, 9, 18);
float y = pad + titleSize;
boolean titleBold = getBoolean(config, "nutritionTitleBold", true);
boolean bodyBold = getBoolean(config, "nutritionBodyBold", true);
Paint titlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
titlePaint.setAntiAlias(false);
titlePaint.setColor(Color.BLACK);
titlePaint.setTextSize(titleSize);
titlePaint.setTypeface(Typeface.create(Typeface.SANS_SERIF, titleBold ? Typeface.BOLD : Typeface.NORMAL));
titlePaint.setSubpixelText(false);
titlePaint.setTextAlign(Align.LEFT);
canvas.drawText("Nutrition Facts", contentLeft, y, titlePaint);
y += 2;
canvas.drawLine(contentLeft, y, innerRight, y, borderPaint);
y += 2;
Paint labelPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
labelPaint.setAntiAlias(false);
labelPaint.setColor(Color.BLACK);
labelPaint.setTextSize(bodySize);
labelPaint.setTypeface(Typeface.create(Typeface.SANS_SERIF, bodyBold ? Typeface.BOLD : Typeface.NORMAL));
labelPaint.setSubpixelText(false);
labelPaint.setTextAlign(Align.LEFT);
Paint valuePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
valuePaint.setAntiAlias(false);
valuePaint.setColor(Color.BLACK);
valuePaint.setTextSize(bodySize);
valuePaint.setTypeface(Typeface.create(Typeface.SANS_SERIF, bodyBold ? Typeface.BOLD : Typeface.NORMAL));
valuePaint.setSubpixelText(false);
valuePaint.setTextAlign(Align.RIGHT);
String calories = getString(config, "calories", getString(config, "Calories",
getNutritionFixedField(config, "calories", "value")));
if (!calories.trim().isEmpty()) {
y = drawNutritionPair(canvas, "Calories", nutritionDisplayValue(calories, ""), contentLeft, right, y, maxY, labelPaint, valuePaint);
}
String servingsPerContainer = getString(config, "servingsPerContainer", getString(config, "ServingsPerContainer", ""));
if (!servingsPerContainer.trim().isEmpty()) {
y = drawNutritionPair(canvas, "Servings Per Container", servingsPerContainer, contentLeft, right, y, maxY, labelPaint, valuePaint);
}
String servingSize = getString(config, "servingSize", getString(config, "ServingSize", ""));
if (!servingSize.trim().isEmpty()) {
y = drawNutritionPair(canvas, "Serving Size", servingSize, contentLeft, right, y, maxY, labelPaint, valuePaint);
}
for (String[] row : NUTRITION_FIXED_ITEMS) {
String key = row[0];
String name = row[1];
String value = getNutritionFixedField(config, key, "value");
if (value.trim().isEmpty()) continue;
String unit = getNutritionFixedField(config, key, "unit");
y = drawNutritionPair(canvas, name, nutritionDisplayValue(value, unit), contentLeft, right, y, maxY, labelPaint, valuePaint);
if (y >= maxY) break;
}
if (y < maxY) {
JSONArray extra = config.optJSONArray("extraNutrients");
if (extra != null) {
for (int i = 0; i < extra.length(); i++) {
JSONObject item = extra.optJSONObject(i);
if (item == null) continue;
String name = getString(item, "name", "").trim();
String value = getString(item, "value", "").trim();
String unit = getString(item, "unit", "").trim();
if (value.isEmpty()) continue;
if (name.isEmpty()) name = "Other";
y = drawNutritionPair(canvas, name, nutritionDisplayValue(value, unit), contentLeft, right, y, maxY, labelPaint, valuePaint);
if (y >= maxY) break;
}
}
}
/**
* 与 createTextPatch 一致:TSC BITMAP 在本通道上需二值取反,否则会出现「整块黑底、白字」及边缘杂点列。
*/
BitmapPatch patch = new BitmapPatch(
pxToDots(getDouble(element, "x", 0), dpi),
yDots(getDouble(element, "y", 0), dpi),
invertMonochrome(bitmapToMonochrome(bitmap, DEFAULT_THRESHOLD))
);
bitmap.recycle();
return patch;
}
private static float drawNutritionPair(
Canvas canvas,
String label,
String value,
int left,
int right,
float baseline,
int maxY,
Paint labelPaint,
Paint valuePaint
) {
if (baseline + labelPaint.getTextSize() + 2 > maxY) return maxY;
String safeLabel = (label == null ? "" : label).replace("\n", " ").replace("\r", " ").trim();
String safeValue = (value == null ? "" : value).replace("\n", " ").replace("\r", " ").trim();
/** 数值列不得超过 (right-left);禁止再强制 minWidth=14,否则窄营养表(如 width=32dot)会挤爆列划分 */
float totalWidth = (float) right - (float) left;
if (totalWidth < 8f) {
return maxY;
}
float minName = Math.min(40f, Math.max(14f, totalWidth * 0.5f));
float valueColumnWidth = Math.min(totalWidth * 0.45f, Math.max(4f, totalWidth - minName));
float valueColumnLeft = (float) right - valueColumnWidth;
if (valueColumnLeft < left + 2f) {
valueColumnLeft = left + 2f;
valueColumnWidth = (float) right - valueColumnLeft;
}
float labelMaxRight = valueColumnLeft - 4f;
float labelMaxWidth = Math.max(6f, labelMaxRight - left);
if (!safeLabel.isEmpty() && labelPaint.measureText(safeLabel) > labelMaxWidth) {
while (safeLabel.length() > 1 && labelPaint.measureText(safeLabel + "...") > labelMaxWidth) {
safeLabel = safeLabel.substring(0, safeLabel.length() - 1);
}
safeLabel = safeLabel + "...";
}
labelPaint.setTextAlign(Align.LEFT);
canvas.drawText(safeLabel, left, baseline + labelPaint.getTextSize(), labelPaint);
if (!safeValue.isEmpty()) {
/**
* 不用 RIGHT +「<」前缀(易触发双向/锚点异常,纸上出现字符挤到最左侧)。
* 用 LEFT + (right - measureWidth) 等效右对齐,锚点始终在格内。
*/
valuePaint.setTextAlign(Align.LEFT);
float tw = valuePaint.measureText(safeValue);
float cellRight = (float) right - 2f;
float vx = cellRight - tw;
float colLeft = Math.max(left + 1f, valueColumnLeft + 1f);
if (vx < colLeft) {
vx = colLeft;
}
canvas.drawText(safeValue, vx, baseline + valuePaint.getTextSize(), valuePaint);
}
return baseline + labelPaint.getTextSize() + 2;
}
private static String getNutritionFixedField(JSONObject config, String key, String field) {
String directKey = "value".equals(field) ? key : key + "Unit";
String direct = getString(config, directKey, "").trim();
if (!direct.isEmpty()) return direct;
JSONArray rows = config.optJSONArray("fixedNutrients");
if (rows == null) return "";
for (int i = 0; i < rows.length(); i++) {
JSONObject item = rows.optJSONObject(i);
if (item == null) continue;
if (!key.equals(getString(item, "key", "").trim())) continue;
return getString(item, field, "").trim();
}
return "";
}
private static String nutritionDisplayValue(String value, String unit) {
String v = value == null ? "" : value.trim();
String u = unit == null ? "" : unit.trim();
if (v.isEmpty() && u.isEmpty()) return "";
return "<" + v + (u.isEmpty() ? "" : (" " + u));
}
private static BitmapPatch createImagePatch(JSONObject element, JSONObject config, int dpi, String sourceOverride) {
String source = sourceOverride;
if (source == null || source.isEmpty()) {
source = getString(config, "src", getString(config, "data", getString(config, "url", "")));
}
if (source.isEmpty()) return null;
Bitmap sourceBitmap = decodeBitmap(source);
if (sourceBitmap == null) return null;
int width = ensureMultipleOf8(Math.max(8, pxToDots(getDouble(element, "width", 0), dpi)));
int height = Math.max(8, pxToDots(getDouble(element, "height", 0), dpi));
Bitmap outputBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(outputBitmap);
canvas.drawColor(Color.WHITE);
int sourceWidth = sourceBitmap.getWidth();
int sourceHeight = sourceBitmap.getHeight();
String scaleMode = getString(config, "scaleMode", "contain").toLowerCase();
int targetWidth = width;
int targetHeight = height;
int targetLeft = 0;
int targetTop = 0;
if (sourceWidth > 0 && sourceHeight > 0 && !"fill".equals(scaleMode)) {
double ratio = "cover".equals(scaleMode)
? Math.max((double) width / sourceWidth, (double) height / sourceHeight)
: Math.min((double) width / sourceWidth, (double) height / sourceHeight);
targetWidth = Math.max(1, (int) Math.round(sourceWidth * ratio));
targetHeight = Math.max(1, (int) Math.round(sourceHeight * ratio));
targetLeft = (width - targetWidth) / 2;
targetTop = (height - targetHeight) / 2;
}
Bitmap scaledBitmap = Bitmap.createScaledBitmap(sourceBitmap, targetWidth, targetHeight, true);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
canvas.drawBitmap(scaledBitmap, targetLeft, targetTop, paint);
BitmapPatch patch = new BitmapPatch(pxToDots(getDouble(element, "x", 0), dpi),
yDots(getDouble(element, "y", 0), dpi),
bitmapToMonochrome(outputBitmap, (int) getDouble(config, "threshold", DEFAULT_THRESHOLD)));
scaledBitmap.recycle();
sourceBitmap.recycle();
outputBitmap.recycle();
return patch;
}
private static boolean isImageLikeSource(String source) {
if (source == null) return false;
String s = source.trim().toLowerCase();
if (s.isEmpty()) return false;
if (s.startsWith("data:image/")) return true;
if (s.startsWith("file://")) return true;
if (s.startsWith("/picture/") || s.startsWith("picture/")) return true;
if (s.startsWith("/static/") || s.startsWith("static/")) return true;
if (s.matches("^[a-z]:[\\\\/].*")) return true;
return s.matches(".*\\.(png|jpe?g|gif|webp|bmp)(\\?.*)?$");
}
private static Bitmap decodeBitmap(String source) {
try {
if (source.startsWith("data:image/")) {
int comma = source.indexOf(',');
String payload = comma >= 0 ? source.substring(comma + 1) : "";
if (payload.isEmpty()) return null;
byte[] bytes = Base64.decode(payload, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
if (source.matches("^[A-Za-z0-9+/=\\r\\n]+$") && source.length() > 128) {
byte[] bytes = Base64.decode(source, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
String path = source.startsWith("file://") ? source.substring(7) : source;
return BitmapFactory.decodeFile(path);
} catch (Exception e) {
return null;
}
}
private static java.util.List<String> splitTextLines(String text, Paint paint, int maxWidth) {
java.util.List<String> lines = new java.util.ArrayList<>();
String[] rawLines = (text == null ? "" : text.replace("\r", "")).split("\n");
for (String segment : rawLines) {
if (segment.isEmpty()) {
lines.add("");
continue;
}
StringBuilder current = new StringBuilder();
for (int i = 0; i < segment.length(); i++) {
char c = segment.charAt(i);
String candidate = current.toString() + c;
if (current.length() > 0 && paint.measureText(candidate) > maxWidth) {
lines.add(current.toString());
current.setLength(0);
current.append(c);
} else {
current.append(c);
}
}
if (current.length() > 0) lines.add(current.toString());
}
if (lines.isEmpty()) lines.add("");
return lines;
}
private static void writeBitmapPatch(ByteArrayOutputStream out, BitmapPatch patch) {
int bytesPerRow = patch.image.width / 8;
addLine(out, "BITMAP " + patch.x + "," + patch.y + "," + bytesPerRow + "," + patch.image.height + ",0,");
for (int y = 0; y < patch.image.height; y++) {
for (int byteIndex = 0; byteIndex < bytesPerRow; byteIndex++) {
int value = 0;
for (int bit = 0; bit < 8; bit++) {
int x = byteIndex * 8 + bit;
int pixel = patch.image.pixels[y * patch.image.width + x];
if (pixel == 1) value |= (1 << (7 - bit));
}
out.write(value & 0xFF);
}
}
out.write('\r');
out.write('\n');
}
private static MonochromeImage bitmapToMonochrome(Bitmap bitmap, int threshold) {
int bitmapWidth = bitmap.getWidth();
int bitmapHeight = bitmap.getHeight();
int width = ensureMultipleOf8(bitmapWidth);
int[] pixels = new int[width * bitmapHeight];
for (int y = 0; y < bitmapHeight; y++) {
for (int x = 0; x < width; x++) {
if (x >= bitmapWidth) {
pixels[y * width + x] = 0;
continue;
}
int color = bitmap.getPixel(x, y);
int alpha = (color >>> 24) & 0xFF;
int red = (color >>> 16) & 0xFF;
int green = (color >>> 8) & 0xFF;
int blue = color & 0xFF;
double gray = red * 0.299 + green * 0.587 + blue * 0.114;
pixels[y * width + x] = alpha <= 10 || gray > threshold ? 0 : 1;
}
}
return new MonochromeImage(width, bitmapHeight, pixels);
}
private static MonochromeImage invertMonochrome(MonochromeImage image) {
if (image == null || image.pixels == null) return image;
int[] pixels = new int[image.pixels.length];
for (int i = 0; i < image.pixels.length; i++) {
pixels[i] = image.pixels[i] == 1 ? 0 : 1;
}
return new MonochromeImage(image.width, image.height, pixels);
}
private static void addLine(ByteArrayOutputStream out, String line) {
byte[] bytes = line.getBytes(getPrinterCharset());
out.write(bytes, 0, bytes.length);
out.write('\r');
out.write('\n');
}
private static Charset getPrinterCharset() {
try {
return Charset.forName("windows-1252");
} catch (Throwable first) {
try {
return Charset.forName("Cp1252");
} catch (Throwable second) {
return StandardCharsets.ISO_8859_1;
}
}
}
private static CharsetEncoder getPrinterEncoder() {
try {
return getPrinterCharset().newEncoder();
} catch (Throwable first) {
try {
return StandardCharsets.ISO_8859_1.newEncoder();
} catch (Throwable second) {
return null;
}
}
}
private static String escapeTscString(String value) {
return value == null ? "" : value.replace("\\", "\\\\").replace("\"", "\\\"");
}
private static String normalizeBarcodeType(String value) {
String key = value == null ? "CODE128" : value.trim().toUpperCase();
switch (key) {
case "CODE39": return "39";
case "EAN13": return "EAN13";
case "EAN8": return "EAN8";
case "UPCA": return "UPCA";
case "UPCE": return "UPCE";
case "CODABAR": return "CODA";
case "ITF14": return "ITF14";
case "ITF": return "ITF";
default: return "128";
}
}
private static String normalizeQrLevel(String value) {
String key = value == null ? "M" : value.trim().toUpperCase();
if ("L".equals(key) || "M".equals(key) || "Q".equals(key) || "H".equals(key)) return key;
return "M";
}
private static int resolveQrModuleSize(double widthPx, double heightPx, int dpi, String value, String level) {
int targetDots = Math.max(24, Math.min(pxToDots(widthPx, dpi), pxToDots(heightPx, dpi)));
int moduleCount = Math.max(21, estimateQrModuleCount(value, level));
return clamp(Math.floorDiv(targetDots, moduleCount), 3, 12);
}
private static int estimateQrModuleCount(String value, String level) {
int length = Math.max(1, value == null ? 0 : value.length());
int[] capacities;
switch (level) {
case "L": capacities = new int[]{17, 32, 53, 78, 106, 134, 154, 192, 230, 271}; break;
case "Q": capacities = new int[]{11, 20, 32, 46, 60, 74, 86, 108, 130, 151}; break;
case "H": capacities = new int[]{7, 14, 24, 34, 44, 58, 64, 84, 98, 119}; break;
default: capacities = new int[]{14, 26, 42, 62, 84, 106, 122, 152, 180, 213};
}
int version = capacities.length;
for (int i = 0; i < capacities.length; i++) {
if (length <= capacities[i]) {
version = i + 1;
break;
}
}
return 21 + (version - 1) * 4;
}
private static int resolveTextScale(double fontSizePx, int dpi) {
int targetDots = Math.max(12, (int) Math.round(fontSizePx * dpi / DESIGN_DPI));
return clamp(targetDots / 24.0, 1, 7);
}
private static int resolveTextX(String align, double xPx, double widthPx, int dpi, String text, int scale) {
int left = pxToDots(xPx, dpi);
if ("left".equals(align)) return left;
int boxWidth = pxToDots(widthPx, dpi);
int fontDots = Math.max(24, scale * 24);
int textWidth = estimateTextWidthDots(text, fontDots);
if ("center".equals(align)) return Math.max(0, left + Math.max(0, boxWidth - textWidth) / 2);
return Math.max(0, left + Math.max(0, boxWidth - textWidth - RIGHT_SAFE_MARGIN_DOTS));
}
private static int estimateTextWidthDots(String text, int fontDots) {
double total = 0;
for (int i = 0; i < text.length(); i++) {
total += text.charAt(i) > 255 ? fontDots : fontDots * 0.6;
}
return (int) Math.round(total);
}
private static int clamp(double value, int min, int max) {
return Math.max(min, Math.min(max, (int) Math.round(value)));
}
private static int ensureMultipleOf8(int value) {
int safe = Math.max(8, value);
return safe % 8 == 0 ? safe : safe + (8 - safe % 8);
}
private static int pxToDots(double value, int dpi) {
return Math.max(0, (int) Math.round(value * dpi / DESIGN_DPI));
}
/** 模板 y(px)→ 点阵 y,并加上与光栅路径一致的上边距,减轻顶部裁切 */
private static int yDots(double yPx, int dpi) {
return Math.max(0, pxToDots(yPx, dpi) + LABEL_TOP_MARGIN_DOTS);
}
private static double toMillimeter(double value, String unit) {
if ("mm".equalsIgnoreCase(unit)) return value;
if ("cm".equalsIgnoreCase(unit)) return value * 10;
if ("px".equalsIgnoreCase(unit)) return value / DESIGN_DPI * 25.4;
return value * 25.4;
}
private static double round1(double value) {
return Math.round(value * 10.0) / 10.0;
}
private static String formatMm(double value) {
return String.format(java.util.Locale.US, "%.1f", value);
}
private static String getString(JSONObject json, String key, String fallback) {
Object value = json.opt(key);
return value == null ? fallback : String.valueOf(value);
}
private static double getDouble(JSONObject json, String key, double fallback) {
try {
Object value = json.opt(key);
if (value == null) return fallback;
if (value instanceof Number) return ((Number) value).doubleValue();
return Double.parseDouble(String.valueOf(value));
} catch (Exception e) {
return fallback;
}
}
private static boolean getBoolean(JSONObject json, String key, boolean fallback) {
try {
Object value = json.opt(key);
if (value == null) return fallback;
if (value instanceof Boolean) return (Boolean) value;
return Boolean.parseBoolean(String.valueOf(value));
} catch (Exception e) {
return fallback;
}
}
private static final class BitmapPatch {
final int x;
final int y;
final MonochromeImage image;
BitmapPatch(int x, int y, MonochromeImage image) {
this.x = x;
this.y = y;
this.image = image;
}
}
private static final class MonochromeImage {
final int width;
final int height;
final int[] pixels;
MonochromeImage(int width, int height, int[] pixels) {
this.width = width;
this.height = height;
this.pixels = pixels;
}
}
public static final class BuildResult {
public final byte[] bytes;
public final int nativeTextCount;
public final int rasterTextCount;
public final int qrCodeCount;
public final int barcodeCount;
public final int imagePatchCount;
public final int lineCount;
public final int elementCount;
public BuildResult(byte[] bytes, int nativeTextCount, int rasterTextCount, int qrCodeCount, int barcodeCount,
int imagePatchCount, int lineCount, int elementCount) {
this.bytes = bytes == null ? new byte[0] : bytes;
this.nativeTextCount = nativeTextCount;
this.rasterTextCount = rasterTextCount;
this.qrCodeCount = qrCodeCount;
this.barcodeCount = barcodeCount;
this.imagePatchCount = imagePatchCount;
this.lineCount = lineCount;
this.elementCount = elementCount;
}
}
}