Skip to content

Instantly share code, notes, and snippets.

@rossgoodwin
Created April 30, 2018 17:46
Show Gist options
  • Save rossgoodwin/0c0d3aed3a379c03e7c98c87a4ad33f2 to your computer and use it in GitHub Desktop.
Save rossgoodwin/0c0d3aed3a379c03e7c98c87a4ad33f2 to your computer and use it in GitHub Desktop.
Thermal Printer Library (Python3)
import serial
import string
import os
import time
ser = serial.Serial('/dev/ttyUSB0')
ser.write(b'{LP}')
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in xrange(0, len(l), n):
yield l[i:i+n]
def split_to_lines(text, ll=80):
printable_char_set = set(string.printable)
if not text:
return ""
text_list = list(filter(
lambda x: x in printable_char_set,
list(text.strip())
))
char_count = 0
ws_indexes = list()
cur_line = list()
all_lines = list()
i = 0
start_ix = 0
while i < len(text_list):
c = text_list[i]
# print c
if c in [' ', '\t']:
ws_indexes.append(i)
cur_line.append(c)
char_count += 1
if c == '\n':
cur_line = text_list[start_ix:i]
start_ix = i
all_lines.append(''.join(cur_line))
cur_line = list()
char_count = 0
elif char_count >= ll:
tgt_ix = ws_indexes.pop()
cur_line = text_list[start_ix:tgt_ix]
i = tgt_ix
start_ix = i
all_lines.append(''.join(cur_line))
cur_line = list()
char_count = 0
i += 1
all_lines.append(''.join(cur_line))
return list(map(lambda x: x.strip(), all_lines))
def line_print_mode():
ser.write('{LP}'.encode('utf8'))
def feed_paper():
ser.write('\n'.encode('utf8')*4)
def line_break():
ser.write('\n'.encode('utf8'))
def basic_print(text):
ser.write('\n'.encode('utf8'))
ser.write(text.encode('utf8'))
time.sleep(0.5)
def thermal_print(text):
font_switch = chr(27) + '!4'
for l in split_to_lines(text, ll=38):
ser.write(font_switch.encode('utf8'))
ser.write(' '.encode('utf8')+l.encode('utf8'))
ser.write('\n'.encode('utf8'))
time.sleep(0.5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment