Guest User

barcode test

a guest
Jul 9th, 2011
387
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. import barcode
  2. from barcode.writer import ImageWriter
  3. from cStringIO import StringIO
  4. from PIL import ImageFont
  5. import os
  6.  
  7. PATH = os.path.dirname(os.path.abspath(__file__))
  8. FONT = os.path.join(PATH, 'DejaVuSansMono.ttf')
  9.  
  10. def mm2px(mm, dpi=300):
  11.     return (mm * dpi) / 25.4
  12.  
  13. class MyImageWriter(ImageWriter):
  14.     def calculate_size(self, modules_per_line, number_of_lines, dpi=300):
  15.         width = 2 * self.quiet_zone + modules_per_line * self.module_width
  16.         height = 1.0 + self.module_height * number_of_lines
  17.         if self.text:
  18.             height += (self.font_size + self.text_distance) / 3
  19.  
  20.         return int(mm2px(width, dpi)), int(mm2px(height, dpi))
  21.            
  22.     def _paint_text(self, xpos, ypos):
  23.         # this should hopefully align your font to the left side of the bar code:
  24.         xpos = self.quiet_zone
  25.         pos = (mm2px(xpos, self.dpi), mm2px(ypos, self.dpi))
  26.         font = ImageFont.truetype(FONT, self.font_size)
  27.         self._draw.text(pos, self.text, font=font, fill=self.foreground)
  28.        
  29. i = StringIO()
  30. bc_factory = barcode.get_barcode_class('upca')
  31. bc_factory.default_writer_options['quiet_zone'] = 1.0
  32. bc_factory.default_writer_options['text_distance'] = 1.0
  33. bc_factory.default_writer_options['module_height'] = 10.0
  34. bc_factory.default_writer_options['module_width'] = 0.3
  35. bc_factory.default_writer_options['font_size'] = 46
  36.  
  37. bc = bc_factory('12345678910', writer=MyImageWriter())
  38. bc.write(i)
  39.  
  40. f = file('barcode.png', 'w')
  41. f.write(i.getvalue())
  42. f.close()
  43. i.close()
Advertisement
Add Comment
Please, Sign In to add comment