code128.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. #
  2. # Copyright (c) 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.lib.units import inch
  33. from reportlab.lib.utils import asNative
  34. from reportlab.graphics.barcode.common import MultiWidthBarcode
  35. from string import digits
  36. _patterns = {
  37. 0 : 'BaBbBb', 1 : 'BbBaBb', 2 : 'BbBbBa',
  38. 3 : 'AbAbBc', 4 : 'AbAcBb', 5 : 'AcAbBb',
  39. 6 : 'AbBbAc', 7 : 'AbBcAb', 8 : 'AcBbAb',
  40. 9 : 'BbAbAc', 10 : 'BbAcAb', 11 : 'BcAbAb',
  41. 12 : 'AaBbCb', 13 : 'AbBaCb', 14 : 'AbBbCa',
  42. 15 : 'AaCbBb', 16 : 'AbCaBb', 17 : 'AbCbBa',
  43. 18 : 'BbCbAa', 19 : 'BbAaCb', 20 : 'BbAbCa',
  44. 21 : 'BaCbAb', 22 : 'BbCaAb', 23 : 'CaBaCa',
  45. 24 : 'CaAbBb', 25 : 'CbAaBb', 26 : 'CbAbBa',
  46. 27 : 'CaBbAb', 28 : 'CbBaAb', 29 : 'CbBbAa',
  47. 30 : 'BaBaBc', 31 : 'BaBcBa', 32 : 'BcBaBa',
  48. 33 : 'AaAcBc', 34 : 'AcAaBc', 35 : 'AcAcBa',
  49. 36 : 'AaBcAc', 37 : 'AcBaAc', 38 : 'AcBcAa',
  50. 39 : 'BaAcAc', 40 : 'BcAaAc', 41 : 'BcAcAa',
  51. 42 : 'AaBaCc', 43 : 'AaBcCa', 44 : 'AcBaCa',
  52. 45 : 'AaCaBc', 46 : 'AaCcBa', 47 : 'AcCaBa',
  53. 48 : 'CaCaBa', 49 : 'BaAcCa', 50 : 'BcAaCa',
  54. 51 : 'BaCaAc', 52 : 'BaCcAa', 53 : 'BaCaCa',
  55. 54 : 'CaAaBc', 55 : 'CaAcBa', 56 : 'CcAaBa',
  56. 57 : 'CaBaAc', 58 : 'CaBcAa', 59 : 'CcBaAa',
  57. 60 : 'CaDaAa', 61 : 'BbAdAa', 62 : 'DcAaAa',
  58. 63 : 'AaAbBd', 64 : 'AaAdBb', 65 : 'AbAaBd',
  59. 66 : 'AbAdBa', 67 : 'AdAaBb', 68 : 'AdAbBa',
  60. 69 : 'AaBbAd', 70 : 'AaBdAb', 71 : 'AbBaAd',
  61. 72 : 'AbBdAa', 73 : 'AdBaAb', 74 : 'AdBbAa',
  62. 75 : 'BdAbAa', 76 : 'BbAaAd', 77 : 'DaCaAa',
  63. 78 : 'BdAaAb', 79 : 'AcDaAa', 80 : 'AaAbDb',
  64. 81 : 'AbAaDb', 82 : 'AbAbDa', 83 : 'AaDbAb',
  65. 84 : 'AbDaAb', 85 : 'AbDbAa', 86 : 'DaAbAb',
  66. 87 : 'DbAaAb', 88 : 'DbAbAa', 89 : 'BaBaDa',
  67. 90 : 'BaDaBa', 91 : 'DaBaBa', 92 : 'AaAaDc',
  68. 93 : 'AaAcDa', 94 : 'AcAaDa', 95 : 'AaDaAc',
  69. 96 : 'AaDcAa', 97 : 'DaAaAc', 98 : 'DaAcAa',
  70. 99 : 'AaCaDa', 100 : 'AaDaCa', 101 : 'CaAaDa',
  71. 102 : 'DaAaCa', 103 : 'BaAdAb', 104 : 'BaAbAd',
  72. 105 : 'BaAbCb', 106 : 'BcCaAaB'
  73. }
  74. starta, startb, startc, stop = 103, 104, 105, 106
  75. seta = {
  76. ' ' : 0, '!' : 1, '"' : 2, '#' : 3,
  77. '$' : 4, '%' : 5, '&' : 6, '\'' : 7,
  78. '(' : 8, ')' : 9, '*' : 10, '+' : 11,
  79. ',' : 12, '-' : 13, '.' : 14, '/' : 15,
  80. '0' : 16, '1' : 17, '2' : 18, '3' : 19,
  81. '4' : 20, '5' : 21, '6' : 22, '7' : 23,
  82. '8' : 24, '9' : 25, ':' : 26, ';' : 27,
  83. '<' : 28, '=' : 29, '>' : 30, '?' : 31,
  84. '@' : 32, 'A' : 33, 'B' : 34, 'C' : 35,
  85. 'D' : 36, 'E' : 37, 'F' : 38, 'G' : 39,
  86. 'H' : 40, 'I' : 41, 'J' : 42, 'K' : 43,
  87. 'L' : 44, 'M' : 45, 'N' : 46, 'O' : 47,
  88. 'P' : 48, 'Q' : 49, 'R' : 50, 'S' : 51,
  89. 'T' : 52, 'U' : 53, 'V' : 54, 'W' : 55,
  90. 'X' : 56, 'Y' : 57, 'Z' : 58, '[' : 59,
  91. '\\' : 60, ']' : 61, '^' : 62, '_' : 63,
  92. '\x00' : 64, '\x01' : 65, '\x02' : 66, '\x03' : 67,
  93. '\x04' : 68, '\x05' : 69, '\x06' : 70, '\x07' : 71,
  94. '\x08' : 72, '\x09' : 73, '\x0a' : 74, '\x0b' : 75,
  95. '\x0c' : 76, '\x0d' : 77, '\x0e' : 78, '\x0f' : 79,
  96. '\x10' : 80, '\x11' : 81, '\x12' : 82, '\x13' : 83,
  97. '\x14' : 84, '\x15' : 85, '\x16' : 86, '\x17' : 87,
  98. '\x18' : 88, '\x19' : 89, '\x1a' : 90, '\x1b' : 91,
  99. '\x1c' : 92, '\x1d' : 93, '\x1e' : 94, '\x1f' : 95,
  100. '\xf3' : 96, '\xf2' : 97, 'SHIFT' : 98, 'TO_C' : 99,
  101. 'TO_B' : 100, '\xf4' : 101, '\xf1' : 102
  102. }
  103. setb = {
  104. ' ' : 0, '!' : 1, '"' : 2, '#' : 3,
  105. '$' : 4, '%' : 5, '&' : 6, '\'' : 7,
  106. '(' : 8, ')' : 9, '*' : 10, '+' : 11,
  107. ',' : 12, '-' : 13, '.' : 14, '/' : 15,
  108. '0' : 16, '1' : 17, '2' : 18, '3' : 19,
  109. '4' : 20, '5' : 21, '6' : 22, '7' : 23,
  110. '8' : 24, '9' : 25, ':' : 26, ';' : 27,
  111. '<' : 28, '=' : 29, '>' : 30, '?' : 31,
  112. '@' : 32, 'A' : 33, 'B' : 34, 'C' : 35,
  113. 'D' : 36, 'E' : 37, 'F' : 38, 'G' : 39,
  114. 'H' : 40, 'I' : 41, 'J' : 42, 'K' : 43,
  115. 'L' : 44, 'M' : 45, 'N' : 46, 'O' : 47,
  116. 'P' : 48, 'Q' : 49, 'R' : 50, 'S' : 51,
  117. 'T' : 52, 'U' : 53, 'V' : 54, 'W' : 55,
  118. 'X' : 56, 'Y' : 57, 'Z' : 58, '[' : 59,
  119. '\\' : 60, ']' : 61, '^' : 62, '_' : 63,
  120. '`' : 64, 'a' : 65, 'b' : 66, 'c' : 67,
  121. 'd' : 68, 'e' : 69, 'f' : 70, 'g' : 71,
  122. 'h' : 72, 'i' : 73, 'j' : 74, 'k' : 75,
  123. 'l' : 76, 'm' : 77, 'n' : 78, 'o' : 79,
  124. 'p' : 80, 'q' : 81, 'r' : 82, 's' : 83,
  125. 't' : 84, 'u' : 85, 'v' : 86, 'w' : 87,
  126. 'x' : 88, 'y' : 89, 'z' : 90, '{' : 91,
  127. '|' : 92, '}' : 93, '~' : 94, '\x7f' : 95,
  128. '\xf3' : 96, '\xf2' : 97, 'SHIFT' : 98, 'TO_C' : 99,
  129. '\xf4' : 100, 'TO_A' : 101, '\xf1' : 102
  130. }
  131. setc = {
  132. '00': 0, '01': 1, '02': 2, '03': 3, '04': 4,
  133. '05': 5, '06': 6, '07': 7, '08': 8, '09': 9,
  134. '10':10, '11':11, '12':12, '13':13, '14':14,
  135. '15':15, '16':16, '17':17, '18':18, '19':19,
  136. '20':20, '21':21, '22':22, '23':23, '24':24,
  137. '25':25, '26':26, '27':27, '28':28, '29':29,
  138. '30':30, '31':31, '32':32, '33':33, '34':34,
  139. '35':35, '36':36, '37':37, '38':38, '39':39,
  140. '40':40, '41':41, '42':42, '43':43, '44':44,
  141. '45':45, '46':46, '47':47, '48':48, '49':49,
  142. '50':50, '51':51, '52':52, '53':53, '54':54,
  143. '55':55, '56':56, '57':57, '58':58, '59':59,
  144. '60':60, '61':61, '62':62, '63':63, '64':64,
  145. '65':65, '66':66, '67':67, '68':68, '69':69,
  146. '70':70, '71':71, '72':72, '73':73, '74':74,
  147. '75':75, '76':76, '77':77, '78':78, '79':79,
  148. '80':80, '81':81, '82':82, '83':83, '84':84,
  149. '85':85, '86':86, '87':87, '88':88, '89':89,
  150. '90':90, '91':91, '92':92, '93':93, '94':94,
  151. '95':95, '96':96, '97':97, '98':98, '99':99,
  152. 'TO_B' : 100, 'TO_A' : 101, '\xf1' : 102
  153. }
  154. setmap = {
  155. 'TO_A' : (seta, setb),
  156. 'TO_B' : (setb, seta),
  157. 'TO_C' : (setc, None),
  158. 'START_A' : (starta, seta, setb),
  159. 'START_B' : (startb, setb, seta),
  160. 'START_C' : (startc, setc, None),
  161. }
  162. cStarts = ('START_B','TO_A','TO_B')
  163. tos = list(setmap.keys())
  164. class Code128(MultiWidthBarcode):
  165. """
  166. Code 128 is a very compact symbology that can encode the entire
  167. 128 character ASCII set, plus 4 special control codes,
  168. (FNC1-FNC4, expressed in the input string as \xf1 to \xf4).
  169. Code 128 can also encode digits at double density (2 per byte)
  170. and has a mandatory checksum. Code 128 is well supported and
  171. commonly used -- for example, by UPS for tracking labels.
  172. Because of these qualities, Code 128 is probably the best choice
  173. for a linear symbology today (assuming you have a choice).
  174. Options that may be passed to constructor:
  175. value (int, or numeric string. required.):
  176. The value to encode.
  177. barWidth (float, default .0075):
  178. X-Dimension, or width of the smallest element
  179. Minumum is .0075 inch (7.5 mils).
  180. barHeight (float, see default below):
  181. Height of the symbol. Default is the height of the two
  182. bearer bars (if they exist) plus the greater of .25 inch
  183. or .15 times the symbol's length.
  184. quiet (bool, default 1):
  185. Wether to include quiet zones in the symbol.
  186. lquiet (float, see default below):
  187. Quiet zone size to left of code, if quiet is true.
  188. Default is the greater of .25 inch, or 10 barWidth
  189. rquiet (float, defaults as above):
  190. Quiet zone size to right left of code, if quiet is true.
  191. Sources of Information on Code 128:
  192. http://www.semiconductor.agilent.com/barcode/sg/Misc/code_128.html
  193. http://www.adams1.com/pub/russadam/128code.html
  194. http://www.barcodeman.com/c128.html
  195. Official Spec, "ANSI/AIM BC4-1999, ISS" is available for US$45 from
  196. http://www.aimglobal.org/aimstore/
  197. """
  198. barWidth = inch * 0.0075
  199. lquiet = None
  200. rquiet = None
  201. quiet = 1
  202. barHeight = None
  203. def __init__(self, value='', **args):
  204. value = str(value) if isinstance(value,int) else asNative(value)
  205. for k, v in args.items():
  206. setattr(self, k, v)
  207. if self.quiet:
  208. if self.lquiet is None:
  209. self.lquiet = max(inch * 0.25, self.barWidth * 10.0)
  210. if self.rquiet is None:
  211. self.rquiet = max(inch * 0.25, self.barWidth * 10.0)
  212. else:
  213. self.lquiet = self.rquiet = 0.0
  214. MultiWidthBarcode.__init__(self, value)
  215. def validate(self):
  216. vval = ""
  217. self.valid = 1
  218. for c in self.value:
  219. if ord(c) > 127 and c not in '\xf1\xf2\xf3\xf4':
  220. self.valid = 0
  221. continue
  222. vval = vval + c
  223. self.validated = vval
  224. return vval
  225. def _try_TO_C(self, l):
  226. '''Improved version of old _trailingDigitsToC(self, l) inspired by'''
  227. i = 0
  228. nl = []
  229. while i < len(l):
  230. startpos = i
  231. rl = []
  232. savings = -1 # the TO_C costs one character
  233. while i < len(l):
  234. if l[i] in cStarts:
  235. j = i
  236. break
  237. elif l[i] == '\xf1':
  238. rl.append(l[i])
  239. i += 1
  240. continue
  241. elif l[i] in digits \
  242. and l[i+1] in digits:
  243. rl.append(l[i] + l[i+1])
  244. i += 2
  245. savings += 1
  246. continue
  247. else:
  248. if l[i] in digits and l[i+1]=='STOP':
  249. rrl = []
  250. rsavings = -1 #we need a TO_C
  251. k = i
  252. while k>startpos:
  253. if l[k]=='\xf1':
  254. rrl.append(l[i])
  255. k -= 1
  256. elif l[k] in digits and l[k-1] in digits:
  257. rrl.append(l[k-1]+l[k])
  258. rsavings += 1
  259. k -= 2
  260. else:
  261. break
  262. rrl.reverse()
  263. if rsavings>savings+int(savings>=0 and (startpos and nl[-1] in cStarts))-1:
  264. nl += l[startpos]
  265. startpos += 1
  266. rl = rrl
  267. del rrl
  268. i += 1
  269. break
  270. ta = not (l[i]=='STOP' or j==i)
  271. xs = savings>=0 and (startpos and nl[-1] in cStarts)
  272. if savings+int(xs) > int(ta):
  273. if xs:
  274. toc = nl[-1][:-1]+'C'
  275. del nl[-1]
  276. else:
  277. toc = 'TO_C'
  278. nl += [toc]+rl
  279. if ta:
  280. nl.append('TO'+l[j][-2:])
  281. nl.append(l[i])
  282. else:
  283. nl += l[startpos:i+1]
  284. i += 1
  285. return nl
  286. def encode(self):
  287. # First, encode using only B
  288. s = self.validated
  289. l = ['START_B']
  290. for c in s:
  291. if c not in setb:
  292. l = l + ['TO_A', c, 'TO_B']
  293. else:
  294. l.append(c)
  295. l.append('STOP')
  296. l = self._try_TO_C(l)
  297. # Finally, replace START_X,TO_Y with START_Y
  298. if l[1] in tos:
  299. l[:2] = ['START_' + l[1][-1]]
  300. # print repr(l)
  301. # encode into numbers
  302. start, set, shset = setmap[l[0]]
  303. e = [start]
  304. l = l[1:-1]
  305. while l:
  306. c = l[0]
  307. if c == 'SHIFT':
  308. e = e + [set[c], shset[l[1]]]
  309. l = l[2:]
  310. elif c in tos:
  311. e.append(set[c])
  312. set, shset = setmap[c]
  313. l = l[1:]
  314. else:
  315. e.append(set[c])
  316. l = l[1:]
  317. c = e[0]
  318. for i in range(1, len(e)):
  319. c = c + i * e[i]
  320. self.encoded = e + [c % 103, stop]
  321. return self.encoded
  322. def decompose(self):
  323. self.decomposed = ''.join([_patterns[c] for c in self.encoded])
  324. return self.decomposed
  325. def _humanText(self):
  326. return self.value
  327. class Code128Auto(Code128):
  328. '''contributed by https://bitbucket.org/kylemacfarlane/
  329. see https://bitbucket.org/rptlab/reportlab/issues/69/implementations-of-code-128-auto-and-data
  330. '''
  331. def encode(self):
  332. s = self.validated
  333. current_set = None
  334. l = []
  335. value = list(s)
  336. while value:
  337. c = value.pop(0)
  338. if c in digits and value and value[0] in digits:
  339. c += value.pop(0)
  340. if c in setc:
  341. set_ = 'C'
  342. elif c in setb:
  343. set_ = 'B'
  344. else:
  345. set_ = 'A'
  346. if current_set != set_:
  347. if current_set:
  348. l.append('TO_' + set_)
  349. else:
  350. l.append('START_' + set_)
  351. current_set = set_
  352. l.append(c)
  353. l.append('STOP')
  354. start, set, shset = setmap[l[0]]
  355. e = [start]
  356. l = l[1:-1]
  357. while l:
  358. c = l[0]
  359. if c == 'SHIFT':
  360. e = e + [set[c], shset[l[1]]]
  361. l = l[2:]
  362. elif c in tos:
  363. e.append(set[c])
  364. set, shset = setmap[c]
  365. l = l[1:]
  366. else:
  367. e.append(set[c])
  368. l = l[1:]
  369. c = e[0]
  370. for i in range(1, len(e)):
  371. c = c + i * e[i]
  372. self.encoded = e + [c % 103, stop]
  373. return self.encoded
  374. if __name__=='__main__':
  375. def main():
  376. from reportlab.graphics.barcode.code128 import Code128
  377. from reportlab.platypus import Spacer, SimpleDocTemplate
  378. from reportlab.lib.units import inch, cm
  379. from reportlab.lib.styles import getSampleStyleSheet
  380. from reportlab.platypus.paragraph import Paragraph
  381. from reportlab.platypus.flowables import KeepTogether
  382. import os
  383. styles = getSampleStyleSheet()
  384. styleN = styles['Normal']
  385. styleH = styles['Heading1']
  386. story = []
  387. storyAdd = story.append
  388. for s in (
  389. 'BBBB123456BBB',
  390. 'BBBB12345BBB',
  391. 'BBBB1234BBB',
  392. 'BBBB123BBB',
  393. 'BBBB12BBB',
  394. 'BBBB1BBB',
  395. 'BBBB123456aa',
  396. 'BBBB1234aa',
  397. 'BBBB123aa',
  398. 'BBBB12aa',
  399. 'BBBB1aa',
  400. 'BBBB123456',
  401. 'BBBB12345',
  402. 'BBBB1234',
  403. 'BBBB123',
  404. 'BBBB12',
  405. 'BBBB1',
  406. '\xf11234B',
  407. 'Ba\xf11234B',
  408. 'Ba12',
  409. 'Ba123B',
  410. 'Ba1234B',
  411. 'BBBB1234567',
  412. 'BBBB1234567aa',
  413. ):
  414. storyAdd(KeepTogether([Paragraph('Code 128 %r' % s, styleN),Code128(s)]))
  415. storyAdd(Spacer(inch,inch))
  416. SimpleDocTemplate('code128-out.pdf').build(story)
  417. main()