dibbler/barcode_helpers.py

67 lines
2.3 KiB
Python
Raw Normal View History

2017-03-22 18:16:22 +01:00
import os
2017-03-21 21:43:36 +01:00
from PIL import ImageFont
from barcode.writer import ImageWriter, mm2px
from brother_ql.devicedependent import label_type_specs
def px2mm(px, dpi=300):
return (25.4 * px)/dpi
class BrotherLabelWriter(ImageWriter):
def __init__(self, typ='62', max_height=350, rot=False, text=None):
2017-03-21 21:50:41 +01:00
super(BrotherLabelWriter, self).__init__()
2017-03-21 21:43:36 +01:00
assert typ in label_type_specs
self.rot = rot
if self.rot:
2017-03-21 21:43:36 +01:00
self._h, self._w = label_type_specs[typ]['dots_printable']
if self._w == 0 or self._w > max_height:
self._w = min(max_height, self._h / 2)
else:
2017-03-21 21:43:36 +01:00
self._w, self._h = label_type_specs[typ]['dots_printable']
if self._h == 0 or self._h > max_height:
self._h = min(max_height, self._w / 2)
2017-03-21 21:43:36 +01:00
self._xo = 0.0
self._yo = 0.0
self._title = text
def _init(self, code):
self.text = None
2017-03-21 21:50:41 +01:00
super(BrotherLabelWriter, self)._init(code)
2017-03-21 21:43:36 +01:00
def calculate_size(self, modules_per_line, number_of_lines, dpi=300):
x, y = super(BrotherLabelWriter, self).calculate_size(modules_per_line, number_of_lines, dpi)
2017-03-21 21:43:36 +01:00
self._xo = (px2mm(self._w)-px2mm(x))/2
self._yo = (px2mm(self._h)-px2mm(y))
assert self._xo >= 0
assert self._yo >= 0
return int(self._w), int(self._h)
def _paint_module(self, xpos, ypos, width, color):
2017-03-21 21:50:41 +01:00
super(BrotherLabelWriter, self)._paint_module(xpos+self._xo, ypos+self._yo, width, color)
2017-03-21 21:43:36 +01:00
def _paint_text(self, xpos, ypos):
2017-03-21 21:50:41 +01:00
super(BrotherLabelWriter, self)._paint_text(xpos+self._xo, ypos+self._yo)
2017-03-21 21:43:36 +01:00
def _finish(self):
if self._title:
width = self._w+1
height = 0
max_h = self._h - mm2px(self._yo, self.dpi)
fs = int(max_h / 1.2)
2017-03-22 18:16:22 +01:00
font_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "Stranger back in the Night.ttf")
font = ImageFont.truetype(font_path, 10)
2017-03-21 21:43:36 +01:00
while width > self._w or height > max_h:
2017-03-22 18:16:22 +01:00
font = ImageFont.truetype(font_path, fs)
2017-03-21 21:43:36 +01:00
width, height = font.getsize(self._title)
fs -= 1
pos = (
(self._w-width)//2,
0 - (height // 8)
2017-03-21 21:43:36 +01:00
)
self._draw.text(pos, self._title, font=font, fill=self.foreground)
return self._image