code39.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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.lib.units import inch
  33. from reportlab.lib.utils import asNative
  34. from reportlab.graphics.barcode.common import Barcode
  35. from string import digits as string_digits
  36. _patterns = {
  37. '0': ("bsbSBsBsb", 0), '1': ("BsbSbsbsB", 1),
  38. '2': ("bsBSbsbsB", 2), '3': ("BsBSbsbsb", 3),
  39. '4': ("bsbSBsbsB", 4), '5': ("BsbSBsbsb", 5),
  40. '6': ("bsBSBsbsb", 6), '7': ("bsbSbsBsB", 7),
  41. '8': ("BsbSbsBsb", 8), '9': ("bsBSbsBsb", 9),
  42. 'A': ("BsbsbSbsB", 10), 'B': ("bsBsbSbsB", 11),
  43. 'C': ("BsBsbSbsb", 12), 'D': ("bsbsBSbsB", 13),
  44. 'E': ("BsbsBSbsb", 14), 'F': ("bsBsBSbsb", 15),
  45. 'G': ("bsbsbSBsB", 16), 'H': ("BsbsbSBsb", 17),
  46. 'I': ("bsBsbSBsb", 18), 'J': ("bsbsBSBsb", 19),
  47. 'K': ("BsbsbsbSB", 20), 'L': ("bsBsbsbSB", 21),
  48. 'M': ("BsBsbsbSb", 22), 'N': ("bsbsBsbSB", 23),
  49. 'O': ("BsbsBsbSb", 24), 'P': ("bsBsBsbSb", 25),
  50. 'Q': ("bsbsbsBSB", 26), 'R': ("BsbsbsBSb", 27),
  51. 'S': ("bsBsbsBSb", 28), 'T': ("bsbsBsBSb", 29),
  52. 'U': ("BSbsbsbsB", 30), 'V': ("bSBsbsbsB", 31),
  53. 'W': ("BSBsbsbsb", 32), 'X': ("bSbsBsbsB", 33),
  54. 'Y': ("BSbsBsbsb", 34), 'Z': ("bSBsBsbsb", 35),
  55. '-': ("bSbsbsBsB", 36), '.': ("BSbsbsBsb", 37),
  56. ' ': ("bSBsbsBsb", 38), '*': ("bSbsBsBsb", None),
  57. '$': ("bSbSbSbsb", 39), '/': ("bSbSbsbSb", 40),
  58. '+': ("bSbsbSbSb", 41), '%': ("bsbSbSbSb", 42)
  59. }
  60. from reportlab.lib.utils import ascii_uppercase, ascii_lowercase
  61. _stdchrs = string_digits + ascii_uppercase + "-. $/+%"
  62. _extended = {
  63. '\0': "%U", '\01': "$A", '\02': "$B", '\03': "$C",
  64. '\04': "$D", '\05': "$E", '\06': "$F", '\07': "$G",
  65. '\010': "$H", '\011': "$I", '\012': "$J", '\013': "$K",
  66. '\014': "$L", '\015': "$M", '\016': "$N", '\017': "$O",
  67. '\020': "$P", '\021': "$Q", '\022': "$R", '\023': "$S",
  68. '\024': "$T", '\025': "$U", '\026': "$V", '\027': "$W",
  69. '\030': "$X", '\031': "$Y", '\032': "$Z", '\033': "%A",
  70. '\034': "%B", '\035': "%C", '\036': "%D", '\037': "%E",
  71. '!': "/A", '"': "/B", '#': "/C", '$': "/D",
  72. '%': "/E", '&': "/F", '\'': "/G", '(': "/H",
  73. ')': "/I", '*': "/J", '+': "/K", ',': "/L",
  74. '/': "/O", ':': "/Z", ';': "%F", '<': "%G",
  75. '=': "%H", '>': "%I", '?': "%J", '@': "%V",
  76. '[': "%K", '\\': "%L", ']': "%M", '^': "%N",
  77. '_': "%O", '`': "%W", 'a': "+A", 'b': "+B",
  78. 'c': "+C", 'd': "+D", 'e': "+E", 'f': "+F",
  79. 'g': "+G", 'h': "+H", 'i': "+I", 'j': "+J",
  80. 'k': "+K", 'l': "+L", 'm': "+M", 'n': "+N",
  81. 'o': "+O", 'p': "+P", 'q': "+Q", 'r': "+R",
  82. 's': "+S", 't': "+T", 'u': "+U", 'v': "+V",
  83. 'w': "+W", 'x': "+X", 'y': "+Y", 'z': "+Z",
  84. '{': "%P", '|': "%Q", '}': "%R", '~': "%S",
  85. '\177': "%T"
  86. }
  87. _extchrs = _stdchrs + ascii_lowercase + \
  88. "\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017" + \
  89. "\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" + \
  90. "*!'#&\"(),:;<=>?@[\\]^_`{|}~\177"
  91. def _encode39(value, cksum, stop):
  92. v = sum([_patterns[c][1] for c in value]) % 43
  93. if cksum:
  94. value += _stdchrs[v]
  95. if stop: value = '*'+value+'*'
  96. return value
  97. class _Code39Base(Barcode):
  98. barWidth = inch * 0.0075
  99. lquiet = None
  100. rquiet = None
  101. quiet = 1
  102. gap = None
  103. barHeight = None
  104. ratio = 2.2
  105. checksum = 1
  106. bearers = 0.0
  107. stop = 1
  108. def __init__(self, value = "", **args):
  109. value = asNative(value)
  110. for k, v in args.items():
  111. setattr(self, k, v)
  112. if self.quiet:
  113. if self.lquiet is None:
  114. self.lquiet = max(inch * 0.25, self.barWidth * 10.0)
  115. self.rquiet = max(inch * 0.25, self.barWidth * 10.0)
  116. else:
  117. self.lquiet = self.rquiet = 0.0
  118. Barcode.__init__(self, value)
  119. def decompose(self):
  120. dval = ""
  121. for c in self.encoded:
  122. dval = dval + _patterns[c][0] + 'i'
  123. self.decomposed = dval[:-1]
  124. return self.decomposed
  125. def _humanText(self):
  126. return self.stop and self.encoded[1:-1] or self.encoded
  127. class Standard39(_Code39Base):
  128. """
  129. Options that may be passed to constructor:
  130. value (int, or numeric string required.):
  131. The value to encode.
  132. barWidth (float, default .0075):
  133. X-Dimension, or width of the smallest element
  134. Minumum is .0075 inch (7.5 mils).
  135. ratio (float, default 2.2):
  136. The ratio of wide elements to narrow elements.
  137. Must be between 2.0 and 3.0 (or 2.2 and 3.0 if the
  138. barWidth is greater than 20 mils (.02 inch))
  139. gap (float or None, default None):
  140. width of intercharacter gap. None means "use barWidth".
  141. barHeight (float, see default below):
  142. Height of the symbol. Default is the height of the two
  143. bearer bars (if they exist) plus the greater of .25 inch
  144. or .15 times the symbol's length.
  145. checksum (bool, default 1):
  146. Wether to compute and include the check digit
  147. bearers (float, in units of barWidth. default 0):
  148. Height of bearer bars (horizontal bars along the top and
  149. bottom of the barcode). Default is 0 (no bearers).
  150. quiet (bool, default 1):
  151. Wether to include quiet zones in the symbol.
  152. lquiet (float, see default below):
  153. Quiet zone size to left of code, if quiet is true.
  154. Default is the greater of .25 inch, or .15 times the symbol's
  155. length.
  156. rquiet (float, defaults as above):
  157. Quiet zone size to right left of code, if quiet is true.
  158. stop (bool, default 1):
  159. Whether to include start/stop symbols.
  160. Sources of Information on Code 39:
  161. http://www.semiconductor.agilent.com/barcode/sg/Misc/code_39.html
  162. http://www.adams1.com/pub/russadam/39code.html
  163. http://www.barcodeman.com/c39_1.html
  164. Official Spec, "ANSI/AIM BC1-1995, USS" is available for US$45 from
  165. http://www.aimglobal.org/aimstore/
  166. """
  167. def validate(self):
  168. vval = [].append
  169. self.valid = 1
  170. for c in self.value:
  171. if c in ascii_lowercase:
  172. c = c.upper()
  173. if c not in _stdchrs:
  174. self.valid = 0
  175. continue
  176. vval(c)
  177. self.validated = ''.join(vval.__self__)
  178. return self.validated
  179. def encode(self):
  180. self.encoded = _encode39(self.validated, self.checksum, self.stop)
  181. return self.encoded
  182. class Extended39(_Code39Base):
  183. """
  184. Extended Code 39 is a convention for encoding additional characters
  185. not present in stanmdard Code 39 by using pairs of characters to
  186. represent the characters missing in Standard Code 39.
  187. See Standard39 for arguments.
  188. Sources of Information on Extended Code 39:
  189. http://www.semiconductor.agilent.com/barcode/sg/Misc/xcode_39.html
  190. http://www.barcodeman.com/c39_ext.html
  191. """
  192. def validate(self):
  193. vval = ""
  194. self.valid = 1
  195. for c in self.value:
  196. if c not in _extchrs:
  197. self.valid = 0
  198. continue
  199. vval = vval + c
  200. self.validated = vval
  201. return vval
  202. def encode(self):
  203. self.encoded = ""
  204. for c in self.validated:
  205. if c in _extended:
  206. self.encoded = self.encoded + _extended[c]
  207. elif c in _stdchrs:
  208. self.encoded = self.encoded + c
  209. else:
  210. raise ValueError
  211. self.encoded = _encode39(self.encoded, self.checksum,self.stop)
  212. return self.encoded