print_label.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/env python
  2. """print_label.py - print a label with the name, the company and the person_id (in a barcode) of an attendee
  3. Copyright 2015 Emiliano Mattioli <oloturia AT gmail.com>
  4. Davide Alberani <da@erlug.linux.it>
  5. RaspiBO <info@raspibo.org>
  6. Licensed under the Apache License 2.0
  7. """
  8. import os
  9. import sys
  10. import cups
  11. import tempfile
  12. from PIL import Image, ImageFont, ImageDraw
  13. LABEL_WIDTH = 13488
  14. LABEL_HEIGHT = 3744
  15. FONT_TEXT = 'Ubuntu-C.ttf'
  16. FONT_TEXT_ENCODING = 'latin-1'
  17. FONT_BARCODE = 'free3of9.ttf'
  18. PRINTER_NAME = None
  19. def _get_resource(filename):
  20. return os.path.join(os.path.dirname(sys.argv[0]), filename)
  21. def build_label(w, h, barcode_text, line1, line2, font_text=FONT_TEXT, font_barcode=FONT_BARCODE):
  22. barcode_text = "*" + barcode_text + "*"
  23. line1 = unicode(line1, 'utf-8').encode(FONT_TEXT_ENCODING, 'ignore')
  24. line2 = unicode(line2, 'utf-8').encode(FONT_TEXT_ENCODING, 'ignore')
  25. fontbar = ImageFont.truetype(_get_resource(font_barcode), 1200)
  26. fontnorm = ImageFont.truetype(_get_resource(font_text), 780)
  27. image = Image.new('RGB', (w, h), (255, 255, 255))
  28. draw = ImageDraw.Draw(image)
  29. wbar, hbar = draw.textsize(barcode_text, font=fontbar)
  30. wnorm1, hnorm1 = draw.textsize(line1, font=fontnorm)
  31. wnorm2, hnorm2 = draw.textsize(line2, font=fontnorm)
  32. draw.text(((w-wnorm1)/2, -1200+(h-hnorm1)/2), line1, (0, 0, 0), font=fontnorm)
  33. draw.text(((w-wnorm2)/2, -450+(h-hnorm2)/2), line2, (0, 0, 0), font=fontnorm)
  34. draw.text(((w-wbar)/2, 750+(h-hbar)/2), barcode_text, (0, 0, 0), font=fontbar)
  35. tmpfile = tempfile.NamedTemporaryFile(prefix='eventman_print_label_', suffix='.png')
  36. image.save(tmpfile, dpi=[600,300], format='png')
  37. return tmpfile
  38. def print_label(label_file, name):
  39. conn = cups.Connection()
  40. printer = PRINTER_NAME or conn.getDefault()
  41. conn.printFile(printer, label_file.name, name, {})
  42. def run():
  43. # Always consume stdin.
  44. sys.stdin.read()
  45. name = ' '.join([os.environ.get('NAME') or '', os.environ.get('SURNAME') or ''])
  46. company = os.environ.get('COMPANY') or ''
  47. person_id = os.environ.get('PERSON_ID', '').upper()
  48. label_file = build_label(LABEL_WIDTH, LABEL_HEIGHT, person_id, name, company)
  49. print_label(label_file, name)
  50. if __name__ == '__main__':
  51. try:
  52. run()
  53. except Exception, e:
  54. sys.stderr.write('print_label. Exception raised: %s\n' % e)