-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathescpos_printer.py
More file actions
1031 lines (872 loc) · 34.1 KB
/
Copy pathescpos_printer.py
File metadata and controls
1031 lines (872 loc) · 34.1 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
from __future__ import annotations
import dataclasses
import sys
from PIL import Image, ImageDraw, ImageFont
import qrcode
from .const import DEFAULT_PAPER_WIDTH, DEFAULT_FONT_SIZES
@dataclasses.dataclass
class UsbInfo:
"""
打印机连接类, 现在只用于 macOS
:param vendor_id: USB 设备的供应商 ID
:param product_id: USB 设备的产品 ID
:param interface: USB 接口号
:param in_ep: 输入端点
:param out_ep: 输出端点
"""
vendor_id: int
product_id: int
interface: int = 0
in_ep: int = 0x81
out_ep: int = 0x02
@dataclasses.dataclass
class PrinterConfig:
"""
打印机配置类
:param printer_name: str
- 打印机名称
- 在 Windows 中是 `win32print.OpenPrinter` 的参数
- 在 Linux 中是 `/dev/usb/lp0` 或 `/dev/usb/lp1` 等设备文件, 会通过 `open` 打开
- 在 macOS 中需要传入任意字符串来避免报错, 实际连接通过 `usb_info` 传入
:param paper_width: (str | int)
- 纸张宽度, 详见`const.DEFAULT_PAPER_WIDTH`
:param default_font: 默认字体路径
:param platform: ("windows" | "linux" | "macos)
- 操作系统平台
- default: 自动检测
"""
printer_name: str
paper_width: str | int
default_font: str
platform: str | None = None
padding_x: int = 10
font_sizes: dict[str, int] | None = None
@dataclasses.dataclass
class Text:
text: str
align: str
font_size: int
font: str
line_spacing: int
@dataclasses.dataclass
class QrCode:
data: str
box_size: int
border: int
@dataclasses.dataclass
class NewLine:
height: int
lines: int
@dataclasses.dataclass
class ImageContent:
image: Image.Image
max_width: int | None = None
@dataclasses.dataclass
class Flex:
items: list[Text | QrCode | ImageContent | Flex]
# Gap between items in same row
item_gap: int
# Gap between rows
row_gap: int
# Horizontal alignment: "left" | "right" | "between"
horizontal_align: str
# Vertical alignment: "top" | "center" | "bottom"
vertical_align: str
max_width: int
class FlexItemFactory:
def __init__(
self, default_font: str, avaliable_width: int, font_sizes: dict[str, int]
):
self.default_font = default_font
self.avaliable_width = avaliable_width
self.font_sizes = font_sizes
def text(
self,
*,
text,
aligin="left",
font_size=None,
font=None,
) -> Text:
if font is None:
font = self.default_font
if font_size is None:
font_size = self.font_sizes["md"]
elif font_size in self.font_sizes:
font_size = self.font_sizes[font_size]
elif isinstance(font_size, int):
font_size = font_size
else:
raise ValueError("font_size must be an int or a key in DEFAULT_FONT_SIZES.")
return Text(
text=text,
align=aligin,
font_size=font_size,
font=font,
line_spacing=0,
)
def qrcode(self, *, data, size="lg") -> QrCode:
if size == "sm":
box_size = 8
border = 2
elif size == "md":
box_size = 10
border = 2
elif size == "lg":
box_size = 16
border = 2
else:
raise ValueError("Invalid size. Choose 'sm', 'md', or 'lg'.")
return QrCode(data=data, box_size=box_size, border=border)
def image(
self,
*,
image=None,
max_width=None,
):
if max_width == "full":
max_width = self.avaliable_width
if image is None:
raise ValueError("Image must be provided.")
return ImageContent(image=image, max_width=max_width)
def flex(
self,
*,
items: list[Text | QrCode | ImageContent | Flex],
item_gap: int = 0,
row_gap: int = 0,
horizontal_align: str = "left",
vertical_align: str = "top",
max_width: int | None = None,
) -> Flex:
# 如果 max_width 未指定,则继承父级 paper_width
if max_width is None:
max_width = self.avaliable_width
return Flex(
items=items,
item_gap=item_gap,
row_gap=row_gap,
horizontal_align=horizontal_align,
vertical_align=vertical_align,
max_width=max_width,
)
class FlexRenderer:
def __init__(self, flex: Flex, max_width: int):
self.flex_obj = flex
self.max_width = max_width
def _render_text(self, text_obj: Text, max_width) -> Image.Image:
"""
Render a Text object to a list of images, each representing a single line of text.
Start rendering from the given current_x position.
Will ignore the Text.align and Text.line_spacing attributes.
You can use the Flex.row_gap and Flex.item_gap attributes to control the spacing.
"""
try:
font = ImageFont.truetype(text_obj.font, text_obj.font_size)
except Exception:
font = ImageFont.load_default()
# Split text into lines based on container width and current_x
lines = []
current_line = ""
line_images = []
for char in text_obj.text:
test_line = current_line + char
dummy_img = Image.new("L", (1, 1), color=255)
draw = ImageDraw.Draw(dummy_img)
bbox = draw.textbbox((0, 0), test_line, font=font)
if bbox[2] > max_width: # If line exceeds available width
lines.append((current_line, max_width))
current_line = char
else:
current_line = test_line
if current_line: # Add the last line
lines.append((current_line, max_width))
max_actual_width = 0
# Render each line as a separate image
for line, line_width in lines:
dummy_img = Image.new("L", (1, 1), color=255)
draw = ImageDraw.Draw(dummy_img)
bbox = draw.textbbox((0, 0), line, font=font)
actual_line_width = bbox[2]
if actual_line_width > max_actual_width:
max_actual_width = actual_line_width
line_height = bbox[3] - bbox[1] # Ensure height includes baseline content
img = Image.new("L", (actual_line_width, line_height), color=255)
draw = ImageDraw.Draw(img)
draw.text((0, -bbox[1]), line, font=font, fill=0) # Adjust for baseline
line_images.append(img)
# print(
# f"[{text_obj.text[:5]}] Max actual width: {max_actual_width}, Max width: {self.max_width}"
# )
final_img = Image.new(
"L", (max_actual_width, sum(img.height for img in line_images)), color=255
)
current_y = 0
for line_img in line_images:
final_img.paste(line_img, (0, current_y))
current_y += line_img.height
return final_img
def _render_qrcode(self, qr_obj: QrCode) -> Image.Image:
"""
Render a QrCode object to an image.
"""
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.ERROR_CORRECT_L,
box_size=qr_obj.box_size,
border=qr_obj.border,
)
qr.add_data(qr_obj.data)
qr.make(fit=True)
qr_img = qr.make_image(fill_color="black", back_color="white").convert("L")
return qr_img
def _render_image(self, img_obj: ImageContent) -> Image.Image:
"""
Render an ImageContent object to an image.
"""
img = img_obj.image.convert("L")
if img_obj.max_width and img.width > img_obj.max_width:
ratio = img_obj.max_width / img.width
new_height = int(img.height * ratio)
img = img.resize((img_obj.max_width, new_height))
return img
def render(self) -> Image.Image:
"""
Render a Flex object using Pillow, following CSS flexbox logic.
:return: A rendered image.
"""
items = self.flex_obj.items
# Render each item and calculate positions with wrapping
rendered_items = []
item_positions = []
current_x = 0 # 目前 Flex 不支持竖向渲染
max_row_height = 0
rendered_width = 0
for item in items:
if isinstance(item, Text):
rendered_item = self._render_text(item, self.max_width - rendered_width)
item_width, item_height = rendered_item.size
# Update max_row_height for the current row
max_row_height = max(max_row_height, item_height)
# Store the position and rendered item
item_positions.append((current_x, 0))
rendered_items.append(rendered_item)
# Update current_x for the next item, including item_gap
current_x += item_width + self.flex_obj.item_gap
# Update rendered_width
rendered_width = max(rendered_width, current_x)
elif isinstance(item, QrCode):
rendered_item = self._render_qrcode(item)
item_width, item_height = rendered_item.size
# Update max_row_height for the current row
max_row_height = max(max_row_height, item_height)
# Store the position and rendered item
item_positions.append((current_x, 0))
rendered_items.append(rendered_item)
# Update current_x for the next item, including item_gap
current_x += item_width + self.flex_obj.item_gap
# Update rendered_width
rendered_width = max(rendered_width, current_x)
elif isinstance(item, ImageContent):
rendered_item = self._render_image(item)
item_width, item_height = rendered_item.size
# Update max_row_height for the current row
max_row_height = max(max_row_height, item_height)
# Store the position and rendered item
item_positions.append((current_x, 0))
rendered_items.append(rendered_item)
# Update current_x for the next item, including item_gap
current_x += item_width + self.flex_obj.item_gap
# Update rendered_width
rendered_width = max(rendered_width, current_x)
elif isinstance(item, Flex):
# Push the placeholder for nexted flex obj
item_positions.append((current_x, 0))
rendered_items.append(item)
else:
raise ValueError(f"Unsupported item type: {item}")
# 目前只支持嵌套一层 Flex, 多了就出错
flex_item_idx = None
for i, item in enumerate(rendered_items):
if isinstance(item, Flex):
flex_item_idx = i
break
if flex_item_idx is not None:
before_flex_item_width = 0
after_flex_item_width = 0
for j in range(flex_item_idx):
before_flex_item_width += (
rendered_items[j].size[0] + self.flex_obj.item_gap
)
for j in range(flex_item_idx + 1, len(rendered_items)):
after_flex_item_width += (
rendered_items[j].size[0] + self.flex_obj.item_gap
)
flex_item_max_width = (
self.max_width - before_flex_item_width - after_flex_item_width
)
nested_renderer = FlexRenderer(
rendered_items[flex_item_idx], flex_item_max_width
)
nested_img = nested_renderer.render()
item_width, item_height = nested_img.size
rendered_items[flex_item_idx] = nested_img
current_x = 0
for idx, item in enumerate(rendered_items):
item_positions[idx] = (current_x, 0)
current_x += item.size[0] + self.flex_obj.item_gap
max_row_height = max(max_row_height, item.size[1])
rendered_width = current_x + rendered_items[-1].size[0]
# Adjust positions based on horizontal_align
if self.flex_obj.horizontal_align == "right":
row_widths = {}
rendered_width = self.max_width
for (x, y), item_img in zip(item_positions, rendered_items):
row_widths.setdefault(y, 0)
row_widths[y] += item_img.size[0] + self.flex_obj.item_gap
for i, ((x, y), item_img) in enumerate(zip(item_positions, rendered_items)):
row_width = row_widths[y] - self.flex_obj.item_gap # Remove extra gap
offset = self.max_width - row_width
item_positions[i] = (x + offset, y)
elif self.flex_obj.horizontal_align == "between":
row_items = {}
rendered_width = self.max_width
for (x, y), item_img in zip(item_positions, rendered_items):
row_items.setdefault(y, []).append((x, item_img))
for y, items_in_row in row_items.items():
total_row_width = sum(item.size[0] for _, item in items_in_row)
total_gaps = len(items_in_row) - 1
if total_gaps > 0:
extra_gap = (self.max_width - total_row_width) // total_gaps
else:
extra_gap = 0
current_x = 0
for i, (original_x, item_img) in enumerate(items_in_row):
item_width = item_img.size[0]
for j, ((x, row_y), _) in enumerate(
zip(item_positions, rendered_items)
):
if row_y == y and x == original_x:
item_positions[j] = (current_x, row_y)
break
current_x += item_width + extra_gap
# Adjust positions based on vertical_align
if self.flex_obj.vertical_align in ["center", "bottom"]:
row_heights = {}
for (x, y), item_img in zip(item_positions, rendered_items):
row_heights.setdefault(y, 0)
row_heights[y] = max(row_heights[y], item_img.size[1])
for i, ((x, y), item_img) in enumerate(zip(item_positions, rendered_items)):
row_height = row_heights[y]
if self.flex_obj.vertical_align == "center":
offset = (row_height - item_img.size[1]) // 2
elif self.flex_obj.vertical_align == "bottom":
offset = row_height - item_img.size[1]
else:
offset = 0
item_positions[i] = (x, y + offset)
final_img = Image.new("L", (rendered_width, max_row_height), color=255)
for (x, y), item_img in zip(item_positions, rendered_items):
final_img.paste(item_img, (x, y))
return final_img
ContentUnion = Text | QrCode | NewLine | ImageContent | Flex
class Content:
Text = Text
QrCode = QrCode
NewLine = NewLine
ImageContent = ImageContent
Flex = Flex
@dataclasses.dataclass
class _RenderedBlock:
image: Image.Image
x: int
class EscPosPrinter:
"""
ESC/POS 打印机类
把所有打印内容渲染为图像,然后通过 ESC/POS 指令发送到打印机
"""
def __init__(self, config: PrinterConfig, usb_info: UsbInfo | None = None):
# Setup printer config
self._validate_config(config)
self.printer_name = config.printer_name
if isinstance(config.paper_width, str):
self.paper_width = DEFAULT_PAPER_WIDTH[config.paper_width]
elif isinstance(config.paper_width, int):
self.paper_width = config.paper_width
else:
raise ValueError(
"Invalid Config: paper_width must be a int or key of DEFAULT_PAPER_WIDTH."
)
self.default_font = config.default_font
self.padding_x = config.padding_x
self.font_sizes = {
**DEFAULT_FONT_SIZES,
**(config.font_sizes if config.font_sizes else {}),
}
if config.platform is None:
if sys.platform.startswith("win"):
self.platform = "windows"
elif sys.platform.startswith("linux"):
self.platform = "linux"
elif sys.platform.startswith("darwin"):
self.platform = "macos"
else:
raise ValueError(f"Unsupported platform: {sys.platform}")
else:
self.platform = config.platform
self.usb_info = usb_info
if config.platform == "macos" and usb_info is None:
raise ValueError("macos_connect must be provided for macOS platform.")
self.contents: list[ContentUnion] = []
# ESC/POS commands
self.commands = bytearray()
# add helper
self.FlexItem = FlexItemFactory(
self.default_font, self.paper_width - 2 * self.padding_x, self.font_sizes
)
def _validate_config(self, config: PrinterConfig):
"""
Just validate the printer config.
Do not modify the config.
"""
if not isinstance(config.paper_width, (str, int)):
raise ValueError("Invalid Config: paper_width must be a str or int.")
if (
isinstance(config.paper_width, str)
and config.paper_width not in DEFAULT_PAPER_WIDTH
):
raise ValueError(
"Invalid Config: paper_width must be a key of DEFAULT_PAPER_WIDTH."
)
if config.font_sizes is not None:
if not isinstance(config.font_sizes, dict):
raise ValueError("Invalid Config: font_sizes. Must be a dictionary.")
for key, value in config.font_sizes.items():
if key not in DEFAULT_FONT_SIZES:
raise ValueError(
f"Invalid Config: font_sizes. Unsupported key '{key}'."
)
if not isinstance(value, int):
raise ValueError(
f"Invalid Config: font_sizes. Value for '{key}' must be an int."
)
if config.platform is not None and config.platform not in [
"windows",
"linux",
"macos",
]:
raise ValueError("Invalid Config: Unsupported platform.")
# ==================
# ===== render =====
# ==================
def _convert_contents(self) -> Image.Image:
"""
把 contents 渲染为图像
"""
# 先生成每一段的 Image,收集所有高度
rendered_blocks: list[_RenderedBlock] = []
total_height = 0
for content in self.contents:
if isinstance(content, Text):
blocks = self._render_text(content)
for index, _block in enumerate(blocks):
if len(blocks) > 1 and index > 0 and content.line_spacing > 0:
spacing_bloak = self._render_newline(
NewLine(lines=1, height=content.line_spacing)
)
rendered_blocks.append(_RenderedBlock(spacing_bloak, 0))
total_height += spacing_bloak.height
rendered_blocks.append(_RenderedBlock(_block, 0))
total_height += _block.height
elif isinstance(content, QrCode):
block = self._render_qrcode(content)
rendered_blocks.append(_RenderedBlock(block, 0))
total_height += block.height
elif isinstance(content, NewLine):
block = self._render_newline(content)
rendered_blocks.append(_RenderedBlock(block, 0))
total_height += block.height
elif isinstance(content, ImageContent):
block = self._render_image(content)
rendered_blocks.append(_RenderedBlock(block, 0))
total_height += block.height
elif isinstance(content, Flex):
renderer = FlexRenderer(content, self.paper_width - 2 * self.padding_x)
block = renderer.render()
rendered_blocks.append(_RenderedBlock(block, self.padding_x))
total_height += block.height
else:
raise ValueError(f"Unsupported content type. {content}")
# 创建最终图像
result_img = Image.new("L", (self.paper_width, total_height), color=255)
y_offset = 0
for block in rendered_blocks:
result_img.paste(block.image, (block.x, y_offset))
y_offset += block.image.height
return result_img
def _render_text(self, text_obj: Text) -> list[Image.Image]:
try:
font = ImageFont.truetype(text_obj.font, text_obj.font_size)
except Exception:
font = ImageFont.load_default()
# Split text into lines based on container width and current_x
lines = []
current_line = ""
line_images = []
for char in text_obj.text:
test_line = current_line + char
dummy_img = Image.new("L", (1, 1), color=255)
draw = ImageDraw.Draw(dummy_img)
bbox = draw.textbbox((0, 0), test_line, font=font)
if bbox[2] > (
self.paper_width - 2 * self.padding_x
): # Adjust for padding_x
lines.append((current_line, self.paper_width - 2 * self.padding_x))
current_line = char
else:
current_line = test_line
if current_line: # Add the last line
lines.append((current_line, self.paper_width - 2 * self.padding_x))
# Render each line as a separate image
for line, line_width in lines:
dummy_img = Image.new("L", (1, 1), color=255)
draw = ImageDraw.Draw(dummy_img)
actual_line_width = draw.textbbox((0, 0), line, font=font)[2]
bbox = draw.textbbox((0, 0), line, font=font)
line_height = bbox[3] - bbox[1] # Ensure height includes baseline content
if text_obj.align == "left":
x_offset = self.padding_x
elif text_obj.align == "center":
x_offset = (self.paper_width - actual_line_width) // 2
elif text_obj.align == "right":
x_offset = self.paper_width - actual_line_width - self.padding_x
else:
raise ValueError(f"Unsupported alignment: {text_obj.align}")
img = Image.new("L", (self.paper_width, line_height), color=255)
draw = ImageDraw.Draw(img)
draw.text(
(x_offset, -bbox[1]), line, font=font, fill=0
) # Adjust for baseline
line_images.append(img)
return line_images
def _render_qrcode(self, qr_obj: QrCode) -> Image.Image:
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.ERROR_CORRECT_L,
box_size=qr_obj.box_size,
border=qr_obj.border,
)
qr.add_data(qr_obj.data)
qr.make(fit=True)
qr_img = qr.make_image(fill_color="black", back_color="white").convert("L")
# Centering with padding_x
qr_width, qr_height = qr_img.size
if qr_width > (self.paper_width - 2 * self.padding_x):
qr_img = qr_img.resize(
(
self.paper_width - 2 * self.padding_x,
self.paper_width - 2 * self.padding_x,
)
)
final_img = Image.new("L", (self.paper_width, qr_img.height), color=255)
x = (self.paper_width - qr_img.width) // 2
final_img.paste(qr_img, (x, 0))
return final_img
def _render_newline(self, newline_obj: NewLine) -> Image.Image:
height = newline_obj.height * newline_obj.lines
return Image.new("L", (self.paper_width, height), color=255)
def _render_image(self, img_obj: ImageContent) -> Image.Image:
img = img_obj.image.convert("L") # Convert to grayscale
if img_obj.max_width:
if img_obj.max_width > (self.paper_width - 2 * self.padding_x):
img_obj.max_width = self.paper_width - 2 * self.padding_x
if img.width > img_obj.max_width:
ratio = img_obj.max_width / img.width
new_height = int(img.height * ratio)
img = img.resize((img_obj.max_width, new_height))
else:
if img.width > (self.paper_width - 2 * self.padding_x):
ratio = (self.paper_width - 2 * self.padding_x) / img.width
new_height = int(img.height * ratio)
img = img.resize((self.paper_width - 2 * self.padding_x, new_height))
# Centering with padding_x
canvas = Image.new("L", (self.paper_width, img.height), color=255)
x = (self.paper_width - img.width) // 2
canvas.paste(img, (x, 0))
return canvas
# =============================
# ====== ESC/POS command ======
# =============================
def _escpos_init(self):
"""
初始化打印机
"""
self.commands += b"\x1b\x40"
return self
def _escpos_feed(self, lines=1):
"""
进纸
"""
self.commands += b"\x1b\x64" + bytes([lines])
return self
def _escpos_cut(self):
"""
切纸
"""
self.commands += b"\x1d\x56\x00"
return self
def _image_to_escpos(self, image):
"""
将 PIL 黑白图像转换为 ESC/POS 图像打印指令(单色)并添加到命令列表中
"""
# 二值化图像
threshold = 200
image = image.point(lambda p: 0 if p < threshold else 255, mode="1")
width = image.width
height = image.height
if width % 8 != 0:
new_width = (width + 7) & ~7
image = image.resize((new_width, height))
width = new_width
data = bytearray()
data += b"\x1d\x76\x30\x00" # GS v 0
data += (width // 8).to_bytes(2, "little")
data += height.to_bytes(2, "little")
pixels = image.load()
for y in range(height):
for x_byte in range(width // 8):
byte = 0
for bit in range(8):
x = x_byte * 8 + bit
if pixels[x, y] == 0:
byte |= 1 << (7 - bit)
data.append(byte)
self.commands += data
return self
def _escpos_send_windows(self):
import win32print
printer = win32print.OpenPrinter(self.printer_name)
try:
win32print.StartDocPrinter(printer, 1, ("ESC/POS Job", None, "RAW"))
win32print.StartPagePrinter(printer)
win32print.WritePrinter(printer, self.commands)
win32print.EndPagePrinter(printer)
win32print.EndDocPrinter(printer)
finally:
win32print.ClosePrinter(printer)
def _escpos_send_linux(self):
try:
with open(self.printer_name, "wb") as printer:
printer.write(self.commands)
except FileNotFoundError:
raise ValueError(f"Printer '{self.printer_name}' not found.")
except PermissionError:
raise ValueError(
f"Permission denied to access printer '{self.printer_name}'."
)
def _escpos_send_macos(self):
from escpos.printer import Usb
if not self.usb_info:
raise ValueError("USB info is required for macOS platform.")
p = Usb(
self.usb_info.vendor_id,
self.usb_info.product_id,
interface=self.usb_info.interface,
in_ep=self.usb_info.in_ep,
out_ep=self.usb_info.out_ep,
)
p._raw(self.commands)
def _escpos_send(self):
"""
发送命令到打印机
"""
if self.platform == "windows":
self._escpos_send_windows()
elif self.platform == "linux":
self._escpos_send_linux()
elif self.platform == "macos":
self._escpos_send_macos()
else:
raise ValueError(
"Unsupported platform. Only 'windows', 'linux', 'macOS' are supported."
)
# ==========================
# ===== public methods =====
# ==========================
def text(
self,
*,
text,
align="left",
font_size=None,
font=None,
line_spacing=4,
):
"""
打印文本内容
:param text: 文本内容
:param align: 对齐方式 ("left" | "center" | "right")
- default: "left"
:param font_size: 字体大小 (int)
:param font: 字体路径
- default: self.default_font
:param line_spacing: 行间距 (int)
- default: 4
"""
if font is None:
font = self.default_font
if font_size is None:
font_size = self.font_sizes["md"]
elif font_size in self.font_sizes:
font_size = self.font_sizes[font_size]
elif isinstance(font_size, int):
font_size = font_size
else:
raise ValueError("font_size must be an int or a key in self.font_sizes.")
self.contents.append(
Text(
text=text,
align=align,
font_size=font_size,
font=font,
line_spacing=line_spacing,
)
)
return self
def newline(self, *, height=28, lines=1):
"""
换行
:param height: 换行高度
- default: 28
:param lines: 换行的行数
- default: 1
"""
self.contents.append(NewLine(lines=lines, height=height))
return self
def qrcode(self, *, data, size="lg"):
"""
打印二维码
:param data: 二维码内容
:param size: 二维码大小 ("sm" | "md" | "lg" | Tuple[box_size: int, border: int])
"""
if isinstance(size, tuple):
if len(size) != 2:
raise ValueError("size must be a tuple of (box_size, border).")
box_size, border = size
elif isinstance(size, str):
if size == "sm":
box_size = 8
border = 2
elif size == "md":
box_size = 10
border = 2
elif size == "lg":
box_size = 16
border = 2
else:
raise ValueError("Invalid size. Choose 'sm', 'md', or 'lg'.")
else:
raise ValueError("size must be a str or a tuple of (box_size, border).")
self.contents.append(QrCode(data=data, box_size=box_size, border=border))
return self
def image(
self,
*,
image=None,
max_width=None,
):
"""
打印图片
:param image: (str | Image.Image)
- str: 图片路径
- Image.Image: PIL 图像对象
:param max_width: 图片最大宽度 (int | None | "full")
- int: 缩放到指定宽度
- None: 不缩放 (大于纸张宽度时会自动缩放到纸张宽度)
- "full": 缩放到纸张宽度
- default: None
"""
if max_width == "full":
max_width = self.paper_width
if image is None:
raise ValueError("Image must be provided.")
if not isinstance(image, Image.Image) and not isinstance(image, str):
raise ValueError("Image must be a PIL Image or a file path.")
if isinstance(image, str):
image = Image.open(image).convert("L")
self.contents.append(ImageContent(image=image, max_width=max_width))
return self
def flex(
self,
*,
items: list[Text | QrCode | ImageContent | Flex],
item_gap: int = 0,
row_gap: int = 0,
horizontal_align: str = "left",
vertical_align: str = "top",
):
"""
打印 Flex 布局内容
:param items: Flex 布局的内容列表
- list[Text | QrCode | ImageContent]
:param item_gap: 同一行内元素之间的间距 (int)
- default: 0
:param row_gap: 行与行之间的间距 (int)
- default: 0
:param horizontal_align: 水平对齐方式 ("left" | "right" | "between")
- default: "left"
:param vertical_align: 垂直对齐方式 ("top" | "center" | "bottom")
- default: "top"
"""
self.contents.append(
Flex(
items=items,
item_gap=item_gap,
row_gap=row_gap,
horizontal_align=horizontal_align,
vertical_align=vertical_align,
max_width=self.paper_width,
)
)
return self
def print(self, padding_top=2, padding_bottom=2):
"""
打印所有内容
"""
image = self._convert_contents()
# fmt: off
self \
._escpos_init() \
._escpos_feed(padding_top) \
._image_to_escpos(image) \
._escpos_feed(padding_bottom) \
._escpos_cut() \
._escpos_send()
# fmt: on