ESC/POS Thermal Printer Server
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.2 KiB

  1. #!/bin/env python3
  2. from escpos.printer import Usb
  3. import getopt
  4. import sys
  5. import datetime
  6. TEXT_LIMIT=256
  7. class PrintOptions:
  8. title = None
  9. text = None
  10. verbose = False
  11. image = None
  12. def get_printer():
  13. return Usb(0x0525, 0xa700) # <-- change based on your printer vendor and product ID
  14. def do_print(options):
  15. p = get_printer()
  16. p.set(align='center')
  17. p.text(str(datetime.datetime.now().strftime("%H:%M:%S")))
  18. p.text(' ')
  19. p.text(str(datetime.date.today()))
  20. p.text('\n')
  21. if (options.title):
  22. p.set(align='center', text_type='B') # center bold
  23. p.text(options.title + '\n')
  24. p.set()
  25. if len(options.text) > TEXT_LIMIT:
  26. p.text(options.text[:TEXT_LIMIT] + '[...]\n(truncated)')
  27. else:
  28. p.text(options.text + '\n')
  29. if options.image != None:
  30. p.image(options.image)
  31. p.cut()
  32. def do_print_image(path):
  33. p = get_printer()
  34. p.image(path)
  35. p.cut()
  36. def usage():
  37. print(f'usage: {sys.argv[0]} [OPTIONS] TEXT...')
  38. print(f' OPTIONS')
  39. print(f' -v ... verbose')
  40. print(f' -h ... help')
  41. print(f' -t --title=X ... title to prepend')
  42. print(f' -i --image=X ... image path')
  43. print(f' TEXT is taken as the rest of argumenats if present,')
  44. print(f' otherwise from STDIN (terminated by Ctrl+D).')
  45. def main():
  46. try:
  47. opts, args = getopt.getopt(sys.argv[1:], "ht:i:v", ["help", "title=", "image="])
  48. except getopt.GetoptError as err:
  49. print(err)
  50. usage()
  51. sys.exit(2)
  52. title = None
  53. verbose = False
  54. image = None
  55. for o, a in opts:
  56. if o == "-v":
  57. verbose = True
  58. elif o in ("-h", "--help"):
  59. usage()
  60. sys.exit()
  61. elif o in ("-i", "--image"):
  62. image = a
  63. elif o in ("-t", "--title"):
  64. title = a
  65. else:
  66. assert False, "unhandled option"
  67. options = PrintOptions()
  68. options.title = title
  69. options.verbose = verbose
  70. options.text = " ".join(args)
  71. options.image = image
  72. if len(options.text) <= 0:
  73. for line in sys.stdin:
  74. options.text = options.text + line
  75. do_print(options)
  76. if __name__ == "__main__":
  77. main()