Jun 302017
 

This small thermal printer is very basic and uses 1980s style ESC/POS control codes (like most similar printers of this type that are used in shops for receipt printing). Sending UTF-8 text directly to it (such as any accented characters) doesn’t work well, as the accented characters have different codes (this printer can use a variety of old DOS code pages but defaults to 437).

Luckily Python has all these text conversion functions built in (you don’t even need to roll your own lookup tables!)

# # # convert UTF-8 to codepage for thermal printer # # # this is UTF-8 text with German characters # import pprint import serial # # USB converter device name for thermal printer # ttyname = 'COM2' text1 = [ 'Sie kam als Kind\nwohl am Sonntag an,\n', 'denn sie hieß,\nseit ich denken kann,\n', 'immer nur Sunday Girl.\n', 'Sie war nie Schuld,\nganz egal woran,\n', 'ihr hat nie etwas weh getan,\n', 'denn sie war Sunday Girl.\n\n', 'Kalt wie Eis und genau so süß\n', 'so war sie und auch manchmal\nganz schön mies.\n', 'Für sie war es ein Kinderspiel,\n', 'pech für den, dem sie gefiel.\n', ] # # convert output to list of bytes with codepage # using printers default codepage 437 # opt =[] for i in range(len(text1)): byt = str.encode(text1[i],'cp437') opt.append(byt) # # open the printer port and send data # s=serial.Serial(ttyname,19200) # # centre the title text and bold it # s.write(b'\x1ba1\x1bE1') s.write(b'Text conversion test\n\n') s.write(b'\x1ba0\x1bE0') # print the converted text for i in range(len(opt)): s.write(opt[i]) # # done, print complete message # s.write(b'\x1ba1\x1bE1') s.write(b'\n\nComplete...\n\n\n') s.write(b'\x1ba0\x1bE0')
textconv.py


 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)