common.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. #
  2. # Copyright (c) 1996-2000 Tyler C. Sarna <tsarna@sarna.org>
  3. # All rights reserved.
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions
  7. # are met:
  8. # 1. Redistributions of source code must retain the above copyright
  9. # notice, this list of conditions and the following disclaimer.
  10. # 2. Redistributions in binary form must reproduce the above copyright
  11. # notice, this list of conditions and the following disclaimer in the
  12. # documentation and/or other materials provided with the distribution.
  13. # 3. All advertising materials mentioning features or use of this software
  14. # must display the following acknowledgement:
  15. # This product includes software developed by Tyler C. Sarna.
  16. # 4. Neither the name of the author nor the names of contributors
  17. # may be used to endorse or promote products derived from this software
  18. # without specific prior written permission.
  19. #
  20. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  21. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  23. # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
  24. # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  25. # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  26. # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  27. # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  28. # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  29. # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  30. # POSSIBILITY OF SUCH DAMAGE.
  31. #
  32. from reportlab.platypus.flowables import Flowable
  33. from reportlab.lib.units import inch
  34. from reportlab.lib.utils import ascii_uppercase, ascii_lowercase
  35. from string import digits as string_digits
  36. class Barcode(Flowable,object):
  37. """Abstract Base for barcodes. Includes implementations of
  38. some methods suitable for the more primitive barcode types"""
  39. fontName = 'Courier'
  40. fontSize = 12
  41. humanReadable = 0
  42. def _humanText(self):
  43. return self.encoded
  44. def __init__(self, value='',**kwd):
  45. self.value = str(value)
  46. self._setKeywords(**kwd)
  47. if not hasattr(self, 'gap'):
  48. self.gap = None
  49. def _calculate(self):
  50. self.validate()
  51. self.encode()
  52. self.decompose()
  53. self.computeSize()
  54. def _setKeywords(self,**kwd):
  55. for (k, v) in kwd.items():
  56. setattr(self, k, v)
  57. def validate(self):
  58. self.valid = 1
  59. self.validated = self.value
  60. def encode(self):
  61. self.encoded = self.validated
  62. def decompose(self):
  63. self.decomposed = self.encoded
  64. def computeSize(self, *args):
  65. barWidth = self.barWidth
  66. wx = barWidth * self.ratio
  67. if self.gap == None:
  68. self.gap = barWidth
  69. w = 0.0
  70. for c in self.decomposed:
  71. if c in 'sb':
  72. w = w + barWidth
  73. elif c in 'SB':
  74. w = w + wx
  75. else: # 'i'
  76. w = w + self.gap
  77. if self.barHeight is None:
  78. self.barHeight = w * 0.15
  79. self.barHeight = max(0.25 * inch, self.barHeight)
  80. if self.bearers:
  81. self.barHeight = self.barHeight + self.bearers * 2.0 * barWidth
  82. if self.quiet:
  83. w += self.lquiet + self.rquiet
  84. self._height = self.barHeight
  85. self._width = w
  86. def width(self):
  87. self._calculate()
  88. return self._width
  89. width = property(width)
  90. def height(self):
  91. self._calculate()
  92. return self._height
  93. height = property(height)
  94. def draw(self):
  95. self._calculate()
  96. barWidth = self.barWidth
  97. wx = barWidth * self.ratio
  98. left = self.quiet and self.lquiet or 0
  99. b = self.bearers * barWidth
  100. bb = b * 0.5
  101. tb = self.barHeight - (b * 1.5)
  102. for c in self.decomposed:
  103. if c == 'i':
  104. left = left + self.gap
  105. elif c == 's':
  106. left = left + barWidth
  107. elif c == 'S':
  108. left = left + wx
  109. elif c == 'b':
  110. self.rect(left, bb, barWidth, tb)
  111. left = left + barWidth
  112. elif c == 'B':
  113. self.rect(left, bb, wx, tb)
  114. left = left + wx
  115. if self.bearers:
  116. self.rect(self.lquiet, 0, \
  117. self._width - (self.lquiet + self.rquiet), b)
  118. self.rect(self.lquiet, self.barHeight - b, \
  119. self._width - (self.lquiet + self.rquiet), b)
  120. self.drawHumanReadable()
  121. def drawHumanReadable(self):
  122. if self.humanReadable:
  123. #we have text
  124. from reportlab.pdfbase.pdfmetrics import getAscent, stringWidth
  125. s = str(self._humanText())
  126. fontSize = self.fontSize
  127. fontName = self.fontName
  128. w = stringWidth(s,fontName,fontSize)
  129. width = self._width
  130. if self.quiet:
  131. width -= self.lquiet+self.rquiet
  132. x = self.lquiet
  133. else:
  134. x = 0
  135. if w>width: fontSize *= width/float(w)
  136. y = 1.07*getAscent(fontName)*fontSize/1000.
  137. self.annotate(x+width/2.,-y,s,fontName,fontSize)
  138. def rect(self, x, y, w, h):
  139. self.canv.rect(x, y, w, h, stroke=0, fill=1)
  140. def annotate(self,x,y,text,fontName,fontSize,anchor='middle'):
  141. canv = self.canv
  142. canv.saveState()
  143. canv.setFont(self.fontName,fontSize)
  144. if anchor=='middle': func = 'drawCentredString'
  145. elif anchor=='end': func = 'drawRightString'
  146. else: func = 'drawString'
  147. getattr(canv,func)(x,y,text)
  148. canv.restoreState()
  149. def _checkVal(self, name, v, allowed):
  150. if v not in allowed:
  151. raise ValueError('%s attribute %s is invalid %r\nnot in allowed %r' % (
  152. self.__class__.__name__, name, v, allowed))
  153. return v
  154. class MultiWidthBarcode(Barcode):
  155. """Base for variable-bar-width codes like Code93 and Code128"""
  156. def computeSize(self, *args):
  157. barWidth = self.barWidth
  158. oa, oA = ord('a') - 1, ord('A') - 1
  159. w = 0.0
  160. for c in self.decomposed:
  161. oc = ord(c)
  162. if c in ascii_lowercase:
  163. w = w + barWidth * (oc - oa)
  164. elif c in ascii_uppercase:
  165. w = w + barWidth * (oc - oA)
  166. if self.barHeight is None:
  167. self.barHeight = w * 0.15
  168. self.barHeight = max(0.25 * inch, self.barHeight)
  169. if self.quiet:
  170. w += self.lquiet + self.rquiet
  171. self._height = self.barHeight
  172. self._width = w
  173. def draw(self):
  174. self._calculate()
  175. oa, oA = ord('a') - 1, ord('A') - 1
  176. barWidth = self.barWidth
  177. left = self.quiet and self.lquiet or 0
  178. for c in self.decomposed:
  179. oc = ord(c)
  180. if c in ascii_lowercase:
  181. left = left + (oc - oa) * barWidth
  182. elif c in ascii_uppercase:
  183. w = (oc - oA) * barWidth
  184. self.rect(left, 0, w, self.barHeight)
  185. left += w
  186. self.drawHumanReadable()
  187. class I2of5(Barcode):
  188. """
  189. Interleaved 2 of 5 is a numeric-only barcode. It encodes an even
  190. number of digits; if an odd number is given, a 0 is prepended.
  191. Options that may be passed to constructor:
  192. value (int, or numeric string required.):
  193. The value to encode.
  194. barWidth (float, default .0075):
  195. X-Dimension, or width of the smallest element
  196. Minumum is .0075 inch (7.5 mils).
  197. ratio (float, default 2.2):
  198. The ratio of wide elements to narrow elements.
  199. Must be between 2.0 and 3.0 (or 2.2 and 3.0 if the
  200. barWidth is greater than 20 mils (.02 inch))
  201. gap (float or None, default None):
  202. width of intercharacter gap. None means "use barWidth".
  203. barHeight (float, see default below):
  204. Height of the symbol. Default is the height of the two
  205. bearer bars (if they exist) plus the greater of .25 inch
  206. or .15 times the symbol's length.
  207. checksum (bool, default 1):
  208. Whether to compute and include the check digit
  209. bearers (float, in units of barWidth. default 3.0):
  210. Height of bearer bars (horizontal bars along the top and
  211. bottom of the barcode). Default is 3 x-dimensions.
  212. Set to zero for no bearer bars. (Bearer bars help detect
  213. misscans, so it is suggested to leave them on).
  214. quiet (bool, default 1):
  215. Whether to include quiet zones in the symbol.
  216. lquiet (float, see default below):
  217. Quiet zone size to left of code, if quiet is true.
  218. Default is the greater of .25 inch, or .15 times the symbol's
  219. length.
  220. rquiet (float, defaults as above):
  221. Quiet zone size to right left of code, if quiet is true.
  222. stop (bool, default 1):
  223. Whether to include start/stop symbols.
  224. Sources of Information on Interleaved 2 of 5:
  225. http://www.semiconductor.agilent.com/barcode/sg/Misc/i_25.html
  226. http://www.adams1.com/pub/russadam/i25code.html
  227. Official Spec, "ANSI/AIM BC2-1995, USS" is available for US$45 from
  228. http://www.aimglobal.org/aimstore/
  229. """
  230. patterns = {
  231. 'start' : 'bsbs',
  232. 'stop' : 'Bsb',
  233. 'B0' : 'bbBBb', 'S0' : 'ssSSs',
  234. 'B1' : 'BbbbB', 'S1' : 'SsssS',
  235. 'B2' : 'bBbbB', 'S2' : 'sSssS',
  236. 'B3' : 'BBbbb', 'S3' : 'SSsss',
  237. 'B4' : 'bbBbB', 'S4' : 'ssSsS',
  238. 'B5' : 'BbBbb', 'S5' : 'SsSss',
  239. 'B6' : 'bBBbb', 'S6' : 'sSSss',
  240. 'B7' : 'bbbBB', 'S7' : 'sssSS',
  241. 'B8' : 'BbbBb', 'S8' : 'SssSs',
  242. 'B9' : 'bBbBb', 'S9' : 'sSsSs'
  243. }
  244. barHeight = None
  245. barWidth = inch * 0.0075
  246. ratio = 2.2
  247. checksum = 1
  248. bearers = 3.0
  249. quiet = 1
  250. lquiet = None
  251. rquiet = None
  252. stop = 1
  253. def __init__(self, value='', **args):
  254. if type(value) == type(1):
  255. value = str(value)
  256. for k, v in args.items():
  257. setattr(self, k, v)
  258. if self.quiet:
  259. if self.lquiet is None:
  260. self.lquiet = min(inch * 0.25, self.barWidth * 10.0)
  261. self.rquiet = min(inch * 0.25, self.barWidth * 10.0)
  262. else:
  263. self.lquiet = self.rquiet = 0.0
  264. Barcode.__init__(self, value)
  265. def validate(self):
  266. vval = ""
  267. self.valid = 1
  268. for c in self.value.strip():
  269. if c not in string_digits:
  270. self.valid = 0
  271. continue
  272. vval = vval + c
  273. self.validated = vval
  274. return vval
  275. def encode(self):
  276. s = self.validated
  277. cs = self.checksum
  278. c = len(s)
  279. #ensure len(result)%2 == 0, checksum included
  280. if ((c % 2 == 0) and cs) or ((c % 2 == 1) and not cs):
  281. s = '0' + s
  282. c += 1
  283. if cs:
  284. c = 3*sum([int(s[i]) for i in range(0,c,2)])+sum([int(s[i]) for i in range(1,c,2)])
  285. s += str((10 - c) % 10)
  286. self.encoded = s
  287. def decompose(self):
  288. dval = self.stop and [self.patterns['start']] or []
  289. a = dval.append
  290. for i in range(0, len(self.encoded), 2):
  291. b = self.patterns['B' + self.encoded[i]]
  292. s = self.patterns['S' + self.encoded[i+1]]
  293. for i in range(0, len(b)):
  294. a(b[i] + s[i])
  295. if self.stop: a(self.patterns['stop'])
  296. self.decomposed = ''.join(dval)
  297. return self.decomposed
  298. class MSI(Barcode):
  299. """
  300. MSI is a numeric-only barcode.
  301. Options that may be passed to constructor:
  302. value (int, or numeric string required.):
  303. The value to encode.
  304. barWidth (float, default .0075):
  305. X-Dimension, or width of the smallest element
  306. ratio (float, default 2.2):
  307. The ratio of wide elements to narrow elements.
  308. gap (float or None, default None):
  309. width of intercharacter gap. None means "use barWidth".
  310. barHeight (float, see default below):
  311. Height of the symbol. Default is the height of the two
  312. bearer bars (if they exist) plus the greater of .25 inch
  313. or .15 times the symbol's length.
  314. checksum (bool, default 1):
  315. Wether to compute and include the check digit
  316. bearers (float, in units of barWidth. default 0):
  317. Height of bearer bars (horizontal bars along the top and
  318. bottom of the barcode). Default is 0 (no bearers).
  319. lquiet (float, see default below):
  320. Quiet zone size to left of code, if quiet is true.
  321. Default is the greater of .25 inch, or 10 barWidths.
  322. rquiet (float, defaults as above):
  323. Quiet zone size to right left of code, if quiet is true.
  324. stop (bool, default 1):
  325. Whether to include start/stop symbols.
  326. Sources of Information on MSI Bar Code:
  327. http://www.semiconductor.agilent.com/barcode/sg/Misc/msi_code.html
  328. http://www.adams1.com/pub/russadam/plessy.html
  329. """
  330. patterns = {
  331. 'start' : 'Bs', 'stop' : 'bSb',
  332. '0' : 'bSbSbSbS', '1' : 'bSbSbSBs',
  333. '2' : 'bSbSBsbS', '3' : 'bSbSBsBs',
  334. '4' : 'bSBsbSbS', '5' : 'bSBsbSBs',
  335. '6' : 'bSBsBsbS', '7' : 'bSBsBsBs',
  336. '8' : 'BsbSbSbS', '9' : 'BsbSbSBs'
  337. }
  338. stop = 1
  339. barHeight = None
  340. barWidth = inch * 0.0075
  341. ratio = 2.2
  342. checksum = 1
  343. bearers = 0.0
  344. quiet = 1
  345. lquiet = None
  346. rquiet = None
  347. def __init__(self, value="", **args):
  348. if type(value) == type(1):
  349. value = str(value)
  350. for k, v in args.items():
  351. setattr(self, k, v)
  352. if self.quiet:
  353. if self.lquiet is None:
  354. self.lquiet = max(inch * 0.25, self.barWidth * 10.0)
  355. self.rquiet = max(inch * 0.25, self.barWidth * 10.0)
  356. else:
  357. self.lquiet = self.rquiet = 0.0
  358. Barcode.__init__(self, value)
  359. def validate(self):
  360. vval = ""
  361. self.valid = 1
  362. for c in self.value.strip():
  363. if c not in string_digits:
  364. self.valid = 0
  365. continue
  366. vval = vval + c
  367. self.validated = vval
  368. return vval
  369. def encode(self):
  370. s = self.validated
  371. if self.checksum:
  372. c = ''
  373. for i in range(1, len(s), 2):
  374. c = c + s[i]
  375. d = str(int(c) * 2)
  376. t = 0
  377. for c in d:
  378. t = t + int(c)
  379. for i in range(0, len(s), 2):
  380. t = t + int(s[i])
  381. c = 10 - (t % 10)
  382. s = s + str(c)
  383. self.encoded = s
  384. def decompose(self):
  385. dval = self.stop and [self.patterns['start']] or []
  386. dval += [self.patterns[c] for c in self.encoded]
  387. if self.stop: dval.append(self.patterns['stop'])
  388. self.decomposed = ''.join(dval)
  389. return self.decomposed
  390. class Codabar(Barcode):
  391. """
  392. Codabar is a numeric plus some puntuation ("-$:/.+") barcode
  393. with four start/stop characters (A, B, C, and D).
  394. Options that may be passed to constructor:
  395. value (string required.):
  396. The value to encode.
  397. barWidth (float, default .0065):
  398. X-Dimension, or width of the smallest element
  399. minimum is 6.5 mils (.0065 inch)
  400. ratio (float, default 2.0):
  401. The ratio of wide elements to narrow elements.
  402. gap (float or None, default None):
  403. width of intercharacter gap. None means "use barWidth".
  404. barHeight (float, see default below):
  405. Height of the symbol. Default is the height of the two
  406. bearer bars (if they exist) plus the greater of .25 inch
  407. or .15 times the symbol's length.
  408. checksum (bool, default 0):
  409. Whether to compute and include the check digit
  410. bearers (float, in units of barWidth. default 0):
  411. Height of bearer bars (horizontal bars along the top and
  412. bottom of the barcode). Default is 0 (no bearers).
  413. quiet (bool, default 1):
  414. Whether to include quiet zones in the symbol.
  415. stop (bool, default 1):
  416. Whether to include start/stop symbols.
  417. lquiet (float, see default below):
  418. Quiet zone size to left of code, if quiet is true.
  419. Default is the greater of .25 inch, or 10 barWidth
  420. rquiet (float, defaults as above):
  421. Quiet zone size to right left of code, if quiet is true.
  422. Sources of Information on Codabar
  423. http://www.semiconductor.agilent.com/barcode/sg/Misc/codabar.html
  424. http://www.barcodeman.com/codabar.html
  425. Official Spec, "ANSI/AIM BC3-1995, USS" is available for US$45 from
  426. http://www.aimglobal.org/aimstore/
  427. """
  428. patterns = {
  429. '0': 'bsbsbSB', '1': 'bsbsBSb', '2': 'bsbSbsB',
  430. '3': 'BSbsbsb', '4': 'bsBsbSb', '5': 'BsbsbSb',
  431. '6': 'bSbsbsB', '7': 'bSbsBsb', '8': 'bSBsbsb',
  432. '9': 'BsbSbsb', '-': 'bsbSBsb', '$': 'bsBSbsb',
  433. ':': 'BsbsBsB', '/': 'BsBsbsB', '.': 'BsBsBsb',
  434. '+': 'bsBsBsB', 'A': 'bsBSbSb', 'B': 'bSbSbsB',
  435. 'C': 'bsbSbSB', 'D': 'bsbSBSb'
  436. }
  437. values = {
  438. '0' : 0, '1' : 1, '2' : 2, '3' : 3, '4' : 4,
  439. '5' : 5, '6' : 6, '7' : 7, '8' : 8, '9' : 9,
  440. '-' : 10, '$' : 11, ':' : 12, '/' : 13, '.' : 14,
  441. '+' : 15, 'A' : 16, 'B' : 17, 'C' : 18, 'D' : 19
  442. }
  443. chars = string_digits + "-$:/.+"
  444. stop = 1
  445. barHeight = None
  446. barWidth = inch * 0.0065
  447. ratio = 2.0 # XXX ?
  448. checksum = 0
  449. bearers = 0.0
  450. quiet = 1
  451. lquiet = None
  452. rquiet = None
  453. def __init__(self, value='', **args):
  454. if type(value) == type(1):
  455. value = str(value)
  456. for k, v in args.items():
  457. setattr(self, k, v)
  458. if self.quiet:
  459. if self.lquiet is None:
  460. self.lquiet = min(inch * 0.25, self.barWidth * 10.0)
  461. self.rquiet = min(inch * 0.25, self.barWidth * 10.0)
  462. else:
  463. self.lquiet = self.rquiet = 0.0
  464. Barcode.__init__(self, value)
  465. def validate(self):
  466. vval = ""
  467. self.valid = 1
  468. s = self.value.strip()
  469. for i in range(0, len(s)):
  470. c = s[i]
  471. if c not in self.chars:
  472. if ((i != 0) and (i != len(s) - 1)) or (c not in 'ABCD'):
  473. self.Valid = 0
  474. continue
  475. vval = vval + c
  476. if self.stop:
  477. if vval[0] not in 'ABCD':
  478. vval = 'A' + vval
  479. if vval[-1] not in 'ABCD':
  480. vval = vval + vval[0]
  481. self.validated = vval
  482. return vval
  483. def encode(self):
  484. s = self.validated
  485. if self.checksum:
  486. v = sum([self.values[c] for c in s])
  487. s += self.chars[v % 16]
  488. self.encoded = s
  489. def decompose(self):
  490. dval = ''.join([self.patterns[c]+'i' for c in self.encoded])
  491. self.decomposed = dval[:-1]
  492. return self.decomposed
  493. class Code11(Barcode):
  494. """
  495. Code 11 is an almost-numeric barcode. It encodes the digits 0-9 plus
  496. dash ("-"). 11 characters total, hence the name.
  497. value (int or string required.):
  498. The value to encode.
  499. barWidth (float, default .0075):
  500. X-Dimension, or width of the smallest element
  501. ratio (float, default 2.2):
  502. The ratio of wide elements to narrow elements.
  503. gap (float or None, default None):
  504. width of intercharacter gap. None means "use barWidth".
  505. barHeight (float, see default below):
  506. Height of the symbol. Default is the height of the two
  507. bearer bars (if they exist) plus the greater of .25 inch
  508. or .15 times the symbol's length.
  509. checksum (0 none, 1 1-digit, 2 2-digit, -1 auto, default -1):
  510. How many checksum digits to include. -1 ("auto") means
  511. 1 if the number of digits is 10 or less, else 2.
  512. bearers (float, in units of barWidth. default 0):
  513. Height of bearer bars (horizontal bars along the top and
  514. bottom of the barcode). Default is 0 (no bearers).
  515. quiet (bool, default 1):
  516. Wether to include quiet zones in the symbol.
  517. lquiet (float, see default below):
  518. Quiet zone size to left of code, if quiet is true.
  519. Default is the greater of .25 inch, or 10 barWidth
  520. rquiet (float, defaults as above):
  521. Quiet zone size to right left of code, if quiet is true.
  522. Sources of Information on Code 11:
  523. http://www.cwi.nl/people/dik/english/codes/barcodes.html
  524. """
  525. chars = '0123456789-'
  526. patterns = {
  527. '0' : 'bsbsB', '1' : 'BsbsB', '2' : 'bSbsB',
  528. '3' : 'BSbsb', '4' : 'bsBsB', '5' : 'BsBsb',
  529. '6' : 'bSBsb', '7' : 'bsbSB', '8' : 'BsbSb',
  530. '9' : 'Bsbsb', '-' : 'bsBsb', 'S' : 'bsBSb' # Start/Stop
  531. }
  532. values = {
  533. '0' : 0, '1' : 1, '2' : 2, '3' : 3, '4' : 4,
  534. '5' : 5, '6' : 6, '7' : 7, '8' : 8, '9' : 9,
  535. '-' : 10,
  536. }
  537. stop = 1
  538. barHeight = None
  539. barWidth = inch * 0.0075
  540. ratio = 2.2 # XXX ?
  541. checksum = -1 # Auto
  542. bearers = 0.0
  543. quiet = 1
  544. lquiet = None
  545. rquiet = None
  546. def __init__(self, value='', **args):
  547. if type(value) == type(1):
  548. value = str(value)
  549. for k, v in args.items():
  550. setattr(self, k, v)
  551. if self.quiet:
  552. if self.lquiet is None:
  553. self.lquiet = min(inch * 0.25, self.barWidth * 10.0)
  554. self.rquiet = min(inch * 0.25, self.barWidth * 10.0)
  555. else:
  556. self.lquiet = self.rquiet = 0.0
  557. Barcode.__init__(self, value)
  558. def validate(self):
  559. vval = ""
  560. self.valid = 1
  561. s = self.value.strip()
  562. for i in range(0, len(s)):
  563. c = s[i]
  564. if c not in self.chars:
  565. self.Valid = 0
  566. continue
  567. vval = vval + c
  568. self.validated = vval
  569. return vval
  570. def _addCSD(self,s,m):
  571. # compute first checksum
  572. i = c = 0
  573. v = 1
  574. V = self.values
  575. while i < len(s):
  576. c += v * V[s[-(i+1)]]
  577. i += 1
  578. v += 1
  579. if v==m:
  580. v = 1
  581. return s+self.chars[c % 11]
  582. def encode(self):
  583. s = self.validated
  584. tcs = self.checksum
  585. if tcs<0:
  586. self.checksum = tcs = 1+int(len(s)>10)
  587. if tcs > 0: s = self._addCSD(s,11)
  588. if tcs > 1: s = self._addCSD(s,10)
  589. self.encoded = self.stop and ('S' + s + 'S') or s
  590. def decompose(self):
  591. self.decomposed = ''.join([(self.patterns[c]+'i') for c in self.encoded])[:-1]
  592. return self.decomposed
  593. def _humanText(self):
  594. return self.stop and self.encoded[1:-1] or self.encoded