pos-printer-server/print_log.py

87 lines
2.2 KiB
Python
Raw Normal View History

2022-05-04 04:25:26 +00:00
#!/bin/env python3
from escpos.printer import Usb
import getopt
import sys
import datetime
TEXT_LIMIT=256
class PrintOptions:
title = None
text = None
verbose = False
image = None
def get_printer():
return Usb(0x0525, 0xa700) # <-- change based on your printer vendor and product ID
def do_print(options):
p = get_printer()
p.set(align='center')
p.text(str(datetime.datetime.now().strftime("%H:%M:%S")))
p.text(' ')
p.text(str(datetime.date.today()))
p.text('\n')
if (options.title):
p.set(align='center', text_type='B') # center bold
p.text(options.title + '\n')
p.set()
if len(options.text) > TEXT_LIMIT:
p.text(options.text[:TEXT_LIMIT] + '[...]\n(truncated)')
else:
p.text(options.text + '\n')
if options.image != None:
p.image(options.image)
p.cut()
def do_print_image(path):
p = get_printer()
p.image(path)
p.cut()
def usage():
print(f'usage: {sys.argv[0]} [OPTIONS] TEXT...')
print(f' OPTIONS')
print(f' -v ... verbose')
print(f' -h ... help')
print(f' -t --title=X ... title to prepend')
print(f' -i --image=X ... image path')
print(f' TEXT is taken as the rest of argumenats if present,')
print(f' otherwise from STDIN (terminated by Ctrl+D).')
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "ht:i:v", ["help", "title=", "image="])
except getopt.GetoptError as err:
print(err)
usage()
sys.exit(2)
title = None
verbose = False
image = None
for o, a in opts:
if o == "-v":
verbose = True
elif o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-i", "--image"):
image = a
elif o in ("-t", "--title"):
title = a
else:
assert False, "unhandled option"
options = PrintOptions()
options.title = title
options.verbose = verbose
options.text = " ".join(args)
options.image = image
if len(options.text) <= 0:
for line in sys.stdin:
options.text = options.text + line
do_print(options)
if __name__ == "__main__":
main()