git.schokokeks.org
Repositories
Help
Report an Issue
python-escpos-printer.git
Code
Commits
Branches
Tags
Suche
Strukturansicht:
ff31c22
Branches
Tags
main
v0.1.0
python-escpos-printer.git
src
escpos_printer
esc.py
initial commit
Bernd Wurst
commited
ff31c22
at 2026-11-26 17:47:00
esc.py
Blame
History
Raw
# -* coding: utf-8 *- # (C) 2012 by Bernd Wurst <bernd@schokokeks.org> # This file is part of Bib2011. # # Bib2011 is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Bib2011 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Bib2011. If not, see <http://www.gnu.org/licenses/>. import time from functools import reduce from .networkprinter import NetworkPrinter from .usbprinter import USBPrinter from .EscposImage import EscposImage import six # Barcode chars BARCODE_TXT_BLW = b'\x1d\x48\x02' # HRI barcode chars below BARCODE_FONT_A = b'\x1d\x66\x00' # Font type A for HRI barcode chars BARCODE_HEIGHT = b'\x1d\x68\x64' # Barcode Height [1-255] BARCODE_WIDTH = b'\x1d\x77\x03' # Barcode Width [2-6] BARCODE_EAN13 = b'\x1d\x6b\x02' # Barcode type EAN13 class ESCPrinter(object): def __init__(self, type='usb', address=None, port=None, cp858=None, usb_fix_script=None): """type: 'usb' or 'network'. address/port/cp858 are used for network printers.""" if type == 'usb': self.device = USBPrinter(fix_script=usb_fix_script) elif type == 'network': if address is None or port is None: raise ValueError("address and port are required for network printers") kwargs = {} if cp858 is None else {'cp858': cp858} self.device = NetworkPrinter(address, port, **kwargs) else: raise ValueError("unknown printer type: %r" % (type,)) self.ready = self.device.initialized self.codepage_id = self.device.printer_config['cp858'] or 19 self.reset() def initialize(self): if not self.device.initialized: self.device.initialize() self.ready = self.device.initialized def __del__(self): self.terminate() del self.device def terminate(self): self.device.terminate() def reset(self): # Reset printer self.write(self.encode(chr(27) + chr(64))) # Set code page 858 (mit Euro-Zeichen) self.write(self.encode(chr(27) + chr(116) + chr(self.codepage_id))) def encode(self, string): assert type(string) == str, 'illegal argument, cannot encode' return string.encode('cp858') def write(self, string): if not isinstance(string, bytes): string = string.encode('cp858') self.raw(string) def raw(self, command): if not self.device.initialized: return self.device.write(command) def read(self): if not self.device.initialized: return return self.device.read() def print_esc(self, data): # split bei RESET-Befehl for part in data.split(self.encode(chr(27) + chr(64))): # alten codepage-Befehl herausnehmen if part.startswith(self.encode(chr(27) + chr(116))): part = part[3:] self.raw(part) self.reset() def ean13(self, code): if len(code) != 12: raise ValueError('require 12 digits') code = [int(i) for i in code] sum_ = lambda x, y: int(x) + int(y) evensum = reduce(sum_, code[::2]) oddsum = reduce(sum_, code[1::2]) check = (10 - ((evensum + oddsum * 3) % 10)) % 10 code = b''.join([bytes(i) for i in code]) + bytes(check) # Align Bar Code() self.raw(b'\x1b\x61\x01') # center self.raw(BARCODE_HEIGHT) self.raw(BARCODE_WIDTH) self.raw(BARCODE_FONT_A) self.raw(BARCODE_TXT_BLW) self.raw(BARCODE_EAN13) # Print Code if code: self.raw(code) else: raise ValueError('No code') def text(self, string): self.write(string) def bold(self, state=True): if state: self.write(chr(27) + chr(69) + chr(1)) else: self.write(chr(27) + chr(69) + chr(0)) def underline(self, state=True): if state == 2: self.write(chr(27) + chr(45) + chr(2)) elif state == 1 or state is True: self.write(chr(27) + chr(45) + chr(1)) else: self.write(chr(27) + chr(45) + chr(0)) def align(self, align): command = 0 if align == 'center': command = 1 elif align == 'right': command = 2 self.write(chr(27) + chr(97) + chr(command)) def font(self, mytype): command = 0 if mytype == 'B': command = 1 self.write(chr(27) + chr(77) + chr(command)) def fontsize(self, width, height): width = (width - 1) % 8 height = (height - 1) % 8 size = (width << 4) | height # set font scaling self.write(chr(29) + chr(33) + chr(size)) # turn smoothing on self.write(chr(29) + chr(98) + chr(1)) def cut(self, mode='full'): command = 0 if mode == 'partial': command = 1 blanklines = 3 self.write(chr(29) + chr(86) + chr(command + 65) + chr(blanklines)) def openDrawer(self): self.write(chr(27) + chr(112) + chr(0) + chr(25) + chr(250)) def drawerIsOpen(self): garbage = self.read() self.write(chr(27) + chr(117) + chr(0)) status = None for i in range(100): time.sleep(0.01) recv = self.read().tolist() if len(recv) > 0: status = recv[0] break if status & 0x01: return False else: return True def image(self, imgfile, center=True): # heavily based on python-escpos (https://github.com/python-escpos/python-escpos) # by Manuel F Martinez <manpaz@bashlinux.com> and others im = EscposImage(imgfile) # Breite: 576 px max_width = 576 if center: im.center(max_width) # GS v 0, raster format bit image header = ( b"\x1d" + b"v0" + b"\x00" + self._int_low_high(im.width_bytes, 2) + self._int_low_high(im.height, 2) ) self.raw(header + im.to_raster_format()) @staticmethod def _int_low_high(inp_number, out_bytes): """Generate multiple bytes for a number: In lower and higher parts, or more parts as needed. :param inp_number: Input number :param out_bytes: The number of bytes to output (1 - 4). """ max_input = 256 << (out_bytes * 8) - 1 if not 1 <= out_bytes <= 4: raise ValueError("Can only output 1-4 bytes") if not 0 <= inp_number <= max_input: raise ValueError( "Number too large. Can only output up to {0} in {1} bytes".format( max_input, out_bytes ) ) outp = b"" for _ in range(0, out_bytes): outp += six.int2byte(inp_number % 256) inp_number //= 256 return outp if __name__ == '__main__': import sys e = ESCPrinter() e.raw(sys.stdin.buffer.read()) # e.font('A') # e.reset() # rawdata = '\xff' * (16 * 32) # e.raw('\x1d\x76\x30\0\x02\0\x01\0\xff') # e.text('\n\n\n') # e.fontsize(2,2) # e.text('1234567890'*3) # e.text('\n') # e.ean13('200123456789') # printer = e # printer.image('logo.gif') # printer.text('\n') # printer.align('center') # printer.text('Mosterei Bernd Wurst\n') # printer.text('Köchersberg 30\n') # printer.text('71540 Murrhardt\n') # printer.text('07192 - 936434\n') # printer.text('\n\n') # e.cut()