Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import barcode
- from barcode.writer import ImageWriter
- from cStringIO import StringIO
- from PIL import ImageFont
- import os
- PATH = os.path.dirname(os.path.abspath(__file__))
- FONT = os.path.join(PATH, 'DejaVuSansMono.ttf')
- def mm2px(mm, dpi=300):
- return (mm * dpi) / 25.4
- class MyImageWriter(ImageWriter):
- def calculate_size(self, modules_per_line, number_of_lines, dpi=300):
- width = 2 * self.quiet_zone + modules_per_line * self.module_width
- height = 1.0 + self.module_height * number_of_lines
- if self.text:
- height += (self.font_size + self.text_distance) / 3
- return int(mm2px(width, dpi)), int(mm2px(height, dpi))
- def _paint_text(self, xpos, ypos):
- # this should hopefully align your font to the left side of the bar code:
- xpos = self.quiet_zone
- pos = (mm2px(xpos, self.dpi), mm2px(ypos, self.dpi))
- font = ImageFont.truetype(FONT, self.font_size)
- self._draw.text(pos, self.text, font=font, fill=self.foreground)
- i = StringIO()
- bc_factory = barcode.get_barcode_class('upca')
- bc_factory.default_writer_options['quiet_zone'] = 1.0
- bc_factory.default_writer_options['text_distance'] = 1.0
- bc_factory.default_writer_options['module_height'] = 10.0
- bc_factory.default_writer_options['module_width'] = 0.3
- bc_factory.default_writer_options['font_size'] = 46
- bc = bc_factory('12345678910', writer=MyImageWriter())
- bc.write(i)
- f = file('barcode.png', 'w')
- f.write(i.getvalue())
- f.close()
- i.close()
Advertisement
Add Comment
Please, Sign In to add comment