widgets.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. #copyright ReportLab Europe Limited. 2000-2016
  2. #see license.txt for license details
  3. __version__='3.3.0'
  4. __all__= (
  5. 'BarcodeI2of5',
  6. 'BarcodeCode128',
  7. 'BarcodeStandard93',
  8. 'BarcodeExtended93',
  9. 'BarcodeStandard39',
  10. 'BarcodeExtended39',
  11. 'BarcodeMSI',
  12. 'BarcodeCodabar',
  13. 'BarcodeCode11',
  14. 'BarcodeFIM',
  15. 'BarcodePOSTNET',
  16. 'BarcodeUSPS_4State',
  17. )
  18. from reportlab.lib.validators import isInt, isNumber, isColor, isString, isColorOrNone, OneOf, isBoolean, EitherOr, isNumberOrNone
  19. from reportlab.lib.attrmap import AttrMap, AttrMapValue
  20. from reportlab.lib.colors import black
  21. from reportlab.lib.utils import rl_exec
  22. from reportlab.graphics.shapes import Line, Rect, Group, NotImplementedError, String
  23. from reportlab.graphics.charts.areas import PlotArea
  24. '''
  25. #snippet
  26. #first make your Drawing
  27. from reportlab.graphics.shapes import Drawing
  28. d= Drawing(100,50)
  29. #create and set up the widget
  30. from reportlab.graphics.barcode.widgets import BarcodeStandard93
  31. bc = BarcodeStandard93()
  32. bc.value = 'RGB-123456'
  33. #add to the drawing and save
  34. d.add(bc)
  35. # d.save(formats=['gif','pict'],fnRoot='bc_sample')
  36. '''
  37. class _BarcodeWidget(PlotArea):
  38. _attrMap = AttrMap(BASE=PlotArea,
  39. barStrokeColor = AttrMapValue(isColorOrNone, desc='Color of bar borders.'),
  40. barFillColor = AttrMapValue(isColorOrNone, desc='Color of bar interior areas.'),
  41. barStrokeWidth = AttrMapValue(isNumber, desc='Width of bar borders.'),
  42. value = AttrMapValue(EitherOr((isString,isNumber)), desc='Value.'),
  43. textColor = AttrMapValue(isColorOrNone, desc='Color of human readable text.'),
  44. valid = AttrMapValue(isBoolean),
  45. validated = AttrMapValue(isString,desc="validated form of input"),
  46. encoded = AttrMapValue(None,desc="encoded form of input"),
  47. decomposed = AttrMapValue(isString,desc="decomposed form of input"),
  48. canv = AttrMapValue(None,desc="temporarily used for internal methods"),
  49. gap = AttrMapValue(isNumberOrNone, desc='Width of inter character gaps.'),
  50. )
  51. textColor = barFillColor = black
  52. barStrokeColor = None
  53. barStrokeWidth = 0
  54. _BCC = None
  55. def __init__(self,_value='',**kw):
  56. PlotArea.__init__(self)
  57. if 'width' in self.__dict__: del self.__dict__['width']
  58. if 'height' in self.__dict__: del self.__dict__['height']
  59. self.x = self.y = 0
  60. kw.setdefault('value',_value)
  61. self._BCC.__init__(self,**kw)
  62. def rect(self,x,y,w,h,**kw):
  63. self._Gadd(Rect(self.x+x,self.y+y,w,h,
  64. strokeColor=self.barStrokeColor,strokeWidth=self.barStrokeWidth, fillColor=self.barFillColor))
  65. def draw(self):
  66. if not self._BCC: raise NotImplementedError("Abstract class %s cannot be drawn" % self.__class__.__name__)
  67. self.canv = self
  68. G = Group()
  69. self._Gadd = G.add
  70. self._Gadd(Rect(self.x,self.y,self.width,self.height,fillColor=None,strokeColor=None,strokeWidth=0.0001))
  71. self._BCC.draw(self)
  72. del self.canv, self._Gadd
  73. return G
  74. def annotate(self,x,y,text,fontName,fontSize,anchor='middle'):
  75. self._Gadd(String(self.x+x,self.y+y,text,fontName=fontName,fontSize=fontSize,
  76. textAnchor=anchor,fillColor=self.textColor))
  77. def _BCW(doc,codeName,attrMap,mod,value,**kwds):
  78. """factory for Barcode Widgets"""
  79. _pre_init = kwds.pop('_pre_init','')
  80. _methods = kwds.pop('_methods','')
  81. name = 'Barcode'+codeName
  82. ns = vars().copy()
  83. code = 'from %s import %s' % (mod,codeName)
  84. rl_exec(code,ns)
  85. ns['_BarcodeWidget'] = _BarcodeWidget
  86. ns['doc'] = ("\n\t'''%s'''" % doc) if doc else ''
  87. code = '''class %(name)s(_BarcodeWidget,%(codeName)s):%(doc)s
  88. \t_BCC = %(codeName)s
  89. \tcodeName = %(codeName)r
  90. \tdef __init__(self,**kw):%(_pre_init)s
  91. \t\t_BarcodeWidget.__init__(self,%(value)r,**kw)%(_methods)s''' % ns
  92. rl_exec(code,ns)
  93. Klass = ns[name]
  94. if attrMap: Klass._attrMap = attrMap
  95. for k, v in kwds.items():
  96. setattr(Klass,k,v)
  97. return Klass
  98. BarcodeI2of5 = _BCW(
  99. """Interleaved 2 of 5 is used in distribution and warehouse industries.
  100. It encodes an even-numbered sequence of numeric digits. There is an optional
  101. module 10 check digit; if including this, the total length must be odd so that
  102. it becomes even after including the check digit. Otherwise the length must be
  103. even. Since the check digit is optional, our library does not check it.
  104. """,
  105. "I2of5",
  106. AttrMap(BASE=_BarcodeWidget,
  107. barWidth = AttrMapValue(isNumber,'''(float, default .0075):
  108. X-Dimension, or width of the smallest element
  109. Minumum is .0075 inch (7.5 mils).'''),
  110. ratio = AttrMapValue(isNumber,'''(float, default 2.2):
  111. The ratio of wide elements to narrow elements.
  112. Must be between 2.0 and 3.0 (or 2.2 and 3.0 if the
  113. barWidth is greater than 20 mils (.02 inch))'''),
  114. gap = AttrMapValue(isNumberOrNone,'''(float or None, default None):
  115. width of intercharacter gap. None means "use barWidth".'''),
  116. barHeight = AttrMapValue(isNumber,'''(float, see default below):
  117. Height of the symbol. Default is the height of the two
  118. bearer bars (if they exist) plus the greater of .25 inch
  119. or .15 times the symbol's length.'''),
  120. checksum = AttrMapValue(isBoolean,'''(bool, default 1):
  121. Whether to compute and include the check digit'''),
  122. bearers = AttrMapValue(isNumber,'''(float, in units of barWidth. default 3.0):
  123. Height of bearer bars (horizontal bars along the top and
  124. bottom of the barcode). Default is 3 x-dimensions.
  125. Set to zero for no bearer bars. (Bearer bars help detect
  126. misscans, so it is suggested to leave them on).'''),
  127. quiet = AttrMapValue(isBoolean,'''(bool, default 1):
  128. Whether to include quiet zones in the symbol.'''),
  129. lquiet = AttrMapValue(isNumber,'''(float, see default below):
  130. Quiet zone size to left of code, if quiet is true.
  131. Default is the greater of .25 inch, or .15 times the symbol's
  132. length.'''),
  133. rquiet = AttrMapValue(isNumber,'''(float, defaults as above):
  134. Quiet zone size to right left of code, if quiet is true.'''),
  135. fontName = AttrMapValue(isString, desc='human readable font'),
  136. fontSize = AttrMapValue(isNumber, desc='human readable font size'),
  137. humanReadable = AttrMapValue(isBoolean, desc='if human readable'),
  138. stop = AttrMapValue(isBoolean, desc='if we use start/stop symbols (default 1)'),
  139. ),
  140. 'reportlab.graphics.barcode.common',
  141. 1234,
  142. _tests = [
  143. '12',
  144. '1234',
  145. '123456',
  146. '12345678',
  147. '1234567890'
  148. ],
  149. )
  150. BarcodeCode128 = _BCW("""Code 128 encodes any number of characters in the ASCII character set.""",
  151. "Code128",
  152. AttrMap(BASE=BarcodeI2of5,UNWANTED=('bearers','checksum','ratio','checksum','stop')),
  153. 'reportlab.graphics.barcode.code128',
  154. "AB-12345678",
  155. _tests = ['ReportLab Rocks!', 'PFWZF'],
  156. )
  157. BarcodeCode128Auto = _BCW(
  158. 'Modified Code128 to use auto encoding',
  159. 'Code128Auto',
  160. AttrMap(BASE=BarcodeCode128),
  161. 'reportlab.graphics.barcode.code128',
  162. 'XY149740345GB'
  163. )
  164. BarcodeStandard93=_BCW("""This is a compressed form of Code 39""",
  165. "Standard93",
  166. AttrMap(BASE=BarcodeCode128,
  167. stop = AttrMapValue(isBoolean, desc='if we use start/stop symbols (default 1)'),
  168. ),
  169. 'reportlab.graphics.barcode.code93',
  170. "CODE 93",
  171. )
  172. BarcodeExtended93=_BCW("""This is a compressed form of Code 39, allowing the full ASCII charset""",
  173. "Extended93",
  174. AttrMap(BASE=BarcodeCode128,
  175. stop = AttrMapValue(isBoolean, desc='if we use start/stop symbols (default 1)'),
  176. ),
  177. 'reportlab.graphics.barcode.code93',
  178. "L@@K! Code 93 ;-)",
  179. )
  180. BarcodeStandard39=_BCW("""Code39 is widely used in non-retail, especially US defence and health.
  181. Allowed characters are 0-9, A-Z (caps only), space, and -.$/+%*.""",
  182. "Standard39",
  183. AttrMap(BASE=BarcodeI2of5),
  184. 'reportlab.graphics.barcode.code39',
  185. "A012345B%R",
  186. )
  187. BarcodeExtended39=_BCW("""Extended 39 encodes the full ASCII character set by encoding
  188. characters as pairs of Code 39 characters; $, /, % and + are used as
  189. shift characters.""",
  190. "Extended39",
  191. AttrMap(BASE=BarcodeI2of5),
  192. 'reportlab.graphics.barcode.code39',
  193. "A012345B}",
  194. )
  195. BarcodeMSI=_BCW("""MSI is used for inventory control in retail applications.
  196. There are several methods for calculating check digits so we
  197. do not implement one.
  198. """,
  199. "MSI",
  200. AttrMap(BASE=BarcodeI2of5),
  201. 'reportlab.graphics.barcode.common',
  202. 1234,
  203. )
  204. BarcodeCodabar=_BCW("""Used in blood banks, photo labs and FedEx labels.
  205. Encodes 0-9, -$:/.+, and four start/stop characters A-D.""",
  206. "Codabar",
  207. AttrMap(BASE=BarcodeI2of5),
  208. 'reportlab.graphics.barcode.common',
  209. "A012345B",
  210. )
  211. BarcodeCode11=_BCW("""Used mostly for labelling telecommunications equipment.
  212. It encodes numeric digits.""",
  213. 'Code11',
  214. AttrMap(BASE=BarcodeI2of5,
  215. checksum = AttrMapValue(isInt,'''(integer, default 2):
  216. Whether to compute and include the check digit(s).
  217. (0 none, 1 1-digit, 2 2-digit, -1 auto, default -1):
  218. How many checksum digits to include. -1 ("auto") means
  219. 1 if the number of digits is 10 or less, else 2.'''),
  220. ),
  221. 'reportlab.graphics.barcode.common',
  222. "01234545634563",
  223. )
  224. BarcodeFIM=_BCW("""
  225. FIM was developed as part of the POSTNET barcoding system.
  226. FIM (Face Identification Marking) is used by the cancelling machines
  227. to sort mail according to whether or not they have bar code
  228. and their postage requirements. There are four types of FIM
  229. called FIM A, FIM B, FIM C, and FIM D.
  230. The four FIM types have the following meanings:
  231. FIM A- Postage required pre-barcoded
  232. FIM B - Postage pre-paid, no bar code exists
  233. FIM C- Postage prepaid prebarcoded
  234. FIM D- Postage required, no bar code exists""",
  235. "FIM",
  236. AttrMap(BASE=_BarcodeWidget,
  237. barWidth = AttrMapValue(isNumber,'''(float, default 1/32in): the bar width.'''),
  238. spaceWidth = AttrMapValue(isNumber,'''(float or None, default 1/16in):
  239. width of intercharacter gap. None means "use barWidth".'''),
  240. barHeight = AttrMapValue(isNumber,'''(float, default 5/8in): The bar height.'''),
  241. quiet = AttrMapValue(isBoolean,'''(bool, default 0):
  242. Whether to include quiet zones in the symbol.'''),
  243. lquiet = AttrMapValue(isNumber,'''(float, default: 15/32in):
  244. Quiet zone size to left of code, if quiet is true.'''),
  245. rquiet = AttrMapValue(isNumber,'''(float, default 1/4in):
  246. Quiet zone size to right left of code, if quiet is true.'''),
  247. fontName = AttrMapValue(isString, desc='human readable font'),
  248. fontSize = AttrMapValue(isNumber, desc='human readable font size'),
  249. humanReadable = AttrMapValue(isBoolean, desc='if human readable'),
  250. ),
  251. 'reportlab.graphics.barcode.usps',
  252. "A",
  253. )
  254. BarcodePOSTNET=_BCW('',
  255. "POSTNET",
  256. AttrMap(BASE=_BarcodeWidget,
  257. barWidth = AttrMapValue(isNumber,'''(float, default 0.018*in): the bar width.'''),
  258. spaceWidth = AttrMapValue(isNumber,'''(float or None, default 0.0275in): width of intercharacter gap.'''),
  259. shortHeight = AttrMapValue(isNumber,'''(float, default 0.05in): The short bar height.'''),
  260. barHeight = AttrMapValue(isNumber,'''(float, default 0.125in): The full bar height.'''),
  261. fontName = AttrMapValue(isString, desc='human readable font'),
  262. fontSize = AttrMapValue(isNumber, desc='human readable font size'),
  263. humanReadable = AttrMapValue(isBoolean, desc='if human readable'),
  264. ),
  265. 'reportlab.graphics.barcode.usps',
  266. "78247-1043",
  267. )
  268. BarcodeUSPS_4State=_BCW('',
  269. "USPS_4State",
  270. AttrMap(BASE=_BarcodeWidget,
  271. widthSize = AttrMapValue(isNumber,'''(float, default 1): the bar width size adjustment between 0 and 1.'''),
  272. heightSize = AttrMapValue(isNumber,'''(float, default 1): the bar height size adjustment between 0 and 1.'''),
  273. fontName = AttrMapValue(isString, desc='human readable font'),
  274. fontSize = AttrMapValue(isNumber, desc='human readable font size'),
  275. tracking = AttrMapValue(isString, desc='tracking data'),
  276. routing = AttrMapValue(isString, desc='routing data'),
  277. humanReadable = AttrMapValue(isBoolean, desc='if human readable'),
  278. barWidth = AttrMapValue(isNumber, desc='barWidth'),
  279. barHeight = AttrMapValue(isNumber, desc='barHeight'),
  280. pitch = AttrMapValue(isNumber, desc='pitch'),
  281. ),
  282. 'reportlab.graphics.barcode.usps4s',
  283. '01234567094987654321',
  284. _pre_init="\n\t\tkw.setdefault('routing','01234567891')\n",
  285. _methods = "\n\tdef annotate(self,x,y,text,fontName,fontSize,anchor='middle'):\n\t\t_BarcodeWidget.annotate(self,x,y,text,fontName,fontSize,anchor='start')\n"
  286. )
  287. BarcodeECC200DataMatrix = _BCW(
  288. 'ECC200DataMatrix',
  289. 'ECC200DataMatrix',
  290. AttrMap(BASE=_BarcodeWidget,
  291. x=AttrMapValue(isNumber, desc='X position of the lower-left corner of the barcode.'),
  292. y=AttrMapValue(isNumber, desc='Y position of the lower-left corner of the barcode.'),
  293. barWidth=AttrMapValue(isNumber, desc='Size of data modules.'),
  294. barFillColor=AttrMapValue(isColorOrNone, desc='Color of data modules.'),
  295. value=AttrMapValue(EitherOr((isString,isNumber)), desc='Value.'),
  296. height=AttrMapValue(None, desc='ignored'),
  297. width=AttrMapValue(None, desc='ignored'),
  298. strokeColor=AttrMapValue(None, desc='ignored'),
  299. strokeWidth=AttrMapValue(None, desc='ignored'),
  300. fillColor=AttrMapValue(None, desc='ignored'),
  301. background=AttrMapValue(None, desc='ignored'),
  302. debug=AttrMapValue(None, desc='ignored'),
  303. gap=AttrMapValue(None, desc='ignored'),
  304. row_modules=AttrMapValue(None, desc='???'),
  305. col_modules=AttrMapValue(None, desc='???'),
  306. row_regions=AttrMapValue(None, desc='???'),
  307. col_regions=AttrMapValue(None, desc='???'),
  308. cw_data=AttrMapValue(None, desc='???'),
  309. cw_ecc=AttrMapValue(None, desc='???'),
  310. row_usable_modules = AttrMapValue(None, desc='???'),
  311. col_usable_modules = AttrMapValue(None, desc='???'),
  312. valid = AttrMapValue(None, desc='???'),
  313. validated = AttrMapValue(None, desc='???'),
  314. decomposed = AttrMapValue(None, desc='???'),
  315. ),
  316. 'reportlab.graphics.barcode.ecc200datamatrix',
  317. 'JGB 0204H20B012722900021AC35B2100001003241014241014TPS01 WJ067073605GB185 MOUNT PLEASANT MAIL CENTER EC1A1BB9ZGBREC1A1BB EC1A1BB STEST FILE FOR SPEC '
  318. )
  319. if __name__=='__main__':
  320. raise ValueError('widgets.py has no script function')