code
stringlengths
114
1.05M
path
stringlengths
3
312
quality_prob
float64
0.5
0.99
learning_prob
float64
0.2
1
filename
stringlengths
3
168
kind
stringclasses
1 value
widths = {'A': 611, 'AE': 889, 'Aacute': 611, 'Acircumflex': 611, 'Adieresis': 611, 'Agrave': 611, 'Aring': 611, 'Atilde': 611, 'B': 611, 'C': 667, 'Ccedilla': 667, 'D': 722, 'E': 611, 'Eacute': 611, 'Ecircumflex': 611, 'Edieresis': 611, 'Egrave': 611, 'Eth': 722, 'Euro': 500, 'F': 611, 'G': 722, 'H': 722, 'I': 333, 'Iacute': 333, 'Icircumflex': 333, 'Idieresis': 333, 'Igrave': 333, 'J': 444, 'K': 667, 'L': 556, 'Lslash': 556, 'M': 833, 'N': 667, 'Ntilde': 667, 'O': 722, 'OE': 944, 'Oacute': 722, 'Ocircumflex': 722, 'Odieresis': 722, 'Ograve': 722, 'Oslash': 722, 'Otilde': 722, 'P': 611, 'Q': 722, 'R': 611, 'S': 500, 'Scaron': 500, 'T': 556, 'Thorn': 611, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 611, 'W': 833, 'X': 611, 'Y': 556, 'Yacute': 556, 'Ydieresis': 556, 'Z': 556, 'Zcaron': 556, 'a': 500, 'aacute': 500, 'acircumflex': 500, 'acute': 333, 'adieresis': 500, 'ae': 667, 'agrave': 500, 'ampersand': 778, 'aring': 500, 'asciicircum': 422, 'asciitilde': 541, 'asterisk': 500, 'at': 920, 'atilde': 500, 'b': 500, 'backslash': 278, 'bar': 275, 'braceleft': 400, 'braceright': 400, 'bracketleft': 389, 'bracketright': 389, 'breve': 333, 'brokenbar': 275, 'bullet': 350, 'c': 444, 'caron': 333, 'ccedilla': 444, 'cedilla': 333, 'cent': 500, 'circumflex': 333, 'colon': 333, 'comma': 250, 'copyright': 760, 'currency': 500, 'd': 500, 'dagger': 500, 'daggerdbl': 500, 'degree': 400, 'dieresis': 333, 'divide': 675, 'dollar': 500, 'dotaccent': 333, 'dotlessi': 278, 'e': 444, 'eacute': 444, 'ecircumflex': 444, 'edieresis': 444, 'egrave': 444, 'eight': 500, 'ellipsis': 889, 'emdash': 889, 'endash': 500, 'equal': 675, 'eth': 500, 'exclam': 333, 'exclamdown': 389, 'f': 278, 'fi': 500, 'five': 500, 'fl': 500, 'florin': 500, 'four': 500, 'fraction': 167, 'g': 500, 'germandbls': 500, 'grave': 333, 'greater': 675, 'guillemotleft': 500, 'guillemotright': 500, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 500, 'hungarumlaut': 333, 'hyphen': 333, 'i': 278, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 278, 'k': 444, 'l': 278, 'less': 675, 'logicalnot': 675, 'lslash': 278, 'm': 722, 'macron': 333, 'minus': 675, 'mu': 500, 'multiply': 675, 'n': 500, 'nine': 500, 'ntilde': 500, 'numbersign': 500, 'o': 500, 'oacute': 500, 'ocircumflex': 500, 'odieresis': 500, 'oe': 667, 'ogonek': 333, 'ograve': 500, 'one': 500, 'onehalf': 750, 'onequarter': 750, 'onesuperior': 300, 'ordfeminine': 276, 'ordmasculine': 310, 'oslash': 500, 'otilde': 500, 'p': 500, 'paragraph': 523, 'parenleft': 333, 'parenright': 333, 'percent': 833, 'period': 250, 'periodcentered': 250, 'perthousand': 1000, 'plus': 675, 'plusminus': 675, 'q': 500, 'question': 500, 'questiondown': 500, 'quotedbl': 420, 'quotedblbase': 556, 'quotedblleft': 556, 'quotedblright': 556, 'quoteleft': 333, 'quoteright': 333, 'quotesinglbase': 333, 'quotesingle': 214, 'r': 389, 'registered': 760, 'ring': 333, 's': 389, 'scaron': 389, 'section': 500, 'semicolon': 333, 'seven': 500, 'six': 500, 'slash': 278, 'space': 250, 'sterling': 500, 't': 278, 'thorn': 500, 'three': 500, 'threequarters': 750, 'threesuperior': 300, 'tilde': 333, 'trademark': 980, 'two': 500, 'twosuperior': 300, 'u': 500, 'uacute': 500, 'ucircumflex': 500, 'udieresis': 500, 'ugrave': 500, 'underscore': 500, 'v': 444, 'w': 667, 'x': 444, 'y': 444, 'yacute': 444, 'ydieresis': 444, 'yen': 500, 'z': 389, 'zcaron': 389, 'zero': 500}
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/pdfbase/_fontdata_widths_timesitalic.py
0.546496
0.215516
_fontdata_widths_timesitalic.py
pypi
MacRomanEncoding = ( None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', None, 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis', 'Udieresis', 'aacute', 'agrave', 'acircumflex', 'adieresis', 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis', 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve', 'ocircumflex', 'odieresis', 'otilde', 'uacute', 'ugrave', 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section', 'bullet', 'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute', 'dieresis', None, 'AE', 'Oslash', None, 'plusminus', None, None, 'yen', 'mu', None, None, None, None, None, 'ordfeminine', 'ordmasculine', None, 'ae', 'oslash', 'questiondown', 'exclamdown', 'logicalnot', None, 'florin', None, None, 'guillemotleft', 'guillemotright', 'ellipsis', 'space', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash', 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft', 'quoteright', 'divide', None, 'ydieresis', 'Ydieresis', 'fraction', 'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered', 'quotesinglbase', 'quotedblbase', 'perthousand', 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', None, 'Ograve', 'Uacute', 'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron')
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/pdfbase/_fontdata_enc_macroman.py
0.529263
0.177401
_fontdata_enc_macroman.py
pypi
widths = {'A': 667, 'AE': 1000, 'Aacute': 667, 'Acircumflex': 667, 'Adieresis': 667, 'Agrave': 667, 'Aring': 667, 'Atilde': 667, 'B': 667, 'C': 722, 'Ccedilla': 722, 'D': 722, 'E': 667, 'Eacute': 667, 'Ecircumflex': 667, 'Edieresis': 667, 'Egrave': 667, 'Eth': 722, 'Euro': 556, 'F': 611, 'G': 778, 'H': 722, 'I': 278, 'Iacute': 278, 'Icircumflex': 278, 'Idieresis': 278, 'Igrave': 278, 'J': 500, 'K': 667, 'L': 556, 'Lslash': 556, 'M': 833, 'N': 722, 'Ntilde': 722, 'O': 778, 'OE': 1000, 'Oacute': 778, 'Ocircumflex': 778, 'Odieresis': 778, 'Ograve': 778, 'Oslash': 778, 'Otilde': 778, 'P': 667, 'Q': 778, 'R': 722, 'S': 667, 'Scaron': 667, 'T': 611, 'Thorn': 667, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 667, 'W': 944, 'X': 667, 'Y': 667, 'Yacute': 667, 'Ydieresis': 667, 'Z': 611, 'Zcaron': 611, 'a': 556, 'aacute': 556, 'acircumflex': 556, 'acute': 333, 'adieresis': 556, 'ae': 889, 'agrave': 556, 'ampersand': 667, 'aring': 556, 'asciicircum': 469, 'asciitilde': 584, 'asterisk': 389, 'at': 1015, 'atilde': 556, 'b': 556, 'backslash': 278, 'bar': 260, 'braceleft': 334, 'braceright': 334, 'bracketleft': 278, 'bracketright': 278, 'breve': 333, 'brokenbar': 260, 'bullet': 350, 'c': 500, 'caron': 333, 'ccedilla': 500, 'cedilla': 333, 'cent': 556, 'circumflex': 333, 'colon': 278, 'comma': 278, 'copyright': 737, 'currency': 556, 'd': 556, 'dagger': 556, 'daggerdbl': 556, 'degree': 400, 'dieresis': 333, 'divide': 584, 'dollar': 556, 'dotaccent': 333, 'dotlessi': 278, 'e': 556, 'eacute': 556, 'ecircumflex': 556, 'edieresis': 556, 'egrave': 556, 'eight': 556, 'ellipsis': 1000, 'emdash': 1000, 'endash': 556, 'equal': 584, 'eth': 556, 'exclam': 278, 'exclamdown': 333, 'f': 278, 'fi': 500, 'five': 556, 'fl': 500, 'florin': 556, 'four': 556, 'fraction': 167, 'g': 556, 'germandbls': 611, 'grave': 333, 'greater': 584, 'guillemotleft': 556, 'guillemotright': 556, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 556, 'hungarumlaut': 333, 'hyphen': 333, 'i': 222, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 222, 'k': 500, 'l': 222, 'less': 584, 'logicalnot': 584, 'lslash': 222, 'm': 833, 'macron': 333, 'minus': 584, 'mu': 556, 'multiply': 584, 'n': 556, 'nine': 556, 'ntilde': 556, 'numbersign': 556, 'o': 556, 'oacute': 556, 'ocircumflex': 556, 'odieresis': 556, 'oe': 944, 'ogonek': 333, 'ograve': 556, 'one': 556, 'onehalf': 834, 'onequarter': 834, 'onesuperior': 333, 'ordfeminine': 370, 'ordmasculine': 365, 'oslash': 611, 'otilde': 556, 'p': 556, 'paragraph': 537, 'parenleft': 333, 'parenright': 333, 'percent': 889, 'period': 278, 'periodcentered': 278, 'perthousand': 1000, 'plus': 584, 'plusminus': 584, 'q': 556, 'question': 556, 'questiondown': 611, 'quotedbl': 355, 'quotedblbase': 333, 'quotedblleft': 333, 'quotedblright': 333, 'quoteleft': 222, 'quoteright': 222, 'quotesinglbase': 222, 'quotesingle': 191, 'r': 333, 'registered': 737, 'ring': 333, 's': 500, 'scaron': 500, 'section': 556, 'semicolon': 278, 'seven': 556, 'six': 556, 'slash': 278, 'space': 278, 'sterling': 556, 't': 278, 'thorn': 556, 'three': 556, 'threequarters': 834, 'threesuperior': 333, 'tilde': 333, 'trademark': 1000, 'two': 556, 'twosuperior': 333, 'u': 556, 'uacute': 556, 'ucircumflex': 556, 'udieresis': 556, 'ugrave': 556, 'underscore': 556, 'v': 500, 'w': 722, 'x': 500, 'y': 500, 'yacute': 500, 'ydieresis': 500, 'yen': 556, 'z': 500, 'zcaron': 500, 'zero': 556}
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/pdfbase/_fontdata_widths_helveticaoblique.py
0.572245
0.290893
_fontdata_widths_helveticaoblique.py
pypi
from reportlab.platypus.flowables import Flowable from reportlab.lib.units import inch from reportlab.lib.utils import ascii_uppercase, ascii_lowercase from string import digits as string_digits class Barcode(Flowable): """Abstract Base for barcodes. Includes implementations of some methods suitable for the more primitive barcode types""" fontName = 'Courier' fontSize = 12 humanReadable = 0 def _humanText(self): return self.encoded def __init__(self, value='',**kwd): self.value = str(value) self._setKeywords(**kwd) if not hasattr(self, 'gap'): self.gap = None def _calculate(self): self.validate() self.encode() self.decompose() self.computeSize() def _setKeywords(self,**kwd): for (k, v) in kwd.items(): setattr(self, k, v) def validate(self): self.valid = 1 self.validated = self.value def encode(self): self.encoded = self.validated def decompose(self): self.decomposed = self.encoded def computeSize(self, *args): barWidth = self.barWidth wx = barWidth * self.ratio if self.gap == None: self.gap = barWidth w = 0.0 for c in self.decomposed: if c in 'sb': w = w + barWidth elif c in 'SB': w = w + wx else: # 'i' w = w + self.gap if self.barHeight is None: self.barHeight = w * 0.15 self.barHeight = max(0.25 * inch, self.barHeight) if self.bearers: self.barHeight = self.barHeight + self.bearers * 2.0 * barWidth if self.quiet: w += self.lquiet + self.rquiet self._height = self.barHeight self._width = w def width(self): self._calculate() return self._width width = property(width) def height(self): self._calculate() return self._height height = property(height) def draw(self): self._calculate() barWidth = self.barWidth wx = barWidth * self.ratio left = self.quiet and self.lquiet or 0 b = self.bearers * barWidth bb = b * 0.5 tb = self.barHeight - (b * 1.5) for c in self.decomposed: if c == 'i': left = left + self.gap elif c == 's': left = left + barWidth elif c == 'S': left = left + wx elif c == 'b': self.rect(left, bb, barWidth, tb) left = left + barWidth elif c == 'B': self.rect(left, bb, wx, tb) left = left + wx if self.bearers: self.rect(self.lquiet, 0, \ self._width - (self.lquiet + self.rquiet), b) self.rect(self.lquiet, self.barHeight - b, \ self._width - (self.lquiet + self.rquiet), b) self.drawHumanReadable() def drawHumanReadable(self): if self.humanReadable: #we have text from reportlab.pdfbase.pdfmetrics import getAscent, stringWidth s = str(self._humanText()) fontSize = self.fontSize fontName = self.fontName w = stringWidth(s,fontName,fontSize) width = self._width if self.quiet: width -= self.lquiet+self.rquiet x = self.lquiet else: x = 0 if w>width: fontSize *= width/float(w) y = 1.07*getAscent(fontName)*fontSize/1000. self.annotate(x+width/2.,-y,s,fontName,fontSize) def rect(self, x, y, w, h): self.canv.rect(x, y, w, h, stroke=0, fill=1) def annotate(self,x,y,text,fontName,fontSize,anchor='middle'): canv = self.canv canv.saveState() canv.setFont(self.fontName,fontSize) if anchor=='middle': func = 'drawCentredString' elif anchor=='end': func = 'drawRightString' else: func = 'drawString' getattr(canv,func)(x,y,text) canv.restoreState() class MultiWidthBarcode(Barcode): """Base for variable-bar-width codes like Code93 and Code128""" def computeSize(self, *args): barWidth = self.barWidth oa, oA = ord('a') - 1, ord('A') - 1 w = 0.0 for c in self.decomposed: oc = ord(c) if c in ascii_lowercase: w = w + barWidth * (oc - oa) elif c in ascii_uppercase: w = w + barWidth * (oc - oA) if self.barHeight is None: self.barHeight = w * 0.15 self.barHeight = max(0.25 * inch, self.barHeight) if self.quiet: w += self.lquiet + self.rquiet self._height = self.barHeight self._width = w def draw(self): self._calculate() oa, oA = ord('a') - 1, ord('A') - 1 barWidth = self.barWidth left = self.quiet and self.lquiet or 0 for c in self.decomposed: oc = ord(c) if c in ascii_lowercase: left = left + (oc - oa) * barWidth elif c in ascii_uppercase: w = (oc - oA) * barWidth self.rect(left, 0, w, self.barHeight) left += w self.drawHumanReadable() class I2of5(Barcode): """ Interleaved 2 of 5 is a numeric-only barcode. It encodes an even number of digits; if an odd number is given, a 0 is prepended. Options that may be passed to constructor: value (int, or numeric string required.): The value to encode. barWidth (float, default .0075): X-Dimension, or width of the smallest element Minumum is .0075 inch (7.5 mils). ratio (float, default 2.2): The ratio of wide elements to narrow elements. Must be between 2.0 and 3.0 (or 2.2 and 3.0 if the barWidth is greater than 20 mils (.02 inch)) gap (float or None, default None): width of intercharacter gap. None means "use barWidth". barHeight (float, see default below): Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol's length. checksum (bool, default 1): Whether to compute and include the check digit bearers (float, in units of barWidth. default 3.0): Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 3 x-dimensions. Set to zero for no bearer bars. (Bearer bars help detect misscans, so it is suggested to leave them on). quiet (bool, default 1): Whether to include quiet zones in the symbol. lquiet (float, see default below): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or .15 times the symbol's length. rquiet (float, defaults as above): Quiet zone size to right left of code, if quiet is true. stop (bool, default 1): Whether to include start/stop symbols. Sources of Information on Interleaved 2 of 5: http://www.semiconductor.agilent.com/barcode/sg/Misc/i_25.html http://www.adams1.com/pub/russadam/i25code.html Official Spec, "ANSI/AIM BC2-1995, USS" is available for US$45 from http://www.aimglobal.org/aimstore/ """ patterns = { 'start' : 'bsbs', 'stop' : 'Bsb', 'B0' : 'bbBBb', 'S0' : 'ssSSs', 'B1' : 'BbbbB', 'S1' : 'SsssS', 'B2' : 'bBbbB', 'S2' : 'sSssS', 'B3' : 'BBbbb', 'S3' : 'SSsss', 'B4' : 'bbBbB', 'S4' : 'ssSsS', 'B5' : 'BbBbb', 'S5' : 'SsSss', 'B6' : 'bBBbb', 'S6' : 'sSSss', 'B7' : 'bbbBB', 'S7' : 'sssSS', 'B8' : 'BbbBb', 'S8' : 'SssSs', 'B9' : 'bBbBb', 'S9' : 'sSsSs' } barHeight = None barWidth = inch * 0.0075 ratio = 2.2 checksum = 1 bearers = 3.0 quiet = 1 lquiet = None rquiet = None stop = 1 def __init__(self, value='', **args): if type(value) == type(1): value = str(value) for k, v in args.items(): setattr(self, k, v) if self.quiet: if self.lquiet is None: self.lquiet = min(inch * 0.25, self.barWidth * 10.0) self.rquiet = min(inch * 0.25, self.barWidth * 10.0) else: self.lquiet = self.rquiet = 0.0 Barcode.__init__(self, value) def validate(self): vval = "" self.valid = 1 for c in self.value.strip(): if c not in string_digits: self.valid = 0 continue vval = vval + c self.validated = vval return vval def encode(self): s = self.validated cs = self.checksum c = len(s) #ensure len(result)%2 == 0, checksum included if ((c % 2 == 0) and cs) or ((c % 2 == 1) and not cs): s = '0' + s c += 1 if cs: c = 3*sum([int(s[i]) for i in range(0,c,2)])+sum([int(s[i]) for i in range(1,c,2)]) s += str((10 - c) % 10) self.encoded = s def decompose(self): dval = self.stop and [self.patterns['start']] or [] a = dval.append for i in range(0, len(self.encoded), 2): b = self.patterns['B' + self.encoded[i]] s = self.patterns['S' + self.encoded[i+1]] for i in range(0, len(b)): a(b[i] + s[i]) if self.stop: a(self.patterns['stop']) self.decomposed = ''.join(dval) return self.decomposed class MSI(Barcode): """ MSI is a numeric-only barcode. Options that may be passed to constructor: value (int, or numeric string required.): The value to encode. barWidth (float, default .0075): X-Dimension, or width of the smallest element ratio (float, default 2.2): The ratio of wide elements to narrow elements. gap (float or None, default None): width of intercharacter gap. None means "use barWidth". barHeight (float, see default below): Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol's length. checksum (bool, default 1): Wether to compute and include the check digit bearers (float, in units of barWidth. default 0): Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 0 (no bearers). lquiet (float, see default below): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or 10 barWidths. rquiet (float, defaults as above): Quiet zone size to right left of code, if quiet is true. stop (bool, default 1): Whether to include start/stop symbols. Sources of Information on MSI Bar Code: http://www.semiconductor.agilent.com/barcode/sg/Misc/msi_code.html http://www.adams1.com/pub/russadam/plessy.html """ patterns = { 'start' : 'Bs', 'stop' : 'bSb', '0' : 'bSbSbSbS', '1' : 'bSbSbSBs', '2' : 'bSbSBsbS', '3' : 'bSbSBsBs', '4' : 'bSBsbSbS', '5' : 'bSBsbSBs', '6' : 'bSBsBsbS', '7' : 'bSBsBsBs', '8' : 'BsbSbSbS', '9' : 'BsbSbSBs' } stop = 1 barHeight = None barWidth = inch * 0.0075 ratio = 2.2 checksum = 1 bearers = 0.0 quiet = 1 lquiet = None rquiet = None def __init__(self, value="", **args): if type(value) == type(1): value = str(value) for k, v in args.items(): setattr(self, k, v) if self.quiet: if self.lquiet is None: self.lquiet = max(inch * 0.25, self.barWidth * 10.0) self.rquiet = max(inch * 0.25, self.barWidth * 10.0) else: self.lquiet = self.rquiet = 0.0 Barcode.__init__(self, value) def validate(self): vval = "" self.valid = 1 for c in self.value.strip(): if c not in string_digits: self.valid = 0 continue vval = vval + c self.validated = vval return vval def encode(self): s = self.validated if self.checksum: c = '' for i in range(1, len(s), 2): c = c + s[i] d = str(int(c) * 2) t = 0 for c in d: t = t + int(c) for i in range(0, len(s), 2): t = t + int(s[i]) c = 10 - (t % 10) s = s + str(c) self.encoded = s def decompose(self): dval = self.stop and [self.patterns['start']] or [] dval += [self.patterns[c] for c in self.encoded] if self.stop: dval.append(self.patterns['stop']) self.decomposed = ''.join(dval) return self.decomposed class Codabar(Barcode): """ Codabar is a numeric plus some puntuation ("-$:/.+") barcode with four start/stop characters (A, B, C, and D). Options that may be passed to constructor: value (string required.): The value to encode. barWidth (float, default .0065): X-Dimension, or width of the smallest element minimum is 6.5 mils (.0065 inch) ratio (float, default 2.0): The ratio of wide elements to narrow elements. gap (float or None, default None): width of intercharacter gap. None means "use barWidth". barHeight (float, see default below): Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol's length. checksum (bool, default 0): Whether to compute and include the check digit bearers (float, in units of barWidth. default 0): Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 0 (no bearers). quiet (bool, default 1): Whether to include quiet zones in the symbol. stop (bool, default 1): Whether to include start/stop symbols. lquiet (float, see default below): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or 10 barWidth rquiet (float, defaults as above): Quiet zone size to right left of code, if quiet is true. Sources of Information on Codabar http://www.semiconductor.agilent.com/barcode/sg/Misc/codabar.html http://www.barcodeman.com/codabar.html Official Spec, "ANSI/AIM BC3-1995, USS" is available for US$45 from http://www.aimglobal.org/aimstore/ """ patterns = { '0': 'bsbsbSB', '1': 'bsbsBSb', '2': 'bsbSbsB', '3': 'BSbsbsb', '4': 'bsBsbSb', '5': 'BsbsbSb', '6': 'bSbsbsB', '7': 'bSbsBsb', '8': 'bSBsbsb', '9': 'BsbSbsb', '-': 'bsbSBsb', '$': 'bsBSbsb', ':': 'BsbsBsB', '/': 'BsBsbsB', '.': 'BsBsBsb', '+': 'bsBsBsB', 'A': 'bsBSbSb', 'B': 'bSbSbsB', 'C': 'bsbSbSB', 'D': 'bsbSBSb' } values = { '0' : 0, '1' : 1, '2' : 2, '3' : 3, '4' : 4, '5' : 5, '6' : 6, '7' : 7, '8' : 8, '9' : 9, '-' : 10, '$' : 11, ':' : 12, '/' : 13, '.' : 14, '+' : 15, 'A' : 16, 'B' : 17, 'C' : 18, 'D' : 19 } chars = string_digits + "-$:/.+" stop = 1 barHeight = None barWidth = inch * 0.0065 ratio = 2.0 # XXX ? checksum = 0 bearers = 0.0 quiet = 1 lquiet = None rquiet = None def __init__(self, value='', **args): if type(value) == type(1): value = str(value) for k, v in args.items(): setattr(self, k, v) if self.quiet: if self.lquiet is None: self.lquiet = min(inch * 0.25, self.barWidth * 10.0) self.rquiet = min(inch * 0.25, self.barWidth * 10.0) else: self.lquiet = self.rquiet = 0.0 Barcode.__init__(self, value) def validate(self): vval = "" self.valid = 1 s = self.value.strip() for i in range(0, len(s)): c = s[i] if c not in self.chars: if ((i != 0) and (i != len(s) - 1)) or (c not in 'ABCD'): self.Valid = 0 continue vval = vval + c if self.stop: if vval[0] not in 'ABCD': vval = 'A' + vval if vval[-1] not in 'ABCD': vval = vval + vval[0] self.validated = vval return vval def encode(self): s = self.validated if self.checksum: v = sum([self.values[c] for c in s]) s += self.chars[v % 16] self.encoded = s def decompose(self): dval = ''.join([self.patterns[c]+'i' for c in self.encoded]) self.decomposed = dval[:-1] return self.decomposed class Code11(Barcode): """ Code 11 is an almost-numeric barcode. It encodes the digits 0-9 plus dash ("-"). 11 characters total, hence the name. value (int or string required.): The value to encode. barWidth (float, default .0075): X-Dimension, or width of the smallest element ratio (float, default 2.2): The ratio of wide elements to narrow elements. gap (float or None, default None): width of intercharacter gap. None means "use barWidth". barHeight (float, see default below): Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol's length. checksum (0 none, 1 1-digit, 2 2-digit, -1 auto, default -1): How many checksum digits to include. -1 ("auto") means 1 if the number of digits is 10 or less, else 2. bearers (float, in units of barWidth. default 0): Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 0 (no bearers). quiet (bool, default 1): Wether to include quiet zones in the symbol. lquiet (float, see default below): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or 10 barWidth rquiet (float, defaults as above): Quiet zone size to right left of code, if quiet is true. Sources of Information on Code 11: http://www.cwi.nl/people/dik/english/codes/barcodes.html """ chars = '0123456789-' patterns = { '0' : 'bsbsB', '1' : 'BsbsB', '2' : 'bSbsB', '3' : 'BSbsb', '4' : 'bsBsB', '5' : 'BsBsb', '6' : 'bSBsb', '7' : 'bsbSB', '8' : 'BsbSb', '9' : 'Bsbsb', '-' : 'bsBsb', 'S' : 'bsBSb' # Start/Stop } values = { '0' : 0, '1' : 1, '2' : 2, '3' : 3, '4' : 4, '5' : 5, '6' : 6, '7' : 7, '8' : 8, '9' : 9, '-' : 10, } stop = 1 barHeight = None barWidth = inch * 0.0075 ratio = 2.2 # XXX ? checksum = -1 # Auto bearers = 0.0 quiet = 1 lquiet = None rquiet = None def __init__(self, value='', **args): if type(value) == type(1): value = str(value) for k, v in args.items(): setattr(self, k, v) if self.quiet: if self.lquiet is None: self.lquiet = min(inch * 0.25, self.barWidth * 10.0) self.rquiet = min(inch * 0.25, self.barWidth * 10.0) else: self.lquiet = self.rquiet = 0.0 Barcode.__init__(self, value) def validate(self): vval = "" self.valid = 1 s = self.value.strip() for i in range(0, len(s)): c = s[i] if c not in self.chars: self.Valid = 0 continue vval = vval + c self.validated = vval return vval def _addCSD(self,s,m): # compute first checksum i = c = 0 v = 1 V = self.values while i < len(s): c += v * V[s[-(i+1)]] i += 1 v += 1 if v==m: v = 1 return s+self.chars[c % 11] def encode(self): s = self.validated tcs = self.checksum if tcs<0: self.checksum = tcs = 1+int(len(s)>10) if tcs > 0: s = self._addCSD(s,11) if tcs > 1: s = self._addCSD(s,10) self.encoded = self.stop and ('S' + s + 'S') or s def decompose(self): self.decomposed = ''.join([(self.patterns[c]+'i') for c in self.encoded])[:-1] return self.decomposed def _humanText(self): return self.stop and self.encoded[1:-1] or self.encoded
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/graphics/barcode/common.py
0.596433
0.339253
common.py
pypi
from reportlab.lib.units import inch from reportlab.lib.utils import asNative from reportlab.graphics.barcode.common import MultiWidthBarcode _patterns = { '0' : ('AcAaAb', 0), '1' : ('AaAbAc', 1), '2' : ('AaAcAb', 2), '3' : ('AaAdAa', 3), '4' : ('AbAaAc', 4), '5' : ('AbAbAb', 5), '6' : ('AbAcAa', 6), '7' : ('AaAaAd', 7), '8' : ('AcAbAa', 8), '9' : ('AdAaAa', 9), 'A' : ('BaAaAc', 10), 'B' : ('BaAbAb', 11), 'C' : ('BaAcAa', 12), 'D' : ('BbAaAb', 13), 'E' : ('BbAbAa', 14), 'F' : ('BcAaAa', 15), 'G' : ('AaBaAc', 16), 'H' : ('AaBbAb', 17), 'I' : ('AaBcAa', 18), 'J' : ('AbBaAb', 19), 'K' : ('AcBaAa', 20), 'L' : ('AaAaBc', 21), 'M' : ('AaAbBb', 22), 'N' : ('AaAcBa', 23), 'O' : ('AbAaBb', 24), 'P' : ('AcAaBa', 25), 'Q' : ('BaBaAb', 26), 'R' : ('BaBbAa', 27), 'S' : ('BaAaBb', 28), 'T' : ('BaAbBa', 29), 'U' : ('BbAaBa', 30), 'V' : ('BbBaAa', 31), 'W' : ('AaBaBb', 32), 'X' : ('AaBbBa', 33), 'Y' : ('AbBaBa', 34), 'Z' : ('AbCaAa', 35), '-' : ('AbAaCa', 36), '.' : ('CaAaAb', 37), ' ' : ('CaAbAa', 38), '$' : ('CbAaAa', 39), '/' : ('AaBaCa', 40), '+' : ('AaCaBa', 41), '%' : ('BaAaCa', 42), '#' : ('AbAbBa', 43), '!' : ('CaBaAa', 44), '=' : ('CaAaBa', 45), '&' : ('AbBbAa', 46), 'start' : ('AaAaDa', -1), 'stop' : ('AaAaDaA', -2) } _charsbyval = {} for k, v in _patterns.items(): _charsbyval[v[1]] = k _extended = { '\x00' : '!U', '\x01' : '#A', '\x02' : '#B', '\x03' : '#C', '\x04' : '#D', '\x05' : '#E', '\x06' : '#F', '\x07' : '#G', '\x08' : '#H', '\x09' : '#I', '\x0a' : '#J', '\x0b' : '#K', '\x0c' : '#L', '\x0d' : '#M', '\x0e' : '#N', '\x0f' : '#O', '\x10' : '#P', '\x11' : '#Q', '\x12' : '#R', '\x13' : '#S', '\x14' : '#T', '\x15' : '#U', '\x16' : '#V', '\x17' : '#W', '\x18' : '#X', '\x19' : '#Y', '\x1a' : '#Z', '\x1b' : '!A', '\x1c' : '!B', '\x1d' : '!C', '\x1e' : '!D', '\x1f' : '!E', '!' : '=A', '"' : '=B', '#' : '=C', '$' : '=D', '%' : '=E', '&' : '=F', '\'' : '=G', '(' : '=H', ')' : '=I', '*' : '=J', '+' : '=K', ',' : '=L', '/' : '=O', ':' : '=Z', ';' : '!F', '<' : '!G', '=' : '!H', '>' : '!I', '?' : '!J', '@' : '!V', '[' : '!K', '\\' : '!L', ']' : '!M', '^' : '!N', '_' : '!O', '`' : '!W', 'a' : '&A', 'b' : '&B', 'c' : '&C', 'd' : '&D', 'e' : '&E', 'f' : '&F', 'g' : '&G', 'h' : '&H', 'i' : '&I', 'j' : '&J', 'k' : '&K', 'l' : '&L', 'm' : '&M', 'n' : '&N', 'o' : '&O', 'p' : '&P', 'q' : '&Q', 'r' : '&R', 's' : '&S', 't' : '&T', 'u' : '&U', 'v' : '&V', 'w' : '&W', 'x' : '&X', 'y' : '&Y', 'z' : '&Z', '{' : '!P', '|' : '!Q', '}' : '!R', '~' : '!S', '\x7f' : '!T' } def _encode93(str): s = list(str) s.reverse() # compute 'C' checksum i = 0; v = 1; c = 0 while i < len(s): c = c + v * _patterns[s[i]][1] i = i + 1; v = v + 1 if v > 20: v = 1 s.insert(0, _charsbyval[c % 47]) # compute 'K' checksum i = 0; v = 1; c = 0 while i < len(s): c = c + v * _patterns[s[i]][1] i = i + 1; v = v + 1 if v > 15: v = 1 s.insert(0, _charsbyval[c % 47]) s.reverse() return ''.join(s) class _Code93Base(MultiWidthBarcode): barWidth = inch * 0.0075 lquiet = None rquiet = None quiet = 1 barHeight = None stop = 1 def __init__(self, value='', **args): if type(value) is type(1): value = asNative(value) for (k, v) in args.items(): setattr(self, k, v) if self.quiet: if self.lquiet is None: self.lquiet = max(inch * 0.25, self.barWidth * 10.0) self.rquiet = max(inch * 0.25, self.barWidth * 10.0) else: self.lquiet = self.rquiet = 0.0 MultiWidthBarcode.__init__(self, value) def decompose(self): dval = self.stop and [_patterns['start'][0]] or [] dval += [_patterns[c][0] for c in self.encoded] if self.stop: dval.append(_patterns['stop'][0]) self.decomposed = ''.join(dval) return self.decomposed class Standard93(_Code93Base): """ Code 93 is a Uppercase alphanumeric symbology with some punctuation. See Extended Code 93 for a variant that can represent the entire 128 characrter ASCII set. Options that may be passed to constructor: value (int, or numeric string. required.): The value to encode. barWidth (float, default .0075): X-Dimension, or width of the smallest element Minumum is .0075 inch (7.5 mils). barHeight (float, see default below): Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol's length. quiet (bool, default 1): Wether to include quiet zones in the symbol. lquiet (float, see default below): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or 10 barWidth rquiet (float, defaults as above): Quiet zone size to right left of code, if quiet is true. stop (bool, default 1): Whether to include start/stop symbols. Sources of Information on Code 93: http://www.semiconductor.agilent.com/barcode/sg/Misc/code_93.html Official Spec, "NSI/AIM BC5-1995, USS" is available for US$45 from http://www.aimglobal.org/aimstore/ """ def validate(self): vval = "" self.valid = 1 for c in self.value.upper(): if c not in _patterns: self.valid = 0 continue vval = vval + c self.validated = vval return vval def encode(self): self.encoded = _encode93(self.validated) return self.encoded class Extended93(_Code93Base): """ Extended Code 93 is a convention for encoding the entire 128 character set using pairs of characters to represent the characters missing in Standard Code 93. It is very much like Extended Code 39 in that way. See Standard93 for arguments. """ def validate(self): vval = [] self.valid = 1 a = vval.append for c in self.value: if c not in _patterns and c not in _extended: self.valid = 0 continue a(c) self.validated = ''.join(vval) return self.validated def encode(self): self.encoded = "" for c in self.validated: if c in _patterns: self.encoded = self.encoded + c elif c in _extended: self.encoded = self.encoded + _extended[c] else: raise ValueError self.encoded = _encode93(self.encoded) return self.encoded def _humanText(self): return self.validated+self.encoded[-2:]
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/graphics/barcode/code93.py
0.510008
0.449332
code93.py
pypi
import re import itertools try: from itertools import zip_longest except: from itertools import izip_longest as zip_longest try: unicode except NameError: # No unicode in Python 3 unicode = str class QR: valid = None bits = None group = 0 def __init__(self, data): if self.valid and not self.valid(data): raise ValueError self.data = data def __len__(self): return len(self.data) @property def bitlength(self): if self.bits is None: return 0 q, r = divmod(len(self), len(self.bits)) return q * sum(self.bits) + sum(self.bits[:r]) def getLengthBits(self, ver): if 0 < ver < 10: return self.lengthbits[0] elif ver < 27: return self.lengthbits[1] elif ver < 41: return self.lengthbits[2] raise ValueError("Unknown version: " + ver) def getLength(self): return len(self.data) def __repr__(self): return repr(self.data) def write_header(self, buffer, version): buffer.put(self.mode, 4) lenbits = self.getLengthBits(version) if lenbits: buffer.put(len(self.data), lenbits ) def write(self, buffer, version): self.write_header(buffer, version) for g in zip_longest(*[iter(self.data)] * self.group): bits = 0 n = 0 for i in range(self.group): if g[i] is not None: n *= len(self.chars) n += self.chars.index(g[i]) bits += self.bits[i] buffer.put(n, bits) class QRNumber(QR): valid = re.compile(u'[0-9]*$').match chars = u'0123456789' bits = (4,3,3) group = 3 mode = 0x1 lengthbits = (10, 12, 14) class QRAlphaNum(QR): valid = re.compile(u'[-0-9A-Z $%*+-./:]*$').match chars = u'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:' bits = (6,5) group = 2 mode = 0x2 lengthbits = (9, 11, 13) class QR8bitByte(QR): bits = (8,) group = 1 mode = 0x4 lengthbits = (8, 16, 16) def __init__(self, data): if isinstance(data, unicode): self.data = data.encode('utf-8') # XXX This really needs an ECI too else: self.data = data # It'd better be byte data def write(self, buffer, version): self.write_header(buffer, version) for c in self.data: if isinstance(c, str): c = ord(c) buffer.put(c, 8) class QRKanji(QR): bits = (13,) group = 1 mode = 0x8 lengthbits = (8, 10, 12) def __init__(self, data): try: self.data = self.unicode_to_qrkanji(data) except UnicodeEncodeError: raise ValueError('Not valid kanji') def unicode_to_qrkanji(self, data): codes = [] for i,c in enumerate(data): try: c = c.encode('shift-jis') try: c,d = map(ord, c) except TypeError: # Python 3 c,d = c except UnicodeEncodeError as e: raise UnicodeEncodeError('qrkanji', data, i, i+1, e.args[4]) except ValueError: raise UnicodeEncodeError('qrkanji', data, i, i+1, 'illegal multibyte sequence') c = c << 8 | d if 0x8140 <= c <=0x9ffc: c -= 0x8140 c = (((c & 0xff00) >> 8) * 0xc0) + (c & 0xff) elif 0xe040 <= c <= 0xebbf: c -= 0xc140 c = (((c & 0xff00) >> 8) * 0xc0) + (c & 0xff) else: raise UnicodeEncodeError('qrkanji', data, i, i+1, 'illegal multibyte sequence') codes.append(c) return codes def write(self, buffer, version): self.write_header(buffer, version) for d in self.data: buffer.put(d, 13) class QRHanzi(QR): bits = (13,) group = 1 mode = 0xD lengthbits = (8, 10, 12) def __init__(self, data): try: self.data = self.unicode_to_qrhanzi(data) except UnicodeEncodeError: raise ValueError('Not valid hanzi') def unicode_to_qrhanzi(self, data): codes = [] for i,c in enumerate(data): try: c = c.encode('gb2312') try: c,d = map(ord, c) except TypeError: # Python 3 c,d = c except UnicodeEncodeError as e: raise UnicodeEncodeError('qrhanzi', data, i, i+1, e.args[4]) except ValueError: raise UnicodeEncodeError('qrhanzi', data, i, i+1, 'illegal multibyte sequence') c = c << 8 | d if 0xa1a1 <= c <=0xaafe: c -= 0xa1a1 c = (((c & 0xff00) >> 8) * 0x60) + (c & 0xff) elif 0xb0a1 <= c <= 0xfafe: c -= 0xa6a1 c = (((c & 0xff00) >> 8) * 0x60) + (c & 0xff) else: raise UnicodeEncodeError('qrhanzi', data, i, i+1, 'illegal multibyte sequence') codes.append(c) return codes def write_header(self, buffer, version): buffer.put(self.mode, 4) buffer.put(1, 4) # Subset 1: GB2312 encoding lenbits = self.getLengthBits(version) if lenbits: buffer.put(len(self.data), lenbits ) def write(self, buffer, version): self.write_header(buffer, version) for d in self.data: buffer.put(d, 13) # Special modes class QRECI(QR): mode = 0x7 lengthbits = (0, 0, 0) def __init__(self, data): if not 0 < data < 999999: # Spec says 999999, format supports up to 0x1fffff = 2097151 raise ValueError("ECI out of range") self.data = data def write(self, buffer, version): self.write_header(buffer, version) if self.data <= 0x7f: buffer.put(self.data, 8) elif self.data <= 0x3fff: buffer.put(self.data | 0x8000, 16) elif self.data <= 0x1fffff: buffer.put(self.data | 0xC00000, 24) class QRStructAppend(QR): mode = 0x3 lengthbits = (0, 0, 0) def __init__(self, part, total, parity): if not 0 < part <= 16: raise ValueError("part out of range [1,16]") if not 0 < total <= 16: raise ValueError("total out of range [1,16]") self.part = part self.total = total self.parity = parity def write(self, buffer, version): self.write_header(buffer, version) buffer.put(self.part, 4) buffer.put(self.total, 4) buffer.put(self.parity, 8) class QRFNC1First(QR): mode = 0x5 lengthbits = (0, 0, 0) def __init__(self): pass def write(self, buffer, version): self.write_header(buffer, version) class QRFNC1Second(QR): valid = re.compile('^([A-Za-z]|[0-9][0-9])$').match mode = 0x9 lengthbits = (0, 0, 0) def write(self, buffer, version): self.write_header(buffer, version) d = self.data if len(d) == 1: d = ord(d) + 100 else: d = int(d) buffer.put(d, 8) class QRCode: def __init__(self, version, errorCorrectLevel): self.version = version self.errorCorrectLevel = errorCorrectLevel self.modules = None self.moduleCount = 0 self.dataCache = None self.dataList = [] def addData(self, data): if isinstance(data, QR): newData = data else: for conv in (QRNumber, QRAlphaNum, QRKanji, QR8bitByte): try: newData = conv(data) break except ValueError: pass else: raise ValueError self.dataList.append(newData) self.dataCache = None def isDark(self, row, col): return self.modules[row][col] def getModuleCount(self): return self.moduleCount def calculate_version(self): # Calculate version for data to fit the QR Code capacity for version in range(1, 40): rsBlocks = QRRSBlock.getRSBlocks(version, self.errorCorrectLevel) totalDataCount = sum(block.dataCount for block in rsBlocks) length = 0 for data in self.dataList: length += 4 length += data.getLengthBits(version) length += data.bitlength if length <= totalDataCount * 8: break return version def make(self): if self.version is None: self.version = self.calculate_version() self.makeImpl(False, self.getBestMaskPattern()) def makeImpl(self, test, maskPattern): self.moduleCount = self.version * 4 + 17 self.modules = [ [False] * self.moduleCount for x in range(self.moduleCount) ] self.setupPositionProbePattern(0, 0) self.setupPositionProbePattern(self.moduleCount - 7, 0) self.setupPositionProbePattern(0, self.moduleCount - 7) self.setupPositionAdjustPattern() self.setupTimingPattern() self.setupTypeInfo(test, maskPattern) if (self.version >= 7): self.setupTypeNumber(test) if (self.dataCache == None): self.dataCache = QRCode.createData(self.version, self.errorCorrectLevel, self.dataList) self.mapData(self.dataCache, maskPattern) _positionProbePattern = [ [True, True, True, True, True, True, True], [True, False, False, False, False, False, True], [True, False, True, True, True, False, True], [True, False, True, True, True, False, True], [True, False, True, True, True, False, True], [True, False, False, False, False, False, True], [True, True, True, True, True, True, True], ] def setupPositionProbePattern(self, row, col): if row == 0: self.modules[row+7][col:col+7] = [False] * 7 if col == 0: self.modules[row+7][col+7] = False else: self.modules[row+7][col-1] = False else: # col == 0 self.modules[row-1][col:col+8] = [False] * 8 for r, data in enumerate(self._positionProbePattern): self.modules[row+r][col:col+7] = data if col == 0: self.modules[row+r][col+7] = False else: self.modules[row+r][col-1] = False def getBestMaskPattern(self): minLostPoint = 0 pattern = 0 for i in range(8): self.makeImpl(True, i); lostPoint = QRUtil.getLostPoint(self); if (i == 0 or minLostPoint > lostPoint): minLostPoint = lostPoint pattern = i return pattern def setupTimingPattern(self): for r in range(8, self.moduleCount - 8): self.modules[r][6] = (r % 2 == 0) self.modules[6][8:self.moduleCount - 8] = itertools.islice( itertools.cycle([True, False]), self.moduleCount - 16) _positionAdjustPattern = [ [True, True, True, True, True], [True, False, False, False, True], [True, False, True, False, True], [True, False, False, False, True], [True, True, True, True, True], ] def setupPositionAdjustPattern(self): pos = QRUtil.getPatternPosition(self.version) maxpos = self.moduleCount - 8 for row, col in itertools.product(pos, pos): if col <= 8 and (row <= 8 or row >= maxpos): continue elif col >= maxpos and row <= 8: continue for r, data in enumerate(self._positionAdjustPattern): self.modules[row + r - 2][col-2:col+3] = data def setupTypeNumber(self, test): bits = QRUtil.getBCHTypeNumber(self.version) for i in range(18): mod = (not test and ( (bits >> i) & 1) == 1) self.modules[i // 3][i % 3 + self.moduleCount - 8 - 3] = mod; for i in range(18): mod = (not test and ( (bits >> i) & 1) == 1) self.modules[i % 3 + self.moduleCount - 8 - 3][i // 3] = mod; def setupTypeInfo(self, test, maskPattern): data = (self.errorCorrectLevel << 3) | maskPattern bits = QRUtil.getBCHTypeInfo(data) # vertical for i in range(15): mod = (not test and ( (bits >> i) & 1) == 1) if (i < 6): self.modules[i][8] = mod elif (i < 8): self.modules[i + 1][8] = mod else: self.modules[self.moduleCount - 15 + i][8] = mod # horizontal for i in range(15): mod = (not test and ( (bits >> i) & 1) == 1); if (i < 8): self.modules[8][self.moduleCount - i - 1] = mod elif (i < 9): self.modules[8][15 - i - 1 + 1] = mod else: self.modules[8][15 - i - 1] = mod # fixed module self.modules[self.moduleCount - 8][8] = (not test) def _dataPosIterator(self): cols = itertools.chain(range(self.moduleCount - 1, 6, -2), range(5, 0, -2)) rows = (list(range(9, self.moduleCount - 8)), list(itertools.chain(range(6), range(7, self.moduleCount))), list(range(9, self.moduleCount))) rrows = tuple( list(reversed(r)) for r in rows) ppos = QRUtil.getPatternPosition(self.version) ppos = set(itertools.chain.from_iterable( (p-2, p-1, p, p+1, p+2) for p in ppos)) maxpos = self.moduleCount - 11 for col in cols: rows, rrows = rrows, rows if col <= 8: rowidx = 0 elif col >= self.moduleCount - 8: rowidx = 2 else: rowidx = 1 for row in rows[rowidx]: for c in range(2): c = col - c if self.version >= 7: if row < 6 and c >= self.moduleCount - 11: continue elif col < 6 and row >= self.moduleCount - 11: continue if row in ppos and c in ppos: if not (row < 11 and (c < 11 or c > maxpos) or c < 11 and (row < 11 or row > maxpos)): continue yield (c, row) _dataPosList = None def dataPosIterator(self): if not self._dataPosList: self._dataPosList = list(self._dataPosIterator()) return self._dataPosList def _dataBitIterator(self, data): for byte in data: for bit in [0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01]: yield bool(byte & bit) _dataBitList = None def dataBitIterator(self, data): if not self._dataBitList: self._dataBitList = list(self._dataBitIterator(data)) return iter(self._dataBitList) def mapData(self, data, maskPattern): bits = self.dataBitIterator(data) mask = QRUtil.getMask(maskPattern) for (col, row), dark in zip_longest(self.dataPosIterator(), bits, fillvalue=False): self.modules[row][col] = dark ^ mask(row, col) PAD0 = 0xEC PAD1 = 0x11 @staticmethod def createData(version, errorCorrectLevel, dataList): rsBlocks = QRRSBlock.getRSBlocks(version, errorCorrectLevel) buffer = QRBitBuffer(); for data in dataList: data.write(buffer, version) # calc num max data. totalDataCount = 0; for block in rsBlocks: totalDataCount += block.dataCount if (buffer.getLengthInBits() > totalDataCount * 8): raise Exception("code length overflow. (%d > %d)" % (buffer.getLengthInBits(), totalDataCount * 8)) # end code if (buffer.getLengthInBits() + 4 <= totalDataCount * 8): buffer.put(0, 4) # padding while (buffer.getLengthInBits() % 8 != 0): buffer.putBit(False) # padding while (True): if (buffer.getLengthInBits() >= totalDataCount * 8): break buffer.put(QRCode.PAD0, 8) if (buffer.getLengthInBits() >= totalDataCount * 8): break buffer.put(QRCode.PAD1, 8) return QRCode.createBytes(buffer, rsBlocks) @staticmethod def createBytes(buffer, rsBlocks): offset = 0 maxDcCount = 0 maxEcCount = 0 totalCodeCount = 0 dcdata = [] ecdata = [] for block in rsBlocks: totalCodeCount += block.totalCount dcCount = block.dataCount ecCount = block.totalCount - dcCount maxDcCount = max(maxDcCount, dcCount) maxEcCount = max(maxEcCount, ecCount) dcdata.append(buffer.buffer[offset:offset+dcCount]) offset += dcCount rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount) rawPoly = QRPolynomial(dcdata[-1], rsPoly.getLength() - 1) modPoly = rawPoly.mod(rsPoly) rLen = rsPoly.getLength() - 1 mLen = modPoly.getLength() ecdata.append([ (modPoly.get(i) if i >= 0 else 0) for i in range(mLen - rLen, mLen) ]) data = [ d for dd in itertools.chain( zip_longest(*dcdata), zip_longest(*ecdata)) for d in dd if d is not None] return data class QRErrorCorrectLevel: L = 1 M = 0 Q = 3 H = 2 class QRMaskPattern: PATTERN000 = 0 PATTERN001 = 1 PATTERN010 = 2 PATTERN011 = 3 PATTERN100 = 4 PATTERN101 = 5 PATTERN110 = 6 PATTERN111 = 7 class QRUtil(object): PATTERN_POSITION_TABLE = [ [], [6, 18], [6, 22], [6, 26], [6, 30], [6, 34], [6, 22, 38], [6, 24, 42], [6, 26, 46], [6, 28, 50], [6, 30, 54], [6, 32, 58], [6, 34, 62], [6, 26, 46, 66], [6, 26, 48, 70], [6, 26, 50, 74], [6, 30, 54, 78], [6, 30, 56, 82], [6, 30, 58, 86], [6, 34, 62, 90], [6, 28, 50, 72, 94], [6, 26, 50, 74, 98], [6, 30, 54, 78, 102], [6, 28, 54, 80, 106], [6, 32, 58, 84, 110], [6, 30, 58, 86, 114], [6, 34, 62, 90, 118], [6, 26, 50, 74, 98, 122], [6, 30, 54, 78, 102, 126], [6, 26, 52, 78, 104, 130], [6, 30, 56, 82, 108, 134], [6, 34, 60, 86, 112, 138], [6, 30, 58, 86, 114, 142], [6, 34, 62, 90, 118, 146], [6, 30, 54, 78, 102, 126, 150], [6, 24, 50, 76, 102, 128, 154], [6, 28, 54, 80, 106, 132, 158], [6, 32, 58, 84, 110, 136, 162], [6, 26, 54, 82, 110, 138, 166], [6, 30, 58, 86, 114, 142, 170] ] G15 = ((1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0)) G18 = ((1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0)) G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1) @staticmethod def getBCHTypeInfo(data): d = data << 10; while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) >= 0): d ^= (QRUtil.G15 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) ) ) return ( (data << 10) | d) ^ QRUtil.G15_MASK @staticmethod def getBCHTypeNumber(data): d = data << 12; while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) >= 0): d ^= (QRUtil.G18 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) ) ) return (data << 12) | d @staticmethod def getBCHDigit(data): digit = 0; while (data != 0): digit += 1 data >>= 1 return digit @staticmethod def getPatternPosition(version): return QRUtil.PATTERN_POSITION_TABLE[version - 1] maskPattern = { 0: lambda i,j: (i + j) % 2 == 0, 1: lambda i,j: i % 2 == 0, 2: lambda i,j: j % 3 == 0, 3: lambda i,j: (i + j) % 3 == 0, 4: lambda i,j: (i // 2 + j // 3) % 2 == 0, 5: lambda i,j: (i*j)%2 + (i*j)%3 == 0, 6: lambda i,j: ( (i * j) % 2 + (i * j) % 3) % 2 == 0, 7: lambda i,j: ( (i * j) % 3 + (i + j) % 2) % 2 == 0 } @classmethod def getMask(cls, maskPattern): return cls.maskPattern[maskPattern] @staticmethod def getErrorCorrectPolynomial(errorCorrectLength): a = QRPolynomial([1], 0); for i in range(errorCorrectLength): a = a.multiply(QRPolynomial([1, QRMath.gexp(i)], 0) ) return a @classmethod def maskScoreRule1vert(cls, modules): score = 0 lastCount = [0] lastRow = None for row in modules: # Vertical patterns if lastRow: changed = [a ^ b for a,b in zip(row, lastRow)] scores = [a and (b-4+3) for a,b in zip_longest(changed, lastCount, fillvalue=0) if b >= 4] score += sum(scores) lastCount = [0 if a else b + 1 for a,b in zip_longest(changed, lastCount, fillvalue=0)] lastRow = row score += sum([b-4+3 for b in lastCount if b >= 4]) # final counts return score @classmethod def maskScoreRule2(cls, modules): score = 0 lastRow = modules[0] for row in modules[1:]: lastCol0, lastCol1 = row[0], lastRow[0] for col0, col1 in zip(row[1:], lastRow[1:]): if col0 == col1 == lastCol0 == lastCol1: score += 3 lastCol0, lastCol1 = col0, col1 lastRow = row return score @classmethod def maskScoreRule3hor( cls, modules, pattern = [True, False, True, True, True, False, True, False, False, False, False]): patternlen = len(pattern) score = 0 for row in modules: j = 0 maxj = len(row) - patternlen while j < maxj: if row[j:j+patternlen] == pattern: score += 40 j += patternlen else: j += 1 return score @classmethod def maskScoreRule4(cls, modules): cellCount = len(modules)**2 count = sum(sum(row) for row in modules) return 10 * (abs(100 * count // cellCount - 50) // 5) @classmethod def getLostPoint(cls, qrCode): lostPoint = 0; # LEVEL1 lostPoint += cls.maskScoreRule1vert(qrCode.modules) lostPoint += cls.maskScoreRule1vert(zip(*qrCode.modules)) # LEVEL2 lostPoint += cls.maskScoreRule2(qrCode.modules) # LEVEL3 lostPoint += cls.maskScoreRule3hor(qrCode.modules) lostPoint += cls.maskScoreRule3hor(zip(*qrCode.modules)) # LEVEL4 lostPoint += cls.maskScoreRule4(qrCode.modules) return lostPoint class QRMath: @staticmethod def glog(n): if (n < 1): raise Exception("glog(" + n + ")") return LOG_TABLE[n]; @staticmethod def gexp(n): while n < 0: n += 255 while n >= 256: n -= 255 return EXP_TABLE[n]; EXP_TABLE = [x for x in range(256)] LOG_TABLE = [x for x in range(256)] for i in range(8): EXP_TABLE[i] = 1 << i; for i in range(8, 256): EXP_TABLE[i] = (EXP_TABLE[i - 4] ^ EXP_TABLE[i - 5] ^ EXP_TABLE[i - 6] ^ EXP_TABLE[i - 8]) for i in range(255): LOG_TABLE[EXP_TABLE[i] ] = i class QRPolynomial: def __init__(self, num, shift): if (len(num) == 0): raise Exception(len(num) + "/" + shift) offset = 0 while offset < len(num) and num[offset] == 0: offset += 1 self.num = num[offset:] + [0]*shift def get(self, index): return self.num[index] def getLength(self): return len(self.num) def multiply(self, e): num = [0] * (self.getLength() + e.getLength() - 1); for i in range(self.getLength()): for j in range(e.getLength()): num[i + j] ^= QRMath.gexp(QRMath.glog(self.get(i) ) + QRMath.glog(e.get(j) ) ) return QRPolynomial(num, 0); def mod(self, e): if (self.getLength() < e.getLength()): return self; ratio = QRMath.glog(self.num[0] ) - QRMath.glog(e.num[0] ) num = [nn ^ QRMath.gexp(QRMath.glog(en) + ratio) for nn,en in zip(self.num, e.num)] num += self.num[e.getLength():] # recursive call return QRPolynomial(num, 0).mod(e); class QRRSBlock: RS_BLOCK_TABLE = [ # L # M # Q # H # 1 [1, 26, 19], [1, 26, 16], [1, 26, 13], [1, 26, 9], # 2 [1, 44, 34], [1, 44, 28], [1, 44, 22], [1, 44, 16], # 3 [1, 70, 55], [1, 70, 44], [2, 35, 17], [2, 35, 13], # 4 [1, 100, 80], [2, 50, 32], [2, 50, 24], [4, 25, 9], # 5 [1, 134, 108], [2, 67, 43], [2, 33, 15, 2, 34, 16], [2, 33, 11, 2, 34, 12], # 6 [2, 86, 68], [4, 43, 27], [4, 43, 19], [4, 43, 15], # 7 [2, 98, 78], [4, 49, 31], [2, 32, 14, 4, 33, 15], [4, 39, 13, 1, 40, 14], # 8 [2, 121, 97], [2, 60, 38, 2, 61, 39], [4, 40, 18, 2, 41, 19], [4, 40, 14, 2, 41, 15], # 9 [2, 146, 116], [3, 58, 36, 2, 59, 37], [4, 36, 16, 4, 37, 17], [4, 36, 12, 4, 37, 13], # 10 [2, 86, 68, 2, 87, 69], [4, 69, 43, 1, 70, 44], [6, 43, 19, 2, 44, 20], [6, 43, 15, 2, 44, 16], # 11 [4, 101, 81], [1, 80, 50, 4, 81, 51], [4, 50, 22, 4, 51, 23], [3, 36, 12, 8, 37, 13], # 12 [2, 116, 92, 2, 117, 93], [6, 58, 36, 2, 59, 37], [4, 46, 20, 6, 47, 21], [7, 42, 14, 4, 43, 15], # 13 [4, 133, 107], [8, 59, 37, 1, 60, 38], [8, 44, 20, 4, 45, 21], [12, 33, 11, 4, 34, 12], # 14 [3, 145, 115, 1, 146, 116], [4, 64, 40, 5, 65, 41], [11, 36, 16, 5, 37, 17], [11, 36, 12, 5, 37, 13], # 15 [5, 109, 87, 1, 110, 88], [5, 65, 41, 5, 66, 42], [5, 54, 24, 7, 55, 25], [11, 36, 12], # 16 [5, 122, 98, 1, 123, 99], [7, 73, 45, 3, 74, 46], [15, 43, 19, 2, 44, 20], [3, 45, 15, 13, 46, 16], # 17 [1, 135, 107, 5, 136, 108], [10, 74, 46, 1, 75, 47], [1, 50, 22, 15, 51, 23], [2, 42, 14, 17, 43, 15], # 18 [5, 150, 120, 1, 151, 121], [9, 69, 43, 4, 70, 44], [17, 50, 22, 1, 51, 23], [2, 42, 14, 19, 43, 15], # 19 [3, 141, 113, 4, 142, 114], [3, 70, 44, 11, 71, 45], [17, 47, 21, 4, 48, 22], [9, 39, 13, 16, 40, 14], # 20 [3, 135, 107, 5, 136, 108], [3, 67, 41, 13, 68, 42], [15, 54, 24, 5, 55, 25], [15, 43, 15, 10, 44, 16], # 21 [4, 144, 116, 4, 145, 117], [17, 68, 42], [17, 50, 22, 6, 51, 23], [19, 46, 16, 6, 47, 17], # 22 [2, 139, 111, 7, 140, 112], [17, 74, 46], [7, 54, 24, 16, 55, 25], [34, 37, 13], # 23 [4, 151, 121, 5, 152, 122], [4, 75, 47, 14, 76, 48], [11, 54, 24, 14, 55, 25], [16, 45, 15, 14, 46, 16], # 24 [6, 147, 117, 4, 148, 118], [6, 73, 45, 14, 74, 46], [11, 54, 24, 16, 55, 25], [30, 46, 16, 2, 47, 17], # 25 [8, 132, 106, 4, 133, 107], [8, 75, 47, 13, 76, 48], [7, 54, 24, 22, 55, 25], [22, 45, 15, 13, 46, 16], # 26 [10, 142, 114, 2, 143, 115], [19, 74, 46, 4, 75, 47], [28, 50, 22, 6, 51, 23], [33, 46, 16, 4, 47, 17], # 27 [8, 152, 122, 4, 153, 123], [22, 73, 45, 3, 74, 46], [8, 53, 23, 26, 54, 24], [12, 45, 15, 28, 46, 16], # 28 [3, 147, 117, 10, 148, 118], [3, 73, 45, 23, 74, 46], [4, 54, 24, 31, 55, 25], [11, 45, 15, 31, 46, 16], # 29 [7, 146, 116, 7, 147, 117], [21, 73, 45, 7, 74, 46], [1, 53, 23, 37, 54, 24], [19, 45, 15, 26, 46, 16], # 30 [5, 145, 115, 10, 146, 116], [19, 75, 47, 10, 76, 48], [15, 54, 24, 25, 55, 25], [23, 45, 15, 25, 46, 16], # 31 [13, 145, 115, 3, 146, 116], [2, 74, 46, 29, 75, 47], [42, 54, 24, 1, 55, 25], [23, 45, 15, 28, 46, 16], # 32 [17, 145, 115], [10, 74, 46, 23, 75, 47], [10, 54, 24, 35, 55, 25], [19, 45, 15, 35, 46, 16], # 33 [17, 145, 115, 1, 146, 116], [14, 74, 46, 21, 75, 47], [29, 54, 24, 19, 55, 25], [11, 45, 15, 46, 46, 16], # 34 [13, 145, 115, 6, 146, 116], [14, 74, 46, 23, 75, 47], [44, 54, 24, 7, 55, 25], [59, 46, 16, 1, 47, 17], # 35 [12, 151, 121, 7, 152, 122], [12, 75, 47, 26, 76, 48], [39, 54, 24, 14, 55, 25], [22, 45, 15, 41, 46, 16], # 36 [6, 151, 121, 14, 152, 122], [6, 75, 47, 34, 76, 48], [46, 54, 24, 10, 55, 25], [2, 45, 15, 64, 46, 16], # 37 [17, 152, 122, 4, 153, 123], [29, 74, 46, 14, 75, 47], [49, 54, 24, 10, 55, 25], [24, 45, 15, 46, 46, 16], # 38 [4, 152, 122, 18, 153, 123], [13, 74, 46, 32, 75, 47], [48, 54, 24, 14, 55, 25], [42, 45, 15, 32, 46, 16], # 39 [20, 147, 117, 4, 148, 118], [40, 75, 47, 7, 76, 48], [43, 54, 24, 22, 55, 25], [10, 45, 15, 67, 46, 16], # 40 [19, 148, 118, 6, 149, 119], [18, 75, 47, 31, 76, 48], [34, 54, 24, 34, 55, 25], [20, 45, 15, 61, 46, 16] ] def __init__(self, totalCount, dataCount): self.totalCount = totalCount self.dataCount = dataCount @staticmethod def getRSBlocks(version, errorCorrectLevel): rsBlock = QRRSBlock.getRsBlockTable(version, errorCorrectLevel); if rsBlock == None: raise Exception("bad rs block @ version:" + version + "/errorCorrectLevel:" + errorCorrectLevel) length = len(rsBlock) // 3 list = [] for i in range(length): count = rsBlock[i * 3 + 0] totalCount = rsBlock[i * 3 + 1] dataCount = rsBlock[i * 3 + 2] for j in range(count): list.append(QRRSBlock(totalCount, dataCount)) return list; @staticmethod def getRsBlockTable(version, errorCorrectLevel): if errorCorrectLevel == QRErrorCorrectLevel.L: return QRRSBlock.RS_BLOCK_TABLE[(version - 1) * 4 + 0]; elif errorCorrectLevel == QRErrorCorrectLevel.M: return QRRSBlock.RS_BLOCK_TABLE[(version - 1) * 4 + 1]; elif errorCorrectLevel == QRErrorCorrectLevel.Q: return QRRSBlock.RS_BLOCK_TABLE[(version - 1) * 4 + 2]; elif errorCorrectLevel == QRErrorCorrectLevel.H: return QRRSBlock.RS_BLOCK_TABLE[(version - 1) * 4 + 3]; else: return None; class QRBitBuffer: def __init__(self): self.buffer = [] self.length = 0 def __repr__(self): return ".".join([str(n) for n in self.buffer]) def get(self, index): bufIndex = index // 8 return ( (self.buffer[bufIndex] >> (7 - index % 8) ) & 1) == 1 def put(self, num, length): for i in range(length): self.putBit( ( (num >> (length - i - 1) ) & 1) == 1) def getLengthInBits(self): return self.length def putBit(self, bit): bufIndex = self.length // 8 if len(self.buffer) <= bufIndex: self.buffer.append(0) if bit: self.buffer[bufIndex] |= (0x80 >> (self.length % 8) ) self.length += 1
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/graphics/barcode/qrencoder.py
0.443118
0.189184
qrencoder.py
pypi
__version__='3.3.0' __all__ = ('USPS_4State',) from reportlab.lib.colors import black from reportlab.graphics.barcode.common import Barcode from reportlab.lib.utils import asNative class USPS_4State(Barcode): ''' USPS 4-State OneView (TM) barcode. All info from USPS-B-3200A ''' _widthSize = 1 _heightSize = 1 _fontSize = 11 _humanReadable = 0 tops = dict( F = (0.067,0.115), T = (0.021,0.040), A = (0.067,0.115), D = (0.021,0.040), ) bottoms = dict( F = (-0.067,-0.115), D = (-0.067,-0.115), T = (-0.021,-0.040), A = (-0.021,-0.040), ) dimensions = dict( width = (0.015, 0.025), pitch = (0.0416,0.050), hcz = (0.125,0.125), vcz = (0.040,0.040), ) def __init__(self,value='01234567094987654321',routing='',**kwd): self._init() value = str(value) if isinstance(value,int) else asNative(value) self._tracking = value self._routing = routing self._setKeywords(**kwd) def _init(self): self._bvalue = None self._codewords = None self._characters = None self._barcodes = None def scale(kind,D,s): V = D[kind] return 72*(V[0]*(1-s)+s*V[1]) scale = staticmethod(scale) def tracking(self,tracking): self._init() self._tracking = tracking tracking = property(lambda self: self._tracking,tracking) def routing(self,routing): self._init() self._routing = routing routing = property(lambda self: self._routing,routing) def widthSize(self,value): self._sized = None self._widthSize = value widthSize = property(lambda self: self._widthSize,widthSize) def heightSize(self,value): self._sized = None self._heightSize = value heightSize = property(lambda self: self._heightSize,heightSize) def fontSize(self,value): self._sized = None self._fontSize = value fontSize = property(lambda self: self._fontSize,fontSize) def humanReadable(self,value): self._sized = None self._humanReadable = value humanReadable = property(lambda self: self._humanReadable,humanReadable) def binary(self): '''convert the 4 state string values to binary >>> print hex(USPS_4State('01234567094987654321','').binary) 0x1122103B5C2004B1L >>> print hex(USPS_4State('01234567094987654321','01234').binary) 0xD138A87BAB5CF3804B1L >>> print hex(USPS_4State('01234567094987654321','012345678').binary) 0x202BDC097711204D21804B1L >>> print hex(USPS_4State('01234567094987654321','01234567891').binary) 0x16907B2A24ABC16A2E5C004B1L ''' value = self._bvalue if not value: routing = self.routing n = len(routing) try: if n==0: value = 0 elif n==5: value = int(routing)+1 elif n==9: value = int(routing)+100001 elif n==11: value = int(routing)+1000100001 else: raise ValueError except: raise ValueError('Problem converting %s, routing code must be 0, 5, 9 or 11 digits' % routing) tracking = self.tracking svalue = tracking[0:2] try: value *= 10 value += int(svalue[0]) value *= 5 value += int(svalue[1]) except: raise ValueError('Problem converting %s, barcode identifier must be 2 digits' % svalue) i = 2 for name,nd in (('special services',3), ('customer identifier',6), ('sequence number',9)): j = i i += nd svalue = tracking[j:i] try: if len(svalue)!=nd: raise ValueError for j in range(nd): value *= 10 value += int(svalue[j]) except: raise ValueError('Problem converting %s, %s must be %d digits' % (svalue,name,nd)) self._bvalue = value return value binary = property(binary) def codewords(self): '''convert binary value into codewords >>> print USPS_4State('01234567094987654321','01234567891').codewords) (673, 787, 607, 1022, 861, 19, 816, 1294, 35, 602) ''' if not self._codewords: value = self.binary A, J = divmod(value,636) A, I = divmod(A,1365) A, H = divmod(A,1365) A, G = divmod(A,1365) A, F = divmod(A,1365) A, E = divmod(A,1365) A, D = divmod(A,1365) A, C = divmod(A,1365) A, B = divmod(A,1365) assert 0<=A<=658, 'improper value %s passed to _2codewords A-->%s' % (hex(int(value)),A) self._fcs = _crc11(value) if self._fcs&1024: A += 659 J *= 2 self._codewords = tuple(map(int,(A,B,C,D,E,F,G,H,I,J))) return self._codewords codewords = property(codewords) def table1(self): self.__class__.table1 = _initNof13Table(5,1287) return self.__class__.table1 table1 = property(table1) def table2(self): self.__class__.table2 = _initNof13Table(2,78) return self.__class__.table2 table2 = property(table2) def characters(self): ''' convert own codewords to characters >>> print ' '.join(hex(c)[2:] for c in USPS_4State('01234567094987654321','01234567891').characters) dcb 85c 8e4 b06 6dd 1740 17c6 1200 123f 1b2b ''' if not self._characters: codewords = self.codewords fcs = self._fcs C = [] aC = C.append table1 = self.table1 table2 = self.table2 for i in range(10): cw = codewords[i] if cw<=1286: c = table1[cw] else: c = table2[cw-1287] if (fcs>>i)&1: c = ~c & 0x1fff aC(c) self._characters = tuple(C) return self._characters characters = property(characters) def barcodes(self): '''Get 4 state bar codes for current routing and tracking >>> print USPS_4State('01234567094987654321','01234567891').barcodes AADTFFDFTDADTAADAATFDTDDAAADDTDTTDAFADADDDTFFFDDTTTADFAAADFTDAADA ''' if not self._barcodes: C = self.characters B = [] aB = B.append bits2bars = self._bits2bars for dc,db,ac,ab in self.table4: aB(bits2bars[((C[dc]>>db)&1)+2*((C[ac]>>ab)&1)]) self._barcodes = ''.join(B) return self._barcodes barcodes = property(barcodes) table4 = ((7, 2, 4, 3), (1, 10, 0, 0), (9, 12, 2, 8), (5, 5, 6, 11), (8, 9, 3, 1), (0, 1, 5, 12), (2, 5, 1, 8), (4, 4, 9, 11), (6, 3, 8, 10), (3, 9, 7, 6), (5, 11, 1, 4), (8, 5, 2, 12), (9, 10, 0, 2), (7, 1, 6, 7), (3, 6, 4, 9), (0, 3, 8, 6), (6, 4, 2, 7), (1, 1, 9, 9), (7, 10, 5, 2), (4, 0, 3, 8), (6, 2, 0, 4), (8, 11, 1, 0), (9, 8, 3, 12), (2, 6, 7, 7), (5, 1, 4, 10), (1, 12, 6, 9), (7, 3, 8, 0), (5, 8, 9, 7), (4, 6, 2, 10), (3, 4, 0, 5), (8, 4, 5, 7), (7, 11, 1, 9), (6, 0, 9, 6), (0, 6, 4, 8), (2, 1, 3, 2), (5, 9, 8, 12), (4, 11, 6, 1), (9, 5, 7, 4), (3, 3, 1, 2), (0, 7, 2, 0), (1, 3, 4, 1), (6, 10, 3, 5), (8, 7, 9, 4), (2, 11, 5, 6), (0, 8, 7, 12), (4, 2, 8, 1), (5, 10, 3, 0), (9, 3, 0, 9), (6, 5, 2, 4), (7, 8, 1, 7), (5, 0, 4, 5), (2, 3, 0, 10), (6, 12, 9, 2), (3, 11, 1, 6), (8, 8, 7, 9), (5, 4, 0, 11), (1, 5, 2, 2), (9, 1, 4, 12), (8, 3, 6, 6), (7, 0, 3, 7), (4, 7, 7, 5), (0, 12, 1, 11), (2, 9, 9, 0), (6, 8, 5, 3), (3, 10, 8, 2)) _bits2bars = 'T','D','A','F' horizontalClearZone = property(lambda self: self.scale('hcz',self.dimensions,self.widthScale)) verticalClearZone = property(lambda self: self.scale('vcz',self.dimensions,self.heightScale)) pitch = property(lambda self: self.scale('pitch',self.dimensions,self.widthScale)) barWidth = property(lambda self: self.scale('width',self.dimensions,self.widthScale)) barHeight = property(lambda self: self.scale('F',self.tops,self.heightScale) - self.scale('F',self.bottoms,self.heightScale)) widthScale = property(lambda self: min(1,max(0,self.widthSize))) heightScale = property(lambda self: min(1,max(0,self.heightSize))) def width(self): self.computeSize() return self._width width = property(width) def height(self): self.computeSize() return self._height height = property(height) def computeSize(self): if not getattr(self,'_sized',None): ws = self.widthScale hs = self.heightScale barHeight = self.barHeight barWidth = self.barWidth pitch = self.pitch hcz = self.horizontalClearZone vcz = self.verticalClearZone self._width = 2*hcz + barWidth + 64*pitch self._height = 2*vcz+barHeight if self.humanReadable: self._height += self.fontSize*1.2+vcz self._sized = True def wrap(self,aW,aH): self.computeSize() return self.width, self.height def _getBarVInfo(self,y0=0): vInfo = {} hs = self.heightScale for b in ('T','D','A','F'): y = self.scale(b,self.bottoms,hs)+y0 vInfo[b] = y,self.scale(b,self.tops,hs)+y0 - y return vInfo def draw(self): self.computeSize() hcz = self.horizontalClearZone vcz = self.verticalClearZone bw = self.barWidth x = hcz y0 = vcz+self.barHeight*0.5 dw = self.pitch vInfo = self._getBarVInfo(y0) for b in self.barcodes: yb, hb = vInfo[b] self.rect(x,yb,bw,hb) x += dw self.drawHumanReadable() def value(self): tracking = self.tracking routing = self.routing routing = routing and (routing,) or () return ' '.join((tracking[0:2],tracking[2:5],tracking[5:11],tracking[11:])+routing) value = property(value,lambda self,value: self.__dict__.__setitem__('tracking',value)) def drawHumanReadable(self): if self.humanReadable: hcz = self.horizontalClearZone vcz = self.verticalClearZone fontName = self.fontName fontSize = self.fontSize y = self.barHeight+2*vcz+0.2*fontSize self.annotate(hcz,y,self.value,fontName,fontSize) def annotate(self,x,y,text,fontName,fontSize,anchor='middle'): Barcode.annotate(self,x,y,text,fontName,fontSize,anchor='start') def _crc11(value): ''' >>> print ' '.join(hex(_crc11(USPS_4State('01234567094987654321',x).binary)) for x in ('','01234','012345678','01234567891')) 0x51 0x65 0x606 0x751 ''' bytes = hex(int(value))[2:-1] bytes = '0'*(26-len(bytes))+bytes gp = 0x0F35 fcs = 0x07FF data = int(bytes[:2],16)<<5 for b in range(2,8): if (fcs ^ data)&0x400: fcs = (fcs<<1)^gp else: fcs = fcs<<1 fcs &= 0x7ff data <<= 1 for x in range(2,2*13,2): data = int(bytes[x:x+2],16)<<3 for b in range(8): if (fcs ^ data)&0x400: fcs = (fcs<<1)^gp else: fcs = fcs<<1 fcs &= 0x7ff data <<= 1 return fcs def _ru13(i): '''reverse unsigned 13 bit number >>> print _ru13(7936), _ru13(31), _ru13(47), _ru13(7808) 31 7936 7808 47 ''' r = 0 for x in range(13): r <<= 1 r |= i & 1 i >>= 1 return r def _initNof13Table(N,lenT): '''create and return table of 13 bit values with N bits on >>> T = _initNof13Table(5,1287) >>> print ' '.join('T[%d]=%d' % (i, T[i]) for i in (0,1,2,3,4,1271,1272,1284,1285,1286)) T[0]=31 T[1]=7936 T[2]=47 T[3]=7808 T[4]=55 T[1271]=6275 T[1272]=6211 T[1284]=856 T[1285]=744 T[1286]=496 ''' T = lenT*[None] l = 0 u = lenT-1 for c in range(8192): bc = 0 for b in range(13): bc += (c&(1<<b))!=0 if bc!=N: continue r = _ru13(c) if r<c: continue #we already looked at this pair if r==c: T[u] = c u -= 1 else: T[l] = c l += 1 T[l] = r l += 1 assert l==(u+1), 'u+1(%d)!=l(%d) for %d of 13 table' % (u+1,l,N) return T def _test(): import doctest return doctest.testmod() if __name__ == "__main__": _test()
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/graphics/barcode/usps4s.py
0.432063
0.232343
usps4s.py
pypi
from reportlab.graphics.barcode.code39 import Standard39 from reportlab.lib import colors from reportlab.lib.units import cm from string import digits as string_digits from reportlab.lib.utils import ascii_uppercase class BaseLTOLabel(Standard39) : """ Base class for LTO labels. Specification taken from "IBM LTO Ultrium Cartridge Label Specification, Revision 3" available on May 14th 2008 from : http://www-1.ibm.com/support/docview.wss?rs=543&context=STCVQ6R&q1=ssg1*&uid=ssg1S7000429&loc=en_US&cs=utf-8&lang=en+en """ LABELWIDTH = 7.9 * cm LABELHEIGHT = 1.7 * cm LABELROUND = 0.15 * cm CODERATIO = 2.75 CODENOMINALWIDTH = 7.4088 * cm CODEBARHEIGHT = 1.11 * cm CODEBARWIDTH = 0.0432 * cm CODEGAP = CODEBARWIDTH CODELQUIET = 10 * CODEBARWIDTH CODERQUIET = 10 * CODEBARWIDTH def __init__(self, prefix="", number=None, subtype="1", border=None, checksum=False, availheight=None) : """ Initializes an LTO label. prefix : Up to six characters from [A-Z][0-9]. Defaults to "". number : Label's number or None. Defaults to None. subtype : LTO subtype string , e.g. "1" for LTO1. Defaults to "1". border : None, or the width of the label's border. Defaults to None. checksum : Boolean indicates if checksum char has to be printed. Defaults to False. availheight : Available height on the label, or None for automatic. Defaults to None. """ self.height = max(availheight, self.CODEBARHEIGHT) self.border = border if (len(subtype) != 1) \ or (subtype not in ascii_uppercase + string_digits) : raise ValueError("Invalid subtype '%s'" % subtype) if ((not number) and (len(prefix) > 6)) \ or not prefix.isalnum() : raise ValueError("Invalid prefix '%s'" % prefix) label = "%sL%s" % ((prefix + str(number or 0).zfill(6 - len(prefix)))[:6], subtype) if len(label) != 8 : raise ValueError("Invalid set of parameters (%s, %s, %s)" \ % (prefix, number, subtype)) self.label = label Standard39.__init__(self, label, ratio=self.CODERATIO, barHeight=self.height, barWidth=self.CODEBARWIDTH, gap=self.CODEGAP, lquiet=self.CODELQUIET, rquiet=self.CODERQUIET, quiet=True, checksum=checksum) def drawOn(self, canvas, x, y) : """Draws the LTO label onto the canvas.""" canvas.saveState() canvas.translate(x, y) if self.border : canvas.setLineWidth(self.border) canvas.roundRect(0, 0, self.LABELWIDTH, self.LABELHEIGHT, self.LABELROUND) Standard39.drawOn(self, canvas, (self.LABELWIDTH-self.CODENOMINALWIDTH)/2.0, self.LABELHEIGHT-self.height) canvas.restoreState() class VerticalLTOLabel(BaseLTOLabel) : """ A class for LTO labels with rectangular blocks around the tape identifier. """ LABELFONT = ("Helvetica-Bold", 14) BLOCKWIDTH = 1*cm BLOCKHEIGHT = 0.45*cm LINEWIDTH = 0.0125 NBBLOCKS = 7 COLORSCHEME = ("red", "yellow", "lightgreen", "lightblue", "grey", "orangered", "pink", "darkgreen", "orange", "purple") def __init__(self, *args, **kwargs) : """ Initializes the label. colored : boolean to determine if blocks have to be colorized. """ if "colored" in kwargs: self.colored = kwargs["colored"] del kwargs["colored"] else : self.colored = False kwargs["availheight"] = self.LABELHEIGHT-self.BLOCKHEIGHT BaseLTOLabel.__init__(self, *args, **kwargs) def drawOn(self, canvas, x, y) : """Draws some blocks around the identifier's characters.""" BaseLTOLabel.drawOn(self, canvas, x, y) canvas.saveState() canvas.setLineWidth(self.LINEWIDTH) canvas.setStrokeColorRGB(0, 0, 0) canvas.translate(x, y) xblocks = (self.LABELWIDTH-(self.NBBLOCKS*self.BLOCKWIDTH))/2.0 for i in range(self.NBBLOCKS) : (font, size) = self.LABELFONT newfont = self.LABELFONT if i == (self.NBBLOCKS - 1) : part = self.label[i:] (font, size) = newfont size /= 2.0 newfont = (font, size) else : part = self.label[i] canvas.saveState() canvas.translate(xblocks+(i*self.BLOCKWIDTH), 0) if self.colored and part.isdigit() : canvas.setFillColorRGB(*getattr(colors, self.COLORSCHEME[int(part)], colors.Color(1, 1, 1)).rgb()) else: canvas.setFillColorRGB(1, 1, 1) canvas.rect(0, 0, self.BLOCKWIDTH, self.BLOCKHEIGHT, fill=True) canvas.translate((self.BLOCKWIDTH+canvas.stringWidth(part, *newfont))/2.0, (self.BLOCKHEIGHT/2.0)) canvas.rotate(90.0) canvas.setFont(*newfont) canvas.setFillColorRGB(0, 0, 0) canvas.drawCentredString(0, 0, part) canvas.restoreState() canvas.restoreState() def test() : """Test this.""" from reportlab.pdfgen.canvas import Canvas from reportlab.lib import pagesizes canvas = Canvas("labels.pdf", pagesize=pagesizes.A4) canvas.setFont("Helvetica", 30) (width, height) = pagesizes.A4 canvas.drawCentredString(width/2.0, height-4*cm, "Sample LTO labels") xpos = xorig = 2 * cm ypos = yorig = 2 * cm colwidth = 10 * cm lineheight = 3.9 * cm count = 1234 BaseLTOLabel("RL", count, "3").drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 BaseLTOLabel("RL", count, "3", border=0.0125).drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 VerticalLTOLabel("RL", count, "3").drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 VerticalLTOLabel("RL", count, "3", border=0.0125).drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 VerticalLTOLabel("RL", count, "3", colored=True).drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 VerticalLTOLabel("RL", count, "3", border=0.0125, colored=True).drawOn(canvas, xpos, ypos) canvas.showPage() canvas.save() if __name__ == "__main__" : test()
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/graphics/barcode/lto.py
0.736401
0.256436
lto.py
pypi
__all__ = ('QrCodeWidget') import itertools from reportlab.platypus.flowables import Flowable from reportlab.graphics.shapes import Group, Rect from reportlab.lib import colors from reportlab.lib.validators import isNumber, isNumberOrNone, isColor, isString, Validator from reportlab.lib.attrmap import AttrMap, AttrMapValue from reportlab.graphics.widgetbase import Widget from reportlab.lib.units import mm try: from reportlab.lib.utils import asUnicodeEx, isUnicode except ImportError: # ReportLab 2.x compatibility def asUnicodeEx(v, enc='utf8'): if isinstance(v, unicode): return v if isinstance(v, str): return v.decode(enc) return str(v).decode(enc) def isUnicode(v): return isinstance(v, unicode) from reportlab.graphics.barcode import qrencoder class isLevel(Validator): def test(self, x): return x in ['L', 'M', 'Q', 'H'] isLevel = isLevel() class isUnicodeOrQRList(Validator): def _test(self, x): if isUnicode(x): return True if all(isinstance(v, qrencoder.QR) for v in x): return True return False def test(self, x): return self._test(x) or self.normalizeTest(x) def normalize(self, x): if self._test(x): return x try: return asUnicodeEx(x) except UnicodeError: raise ValueError("Can't convert to unicode: %r" % x) isUnicodeOrQRList = isUnicodeOrQRList() class SRect(Rect): def __init__(self, x, y, width, height, fillColor=colors.black): Rect.__init__(self, x, y, width, height, fillColor=fillColor, strokeColor=None, strokeWidth=0) class QrCodeWidget(Widget): codeName = "QR" _attrMap = AttrMap( BASE = Widget, value = AttrMapValue(isUnicodeOrQRList, desc='QRCode data'), x = AttrMapValue(isNumber, desc='x-coord'), y = AttrMapValue(isNumber, desc='y-coord'), barFillColor = AttrMapValue(isColor, desc='bar color'), barWidth = AttrMapValue(isNumber, desc='Width of bars.'), # maybe should be named just width? barHeight = AttrMapValue(isNumber, desc='Height of bars.'), # maybe should be named just height? barBorder = AttrMapValue(isNumber, desc='Width of QR border.'), # maybe should be named qrBorder? barLevel = AttrMapValue(isLevel, desc='QR Code level.'), # maybe should be named qrLevel qrVersion = AttrMapValue(isNumberOrNone, desc='QR Code version. None for auto'), # Below are ignored, they make no sense barStrokeWidth = AttrMapValue(isNumber, desc='Width of bar borders.'), barStrokeColor = AttrMapValue(isColor, desc='Color of bar borders.'), ) x = 0 y = 0 barFillColor = colors.black barStrokeColor = None barStrokeWidth = 0 barHeight = 32*mm barWidth = 32*mm barBorder = 4 barLevel = 'L' qrVersion = None value = None def __init__(self, value='Hello World', **kw): self.value = isUnicodeOrQRList.normalize(value) for k, v in kw.items(): setattr(self, k, v) ec_level = getattr(qrencoder.QRErrorCorrectLevel, self.barLevel) self.__dict__['qr'] = qrencoder.QRCode(self.qrVersion, ec_level) if isUnicode(self.value): self.addData(self.value) elif self.value: for v in self.value: self.addData(v) def addData(self, value): self.qr.addData(value) def draw(self): self.qr.make() g = Group() color = self.barFillColor border = self.barBorder width = self.barWidth height = self.barHeight x = self.x y = self.y g.add(SRect(x, y, width, height, fillColor=None)) moduleCount = self.qr.getModuleCount() minwh = float(min(width, height)) boxsize = minwh / (moduleCount + border * 2.0) offsetX = x + (width - minwh) / 2.0 offsetY = y + (minwh - height) / 2.0 for r, row in enumerate(self.qr.modules): row = map(bool, row) c = 0 for t, tt in itertools.groupby(row): isDark = t count = len(list(tt)) if isDark: x = (c + border) * boxsize y = (r + border + 1) * boxsize s = SRect(offsetX + x, offsetY + height - y, count * boxsize, boxsize) g.add(s) c += count return g # Flowable version class QrCode(Flowable): height = 32*mm width = 32*mm qrBorder = 4 qrLevel = 'L' qrVersion = None value = None def __init__(self, value=None, **kw): self.value = isUnicodeOrQRList.normalize(value) for k, v in kw.items(): setattr(self, k, v) ec_level = getattr(qrencoder.QRErrorCorrectLevel, self.qrLevel) self.qr = qrencoder.QRCode(self.qrVersion, ec_level) if isUnicode(self.value): self.addData(self.value) elif self.value: for v in self.value: self.addData(v) def addData(self, value): self.qr.addData(value) def draw(self): self.qr.make() moduleCount = self.qr.getModuleCount() border = self.qrBorder xsize = self.width / (moduleCount + border * 2.0) ysize = self.height / (moduleCount + border * 2.0) for r, row in enumerate(self.qr.modules): row = map(bool, row) c = 0 for t, tt in itertools.groupby(row): isDark = t count = len(list(tt)) if isDark: x = (c + border) * xsize y = self.height - (r + border + 1) * ysize self.rect(x, y, count * xsize, ysize * 1.05) c += count def rect(self, x, y, w, h): self.canv.rect(x, y, w, h, stroke=0, fill=1)
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/graphics/barcode/qr.py
0.585101
0.222426
qr.py
pypi
from reportlab.lib.units import inch from reportlab.graphics.barcode.common import Barcode from string import digits as string_digits, whitespace as string_whitespace from reportlab.lib.utils import asNative _fim_patterns = { 'A' : "|| | ||", 'B' : "| || || |", 'C' : "|| | | ||", 'D' : "||| | |||", # XXX There is an E. # The below has been seen, but dunno if it is E or not: # 'E' : '|||| ||||' } _postnet_patterns = { '1' : "...||", '2' : "..|.|", '3' : "..||.", '4' : ".|..|", '5' : ".|.|.", '6' : ".||..", '7' : "|...|", '8' : "|..|.", '9' : "|.|..", '0' : "||...", 'S' : "|", } class FIM(Barcode): """ FIM (Facing ID Marks) encode only one letter. There are currently four defined: A Courtesy reply mail with pre-printed POSTNET B Business reply mail without pre-printed POSTNET C Business reply mail with pre-printed POSTNET D OCR Readable mail without pre-printed POSTNET Options that may be passed to constructor: value (single character string from the set A - D. required.): The value to encode. quiet (bool, default 0): Whether to include quiet zones in the symbol. The following may also be passed, but doing so will generate nonstandard symbols which should not be used. This is mainly documented here to show the defaults: barHeight (float, default 5/8 inch): Height of the code. This might legitimately be overriden to make a taller symbol that will 'bleed' off the edge of the paper, leaving 5/8 inch remaining. lquiet (float, default 1/4 inch): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or .15 times the symbol's length. rquiet (float, default 15/32 inch): Quiet zone size to right left of code, if quiet is true. Sources of information on FIM: USPS Publication 25, A Guide to Business Mail Preparation http://new.usps.com/cpim/ftp/pubs/pub25.pdf """ barWidth = inch * (1.0/32.0) spaceWidth = inch * (1.0/16.0) barHeight = inch * (5.0/8.0) rquiet = inch * (0.25) lquiet = inch * (15.0/32.0) quiet = 0 def __init__(self, value='', **args): value = str(value) if isinstance(value,int) else asNative(value) for k, v in args.items(): setattr(self, k, v) Barcode.__init__(self, value) def validate(self): self.valid = 1 self.validated = '' for c in self.value: if c in string_whitespace: continue elif c in "abcdABCD": self.validated = self.validated + c.upper() else: self.valid = 0 if len(self.validated) != 1: raise ValueError("Input must be exactly one character") return self.validated def decompose(self): self.decomposed = '' for c in self.encoded: self.decomposed = self.decomposed + _fim_patterns[c] return self.decomposed def computeSize(self): self._width = (len(self.decomposed) - 1) * self.spaceWidth + self.barWidth if self.quiet: self._width += self.lquiet + self.rquiet self._height = self.barHeight def draw(self): self._calculate() left = self.quiet and self.lquiet or 0 for c in self.decomposed: if c == '|': self.rect(left, 0.0, self.barWidth, self.barHeight) left += self.spaceWidth self.drawHumanReadable() def _humanText(self): return self.value class POSTNET(Barcode): """ POSTNET is used in the US to encode "zip codes" (postal codes) on mail. It can encode 5, 9, or 11 digit codes. I've read that it's pointless to do 5 digits, since USPS will just have to re-print them with 9 or 11 digits. Sources of information on POSTNET: USPS Publication 25, A Guide to Business Mail Preparation http://new.usps.com/cpim/ftp/pubs/pub25.pdf """ quiet = 0 shortHeight = inch * 0.050 barHeight = inch * 0.125 barWidth = inch * 0.018 spaceWidth = inch * 0.0275 def __init__(self, value='', **args): value = str(value) if isinstance(value,int) else asNative(value) for k, v in args.items(): setattr(self, k, v) Barcode.__init__(self, value) def validate(self): self.validated = '' self.valid = 1 count = 0 for c in self.value: if c in (string_whitespace + '-'): pass elif c in string_digits: count = count + 1 if count == 6: self.validated = self.validated + '-' self.validated = self.validated + c else: self.valid = 0 if len(self.validated) not in [5, 10, 12]: self.valid = 0 return self.validated def encode(self): self.encoded = "S" check = 0 for c in self.validated: if c in string_digits: self.encoded = self.encoded + c check = check + int(c) elif c == '-': pass else: raise ValueError("Invalid character in input") check = (10 - check) % 10 self.encoded = self.encoded + repr(check) + 'S' return self.encoded def decompose(self): self.decomposed = '' for c in self.encoded: self.decomposed = self.decomposed + _postnet_patterns[c] return self.decomposed def computeSize(self): self._width = len(self.decomposed) * self.barWidth + (len(self.decomposed) - 1) * self.spaceWidth self._height = self.barHeight def draw(self): self._calculate() sdown = self.barHeight - self.shortHeight left = 0 for c in self.decomposed: if c == '.': h = self.shortHeight else: h = self.barHeight self.rect(left, 0.0, self.barWidth, h) left = left + self.barWidth + self.spaceWidth self.drawHumanReadable() def _humanText(self): return self.encoded[1:-1]
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/graphics/barcode/usps.py
0.692954
0.352759
usps.py
pypi
__version__='3.3.0' __all__= ( 'BarcodeI2of5', 'BarcodeCode128', 'BarcodeStandard93', 'BarcodeExtended93', 'BarcodeStandard39', 'BarcodeExtended39', 'BarcodeMSI', 'BarcodeCodabar', 'BarcodeCode11', 'BarcodeFIM', 'BarcodePOSTNET', 'BarcodeUSPS_4State', ) from reportlab.lib.validators import isInt, isNumber, isColor, isString, isColorOrNone, OneOf, isBoolean, EitherOr, isNumberOrNone from reportlab.lib.attrmap import AttrMap, AttrMapValue from reportlab.lib.colors import black from reportlab.lib.utils import rl_exec from reportlab.graphics.shapes import Line, Rect, Group, NotImplementedError, String from reportlab.graphics.charts.areas import PlotArea ''' #snippet #first make your Drawing from reportlab.graphics.shapes import Drawing d= Drawing(100,50) #create and set up the widget from reportlab.graphics.barcode.widgets import BarcodeStandard93 bc = BarcodeStandard93() bc.value = 'RGB-123456' #add to the drawing and save d.add(bc) # d.save(formats=['gif','pict'],fnRoot='bc_sample') ''' class _BarcodeWidget(PlotArea): _attrMap = AttrMap(BASE=PlotArea, barStrokeColor = AttrMapValue(isColorOrNone, desc='Color of bar borders.'), barFillColor = AttrMapValue(isColorOrNone, desc='Color of bar interior areas.'), barStrokeWidth = AttrMapValue(isNumber, desc='Width of bar borders.'), value = AttrMapValue(EitherOr((isString,isNumber)), desc='Value.'), textColor = AttrMapValue(isColorOrNone, desc='Color of human readable text.'), valid = AttrMapValue(isBoolean), validated = AttrMapValue(isString,desc="validated form of input"), encoded = AttrMapValue(None,desc="encoded form of input"), decomposed = AttrMapValue(isString,desc="decomposed form of input"), canv = AttrMapValue(None,desc="temporarily used for internal methods"), gap = AttrMapValue(isNumberOrNone, desc='Width of inter character gaps.'), ) textColor = barFillColor = black barStrokeColor = None barStrokeWidth = 0 _BCC = None def __init__(self,_value='',**kw): PlotArea.__init__(self) del self.__dict__['width'] del self.__dict__['height'] self.x = self.y = 0 kw.setdefault('value',_value) self._BCC.__init__(self,**kw) def rect(self,x,y,w,h,**kw): self._Gadd(Rect(self.x+x,self.y+y,w,h, strokeColor=self.barStrokeColor,strokeWidth=self.barStrokeWidth, fillColor=self.barFillColor)) def draw(self): if not self._BCC: raise NotImplementedError("Abstract class %s cannot be drawn" % self.__class__.__name__) self.canv = self G = Group() self._Gadd = G.add self._Gadd(Rect(self.x,self.y,self.width,self.height,fillColor=None,strokeColor=None,strokeWidth=0.0001)) self._BCC.draw(self) del self.canv, self._Gadd return G def annotate(self,x,y,text,fontName,fontSize,anchor='middle'): self._Gadd(String(self.x+x,self.y+y,text,fontName=fontName,fontSize=fontSize, textAnchor=anchor,fillColor=self.textColor)) def _BCW(doc,codeName,attrMap,mod,value,**kwds): """factory for Barcode Widgets""" _pre_init = kwds.pop('_pre_init','') _methods = kwds.pop('_methods','') name = 'Barcode'+codeName ns = vars().copy() code = 'from %s import %s' % (mod,codeName) rl_exec(code,ns) ns['_BarcodeWidget'] = _BarcodeWidget code = '''class %(name)s(_BarcodeWidget,%(codeName)s): \t_BCC = %(codeName)s \tcodeName = %(codeName)r \tdef __init__(self,**kw):%(_pre_init)s \t\t_BarcodeWidget.__init__(self,%(value)r,**kw)%(_methods)s''' % ns rl_exec(code,ns) Klass = ns[name] if attrMap: Klass._attrMap = attrMap if doc: Klass.__doc__ = doc for k, v in kwds.items(): setattr(Klass,k,v) return Klass BarcodeI2of5 = _BCW( """Interleaved 2 of 5 is used in distribution and warehouse industries. It encodes an even-numbered sequence of numeric digits. There is an optional module 10 check digit; if including this, the total length must be odd so that it becomes even after including the check digit. Otherwise the length must be even. Since the check digit is optional, our library does not check it. """, "I2of5", AttrMap(BASE=_BarcodeWidget, barWidth = AttrMapValue(isNumber,'''(float, default .0075): X-Dimension, or width of the smallest element Minumum is .0075 inch (7.5 mils).'''), ratio = AttrMapValue(isNumber,'''(float, default 2.2): The ratio of wide elements to narrow elements. Must be between 2.0 and 3.0 (or 2.2 and 3.0 if the barWidth is greater than 20 mils (.02 inch))'''), gap = AttrMapValue(isNumberOrNone,'''(float or None, default None): width of intercharacter gap. None means "use barWidth".'''), barHeight = AttrMapValue(isNumber,'''(float, see default below): Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol's length.'''), checksum = AttrMapValue(isBoolean,'''(bool, default 1): Whether to compute and include the check digit'''), bearers = AttrMapValue(isNumber,'''(float, in units of barWidth. default 3.0): Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 3 x-dimensions. Set to zero for no bearer bars. (Bearer bars help detect misscans, so it is suggested to leave them on).'''), quiet = AttrMapValue(isBoolean,'''(bool, default 1): Whether to include quiet zones in the symbol.'''), lquiet = AttrMapValue(isNumber,'''(float, see default below): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or .15 times the symbol's length.'''), rquiet = AttrMapValue(isNumber,'''(float, defaults as above): Quiet zone size to right left of code, if quiet is true.'''), fontName = AttrMapValue(isString, desc='human readable font'), fontSize = AttrMapValue(isNumber, desc='human readable font size'), humanReadable = AttrMapValue(isBoolean, desc='if human readable'), stop = AttrMapValue(isBoolean, desc='if we use start/stop symbols (default 1)'), ), 'reportlab.graphics.barcode.common', 1234, _tests = [ '12', '1234', '123456', '12345678', '1234567890' ], ) BarcodeCode128 = _BCW("""Code 128 encodes any number of characters in the ASCII character set.""", "Code128", AttrMap(BASE=BarcodeI2of5,UNWANTED=('bearers','checksum','ratio','checksum','stop')), 'reportlab.graphics.barcode.code128', "AB-12345678", _tests = ['ReportLab Rocks!', 'PFWZF'], ) BarcodeCode128Auto = _BCW( 'Modified Code128 to use auto encoding', 'Code128Auto', AttrMap(BASE=BarcodeCode128), 'reportlab.graphics.barcode.code128', 'XY149740345GB' ) BarcodeStandard93=_BCW("""This is a compressed form of Code 39""", "Standard93", AttrMap(BASE=BarcodeCode128, stop = AttrMapValue(isBoolean, desc='if we use start/stop symbols (default 1)'), ), 'reportlab.graphics.barcode.code93', "CODE 93", ) BarcodeExtended93=_BCW("""This is a compressed form of Code 39, allowing the full ASCII charset""", "Extended93", AttrMap(BASE=BarcodeCode128, stop = AttrMapValue(isBoolean, desc='if we use start/stop symbols (default 1)'), ), 'reportlab.graphics.barcode.code93', "L@@K! Code 93 ;-)", ) BarcodeStandard39=_BCW("""Code39 is widely used in non-retail, especially US defence and health. Allowed characters are 0-9, A-Z (caps only), space, and -.$/+%*.""", "Standard39", AttrMap(BASE=BarcodeI2of5), 'reportlab.graphics.barcode.code39', "A012345B%R", ) BarcodeExtended39=_BCW("""Extended 39 encodes the full ASCII character set by encoding characters as pairs of Code 39 characters; $, /, % and + are used as shift characters.""", "Extended39", AttrMap(BASE=BarcodeI2of5), 'reportlab.graphics.barcode.code39', "A012345B}", ) BarcodeMSI=_BCW("""MSI is used for inventory control in retail applications. There are several methods for calculating check digits so we do not implement one. """, "MSI", AttrMap(BASE=BarcodeI2of5), 'reportlab.graphics.barcode.common', 1234, ) BarcodeCodabar=_BCW("""Used in blood banks, photo labs and FedEx labels. Encodes 0-9, -$:/.+, and four start/stop characters A-D.""", "Codabar", AttrMap(BASE=BarcodeI2of5), 'reportlab.graphics.barcode.common', "A012345B", ) BarcodeCode11=_BCW("""Used mostly for labelling telecommunications equipment. It encodes numeric digits.""", 'Code11', AttrMap(BASE=BarcodeI2of5, checksum = AttrMapValue(isInt,'''(integer, default 2): Whether to compute and include the check digit(s). (0 none, 1 1-digit, 2 2-digit, -1 auto, default -1): How many checksum digits to include. -1 ("auto") means 1 if the number of digits is 10 or less, else 2.'''), ), 'reportlab.graphics.barcode.common', "01234545634563", ) BarcodeFIM=_BCW(""" FIM was developed as part of the POSTNET barcoding system. FIM (Face Identification Marking) is used by the cancelling machines to sort mail according to whether or not they have bar code and their postage requirements. There are four types of FIM called FIM A, FIM B, FIM C, and FIM D. The four FIM types have the following meanings: FIM A- Postage required pre-barcoded FIM B - Postage pre-paid, no bar code exists FIM C- Postage prepaid prebarcoded FIM D- Postage required, no bar code exists""", "FIM", AttrMap(BASE=_BarcodeWidget, barWidth = AttrMapValue(isNumber,'''(float, default 1/32in): the bar width.'''), spaceWidth = AttrMapValue(isNumber,'''(float or None, default 1/16in): width of intercharacter gap. None means "use barWidth".'''), barHeight = AttrMapValue(isNumber,'''(float, default 5/8in): The bar height.'''), quiet = AttrMapValue(isBoolean,'''(bool, default 0): Whether to include quiet zones in the symbol.'''), lquiet = AttrMapValue(isNumber,'''(float, default: 15/32in): Quiet zone size to left of code, if quiet is true.'''), rquiet = AttrMapValue(isNumber,'''(float, default 1/4in): Quiet zone size to right left of code, if quiet is true.'''), fontName = AttrMapValue(isString, desc='human readable font'), fontSize = AttrMapValue(isNumber, desc='human readable font size'), humanReadable = AttrMapValue(isBoolean, desc='if human readable'), ), 'reportlab.graphics.barcode.usps', "A", ) BarcodePOSTNET=_BCW('', "POSTNET", AttrMap(BASE=_BarcodeWidget, barWidth = AttrMapValue(isNumber,'''(float, default 0.018*in): the bar width.'''), spaceWidth = AttrMapValue(isNumber,'''(float or None, default 0.0275in): width of intercharacter gap.'''), shortHeight = AttrMapValue(isNumber,'''(float, default 0.05in): The short bar height.'''), barHeight = AttrMapValue(isNumber,'''(float, default 0.125in): The full bar height.'''), fontName = AttrMapValue(isString, desc='human readable font'), fontSize = AttrMapValue(isNumber, desc='human readable font size'), humanReadable = AttrMapValue(isBoolean, desc='if human readable'), ), 'reportlab.graphics.barcode.usps', "78247-1043", ) BarcodeUSPS_4State=_BCW('', "USPS_4State", AttrMap(BASE=_BarcodeWidget, widthSize = AttrMapValue(isNumber,'''(float, default 1): the bar width size adjustment between 0 and 1.'''), heightSize = AttrMapValue(isNumber,'''(float, default 1): the bar height size adjustment between 0 and 1.'''), fontName = AttrMapValue(isString, desc='human readable font'), fontSize = AttrMapValue(isNumber, desc='human readable font size'), tracking = AttrMapValue(isString, desc='tracking data'), routing = AttrMapValue(isString, desc='routing data'), humanReadable = AttrMapValue(isBoolean, desc='if human readable'), ), 'reportlab.graphics.barcode.usps4s', '01234567094987654321', _pre_init="\n\t\tkw.setdefault('routing','01234567891')\n", _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" ) BarcodeECC200DataMatrix = _BCW( 'ECC200DataMatrix', 'ECC200DataMatrix', AttrMap(BASE=_BarcodeWidget, x=AttrMapValue(isNumber, desc='X position of the lower-left corner of the barcode.'), y=AttrMapValue(isNumber, desc='Y position of the lower-left corner of the barcode.'), barWidth=AttrMapValue(isNumber, desc='Size of data modules.'), barFillColor=AttrMapValue(isColorOrNone, desc='Color of data modules.'), value=AttrMapValue(EitherOr((isString,isNumber)), desc='Value.'), height=AttrMapValue(None, desc='ignored'), width=AttrMapValue(None, desc='ignored'), strokeColor=AttrMapValue(None, desc='ignored'), strokeWidth=AttrMapValue(None, desc='ignored'), fillColor=AttrMapValue(None, desc='ignored'), background=AttrMapValue(None, desc='ignored'), debug=AttrMapValue(None, desc='ignored'), gap=AttrMapValue(None, desc='ignored'), row_modules=AttrMapValue(None, desc='???'), col_modules=AttrMapValue(None, desc='???'), row_regions=AttrMapValue(None, desc='???'), col_regions=AttrMapValue(None, desc='???'), cw_data=AttrMapValue(None, desc='???'), cw_ecc=AttrMapValue(None, desc='???'), row_usable_modules = AttrMapValue(None, desc='???'), col_usable_modules = AttrMapValue(None, desc='???'), valid = AttrMapValue(None, desc='???'), validated = AttrMapValue(None, desc='???'), decomposed = AttrMapValue(None, desc='???'), ), 'reportlab.graphics.barcode.ecc200datamatrix', 'JGB 0204H20B012722900021AC35B2100001003241014241014TPS01 WJ067073605GB185 MOUNT PLEASANT MAIL CENTER EC1A1BB9ZGBREC1A1BB EC1A1BB STEST FILE FOR SPEC ' ) if __name__=='__main__': raise ValueError('widgets.py has no script function')
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/graphics/barcode/widgets.py
0.728845
0.197696
widgets.py
pypi
from reportlab.lib.units import inch from reportlab.lib.utils import asNative from reportlab.graphics.barcode.common import Barcode from string import digits as string_digits _patterns = { '0': ("bsbSBsBsb", 0), '1': ("BsbSbsbsB", 1), '2': ("bsBSbsbsB", 2), '3': ("BsBSbsbsb", 3), '4': ("bsbSBsbsB", 4), '5': ("BsbSBsbsb", 5), '6': ("bsBSBsbsb", 6), '7': ("bsbSbsBsB", 7), '8': ("BsbSbsBsb", 8), '9': ("bsBSbsBsb", 9), 'A': ("BsbsbSbsB", 10), 'B': ("bsBsbSbsB", 11), 'C': ("BsBsbSbsb", 12), 'D': ("bsbsBSbsB", 13), 'E': ("BsbsBSbsb", 14), 'F': ("bsBsBSbsb", 15), 'G': ("bsbsbSBsB", 16), 'H': ("BsbsbSBsb", 17), 'I': ("bsBsbSBsb", 18), 'J': ("bsbsBSBsb", 19), 'K': ("BsbsbsbSB", 20), 'L': ("bsBsbsbSB", 21), 'M': ("BsBsbsbSb", 22), 'N': ("bsbsBsbSB", 23), 'O': ("BsbsBsbSb", 24), 'P': ("bsBsBsbSb", 25), 'Q': ("bsbsbsBSB", 26), 'R': ("BsbsbsBSb", 27), 'S': ("bsBsbsBSb", 28), 'T': ("bsbsBsBSb", 29), 'U': ("BSbsbsbsB", 30), 'V': ("bSBsbsbsB", 31), 'W': ("BSBsbsbsb", 32), 'X': ("bSbsBsbsB", 33), 'Y': ("BSbsBsbsb", 34), 'Z': ("bSBsBsbsb", 35), '-': ("bSbsbsBsB", 36), '.': ("BSbsbsBsb", 37), ' ': ("bSBsbsBsb", 38), '*': ("bSbsBsBsb", None), '$': ("bSbSbSbsb", 39), '/': ("bSbSbsbSb", 40), '+': ("bSbsbSbSb", 41), '%': ("bsbSbSbSb", 42) } from reportlab.lib.utils import ascii_uppercase, ascii_lowercase _stdchrs = string_digits + ascii_uppercase + "-. $/+%" _extended = { '\0': "%U", '\01': "$A", '\02': "$B", '\03': "$C", '\04': "$D", '\05': "$E", '\06': "$F", '\07': "$G", '\010': "$H", '\011': "$I", '\012': "$J", '\013': "$K", '\014': "$L", '\015': "$M", '\016': "$N", '\017': "$O", '\020': "$P", '\021': "$Q", '\022': "$R", '\023': "$S", '\024': "$T", '\025': "$U", '\026': "$V", '\027': "$W", '\030': "$X", '\031': "$Y", '\032': "$Z", '\033': "%A", '\034': "%B", '\035': "%C", '\036': "%D", '\037': "%E", '!': "/A", '"': "/B", '#': "/C", '$': "/D", '%': "/E", '&': "/F", '\'': "/G", '(': "/H", ')': "/I", '*': "/J", '+': "/K", ',': "/L", '/': "/O", ':': "/Z", ';': "%F", '<': "%G", '=': "%H", '>': "%I", '?': "%J", '@': "%V", '[': "%K", '\\': "%L", ']': "%M", '^': "%N", '_': "%O", '`': "%W", 'a': "+A", 'b': "+B", 'c': "+C", 'd': "+D", 'e': "+E", 'f': "+F", 'g': "+G", 'h': "+H", 'i': "+I", 'j': "+J", 'k': "+K", 'l': "+L", 'm': "+M", 'n': "+N", 'o': "+O", 'p': "+P", 'q': "+Q", 'r': "+R", 's': "+S", 't': "+T", 'u': "+U", 'v': "+V", 'w': "+W", 'x': "+X", 'y': "+Y", 'z': "+Z", '{': "%P", '|': "%Q", '}': "%R", '~': "%S", '\177': "%T" } _extchrs = _stdchrs + ascii_lowercase + \ "\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017" + \ "\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" + \ "*!'#&\"(),:;<=>?@[\\]^_`{|}~\177" def _encode39(value, cksum, stop): v = sum([_patterns[c][1] for c in value]) % 43 if cksum: value += _stdchrs[v] if stop: value = '*'+value+'*' return value class _Code39Base(Barcode): barWidth = inch * 0.0075 lquiet = None rquiet = None quiet = 1 gap = None barHeight = None ratio = 2.2 checksum = 1 bearers = 0.0 stop = 1 def __init__(self, value = "", **args): value = asNative(value) for k, v in args.items(): setattr(self, k, v) if self.quiet: if self.lquiet is None: self.lquiet = max(inch * 0.25, self.barWidth * 10.0) self.rquiet = max(inch * 0.25, self.barWidth * 10.0) else: self.lquiet = self.rquiet = 0.0 Barcode.__init__(self, value) def decompose(self): dval = "" for c in self.encoded: dval = dval + _patterns[c][0] + 'i' self.decomposed = dval[:-1] return self.decomposed def _humanText(self): return self.stop and self.encoded[1:-1] or self.encoded class Standard39(_Code39Base): """ Options that may be passed to constructor: value (int, or numeric string required.): The value to encode. barWidth (float, default .0075): X-Dimension, or width of the smallest element Minumum is .0075 inch (7.5 mils). ratio (float, default 2.2): The ratio of wide elements to narrow elements. Must be between 2.0 and 3.0 (or 2.2 and 3.0 if the barWidth is greater than 20 mils (.02 inch)) gap (float or None, default None): width of intercharacter gap. None means "use barWidth". barHeight (float, see default below): Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol's length. checksum (bool, default 1): Wether to compute and include the check digit bearers (float, in units of barWidth. default 0): Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 0 (no bearers). quiet (bool, default 1): Wether to include quiet zones in the symbol. lquiet (float, see default below): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or .15 times the symbol's length. rquiet (float, defaults as above): Quiet zone size to right left of code, if quiet is true. stop (bool, default 1): Whether to include start/stop symbols. Sources of Information on Code 39: http://www.semiconductor.agilent.com/barcode/sg/Misc/code_39.html http://www.adams1.com/pub/russadam/39code.html http://www.barcodeman.com/c39_1.html Official Spec, "ANSI/AIM BC1-1995, USS" is available for US$45 from http://www.aimglobal.org/aimstore/ """ def validate(self): vval = [].append self.valid = 1 for c in self.value: if c in ascii_lowercase: c = c.upper() if c not in _stdchrs: self.valid = 0 continue vval(c) self.validated = ''.join(vval.__self__) return self.validated def encode(self): self.encoded = _encode39(self.validated, self.checksum, self.stop) return self.encoded class Extended39(_Code39Base): """ Extended Code 39 is a convention for encoding additional characters not present in stanmdard Code 39 by using pairs of characters to represent the characters missing in Standard Code 39. See Standard39 for arguments. Sources of Information on Extended Code 39: http://www.semiconductor.agilent.com/barcode/sg/Misc/xcode_39.html http://www.barcodeman.com/c39_ext.html """ def validate(self): vval = "" self.valid = 1 for c in self.value: if c not in _extchrs: self.valid = 0 continue vval = vval + c self.validated = vval return vval def encode(self): self.encoded = "" for c in self.validated: if c in _extended: self.encoded = self.encoded + _extended[c] elif c in _stdchrs: self.encoded = self.encoded + c else: raise ValueError self.encoded = _encode39(self.encoded, self.checksum,self.stop) return self.encoded
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/graphics/barcode/code39.py
0.40204
0.499329
code39.py
pypi
__version__='3.3.0' __doc__='''This module defines a Area mixin classes''' from reportlab.lib.validators import isNumber, isColor, isColorOrNone, isNoneOrShape from reportlab.graphics.widgetbase import Widget from reportlab.graphics.shapes import Rect, Group, Line, Polygon from reportlab.lib.attrmap import AttrMap, AttrMapValue from reportlab.lib.colors import grey class PlotArea(Widget): "Abstract base class representing a chart's plot area, pretty unusable by itself." _attrMap = AttrMap( x = AttrMapValue(isNumber, desc='X position of the lower-left corner of the chart.'), y = AttrMapValue(isNumber, desc='Y position of the lower-left corner of the chart.'), width = AttrMapValue(isNumber, desc='Width of the chart.'), height = AttrMapValue(isNumber, desc='Height of the chart.'), strokeColor = AttrMapValue(isColorOrNone, desc='Color of the plot area border.'), strokeWidth = AttrMapValue(isNumber, desc='Width plot area border.'), fillColor = AttrMapValue(isColorOrNone, desc='Color of the plot area interior.'), background = AttrMapValue(isNoneOrShape, desc='Handle to background object e.g. Rect(0,0,width,height).'), debug = AttrMapValue(isNumber, desc='Used only for debugging.'), ) def __init__(self): self.x = 20 self.y = 10 self.height = 85 self.width = 180 self.strokeColor = None self.strokeWidth = 1 self.fillColor = None self.background = None self.debug = 0 def makeBackground(self): if self.background is not None: BG = self.background if isinstance(BG,Group): g = BG for bg in g.contents: bg.x = self.x bg.y = self.y bg.width = self.width bg.height = self.height else: g = Group() if type(BG) not in (type(()),type([])): BG=(BG,) for bg in BG: bg.x = self.x bg.y = self.y bg.width = self.width bg.height = self.height g.add(bg) return g else: strokeColor,strokeWidth,fillColor=self.strokeColor, self.strokeWidth, self.fillColor if (strokeWidth and strokeColor) or fillColor: g = Group() _3d_dy = getattr(self,'_3d_dy',None) x = self.x y = self.y h = self.height w = self.width if _3d_dy is not None: _3d_dx = self._3d_dx if fillColor and not strokeColor: from reportlab.lib.colors import Blacker c = Blacker(fillColor, getattr(self,'_3d_blacken',0.7)) else: c = strokeColor if not strokeWidth: strokeWidth = 0.5 if fillColor or strokeColor or c: bg = Polygon([x,y,x,y+h,x+_3d_dx,y+h+_3d_dy,x+w+_3d_dx,y+h+_3d_dy,x+w+_3d_dx,y+_3d_dy,x+w,y], strokeColor=strokeColor or c or grey, strokeWidth=strokeWidth, fillColor=fillColor) g.add(bg) g.add(Line(x,y,x+_3d_dx,y+_3d_dy, strokeWidth=0.5, strokeColor=c)) g.add(Line(x+_3d_dx,y+_3d_dy, x+_3d_dx,y+h+_3d_dy,strokeWidth=0.5, strokeColor=c)) fc = Blacker(c, getattr(self,'_3d_blacken',0.8)) g.add(Polygon([x,y,x+_3d_dx,y+_3d_dy,x+w+_3d_dx,y+_3d_dy,x+w,y], strokeColor=strokeColor or c or grey, strokeWidth=strokeWidth, fillColor=fc)) bg = Line(x+_3d_dx,y+_3d_dy, x+w+_3d_dx,y+_3d_dy,strokeWidth=0.5, strokeColor=c) else: bg = None else: bg = Rect(x, y, w, h, strokeColor=strokeColor, strokeWidth=strokeWidth, fillColor=fillColor) if bg: g.add(bg) return g else: return None
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/graphics/charts/areas.py
0.820793
0.216198
areas.py
pypi
from reportlab.lib.colors import blue, _PCMYK_black from reportlab.graphics.charts.textlabels import Label from reportlab.graphics.shapes import Circle, Drawing, Group, Line, Rect, String from reportlab.graphics.widgetbase import Widget from reportlab.lib.attrmap import * from reportlab.lib.validators import * from reportlab.lib.units import cm from reportlab.pdfbase.pdfmetrics import getFont from reportlab.graphics.charts.lineplots import _maxWidth class DotBox(Widget): """Returns a dotbox widget.""" #Doesn't use TypedPropertyCollection for labels - this can be a later improvement _attrMap = AttrMap( xlabels = AttrMapValue(isNoneOrListOfNoneOrStrings, desc="List of text labels for boxes on left hand side"), ylabels = AttrMapValue(isNoneOrListOfNoneOrStrings, desc="Text label for second box on left hand side"), labelFontName = AttrMapValue(isString, desc="Name of font used for the labels"), labelFontSize = AttrMapValue(isNumber, desc="Size of font used for the labels"), labelOffset = AttrMapValue(isNumber, desc="Space between label text and grid edge"), strokeWidth = AttrMapValue(isNumber, desc='Width of the grid and dot outline'), gridDivWidth = AttrMapValue(isNumber, desc="Width of each 'box'"), gridColor = AttrMapValue(isColor, desc='Colour for the box and gridding'), dotDiameter = AttrMapValue(isNumber, desc="Diameter of the circle used for the 'dot'"), dotColor = AttrMapValue(isColor, desc='Colour of the circle on the box'), dotXPosition = AttrMapValue(isNumber, desc='X Position of the circle'), dotYPosition = AttrMapValue(isNumber, desc='X Position of the circle'), x = AttrMapValue(isNumber, desc='X Position of dotbox'), y = AttrMapValue(isNumber, desc='Y Position of dotbox'), ) def __init__(self): self.xlabels=["Value", "Blend", "Growth"] self.ylabels=["Small", "Medium", "Large"] self.labelFontName = "Helvetica" self.labelFontSize = 6 self.labelOffset = 5 self.strokeWidth = 0.5 self.gridDivWidth=0.5*cm self.gridColor=colors.Color(25/255.0,77/255.0,135/255.0) self.dotDiameter=0.4*cm self.dotColor=colors.Color(232/255.0,224/255.0,119/255.0) self.dotXPosition = 1 self.dotYPosition = 1 self.x = 30 self.y = 5 def _getDrawingDimensions(self): leftPadding=rightPadding=topPadding=bottomPadding=5 #find width of grid tx=len(self.xlabels)*self.gridDivWidth #add padding (and offset) tx=tx+leftPadding+rightPadding+self.labelOffset #add in maximum width of text tx=tx+_maxWidth(self.xlabels, self.labelFontName, self.labelFontSize) #find height of grid ty=len(self.ylabels)*self.gridDivWidth #add padding (and offset) ty=ty+topPadding+bottomPadding+self.labelOffset #add in maximum width of text ty=ty+_maxWidth(self.ylabels, self.labelFontName, self.labelFontSize) #print (tx, ty) return (tx,ty) def demo(self,drawing=None): if not drawing: tx,ty=self._getDrawingDimensions() drawing = Drawing(tx,ty) drawing.add(self.draw()) return drawing def draw(self): g = Group() #box g.add(Rect(self.x,self.y,len(self.xlabels)*self.gridDivWidth,len(self.ylabels)*self.gridDivWidth, strokeColor=self.gridColor, strokeWidth=self.strokeWidth, fillColor=None)) #internal gridding for f in range (1,len(self.ylabels)): #horizontal g.add(Line(strokeColor=self.gridColor, strokeWidth=self.strokeWidth, x1 = self.x, y1 = self.y+f*self.gridDivWidth, x2 = self.x+len(self.xlabels)*self.gridDivWidth, y2 = self.y+f*self.gridDivWidth)) for f in range (1,len(self.xlabels)): #vertical g.add(Line(strokeColor=self.gridColor, strokeWidth=self.strokeWidth, x1 = self.x+f*self.gridDivWidth, y1 = self.y, x2 = self.x+f*self.gridDivWidth, y2 = self.y+len(self.ylabels)*self.gridDivWidth)) # draw the 'dot' g.add(Circle(strokeColor=self.gridColor, strokeWidth=self.strokeWidth, fillColor=self.dotColor, cx = self.x+(self.dotXPosition*self.gridDivWidth), cy = self.y+(self.dotYPosition*self.gridDivWidth), r = self.dotDiameter/2.0)) #used for centering y-labels (below) ascent=getFont(self.labelFontName).face.ascent if ascent==0: ascent=0.718 # default (from helvetica) ascent=ascent*self.labelFontSize # normalize #do y-labels if self.ylabels != None: for f in range (len(self.ylabels)-1,-1,-1): if self.ylabels[f]!= None: g.add(String(strokeColor=self.gridColor, text = self.ylabels[f], fontName = self.labelFontName, fontSize = self.labelFontSize, fillColor=_PCMYK_black, x = self.x-self.labelOffset, y = self.y+(f*self.gridDivWidth+(self.gridDivWidth-ascent)/2.0), textAnchor = 'end')) #do x-labels if self.xlabels != None: for f in range (0,len(self.xlabels)): if self.xlabels[f]!= None: l=Label() l.x=self.x+(f*self.gridDivWidth)+(self.gridDivWidth+ascent)/2.0 l.y=self.y+(len(self.ylabels)*self.gridDivWidth)+self.labelOffset l.angle=90 l.textAnchor='start' l.fontName = self.labelFontName l.fontSize = self.labelFontSize l.fillColor = _PCMYK_black l.setText(self.xlabels[f]) l.boxAnchor = 'sw' l.draw() g.add(l) return g if __name__ == "__main__": d = DotBox() d.demo().save(fnRoot="dotbox")
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/graphics/charts/dotbox.py
0.615781
0.26171
dotbox.py
pypi
__version__='3.3.0' __doc__="Utilities used here and there." from time import mktime, gmtime, strftime from math import log10, pi, floor, sin, cos, sqrt, hypot import weakref from reportlab.graphics.shapes import transformPoint, transformPoints, inverse, Ellipse, Group, String, Path, numericXShift from reportlab.lib.utils import flatten from reportlab.pdfbase.pdfmetrics import stringWidth ### Dinu's stuff used in some line plots (likely to vansih). def mkTimeTuple(timeString): "Convert a 'dd/mm/yyyy' formatted string to a tuple for use in the time module." list = [0] * 9 dd, mm, yyyy = list(map(int, timeString.split('/'))) list[:3] = [yyyy, mm, dd] return tuple(list) def str2seconds(timeString): "Convert a number of seconds since the epoch into a date string." return mktime(mkTimeTuple(timeString)) def seconds2str(seconds): "Convert a date string into the number of seconds since the epoch." return strftime('%Y-%m-%d', gmtime(seconds)) ### Aaron's rounding function for making nice values on axes. def nextRoundNumber(x): """Return the first 'nice round number' greater than or equal to x Used in selecting apropriate tick mark intervals; we say we want an interval which places ticks at least 10 points apart, work out what that is in chart space, and ask for the nextRoundNumber(). Tries the series 1,2,5,10,20,50,100.., going up or down as needed. """ #guess to nearest order of magnitude if x in (0, 1): return x if x < 0: return -1.0 * nextRoundNumber(-x) else: lg = int(log10(x)) if lg == 0: if x < 1: base = 0.1 else: base = 1.0 elif lg < 0: base = 10.0 ** (lg - 1) else: base = 10.0 ** lg # e.g. base(153) = 100 # base will always be lower than x if base >= x: return base * 1.0 elif (base * 2) >= x: return base * 2.0 elif (base * 5) >= x: return base * 5.0 else: return base * 10.0 _intervals=(.1, .2, .25, .5) _j_max=len(_intervals)-1 def find_interval(lo,hi,I=5): 'determine tick parameters for range [lo, hi] using I intervals' if lo >= hi: if lo==hi: if lo==0: lo = -.1 hi = .1 else: lo = 0.9*lo hi = 1.1*hi else: raise ValueError("lo>hi") x=(hi - lo)/float(I) b= (x>0 and (x<1 or x>10)) and 10**floor(log10(x)) or 1 b = b while 1: a = x/b if a<=_intervals[-1]: break b = b*10 j = 0 while a>_intervals[j]: j = j + 1 while 1: ss = _intervals[j]*b n = lo/ss l = int(n)-(n<0) n = ss*l x = ss*(l+I) a = I*ss if n>0: if a>=hi: n = 0.0 x = a elif hi<0: a = -a if lo>a: n = a x = 0 if hi<=x and n<=lo: break j = j + 1 if j>_j_max: j = 0 b = b*10 return n, x, ss, lo - n + x - hi def find_good_grid(lower,upper,n=(4,5,6,7,8,9), grid=None): if grid: t = divmod(lower,grid)[0] * grid hi, z = divmod(upper,grid) if z>1e-8: hi = hi+1 hi = hi*grid else: try: n[0] except TypeError: n = range(max(1,n-2),max(n+3,2)) w = 1e308 for i in n: z=find_interval(lower,upper,i) if z[3]<w: t, hi, grid = z[:3] w=z[3] return t, hi, grid def ticks(lower, upper, n=(4,5,6,7,8,9), split=1, percent=0, grid=None, labelVOffset=0): ''' return tick positions and labels for range lower<=x<=upper n=number of intervals to try (can be a list or sequence) split=1 return ticks then labels else (tick,label) pairs ''' t, hi, grid = find_good_grid(lower, upper, n, grid) power = floor(log10(grid)) if power==0: power = 1 w = grid/10.**power w = int(w)!=w if power > 3 or power < -3: format = '%+'+repr(w+7)+'.0e' else: if power >= 0: digits = int(power)+w format = '%' + repr(digits)+'.0f' else: digits = w-int(power) format = '%'+repr(digits+2)+'.'+repr(digits)+'f' if percent: format=format+'%%' T = [] n = int(float(hi-t)/grid+0.1)+1 if split: labels = [] for i in range(n): v = t+grid*i T.append(v) labels.append(format % (v+labelVOffset)) return T, labels else: for i in range(n): v = t+grid*i T.append((v, format % (v+labelVOffset))) return T def findNones(data): m = len(data) if None in data: b = 0 while b<m and data[b] is None: b += 1 if b==m: return data l = m-1 while data[l] is None: l -= 1 l+=1 if b or l: data = data[b:l] I = [i for i in range(len(data)) if data[i] is None] for i in I: data[i] = 0.5*(data[i-1]+data[i+1]) return b, l, data return 0,m,data def pairFixNones(pairs): Y = [x[1] for x in pairs] b,l,nY = findNones(Y) m = len(Y) if b or l<m or nY!=Y: if b or l<m: pairs = pairs[b:l] pairs = [(x[0],y) for x,y in zip(pairs,nY)] return pairs def maverage(data,n=6): data = (n-1)*[data[0]]+data data = [float(sum(data[i-n:i]))/n for i in range(n,len(data)+1)] return data def pairMaverage(data,n=6): return [(x[0],s) for x,s in zip(data, maverage([x[1] for x in data],n))] class DrawTimeCollector(object): ''' generic mechanism for collecting information about nodes at the time they are about to be drawn ''' def __init__(self,formats=['gif']): self._nodes = weakref.WeakKeyDictionary() self.clear() self._pmcanv = None self.formats = formats self.disabled = False def clear(self): self._info = [] self._info_append = self._info.append def record(self,func,node,*args,**kwds): self._nodes[node] = (func,args,kwds) node.__dict__['_drawTimeCallback'] = self def __call__(self,node,canvas,renderer): func = self._nodes.get(node,None) if func: func, args, kwds = func i = func(node,canvas,renderer, *args, **kwds) if i is not None: self._info_append(i) @staticmethod def rectDrawTimeCallback(node,canvas,renderer,**kwds): A = getattr(canvas,'ctm',None) if not A: return x1 = node.x y1 = node.y x2 = x1 + node.width y2 = y1 + node.height D = kwds.copy() D['rect']=DrawTimeCollector.transformAndFlatten(A,((x1,y1),(x2,y2))) return D @staticmethod def transformAndFlatten(A,p): ''' transform an flatten a list of points A transformation matrix p points [(x0,y0),....(xk,yk).....] ''' if tuple(A)!=(1,0,0,1,0,0): iA = inverse(A) p = transformPoints(iA,p) return tuple(flatten(p)) @property def pmcanv(self): if not self._pmcanv: import renderPM self._pmcanv = renderPM.PMCanvas(1,1) return self._pmcanv def wedgeDrawTimeCallback(self,node,canvas,renderer,**kwds): A = getattr(canvas,'ctm',None) if not A: return if isinstance(node,Ellipse): c = self.pmcanv c.ellipse(node.cx, node.cy, node.rx,node.ry) p = c.vpath p = [(x[1],x[2]) for x in p] else: p = node.asPolygon().points p = [(p[i],p[i+1]) for i in range(0,len(p),2)] D = kwds.copy() D['poly'] = self.transformAndFlatten(A,p) return D def save(self,fnroot): ''' save the current information known to this collector fnroot is the root name of a resource to name the saved info override this to get the right semantics for your collector ''' import pprint f=open(fnroot+'.default-collector.out','w') try: pprint.pprint(self._info,f) finally: f.close() def xyDist(xxx_todo_changeme, xxx_todo_changeme1 ): '''return distance between two points''' (x0,y0) = xxx_todo_changeme (x1,y1) = xxx_todo_changeme1 return hypot((x1-x0),(y1-y0)) def lineSegmentIntersect(xxx_todo_changeme2, xxx_todo_changeme3, xxx_todo_changeme4, xxx_todo_changeme5 ): (x00,y00) = xxx_todo_changeme2 (x01,y01) = xxx_todo_changeme3 (x10,y10) = xxx_todo_changeme4 (x11,y11) = xxx_todo_changeme5 p = x00,y00 r = x01-x00,y01-y00 q = x10,y10 s = x11-x10,y11-y10 rs = float(r[0]*s[1]-r[1]*s[0]) qp = q[0]-p[0],q[1]-p[1] qpr = qp[0]*r[1]-qp[1]*r[0] qps = qp[0]*s[1]-qp[1]*s[0] if abs(rs)<1e-8: if abs(qpr)<1e-8: return 'collinear' return None t = qps/rs u = qpr/rs if 0<=t<=1 and 0<=u<=1: return p[0]+t*r[0], p[1]+t*r[1] def makeCircularString(x, y, radius, angle, text, fontName, fontSize, inside=0, G=None,textAnchor='start'): '''make a group with circular text in it''' if not G: G = Group() angle %= 360 pi180 = pi/180 phi = angle*pi180 width = stringWidth(text, fontName, fontSize) sig = inside and -1 or 1 hsig = sig*0.5 sig90 = sig*90 if textAnchor!='start': if textAnchor=='middle': phi += sig*(0.5*width)/radius elif textAnchor=='end': phi += sig*float(width)/radius elif textAnchor=='numeric': phi += sig*float(numericXShift(textAnchor,text,width,fontName,fontSize,None))/radius for letter in text: width = stringWidth(letter, fontName, fontSize) beta = float(width)/radius h = Group() h.add(String(0, 0, letter, fontName=fontName,fontSize=fontSize,textAnchor="start")) h.translate(x+cos(phi)*radius,y+sin(phi)*radius) #translate to radius and angle h.rotate((phi-hsig*beta)/pi180-sig90) # rotate as needed G.add(h) #add to main group phi -= sig*beta #increment return G class CustomDrawChanger: ''' a class to simplify making changes at draw time ''' def __init__(self): self.store = None def __call__(self,change,obj): if change: self.store = self._changer(obj) assert isinstance(self.store,dict), '%s.changer should return a dict of changed attributes' % self.__class__.__name__ elif self.store is not None: for a,v in self.store.items(): setattr(obj,a,v) self.store = None def _changer(self,obj): ''' When implemented this method should return a dictionary of original attribute values so that a future self(False,obj) can restore them. ''' raise RuntimeError('Abstract method _changer called')
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/graphics/charts/utils.py
0.505615
0.328705
utils.py
pypi
__version__='3.3.0' __doc__="""This will be a collection of legends to be used with charts.""" import copy, operator from reportlab.lib import colors from reportlab.lib.validators import isNumber, OneOf, isString, isColorOrNone,\ isNumberOrNone, isListOfNumbersOrNone, isStringOrNone, isBoolean,\ EitherOr, NoneOr, AutoOr, isAuto, Auto, isBoxAnchor, SequenceOf, isInstanceOf from reportlab.lib.attrmap import * from reportlab.pdfbase.pdfmetrics import stringWidth, getFont from reportlab.graphics.widgetbase import Widget, TypedPropertyCollection, PropHolder from reportlab.graphics.shapes import Drawing, Group, String, Rect, Line, STATE_DEFAULTS from reportlab.graphics.charts.areas import PlotArea from reportlab.graphics.widgets.markers import uSymbol2Symbol, isSymbol from reportlab.lib.utils import isSeq, find_locals from reportlab.graphics.shapes import _baseGFontName from functools import reduce def _transMax(n,A): X = n*[0] m = 0 for a in A: m = max(m,len(a)) for i,x in enumerate(a): X[i] = max(X[i],x) X = [0] + X[:m] for i in range(m): X[i+1] += X[i] return X def _objStr(s): if isinstance(s,str): return s else: return str(s) def _getStr(s): if isSeq(s): return list(map(_getStr,s)) else: return _objStr(s) def _getLines(s): if isSeq(s): return tuple([(x or '').split('\n') for x in s]) else: return (s or '').split('\n') def _getLineCount(s): T = _getLines(s) if isSeq(s): return max([len(x) for x in T]) else: return len(T) def _getWidths(i,s, fontName, fontSize, subCols): S = [] aS = S.append if isSeq(s): for j,t in enumerate(s): sc = subCols[j,i] fN = getattr(sc,'fontName',fontName) fS = getattr(sc,'fontSize',fontSize) m = [stringWidth(x, fN, fS) for x in t.split('\n')] m = max(sc.minWidth,m and max(m) or 0) aS(m) aS(sc.rpad) del S[-1] else: sc = subCols[0,i] fN = getattr(sc,'fontName',fontName) fS = getattr(sc,'fontSize',fontSize) m = [stringWidth(x, fN, fS) for x in s.split('\n')] aS(max(sc.minWidth,m and max(m) or 0)) return S class SubColProperty(PropHolder): dividerLines = 0 _attrMap = AttrMap( minWidth = AttrMapValue(isNumber,desc="minimum width for this subcol"), rpad = AttrMapValue(isNumber,desc="right padding for this subcol"), align = AttrMapValue(OneOf('left','right','center','centre','numeric'),desc='alignment in subCol'), fontName = AttrMapValue(isString, desc="Font name of the strings"), fontSize = AttrMapValue(isNumber, desc="Font size of the strings"), leading = AttrMapValue(isNumber, desc="leading for the strings"), fillColor = AttrMapValue(isColorOrNone, desc="fontColor"), underlines = AttrMapValue(EitherOr((NoneOr(isInstanceOf(Line)),SequenceOf(isInstanceOf(Line),emptyOK=0,lo=0,hi=0x7fffffff))), desc="underline definitions"), overlines = AttrMapValue(EitherOr((NoneOr(isInstanceOf(Line)),SequenceOf(isInstanceOf(Line),emptyOK=0,lo=0,hi=0x7fffffff))), desc="overline definitions"), dx = AttrMapValue(isNumber, desc="x offset from default position"), dy = AttrMapValue(isNumber, desc="y offset from default position"), ) class LegendCallout: def _legendValues(legend,*args): '''return a tuple of values from the first function up the stack with isinstance(self,legend)''' L = find_locals(lambda L: L.get('self',None) is legend and L or None) return tuple([L[a] for a in args]) _legendValues = staticmethod(_legendValues) def _selfOrLegendValues(self,legend,*args): L = find_locals(lambda L: L.get('self',None) is legend and L or None) return tuple([getattr(self,a,L[a]) for a in args]) def __call__(self,legend,g,thisx,y,colName): col, name = colName class LegendSwatchCallout(LegendCallout): def __call__(self,legend,g,thisx,y,i,colName,swatch): col, name = colName class LegendColEndCallout(LegendCallout): def __call__(self,legend, g, x, xt, y, width, lWidth): pass class Legend(Widget): """A simple legend containing rectangular swatches and strings. The swatches are filled rectangles whenever the respective color object in 'colorNamePairs' is a subclass of Color in reportlab.lib.colors. Otherwise the object passed instead is assumed to have 'x', 'y', 'width' and 'height' attributes. A legend then tries to set them or catches any error. This lets you plug-in any widget you like as a replacement for the default rectangular swatches. Strings can be nicely aligned left or right to the swatches. """ _attrMap = AttrMap( x = AttrMapValue(isNumber, desc="x-coordinate of upper-left reference point"), y = AttrMapValue(isNumber, desc="y-coordinate of upper-left reference point"), deltax = AttrMapValue(isNumberOrNone, desc="x-distance between neighbouring swatches"), deltay = AttrMapValue(isNumberOrNone, desc="y-distance between neighbouring swatches"), dxTextSpace = AttrMapValue(isNumber, desc="Distance between swatch rectangle and text"), autoXPadding = AttrMapValue(isNumber, desc="x Padding between columns if deltax=None",advancedUsage=1), autoYPadding = AttrMapValue(isNumber, desc="y Padding between rows if deltay=None",advancedUsage=1), yGap = AttrMapValue(isNumber, desc="Additional gap between rows",advancedUsage=1), dx = AttrMapValue(isNumber, desc="Width of swatch rectangle"), dy = AttrMapValue(isNumber, desc="Height of swatch rectangle"), columnMaximum = AttrMapValue(isNumber, desc="Max. number of items per column"), alignment = AttrMapValue(OneOf("left", "right"), desc="Alignment of text with respect to swatches"), colorNamePairs = AttrMapValue(None, desc="List of color/name tuples (color can also be widget)"), fontName = AttrMapValue(isString, desc="Font name of the strings"), fontSize = AttrMapValue(isNumber, desc="Font size of the strings"), fillColor = AttrMapValue(isColorOrNone, desc="swatches filling color"), strokeColor = AttrMapValue(isColorOrNone, desc="Border color of the swatches"), strokeWidth = AttrMapValue(isNumber, desc="Width of the border color of the swatches"), swatchMarker = AttrMapValue(NoneOr(AutoOr(isSymbol)), desc="None, Auto() or makeMarker('Diamond') ...",advancedUsage=1), callout = AttrMapValue(None, desc="a user callout(self,g,x,y,(color,text))",advancedUsage=1), boxAnchor = AttrMapValue(isBoxAnchor,'Anchor point for the legend area'), variColumn = AttrMapValue(isBoolean,'If true column widths may vary (default is false)',advancedUsage=1), dividerLines = AttrMapValue(OneOf(0,1,2,3,4,5,6,7),'If 1 we have dividers between the rows | 2 for extra top | 4 for bottom',advancedUsage=1), dividerWidth = AttrMapValue(isNumber, desc="dividerLines width",advancedUsage=1), dividerColor = AttrMapValue(isColorOrNone, desc="dividerLines color",advancedUsage=1), dividerDashArray = AttrMapValue(isListOfNumbersOrNone, desc='Dash array for dividerLines.',advancedUsage=1), dividerOffsX = AttrMapValue(SequenceOf(isNumber,emptyOK=0,lo=2,hi=2), desc='divider lines X offsets',advancedUsage=1), dividerOffsY = AttrMapValue(isNumber, desc="dividerLines Y offset",advancedUsage=1), colEndCallout = AttrMapValue(None, desc="a user callout(self,g, x, xt, y,width, lWidth)",advancedUsage=1), subCols = AttrMapValue(None,desc="subColumn properties"), swatchCallout = AttrMapValue(None, desc="a user swatch callout(self,g,x,y,i,(col,name),swatch)",advancedUsage=1), swdx = AttrMapValue(isNumber, desc="x position adjustment for the swatch"), swdy = AttrMapValue(isNumber, desc="y position adjustment for the swatch"), ) def __init__(self): # Upper-left reference point. self.x = 0 self.y = 0 # Alginment of text with respect to swatches. self.alignment = "left" # x- and y-distances between neighbouring swatches. self.deltax = 75 self.deltay = 20 self.autoXPadding = 5 self.autoYPadding = 2 # Size of swatch rectangle. self.dx = 10 self.dy = 10 self.swdx = 0 self.swdy = 0 # Distance between swatch rectangle and text. self.dxTextSpace = 10 # Max. number of items per column. self.columnMaximum = 3 # Color/name pairs. self.colorNamePairs = [ (colors.red, "red"), (colors.blue, "blue"), (colors.green, "green"), (colors.pink, "pink"), (colors.yellow, "yellow") ] # Font name and size of the labels. self.fontName = STATE_DEFAULTS['fontName'] self.fontSize = STATE_DEFAULTS['fontSize'] self.fillColor = STATE_DEFAULTS['fillColor'] self.strokeColor = STATE_DEFAULTS['strokeColor'] self.strokeWidth = STATE_DEFAULTS['strokeWidth'] self.swatchMarker = None self.boxAnchor = 'nw' self.yGap = 0 self.variColumn = 0 self.dividerLines = 0 self.dividerWidth = 0.5 self.dividerDashArray = None self.dividerColor = colors.black self.dividerOffsX = (0,0) self.dividerOffsY = 0 self.colEndCallout = None self._init_subCols() def _init_subCols(self): sc = self.subCols = TypedPropertyCollection(SubColProperty) sc.rpad = 1 sc.dx = sc.dy = sc.minWidth = 0 sc.align = 'right' sc[0].align = 'left' def _getChartStyleName(self,chart): for a in 'lines', 'bars', 'slices', 'strands': if hasattr(chart,a): return a return None def _getChartStyle(self,chart): return getattr(chart,self._getChartStyleName(chart),None) def _getTexts(self,colorNamePairs): if not isAuto(colorNamePairs): texts = [_getStr(p[1]) for p in colorNamePairs] else: chart = getattr(colorNamePairs,'chart',getattr(colorNamePairs,'obj',None)) texts = [chart.getSeriesName(i,'series %d' % i) for i in range(chart._seriesCount)] return texts def _calculateMaxBoundaries(self, colorNamePairs): "Calculate the maximum width of some given strings." fontName = self.fontName fontSize = self.fontSize subCols = self.subCols M = [_getWidths(i, m, fontName, fontSize, subCols) for i,m in enumerate(self._getTexts(colorNamePairs))] if not M: return [0,0] n = max([len(m) for m in M]) if self.variColumn: columnMaximum = self.columnMaximum return [_transMax(n,M[r:r+columnMaximum]) for r in range(0,len(M),self.columnMaximum)] else: return _transMax(n,M) def _calcHeight(self): dy = self.dy yGap = self.yGap thisy = upperlefty = self.y - dy fontSize = self.fontSize ascent=getFont(self.fontName).face.ascent/1000. if ascent==0: ascent=0.718 # default (from helvetica) ascent *= fontSize leading = fontSize*1.2 deltay = self.deltay if not deltay: deltay = max(dy,leading)+self.autoYPadding columnCount = 0 count = 0 lowy = upperlefty lim = self.columnMaximum - 1 for name in self._getTexts(self.colorNamePairs): y0 = thisy+(dy-ascent)*0.5 y = y0 - _getLineCount(name)*leading leadingMove = 2*y0-y-thisy newy = thisy-max(deltay,leadingMove)-yGap lowy = min(y,newy,lowy) if count==lim: count = 0 thisy = upperlefty columnCount = columnCount + 1 else: thisy = newy count = count+1 return upperlefty - lowy def _defaultSwatch(self,x,thisy,dx,dy,fillColor,strokeWidth,strokeColor): return Rect(x, thisy, dx, dy, fillColor = fillColor, strokeColor = strokeColor, strokeWidth = strokeWidth, ) def draw(self): colorNamePairs = self.colorNamePairs autoCP = isAuto(colorNamePairs) if autoCP: chart = getattr(colorNamePairs,'chart',getattr(colorNamePairs,'obj',None)) swatchMarker = None autoCP = Auto(obj=chart) n = chart._seriesCount chartTexts = self._getTexts(colorNamePairs) else: swatchMarker = getattr(self,'swatchMarker',None) if isAuto(swatchMarker): chart = getattr(swatchMarker,'chart',getattr(swatchMarker,'obj',None)) swatchMarker = Auto(obj=chart) n = len(colorNamePairs) dx = self.dx dy = self.dy alignment = self.alignment columnMaximum = self.columnMaximum deltax = self.deltax deltay = self.deltay dxTextSpace = self.dxTextSpace fontName = self.fontName fontSize = self.fontSize fillColor = self.fillColor strokeWidth = self.strokeWidth strokeColor = self.strokeColor subCols = self.subCols leading = fontSize*1.2 yGap = self.yGap if not deltay: deltay = max(dy,leading)+self.autoYPadding ba = self.boxAnchor maxWidth = self._calculateMaxBoundaries(colorNamePairs) nCols = int((n+columnMaximum-1)/(columnMaximum*1.0)) xW = dx+dxTextSpace+self.autoXPadding variColumn = self.variColumn if variColumn: width = sum([m[-1] for m in maxWidth])+xW*nCols else: deltax = max(maxWidth[-1]+xW,deltax) width = nCols*deltax maxWidth = nCols*[maxWidth] thisx = self.x thisy = self.y - self.dy if ba not in ('ne','n','nw','autoy'): height = self._calcHeight() if ba in ('e','c','w'): thisy += height/2. else: thisy += height if ba not in ('nw','w','sw','autox'): if ba in ('n','c','s'): thisx -= width/2 else: thisx -= width upperlefty = thisy g = Group() ascent=getFont(fontName).face.ascent/1000. if ascent==0: ascent=0.718 # default (from helvetica) ascent *= fontSize # normalize lim = columnMaximum - 1 callout = getattr(self,'callout',None) scallout = getattr(self,'swatchCallout',None) dividerLines = self.dividerLines if dividerLines: dividerWidth = self.dividerWidth dividerColor = self.dividerColor dividerDashArray = self.dividerDashArray dividerOffsX = self.dividerOffsX dividerOffsY = self.dividerOffsY for i in xrange(n): if autoCP: col = autoCP col.index = i name = chartTexts[i] else: col, name = colorNamePairs[i] if isAuto(swatchMarker): col = swatchMarker col.index = i if isAuto(name): name = getattr(swatchMarker,'chart',getattr(swatchMarker,'obj',None)).getSeriesName(i,'series %d' % i) T = _getLines(name) S = [] aS = S.append j = int(i/(columnMaximum*1.0)) jOffs = maxWidth[j] # thisy+dy/2 = y+leading/2 y = y0 = thisy+(dy-ascent)*0.5 if callout: callout(self,g,thisx,y,(col,name)) if alignment == "left": x = thisx xn = thisx+jOffs[-1]+dxTextSpace elif alignment == "right": x = thisx+dx+dxTextSpace xn = thisx else: raise ValueError("bad alignment") if not isSeq(name): T = [T] yd = y for k,lines in enumerate(T): y = y0 kk = k*2 x1 = x+jOffs[kk] x2 = x+jOffs[kk+1] sc = subCols[k,i] anchor = sc.align scdx = sc.dx scdy = sc.dy fN = getattr(sc,'fontName',fontName) fS = getattr(sc,'fontSize',fontSize) fC = getattr(sc,'fillColor',fillColor) fL = getattr(sc,'leading',1.2*fontSize) if fN==fontName: fA = (ascent*fS)/fontSize else: fA = getFont(fontName).face.ascent/1000. if fA==0: fA=0.718 fA *= fS if anchor=='left': anchor = 'start' xoffs = x1 elif anchor=='right': anchor = 'end' xoffs = x2 elif anchor=='numeric': xoffs = x2 else: anchor = 'middle' xoffs = 0.5*(x1+x2) for t in lines: aS(String(xoffs+scdx,y+scdy,t,fontName=fN,fontSize=fS,fillColor=fC, textAnchor = anchor)) y -= fL yd = min(yd,y) y += fL for iy, a in ((y-max(fL-fA,0),'underlines'),(y+fA,'overlines')): il = getattr(sc,a,None) if il: if not isinstance(il,(tuple,list)): il = (il,) for l in il: l = copy.copy(l) l.y1 += iy l.y2 += iy l.x1 += x1 l.x2 += x2 aS(l) x = xn y = yd leadingMove = 2*y0-y-thisy if dividerLines: xd = thisx+dx+dxTextSpace+jOffs[-1]+dividerOffsX[1] yd = thisy+dy*0.5+dividerOffsY if ((dividerLines&1) and i%columnMaximum) or ((dividerLines&2) and not i%columnMaximum): g.add(Line(thisx+dividerOffsX[0],yd,xd,yd, strokeColor=dividerColor, strokeWidth=dividerWidth, strokeDashArray=dividerDashArray)) if (dividerLines&4) and (i%columnMaximum==lim or i==(n-1)): yd -= max(deltay,leadingMove)+yGap g.add(Line(thisx+dividerOffsX[0],yd,xd,yd, strokeColor=dividerColor, strokeWidth=dividerWidth, strokeDashArray=dividerDashArray)) # Make a 'normal' color swatch... swatchX = x + getattr(self,'swdx',0) swatchY = thisy + getattr(self,'swdy',0) if isAuto(col): chart = getattr(col,'chart',getattr(col,'obj',None)) c = chart.makeSwatchSample(getattr(col,'index',i),swatchX,swatchY,dx,dy) elif isinstance(col, colors.Color): if isSymbol(swatchMarker): c = uSymbol2Symbol(swatchMarker,swatchX+dx/2.,swatchY+dy/2.,col) else: c = self._defaultSwatch(swatchX,swatchY,dx,dy,fillColor=col,strokeWidth=strokeWidth,strokeColor=strokeColor) elif col is not None: try: c = copy.deepcopy(col) c.x = swatchX c.y = swatchY c.width = dx c.height = dy except: c = None else: c = None if c: g.add(c) if scallout: scallout(self,g,thisx,y0,i,(col,name),c) for s in S: g.add(s) if self.colEndCallout and (i%columnMaximum==lim or i==(n-1)): if alignment == "left": xt = thisx else: xt = thisx+dx+dxTextSpace yd = thisy+dy*0.5+dividerOffsY - (max(deltay,leadingMove)+yGap) self.colEndCallout(self, g, thisx, xt, yd, jOffs[-1], jOffs[-1]+dx+dxTextSpace) if i%columnMaximum==lim: if variColumn: thisx += jOffs[-1]+xW else: thisx = thisx+deltax thisy = upperlefty else: thisy = thisy-max(deltay,leadingMove)-yGap return g def demo(self): "Make sample legend." d = Drawing(200, 100) legend = Legend() legend.alignment = 'left' legend.x = 0 legend.y = 100 legend.dxTextSpace = 5 items = 'red green blue yellow pink black white'.split() items = [(getattr(colors, i), i) for i in items] legend.colorNamePairs = items d.add(legend, 'legend') return d class TotalAnnotator(LegendColEndCallout): def __init__(self, lText='Total', rText='0.0', fontName=_baseGFontName, fontSize=10, fillColor=colors.black, strokeWidth=0.5, strokeColor=colors.black, strokeDashArray=None, dx=0, dy=0, dly=0, dlx=(0,0)): self.lText = lText self.rText = rText self.fontName = fontName self.fontSize = fontSize self.fillColor = fillColor self.dy = dy self.dx = dx self.dly = dly self.dlx = dlx self.strokeWidth = strokeWidth self.strokeColor = strokeColor self.strokeDashArray = strokeDashArray def __call__(self,legend, g, x, xt, y, width, lWidth): from reportlab.graphics.shapes import String, Line fontSize = self.fontSize fontName = self.fontName fillColor = self.fillColor strokeColor = self.strokeColor strokeWidth = self.strokeWidth ascent=getFont(fontName).face.ascent/1000. if ascent==0: ascent=0.718 # default (from helvetica) ascent *= fontSize leading = fontSize*1.2 yt = y+self.dy-ascent*1.3 if self.lText and fillColor: g.add(String(xt,yt,self.lText, fontName=fontName, fontSize=fontSize, fillColor=fillColor, textAnchor = "start")) if self.rText: g.add(String(xt+width,yt,self.rText, fontName=fontName, fontSize=fontSize, fillColor=fillColor, textAnchor = "end")) if strokeWidth and strokeColor: yL = y+self.dly-leading g.add(Line(x+self.dlx[0],yL,x+self.dlx[1]+lWidth,yL, strokeColor=strokeColor, strokeWidth=strokeWidth, strokeDashArray=self.strokeDashArray)) class LineSwatch(Widget): """basically a Line with properties added so it can be used in a LineLegend""" _attrMap = AttrMap( x = AttrMapValue(isNumber, desc="x-coordinate for swatch line start point"), y = AttrMapValue(isNumber, desc="y-coordinate for swatch line start point"), width = AttrMapValue(isNumber, desc="length of swatch line"), height = AttrMapValue(isNumber, desc="used for line strokeWidth"), strokeColor = AttrMapValue(isColorOrNone, desc="color of swatch line"), strokeDashArray = AttrMapValue(isListOfNumbersOrNone, desc="dash array for swatch line"), ) def __init__(self): from reportlab.lib.colors import red from reportlab.graphics.shapes import Line self.x = 0 self.y = 0 self.width = 20 self.height = 1 self.strokeColor = red self.strokeDashArray = None def draw(self): l = Line(self.x,self.y,self.x+self.width,self.y) l.strokeColor = self.strokeColor l.strokeDashArray = self.strokeDashArray l.strokeWidth = self.height return l class LineLegend(Legend): """A subclass of Legend for drawing legends with lines as the swatches rather than rectangles. Useful for lineCharts and linePlots. Should be similar in all other ways the the standard Legend class. """ def __init__(self): Legend.__init__(self) # Size of swatch rectangle. self.dx = 10 self.dy = 2 def _defaultSwatch(self,x,thisy,dx,dy,fillColor,strokeWidth,strokeColor): l = LineSwatch() l.x = x l.y = thisy l.width = dx l.height = dy l.strokeColor = fillColor return l def sample1c(): "Make sample legend." d = Drawing(200, 100) legend = Legend() legend.alignment = 'right' legend.x = 0 legend.y = 100 legend.dxTextSpace = 5 items = 'red green blue yellow pink black white'.split() items = [(getattr(colors, i), i) for i in items] legend.colorNamePairs = items d.add(legend, 'legend') return d def sample2c(): "Make sample legend." d = Drawing(200, 100) legend = Legend() legend.alignment = 'right' legend.x = 20 legend.y = 90 legend.deltax = 60 legend.dxTextSpace = 10 legend.columnMaximum = 4 items = 'red green blue yellow pink black white'.split() items = [(getattr(colors, i), i) for i in items] legend.colorNamePairs = items d.add(legend, 'legend') return d def sample3(): "Make sample legend with line swatches." d = Drawing(200, 100) legend = LineLegend() legend.alignment = 'right' legend.x = 20 legend.y = 90 legend.deltax = 60 legend.dxTextSpace = 10 legend.columnMaximum = 4 items = 'red green blue yellow pink black white'.split() items = [(getattr(colors, i), i) for i in items] legend.colorNamePairs = items d.add(legend, 'legend') return d def sample3a(): "Make sample legend with line swatches and dasharrays on the lines." d = Drawing(200, 100) legend = LineLegend() legend.alignment = 'right' legend.x = 20 legend.y = 90 legend.deltax = 60 legend.dxTextSpace = 10 legend.columnMaximum = 4 items = 'red green blue yellow pink black white'.split() darrays = ([2,1], [2,5], [2,2,5,5], [1,2,3,4], [4,2,3,4], [1,2,3,4,5,6], [1]) cnp = [] for i in range(0, len(items)): l = LineSwatch() l.strokeColor = getattr(colors, items[i]) l.strokeDashArray = darrays[i] cnp.append((l, items[i])) legend.colorNamePairs = cnp d.add(legend, 'legend') return d
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/graphics/charts/legends.py
0.793706
0.222257
legends.py
pypi
from reportlab.lib import colors from reportlab.lib.attrmap import * from reportlab.pdfgen.canvas import Canvas from reportlab.graphics.shapes import Group, Drawing, Ellipse, Wedge, String, STATE_DEFAULTS, Polygon, Line def _getShaded(col,shd=None,shading=0.1): if shd is None: from reportlab.lib.colors import Blacker if col: shd = Blacker(col,1-shading) return shd def _getLit(col,shd=None,lighting=0.1): if shd is None: from reportlab.lib.colors import Whiter if col: shd = Whiter(col,1-lighting) return shd def _draw_3d_bar(G, x1, x2, y0, yhigh, xdepth, ydepth, fillColor=None, fillColorShaded=None, strokeColor=None, strokeWidth=1, shading=0.1): fillColorShaded = _getShaded(fillColor,None,shading) fillColorShadedTop = _getShaded(fillColor,None,shading/2.0) def _add_3d_bar(x1, x2, y1, y2, xoff, yoff, G=G,strokeColor=strokeColor, strokeWidth=strokeWidth, fillColor=fillColor): G.add(Polygon((x1,y1, x1+xoff,y1+yoff, x2+xoff,y2+yoff, x2,y2), strokeWidth=strokeWidth, strokeColor=strokeColor, fillColor=fillColor,strokeLineJoin=1)) usd = max(y0, yhigh) if xdepth or ydepth: if y0!=yhigh: #non-zero height _add_3d_bar( x2, x2, y0, yhigh, xdepth, ydepth, fillColor=fillColorShaded) #side _add_3d_bar(x1, x2, usd, usd, xdepth, ydepth, fillColor=fillColorShadedTop) #top G.add(Polygon((x1,y0,x2,y0,x2,yhigh,x1,yhigh), strokeColor=strokeColor, strokeWidth=strokeWidth, fillColor=fillColor,strokeLineJoin=1)) #front if xdepth or ydepth: G.add(Line( x1, usd, x2, usd, strokeWidth=strokeWidth, strokeColor=strokeColor or fillColorShaded)) class _YStrip: def __init__(self,y0,y1, slope, fillColor, fillColorShaded, shading=0.1): self.y0 = y0 self.y1 = y1 self.slope = slope self.fillColor = fillColor self.fillColorShaded = _getShaded(fillColor,fillColorShaded,shading) def _ystrip_poly( x0, x1, y0, y1, xoff, yoff): return [x0,y0,x0+xoff,y0+yoff,x1+xoff,y1+yoff,x1,y1] def _make_3d_line_info( G, x0, x1, y0, y1, z0, z1, theta_x, theta_y, fillColor, fillColorShaded=None, tileWidth=1, strokeColor=None, strokeWidth=None, strokeDashArray=None, shading=0.1): zwidth = abs(z1-z0) xdepth = zwidth*theta_x ydepth = zwidth*theta_y depth_slope = xdepth==0 and 1e150 or -ydepth/float(xdepth) x = float(x1-x0) slope = x==0 and 1e150 or (y1-y0)/x c = slope>depth_slope and _getShaded(fillColor,fillColorShaded,shading) or fillColor zy0 = z0*theta_y zx0 = z0*theta_x tileStrokeWidth = 0.6 if tileWidth is None: D = [(x1,y1)] else: T = ((y1-y0)**2+(x1-x0)**2)**0.5 tileStrokeWidth *= tileWidth if T<tileWidth: D = [(x1,y1)] else: n = int(T/float(tileWidth))+1 dx = float(x1-x0)/n dy = float(y1-y0)/n D = [] a = D.append for i in range(1,n): a((x0+dx*i,y0+dy*i)) a = G.add x_0 = x0+zx0 y_0 = y0+zy0 for x,y in D: x_1 = x+zx0 y_1 = y+zy0 P = Polygon(_ystrip_poly(x_0, x_1, y_0, y_1, xdepth, ydepth), fillColor = c, strokeColor=c, strokeWidth=tileStrokeWidth) a((0,z0,z1,x_0,y_0,P)) x_0 = x_1 y_0 = y_1 from math import pi, sin, cos _pi_2 = pi*0.5 _2pi = 2*pi _180_pi=180./pi def _2rad(angle): return angle/_180_pi def mod_2pi(radians): radians = radians % _2pi if radians<-1e-6: radians += _2pi return radians def _2deg(o): return o*_180_pi def _360(a): a %= 360 if a<-1e-6: a += 360 return a _ZERO = 1e-8 _ONE = 1-_ZERO class _Segment: def __init__(self,s,i,data): S = data[s] x0 = S[i-1][0] y0 = S[i-1][1] x1 = S[i][0] y1 = S[i][1] if x1<x0: x0,y0,x1,y1 = x1,y1,x0,y0 # (y-y0)*(x1-x0) = (y1-y0)*(x-x0) # (x1-x0)*y + (y0-y1)*x = y0*(x1-x0)+x0*(y0-y1) # a*y+b*x = c self.a = float(x1-x0) self.b = float(y1-y0) self.x0 = x0 self.x1 = x1 self.y0 = y0 self.y1 = y1 self.series = s self.i = i self.s = s def __str__(self): return '[(%s,%s),(%s,%s)]' % (self.x0,self.y0,self.x1,self.y1) __repr__ = __str__ def intersect(self,o,I): '''try to find an intersection with _Segment o ''' x0 = self.x0 ox0 = o.x0 assert x0<=ox0 if ox0>self.x1: return 1 if o.s==self.s and o.i in (self.i-1,self.i+1): return a = self.a b = self.b oa = o.a ob = o.b det = ob*a - oa*b if -1e-8<det<1e-8: return dx = x0 - ox0 dy = self.y0 - o.y0 u = (oa*dy - ob*dx)/det ou = (a*dy - b*dx)/det if u<0 or u>1 or ou<0 or ou>1: return x = x0 + u*a y = self.y0 + u*b if _ZERO<u<_ONE: t = self.s,self.i,x,y if t not in I: I.append(t) if _ZERO<ou<_ONE: t = o.s,o.i,x,y if t not in I: I.append(t) def _segKey(a): return (a.x0,a.x1,a.y0,a.y1,a.s,a.i) def find_intersections(data,small=0): ''' data is a sequence of series each series is a list of (x,y) coordinates where x & y are ints or floats find_intersections returns a sequence of 4-tuples i, j, x, y where i is a data index j is an insertion position for data[i] and x, y are coordinates of an intersection of series data[i] with some other series. If correctly implemented we get all such intersections. We don't count endpoint intersections and consider parallel lines as non intersecting (even when coincident). We ignore segments that have an estimated size less than small. ''' #find all line segments S = [] a = S.append for s in range(len(data)): ds = data[s] if not ds: continue n = len(ds) if n==1: continue for i in range(1,n): seg = _Segment(s,i,data) if seg.a+abs(seg.b)>=small: a(seg) S.sort(key=_segKey) I = [] n = len(S) for i in range(0,n-1): s = S[i] for j in range(i+1,n): if s.intersect(S[j],I)==1: break I.sort() return I if __name__=='__main__': from reportlab.graphics.shapes import Drawing from reportlab.lib.colors import lightgrey, pink D = Drawing(300,200) _draw_3d_bar(D, 10, 20, 10, 50, 5, 5, fillColor=lightgrey, strokeColor=pink) _draw_3d_bar(D, 30, 40, 10, 45, 5, 5, fillColor=lightgrey, strokeColor=pink) D.save(formats=['pdf'],outDir='.',fnRoot='_draw_3d_bar') print(find_intersections([[(0,0.5),(1,0.5),(0.5,0),(0.5,1)],[(.2666666667,0.4),(0.1,0.4),(0.1,0.2),(0,0),(1,1)],[(0,1),(0.4,0.1),(1,0.1)]])) print(find_intersections([[(0.1, 0.2), (0.1, 0.4)], [(0, 1), (0.4, 0.1)]])) print(find_intersections([[(0.2, 0.4), (0.1, 0.4)], [(0.1, 0.8), (0.4, 0.1)]])) print(find_intersections([[(0,0),(1,1)],[(0.4,0.1),(1,0.1)]])) print(find_intersections([[(0,0.5),(1,0.5),(0.5,0),(0.5,1)],[(0,0),(1,1)],[(0.1,0.8),(0.4,0.1),(1,0.1)]]))
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/graphics/charts/utils3d.py
0.47926
0.399694
utils3d.py
pypi
from reportlab.graphics.charts.legends import Legend from reportlab.graphics.charts.lineplots import ScatterPlot from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin, String from reportlab.graphics.charts.textlabels import Label from reportlab.graphics.samples.excelcolors import * class Bubble(_DrawingEditorMixin,Drawing): def __init__(self,width=200,height=150,*args,**kw): Drawing.__init__(self,width,height,*args,**kw) self._add(self,ScatterPlot(),name='chart',validate=None,desc="The main chart") self.chart.width = 115 self.chart.height = 80 self.chart.x = 30 self.chart.y = 40 self.chart.lines[0].strokeColor = color01 self.chart.lines[1].strokeColor = color02 self.chart.lines[2].strokeColor = color03 self.chart.lines[3].strokeColor = color04 self.chart.lines[4].strokeColor = color05 self.chart.lines[5].strokeColor = color06 self.chart.lines[6].strokeColor = color07 self.chart.lines[7].strokeColor = color08 self.chart.lines[8].strokeColor = color09 self.chart.lines[9].strokeColor = color10 self.chart.lines.symbol.kind ='Circle' self.chart.lines.symbol.size = 15 self.chart.fillColor = backgroundGrey self.chart.lineLabels.fontName = 'Helvetica' self.chart.xValueAxis.labels.fontName = 'Helvetica' self.chart.xValueAxis.labels.fontSize = 7 self.chart.xValueAxis.forceZero = 0 self.chart.data = [((100,100), (200,200), (250,210), (300,300), (350,450))] self.chart.xValueAxis.avoidBoundFrac = 1 self.chart.xValueAxis.gridEnd = 115 self.chart.xValueAxis.tickDown = 3 self.chart.xValueAxis.visibleGrid = 1 self.chart.yValueAxis.tickLeft = 3 self.chart.yValueAxis.labels.fontName = 'Helvetica' self.chart.yValueAxis.labels.fontSize = 7 self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") self.Title.fontName = 'Helvetica-Bold' self.Title.fontSize = 7 self.Title.x = 100 self.Title.y = 135 self.Title._text = 'Chart Title' self.Title.maxWidth = 180 self.Title.height = 20 self.Title.textAnchor ='middle' self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") self.Legend.colorNamePairs = [(color01, 'Widgets')] self.Legend.fontName = 'Helvetica' self.Legend.fontSize = 7 self.Legend.x = 153 self.Legend.y = 85 self.Legend.dxTextSpace = 5 self.Legend.dy = 5 self.Legend.dx = 5 self.Legend.deltay = 5 self.Legend.alignment ='right' self.chart.lineLabelFormat = None self.chart.xLabel = 'X Axis' self.chart.y = 30 self.chart.yLabel = 'Y Axis' self.chart.yValueAxis.labelTextFormat = '%d' self.chart.yValueAxis.forceZero = 1 self.chart.xValueAxis.forceZero = 1 self._add(self,0,name='preview',validate=None,desc=None) if __name__=="__main__": #NORUNTESTS Bubble().save(formats=['pdf'],outDir=None,fnRoot='bubble')
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/graphics/samples/bubble.py
0.68763
0.151624
bubble.py
pypi
from reportlab.graphics.charts.piecharts import Pie from reportlab.graphics.samples.excelcolors import * from reportlab.graphics.widgets.grids import ShadedRect from reportlab.graphics.charts.legends import Legend from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin, String from reportlab.graphics.charts.textlabels import Label class ExplodedPie(_DrawingEditorMixin,Drawing): def __init__(self,width=200,height=150,*args,**kw): Drawing.__init__(self,width,height,*args,**kw) self._add(self,Pie(),name='chart',validate=None,desc="The main chart") self.chart.width = 100 self.chart.height = 100 self.chart.x = 25 self.chart.y = 25 self.chart.slices[0].fillColor = color01 self.chart.slices[1].fillColor = color02 self.chart.slices[2].fillColor = color03 self.chart.slices[3].fillColor = color04 self.chart.slices[4].fillColor = color05 self.chart.slices[5].fillColor = color06 self.chart.slices[6].fillColor = color07 self.chart.slices[7].fillColor = color08 self.chart.slices[8].fillColor = color09 self.chart.slices[9].fillColor = color10 self.chart.data = (100, 150, 180) self.chart.startAngle = -90 self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") self.Title.fontName = 'Helvetica-Bold' self.Title.fontSize = 7 self.Title.x = 100 self.Title.y = 135 self.Title._text = 'Chart Title' self.Title.maxWidth = 180 self.Title.height = 20 self.Title.textAnchor ='middle' self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") self.Legend.colorNamePairs = [(color01, 'North'), (color02, 'South'), (color03, 'Central')] self.Legend.fontName = 'Helvetica' self.Legend.fontSize = 7 self.Legend.x = 160 self.Legend.y = 85 self.Legend.dxTextSpace = 5 self.Legend.dy = 5 self.Legend.dx = 5 self.Legend.deltay = 5 self.Legend.alignment ='right' self.Legend.columnMaximum = 10 self.chart.slices.strokeWidth = 1 self.chart.slices.fontName = 'Helvetica' self.background = ShadedRect() self.background.fillColorStart = backgroundGrey self.background.fillColorEnd = backgroundGrey self.background.numShades = 1 self.background.strokeWidth = 0.5 self.background.x = 20 self.background.y = 20 self.chart.slices.popout = 5 self.background.height = 110 self.background.width = 110 self._add(self,0,name='preview',validate=None,desc=None) if __name__=="__main__": #NORUNTESTS ExplodedPie().save(formats=['pdf'],outDir=None,fnRoot='exploded_pie')
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/graphics/samples/exploded_pie.py
0.642545
0.165998
exploded_pie.py
pypi
from reportlab.graphics.charts.piecharts import Pie from reportlab.graphics.widgets.grids import ShadedRect from reportlab.graphics.charts.legends import Legend from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin, String from reportlab.graphics.charts.textlabels import Label from reportlab.graphics.samples.excelcolors import * class SimplePie(_DrawingEditorMixin,Drawing): def __init__(self,width=200,height=150,*args,**kw): Drawing.__init__(self,width,height,*args,**kw) self._add(self,Pie(),name='chart',validate=None,desc="The main chart") self.chart.width = 100 self.chart.height = 100 self.chart.x = 25 self.chart.y = 25 self.chart.slices[0].fillColor = color01 self.chart.slices[1].fillColor = color02 self.chart.slices[2].fillColor = color03 self.chart.slices[3].fillColor = color04 self.chart.slices[4].fillColor = color05 self.chart.slices[5].fillColor = color06 self.chart.slices[6].fillColor = color07 self.chart.slices[7].fillColor = color08 self.chart.slices[8].fillColor = color09 self.chart.slices[9].fillColor = color10 self.chart.data = (100, 150, 180) self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") self.Title.fontName = 'Helvetica-Bold' self.Title.fontSize = 7 self.Title.x = 100 self.Title.y = 135 self.Title._text = 'Chart Title' self.Title.maxWidth = 180 self.Title.height = 20 self.Title.textAnchor ='middle' self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") self.Legend.colorNamePairs = [(color01, 'North'), (color02, 'South'),(color03, 'Central')] self.Legend.fontName = 'Helvetica' self.Legend.fontSize = 7 self.Legend.x = 160 self.Legend.y = 85 self.Legend.dxTextSpace = 5 self.Legend.dy = 5 self.Legend.dx = 5 self.Legend.deltay = 5 self.Legend.alignment ='right' self.chart.slices.strokeWidth = 1 self.chart.slices.fontName = 'Helvetica' self.background = ShadedRect() self.background.fillColorStart = backgroundGrey self.background.fillColorEnd = backgroundGrey self.background.numShades = 1 self.background.strokeWidth = 0.5 self.background.x = 25 self.background.y = 25 self.Legend.columnMaximum = 10 self._add(self,0,name='preview',validate=None,desc=None) if __name__=="__main__": #NORUNTESTS SimplePie().save(formats=['pdf'],outDir=None,fnRoot=None)
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/graphics/samples/simple_pie.py
0.63861
0.17252
simple_pie.py
pypi
__version__='3.3.0' __doc__="""This file is a collection of widgets to produce some common signs and symbols. Widgets include: - ETriangle (an equilateral triangle), - RTriangle (a right angled triangle), - Octagon, - Crossbox, - Tickbox, - SmileyFace, - StopSign, - NoEntry, - NotAllowed (the red roundel from 'no smoking' signs), - NoSmoking, - DangerSign (a black exclamation point in a yellow triangle), - YesNo (returns a tickbox or a crossbox depending on a testvalue), - FloppyDisk, - ArrowOne, and - ArrowTwo """ from reportlab.lib import colors from reportlab.lib.validators import * from reportlab.lib.attrmap import * from reportlab.graphics import shapes from reportlab.graphics.widgetbase import Widget from reportlab.graphics import renderPDF class _Symbol(Widget): """Abstract base widget possible attributes: 'x', 'y', 'size', 'fillColor', 'strokeColor' """ _nodoc = 1 _attrMap = AttrMap( x = AttrMapValue(isNumber,desc='symbol x coordinate'), y = AttrMapValue(isNumber,desc='symbol y coordinate'), dx = AttrMapValue(isNumber,desc='symbol x coordinate adjustment'), dy = AttrMapValue(isNumber,desc='symbol x coordinate adjustment'), size = AttrMapValue(isNumber), fillColor = AttrMapValue(isColorOrNone), strokeColor = AttrMapValue(isColorOrNone), strokeWidth = AttrMapValue(isNumber), ) def __init__(self): assert self.__class__.__name__!='_Symbol', 'Abstract class _Symbol instantiated' self.x = self.y = self.dx = self.dy = 0 self.size = 100 self.fillColor = colors.red self.strokeColor = None self.strokeWidth = 0.1 def demo(self): D = shapes.Drawing(200, 100) s = float(self.size) ob = self.__class__() ob.x=50 ob.y=0 ob.draw() D.add(ob) D.add(shapes.String(ob.x+(s/2),(ob.y-12), ob.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=10)) return D class ETriangle(_Symbol): """This draws an equilateral triangle.""" def __init__(self): pass #AbstractSymbol def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # Triangle specific bits ae = s*0.125 #(ae = 'an eighth') triangle = shapes.Polygon(points = [ self.x, self.y, self.x+s, self.y, self.x+(s/2),self.y+s], fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth=s/50.) g.add(triangle) return g class RTriangle(_Symbol): """This draws a right-angled triangle. possible attributes: 'x', 'y', 'size', 'fillColor', 'strokeColor' """ def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.fillColor = colors.green self.strokeColor = None def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # Triangle specific bits ae = s*0.125 #(ae = 'an eighth') triangle = shapes.Polygon(points = [ self.x, self.y, self.x+s, self.y, self.x,self.y+s], fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth=s/50.) g.add(triangle) return g class Octagon(_Symbol): """This widget draws an Octagon. possible attributes: 'x', 'y', 'size', 'fillColor', 'strokeColor' """ def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.fillColor = colors.yellow self.strokeColor = None def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # Octagon specific bits athird=s/3 octagon = shapes.Polygon(points=[self.x+athird, self.y, self.x, self.y+athird, self.x, self.y+(athird*2), self.x+athird, self.y+s, self.x+(athird*2), self.y+s, self.x+s, self.y+(athird*2), self.x+s, self.y+athird, self.x+(athird*2), self.y], strokeColor = self.strokeColor, fillColor = self.fillColor, strokeWidth=10) g.add(octagon) return g class Crossbox(_Symbol): """This draws a black box with a red cross in it - a 'checkbox'. possible attributes: 'x', 'y', 'size', 'crossColor', 'strokeColor', 'crosswidth' """ _attrMap = AttrMap(BASE=_Symbol, crossColor = AttrMapValue(isColorOrNone), crosswidth = AttrMapValue(isNumber), ) def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.fillColor = colors.white self.crossColor = colors.red self.strokeColor = colors.black self.crosswidth = 10 def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # crossbox specific bits box = shapes.Rect(self.x+1, self.y+1, s-2, s-2, fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth=2) g.add(box) crossLine1 = shapes.Line(self.x+(s*0.15), self.y+(s*0.15), self.x+(s*0.85), self.y+(s*0.85), fillColor = self.crossColor, strokeColor = self.crossColor, strokeWidth = self.crosswidth) g.add(crossLine1) crossLine2 = shapes.Line(self.x+(s*0.15), self.y+(s*0.85), self.x+(s*0.85) ,self.y+(s*0.15), fillColor = self.crossColor, strokeColor = self.crossColor, strokeWidth = self.crosswidth) g.add(crossLine2) return g class Tickbox(_Symbol): """This draws a black box with a red tick in it - another 'checkbox'. possible attributes: 'x', 'y', 'size', 'tickColor', 'strokeColor', 'tickwidth' """ _attrMap = AttrMap(BASE=_Symbol, tickColor = AttrMapValue(isColorOrNone), tickwidth = AttrMapValue(isNumber), ) def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.tickColor = colors.red self.strokeColor = colors.black self.fillColor = colors.white self.tickwidth = 10 def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # tickbox specific bits box = shapes.Rect(self.x+1, self.y+1, s-2, s-2, fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth=2) g.add(box) tickLine = shapes.PolyLine(points = [self.x+(s*0.15), self.y+(s*0.35), self.x+(s*0.35), self.y+(s*0.15), self.x+(s*0.35), self.y+(s*0.15), self.x+(s*0.85) ,self.y+(s*0.85)], fillColor = self.tickColor, strokeColor = self.tickColor, strokeWidth = self.tickwidth) g.add(tickLine) return g class SmileyFace(_Symbol): """This draws a classic smiley face. possible attributes: 'x', 'y', 'size', 'fillColor' """ def __init__(self): _Symbol.__init__(self) self.x = 0 self.y = 0 self.size = 100 self.fillColor = colors.yellow self.strokeColor = colors.black def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # SmileyFace specific bits g.add(shapes.Circle(cx=self.x+(s/2), cy=self.y+(s/2), r=s/2, fillColor=self.fillColor, strokeColor=self.strokeColor, strokeWidth=max(s/38.,self.strokeWidth))) for i in (1,2): g.add(shapes.Ellipse(self.x+(s/3)*i,self.y+(s/3)*2, s/30, s/10, fillColor=self.strokeColor, strokeColor = self.strokeColor, strokeWidth=max(s/38.,self.strokeWidth))) # calculate a pointslist for the mouth # THIS IS A HACK! - don't use if there is a 'shapes.Arc' centerx=self.x+(s/2) centery=self.y+(s/2) radius=s/3 yradius = radius xradius = radius startangledegrees=200 endangledegrees=340 degreedelta = 1 pointslist = [] a = pointslist.append from math import sin, cos, pi degreestoradians = pi/180.0 radiansdelta = degreedelta*degreestoradians startangle = startangledegrees*degreestoradians endangle = endangledegrees*degreestoradians while endangle<startangle: endangle = endangle+2*pi angle = startangle while angle<endangle: x = centerx + cos(angle)*radius y = centery + sin(angle)*yradius a(x); a(y) angle = angle+radiansdelta # make the mouth smile = shapes.PolyLine(pointslist, fillColor = self.strokeColor, strokeColor = self.strokeColor, strokeWidth = max(s/38.,self.strokeWidth)) g.add(smile) return g class StopSign(_Symbol): """This draws a (British) stop sign. possible attributes: 'x', 'y', 'size' """ _attrMap = AttrMap(BASE=_Symbol, stopColor = AttrMapValue(isColorOrNone,desc='color of the word stop'), ) def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.strokeColor = colors.black self.fillColor = colors.orangered self.stopColor = colors.ghostwhite def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # stop-sign specific bits athird=s/3 outerOctagon = shapes.Polygon(points=[self.x+athird, self.y, self.x, self.y+athird, self.x, self.y+(athird*2), self.x+athird, self.y+s, self.x+(athird*2), self.y+s, self.x+s, self.y+(athird*2), self.x+s, self.y+athird, self.x+(athird*2), self.y], strokeColor = self.strokeColor, fillColor = None, strokeWidth=1) g.add(outerOctagon) innerOctagon = shapes.Polygon(points=[self.x+athird+(s/75), self.y+(s/75), self.x+(s/75), self.y+athird+(s/75), self.x+(s/75), self.y+(athird*2)-(s/75), self.x+athird+(s/75), self.y+s-(s/75), self.x+(athird*2)-(s/75), (self.y+s)-(s/75), (self.x+s)-(s/75), self.y+(athird*2)-(s/75), (self.x+s)-(s/75), self.y+athird+(s/75), self.x+(athird*2)-(s/75), self.y+(s/75)], strokeColor = None, fillColor = self.fillColor, strokeWidth=0) g.add(innerOctagon) if self.stopColor: g.add(shapes.String(self.x+(s*0.5),self.y+(s*0.4), 'STOP', fillColor=self.stopColor, textAnchor='middle', fontSize=s/3, fontName="Helvetica-Bold")) return g class NoEntry(_Symbol): """This draws a (British) No Entry sign - a red circle with a white line on it. possible attributes: 'x', 'y', 'size' """ _attrMap = AttrMap(BASE=_Symbol, innerBarColor = AttrMapValue(isColorOrNone,desc='color of the inner bar'), ) def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.strokeColor = colors.black self.fillColor = colors.orangered self.innerBarColor = colors.ghostwhite def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # no-entry-sign specific bits if self.strokeColor: g.add(shapes.Circle(cx = (self.x+(s/2)), cy = (self.y+(s/2)), r = s/2, fillColor = None, strokeColor = self.strokeColor, strokeWidth=1)) if self.fillColor: g.add(shapes.Circle(cx = (self.x+(s/2)), cy =(self.y+(s/2)), r = ((s/2)-(s/50)), fillColor = self.fillColor, strokeColor = None, strokeWidth=0)) innerBarColor = self.innerBarColor if innerBarColor: g.add(shapes.Rect(self.x+(s*0.1), self.y+(s*0.4), width=s*0.8, height=s*0.2, fillColor = innerBarColor, strokeColor = innerBarColor, strokeLineCap = 1, strokeWidth = 0)) return g class NotAllowed(_Symbol): """This draws a 'forbidden' roundel (as used in the no-smoking sign). possible attributes: 'x', 'y', 'size' """ _attrMap = AttrMap(BASE=_Symbol, ) def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.strokeColor = colors.red self.fillColor = colors.white def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() strokeColor = self.strokeColor # not=allowed specific bits outerCircle = shapes.Circle(cx = (self.x+(s/2)), cy = (self.y+(s/2)), r = (s/2)-(s/10), fillColor = self.fillColor, strokeColor = strokeColor, strokeWidth=s/10.) g.add(outerCircle) centerx=self.x+s centery=self.y+(s/2)-(s/6) radius=s-(s/6) yradius = radius/2 xradius = radius/2 startangledegrees=100 endangledegrees=-80 degreedelta = 90 pointslist = [] a = pointslist.append from math import sin, cos, pi degreestoradians = pi/180.0 radiansdelta = degreedelta*degreestoradians startangle = startangledegrees*degreestoradians endangle = endangledegrees*degreestoradians while endangle<startangle: endangle = endangle+2*pi angle = startangle while angle<endangle: x = centerx + cos(angle)*radius y = centery + sin(angle)*yradius a(x); a(y) angle = angle+radiansdelta crossbar = shapes.PolyLine(pointslist, fillColor = strokeColor, strokeColor = strokeColor, strokeWidth = s/10.) g.add(crossbar) return g class NoSmoking(NotAllowed): """This draws a no-smoking sign. possible attributes: 'x', 'y', 'size' """ def __init__(self): NotAllowed.__init__(self) def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = NotAllowed.draw(self) # no-smoking-sign specific bits newx = self.x+(s/2)-(s/3.5) newy = self.y+(s/2)-(s/32) cigarrette1 = shapes.Rect(x = newx, y = newy, width = (s/2), height =(s/16), fillColor = colors.ghostwhite, strokeColor = colors.gray, strokeWidth=0) newx=newx+(s/2)+(s/64) g.insert(-1,cigarrette1) cigarrette2 = shapes.Rect(x = newx, y = newy, width = (s/80), height =(s/16), fillColor = colors.orangered, strokeColor = None, strokeWidth=0) newx= newx+(s/35) g.insert(-1,cigarrette2) cigarrette3 = shapes.Rect(x = newx, y = newy, width = (s/80), height =(s/16), fillColor = colors.orangered, strokeColor = None, strokeWidth=0) newx= newx+(s/35) g.insert(-1,cigarrette3) cigarrette4 = shapes.Rect(x = newx, y = newy, width = (s/80), height =(s/16), fillColor = colors.orangered, strokeColor = None, strokeWidth=0) newx= newx+(s/35) g.insert(-1,cigarrette4) return g class DangerSign(_Symbol): """This draws a 'danger' sign: a yellow box with a black exclamation point. possible attributes: 'x', 'y', 'size', 'strokeColor', 'fillColor', 'strokeWidth' """ def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.strokeColor = colors.black self.fillColor = colors.gold self.strokeWidth = self.size*0.125 def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() ew = self.strokeWidth ae = s*0.125 #(ae = 'an eighth') # danger sign specific bits ew = self.strokeWidth ae = s*0.125 #(ae = 'an eighth') outerTriangle = shapes.Polygon(points = [ self.x, self.y, self.x+s, self.y, self.x+(s/2),self.y+s], fillColor = None, strokeColor = self.strokeColor, strokeWidth=0) g.add(outerTriangle) innerTriangle = shapes.Polygon(points = [ self.x+(s/50), self.y+(s/75), (self.x+s)-(s/50), self.y+(s/75), self.x+(s/2),(self.y+s)-(s/50)], fillColor = self.fillColor, strokeColor = None, strokeWidth=0) g.add(innerTriangle) exmark = shapes.Polygon(points=[ ((self.x+s/2)-ew/2), self.y+ae*2.5, ((self.x+s/2)+ew/2), self.y+ae*2.5, ((self.x+s/2)+((ew/2))+(ew/6)), self.y+ae*5.5, ((self.x+s/2)-((ew/2))-(ew/6)), self.y+ae*5.5], fillColor = self.strokeColor, strokeColor = None) g.add(exmark) exdot = shapes.Polygon(points=[ ((self.x+s/2)-ew/2), self.y+ae, ((self.x+s/2)+ew/2), self.y+ae, ((self.x+s/2)+ew/2), self.y+ae*2, ((self.x+s/2)-ew/2), self.y+ae*2], fillColor = self.strokeColor, strokeColor = None) g.add(exdot) return g class YesNo(_Symbol): """This widget draw a tickbox or crossbox depending on 'testValue'. If this widget is supplied with a 'True' or 1 as a value for testValue, it will use the tickbox widget. Otherwise, it will produce a crossbox. possible attributes: 'x', 'y', 'size', 'tickcolor', 'crosscolor', 'testValue' """ _attrMap = AttrMap(BASE=_Symbol, tickcolor = AttrMapValue(isColor), crosscolor = AttrMapValue(isColor), testValue = AttrMapValue(isBoolean), ) def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.tickcolor = colors.green self.crosscolor = colors.red self.testValue = 1 def draw(self): if self.testValue: yn=Tickbox() yn.tickColor=self.tickcolor else: yn=Crossbox() yn.crossColor=self.crosscolor yn.x=self.x yn.y=self.y yn.size=self.size yn.draw() return yn def demo(self): D = shapes.Drawing(200, 100) yn = YesNo() yn.x = 15 yn.y = 25 yn.size = 70 yn.testValue = 0 yn.draw() D.add(yn) yn2 = YesNo() yn2.x = 120 yn2.y = 25 yn2.size = 70 yn2.testValue = 1 yn2.draw() D.add(yn2) labelFontSize = 8 D.add(shapes.String(yn.x+(yn.size/2),(yn.y-(1.2*labelFontSize)), 'testValue=0', fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) D.add(shapes.String(yn2.x+(yn2.size/2),(yn2.y-(1.2*labelFontSize)), 'testValue=1', fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) labelFontSize = 10 D.add(shapes.String(yn.x+85,(yn.y-20), self.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) return D class FloppyDisk(_Symbol): """This widget draws an icon of a floppy disk. possible attributes: 'x', 'y', 'size', 'diskcolor' """ _attrMap = AttrMap(BASE=_Symbol, diskColor = AttrMapValue(isColor), ) def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.diskColor = colors.black def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # floppy disk specific bits diskBody = shapes.Rect(x=self.x, y=self.y+(s/100), width=s, height=s-(s/100), fillColor = self.diskColor, strokeColor = None, strokeWidth=0) g.add(diskBody) label = shapes.Rect(x=self.x+(s*0.1), y=(self.y+s)-(s*0.5), width=s*0.8, height=s*0.48, fillColor = colors.whitesmoke, strokeColor = None, strokeWidth=0) g.add(label) labelsplash = shapes.Rect(x=self.x+(s*0.1), y=(self.y+s)-(s*0.1), width=s*0.8, height=s*0.08, fillColor = colors.royalblue, strokeColor = None, strokeWidth=0) g.add(labelsplash) line1 = shapes.Line(x1=self.x+(s*0.15), y1=self.y+(0.6*s), x2=self.x+(s*0.85), y2=self.y+(0.6*s), fillColor = colors.black, strokeColor = colors.black, strokeWidth=0) g.add(line1) line2 = shapes.Line(x1=self.x+(s*0.15), y1=self.y+(0.7*s), x2=self.x+(s*0.85), y2=self.y+(0.7*s), fillColor = colors.black, strokeColor = colors.black, strokeWidth=0) g.add(line2) line3 = shapes.Line(x1=self.x+(s*0.15), y1=self.y+(0.8*s), x2=self.x+(s*0.85), y2=self.y+(0.8*s), fillColor = colors.black, strokeColor = colors.black, strokeWidth=0) g.add(line3) metalcover = shapes.Rect(x=self.x+(s*0.2), y=(self.y), width=s*0.5, height=s*0.35, fillColor = colors.silver, strokeColor = None, strokeWidth=0) g.add(metalcover) coverslot = shapes.Rect(x=self.x+(s*0.28), y=(self.y)+(s*0.035), width=s*0.12, height=s*0.28, fillColor = self.diskColor, strokeColor = None, strokeWidth=0) g.add(coverslot) return g class ArrowOne(_Symbol): """This widget draws an arrow (style one). possible attributes: 'x', 'y', 'size', 'fillColor' """ def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.fillColor = colors.red self.strokeWidth = 0 self.strokeColor = None def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() x = self.x y = self.y s2 = s/2 s3 = s/3 s5 = s/5 g.add(shapes.Polygon(points = [ x,y+s3, x,y+2*s3, x+s2,y+2*s3, x+s2,y+4*s5, x+s,y+s2, x+s2,y+s5, x+s2,y+s3, ], fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth = self.strokeWidth, ) ) return g class ArrowTwo(ArrowOne): """This widget draws an arrow (style two). possible attributes: 'x', 'y', 'size', 'fillColor' """ def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.fillColor = colors.blue self.strokeWidth = 0 self.strokeColor = None def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # arrow specific bits x = self.x y = self.y s2 = s/2 s3 = s/3 s5 = s/5 s24 = s/24 g.add(shapes.Polygon( points = [ x,y+11*s24, x,y+13*s24, x+18.75*s24, y+13*s24, x+2*s3, y+2*s3, x+s, y+s2, x+2*s3, y+s3, x+18.75*s24, y+11*s24, ], fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth = self.strokeWidth) ) return g def test(): """This function produces a pdf with examples of all the signs and symbols from this file. """ labelFontSize = 10 D = shapes.Drawing(450,650) cb = Crossbox() cb.x = 20 cb.y = 530 D.add(cb) D.add(shapes.String(cb.x+(cb.size/2),(cb.y-(1.2*labelFontSize)), cb.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) tb = Tickbox() tb.x = 170 tb.y = 530 D.add(tb) D.add(shapes.String(tb.x+(tb.size/2),(tb.y-(1.2*labelFontSize)), tb.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) yn = YesNo() yn.x = 320 yn.y = 530 D.add(yn) tempstring = yn.__class__.__name__ + '*' D.add(shapes.String(yn.x+(tb.size/2),(yn.y-(1.2*labelFontSize)), tempstring, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) D.add(shapes.String(130,6, "(The 'YesNo' widget returns a tickbox if testvalue=1, and a crossbox if testvalue=0)", fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize*0.75)) ss = StopSign() ss.x = 20 ss.y = 400 D.add(ss) D.add(shapes.String(ss.x+(ss.size/2), ss.y-(1.2*labelFontSize), ss.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) ne = NoEntry() ne.x = 170 ne.y = 400 D.add(ne) D.add(shapes.String(ne.x+(ne.size/2),(ne.y-(1.2*labelFontSize)), ne.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) sf = SmileyFace() sf.x = 320 sf.y = 400 D.add(sf) D.add(shapes.String(sf.x+(sf.size/2),(sf.y-(1.2*labelFontSize)), sf.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) ds = DangerSign() ds.x = 20 ds.y = 270 D.add(ds) D.add(shapes.String(ds.x+(ds.size/2),(ds.y-(1.2*labelFontSize)), ds.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) na = NotAllowed() na.x = 170 na.y = 270 D.add(na) D.add(shapes.String(na.x+(na.size/2),(na.y-(1.2*labelFontSize)), na.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) ns = NoSmoking() ns.x = 320 ns.y = 270 D.add(ns) D.add(shapes.String(ns.x+(ns.size/2),(ns.y-(1.2*labelFontSize)), ns.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) a1 = ArrowOne() a1.x = 20 a1.y = 140 D.add(a1) D.add(shapes.String(a1.x+(a1.size/2),(a1.y-(1.2*labelFontSize)), a1.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) a2 = ArrowTwo() a2.x = 170 a2.y = 140 D.add(a2) D.add(shapes.String(a2.x+(a2.size/2),(a2.y-(1.2*labelFontSize)), a2.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) fd = FloppyDisk() fd.x = 320 fd.y = 140 D.add(fd) D.add(shapes.String(fd.x+(fd.size/2),(fd.y-(1.2*labelFontSize)), fd.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) renderPDF.drawToFile(D, 'signsandsymbols.pdf', 'signsandsymbols.py') print('wrote file: signsandsymbols.pdf') if __name__=='__main__': test()
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/graphics/widgets/signsandsymbols.py
0.915207
0.347274
signsandsymbols.py
pypi
__version__='3.3.0' from reportlab.lib import colors from reportlab.lib.validators import isNumber, isColorOrNone, isBoolean, isListOfNumbers, OneOf, isListOfColors, isNumberOrNone from reportlab.lib.attrmap import AttrMap, AttrMapValue from reportlab.graphics.shapes import Drawing, Group, Line, Rect, LineShape, definePath, EmptyClipPath from reportlab.graphics.widgetbase import Widget def frange(start, end=None, inc=None): "A range function, that does accept float increments..." if end == None: end = start + 0.0 start = 0.0 if inc == None: inc = 1.0 L = [] end = end - inc*0.0001 #to avoid numrical problems while 1: next = start + len(L) * inc if inc > 0 and next >= end: break elif inc < 0 and next <= end: break L.append(next) return L def makeDistancesList(list): """Returns a list of distances between adjacent numbers in some input list. E.g. [1, 1, 2, 3, 5, 7] -> [0, 1, 1, 2, 2] """ d = [] for i in range(len(list[:-1])): d.append(list[i+1] - list[i]) return d class Grid(Widget): """This makes a rectangular grid of equidistant stripes. The grid contains an outer border rectangle, and stripes inside which can be drawn with lines and/or as solid tiles. The drawing order is: outer rectangle, then lines and tiles. The stripes' width is indicated as 'delta'. The sequence of stripes can have an offset named 'delta0'. Both values need to be positive! """ _attrMap = AttrMap( x = AttrMapValue(isNumber, desc="The grid's lower-left x position."), y = AttrMapValue(isNumber, desc="The grid's lower-left y position."), width = AttrMapValue(isNumber, desc="The grid's width."), height = AttrMapValue(isNumber, desc="The grid's height."), orientation = AttrMapValue(OneOf(('vertical', 'horizontal')), desc='Determines if stripes are vertical or horizontal.'), useLines = AttrMapValue(OneOf((0, 1)), desc='Determines if stripes are drawn with lines.'), useRects = AttrMapValue(OneOf((0, 1)), desc='Determines if stripes are drawn with solid rectangles.'), delta = AttrMapValue(isNumber, desc='Determines the width/height of the stripes.'), delta0 = AttrMapValue(isNumber, desc='Determines the stripes initial width/height offset.'), deltaSteps = AttrMapValue(isListOfNumbers, desc='List of deltas to be used cyclically.'), stripeColors = AttrMapValue(isListOfColors, desc='Colors applied cyclically in the right or upper direction.'), fillColor = AttrMapValue(isColorOrNone, desc='Background color for entire rectangle.'), strokeColor = AttrMapValue(isColorOrNone, desc='Color used for lines.'), strokeWidth = AttrMapValue(isNumber, desc='Width used for lines.'), rectStrokeColor = AttrMapValue(isColorOrNone, desc='Color for outer rect stroke.'), rectStrokeWidth = AttrMapValue(isNumberOrNone, desc='Width for outer rect stroke.'), ) def __init__(self): self.x = 0 self.y = 0 self.width = 100 self.height = 100 self.orientation = 'vertical' self.useLines = 0 self.useRects = 1 self.delta = 20 self.delta0 = 0 self.deltaSteps = [] self.fillColor = colors.white self.stripeColors = [colors.red, colors.green, colors.blue] self.strokeColor = colors.black self.strokeWidth = 2 def demo(self): D = Drawing(100, 100) g = Grid() D.add(g) return D def makeOuterRect(self): strokeColor = getattr(self,'rectStrokeColor',self.strokeColor) strokeWidth = getattr(self,'rectStrokeWidth',self.strokeWidth) if self.fillColor or (strokeColor and strokeWidth): rect = Rect(self.x, self.y, self.width, self.height) rect.fillColor = self.fillColor rect.strokeColor = strokeColor rect.strokeWidth = strokeWidth return rect else: return None def makeLinePosList(self, start, isX=0): "Returns a list of positions where to place lines." w, h = self.width, self.height if isX: length = w else: length = h if self.deltaSteps: r = [start + self.delta0] i = 0 while 1: if r[-1] > start + length: del r[-1] break r.append(r[-1] + self.deltaSteps[i % len(self.deltaSteps)]) i = i + 1 else: r = frange(start + self.delta0, start + length, self.delta) r.append(start + length) if self.delta0 != 0: r.insert(0, start) #print 'Grid.makeLinePosList() -> %s' % r return r def makeInnerLines(self): # inner grid lines group = Group() w, h = self.width, self.height if self.useLines == 1: if self.orientation == 'vertical': r = self.makeLinePosList(self.x, isX=1) for x in r: line = Line(x, self.y, x, self.y + h) line.strokeColor = self.strokeColor line.strokeWidth = self.strokeWidth group.add(line) elif self.orientation == 'horizontal': r = self.makeLinePosList(self.y, isX=0) for y in r: line = Line(self.x, y, self.x + w, y) line.strokeColor = self.strokeColor line.strokeWidth = self.strokeWidth group.add(line) return group def makeInnerTiles(self): # inner grid lines group = Group() w, h = self.width, self.height # inner grid stripes (solid rectangles) if self.useRects == 1: cols = self.stripeColors if self.orientation == 'vertical': r = self.makeLinePosList(self.x, isX=1) elif self.orientation == 'horizontal': r = self.makeLinePosList(self.y, isX=0) dist = makeDistancesList(r) i = 0 for j in range(len(dist)): if self.orientation == 'vertical': x = r[j] stripe = Rect(x, self.y, dist[j], h) elif self.orientation == 'horizontal': y = r[j] stripe = Rect(self.x, y, w, dist[j]) stripe.fillColor = cols[i % len(cols)] stripe.strokeColor = None group.add(stripe) i = i + 1 return group def draw(self): # general widget bits group = Group() group.add(self.makeOuterRect()) group.add(self.makeInnerTiles()) group.add(self.makeInnerLines(),name='_gridLines') return group class DoubleGrid(Widget): """This combines two ordinary Grid objects orthogonal to each other. """ _attrMap = AttrMap( x = AttrMapValue(isNumber, desc="The grid's lower-left x position."), y = AttrMapValue(isNumber, desc="The grid's lower-left y position."), width = AttrMapValue(isNumber, desc="The grid's width."), height = AttrMapValue(isNumber, desc="The grid's height."), grid0 = AttrMapValue(None, desc="The first grid component."), grid1 = AttrMapValue(None, desc="The second grid component."), ) def __init__(self): self.x = 0 self.y = 0 self.width = 100 self.height = 100 g0 = Grid() g0.x = self.x g0.y = self.y g0.width = self.width g0.height = self.height g0.orientation = 'vertical' g0.useLines = 1 g0.useRects = 0 g0.delta = 20 g0.delta0 = 0 g0.deltaSteps = [] g0.fillColor = colors.white g0.stripeColors = [colors.red, colors.green, colors.blue] g0.strokeColor = colors.black g0.strokeWidth = 1 g1 = Grid() g1.x = self.x g1.y = self.y g1.width = self.width g1.height = self.height g1.orientation = 'horizontal' g1.useLines = 1 g1.useRects = 0 g1.delta = 20 g1.delta0 = 0 g1.deltaSteps = [] g1.fillColor = colors.white g1.stripeColors = [colors.red, colors.green, colors.blue] g1.strokeColor = colors.black g1.strokeWidth = 1 self.grid0 = g0 self.grid1 = g1 ## # This gives an AttributeError: ## # DoubleGrid instance has no attribute 'grid0' ## def __setattr__(self, name, value): ## if name in ('x', 'y', 'width', 'height'): ## setattr(self.grid0, name, value) ## setattr(self.grid1, name, value) def demo(self): D = Drawing(100, 100) g = DoubleGrid() D.add(g) return D def draw(self): group = Group() g0, g1 = self.grid0, self.grid1 # Order groups to make sure both v and h lines # are visible (works only when there is only # one kind of stripes, v or h). G = g0.useRects == 1 and g1.useRects == 0 and (g0,g1) or (g1,g0) for g in G: group.add(g.makeOuterRect()) for g in G: group.add(g.makeInnerTiles()) group.add(g.makeInnerLines(),name='_gridLines') return group class ShadedRect(Widget): """This makes a rectangle with shaded colors between two colors. Colors are interpolated linearly between 'fillColorStart' and 'fillColorEnd', both of which appear at the margins. If 'numShades' is set to one, though, only 'fillColorStart' is used. """ _attrMap = AttrMap( x = AttrMapValue(isNumber, desc="The grid's lower-left x position."), y = AttrMapValue(isNumber, desc="The grid's lower-left y position."), width = AttrMapValue(isNumber, desc="The grid's width."), height = AttrMapValue(isNumber, desc="The grid's height."), orientation = AttrMapValue(OneOf(('vertical', 'horizontal')), desc='Determines if stripes are vertical or horizontal.'), numShades = AttrMapValue(isNumber, desc='The number of interpolating colors.'), fillColorStart = AttrMapValue(isColorOrNone, desc='Start value of the color shade.'), fillColorEnd = AttrMapValue(isColorOrNone, desc='End value of the color shade.'), strokeColor = AttrMapValue(isColorOrNone, desc='Color used for border line.'), strokeWidth = AttrMapValue(isNumber, desc='Width used for lines.'), cylinderMode = AttrMapValue(isBoolean, desc='True if shading reverses in middle.'), ) def __init__(self,**kw): self.x = 0 self.y = 0 self.width = 100 self.height = 100 self.orientation = 'vertical' self.numShades = 20 self.fillColorStart = colors.pink self.fillColorEnd = colors.black self.strokeColor = colors.black self.strokeWidth = 2 self.cylinderMode = 0 self.setProperties(kw) def demo(self): D = Drawing(100, 100) g = ShadedRect() D.add(g) return D def _flipRectCorners(self): "Flip rectangle's corners if width or height is negative." x, y, width, height, fillColorStart, fillColorEnd = self.x, self.y, self.width, self.height, self.fillColorStart, self.fillColorEnd if width < 0 and height > 0: x = x + width width = -width if self.orientation=='vertical': fillColorStart, fillColorEnd = fillColorEnd, fillColorStart elif height<0 and width>0: y = y + height height = -height if self.orientation=='horizontal': fillColorStart, fillColorEnd = fillColorEnd, fillColorStart elif height < 0 and height < 0: x = x + width width = -width y = y + height height = -height return x, y, width, height, fillColorStart, fillColorEnd def draw(self): # general widget bits group = Group() x, y, w, h, c0, c1 = self._flipRectCorners() numShades = self.numShades if self.cylinderMode: if not numShades%2: numShades = numShades+1 halfNumShades = int((numShades-1)/2) + 1 num = float(numShades) # must make it float! vertical = self.orientation == 'vertical' if vertical: if numShades == 1: V = [x] else: V = frange(x, x + w, w/num) else: if numShades == 1: V = [y] else: V = frange(y, y + h, h/num) for v in V: stripe = vertical and Rect(v, y, w/num, h) or Rect(x, v, w, h/num) if self.cylinderMode: if V.index(v)>=halfNumShades: col = colors.linearlyInterpolatedColor(c1,c0,V[halfNumShades],V[-1], v) else: col = colors.linearlyInterpolatedColor(c0,c1,V[0],V[halfNumShades], v) else: col = colors.linearlyInterpolatedColor(c0,c1,V[0],V[-1], v) stripe.fillColor = col stripe.strokeColor = col stripe.strokeWidth = 1 group.add(stripe) if self.strokeColor and self.strokeWidth>=0: rect = Rect(x, y, w, h) rect.strokeColor = self.strokeColor rect.strokeWidth = self.strokeWidth rect.fillColor = None group.add(rect) return group def colorRange(c0, c1, n): "Return a range of intermediate colors between c0 and c1" if n==1: return [c0] C = [] if n>1: lim = n-1 for i in range(n): C.append(colors.linearlyInterpolatedColor(c0,c1,0,lim, i)) return C def centroid(P): '''compute average point of a set of points''' cx = 0 cy = 0 for x,y in P: cx+=x cy+=y n = float(len(P)) return cx/n, cy/n def rotatedEnclosingRect(P, angle, rect): ''' given P a sequence P of x,y coordinate pairs and an angle in degrees find the centroid of P and the axis at angle theta through it find the extreme points of P wrt axis parallel distance and axis orthogonal distance. Then compute the least rectangle that will still enclose P when rotated by angle. The class R ''' from math import pi, cos, sin, tan x0, y0 = centroid(P) theta = (angle/180.)*pi s,c=sin(theta),cos(theta) def parallelAxisDist(xy,s=s,c=c,x0=x0,y0=y0): x,y = xy return (s*(y-y0)+c*(x-x0)) def orthogonalAxisDist(xy,s=s,c=c,x0=x0,y0=y0): x,y = xy return (c*(y-y0)+s*(x-x0)) L = list(map(parallelAxisDist,P)) L.sort() a0, a1 = L[0], L[-1] L = list(map(orthogonalAxisDist,P)) L.sort() b0, b1 = L[0], L[-1] rect.x, rect.width = a0, a1-a0 rect.y, rect.height = b0, b1-b0 g = Group(transform=(c,s,-s,c,x0,y0)) g.add(rect) return g class ShadedPolygon(Widget,LineShape): _attrMap = AttrMap(BASE=LineShape, angle = AttrMapValue(isNumber,desc="Shading angle"), fillColorStart = AttrMapValue(isColorOrNone), fillColorEnd = AttrMapValue(isColorOrNone), numShades = AttrMapValue(isNumber, desc='The number of interpolating colors.'), cylinderMode = AttrMapValue(isBoolean, desc='True if shading reverses in middle.'), points = AttrMapValue(isListOfNumbers), ) def __init__(self,**kw): self.angle = 90 self.fillColorStart = colors.red self.fillColorEnd = colors.green self.cylinderMode = 0 self.numShades = 50 self.points = [-1,-1,2,2,3,-1] LineShape.__init__(self,kw) def draw(self): P = self.points P = list(map(lambda i, P=P:(P[i],P[i+1]),range(0,len(P),2))) path = definePath([('moveTo',)+P[0]]+[('lineTo',)+x for x in P[1:]]+['closePath'], fillColor=None, strokeColor=None) path.isClipPath = 1 g = Group() g.add(path) angle = self.angle orientation = 'vertical' if angle==180: angle = 0 elif angle in (90,270): orientation ='horizontal' angle = 0 rect = ShadedRect(strokeWidth=0,strokeColor=None,orientation=orientation) for k in 'fillColorStart', 'fillColorEnd', 'numShades', 'cylinderMode': setattr(rect,k,getattr(self,k)) g.add(rotatedEnclosingRect(P, angle, rect)) g.add(EmptyClipPath) path = path.copy() path.isClipPath = 0 path.strokeColor = self.strokeColor path.strokeWidth = self.strokeWidth g.add(path) return g if __name__=='__main__': #noruntests from reportlab.lib.colors import blue from reportlab.graphics.shapes import Drawing angle=45 D = Drawing(120,120) D.add(ShadedPolygon(points=(10,10,60,60,110,10),strokeColor=None,strokeWidth=1,angle=90,numShades=50,cylinderMode=0)) D.save(formats=['gif'],fnRoot='shobj',outDir='/tmp')
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/graphics/widgets/grids.py
0.609059
0.444324
grids.py
pypi
__version__='3.3.0' __doc__="""This file is a collection of flag graphics as widgets. All flags are represented at the ratio of 1:2, even where the official ratio for the flag is something else (such as 3:5 for the German national flag). The only exceptions are for where this would look _very_ wrong, such as the Danish flag whose (ratio is 28:37), or the Swiss flag (which is square). Unless otherwise stated, these flags are all the 'national flags' of the countries, rather than their state flags, naval flags, ensigns or any other variants. (National flags are the flag flown by civilians of a country and the ones usually used to represent a country abroad. State flags are the variants used by the government and by diplomatic missions overseas). To check on how close these are to the 'official' representations of flags, check the World Flag Database at http://www.flags.ndirect.co.uk/ The flags this file contains are: EU Members: United Kingdom, Austria, Belgium, Denmark, Finland, France, Germany, Greece, Ireland, Italy, Luxembourg, Holland (The Netherlands), Spain, Sweden Others: USA, Czech Republic, European Union, Switzerland, Turkey, Brazil (Brazilian flag contributed by Publio da Costa Melo [publio@planetarium.com.br]). """ from reportlab.lib import colors from reportlab.lib.validators import * from reportlab.lib.attrmap import * from reportlab.graphics.shapes import Line, Rect, Polygon, Drawing, Group, String, Circle, Wedge from reportlab.graphics.widgetbase import Widget from reportlab.graphics import renderPDF from reportlab.graphics.widgets.signsandsymbols import _Symbol import copy from math import sin, cos, pi validFlag=OneOf(None, 'UK', 'USA', 'Afghanistan', 'Austria', 'Belgium', 'China', 'Cuba', 'Denmark', 'Finland', 'France', 'Germany', 'Greece', 'Ireland', 'Italy', 'Japan', 'Luxembourg', 'Holland', 'Palestine', 'Portugal', 'Russia', 'Spain', 'Sweden', 'Norway', 'CzechRepublic', 'Turkey', 'Switzerland', 'EU', 'Brazil' ) _size = 100. class Star(_Symbol): """This draws a 5-pointed star. possible attributes: 'x', 'y', 'size', 'fillColor', 'strokeColor' """ _attrMap = AttrMap(BASE=_Symbol, angle = AttrMapValue(isNumber, desc='angle in degrees'), ) _size = 100. def __init__(self): _Symbol.__init__(self) self.size = 100 self.fillColor = colors.yellow self.strokeColor = None self.angle = 0 def demo(self): D = Drawing(200, 100) et = Star() et.x=50 et.y=0 D.add(et) labelFontSize = 10 D.add(String(et.x+(et.size/2.0),(et.y-(1.2*labelFontSize)), et.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) return D def draw(self): s = float(self.size) #abbreviate as we will use this a lot g = Group() # new algorithm from markers.StarFive R = float(self.size)/2 r = R*sin(18*(pi/180.0))/cos(36*(pi/180.0)) P = [] angle = 90 for i in range(5): for radius in R, r: theta = angle*(pi/180.0) P.append(radius*cos(theta)) P.append(radius*sin(theta)) angle = angle + 36 # star specific bits star = Polygon(P, fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth=s/50) g.rotate(self.angle) g.shift(self.x+self.dx,self.y+self.dy) g.add(star) return g class Flag(_Symbol): """This is a generic flag class that all the flags in this file use as a basis. This class basically provides edges and a tidy-up routine to hide any bits of line that overlap the 'outside' of the flag possible attributes: 'x', 'y', 'size', 'fillColor' """ _attrMap = AttrMap(BASE=_Symbol, fillColor = AttrMapValue(isColor, desc='Background color'), border = AttrMapValue(isBoolean, 'Whether a background is drawn'), kind = AttrMapValue(validFlag, desc='Which flag'), ) _cache = {} def __init__(self,**kw): _Symbol.__init__(self) self.kind = None self.size = 100 self.fillColor = colors.white self.border=1 self.setProperties(kw) def availableFlagNames(self): '''return a list of the things we can display''' return [x for x in self._attrMap['kind'].validate._enum if x is not None] def _Flag_None(self): s = _size # abbreviate as we will use this a lot g = Group() g.add(Rect(0, 0, s*2, s, fillColor = colors.purple, strokeColor = colors.black, strokeWidth=0)) return g def _borderDraw(self,f): s = self.size # abbreviate as we will use this a lot g = Group() g.add(f) x, y, sW = self.x+self.dx, self.y+self.dy, self.strokeWidth/2. g.insert(0,Rect(-sW, -sW, width=getattr(self,'_width',2*s)+3*sW, height=getattr(self,'_height',s)+2*sW, fillColor = None, strokeColor = self.strokeColor, strokeWidth=sW*2)) g.shift(x,y) g.scale(s/_size, s/_size) return g def draw(self): kind = self.kind or 'None' f = self._cache.get(kind) if not f: f = getattr(self,'_Flag_'+kind)() self._cache[kind] = f._explode() return self._borderDraw(f) def clone(self): return copy.copy(self) def demo(self): D = Drawing(200, 100) name = self.availableFlagNames() import time name = name[int(time.time()) % len(name)] fx = Flag() fx.kind = name fx.x = 0 fx.y = 0 D.add(fx) labelFontSize = 10 D.add(String(fx.x+(fx.size/2.0),(fx.y-(1.2*labelFontSize)), name, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) labelFontSize = int(fx.size/4.0) D.add(String(fx.x+(fx.size),(fx.y+((fx.size/2.0))), "SAMPLE", fillColor=colors.gold, textAnchor='middle', fontSize=labelFontSize, fontName="Helvetica-Bold")) return D def _Flag_UK(self): s = _size g = Group() w = s*2 g.add(Rect(0, 0, w, s, fillColor = colors.navy, strokeColor = colors.black, strokeWidth=0)) g.add(Polygon([0,0, s*.225,0, w,s*(1-.1125), w,s, w-s*.225,s, 0, s*.1125], fillColor = colors.mintcream, strokeColor=None, strokeWidth=0)) g.add(Polygon([0,s*(1-.1125), 0, s, s*.225,s, w, s*.1125, w,0, w-s*.225,0], fillColor = colors.mintcream, strokeColor=None, strokeWidth=0)) g.add(Polygon([0, s-(s/15.0), (s-((s/10.0)*4)), (s*0.65), (s-(s/10.0)*3), (s*0.65), 0, s], fillColor = colors.red, strokeColor = None, strokeWidth=0)) g.add(Polygon([0, 0, (s-((s/10.0)*3)), (s*0.35), (s-((s/10.0)*2)), (s*0.35), (s/10.0), 0], fillColor = colors.red, strokeColor = None, strokeWidth=0)) g.add(Polygon([w, s, (s+((s/10.0)*3)), (s*0.65), (s+((s/10.0)*2)), (s*0.65), w-(s/10.0), s], fillColor = colors.red, strokeColor = None, strokeWidth=0)) g.add(Polygon([w, (s/15.0), (s+((s/10.0)*4)), (s*0.35), (s+((s/10.0)*3)), (s*0.35), w, 0], fillColor = colors.red, strokeColor = None, strokeWidth=0)) g.add(Rect(((s*0.42)*2), 0, width=(0.16*s)*2, height=s, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0)) g.add(Rect(0, (s*0.35), width=w, height=s*0.3, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0)) g.add(Rect(((s*0.45)*2), 0, width=(0.1*s)*2, height=s, fillColor = colors.red, strokeColor = None, strokeWidth=0)) g.add(Rect(0, (s*0.4), width=w, height=s*0.2, fillColor = colors.red, strokeColor = None, strokeWidth=0)) return g def _Flag_USA(self): s = _size # abbreviate as we will use this a lot g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) g.add(box) for stripecounter in range (13,0, -1): stripeheight = s/13.0 if not (stripecounter%2 == 0): stripecolor = colors.red else: stripecolor = colors.mintcream redorwhiteline = Rect(0, (s-(stripeheight*stripecounter)), width=s*2, height=stripeheight, fillColor = stripecolor, strokeColor = None, strokeWidth=20) g.add(redorwhiteline) bluebox = Rect(0, (s-(stripeheight*7)), width=0.8*s, height=stripeheight*7, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) g.add(bluebox) lss = s*0.045 lss2 = lss/2.0 s9 = s/9.0 s7 = s/7.0 for starxcounter in range(5): for starycounter in range(4): ls = Star() ls.size = lss ls.x = 0-s/22.0+lss/2.0+s7+starxcounter*s7 ls.fillColor = colors.mintcream ls.y = s-(starycounter+1)*s9+lss2 g.add(ls) for starxcounter in range(6): for starycounter in range(5): ls = Star() ls.size = lss ls.x = 0-(s/22.0)+lss/2.0+s/14.0+starxcounter*s7 ls.fillColor = colors.mintcream ls.y = s-(starycounter+1)*s9+(s/18.0)+lss2 g.add(ls) return g def _Flag_Afghanistan(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) g.add(box) greenbox = Rect(0, ((s/3.0)*2.0), width=s*2.0, height=s/3.0, fillColor = colors.limegreen, strokeColor = None, strokeWidth=0) g.add(greenbox) blackbox = Rect(0, 0, width=s*2.0, height=s/3.0, fillColor = colors.black, strokeColor = None, strokeWidth=0) g.add(blackbox) return g def _Flag_Austria(self): s = _size # abbreviate as we will use this a lot g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) g.add(box) redbox1 = Rect(0, 0, width=s*2.0, height=s/3.0, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redbox1) redbox2 = Rect(0, ((s/3.0)*2.0), width=s*2.0, height=s/3.0, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redbox2) return g def _Flag_Belgium(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.black, strokeColor = colors.black, strokeWidth=0) g.add(box) box1 = Rect(0, 0, width=(s/3.0)*2.0, height=s, fillColor = colors.black, strokeColor = None, strokeWidth=0) g.add(box1) box2 = Rect(((s/3.0)*2.0), 0, width=(s/3.0)*2.0, height=s, fillColor = colors.gold, strokeColor = None, strokeWidth=0) g.add(box2) box3 = Rect(((s/3.0)*4.0), 0, width=(s/3.0)*2.0, height=s, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(box3) return g def _Flag_China(self): s = _size g = Group() self._width = w = s*1.5 g.add(Rect(0, 0, w, s, fillColor=colors.red, strokeColor=None, strokeWidth=0)) def addStar(x,y,size,angle,g=g,w=s/20.0,x0=0,y0=s/2.0): s = Star() s.fillColor=colors.yellow s.angle = angle s.size = size*w*2 s.x = x*w+x0 s.y = y*w+y0 g.add(s) addStar(5,5,3, 0) addStar(10,1,1,36.86989765) addStar(12,3,1,8.213210702) addStar(12,6,1,16.60154960) addStar(10,8,1,53.13010235) return g def _Flag_Cuba(self): s = _size g = Group() for i in range(5): stripe = Rect(0, i*s/5.0, width=s*2, height=s/5.0, fillColor = [colors.darkblue, colors.mintcream][i%2], strokeColor = None, strokeWidth=0) g.add(stripe) redwedge = Polygon(points = [ 0, 0, 4*s/5.0, (s/2.0), 0, s], fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redwedge) star = Star() star.x = 2.5*s/10.0 star.y = s/2.0 star.size = 3*s/10.0 star.fillColor = colors.white g.add(star) box = Rect(0, 0, s*2, s, fillColor = None, strokeColor = colors.black, strokeWidth=0) g.add(box) return g def _Flag_Denmark(self): s = _size g = Group() self._width = w = s*1.4 box = Rect(0, 0, w, s, fillColor = colors.red, strokeColor = colors.black, strokeWidth=0) g.add(box) whitebox1 = Rect(((s/5.0)*2), 0, width=s/6.0, height=s, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(whitebox1) whitebox2 = Rect(0, ((s/2.0)-(s/12.0)), width=w, height=s/6.0, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(whitebox2) return g def _Flag_Finland(self): s = _size g = Group() # crossbox specific bits box = Rect(0, 0, s*2, s, fillColor = colors.ghostwhite, strokeColor = colors.black, strokeWidth=0) g.add(box) blueline1 = Rect((s*0.6), 0, width=0.3*s, height=s, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) g.add(blueline1) blueline2 = Rect(0, (s*0.4), width=s*2, height=s*0.3, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) g.add(blueline2) return g def _Flag_France(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.navy, strokeColor = colors.black, strokeWidth=0) g.add(box) bluebox = Rect(0, 0, width=((s/3.0)*2.0), height=s, fillColor = colors.blue, strokeColor = None, strokeWidth=0) g.add(bluebox) whitebox = Rect(((s/3.0)*2.0), 0, width=((s/3.0)*2.0), height=s, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(whitebox) redbox = Rect(((s/3.0)*4.0), 0, width=((s/3.0)*2.0), height=s, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redbox) return g def _Flag_Germany(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.gold, strokeColor = colors.black, strokeWidth=0) g.add(box) blackbox1 = Rect(0, ((s/3.0)*2.0), width=s*2.0, height=s/3.0, fillColor = colors.black, strokeColor = None, strokeWidth=0) g.add(blackbox1) redbox1 = Rect(0, (s/3.0), width=s*2.0, height=s/3.0, fillColor = colors.orangered, strokeColor = None, strokeWidth=0) g.add(redbox1) return g def _Flag_Greece(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.gold, strokeColor = colors.black, strokeWidth=0) g.add(box) for stripecounter in range (9,0, -1): stripeheight = s/9.0 if not (stripecounter%2 == 0): stripecolor = colors.deepskyblue else: stripecolor = colors.mintcream blueorwhiteline = Rect(0, (s-(stripeheight*stripecounter)), width=s*2, height=stripeheight, fillColor = stripecolor, strokeColor = None, strokeWidth=20) g.add(blueorwhiteline) bluebox1 = Rect(0, ((s)-stripeheight*5), width=(stripeheight*5), height=stripeheight*5, fillColor = colors.deepskyblue, strokeColor = None, strokeWidth=0) g.add(bluebox1) whiteline1 = Rect(0, ((s)-stripeheight*3), width=stripeheight*5, height=stripeheight, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(whiteline1) whiteline2 = Rect((stripeheight*2), ((s)-stripeheight*5), width=stripeheight, height=stripeheight*5, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(whiteline2) return g def _Flag_Ireland(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.forestgreen, strokeColor = colors.black, strokeWidth=0) g.add(box) whitebox = Rect(((s*2.0)/3.0), 0, width=(2.0*(s*2.0)/3.0), height=s, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(whitebox) orangebox = Rect(((2.0*(s*2.0)/3.0)), 0, width=(s*2.0)/3.0, height=s, fillColor = colors.darkorange, strokeColor = None, strokeWidth=0) g.add(orangebox) return g def _Flag_Italy(self): s = _size g = Group() g.add(Rect(0,0,s*2,s,fillColor=colors.forestgreen,strokeColor=None, strokeWidth=0)) g.add(Rect((2*s)/3.0, 0, width=(s*4)/3.0, height=s, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0)) g.add(Rect((4*s)/3.0, 0, width=(s*2)/3.0, height=s, fillColor = colors.red, strokeColor = None, strokeWidth=0)) return g def _Flag_Japan(self): s = _size g = Group() w = self._width = s*1.5 g.add(Rect(0,0,w,s,fillColor=colors.mintcream,strokeColor=None, strokeWidth=0)) g.add(Circle(cx=w/2.0,cy=s/2.0,r=0.3*w,fillColor=colors.red,strokeColor=None, strokeWidth=0)) return g def _Flag_Luxembourg(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) g.add(box) redbox = Rect(0, ((s/3.0)*2.0), width=s*2.0, height=s/3.0, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redbox) bluebox = Rect(0, 0, width=s*2.0, height=s/3.0, fillColor = colors.dodgerblue, strokeColor = None, strokeWidth=0) g.add(bluebox) return g def _Flag_Holland(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) g.add(box) redbox = Rect(0, ((s/3.0)*2.0), width=s*2.0, height=s/3.0, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redbox) bluebox = Rect(0, 0, width=s*2.0, height=s/3.0, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) g.add(bluebox) return g def _Flag_Portugal(self): return Group() def _Flag_Russia(self): s = _size g = Group() w = self._width = s*1.5 t = s/3.0 g.add(Rect(0, 0, width=w, height=t, fillColor = colors.red, strokeColor = None, strokeWidth=0)) g.add(Rect(0, t, width=w, height=t, fillColor = colors.blue, strokeColor = None, strokeWidth=0)) g.add(Rect(0, 2*t, width=w, height=t, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0)) return g def _Flag_Spain(self): s = _size g = Group() w = self._width = s*1.5 g.add(Rect(0, 0, width=w, height=s, fillColor = colors.red, strokeColor = None, strokeWidth=0)) g.add(Rect(0, (s/4.0), width=w, height=s/2.0, fillColor = colors.yellow, strokeColor = None, strokeWidth=0)) return g def _Flag_Sweden(self): s = _size g = Group() self._width = s*1.4 box = Rect(0, 0, self._width, s, fillColor = colors.dodgerblue, strokeColor = colors.black, strokeWidth=0) g.add(box) box1 = Rect(((s/5.0)*2), 0, width=s/6.0, height=s, fillColor = colors.gold, strokeColor = None, strokeWidth=0) g.add(box1) box2 = Rect(0, ((s/2.0)-(s/12.0)), width=self._width, height=s/6.0, fillColor = colors.gold, strokeColor = None, strokeWidth=0) g.add(box2) return g def _Flag_Norway(self): s = _size g = Group() self._width = s*1.4 box = Rect(0, 0, self._width, s, fillColor = colors.red, strokeColor = colors.black, strokeWidth=0) g.add(box) box = Rect(0, 0, self._width, s, fillColor = colors.red, strokeColor = colors.black, strokeWidth=0) g.add(box) whiteline1 = Rect(((s*0.2)*2), 0, width=s*0.2, height=s, fillColor = colors.ghostwhite, strokeColor = None, strokeWidth=0) g.add(whiteline1) whiteline2 = Rect(0, (s*0.4), width=self._width, height=s*0.2, fillColor = colors.ghostwhite, strokeColor = None, strokeWidth=0) g.add(whiteline2) blueline1 = Rect(((s*0.225)*2), 0, width=0.1*s, height=s, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) g.add(blueline1) blueline2 = Rect(0, (s*0.45), width=self._width, height=s*0.1, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) g.add(blueline2) return g def _Flag_CzechRepublic(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) g.add(box) redbox = Rect(0, 0, width=s*2, height=s/2.0, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redbox) bluewedge = Polygon(points = [ 0, 0, s, (s/2.0), 0, s], fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) g.add(bluewedge) return g def _Flag_Palestine(self): s = _size g = Group() box = Rect(0, s/3.0, s*2, s/3.0, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(box) greenbox = Rect(0, 0, width=s*2, height=s/3.0, fillColor = colors.limegreen, strokeColor = None, strokeWidth=0) g.add(greenbox) blackbox = Rect(0, 2*s/3.0, width=s*2, height=s/3.0, fillColor = colors.black, strokeColor = None, strokeWidth=0) g.add(blackbox) redwedge = Polygon(points = [ 0, 0, 2*s/3.0, (s/2.0), 0, s], fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redwedge) return g def _Flag_Turkey(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.red, strokeColor = colors.black, strokeWidth=0) g.add(box) whitecircle = Circle(cx=((s*0.35)*2), cy=s/2.0, r=s*0.3, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(whitecircle) redcircle = Circle(cx=((s*0.39)*2), cy=s/2.0, r=s*0.24, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redcircle) ws = Star() ws.angle = 15 ws.size = s/5.0 ws.x = (s*0.5)*2+ws.size/2.0 ws.y = (s*0.5) ws.fillColor = colors.mintcream ws.strokeColor = None g.add(ws) return g def _Flag_Switzerland(self): s = _size g = Group() self._width = s g.add(Rect(0, 0, s, s, fillColor = colors.red, strokeColor = colors.black, strokeWidth=0)) g.add(Line((s/2.0), (s/5.5), (s/2), (s-(s/5.5)), fillColor = colors.mintcream, strokeColor = colors.mintcream, strokeWidth=(s/5.0))) g.add(Line((s/5.5), (s/2.0), (s-(s/5.5)), (s/2.0), fillColor = colors.mintcream, strokeColor = colors.mintcream, strokeWidth=s/5.0)) return g def _Flag_EU(self): s = _size g = Group() w = self._width = 1.5*s g.add(Rect(0, 0, w, s, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0)) centerx=w/2.0 centery=s/2.0 radius=s/3.0 yradius = radius xradius = radius nStars = 12 delta = 2*pi/nStars for i in range(nStars): rad = i*delta gs = Star() gs.x=cos(rad)*radius+centerx gs.y=sin(rad)*radius+centery gs.size=s/10.0 gs.fillColor=colors.gold g.add(gs) return g def _Flag_Brazil(self): s = _size # abbreviate as we will use this a lot g = Group() m = s/14.0 self._width = w = (m * 20) def addStar(x,y,size, g=g, w=w, s=s, m=m): st = Star() st.fillColor=colors.mintcream st.size = size*m st.x = (w/2.0) + (x * (0.35 * m)) st.y = (s/2.0) + (y * (0.35 * m)) g.add(st) g.add(Rect(0, 0, w, s, fillColor = colors.green, strokeColor = None, strokeWidth=0)) g.add(Polygon(points = [ 1.7*m, (s/2.0), (w/2.0), s-(1.7*m), w-(1.7*m),(s/2.0),(w/2.0), 1.7*m], fillColor = colors.yellow, strokeColor = None, strokeWidth=0)) g.add(Circle(cx=w/2.0, cy=s/2.0, r=3.5*m, fillColor=colors.blue,strokeColor=None, strokeWidth=0)) g.add(Wedge((w/2.0)-(2*m), 0, 8.5*m, 50, 98.1, 8.5*m, fillColor=colors.mintcream,strokeColor=None, strokeWidth=0)) g.add(Wedge((w/2.0), (s/2.0), 3.501*m, 156, 352, 3.501*m, fillColor=colors.mintcream,strokeColor=None, strokeWidth=0)) g.add(Wedge((w/2.0)-(2*m), 0, 8*m, 48.1, 100, 8*m, fillColor=colors.blue,strokeColor=None, strokeWidth=0)) g.add(Rect(0, 0, w, (s/4.0) + 1.7*m, fillColor = colors.green, strokeColor = None, strokeWidth=0)) g.add(Polygon(points = [ 1.7*m,(s/2.0), (w/2.0),s/2.0 - 2*m, w-(1.7*m),(s/2.0) , (w/2.0),1.7*m], fillColor = colors.yellow, strokeColor = None, strokeWidth=0)) g.add(Wedge(w/2.0, s/2.0, 3.502*m, 166, 342.1, 3.502*m, fillColor=colors.blue,strokeColor=None, strokeWidth=0)) addStar(3.2,3.5,0.3) addStar(-8.5,1.5,0.3) addStar(-7.5,-3,0.3) addStar(-4,-5.5,0.3) addStar(0,-4.5,0.3) addStar(7,-3.5,0.3) addStar(-3.5,-0.5,0.25) addStar(0,-1.5,0.25) addStar(1,-2.5,0.25) addStar(3,-7,0.25) addStar(5,-6.5,0.25) addStar(6.5,-5,0.25) addStar(7,-4.5,0.25) addStar(-5.5,-3.2,0.25) addStar(-6,-4.2,0.25) addStar(-1,-2.75,0.2) addStar(2,-5.5,0.2) addStar(4,-5.5,0.2) addStar(5,-7.5,0.2) addStar(5,-5.5,0.2) addStar(6,-5.5,0.2) addStar(-8.8,-3.2,0.2) addStar(2.5,0.5,0.2) addStar(-0.2,-3.2,0.14) addStar(-7.2,-2,0.14) addStar(0,-8,0.1) sTmp = "ORDEM E PROGRESSO" nTmp = len(sTmp) delta = 0.850848010347/nTmp radius = 7.9 *m centerx = (w/2.0)-(2*m) centery = 0 for i in range(nTmp): rad = 2*pi - i*delta -4.60766922527 x=cos(rad)*radius+centerx y=sin(rad)*radius+centery if i == 6: z = 0.35*m else: z= 0.45*m g2 = Group(String(x, y, sTmp[i], fontName='Helvetica-Bold', fontSize = z,strokeColor=None,fillColor=colors.green)) g2.rotate(rad) g.add(g2) return g def makeFlag(name): flag = Flag() flag.kind = name return flag def test(): """This function produces three pdf files with examples of all the signs and symbols from this file. """ # page 1 labelFontSize = 10 X = (20,245) flags = [ 'UK', 'USA', 'Afghanistan', 'Austria', 'Belgium', 'Denmark', 'Cuba', 'Finland', 'France', 'Germany', 'Greece', 'Ireland', 'Italy', 'Luxembourg', 'Holland', 'Palestine', 'Portugal', 'Spain', 'Sweden', 'Norway', 'CzechRepublic', 'Turkey', 'Switzerland', 'EU', 'Brazil', ] y = Y0 = 530 f = 0 D = None for name in flags: if not D: D = Drawing(450,650) flag = makeFlag(name) i = flags.index(name) flag.x = X[i%2] flag.y = y D.add(flag) D.add(String(flag.x+(flag.size/2.0),(flag.y-(1.2*labelFontSize)), name, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) if i%2: y = y - 125 if (i%2 and y<0) or name==flags[-1]: renderPDF.drawToFile(D, 'flags%02d.pdf'%f, 'flags.py - Page #%d'%(f+1)) y = Y0 f = f+1 D = None if __name__=='__main__': test()
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/graphics/widgets/flags.py
0.78838
0.498657
flags.py
pypi
__version__='3.3.0' __doc__="""This modules defines a collection of markers used in charts. """ from reportlab.graphics.shapes import Rect, Line, Circle, Polygon, Drawing, Group from reportlab.graphics.widgets.signsandsymbols import SmileyFace from reportlab.graphics.widgetbase import Widget from reportlab.lib.validators import isNumber, isColorOrNone, OneOf, Validator from reportlab.lib.attrmap import AttrMap, AttrMapValue from reportlab.lib.colors import black from reportlab.lib.utils import isFunction, isClass from reportlab.graphics.widgets.flags import Flag from math import sin, cos, pi _toradians = pi/180.0 class Marker(Widget): '''A polymorphic class of markers''' _attrMap = AttrMap(BASE=Widget, kind = AttrMapValue( OneOf(None, 'Square', 'Diamond', 'Circle', 'Cross', 'Triangle', 'StarSix', 'Pentagon', 'Hexagon', 'Heptagon', 'Octagon', 'StarFive', 'FilledSquare', 'FilledCircle', 'FilledDiamond', 'FilledCross', 'FilledTriangle','FilledStarSix', 'FilledPentagon', 'FilledHexagon', 'FilledHeptagon', 'FilledOctagon', 'FilledStarFive', 'Smiley','ArrowHead', 'FilledArrowHead'), desc='marker type name'), size = AttrMapValue(isNumber,desc='marker size'), x = AttrMapValue(isNumber,desc='marker x coordinate'), y = AttrMapValue(isNumber,desc='marker y coordinate'), dx = AttrMapValue(isNumber,desc='marker x coordinate adjustment'), dy = AttrMapValue(isNumber,desc='marker y coordinate adjustment'), angle = AttrMapValue(isNumber,desc='marker rotation'), fillColor = AttrMapValue(isColorOrNone, desc='marker fill colour'), strokeColor = AttrMapValue(isColorOrNone, desc='marker stroke colour'), strokeWidth = AttrMapValue(isNumber, desc='marker stroke width'), arrowBarbDx = AttrMapValue(isNumber, desc='arrow only the delta x for the barbs'), arrowHeight = AttrMapValue(isNumber, desc='arrow only height'), ) def __init__(self,*args,**kw): self.setProperties(kw) self._setKeywords( kind = None, strokeColor = black, strokeWidth = 0.1, fillColor = None, size = 5, x = 0, y = 0, dx = 0, dy = 0, angle = 0, arrowBarbDx = -1.25, arrowHeight = 1.875, ) def clone(self,**kwds): n = self.__class__(**self.__dict__) if kwds: n.__dict__.update(kwds) return n def _Smiley(self): x, y = self.x+self.dx, self.y+self.dy d = self.size/2.0 s = SmileyFace() s.fillColor = self.fillColor s.strokeWidth = self.strokeWidth s.strokeColor = self.strokeColor s.x = x-d s.y = y-d s.size = d*2 return s def _Square(self): x, y = self.x+self.dx, self.y+self.dy d = self.size/2.0 s = Rect(x-d,y-d,2*d,2*d,fillColor=self.fillColor,strokeColor=self.strokeColor,strokeWidth=self.strokeWidth) return s def _Diamond(self): d = self.size/2.0 return self._doPolygon((-d,0,0,d,d,0,0,-d)) def _Circle(self): x, y = self.x+self.dx, self.y+self.dy s = Circle(x,y,self.size/2.0,fillColor=self.fillColor,strokeColor=self.strokeColor,strokeWidth=self.strokeWidth) return s def _Cross(self): x, y = self.x+self.dx, self.y+self.dy s = float(self.size) h, s = s/2, s/6 return self._doPolygon((-s,-h,-s,-s,-h,-s,-h,s,-s,s,-s,h,s,h,s,s,h,s,h,-s,s,-s,s,-h)) def _Triangle(self): x, y = self.x+self.dx, self.y+self.dy r = float(self.size)/2 c = 30*_toradians s = sin(30*_toradians)*r c = cos(c)*r return self._doPolygon((0,r,-c,-s,c,-s)) def _StarSix(self): r = float(self.size)/2 c = 30*_toradians s = sin(c)*r c = cos(c)*r z = s/2 g = c/2 return self._doPolygon((0,r,-z,s,-c,s,-s,0,-c,-s,-z,-s,0,-r,z,-s,c,-s,s,0,c,s,z,s)) def _StarFive(self): R = float(self.size)/2 r = R*sin(18*_toradians)/cos(36*_toradians) P = [] angle = 90 for i in range(5): for radius in R, r: theta = angle*_toradians P.append(radius*cos(theta)) P.append(radius*sin(theta)) angle = angle + 36 return self._doPolygon(P) def _Pentagon(self): return self._doNgon(5) def _Hexagon(self): return self._doNgon(6) def _Heptagon(self): return self._doNgon(7) def _Octagon(self): return self._doNgon(8) def _ArrowHead(self): s = self.size h = self.arrowHeight b = self.arrowBarbDx return self._doPolygon((0,0,b,-h,s,0,b,h)) def _doPolygon(self,P): x, y = self.x+self.dx, self.y+self.dy if x or y: P = list(map(lambda i,P=P,A=[x,y]: P[i] + A[i&1], list(range(len(P))))) return Polygon(P, strokeWidth =self.strokeWidth, strokeColor=self.strokeColor, fillColor=self.fillColor) def _doFill(self): old = self.fillColor if old is None: self.fillColor = self.strokeColor r = (self.kind and getattr(self,'_'+self.kind[6:]) or Group)() self.fillColor = old return r def _doNgon(self,n): P = [] size = float(self.size)/2 for i in range(n): r = (2.*i/n+0.5)*pi P.append(size*cos(r)) P.append(size*sin(r)) return self._doPolygon(P) _FilledCircle = _doFill _FilledSquare = _doFill _FilledDiamond = _doFill _FilledCross = _doFill _FilledTriangle = _doFill _FilledStarSix = _doFill _FilledPentagon = _doFill _FilledHexagon = _doFill _FilledHeptagon = _doFill _FilledOctagon = _doFill _FilledStarFive = _doFill _FilledArrowHead = _doFill def draw(self): if self.kind: m = getattr(self,'_'+self.kind) if self.angle: _x, _dx, _y, _dy = self.x, self.dx, self.y, self.dy self.x, self.dx, self.y, self.dy = 0,0,0,0 try: m = m() finally: self.x, self.dx, self.y, self.dy = _x, _dx, _y, _dy if not isinstance(m,Group): _m, m = m, Group() m.add(_m) if self.angle: m.rotate(self.angle) x, y = _x+_dx, _y+_dy if x or y: m.shift(x,y) else: m = m() else: m = Group() return m def uSymbol2Symbol(uSymbol,x,y,color): if isFunction(uSymbol): symbol = uSymbol(x, y, 5, color) elif isClass(uSymbol) and issubclass(uSymbol,Widget): size = 10. symbol = uSymbol() symbol.x = x - (size/2) symbol.y = y - (size/2) try: symbol.size = size symbol.color = color except: pass elif isinstance(uSymbol,Marker) or isinstance(uSymbol,Flag): symbol = uSymbol.clone() if isinstance(uSymbol,Marker): symbol.fillColor = symbol.fillColor or color symbol.x, symbol.y = x, y else: symbol = None return symbol class _isSymbol(Validator): def test(self,x): return hasattr(x,'__call__') or isinstance(x,Marker) or isinstance(x,Flag) or (isinstance(x,type) and issubclass(x,Widget)) isSymbol = _isSymbol() def makeMarker(name,**kw): if Marker._attrMap['kind'].validate(name): m = Marker(**kw) m.kind = name elif name[-5:]=='_Flag' and Flag._attrMap['kind'].validate(name[:-5]): m = Flag(**kw) m.kind = name[:-5] m.size = 10 else: raise ValueError("Invalid marker name %s" % name) return m if __name__=='__main__': D = Drawing() D.add(Marker()) D.save(fnRoot='Marker',formats=['pdf'], outDir='/tmp')
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/graphics/widgets/markers.py
0.87362
0.302198
markers.py
pypi
__version__='3.3.0' from reportlab.graphics.widgetbase import Widget from reportlab.graphics.charts.textlabels import Label from reportlab.graphics import shapes from reportlab.lib import colors from reportlab.lib.validators import * from reportlab.lib.attrmap import * from reportlab.graphics.shapes import Drawing class TableWidget(Widget): """A two dimensions table of labels """ _attrMap = AttrMap( x = AttrMapValue(isNumber, desc="x position of left edge of table"), y = AttrMapValue(isNumber, desc="y position of bottom edge of table"), width = AttrMapValue(isNumber, desc="table width"), height = AttrMapValue(isNumber, desc="table height"), borderStrokeColor = AttrMapValue(isColorOrNone, desc="table border color"), fillColor = AttrMapValue(isColorOrNone, desc="table fill color"), borderStrokeWidth = AttrMapValue(isNumber, desc="border line width"), horizontalDividerStrokeColor = AttrMapValue(isColorOrNone, desc="table inner horizontal lines color"), verticalDividerStrokeColor = AttrMapValue(isColorOrNone, desc="table inner vertical lines color"), horizontalDividerStrokeWidth = AttrMapValue(isNumber, desc="table inner horizontal lines width"), verticalDividerStrokeWidth = AttrMapValue(isNumber, desc="table inner vertical lines width"), dividerDashArray = AttrMapValue(isListOfNumbersOrNone, desc='Dash array for dividerLines.'), data = AttrMapValue(None, desc="a list of list of strings to be displayed in the cells"), boxAnchor = AttrMapValue(isBoxAnchor, desc="location of the table anchoring point"), fontName = AttrMapValue(isString, desc="text font in the table"), fontSize = AttrMapValue(isNumber, desc="font size of the table"), fontColor = AttrMapValue(isColorOrNone, desc="font color"), alignment = AttrMapValue(OneOf("left", "right"), desc="Alignment of text within cells"), textAnchor = AttrMapValue(OneOf('start','middle','end','numeric'), desc="Alignment of text within cells"), ) def __init__(self, x=10, y=10, **kw): self.x = x self.y = y self.width = 200 self.height = 100 self.borderStrokeColor = colors.black self.fillColor = None self.borderStrokeWidth = 0.5 self.horizontalDividerStrokeColor = colors.black self.verticalDividerStrokeColor = colors.black self.horizontalDividerStrokeWidth = 0.5 self.verticalDividerStrokeWidth = 0.25 self.dividerDashArray = None self.data = [['North','South','East','West'],[100,110,120,130],['A','B','C','D']] # list of rows each row is a list of columns self.boxAnchor = 'nw' #self.fontName = None self.fontSize = 8 self.fontColor = colors.black self.alignment = 'right' self.textAnchor = 'start' for k, v in kw.items(): if k in list(self.__class__._attrMap.keys()): setattr(self, k, v) else: raise ValueError('invalid argument supplied for class %s'%self.__class__) def demo(self): """ returns a sample of this widget with data """ d = Drawing(400, 200) t = TableWidget() d.add(t, name='table') d.table.dividerDashArray = (1, 3, 2) d.table.verticalDividerStrokeColor = None d.table.borderStrokeWidth = 0 d.table.borderStrokeColor = colors.red return d def draw(self): """ returns a group of shapes """ g = shapes.Group() #overall border and fill if self.borderStrokeColor or self.fillColor: # adds border and filling color rect = shapes.Rect(self.x, self.y, self.width, self.height) rect.fillColor = self.fillColor rect.strokeColor = self.borderStrokeColor rect.strokeWidth = self.borderStrokeWidth g.add(rect) #special case - for an empty table we want to avoid divide-by-zero data = self.preProcessData(self.data) rows = len(self.data) cols = len(self.data[0]) #print "(rows,cols)=(%s, %s)"%(rows,cols) row_step = self.height / float(rows) col_step = self.width / float(cols) #print "(row_step,col_step)=(%s, %s)"%(row_step,col_step) # draw the grid if self.horizontalDividerStrokeColor: for i in range(rows): # make horizontal lines x1 = self.x x2 = self.x + self.width y = self.y + row_step*i #print 'line (%s, %s), (%s, %s)'%(x1, y, x2, y) line = shapes.Line(x1, y, x2, y) line.strokeDashArray = self.dividerDashArray line.strokeWidth = self.horizontalDividerStrokeWidth line.strokeColor = self.horizontalDividerStrokeColor g.add(line) if self.verticalDividerStrokeColor: for i in range(cols): # make vertical lines x = self.x+col_step*i y1 = self.y y2 = self.y + self.height #print 'line (%s, %s), (%s, %s)'%(x, y1, x, y2) line = shapes.Line(x, y1, x, y2) line.strokeDashArray = self.dividerDashArray line.strokeWidth = self.verticalDividerStrokeWidth line.strokeColor = self.verticalDividerStrokeColor g.add(line) # since we plot data from down up, we reverse the list self.data.reverse() for (j, row) in enumerate(self.data): y = self.y + j*row_step + 0.5*row_step - 0.5 * self.fontSize for (i, datum) in enumerate(row): if datum: x = self.x + i*col_step + 0.5*col_step s = shapes.String(x, y, str(datum), textAnchor=self.textAnchor) s.fontName = self.fontName s.fontSize = self.fontSize s.fillColor = self.fontColor g.add(s) return g def preProcessData(self, data): """preprocess and return a new array with at least one row and column (use a None) if needed, and all rows the same length (adding Nones if needed) """ if not data: return [[None]] #make all rows have similar number of cells, append None when needed max_row = max( [len(x) for x in data] ) for rowNo, row in enumerate(data): if len(row) < max_row: row.extend([None]*(max_row-len(row))) return data #test if __name__ == '__main__': d = TableWidget().demo() import os d.save(formats=['pdf'],outDir=os.getcwd(),fnRoot=None)
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/graphics/widgets/table.py
0.5144
0.361531
table.py
pypi
__all__='''ArcIV encode decode'''.split() __version__="1.0" from reportlab.lib.utils import isUnicode, isPy3 class ArcIV: ''' performs 'ArcIV' Stream Encryption of S using key Based on what is widely thought to be RSA's ArcIV algorithm. It produces output streams that are identical. NB there is no separate decoder arciv(arciv(s,key),key) == s ''' def __init__(self,key): self._key = key self.reset() def reset(self): '''restore the cipher to it's start state''' #Initialize private key, k With the values of the key mod 256. #and sbox With numbers 0 - 255. Then compute sbox key = self._key if isUnicode(key): key = key.encode('utf8') sbox = list(range(256)) k = list(range(256)) lk = len(key) if isPy3: for i in sbox: k[i] = key[i % lk] % 256 else: for i in sbox: k[i] = ord(key[i % lk]) % 256 #Re-order sbox using the private key, k. #Iterating each element of sbox re-calculate the counter j #Then interchange the elements sbox[a] & sbox[b] j = 0 for i in range(256): j = (j+sbox[i]+k[i]) % 256 sbox[i], sbox[j] = sbox[j], sbox[i] self._sbox, self._i, self._j = sbox, 0, 0 def _encode(self, B): ''' return the list of encoded bytes of B, B might be a string or a list of integers between 0 <= i <= 255 ''' sbox, i, j = self._sbox, self._i, self._j if isPy3: C = list(B.encode('utf8')) if isinstance(B,str) else (list(B) if isinstance(B,bytes) else B[:]) elif isinstance(B,basestring): C = list(map(ord,B.encode('utf8') if isinstance(B,unicode) else B)) else: C = B[:] n = len(C) p = 0 while p<n: #update the variables i, j. self._i = i = (i + 1) % 256 self._j = j = (j + sbox[i]) % 256 #swap sbox[i] and sbox[j] sbox[i], sbox[j] = sbox[j], sbox[i] #overwrite the plaintext with the ciphered byte C[p] = C[p] ^ sbox[(sbox[i] + sbox[j]) % 256] p += 1 return C if isPy3: def encode(self,S): 'ArcIV encode string S' return bytes(self._encode(S)) else: def encode(self,S): 'ArcIV encode string S' return "".join(map(chr,self._encode(S))) _TESTS=[{ 'key': b"\x01\x23\x45\x67\x89\xab\xcd\xef", 'input': b"\x01\x23\x45\x67\x89\xab\xcd\xef", 'output': b"\x75\xb7\x87\x80\x99\xe0\xc5\x96", }, { 'key': b"\x01\x23\x45\x67\x89\xab\xcd\xef", 'input': b"\x00\x00\x00\x00\x00\x00\x00\x00", 'output': b"\x74\x94\xc2\xe7\x10\x4b\x08\x79", }, { 'key': b"\x00\x00\x00\x00\x00\x00\x00\x00", 'input': b"\x00\x00\x00\x00\x00\x00\x00\x00", 'output': b"\xde\x18\x89\x41\xa3\x37\x5d\x3a", }, { 'key': b"\xef\x01\x23\x45", 'input': b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 'output': b"\xd6\xa1\x41\xa7\xec\x3c\x38\xdf\xbd\x61", }, { 'key': b"\x01\x23\x45\x67\x89\xab\xcd\xef", 'input': b"\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\ \x01", 'output': b"\x75\x95\xc3\xe6\x11\x4a\x09\x78\x0c\x4a\xd4\ \x52\x33\x8e\x1f\xfd\x9a\x1b\xe9\x49\x8f\ \x81\x3d\x76\x53\x34\x49\xb6\x77\x8d\xca\ \xd8\xc7\x8a\x8d\x2b\xa9\xac\x66\x08\x5d\ \x0e\x53\xd5\x9c\x26\xc2\xd1\xc4\x90\xc1\ \xeb\xbe\x0c\xe6\x6d\x1b\x6b\x1b\x13\xb6\ \xb9\x19\xb8\x47\xc2\x5a\x91\x44\x7a\x95\ \xe7\x5e\x4e\xf1\x67\x79\xcd\xe8\xbf\x0a\ \x95\x85\x0e\x32\xaf\x96\x89\x44\x4f\xd3\ \x77\x10\x8f\x98\xfd\xcb\xd4\xe7\x26\x56\ \x75\x00\x99\x0b\xcc\x7e\x0c\xa3\xc4\xaa\ \xa3\x04\xa3\x87\xd2\x0f\x3b\x8f\xbb\xcd\ \x42\xa1\xbd\x31\x1d\x7a\x43\x03\xdd\xa5\ \xab\x07\x88\x96\xae\x80\xc1\x8b\x0a\xf6\ \x6d\xff\x31\x96\x16\xeb\x78\x4e\x49\x5a\ \xd2\xce\x90\xd7\xf7\x72\xa8\x17\x47\xb6\ \x5f\x62\x09\x3b\x1e\x0d\xb9\xe5\xba\x53\ \x2f\xaf\xec\x47\x50\x83\x23\xe6\x71\x32\ \x7d\xf9\x44\x44\x32\xcb\x73\x67\xce\xc8\ \x2f\x5d\x44\xc0\xd0\x0b\x67\xd6\x50\xa0\ \x75\xcd\x4b\x70\xde\xdd\x77\xeb\x9b\x10\ \x23\x1b\x6b\x5b\x74\x13\x47\x39\x6d\x62\ \x89\x74\x21\xd4\x3d\xf9\xb4\x2e\x44\x6e\ \x35\x8e\x9c\x11\xa9\xb2\x18\x4e\xcb\xef\ \x0c\xd8\xe7\xa8\x77\xef\x96\x8f\x13\x90\ \xec\x9b\x3d\x35\xa5\x58\x5c\xb0\x09\x29\ \x0e\x2f\xcd\xe7\xb5\xec\x66\xd9\x08\x4b\ \xe4\x40\x55\xa6\x19\xd9\xdd\x7f\xc3\x16\ \x6f\x94\x87\xf7\xcb\x27\x29\x12\x42\x64\ \x45\x99\x85\x14\xc1\x5d\x53\xa1\x8c\x86\ \x4c\xe3\xa2\xb7\x55\x57\x93\x98\x81\x26\ \x52\x0e\xac\xf2\xe3\x06\x6e\x23\x0c\x91\ \xbe\xe4\xdd\x53\x04\xf5\xfd\x04\x05\xb3\ \x5b\xd9\x9c\x73\x13\x5d\x3d\x9b\xc3\x35\ \xee\x04\x9e\xf6\x9b\x38\x67\xbf\x2d\x7b\ \xd1\xea\xa5\x95\xd8\xbf\xc0\x06\x6f\xf8\ \xd3\x15\x09\xeb\x0c\x6c\xaa\x00\x6c\x80\ \x7a\x62\x3e\xf8\x4c\x3d\x33\xc1\x95\xd2\ \x3e\xe3\x20\xc4\x0d\xe0\x55\x81\x57\xc8\ \x22\xd4\xb8\xc5\x69\xd8\x49\xae\xd5\x9d\ \x4e\x0f\xd7\xf3\x79\x58\x6b\x4b\x7f\xf6\ \x84\xed\x6a\x18\x9f\x74\x86\xd4\x9b\x9c\ \x4b\xad\x9b\xa2\x4b\x96\xab\xf9\x24\x37\ \x2c\x8a\x8f\xff\xb1\x0d\x55\x35\x49\x00\ \xa7\x7a\x3d\xb5\xf2\x05\xe1\xb9\x9f\xcd\ \x86\x60\x86\x3a\x15\x9a\xd4\xab\xe4\x0f\ \xa4\x89\x34\x16\x3d\xdd\xe5\x42\xa6\x58\ \x55\x40\xfd\x68\x3c\xbf\xd8\xc0\x0f\x12\ \x12\x9a\x28\x4d\xea\xcc\x4c\xde\xfe\x58\ \xbe\x71\x37\x54\x1c\x04\x71\x26\xc8\xd4\ \x9e\x27\x55\xab\x18\x1a\xb7\xe9\x40\xb0\ \xc0", }, ] def encode(text, key): "One-line shortcut for making an encoder object" return ArcIV(key).encode(text) def decode(text, key): "One-line shortcut for decoding" # yes, encode and decode are symmetric - see docstring return ArcIV(key).encode(text) if __name__=='__main__': i = 0 for t in _TESTS: o = ArcIV(t['key']).encode(t['input']) o = ArcIV(t['key']).encode(t['output']) i += 1
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/lib/arciv.py
0.401923
0.378344
arciv.py
pypi
__version__='3.3.0' __doc__=""" Module to analyze Python source code; for syntax coloring tools. Interface:: tags = fontify(pytext, searchfrom, searchto) - The 'pytext' argument is a string containing Python source code. - The (optional) arguments 'searchfrom' and 'searchto' may contain a slice in pytext. - The returned value is a list of tuples, formatted like this:: [('keyword', 0, 6, None), ('keyword', 11, 17, None), ('comment', 23, 53, None), etc. ] - The tuple contents are always like this:: (tag, startindex, endindex, sublist) - tag is one of 'keyword', 'string', 'comment' or 'identifier' - sublist is not used, hence always None. """ # Based on FontText.py by Mitchell S. Chapman, # which was modified by Zachary Roadhouse, # then un-Tk'd by Just van Rossum. # Many thanks for regular expression debugging & authoring are due to: # Tim (the-incredib-ly y'rs) Peters and Cristian Tismer # So, who owns the copyright? ;-) How about this: # Copyright 1996-2001: # Mitchell S. Chapman, # Zachary Roadhouse, # Tim Peters, # Just van Rossum __version__ = "0.4" import re # First a little helper, since I don't like to repeat things. (Tismer speaking) def replace(src, sep, rep): return rep.join(src.split(sep)) # This list of keywords is taken from ref/node13.html of the # Python 1.3 HTML documentation. ("access" is intentionally omitted.) keywordsList = [ "as", "assert", "exec", "del", "from", "lambda", "return", "and", "elif", "global", "not", "try", "break", "else", "if", "or", "while", "class", "except", "import", "pass", "continue", "finally", "in", "print", "def", "for", "is", "raise", "yield"] # Build up a regular expression which will match anything # interesting, including multi-line triple-quoted strings. commentPat = r"#[^\n]*" pat = r"q[^\\q\n]*(\\[\000-\377][^\\q\n]*)*q" quotePat = replace(pat, "q", "'") + "|" + replace(pat, 'q', '"') # Way to go, Tim! pat = r""" qqq [^\\q]* ( ( \\[\000-\377] | q ( \\[\000-\377] | [^\q] | q ( \\[\000-\377] | [^\\q] ) ) ) [^\\q]* )* qqq """ pat = ''.join(pat.split()) # get rid of whitespace tripleQuotePat = replace(pat, "q", "'") + "|" + replace(pat, 'q', '"') # Build up a regular expression which matches all and only # Python keywords. This will let us skip the uninteresting # identifier references. # nonKeyPat identifies characters which may legally precede # a keyword pattern. nonKeyPat = r"(^|[^a-zA-Z0-9_.\"'])" keyPat = nonKeyPat + "(" + "|".join(keywordsList) + ")" + nonKeyPat matchPat = commentPat + "|" + keyPat + "|" + tripleQuotePat + "|" + quotePat matchRE = re.compile(matchPat) idKeyPat = "[ \t]*[A-Za-z_][A-Za-z_0-9.]*" # Ident w. leading whitespace. idRE = re.compile(idKeyPat) def fontify(pytext, searchfrom = 0, searchto = None): if searchto is None: searchto = len(pytext) # Cache a few attributes for quicker reference. search = matchRE.search idSearch = idRE.search tags = [] tags_append = tags.append commentTag = 'comment' stringTag = 'string' keywordTag = 'keyword' identifierTag = 'identifier' start = 0 end = searchfrom while 1: m = search(pytext, end) if m is None: break # EXIT LOOP start = m.start() if start >= searchto: break # EXIT LOOP match = m.group(0) end = start + len(match) c = match[0] if c not in "#'\"": # Must have matched a keyword. if start != searchfrom: # there's still a redundant char before and after it, strip! match = match[1:-1] start = start + 1 else: # this is the first keyword in the text. # Only a space at the end. match = match[:-1] end = end - 1 tags_append((keywordTag, start, end, None)) # If this was a defining keyword, look ahead to the # following identifier. if match in ["def", "class"]: m = idSearch(pytext, end) if m is not None: start = m.start() if start == end: match = m.group(0) end = start + len(match) tags_append((identifierTag, start, end, None)) elif c == "#": tags_append((commentTag, start, end, None)) else: tags_append((stringTag, start, end, None)) return tags def test(path): f = open(path) text = f.read() f.close() tags = fontify(text) for tag, start, end, sublist in tags: print(tag, repr(text[start:end]))
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/lib/PyFontify.py
0.573081
0.360236
PyFontify.py
pypi
__version__='3.3.0' __doc__="""Standard verifying functions used by attrmap.""" import sys, codecs from reportlab.lib.utils import isSeq, isBytes, isStr, isPy3 from reportlab.lib import colors class Percentage(float): pass class Validator: "base validator class" def __call__(self,x): return self.test(x) def __str__(self): return getattr(self,'_str',self.__class__.__name__) def normalize(self,x): return x def normalizeTest(self,x): try: self.normalize(x) return True except: return False class _isAnything(Validator): def test(self,x): return True class _isNothing(Validator): def test(self,x): return False class _isBoolean(Validator): def test(self,x): if isinstance(int,bool): return x in (0,1) return self.normalizeTest(x) def normalize(self,x): if x in (0,1): return x try: S = x.upper() except: raise ValueError('Must be boolean not %s' % ascii(s)) if S in ('YES','TRUE'): return True if S in ('NO','FALSE',None): return False raise ValueError('Must be boolean not %s' % ascii(s)) class _isString(Validator): def test(self,x): return isStr(x) class _isCodec(Validator): def test(self,x): if not isStr(x): return False try: a,b,c,d = codecs.lookup(x) return True except LookupError: return False class _isNumber(Validator): def test(self,x): if isinstance(x,(float,int)): return True return self.normalizeTest(x) def normalize(self,x): try: return float(x) except: return int(x) class _isInt(Validator): def test(self,x): if not isinstance(x,int) and not isStr(x): return False return self.normalizeTest(x) if not isPy3: def normalize(self,x): return int(x) else: def normalize(self,x): return int(x.decode('utf8') if isBytes(x) else x) class _isNumberOrNone(_isNumber): def test(self,x): return x is None or isNumber(x) def normalize(self,x): if x is None: return x return _isNumber.normalize(x) class _isListOfNumbersOrNone(Validator): "ListOfNumbersOrNone validator class." def test(self, x): if x is None: return True return isListOfNumbers(x) class isNumberInRange(_isNumber): def __init__(self, min, max): self.min = min self.max = max def test(self, x): try: n = self.normalize(x) if self.min <= n <= self.max: return True except ValueError: pass return False class _isListOfShapes(Validator): "ListOfShapes validator class." def test(self, x): from reportlab.graphics.shapes import Shape if isSeq(x): answer = 1 for e in x: if not isinstance(e, Shape): answer = 0 return answer else: return False class _isListOfStringsOrNone(Validator): "ListOfStringsOrNone validator class." def test(self, x): if x is None: return True return isListOfStrings(x) class _isTransform(Validator): "Transform validator class." def test(self, x): if isSeq(x): if len(x) == 6: for element in x: if not isNumber(element): return False return True else: return False else: return False class _isColor(Validator): "Color validator class." def test(self, x): return isinstance(x, colors.Color) class _isColorOrNone(Validator): "ColorOrNone validator class." def test(self, x): if x is None: return True return isColor(x) from reportlab.lib.normalDate import NormalDate class _isNormalDate(Validator): def test(self,x): if isinstance(x,NormalDate): return True return x is not None and self.normalizeTest(x) def normalize(self,x): return NormalDate(x) class _isValidChild(Validator): "ValidChild validator class." def test(self, x): """Is this child allowed in a drawing or group? I.e. does it descend from Shape or UserNode? """ from reportlab.graphics.shapes import UserNode, Shape return isinstance(x, UserNode) or isinstance(x, Shape) class _isValidChildOrNone(_isValidChild): def test(self,x): return _isValidChild.test(self,x) or x is None class _isCallable(Validator): def test(self, x): return hasattr(x,'__call__') class OneOf(Validator): """Make validator functions for list of choices. Usage: f = reportlab.lib.validators.OneOf('happy','sad') or f = reportlab.lib.validators.OneOf(('happy','sad')) f('sad'),f('happy'), f('grumpy') (1,1,0) """ def __init__(self, enum,*args): if isSeq(enum): if args!=(): raise ValueError("Either all singleton args or a single sequence argument") self._enum = tuple(enum)+args else: self._enum = (enum,)+args def test(self, x): return x in self._enum class SequenceOf(Validator): def __init__(self,elemTest,name=None,emptyOK=1, NoneOK=0, lo=0,hi=0x7fffffff): self._elemTest = elemTest self._emptyOK = emptyOK self._NoneOK = NoneOK self._lo, self._hi = lo, hi if name: self._str = name def test(self, x): if not isSeq(x): if x is None: return self._NoneOK return False if x==[] or x==(): return self._emptyOK elif not self._lo<=len(x)<=self._hi: return False for e in x: if not self._elemTest(e): return False return True class EitherOr(Validator): def __init__(self,tests,name=None): if not isSeq(tests): tests = (tests,) self._tests = tests if name: self._str = name def test(self, x): for t in self._tests: if t(x): return True return False class NoneOr(Validator): def __init__(self,elemTest,name=None): self._elemTest = elemTest if name: self._str = name def test(self, x): if x is None: return True return self._elemTest(x) class Auto(Validator): def __init__(self,**kw): self.__dict__.update(kw) def test(self,x): return x is self.__class__ or isinstance(x,self.__class__) class AutoOr(NoneOr): def test(self,x): return isAuto(x) or self._elemTest(x) class isInstanceOf(Validator): def __init__(self,klass=None): self._klass = klass def test(self,x): return isinstance(x,self._klass) class matchesPattern(Validator): """Matches value, or its string representation, against regex""" def __init__(self, pattern): self._pattern = re.compile(pattern) def test(self,x): x = str(x) print('testing %s against %s' % (x, self._pattern)) return (self._pattern.match(x) != None) class DerivedValue: """This is used for magic values which work themselves out. An example would be an "inherit" property, so that one can have drawing.chart.categoryAxis.labels.fontName = inherit and pick up the value from the top of the drawing. Validators will permit this provided that a value can be pulled in which satisfies it. And the renderer will have special knowledge of these so they can evaluate themselves. """ def getValue(self, renderer, attr): """Override this. The renderers will pass the renderer, and the attribute name. Algorithms can then backtrack up through all the stuff the renderer provides, including a correct stack of parent nodes.""" return None class Inherit(DerivedValue): def __repr__(self): return "inherit" def getValue(self, renderer, attr): return renderer.getStateValue(attr) inherit = Inherit() class NumericAlign(str): '''for creating the numeric string value for anchors etc etc dp is the character to align on (the last occurrence will be used) dpLen is the length of characters after the dp ''' def __new__(cls,dp='.',dpLen=0): self = str.__new__(cls,'numeric') self._dp=dp self._dpLen = dpLen return self isAuto = Auto() isBoolean = _isBoolean() isString = _isString() isCodec = _isCodec() isNumber = _isNumber() isInt = _isInt() isNoneOrInt = NoneOr(isInt,'isNoneOrInt') isNumberOrNone = _isNumberOrNone() isTextAnchor = OneOf('start','middle','end','boxauto') isListOfNumbers = SequenceOf(isNumber,'isListOfNumbers') isListOfNumbersOrNone = _isListOfNumbersOrNone() isListOfShapes = _isListOfShapes() isListOfStrings = SequenceOf(isString,'isListOfStrings') isListOfStringsOrNone = _isListOfStringsOrNone() isTransform = _isTransform() isColor = _isColor() isListOfColors = SequenceOf(isColor,'isListOfColors') isColorOrNone = _isColorOrNone() isShape = isValidChild = _isValidChild() isNoneOrShape = isValidChildOrNone = _isValidChildOrNone() isAnything = _isAnything() isNothing = _isNothing() isXYCoord = SequenceOf(isNumber,lo=2,hi=2,emptyOK=0) isBoxAnchor = OneOf('nw','n','ne','w','c','e','sw','s','se', 'autox', 'autoy') isNoneOrString = NoneOr(isString,'NoneOrString') isNoneOrListOfNoneOrStrings=SequenceOf(isNoneOrString,'isNoneOrListOfNoneOrStrings',NoneOK=1) isListOfNoneOrString=SequenceOf(isNoneOrString,'isListOfNoneOrString',NoneOK=0) isNoneOrListOfNoneOrNumbers=SequenceOf(isNumberOrNone,'isNoneOrListOfNoneOrNumbers',NoneOK=1) isCallable = _isCallable() isNoneOrCallable = NoneOr(isCallable) isStringOrCallable=EitherOr((isString,isCallable),'isStringOrCallable') isStringOrCallableOrNone=NoneOr(isStringOrCallable,'isStringOrCallableNone') isStringOrNone=NoneOr(isString,'isStringOrNone') isNormalDate=_isNormalDate()
/reportlab_x-3.4.0.2-cp34-cp34m-macosx_10_10_x86_64.whl/reportlab/lib/validators.py
0.477798
0.256221
validators.py
pypi
from tools.docco.rl_doc_utils import * #begin chapter oon paragraphs heading1("Paragraphs") disc(""" The $reportlab.platypus.Paragraph$ class is one of the most useful of the Platypus $Flowables$; it can format fairly arbitrary text and provides for inline font style and colour changes using an XML style markup. The overall shape of the formatted text can be justified, right or left ragged or centered. The XML markup can even be used to insert greek characters or to do subscripts. """) disc("""The following text creates an instance of the $Paragraph$ class:""") eg("""Paragraph(text, style, bulletText=None)""") disc("""The $text$ argument contains the text of the paragraph; excess white space is removed from the text at the ends and internally after linefeeds. This allows easy use of indented triple quoted text in <b>Python</b> scripts. The $bulletText$ argument provides the text of a default bullet for the paragraph. The font and other properties for the paragraph text and bullet are set using the style argument. """) disc(""" The $style$ argument should be an instance of class $ParagraphStyle$ obtained typically using""") eg(""" from reportlab.lib.styles import ParagraphStyle """) disc(""" this container class provides for the setting of multiple default paragraph attributes in a structured way. The styles are arranged in a dictionary style object called a $stylesheet$ which allows for the styles to be accessed as $stylesheet['BodyText']$. A sample style sheet is provided. """) eg(""" from reportlab.lib.styles import getSampleStyleSheet stylesheet=getSampleStyleSheet() normalStyle = stylesheet['Normal'] """) disc(""" The options which can be set for a $Paragraph$ can be seen from the $ParagraphStyle$ defaults. The values with leading underscore ('_') are derived from the defaults in module $reportlab.rl_config$ which are derived from module $reportlab.rl_settings$. """) heading4("$class ParagraphStyle$") eg(""" class ParagraphStyle(PropertySet): defaults = { 'fontName':_baseFontName, 'fontSize':10, 'leading':12, 'leftIndent':0, 'rightIndent':0, 'firstLineIndent':0, 'alignment':TA_LEFT, 'spaceBefore':0, 'spaceAfter':0, 'bulletFontName':_baseFontName, 'bulletFontSize':10, 'bulletIndent':0, 'textColor': black, 'backColor':None, 'wordWrap':None, 'borderWidth': 0, 'borderPadding': 0, 'borderColor': None, 'borderRadius': None, 'allowWidows': 1, 'allowOrphans': 0, 'textTransform':None, 'endDots':None, 'splitLongWords':1, 'underlineWidth': _baseUnderlineWidth, 'bulletAnchor': 'start', 'justifyLastLine': 0, 'justifyBreaks': 0, 'spaceShrinkage': _spaceShrinkage, 'strikeWidth': _baseStrikeWidth, #stroke width 'underlineOffset': _baseUnderlineOffset, #fraction of fontsize to offset underlines 'underlineGap': _baseUnderlineGap, #gap for double/triple underline 'strikeOffset': _baseStrikeOffset, #fraction of fontsize to offset strikethrough 'strikeGap': _baseStrikeGap, #gap for double/triple strike 'linkUnderline': _platypus_link_underline, #'underlineColor': None, #'strikeColor': None, 'hyphenationLang': _hyphenationLang, 'uriWasteReduce': _uriWasteReduce, 'embeddedHyphenation': _embeddedHyphenation, } """) heading2("Using Paragraph Styles") #this will be used in the ParaBox demos. sample = """You are hereby charged that on the 28th day of May, 1970, you did willfully, unlawfully, and with malice of forethought, publish an alleged English-Hungarian phrase book with intent to cause a breach of the peace. How do you plead?""" disc("""The $Paragraph$ and $ParagraphStyle$ classes together handle most common formatting needs. The following examples draw paragraphs in various styles, and add a bounding box so that you can see exactly what space is taken up.""") s1 = ParagraphStyle('Normal') parabox(sample, s1, 'The default $ParagraphStyle$') disc("""The two attributes $spaceBefore$ and $spaceAfter$ do what they say, except at the top or bottom of a frame. At the top of a frame, $spaceBefore$ is ignored, and at the bottom, $spaceAfter$ is ignored. This means that you could specify that a 'Heading2' style had two inches of space before when it occurs in mid-page, but will not get acres of whitespace at the top of a page. These two attributes should be thought of as 'requests' to the Frame and are not part of the space occupied by the Paragraph itself.""") disc("""The $fontSize$ and $fontName$ tags are obvious, but it is important to set the $leading$. This is the spacing between adjacent lines of text; a good rule of thumb is to make this 20% larger than the point size. To get double-spaced text, use a high $leading$. If you set $autoLeading$(default $"off"$) to $"min"$(use observed leading even if smaller than specified) or $"max"$(use the larger of observed and specified) then an attempt is made to determine the leading on a line by line basis. This may be useful if the lines contain different font sizes etc.""") disc("""The figure below shows space before and after and an increased leading:""") parabox(sample, ParagraphStyle('Spaced', spaceBefore=6, spaceAfter=6, leading=16), 'Space before and after and increased leading' ) disc("""The attribute $borderPadding$ adjusts the padding between the paragraph and the border of its background. This can either be a single value or a tuple containing 2 to 4 values. These values are applied the same way as in Cascading Style Sheets (CSS). If a single value is given, that value is applied to all four sides. If more than one value is given, they are applied in clockwise order to the sides starting at the top. If two or three values are given, the missing values are taken from the opposite side(s). Note that in the following example the yellow box is drawn by the paragraph itself.""") parabox(sample, ParagraphStyle('padded', borderPadding=(7, 2, 20), borderColor='#000000', borderWidth=1, backColor='#FFFF00'), 'Variable padding' ) disc("""The $leftIndent$ and $rightIndent$ attributes do exactly what you would expect; $firstLineIndent$ is added to the $leftIndent$ of the first line. If you want a straight left edge, remember to set $firstLineIndent$ equal to 0.""") parabox(sample, ParagraphStyle('indented', firstLineIndent=+24, leftIndent=24, rightIndent=24), 'one third inch indents at left and right, two thirds on first line' ) disc("""Setting $firstLineIndent$ equal to a negative number, $leftIndent$ much higher, and using a different font (we'll show you how later!) can give you a definition list:.""") parabox('<b><i>Judge Pickles: </i></b>' + sample, ParagraphStyle('dl', leftIndent=36), 'Definition Lists' ) disc("""There are four possible values of $alignment$, defined as constants in the module <i>reportlab.lib.enums</i>. These are TA_LEFT, TA_CENTER or TA_CENTRE, TA_RIGHT and TA_JUSTIFY, with values of 0, 1, 2 and 4 respectively. These do exactly what you would expect.""") disc("""Set $wordWrap$ to $'CJK'$ to get Asian language linewrapping. For normal western text you can change the way the line breaking algorithm handles <i>widows</i> and <i>orphans</i> with the $allowWidows$ and $allowOrphans$ values. Both should normally be set to $0$, but for historical reasons we have allowed <i>widows</i>. The default color of the text can be set with $textColor$ and the paragraph background colour can be set with $backColor$. The paragraph's border properties may be changed using $borderWidth$, $borderPadding$, $borderColor$ and $borderRadius$.""") disc("""The $textTransform$ attribute can be <b><i>None</i></b>, <i>'uppercase'</i> or <i>'lowercase'</i> to get the obvious result and <i>'capitalize'</i> to get initial letter capitalization.""") disc("""Attribute $endDots$ can be <b><i>None</i></b>, a string, or an object with attributes text and optional fontName, fontSize, textColor, backColor and dy(y offset) to specify trailing matter on the last line of left/right justified paragraphs.""") disc("""The $splitLongWords$ attribute can be set to a false value to avoid splitting very long words.""") disc("""Attribute $bulletAnchor$ can be <i>'start'</i>, <i>'middle'</i>, <i>'end'</i> or <i>'numeric'</i> to control where the bullet is anchored.""") disc("""The $justifyBreaks$ attribute controls whether lines deliberately broken with a $&lt;br/&gt;$ tag should be justified""") disc("""Attribute $spaceShrinkage$ is a fractional number specifiying by how much the space of a paragraph line may be shrunk in order to make it fit; typically it is something like 0.05""") disc("""The $underlineWidth$, $underlineOffset$, $underlineGap$ &amp; $underlineColor$ attributes control the underline behaviour when the $&lt;u&gt;$ or a linking tag is used. Those tags can have override values of these attributes. The attribute value for width &amp; offset is a $fraction * Letter$ where letter can be one of $P$, $L$, $f$ or $F$ representing fontSize proportions. $P$ uses the fontsize at the tag, $F$ is the maximum fontSize in the tag, $f$ is the initial fontsize inside the tag. $L$ means the global (paragrpah style) font size. $strikeWidth$, $strikeOffset$, $strikeGap$ &amp; $strikeColor$ attributes do the same for strikethrough lines. """) disc("""Attribute $linkUnderline$ controls whether link tags are automatically underlined.""") disc("""If the $pyphen$ python module is installed attribute $hyphenationLang$ controls which language will be used to hyphenate words without explicit embedded hyphens.""") disc("""If $embeddedHyphenation$ is set then attempts will be made to split words with embedded hyphens.""") disc("""Attribute $uriWasteReduce$ controls how we attempt to split long uri's. It is the fraction of a line that we regard as too much waste. The default in module $reportlab.rl_settings$ is <i>0.5</i> which means that we will try and split a word that looks like a uri if we would waste at least half of the line.""") disc("""Currently the hyphenation and uri splitting are turned off by default. You need to modify the default settings by using the file $~/.rl_settings$ or adding a module $reportlab_settings.py$ to the python path. Suitable values are""") eg(""" hyphenationLanguage='en_GB' embeddedHyphenation=1 uriWasteReduce=0.3 """) heading2("Paragraph XML Markup Tags") disc("""XML markup can be used to modify or specify the overall paragraph style, and also to specify intra- paragraph markup.""") heading3("The outermost &lt; para &gt; tag") disc(""" The paragraph text may optionally be surrounded by &lt;para attributes....&gt; &lt;/para&gt; tags. The attributes if any of the opening &lt;para&gt; tag affect the style that is used with the $Paragraph$ $text$ and/or $bulletText$. """) disc(" ") from reportlab.platypus.paraparser import _addAttributeNames, _paraAttrMap, _bulletAttrMap def getAttrs(A): _addAttributeNames(A) S={} for k, v in A.items(): a = v[0] if a not in S: S[a] = [k] else: S[a].append(k) K = list(sorted(S.keys())) K.sort() D=[('Attribute','Synonyms')] for k in K: D.append((k,", ".join(list(sorted(S[k]))))) cols=2*[None] rows=len(D)*[None] return D,cols,rows t=Table(*getAttrs(_paraAttrMap)) t.setStyle(TableStyle([ ('FONT',(0,0),(-1,1),'Times-Bold',10,12), ('FONT',(0,1),(-1,-1),'Courier',8,8), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ])) getStory().append(t) caption("""Table <seq template="%(Chapter)s-%(Table+)s"/> - Synonyms for style attributes""") disc("""Some useful synonyms have been provided for our Python attribute names, including lowercase versions, and the equivalent properties from the HTML standard where they exist. These additions make it much easier to build XML-printing applications, since much intra-paragraph markup may not need translating. The table below shows the allowed attributes and synonyms in the outermost paragraph tag.""") CPage(1) heading2("Intra-paragraph markup") disc("""<![CDATA[Within each paragraph, we use a basic set of XML tags to provide markup. The most basic of these are bold (<b>...</b>), italic (<i>...</i>) and underline (<u>...</u>). Other tags which are allowed are strong (<strong>...</strong>), and strike through (<strike>...</strike>). The <link> and <a> tags may be used to refer to URIs, documents or bookmarks in the current document. The a variant of the <a> tag can be used to mark a position in a document. A break (<br/>) tag is also allowed.]]> """) parabox2("""<b>You are hereby charged</b> that on the 28th day of May, 1970, you did willfully, unlawfully, and <i>with malice of forethought</i>, publish an alleged English-Hungarian phrase book with intent to cause a breach of the peace. <u>How do you plead</u>?""", "Simple bold and italic tags") parabox2("""This <a href="#MYANCHOR" color="blue">is a link to</a> an anchor tag ie <a name="MYANCHOR"/><font color="green">here</font>. This <link href="#MYANCHOR" color="blue" fontName="Helvetica">is another link to</link> the same anchor tag.""", "anchors and links") disc("""The <b>link</b> tag can be used as a reference, but not as an anchor. The a and link hyperlink tags have additional attributes <i>fontName</i>, <i>fontSize</i>, <i>color</i> &amp; <i>backColor</i> attributes. The hyperlink reference can have a scheme of <b>http:</b><i>(external webpage)</i>, <b>pdf:</b><i>(different pdf document)</i> or <b>document:</b><i>(same pdf document)</i>; a missing scheme is treated as <b>document</b> as is the case when the reference starts with # (in which case the anchor should omit it). Any other scheme is treated as some kind of URI. """) parabox2("""<strong>You are hereby charged</strong> that on the 28th day of May, 1970, you did willfully, unlawfully, <strike>and with malice of forethought</strike>, <br/>publish an alleged English-Hungarian phrase book with intent to cause a breach of the peace. How do you plead?""", "Strong, strike, and break tags") heading3("The $&lt;font&gt;$ tag") disc("""The $&lt;font&gt;$ tag can be used to change the font name, size and text color for any substring within the paragraph. Legal attributes are $size$, $face$, $name$ (which is the same as $face$), $color$, and $fg$ (which is the same as $color$). The $name$ is the font family name, without any 'bold' or 'italic' suffixes. Colors may be HTML color names or a hex string encoded in a variety of ways; see ^reportlab.lib.colors^ for the formats allowed.""") parabox2("""<font face="times" color="red">You are hereby charged</font> that on the 28th day of May, 1970, you did willfully, unlawfully, and <font size=14>with malice of forethought</font>, publish an alleged English-Hungarian phrase book with intent to cause a breach of the peace. How do you plead?""", "The $font$ tag") heading3("Superscripts and Subscripts") disc("""Superscripts and subscripts are supported with the <![CDATA[<super>/<sup> and <sub> tags, which work exactly as you might expect. Additionally these three tags have attributes rise and size to optionally set the rise/descent and font size for the superscript/subscript text. In addition, most greek letters can be accessed by using the <greek></greek> tag, or with mathML entity names.]]>""") ##parabox2("""<greek>epsilon</greek><super><greek>iota</greek> ##<greek>pi</greek></super> = -1""", "Greek letters and subscripts") parabox2("""Equation (&alpha;): <greek>e</greek> <super rise=9 size=6><greek>ip</greek></super> = -1""", "Greek letters and superscripts") heading3("Inline Images") disc("""We can embed images in a paragraph with the &lt;img/&gt; tag which has attributes $src$, $width$, $height$ whose meanings are obvious. The $valign$ attribute may be set to a css like value from "baseline", "sub", "super", "top", "text-top", "middle", "bottom", "text-bottom"; the value may also be a numeric percentage or an absolute value. """) parabox2("""<para autoLeading="off" fontSize=12>This &lt;img/&gt; <img src="../images/testimg.gif" valign="top"/> is aligned <b>top</b>.<br/><br/> This &lt;img/&gt; <img src="../images/testimg.gif" valign="bottom"/> is aligned <b>bottom</b>.<br/><br/> This &lt;img/&gt; <img src="../images/testimg.gif" valign="middle"/> is aligned <b>middle</b>.<br/><br/> This &lt;img/&gt; <img src="../images/testimg.gif" valign="-4"/> is aligned <b>-4</b>.<br/><br/> This &lt;img/&gt; <img src="../images/testimg.gif" valign="+4"/> is aligned <b>+4</b>.<br/><br/> This &lt;img/&gt; <img src="../images/testimg.gif" width="10"/> has width <b>10</b>.<br/><br/> </para>""","Inline images") disc("""The $src$ attribute can refer to a remote location eg $src="https://www.reportlab.com/images/logo.gif"$. By default we set $rl_config.trustedShemes$ to $['https','http', 'file', 'data', 'ftp']$ and $rl_config.trustedHosts=None$ the latter meaning no-restriction. You can modify these variables using one of the override files eg $reportlab_settings.py$ or $~/.reportlab_settings$. Or as comma separated strings in the environment variables $RL_trustedSchemes$ &amp; $RL_trustedHosts$. Note that the $trustedHosts$ values may contain <b>glob</b> wild cars so <i>*.reportlab.com</i> will match the obvious domains. <br/><span color="red"><b>*NB*</b></span> use of <i>trustedHosts</i> and or <i>trustedSchemes</i> may not control behaviour &amp; actions when $URI$ patterns are detected by the viewer application.""") heading3("The $&lt;u&gt;$ &amp; $&lt;strike&gt;$ tags") disc("""These tags can be used to carry out explicit underlineing or strikethroughs. These tags have attributes $width$, $offset$, $color$, $gap$ &amp; $kind$. The $kind$ attribute controls how many lines will be drawn (default $kind=1$) and when $kind>1$ the $gap$ attribute controls the disatnce between lines.""") heading3("The $&lt;nobr&gt;$ tag") disc("""If hyphenation is in operation the $&lt;nobr&gt;$ tag suppresses it so $&lt;nobr&gt;averylongwordthatwontbebroken&lt;/nobr&gt;$ won't be broken.""") heading3("Numbering Paragraphs and Lists") disc("""The $&lt;seq&gt;$ tag provides comprehensive support for numbering lists, chapter headings and so on. It acts as an interface to the $Sequencer$ class in ^reportlab.lib.sequencer^. These are used to number headings and figures throughout this document. You may create as many separate 'counters' as you wish, accessed with the $id$ attribute; these will be incremented by one each time they are accessed. The $seqreset$ tag resets a counter. If you want it to resume from a number other than 1, use the syntax &lt;seqreset id="mycounter" base="42"&gt;. Let's have a go:""") parabox2("""<seq id="spam"/>, <seq id="spam"/>, <seq id="spam"/>. Reset<seqreset id="spam"/>. <seq id="spam"/>, <seq id="spam"/>, <seq id="spam"/>.""", "Basic sequences") disc("""You can save specifying an ID by designating a counter ID as the <i>default</i> using the &lt;seqdefault id="Counter"&gt; tag; it will then be used whenever a counter ID is not specified. This saves some typing, especially when doing multi-level lists; you just change counter ID when stepping in or out a level.""") parabox2("""<seqdefault id="spam"/>Continued... <seq/>, <seq/>, <seq/>, <seq/>, <seq/>, <seq/>, <seq/>.""", "The default sequence") disc("""Finally, one can access multi-level sequences using a variation of Python string formatting and the $template$ attribute in a &lt;seq&gt; tags. This is used to do the captions in all of the figures, as well as the level two headings. The substring $%(counter)s$ extracts the current value of a counter without incrementing it; appending a plus sign as in $%(counter)s$ increments the counter. The figure captions use a pattern like the one below:""") parabox2("""Figure <seq template="%(Chapter)s-%(FigureNo+)s"/> - Multi-level templates""", "Multi-level templates") disc("""We cheated a little - the real document used 'Figure', but the text above uses 'FigureNo' - otherwise we would have messed up our numbering!""") heading2("Bullets and Paragraph Numbering") disc("""In addition to the three indent properties, some other parameters are needed to correctly handle bulleted and numbered lists. We discuss this here because you have now seen how to handle numbering. A paragraph may have an optional ^bulletText^ argument passed to its constructor; alternatively, bullet text may be placed in a $<![CDATA[<bullet>..</bullet>]]>$ tag at its head. This text will be drawn on the first line of the paragraph, with its x origin determined by the $bulletIndent$ attribute of the style, and in the font given in the $bulletFontName$ attribute. The "bullet" may be a single character such as (doh!) a bullet, or a fragment of text such as a number in some numbering sequence, or even a short title as used in a definition list. Fonts may offer various bullet characters but we suggest first trying the Unicode bullet ($&bull;$), which may be written as $&amp;bull;$, $&amp;#x2022;$ or (in utf8) $\\xe2\\x80\\xa2$):""") t=Table(*getAttrs(_bulletAttrMap)) t.setStyle([ ('FONT',(0,0),(-1,1),'Times-Bold',10,12), ('FONT',(0,1),(-1,-1),'Courier',8,8), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ]) getStory().append(t) caption("""Table <seq template="%(Chapter)s-%(Table+)s"/> - &lt;bullet&gt; attributes &amp; synonyms""") disc("""The &lt;bullet&gt; tag is only allowed once in a given paragraph and its use overrides the implied bullet style and ^bulletText^ specified in the ^Paragraph^ creation. """) parabox("""<bullet>&bull;</bullet>this is a bullet point. Spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam """, styleSheet['Bullet'], 'Basic use of bullet points') disc("""Exactly the same technique is used for numbers, except that a sequence tag is used. It is also possible to put a multi-character string in the bullet; with a deep indent and bold bullet font, you can make a compact definition list.""")
/reportlab-4.0.4.tar.gz/reportlab-4.0.4/docs/userguide/ch5_paragraphs.py
0.651577
0.467089
ch5_paragraphs.py
pypi
from tools.docco.rl_doc_utils import * Appendix1("ReportLab Demos") disc("""In the subdirectories of $reportlab/demos$ there are a number of working examples showing almost all aspects of reportlab in use.""") heading2("""Odyssey""") disc(""" The three scripts odyssey.py, dodyssey.py and fodyssey.py all take the file odyssey.txt and produce PDF documents. The included odyssey.txt is short; a longer and more testing version can be found at ftp://ftp.reportlab.com/odyssey.full.zip. """) eg(""" Windows cd reportlab\\demos\\odyssey python odyssey.py start odyssey.pdf Linux cd reportlab/demos/odyssey python odyssey.py acrord odyssey.pdf """) disc("""Simple formatting is shown by the odyssey.py script. It runs quite fast, but all it does is gather the text and force it onto the canvas pages. It does no paragraph manipulation at all so you get to see the XML &lt; &amp; &gt; tags. """) disc("""The scripts fodyssey.py and dodyssey.py handle paragraph formatting so you get to see colour changes etc. Both scripts use the document template class and the dodyssey.py script shows the ability to do dual column layout and uses multiple page templates. """) heading2("""Standard Fonts and Colors""") disc("""In $reportlab/demos/stdfonts$ the script stdfonts.py can be used to illustrate ReportLab's standard fonts. Run the script using""") eg(""" cd reportlab\\demos\\stdfonts python stdfonts.py """) disc(""" to produce two PDF documents, StandardFonts_MacRoman.pdf &amp; StandardFonts_WinAnsi.pdf which show the two most common built in font encodings. """) disc("""The colortest.py script in $reportlab/demos/colors$ demonstrates the different ways in which reportlab can set up and use colors.""") disc("""Try running the script and viewing the output document, colortest.pdf. This shows different color spaces and a large selection of the colors which are named in the $reportlab.lib.colors$ module. """) heading2("""Py2pdf""") disc("""Dinu Gherman contributed this useful script which uses reportlab to produce nicely colorized PDF documents from Python scripts including bookmarks for classes, methods and functions. To get a nice version of the main script try""") eg(""" cd reportlab/demos/py2pdf python py2pdf.py py2pdf.py acrord py2pdf.pdf """) disc("""i.e. we used py2pdf to produce a nice version of py2pdf.py in the document with the same rootname and a .pdf extension. """) disc(""" The py2pdf.py script has many options which are beyond the scope of this simple introduction; consult the comments at the start of the script. """) heading2("Gadflypaper") disc(""" The Python script, gfe.py, in $reportlab/demos/gadflypaper$ uses an inline style of document preparation. The script almost entirely produced by Aaron Watters produces a document describing Aaron's $gadfly$ in memory database for Python. To generate the document use """) eg(""" cd reportlab\\gadflypaper python gfe.py start gfe.pdf """) disc(""" everything in the PDF document was produced by the script which is why this is an inline style of document production. So, to produce a header followed by some text the script uses functions $header$ and $p$ which take some text and append to a global story list. """) eg(''' header("Conclusion") p("""The revamped query engine design in Gadfly 2 supports .......... and integration.""") ''') heading2("""Pythonpoint""") disc("""Andy Robinson has refined the pythonpoint.py script (in $reportlab\\demos\\pythonpoint$) until it is a really useful script. It takes an input file containing an XML markup and uses an xmllib style parser to map the tags into PDF slides. When run in its own directory pythonpoint.py takes as a default input the file pythonpoint.xml and produces pythonpoint.pdf which is documentation for Pythonpoint! You can also see it in action with an older paper """) eg(""" cd reportlab\\demos\\pythonpoint python pythonpoint.py monterey.xml start monterey.pdf """) disc(""" Not only is pythonpoint self documenting, but it also demonstrates reportlab and PDF. It uses many features of reportlab (document templates, tables etc). Exotic features of PDF such as fadeins and bookmarks are also shown to good effect. The use of an XML document can be contrasted with the <i>inline</i> style of the gadflypaper demo; the content is completely separate from the formatting """)
/reportlab-4.0.4.tar.gz/reportlab-4.0.4/docs/userguide/app_demos.py
0.613121
0.332825
app_demos.py
pypi
__version__='3.3.0' from tools.docco.rl_doc_utils import * from reportlab.graphics.shapes import * from reportlab.graphics.widgets import signsandsymbols heading2("Widgets") disc(""" We now describe widgets and how they relate to shapes. Using many examples it is shown how widgets make reusable graphics components. """) heading3("Shapes vs. Widgets") disc("""Up until now, Drawings have been 'pure data'. There is no code in them to actually do anything, except assist the programmer in checking and inspecting the drawing. In fact, that's the cornerstone of the whole concept and is what lets us achieve portability - a renderer only needs to implement the primitive shapes.""") disc("""We want to build reusable graphic objects, including a powerful chart library. To do this we need to reuse more tangible things than rectangles and circles. We should be able to write objects for other to reuse - arrows, gears, text boxes, UML diagram nodes, even fully fledged charts.""") disc(""" The Widget standard is a standard built on top of the shapes module. Anyone can write new widgets, and we can build up libraries of them. Widgets support the $getProperties()$ and $setProperties()$ methods, so you can inspect and modify as well as document them in a uniform way. """) bullet("A widget is a reusable shape ") bullet("""it can be initialized with no arguments when its $draw()$ method is called it creates a primitive Shape or a Group to represent itself""") bullet("""It can have any parameters you want, and they can drive the way it is drawn""") bullet("""it has a $demo()$ method which should return an attractively drawn example of itself in a 200x100 rectangle. This is the cornerstone of the automatic documentation tools. The $demo()$ method should also have a well written docstring, since that is printed too!""") disc("""Widgets run contrary to the idea that a drawing is just a bundle of shapes; surely they have their own code? The way they work is that a widget can convert itself to a group of primitive shapes. If some of its components are themselves widgets, they will get converted too. This happens automatically during rendering; the renderer will not see your chart widget, but just a collection of rectangles, lines and strings. You can also explicitly 'flatten out' a drawing, causing all widgets to be converted to primitives.""") heading3("Using a Widget") disc(""" Let's imagine a simple new widget. We will use a widget to draw a face, then show how it was implemented.""") eg(""" >>> from reportlab.lib import colors >>> from reportlab.graphics import shapes >>> from reportlab.graphics import widgetbase >>> from reportlab.graphics import renderPDF >>> d = shapes.Drawing(200, 100) >>> f = widgetbase.Face() >>> f.skinColor = colors.yellow >>> f.mood = "sad" >>> d.add(f) >>> renderPDF.drawToFile(d, 'face.pdf', 'A Face') """) from reportlab.graphics import widgetbase d = Drawing(200, 120) f = widgetbase.Face() f.x = 50 f.y = 10 f.skinColor = colors.yellow f.mood = "sad" d.add(f) draw(d, 'A sample widget') disc(""" Let's see what properties it has available, using the $setProperties()$ method we have seen earlier: """) eg(""" >>> f.dumpProperties() eyeColor = Color(0.00,0.00,1.00) mood = sad size = 80 skinColor = Color(1.00,1.00,0.00) x = 10 y = 10 >>> """) disc(""" One thing which seems strange about the above code is that we did not set the size or position when we made the face. This is a necessary trade-off to allow a uniform interface for constructing widgets and documenting them - they cannot require arguments in their $__init__()$ method. Instead, they are generally designed to fit in a 200 x 100 window, and you move or resize them by setting properties such as x, y, width and so on after creation. """) disc(""" In addition, a widget always provides a $demo()$ method. Simple ones like this always do something sensible before setting properties, but more complex ones like a chart would not have any data to plot. The documentation tool calls $demo()$ so that your fancy new chart class can create a drawing showing what it can do. """) disc(""" Here are a handful of simple widgets available in the module <i>signsandsymbols.py</i>: """) from reportlab.graphics.shapes import Drawing from reportlab.graphics.widgets import signsandsymbols d = Drawing(230, 230) ne = signsandsymbols.NoEntry() ds = signsandsymbols.DangerSign() fd = signsandsymbols.FloppyDisk() ns = signsandsymbols.NoSmoking() ne.x, ne.y = 10, 10 ds.x, ds.y = 120, 10 fd.x, fd.y = 10, 120 ns.x, ns.y = 120, 120 d.add(ne) d.add(ds) d.add(fd) d.add(ns) draw(d, 'A few samples from signsandsymbols.py') disc(""" And this is the code needed to generate them as seen in the drawing above: """) eg(""" from reportlab.graphics.shapes import Drawing from reportlab.graphics.widgets import signsandsymbols d = Drawing(230, 230) ne = signsandsymbols.NoEntry() ds = signsandsymbols.DangerSign() fd = signsandsymbols.FloppyDisk() ns = signsandsymbols.NoSmoking() ne.x, ne.y = 10, 10 ds.x, ds.y = 120, 10 fd.x, fd.y = 10, 120 ns.x, ns.y = 120, 120 d.add(ne) d.add(ds) d.add(fd) d.add(ns) """) heading3("Compound Widgets") disc("""Let's imagine a compound widget which draws two faces side by side. This is easy to build when you have the Face widget.""") eg(""" >>> tf = widgetbase.TwoFaces() >>> tf.faceOne.mood 'happy' >>> tf.faceTwo.mood 'sad' >>> tf.dumpProperties() faceOne.eyeColor = Color(0.00,0.00,1.00) faceOne.mood = happy faceOne.size = 80 faceOne.skinColor = None faceOne.x = 10 faceOne.y = 10 faceTwo.eyeColor = Color(0.00,0.00,1.00) faceTwo.mood = sad faceTwo.size = 80 faceTwo.skinColor = None faceTwo.x = 100 faceTwo.y = 10 >>> """) disc("""The attributes 'faceOne' and 'faceTwo' are deliberately exposed so you can get at them directly. There could also be top-level attributes, but there aren't in this case.""") heading3("Verifying Widgets") disc("""The widget designer decides the policy on verification, but by default they work like shapes - checking every assignment - if the designer has provided the checking information.""") heading3("Implementing Widgets") disc("""We tried to make it as easy to implement widgets as possible. Here's the code for a Face widget which does not do any type checking:""") eg(""" class Face(Widget): \"\"\"This draws a face with two eyes, mouth and nose.\"\"\" def __init__(self): self.x = 10 self.y = 10 self.size = 80 self.skinColor = None self.eyeColor = colors.blue self.mood = 'happy' def draw(self): s = self.size # abbreviate as we will use this a lot g = shapes.Group() g.transform = [1,0,0,1,self.x, self.y] # background g.add(shapes.Circle(s * 0.5, s * 0.5, s * 0.5, fillColor=self.skinColor)) # CODE OMITTED TO MAKE MORE SHAPES return g """) disc("""We left out all the code to draw the shapes in this document, but you can find it in the distribution in $widgetbase.py$.""") disc("""By default, any attribute without a leading underscore is returned by setProperties. This is a deliberate policy to encourage consistent coding conventions.""") disc("""Once your widget works, you probably want to add support for verification. This involves adding a dictionary to the class called $_verifyMap$, which map from attribute names to 'checking functions'. The $widgetbase.py$ module defines a bunch of checking functions with names like $isNumber$, $isListOfShapes$ and so on. You can also simply use $None$, which means that the attribute must be present but can have any type. And you can and should write your own checking functions. We want to restrict the "mood" custom attribute to the values "happy", "sad" or "ok". So we do this:""") eg(""" class Face(Widget): \"\"\"This draws a face with two eyes. It exposes a couple of properties to configure itself and hides all other details\"\"\" def checkMood(moodName): return (moodName in ('happy','sad','ok')) _verifyMap = { 'x': shapes.isNumber, 'y': shapes.isNumber, 'size': shapes.isNumber, 'skinColor':shapes.isColorOrNone, 'eyeColor': shapes.isColorOrNone, 'mood': checkMood } """) disc("""This checking will be performed on every attribute assignment; or, if $config.shapeChecking$ is off, whenever you call $myFace.verify()$.""") heading3("Documenting Widgets") disc(""" We are working on a generic tool to document any Python package or module; this is already checked into ReportLab and will be used to generate a reference for the ReportLab package. When it encounters widgets, it adds extra sections to the manual including:""") bullet("the doc string for your widget class ") bullet("the code snippet from your <i>demo()</i> method, so people can see how to use it") bullet("the drawing produced by the <i>demo()</i> method ") bullet("the property dump for the widget in the drawing. ") disc(""" This tool will mean that we can have guaranteed up-to-date documentation on our widgets and charts, both on the web site and in print; and that you can do the same for your own widgets, too! """) heading3("Widget Design Strategies") disc("""We could not come up with a consistent architecture for designing widgets, so we are leaving that problem to the authors! If you do not like the default verification strategy, or the way $setProperties/getProperties$ works, you can override them yourself.""") disc("""For simple widgets it is recommended that you do what we did above: select non-overlapping properties, initialize every property on $__init__$ and construct everything when $draw()$ is called. You can instead have $__setattr__$ hooks and have things updated when certain attributes are set. Consider a pie chart. If you want to expose the individual slices, you might write code like this:""") eg(""" from reportlab.graphics.charts import piecharts pc = piecharts.Pie() pc.defaultColors = [navy, blue, skyblue] #used in rotation pc.data = [10,30,50,25] pc.slices[7].strokeWidth = 5 """) #removed 'pc.backColor = yellow' from above code example disc("""The last line is problematic as we have only created four slices - in fact we might not have created them yet. Does $pc.slices[7]$ raise an error? Is it a prescription for what should happen if a seventh wedge is defined, used to override the default settings? We dump this problem squarely on the widget author for now, and recommend that you get a simple one working before exposing 'child objects' whose existence depends on other properties' values :-)""") disc("""We also discussed rules by which parent widgets could pass properties to their children. There seems to be a general desire for a global way to say that 'all slices get their lineWidth from the lineWidth of their parent' without a lot of repetitive coding. We do not have a universal solution, so again leave that to widget authors. We hope people will experiment with push-down, pull-down and pattern-matching approaches and come up with something nice. In the meantime, we certainly can write monolithic chart widgets which work like the ones in, say, Visual Basic and Delphi.""") disc("""For now have a look at the following sample code using an early version of a pie chart widget and the output it generates:""") eg(""" from reportlab.lib.colors import * from reportlab.graphics import shapes,renderPDF from reportlab.graphics.charts.piecharts import Pie d = Drawing(400,200) d.add(String(100,175,"Without labels", textAnchor="middle")) d.add(String(300,175,"With labels", textAnchor="middle")) pc = Pie() pc.x = 25 pc.y = 50 pc.data = [10,20,30,40,50,60] pc.slices[0].popout = 5 d.add(pc, 'pie1') pc2 = Pie() pc2.x = 150 pc2.y = 50 pc2.data = [10,20,30,40,50,60] pc2.labels = ['a','b','c','d','e','f'] d.add(pc2, 'pie2') pc3 = Pie() pc3.x = 275 pc3.y = 50 pc3.data = [10,20,30,40,50,60] pc3.labels = ['a','b','c','d','e','f'] pc3.slices.labelRadius = 0.65 pc3.slices.fontName = "Helvetica-Bold" pc3.slices.fontSize = 16 pc3.slices.fontColor = colors.yellow d.add(pc3, 'pie3') """) # Hack to force a new paragraph before the todo() :-( disc("") from reportlab.lib.colors import * from reportlab.graphics import shapes,renderPDF from reportlab.graphics.charts.piecharts import Pie d = Drawing(400,200) d.add(String(100,175,"Without labels", textAnchor="middle")) d.add(String(300,175,"With labels", textAnchor="middle")) pc = Pie() pc.x = 25 pc.y = 50 pc.data = [10,20,30,40,50,60] pc.slices[0].popout = 5 d.add(pc, 'pie1') pc2 = Pie() pc2.x = 150 pc2.y = 50 pc2.data = [10,20,30,40,50,60] pc2.labels = ['a','b','c','d','e','f'] d.add(pc2, 'pie2') pc3 = Pie() pc3.x = 275 pc3.y = 50 pc3.data = [10,20,30,40,50,60] pc3.labels = ['a','b','c','d','e','f'] pc3.slices.labelRadius = 0.65 pc3.slices.fontName = "Helvetica-Bold" pc3.slices.fontSize = 16 pc3.slices.fontColor = colors.yellow d.add(pc3, 'pie3') draw(d, 'Some sample Pies')
/reportlab-4.0.4.tar.gz/reportlab-4.0.4/docs/userguide/graph_widgets.py
0.767603
0.555978
graph_widgets.py
pypi
from tools.docco.rl_doc_utils import * heading1("Writing your own $Flowable$ Objects") disc(""" Flowables are intended to be an open standard for creating reusable report content, and you can easily create your own objects. We hope that over time we will build up a library of contributions, giving reportlab users a rich selection of charts, graphics and other "report widgets" they can use in their own reports. This section shows you how to create your own flowables.""") todo("""we should put the Figure class in the standard library, as it is a very useful base.""") heading2("A very simple $Flowable$") disc(""" Recall the $hand$ function from the $pdfgen$ section of this user guide which generated a drawing of a hand as a closed figure composed from Bezier curves. """) illust(examples.hand, "a hand") disc(""" To embed this or any other drawing in a Platypus flowable we must define a subclass of $Flowable$ with at least a $wrap$ method and a $draw$ method. """) eg(examples.testhandannotation) disc(""" The $wrap$ method must provide the size of the drawing -- it is used by the Platypus mainloop to decide whether this element fits in the space remaining on the current frame. The $draw$ method performs the drawing of the object after the Platypus mainloop has translated the $(0,0)$ origin to an appropriate location in an appropriate frame. """) disc(""" Below are some example uses of the $HandAnnotation$ flowable. """) from reportlab.lib.colors import blue, pink, yellow, cyan, brown from reportlab.lib.units import inch handnote() disc("""The default.""") handnote(size=inch) disc("""Just one inch high.""") handnote(xoffset=3*inch, size=inch, strokecolor=blue, fillcolor=cyan) disc("""One inch high and shifted to the left with blue and cyan.""") heading2("Modifying a Built in $Flowable$") disc("""To modify an existing flowable, you should create a derived class and override the methods you need to change to get the desired behaviour""") disc("""As an example to create a rotated image you need to override the wrap and draw methods of the existing Image class""") import os from reportlab.platypus import * I = '../images/replogo.gif' EmbeddedCode(""" class RotatedImage(Image): def wrap(self,availWidth,availHeight): h, w = Image.wrap(self,availHeight,availWidth) return w, h def draw(self): self.canv.rotate(90) Image.draw(self) I = RotatedImage('%s') I.hAlign = 'CENTER' """ % I,'I')
/reportlab-4.0.4.tar.gz/reportlab-4.0.4/docs/userguide/ch7_custom.py
0.63114
0.513851
ch7_custom.py
pypi
from tools.docco.rl_doc_utils import * heading1("Exposing PDF Special Capabilities") disc("""PDF provides a number of features to make electronic document viewing more efficient and comfortable, and our library exposes a number of these.""") heading2("Forms") disc("""The Form feature lets you create a block of graphics and text once near the start of a PDF file, and then simply refer to it on subsequent pages. If you are dealing with a run of 5000 repetitive business forms - for example, one-page invoices or payslips - you only need to store the backdrop once and simply draw the changing text on each page. Used correctly, forms can dramatically cut file size and production time, and apparently even speed things up on the printer. """) disc("""Forms do not need to refer to a whole page; anything which might be repeated often should be placed in a form.""") disc("""The example below shows the basic sequence used. A real program would probably define the forms up front and refer to them from another location.""") eg(examples.testforms) heading2("Links and Destinations") disc("""PDF supports internal hyperlinks. There is a very wide range of link types, destination types and events which can be triggered by a click. At the moment we just support the basic ability to jump from one part of a document to another, and to control the zoom level of the window after the jump. The bookmarkPage method defines a destination that is the endpoint of a jump.""") #todo("code example here...") eg(""" canvas.bookmarkPage(name, fit="Fit", left=None, top=None, bottom=None, right=None, zoom=None ) """) disc(""" By default the $bookmarkPage$ method defines the page itself as the destination. After jumping to an endpoint defined by bookmarkPage, the PDF browser will display the whole page, scaling it to fit the screen:""") eg("""canvas.bookmarkPage(name)""") disc("""The $bookmarkPage$ method can be instructed to display the page in a number of different ways by providing a $fit$ parameter.""") eg("") t = Table([ ['fit','Parameters Required','Meaning'], ['Fit',None,'Entire page fits in window (the default)'], ['FitH','top','Top coord at top of window, width scaled to fit'], ['FitV','left','Left coord at left of window, height scaled to fit'], ['FitR','left bottom right top','Scale window to fit the specified rectangle'], ['XYZ','left top zoom','Fine grained control. If you omit a parameter\nthe PDF browser interprets it as "leave as is"'] ]) t.setStyle(TableStyle([ ('FONT',(0,0),(-1,1),'Times-Bold',10,12), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ])) getStory().append(t) caption("""Table <seq template="%(Chapter)s-%(Table+)s"/> - Required attributes for different fit types""") disc(""" Note : $fit$ settings are case-sensitive so $fit="FIT"$ is invalid """) disc(""" Sometimes you want the destination of a jump to be some part of a page. The $FitR$ fit allows you to identify a particular rectangle, scaling the area to fit the entire page. """) disc(""" To set the display to a particular x and y coordinate of the page and to control the zoom directly use fit="XYZ". """) eg(""" canvas.bookmarkPage('my_bookmark',fit="XYZ",left=0,top=200) """) disc(""" This destination is at the leftmost of the page with the top of the screen at position 200. Because $zoom$ was not set the zoom remains at whatever the user had it set to. """) eg(""" canvas.bookmarkPage('my_bookmark',fit="XYZ",left=0,top=200,zoom=2) """) disc("""This time zoom is set to expand the page 2X its normal size.""") disc(""" Note : Both $XYZ$ and $FitR$ fit types require that their positional parameters ($top, bottom, left, right$) be specified in terms of the default user space. They ignore any geometric transform in effect in the canvas graphic state. """) pencilnote() disc(""" <i>Note:</i> Two previous bookmark methods are supported but deprecated now that bookmarkPage is so general. These are $bookmarkHorizontalAbsolute$ and $bookmarkHorizontal$. """) heading3("Defining internal links") eg(""" canvas.linkAbsolute(contents, destinationname, Rect=None, addtopage=1, name=None, thickness=0, color=None, dashArray=None, **kw) """) disc(""" The $linkAbsolute$ method defines a starting point for a jump. When the user is browsing the generated document using a dynamic viewer (such as Acrobat Reader) when the mouse is clicked when the pointer is within the rectangle specified by $Rect$ the viewer will jump to the endpoint associated with $destinationname$. As in the case with $bookmarkHorizontalAbsolute$ the rectangle $Rect$ must be specified in terms of the default user space. The $contents$ parameter specifies a chunk of text which displays in the viewer if the user left-clicks on the region. """) disc(""" The rectangle $Rect$ must be specified in terms of a tuple ^(x1,y1,x2,y2)^ identifying the lower left and upper right points of the rectangle in default user space. """) disc(""" For example the code """) eg(""" canvas.bookmarkPage("Meaning_of_life") """) disc(""" defines a location as the whole of the current page with the identifier $Meaning_of_life$. To create a rectangular link to it while drawing a possibly different page, we would use this code: """) eg(""" canvas.linkAbsolute("Find the Meaning of Life", "Meaning_of_life", (inch, inch, 6*inch, 2*inch)) """) disc(""" By default during interactive viewing a rectangle appears around the link. Use the keyword argument $Border='[0 0 0]'$ to suppress the visible rectangle around the during viewing link. For example """) eg(""" canvas.linkAbsolute("Meaning of Life", "Meaning_of_life", (inch, inch, 6*inch, 2*inch), Border='[0 0 0]') """) disc("""The $thickness$, $color$ and $dashArray$ arguments may be used alternately to specify a border if no Border argument is specified. If Border is specified it must be either a string representation of a PDF array or a $PDFArray$ (see the pdfdoc module). The $color$ argument (which should be a $Color$ instance) is equivalent to a keyword argument $C$ which should resolve to a PDF color definition (Normally a three entry PDF array). """) disc("""The $canvas.linkRect$ method is similar in intent to the $linkAbsolute$ method, but has an extra argument $relative=1$ so is intended to obey the local userspace transformation.""") heading2("Outline Trees") disc("""Acrobat Reader has a navigation page which can hold a document outline; it should normally be visible when you open this guide. We provide some simple methods to add outline entries. Typically, a program to make a document (such as this user guide) will call the method $canvas.addOutlineEntry(^self, title, key, level=0, closed=None^)$ as it reaches each heading in the document. """) disc("""^title^ is the caption which will be displayed in the left pane. The ^key^ must be a string which is unique within the document and which names a bookmark, as with the hyperlinks. The ^level^ is zero - the uppermost level - unless otherwise specified, and it is an error to go down more than one level at a time (for example to follow a level 0 heading by a level 2 heading). Finally, the ^closed^ argument specifies whether the node in the outline pane is closed or opened by default.""") disc("""The snippet below is taken from the document template that formats this user guide. A central processor looks at each paragraph in turn, and makes a new outline entry when a new chapter occurs, taking the chapter heading text as the caption text. The key is obtained from the chapter number (not shown here), so Chapter 2 has the key 'ch2'. The bookmark to which the outline entry points aims at the whole page, but it could as easily have been an individual paragraph. """) eg(""" #abridged code from our document template if paragraph.style == 'Heading1': self.chapter = paragraph.getPlainText() key = 'ch%d' % self.chapterNo self.canv.bookmarkPage(key) self.canv.addOutlineEntry(paragraph.getPlainText(), key, 0, 0) """) heading2("Page Transition Effects") eg(""" canvas.setPageTransition(self, effectname=None, duration=1, direction=0,dimension='H',motion='I') """) disc(""" The $setPageTransition$ method specifies how one page will be replaced with the next. By setting the page transition effect to "dissolve" for example the current page will appear to melt away when it is replaced by the next page during interactive viewing. These effects are useful in spicing up slide presentations, among other places. Please see the reference manual for more detail on how to use this method. """) heading2("Internal File Annotations") eg(""" canvas.setAuthor(name) canvas.setTitle(title) canvas.setSubject(subj) """) disc(""" These methods have no automatically seen visible effect on the document. They add internal annotations to the document. These annotations can be viewed using the "Document Info" menu item of the browser and they also can be used as a simple standard way of providing basic information about the document to archiving software which need not parse the entire file. To find the annotations view the $*.pdf$ output file using a standard text editor (such as $notepad$ on MS/Windows or $vi$ or $emacs$ on unix) and look for the string $/Author$ in the file contents. """) eg(examples.testannotations) disc(""" If you want the subject, title, and author to automatically display in the document when viewed and printed you must paint them onto the document like any other text. """) illust(examples.annotations, "Setting document internal annotations") heading2("Encryption") heading3("About encrypting PDF files") disc(""" Adobe's PDF standard allows you to do three related things to a PDF file when you encrypt it: """) bullet("""Apply password protection to it, so a user must supply a valid password before being able to read it, """) bullet("""Encrypt the contents of the file to make it useless until it is decrypted, and """) bullet("""Control whether the user can print, copy and paste or modify the document while viewing it. """) disc(""" The PDF security handler allows two different passwords to be specified for a document: """) bullet("""The 'owner' password (aka the 'security password' or 'master password') """) bullet("""The 'user' password (aka the 'open password') """) disc(""" When a user supplies either one of these passwords, the PDF file will be opened, decrypted and displayed on screen. """) disc(""" If the owner password is supplied, then the file is opened with full control - you can do anything to it, including changing the security settings and passwords, or re-encrypting it with a new password. """) disc(""" If the user password was the one that was supplied, you open it up in a more restricted mode. The restrictions were put in place when the file was encrypted, and will either allow or deny the user permission to do the following: """) bullet(""" Modifying the document's contents """) bullet(""" Copying text and graphics from the document """) bullet(""" Adding or modifying text annotations and interactive form fields """) bullet(""" Printing the document """) disc(""" Note that all password protected PDF files are encrypted, but not all encrypted PDFs are password protected. If a document's user password is an empty string, there will be no prompt for the password when the file is opened. If you only secure a document with the owner password, there will also not be a prompt for the password when you open the file. If the owner and user passwords are set to the same string when encrypting the PDF file, the document will always open with the user access privileges. This means that it is possible to create a file which, for example, is impossible for anyone to print out, even the person who created it. """) t = Table([ ['Owner Password \nset?','User Password \nset?','Result'], ['Y','-','No password required when opening file. \nRestrictions apply to everyone.'], ['-','Y','User password required when opening file. \nRestrictions apply to everyone.'], ['Y','Y','A password required when opening file. \nRestrictions apply only if user password supplied.'], ],[90, 90, 260]) t.setStyle(TableStyle([ ('FONT',(0,0),(-1,0),'Times-Bold',10,12), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ])) getStory().append(t) disc(""" When a PDF file is encrypted, encryption is applied to all the strings and streams in the file. This prevents people who don't have the password from simply removing the password from the PDF file to gain access to it - it renders the file useless unless you actually have the password. """) disc(""" PDF's standard encryption methods use the MD5 message digest algorithm (as described in RFC 1321, The MD5 Message-Digest Algorithm) and an encryption algorithm known as RC4. RC4 is a symmetric stream cipher - the same algorithm is used both for encryption and decryption, and the algorithm does not change the length of the data. """) heading3("How To Use Encryption") disc(""" Documents can be encrypted by passing an argument to the canvas object. """) disc(""" If the argument is a string object, it is used as the User password to the PDF. """) disc(""" The argument can also be an instance of the class $reportlab.lib.pdfencrypt.StandardEncryption$, which allows more finegrained control over encryption settings. """) disc(""" The $StandardEncryption$ constructor takes the following arguments: """) eg(""" def __init__(self, userPassword, ownerPassword=None, canPrint=1, canModify=1, canCopy=1, canAnnotate=1, strength=40): """) disc(""" The $userPassword$ and $ownerPassword$ parameters set the relevant password on the encrypted PDF. """) disc(""" The boolean flags $canPrint$, $canModify$, $canCopy$, $canAnnotate$ determine wether a user can perform the corresponding actions on the PDF when only a user password has been supplied. """) disc(""" If the user supplies the owner password while opening the PDF, all actions can be performed regardless of the flags. """) heading3("Example") disc(""" To create a document named hello.pdf with a user password of 'rptlab' on which printing is not allowed, use the following code: """) eg(""" from reportlab.pdfgen import canvas from reportlab.lib import pdfencrypt enc=pdfencrypt.StandardEncryption("rptlab",canPrint=0) def hello(c): c.drawString(100,100,"Hello World") c = canvas.Canvas("hello.pdf",encrypt=enc) hello(c) c.showPage() c.save() """) heading2("Interactive Forms") heading3("Overview of Interactive Forms") disc("""The PDF standard allows for various kinds of interactive elements, the ReportLab toolkit currently supports only a fraction of the possibilities and should be considered a work in progress. At present we allow choices with <i>checkbox</i>, <i>radio</i>, <i>choice</i> &amp; <i>listbox</i> widgets; text values can be entered with a <i>textfield</i> widget. All the widgets are created by calling methods on the <i>canvas.acroform</i> property.""" ) heading3("Example") disc("This shows the basic mechanism of creating an interactive element on the current page.") eg(""" canvas.acroform.checkbox( name='CB0', tooltip='Field CB0', checked=True, x=72,y=72+4*36, buttonStyle='diamond', borderStyle='bevelled', borderWidth=2, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) """) alStyle=TableStyle([ ('SPAN',(0,0),(-1,0)), ('FONT',(0,0),(-1,0),'Helvetica-Bold',10,12), ('FONT',(0,1),(-1,1),'Helvetica-BoldOblique',8,9.6), ('FONT',(0,2),(0,-1),'Helvetica-Bold',7,8.4), ('FONT',(1,2),(1,-1),'Helvetica',7,8.4), ('FONT',(2,2),(2,-1),'Helvetica-Oblique',7,8.4), ('ALIGN',(0,0),(-1,0),'CENTER'), ('ALIGN',(1,1),(1,1),'CENTER'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ]) disc("""<b>NB</b> note that the <i>acroform</i> canvas property is created automatically on demand and that there is only one form allowd in a document.""") heading3("Checkbox Usage") disc("""The <i>canvas.acroform.checkbox</i> method creates a <i>checkbox</i> widget on the current page. The value of the checkbox is either <b>YES</b> or <b>OFF</b>. The arguments are""") t = Table([ ['canvas.acroform.checkbox parameters','',''], ['Parameter','Meaning','Default'], ["name","the parameter's name","None"], ["x","the horizontal position on the page (absolute coordinates)","0"], ["y","the vertical position on the page (absolute coordinates)","0"], ["size","The outline dimensions size x size","20"], ["checked","if True the checkbox is initially checked","False"], ["buttonStyle","the checkbox style (see below)","'check'"], ["shape","The outline of the widget (see below)","'square'"], ["fillColor","colour to be used to fill the widget","None"], ["textColor","the colour of the symbol or text","None"], ["borderWidth","as it says","1"], ["borderColor","the widget's border colour","None"], ["borderStyle","The border style name","'solid'"], ["tooltip","The text to display when hovering over the widget","None"], ["annotationFlags","blank separated string of annotation flags","'print'"], ["fieldFlags","Blank separated field flags (see below)","'required'"], ["forceBorder","when true a border force a border to be drawn","False"], ["relative","if true obey the current canvas transform","False"], ["dashLen ","the dashline to be used if the borderStyle=='dashed'","3"], ],[90, 260, 90],style=alStyle,repeatRows=2) getStory().append(t) heading3("Radio Usage") disc("""The <i>canvas.acroform.radio</i> method creates a <i>radio</i> widget on the current page. The value of the radio is the value of the radio group's selected value or <b>OFF</b> if none are selected. The arguments are""") t = Table([ ['canvas.acroform.radio parameters','',''], ['Parameter','Meaning','Default'], ["name","the radio's group (ie parameter) name","None"], ["value","the radio's group name","None"], ["x","the horizontal position on the page (absolute coordinates)","0"], ["y","the vertical position on the page (absolute coordinates)","0"], ["size","The outline dimensions size x size","20"], ["selected","if True this radio is the selected one in its group","False"], ["buttonStyle","the checkbox style (see below)","'check'"], ["shape","The outline of the widget (see below)","'square'"], ["fillColor","colour to be used to fill the widget","None"], ["textColor","the colour of the symbol or text","None"], ["borderWidth","as it says","1"], ["borderColor","the widget's border colour","None"], ["borderStyle","The border style name","'solid'"], ["tooltip","The text to display when hovering over the widget","None"], ["annotationFlags","blank separated string of annotation flags","'print'"], ["fieldFlags","Blank separated field flags (see below)","'noToggleToOff required radio'"], ["forceBorder","when true a border force a border to be drawn","False"], ["relative","if true obey the current canvas transform","False"], ["dashLen ","the dashline to be used if the borderStyle=='dashed'","3"], ],[90, 260, 90],style=alStyle,repeatRows=2) getStory().append(t) heading3("Listbox Usage") disc("""The <i>canvas.acroform.listbox</i> method creates a <i>listbox</i> widget on the current page. The listbox contains a list of options one or more of which (depending on fieldFlags) may be selected. """) t = Table([ ['canvas.acroform.listbox parameters','',''], ['Parameter','Meaning','Default'], ["name","the radio's group (ie parameter) name","None"], ["options","List or tuple of avaiable options","[]"], ["value","Singleton or list of strings of selected options","[]"], ["x","the horizontal position on the page (absolute coordinates)","0"], ["y","the vertical position on the page (absolute coordinates)","0"], ["width","The widget width","120"], ["height","The widget height","36"], ["fontName","The name of the type 1 font to be used","'Helvetica'"], ["fontSize","The size of font to be used","12"], ["fillColor","colour to be used to fill the widget","None"], ["textColor","the colour of the symbol or text","None"], ["borderWidth","as it says","1"], ["borderColor","the widget's border colour","None"], ["borderStyle","The border style name","'solid'"], ["tooltip","The text to display when hovering over the widget","None"], ["annotationFlags","blank separated string of annotation flags","'print'"], ["fieldFlags","Blank separated field flags (see below)","''"], ["forceBorder","when true a border force a border to be drawn","False"], ["relative","if true obey the current canvas transform","False"], ["dashLen ","the dashline to be used if the borderStyle=='dashed'","3"], ],[90, 260, 90],style=alStyle,repeatRows=2) getStory().append(t) heading3("Choice Usage") disc("""The <i>canvas.acroform.choice</i> method creates a <i>dropdown</i> widget on the current page. The dropdown contains a list of options one or more of which (depending on fieldFlags) may be selected. If you add <i>edit</i> to the <i>fieldFlags</i> then the result may be edited. """) t = Table([ ['canvas.acroform.choice parameters','',''], ['Parameter','Meaning','Default'], ["name","the radio's group (ie parameter) name","None"], ["options","List or tuple of avaiable options","[]"], ["value","Singleton or list of strings of selected options","[]"], ["x","the horizontal position on the page (absolute coordinates)","0"], ["y","the vertical position on the page (absolute coordinates)","0"], ["width","The widget width","120"], ["height","The widget height","36"], ["fontName","The name of the type 1 font to be used","'Helvetica'"], ["fontSize","The size of font to be used","12"], ["fillColor","colour to be used to fill the widget","None"], ["textColor","the colour of the symbol or text","None"], ["borderWidth","as it says","1"], ["borderColor","the widget's border colour","None"], ["borderStyle","The border style name","'solid'"], ["tooltip","The text to display when hovering over the widget","None"], ["annotationFlags","blank separated string of annotation flags","'print'"], ["fieldFlags","Blank separated field flags (see below)","'combo'"], ["forceBorder","when true a border force a border to be drawn","False"], ["relative","if true obey the current canvas transform","False"], ["dashLen ","the dashline to be used if the borderStyle=='dashed'","3"], ["maxlen ","None or maximum length of the widget value","None"], ],[90, 260, 90],style=alStyle,repeatRows=2) getStory().append(t) heading3("Textfield Usage") disc("""The <i>canvas.acroform.textfield</i> method creates a <i>textfield</i> entry widget on the current page. The textfield may be edited to change tha value of the widget """) t = Table([ ['canvas.acroform.textfield parameters','',''], ['Parameter','Meaning','Default'], ["name","the radio's group (ie parameter) name","None"], ["value","Value of the text field","''"], ["maxlen ","None or maximum length of the widget value","100"], ["x","the horizontal position on the page (absolute coordinates)","0"], ["y","the vertical position on the page (absolute coordinates)","0"], ["width","The widget width","120"], ["height","The widget height","36"], ["fontName","The name of the type 1 font to be used","'Helvetica'"], ["fontSize","The size of font to be used","12"], ["fillColor","colour to be used to fill the widget","None"], ["textColor","the colour of the symbol or text","None"], ["borderWidth","as it says","1"], ["borderColor","the widget's border colour","None"], ["borderStyle","The border style name","'solid'"], ["tooltip","The text to display when hovering over the widget","None"], ["annotationFlags","blank separated string of annotation flags","'print'"], ["fieldFlags","Blank separated field flags (see below)","''"], ["forceBorder","when true a border force a border to be drawn","False"], ["relative","if true obey the current canvas transform","False"], ["dashLen ","the dashline to be used if the borderStyle=='dashed'","3"], ],[90, 260, 90],style=alStyle,repeatRows=2) getStory().append(t) heading3("Button styles") disc("""The button style argument indicates what style of symbol should appear in the button when it is selected. There are several choices""") eg(""" check cross circle star diamond """) disc("""note that the document renderer can make some of these symbols wrong for their intended application. Acrobat reader prefers to use its own rendering on top of what the specification says should be shown (especially when the forms hihlighting features are used""") heading3("Widget shape") disc("""The shape argument describes how the outline of the checkbox or radio widget should appear you can use""") eg(""" circle square """) disc("""The renderer may make its own decisions about how the widget should look; so Acrobat Reader prefers circular outlines for radios.""") heading3("Border style") disc("""The borderStyle argument changes the 3D appearance of the widget on the page alternatives are""") eg(""" solid dashed inset bevelled underlined """) heading3("fieldFlags Argument") disc("""The fieldFlags arguments can be an integer or a string containing blank separate tokens the values are shown in the table below. For more information consult the PDF specification.""") t = Table([ ['Field Flag Tokens and values','',''], ['Token','Meaning','Value'], ["readOnly","The widget is read only","1<<0"], ["required","the widget is required","1<<1"], ["noExport","don't export the widget value","1<<2"], ["noToggleToOff","radios one only must be on","1<<14"], ["radio","added by the radio method","1<<15"], ["pushButton","if the button is a push button","1<<16"], ["radiosInUnison","radios with the same value toggle together","1<<25"], ["multiline","for multiline text widget","1<<12"], ["password","password textfield","1<<13"], ["fileSelect","file selection widget","1<<20"], #1.4 ["doNotSpellCheck","as it says","1<<22"], #1.4 ["doNotScroll","text fields do not scroll","1<<23"], #1.4 ["comb","make a comb style text based on the maxlen value","1<<24"], #1.5 ["richText","if rich text is used","1<<25"], #1.5 ["combo","for choice fields","1<<17"], ["edit","if the choice is editable","1<<18"], ["sort","if the values should be sorted","1<<19"], ["multiSelect","if the choice allows multi-select","1<<21"], #1.4 ["commitOnSelChange","not used by reportlab","1<<26"], #1.5 ],[90, 260, 90],style=alStyle,repeatRows=2) getStory().append(t) heading3("annotationFlags Argument") disc("""PDF widgets are annotations and have annotation properties these are shown in the table below""") t = Table([ ['Annotation Flag Tokens and values','',''], ['Token','Meaning','Value'], ["invisible","The widget is not shown","1<<0"], ["hidden","The widget is hidden","1<<1"], ["print","The widget will print","1<<2"], ["nozoom","The annotation will notscale with the rendered page","1<<3"], ["norotate","The widget won't rotate with the page","1<<4"], ["noview","Don't render the widget","1<<5"], ["readonly","Widget cannot be interacted with","1<<6"], ["locked","The widget cannot be changed","1<<7"], #1.4 ["togglenoview","Teh widget may be viewed after some events","1<<8"], #1.9 ["lockedcontents","The contents of the widget are fixed","1<<9"], #1.7 ],[90, 260, 90],style=alStyle) getStory().append(t)
/reportlab-4.0.4.tar.gz/reportlab-4.0.4/docs/userguide/ch3_pdffeatures.py
0.632389
0.535281
ch3_pdffeatures.py
pypi
from tools.docco.rl_doc_utils import * #####################################################################################################3 heading1("PLATYPUS - Page Layout and Typography Using Scripts") heading2("Design Goals") disc(""" Platypus stands for &quot;Page Layout and Typography Using Scripts&quot;. It is a high level page layout library which lets you programmatically create complex documents with a minimum of effort. """) disc(""" The design of Platypus seeks to separate "high level" layout decisions from the document content as much as possible. Thus, for example, paragraphs are constructed using paragraph styles and pages are constructed using page templates with the intention that hundreds of documents with thousands of pages can be reformatted to different style specifications with the modifications of a few lines in a single shared file which contains the paragraph styles and page layout specifications. """) disc(""" The overall design of Platypus can be thought of has having several layers, top down, these are""") disc("<b>$DocTemplates$</b> the outermost container for the document;") disc("<b>$PageTemplates$</b> specifications for layouts of pages of various kinds;") disc("<b>$Frames$</b> specifications of regions in pages that can contain flowing text or graphics.") disc("""<b>$Flowables$</b> text or graphic elements that should be "flowed into the document (i.e. things like images, paragraphs and tables, but not things like page footers or fixed page graphics).""") disc("""<b>$pdfgen.Canvas$</b> the lowest level which ultimately receives the painting of the document from the other layers.""") illust(examples.doctemplateillustration, "Illustration of DocTemplate structure") disc(""" The illustration above graphically illustrates the concepts of $DocTemplates$, $PageTemplates$ and $Flowables$. It is deceptive, however, because each of the $PageTemplates$ actually may specify the format for any number of pages (not just one as might be inferred from the diagram). """) disc(""" $DocTemplates$ contain one or more $PageTemplates$ each of which contain one or more $Frames$. $Flowables$ are things which can be <i>flowed</i> into a $Frame$ e.g. a $Paragraph$ or a $Table$. """) disc(""" To use platypus you create a document from a $DocTemplate$ class and pass a list of $Flowable$s to its $build$ method. The document $build$ method knows how to process the list of flowables into something reasonable. """) disc(""" Internally the $DocTemplate$ class implements page layout and formatting using various events. Each of the events has a corresponding handler method called $handle_XXX$ where $XXX$ is the event name. A typical event is $frameBegin$ which occurs when the machinery begins to use a frame for the first time. """) disc(""" A Platypus story consists of a sequence of basic elements called $Flowables$ and these elements drive the data driven Platypus formatting engine. To modify the behavior of the engine a special kind of flowable, $ActionFlowables$, tell the layout engine to, for example, skip to the next column or change to another $PageTemplate$. """) heading2("""Getting started""") disc("""Consider the following code sequence which provides a very simple "hello world" example for Platypus.""") eg(examples.platypussetup) disc("""First we import some constructors, some paragraph styles and other conveniences from other modules.""") eg(examples.platypusfirstpage) disc("""We define the fixed features of the first page of the document with the function above.""") eg(examples.platypusnextpage) disc("""Since we want pages after the first to look different from the first we define an alternate layout for the fixed features of the other pages. Note that the two functions above use the $pdfgen$ level canvas operations to paint the annotations for the pages. """) eg(examples.platypusgo) disc(""" Finally, we create a story and build the document. Note that we are using a "canned" document template here which comes pre-built with page templates. We are also using a pre-built paragraph style. We are only using two types of flowables here -- $Spacers$ and $Paragraphs$. The first $Spacer$ ensures that the Paragraphs skip past the title string. """) disc(""" To see the output of this example program run the module $tools/docco/examples.py$ (from the ReportLab $source$ distribution) as a "top level script". The script interpretation $python examples.py$ will generate the Platypus output $phello.pdf$. """) heading2("$Flowables$") disc(""" $Flowables$ are things which can be drawn and which have $wrap$, $draw$ and perhaps $split$ methods. $Flowable$ is an abstract base class for things to be drawn and an instance knows its size and draws in its own coordinate system (this requires the base API to provide an absolute coordinate system when the $Flowable.draw$ method is called). To get an instance use $f=Flowable()$. """) disc(""" It should be noted that the $Flowable$ class is an <i>abstract</i> class and is normally only used as a base class. """) k=startKeep() disc(""" To illustrate the general way in which $Flowables$ are used we show how a derived class $Paragraph$ is used and drawn on a canvas. $Paragraphs$ are so important they will get a whole chapter to themselves. """) eg(""" from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import Paragraph from reportlab.pdfgen.canvas import Canvas styleSheet = getSampleStyleSheet() style = styleSheet['BodyText'] P=Paragraph('This is a very silly example',style) canv = Canvas('doc.pdf') aW = 460 # available width and height aH = 800 w,h = P.wrap(aW, aH) # find required space if w<=aW and h<=aH: P.drawOn(canv,0,aH) aH = aH - h # reduce the available height canv.save() else: raise ValueError, "Not enough room" """) endKeep(k) heading3("$Flowable$ User Methods") eg(""" Flowable.draw() """) disc("""This will be called to ask the flowable to actually render itself. The $Flowable$ class does not implement $draw$. The calling code should ensure that the flowable has an attribute $canv$ which is the $pdfgen.Canvas$ which should be drawn to an that the $Canvas$ is in an appropriate state (as regards translations rotations, etc). Normally this method will only be called internally by the $drawOn$ method. Derived classes must implement this method. """) eg(""" Flowable.drawOn(canvas,x,y) """) disc(""" This is the method which controlling programs use to render the flowable to a particular canvas. It handles the translation to the canvas coordinate (<i>x</i>,<i>y</i>) and ensuring that the flowable has a $canv$ attribute so that the $draw$ method (which is not implemented in the base class) can render in an absolute coordinate frame. """) eg(""" Flowable.wrap(availWidth, availHeight) """) disc("""This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.""") eg(""" Flowable.split(self, availWidth, availheight): """) disc("""This will be called by more sophisticated frames when wrap fails. Stupid flowables should return [] meaning that they are unable to split. Clever flowables should split themselves and return a list of flowables. It is up to the client code to ensure that repeated attempts to split are avoided. If the space is sufficient the split method should return [self]. Otherwise the flowable should rearrange itself and return a list $[f0,...]$ of flowables which will be considered in order. The implemented split method should avoid changing $self$ as this will allow sophisticated layout mechanisms to do multiple passes over a list of flowables. """) heading2("Guidelines for flowable positioning") disc("""Two methods, which by default return zero, provide guidance on vertical spacing of flowables: """) eg(""" Flowable.getSpaceAfter(self): Flowable.getSpaceBefore(self): """) disc("""These methods return how much space should follow or precede the flowable. The space doesn't belong to the flowable itself i.e. the flowable's $draw$ method shouldn't consider it when rendering. Controlling programs will use the values returned in determining how much space is required by a particular flowable in context. """) disc("""All flowables have an $hAlign$ property: $('LEFT', 'RIGHT', 'CENTER' or 'CENTRE')$. For paragraphs, which fill the full width of the frame, this has no effect. For tables, images or other objects which are less than the width of the frame, this determines their horizontal placement. """) disc("""The chapters which follow will cover the most important specific types of flowables: Paragraphs and Tables.""") heading2("Frames") disc(""" $Frames$ are active containers which are themselves contained in $PageTemplates$. $Frames$ have a location and size and maintain a concept of remaining drawable space. The command """) eg(""" Frame(x1, y1, width,height, leftPadding=6, bottomPadding=6, rightPadding=6, topPadding=6, id=None, showBoundary=0) """) disc("""creates a $Frame$ instance with lower left hand corner at coordinate $(x1,y1)$ (relative to the canvas at use time) and with dimensions $width$ x $height$. The $Padding$ arguments are positive quantities used to reduce the space available for drawing. The $id$ argument is an identifier for use at runtime e.g. 'LeftColumn' or 'RightColumn' etc. If the $showBoundary$ argument is non-zero then the boundary of the frame will get drawn at run time (this is useful sometimes). """) heading3("$Frame$ User Methods") eg(""" Frame.addFromList(drawlist, canvas) """) disc("""consumes $Flowables$ from the front of $drawlist$ until the frame is full. If it cannot fit one object, raises an exception.""") eg(""" Frame.split(flowable,canv) """) disc('''Asks the flowable to split using up the available space and return the list of flowables. ''') eg(""" Frame.drawBoundary(canvas) """) disc("draws the frame boundary as a rectangle (primarily for debugging).") heading3("Using $Frames$") disc(""" $Frames$ can be used directly with canvases and flowables to create documents. The $Frame.addFromList$ method handles the $wrap$ &amp; $drawOn$ calls for you. You don't need all of the Platypus machinery to get something useful into PDF. """) eg(""" from reportlab.pdfgen.canvas import Canvas from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.units import inch from reportlab.platypus import Paragraph, Frame styles = getSampleStyleSheet() styleN = styles['Normal'] styleH = styles['Heading1'] story = [] #add some flowables story.append(Paragraph("This is a Heading",styleH)) story.append(Paragraph("This is a paragraph in <i>Normal</i> style.", styleN)) c = Canvas('mydoc.pdf') f = Frame(inch, inch, 6*inch, 9*inch, showBoundary=1) f.addFromList(story,c) c.save() """) heading2("Documents and Templates") disc(""" The $BaseDocTemplate$ class implements the basic machinery for document formatting. An instance of the class contains a list of one or more $PageTemplates$ that can be used to describe the layout of information on a single page. The $build$ method can be used to process a list of $Flowables$ to produce a <b>PDF</b> document. """) CPage(3.0) heading3("The $BaseDocTemplate$ class") eg(""" BaseDocTemplate(self, filename, pagesize=defaultPageSize, pageTemplates=[], showBoundary=0, leftMargin=inch, rightMargin=inch, topMargin=inch, bottomMargin=inch, allowSplitting=1, title=None, author=None, _pageBreakQuick=1, encrypt=None) """) disc(""" creates a document template suitable for creating a basic document. It comes with quite a lot of internal machinery, but no default page templates. The required $filename$ can be a string, the name of a file to receive the created <b>PDF</b> document; alternatively it can be an object which has a $write$ method such as a $BytesIO$ or $file$ or $socket$. """) disc(""" The allowed arguments should be self explanatory, but $showBoundary$ controls whether or not $Frame$ boundaries are drawn which can be useful for debugging purposes. The $allowSplitting$ argument determines whether the builtin methods should try to <i>split</i> individual $Flowables$ across $Frames$. The $_pageBreakQuick$ argument determines whether an attempt to do a page break should try to end all the frames on the page or not, before ending the page. The encrypt argument determines wether or not and how the document is encrypted. By default, the document is not encrypted. If $encrypt$ is a string object, it is used as the user password for the pdf. If $encrypt$ is an instance of $reportlab.lib.pdfencrypt.StandardEncryption$, this object is used to encrypt the pdf. This allows more finegrained control over the encryption settings. """) heading4("User $BaseDocTemplate$ Methods") disc("""These are of direct interest to client programmers in that they are normally expected to be used. """) eg(""" BaseDocTemplate.addPageTemplates(self,pageTemplates) """) disc(""" This method is used to add one or a list of $PageTemplates$ to an existing documents. """) eg(""" BaseDocTemplate.build(self, flowables, filename=None, canvasmaker=canvas.Canvas) """) disc(""" This is the main method which is of interest to the application programmer. Assuming that the document instance is correctly set up the $build$ method takes the <i>story</i> in the shape of the list of flowables (the $flowables$ argument) and loops through the list forcing the flowables one at a time through the formatting machinery. Effectively this causes the $BaseDocTemplate$ instance to issue calls to the instance $handle_XXX$ methods to process the various events. """) heading4("User Virtual $BaseDocTemplate$ Methods") disc(""" These have no semantics at all in the base class. They are intended as pure virtual hooks into the layout machinery. Creators of immediately derived classes can override these without worrying about affecting the properties of the layout engine. """) eg(""" BaseDocTemplate.afterInit(self) """) disc(""" This is called after initialisation of the base class; a derived class could overide the method to add default $PageTemplates$. """) eg(""" BaseDocTemplate.afterPage(self) """) disc("""This is called after page processing, and immediately after the afterDrawPage method of the current page template. A derived class could use this to do things which are dependent on information in the page such as the first and last word on the page of a dictionary. """) eg(""" BaseDocTemplate.beforeDocument(self) """) disc("""This is called before any processing is done on the document, but after the processing machinery is ready. It can therefore be used to do things to the instance\'s $pdfgen.canvas$ and the like. """) eg(""" BaseDocTemplate.beforePage(self) """) disc("""This is called at the beginning of page processing, and immediately before the beforeDrawPage method of the current page template. It could be used to reset page specific information holders.""") eg(""" BaseDocTemplate.filterFlowables(self,flowables) """) disc("""This is called to filter flowables at the start of the main handle_flowable method. Upon return if flowables[0] has been set to None it is discarded and the main method returns immediately. """) eg(""" BaseDocTemplate.afterFlowable(self, flowable) """) disc("""Called after a flowable has been rendered. An interested class could use this hook to gather information about what information is present on a particular page or frame.""") heading4("$BaseDocTemplate$ Event handler Methods") disc(""" These methods constitute the greater part of the layout engine. Programmers shouldn't have to call or override these methods directly unless they are trying to modify the layout engine. Of course, the experienced programmer who wants to intervene at a particular event, $XXX$, which does not correspond to one of the virtual methods can always override and call the base method from the drived class version. We make this easy by providing a base class synonym for each of the handler methods with the same name prefixed by an underscore '_'. """) eg(""" def handle_pageBegin(self): doStuff() BaseDocTemplate.handle_pageBegin(self) doMoreStuff() #using the synonym def handle_pageEnd(self): doStuff() self._handle_pageEnd() doMoreStuff() """) disc(""" Here we list the methods only as an indication of the events that are being handled. Interested programmers can take a look at the source. """) eg(""" handle_currentFrame(self,fx) handle_documentBegin(self) handle_flowable(self,flowables) handle_frameBegin(self,*args) handle_frameEnd(self) handle_nextFrame(self,fx) handle_nextPageTemplate(self,pt) handle_pageBegin(self) handle_pageBreak(self) handle_pageEnd(self) """) disc(""" Using document templates can be very easy; $SimpleDoctemplate$ is a class derived from $BaseDocTemplate$ which provides its own $PageTemplate$ and $Frame$ setup. """) eg(""" from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.pagesizes import letter from reportlab.platypus import Paragraph, SimpleDocTemplate styles = getSampleStyleSheet() styleN = styles['Normal'] styleH = styles['Heading1'] story = [] #add some flowables story.append(Paragraph("This is a Heading",styleH)) story.append(Paragraph("This is a paragraph in <i>Normal</i> style.", styleN)) doc = SimpleDocTemplate('mydoc.pdf',pagesize = letter) doc.build(story) """) heading3("$PageTemplates$") disc(""" The $PageTemplate$ class is a container class with fairly minimal semantics. Each instance contains a list of $Frames$ and has methods which should be called at the start and end of each page. """) eg("PageTemplate(id=None,frames=[],onPage=_doNothing,onPageEnd=_doNothing)") disc(""" is used to initialize an instance, the $frames$ argument should be a list of $Frames$ whilst the optional $onPage$ and $onPageEnd$ arguments are callables which should have signature $def XXX(canvas,document)$ where $canvas$ and $document$ are the canvas and document being drawn. These routines are intended to be used to paint non-flowing (i.e. standard) parts of pages. These attribute functions are exactly parallel to the pure virtual methods $PageTemplate.beforPage$ and $PageTemplate.afterPage$ which have signature $beforPage(self,canvas,document)$. The methods allow class derivation to be used to define standard behaviour, whilst the attributes allow instance changes. The $id$ argument is used at run time to perform $PageTemplate$ switching so $id='FirstPage'$ or $id='TwoColumns'$ are typical. """)
/reportlab-4.0.4.tar.gz/reportlab-4.0.4/docs/userguide/ch4_platypus_concepts.py
0.741019
0.584538
ch4_platypus_concepts.py
pypi
from reportlab.platypus import PageTemplate, BaseDocTemplate, Frame, Paragraph from reportlab.lib.units import inch from reportlab.lib.sequencer import Sequencer from reportlab.rl_config import defaultPageSize class FrontCoverTemplate(PageTemplate): def __init__(self, id, pageSize=defaultPageSize): self.pageWidth = pageSize[0] self.pageHeight = pageSize[1] frame1 = Frame(inch, 3*inch, self.pageWidth - 2*inch, self.pageHeight - 518, id='cover') PageTemplate.__init__(self, id, [frame1]) # note lack of onPage def afterDrawPage(self, canvas, doc): canvas.saveState() canvas.drawImage('../images/replogo.gif',2*inch, 8*inch) canvas.setFont('Times-Roman', 10) canvas.line(inch, 120, self.pageWidth - inch, 120) canvas.drawString(inch, 100, 'ReportLab') canvas.drawString(inch, 88, 'Wimbletech') canvas.drawString(inch, 76, '35 Wimbledon Hill Road') canvas.drawString(inch, 64, 'London SW19 7NB, UK') canvas.restoreState() class OneColumnTemplate(PageTemplate): def __init__(self, id, pageSize=defaultPageSize): self.pageWidth = pageSize[0] self.pageHeight = pageSize[1] frame1 = Frame(inch, inch, self.pageWidth - 2*inch, self.pageHeight - 2*inch, id='normal') PageTemplate.__init__(self, id, [frame1]) # note lack of onPage def afterDrawPage(self, canvas, doc): y = self.pageHeight - 50 canvas.saveState() canvas.setFont('Times-Roman', 10) canvas.drawString(inch, y+8, doc.title) canvas.drawRightString(self.pageWidth - inch, y+8, doc.chapter) canvas.line(inch, y, self.pageWidth - inch, y) canvas.drawCentredString(doc.pagesize[0] / 2, 0.75*inch, 'Page %d' % canvas.getPageNumber()) canvas.restoreState() class TOCTemplate(PageTemplate): def __init__(self, id, pageSize=defaultPageSize): self.pageWidth = pageSize[0] self.pageHeight = pageSize[1] frame1 = Frame(inch, inch, self.pageWidth - 2*inch, self.pageHeight - 2*inch, id='normal') PageTemplate.__init__(self, id, [frame1]) # note lack of onPage def afterDrawPage(self, canvas, doc): y = self.pageHeight - 50 canvas.saveState() canvas.setFont('Times-Roman', 10) canvas.drawString(inch, y+8, doc.title) canvas.drawRightString(self.pageWidth - inch, y+8, 'Table of contents') canvas.line(inch, y, self.pageWidth - inch, y) canvas.drawCentredString(doc.pagesize[0] / 2, 0.75*inch, 'Page %d' % canvas.getPageNumber()) canvas.restoreState() class TwoColumnTemplate(PageTemplate): def __init__(self, id, pageSize=defaultPageSize): self.pageWidth = pageSize[0] self.pageHeight = pageSize[1] colWidth = 0.5 * (self.pageWidth - 2.25*inch) frame1 = Frame(inch, inch, colWidth, self.pageHeight - 2*inch, id='leftCol') frame2 = Frame(0.5 * self.pageWidth + 0.125, inch, colWidth, self.pageHeight - 2*inch, id='rightCol') PageTemplate.__init__(self, id, [frame1, frame2]) # note lack of onPage def afterDrawPage(self, canvas, doc): y = self.pageHeight - 50 canvas.saveState() canvas.setFont('Times-Roman', 10) canvas.drawString(inch, y+8, doc.title) canvas.drawRightString(self.pageWidth - inch, y+8, doc.chapter) canvas.line(inch, y, self.pageWidth - inch, y*inch) canvas.drawCentredString(doc.pagesize[0] / 2, 0.75*inch, 'Page %d' % canvas.getPageNumber()) canvas.restoreState() class RLDocTemplate(BaseDocTemplate): def afterInit(self): self.addPageTemplates(FrontCoverTemplate('Cover', self.pagesize)) self.addPageTemplates(TOCTemplate('TOC', self.pagesize)) self.addPageTemplates(OneColumnTemplate('Normal', self.pagesize)) self.addPageTemplates(TwoColumnTemplate('TwoColumn', self.pagesize)) self.seq = Sequencer() def beforeDocument(self): self.canv.showOutline() self.title = "(Document Title Goes Here)" self.chapter = "(No chapter yet)" self.seq.reset('section') self.seq.reset('chapter') def afterFlowable(self, flowable): """Detect Level 1 and 2 headings, build outline, and track chapter title.""" if isinstance(flowable, Paragraph): style = flowable.style.name txt = flowable.getPlainText() if style == 'Title': self.title = txt elif style == 'Heading1': self.chapter = txt key = 'ch%s' % self.seq.nextf('chapter') self.canv.bookmarkPage(key) self.canv.addOutlineEntry(txt, key, 0, 0) self.seq.reset("section") self.notify('TOCEntry', (0, txt, self.page, key)) elif style == 'Heading2': self.section = flowable.text key = 'ch%ss%s' % (self.seq.thisf("chapter"), self.seq.nextf("section")) self.canv.bookmarkPage(key) self.canv.addOutlineEntry(txt, key, 1, 0) self.notify('TOCEntry', (1, txt, self.page, key))
/reportlab-4.0.4.tar.gz/reportlab-4.0.4/tools/docco/rltemplate.py
0.400515
0.169784
rltemplate.py
pypi
__version__='3.3.0' # xml parser stuff for PythonPoint # PythonPoint Markup Language! __doc__=""" This demonstrates a custom shape for use with the <customshape> tag. The shape must fulfil a very simple interface, which may change in future. The XML tag currently has this form: <customshape module="customshapes.py" class = "MyShape" initargs="(100,200,3)" /> PythonPoint will look in the given module for the given class, evaluate the arguments string and pass it to the constructor. Then, it will call object.drawOn(canvas) Thus your object must be fully defined by the constructor. For this one, we pass three argumenyts: x, y and scale. This does a five-tile jigsaw over which words can be overlaid; based on work done for a customer's presentation. """ import reportlab.pdfgen.canvas from reportlab.lib import colors from reportlab.lib.corp import RL_CorpLogo from reportlab.graphics.shapes import Drawing ## custom shape for use with PythonPoint. class Jigsaw: """This draws a jigsaw patterm. By default it is centred on 0,0 and has dimensions of 200 x 140; use the x/y/scale attributes to move it around.""" #Using my usual bulldozer coding style - I am sure a mathematician could #derive an elegant way to draw this, but I just took a ruler, guessed at #the control points, and reflected a few lists at the interactive prompt. def __init__(self, x, y, scale=1): self.width = 200 self.height = 140 self.x = x self.y = y self.scale = scale def drawOn(self, canvas): canvas.saveState() canvas.setFont('Helvetica-Bold',24) canvas.drawString(600, 100, 'A Custom Shape') canvas.translate(self.x, self.y) canvas.scale(self.scale, self.scale) self.drawBounds(canvas) self.drawCentre(canvas) self.drawTopLeft(canvas) self.drawBottomLeft(canvas) self.drawBottomRight(canvas) self.drawTopRight(canvas) canvas.restoreState() def curveThrough(self, path, pointlist): """Helper to curve through set of control points.""" assert len(pointlist) % 3 == 1, "No. of points must be 3n+1 for integer n" (x,y) = pointlist[0] path.moveTo(x, y) idx = 1 while idx < len(pointlist)-2: p1, p2, p3 = pointlist[idx:idx+3] path.curveTo(p1[0], p1[1], p2[0], p2[1], p3[0], p3[1]) idx = idx + 3 def drawShape(self, canvas, controls, color): """Utlity to draw a closed shape through a list of control points; extends the previous proc""" canvas.setFillColor(color) p = canvas.beginPath() self.curveThrough(p, controls) p.close() canvas.drawPath(p, stroke=1, fill=1) def drawBounds(self, canvas): """Guidelines to help me draw - not needed in production""" canvas.setStrokeColor(colors.red) canvas.rect(-100,-70,200,140) canvas.line(-100,0,100,0) canvas.line(0,70,0,-70) canvas.setStrokeColor(colors.black) def drawCentre(self, canvas): controls = [ (0,50), #top #top right edge - duplicated for that corner piece (5,50),(10,45),(10,40), (10,35),(15,30),(20,30), (25,30),(30,25),(30,20), (30,15),(35,10),(40,10), (45,10),(50,5),(50,0), #bottom right edge (50, -5), (45,-10), (40,-10), (35,-10), (30,-15), (30, -20), (30,-25), (25,-30), (20,-30), (15,-30), (10,-35), (10,-40), (10,-45),(5,-50),(0,-50), #bottom left (-5,-50),(-10,-45),(-10,-40), (-10,-35),(-15,-30),(-20,-30), (-25,-30),(-30,-25),(-30,-20), (-30,-15),(-35,-10),(-40,-10), (-45,-10),(-50,-5),(-50,0), #top left (-50,5),(-45,10),(-40,10), (-35,10),(-30,15),(-30,20), (-30,25),(-25,30),(-20,30), (-15,30),(-10,35),(-10,40), (-10,45),(-5,50),(0,50) ] self.drawShape(canvas, controls, colors.yellow) def drawTopLeft(self, canvas): controls = [(-100,70), (-100,69),(-100,1),(-100,0), (-99,0),(-91,0),(-90,0), #jigsaw interlock - 4 sections (-90,5),(-92,5),(-92,10), (-92,15), (-85,15), (-80,15), (-75,15),(-68,15),(-68,10), (-68,5),(-70,5),(-70,0), (-69,0),(-51,0),(-50,0), #five distinct curves (-50,5),(-45,10),(-40,10), (-35,10),(-30,15),(-30,20), (-30,25),(-25,30),(-20,30), (-15,30),(-10,35),(-10,40), (-10,45),(-5,50),(0,50), (0,51),(0,69),(0,70), (-1,70),(-99,70),(-100,70) ] self.drawShape(canvas, controls, colors.teal) def drawBottomLeft(self, canvas): controls = [(-100,-70), (-99,-70),(-1,-70),(0,-70), (0,-69),(0,-51),(0,-50), #wavyline (-5,-50),(-10,-45),(-10,-40), (-10,-35),(-15,-30),(-20,-30), (-25,-30),(-30,-25),(-30,-20), (-30,-15),(-35,-10),(-40,-10), (-45,-10),(-50,-5),(-50,0), #jigsaw interlock - 4 sections (-51, 0), (-69, 0), (-70, 0), (-70, 5), (-68, 5), (-68, 10), (-68, 15), (-75, 15), (-80, 15), (-85, 15), (-92, 15), (-92, 10), (-92, 5), (-90, 5), (-90, 0), (-91,0),(-99,0),(-100,0) ] self.drawShape(canvas, controls, colors.green) def drawBottomRight(self, canvas): controls = [ (100,-70), (100,-69),(100,-1),(100,0), (99,0),(91,0),(90,0), #jigsaw interlock - 4 sections (90, -5), (92, -5), (92, -10), (92, -15), (85, -15), (80, -15), (75, -15), (68, -15), (68, -10), (68, -5), (70, -5), (70, 0), (69, 0), (51, 0), (50, 0), #wavyline (50, -5), (45,-10), (40,-10), (35,-10), (30,-15), (30, -20), (30,-25), (25,-30), (20,-30), (15,-30), (10,-35), (10,-40), (10,-45),(5,-50),(0,-50), (0,-51), (0,-69), (0,-70), (1,-70),(99,-70),(100,-70) ] self.drawShape(canvas, controls, colors.navy) def drawBottomLeft(self, canvas): controls = [(-100,-70), (-99,-70),(-1,-70),(0,-70), (0,-69),(0,-51),(0,-50), #wavyline (-5,-50),(-10,-45),(-10,-40), (-10,-35),(-15,-30),(-20,-30), (-25,-30),(-30,-25),(-30,-20), (-30,-15),(-35,-10),(-40,-10), (-45,-10),(-50,-5),(-50,0), #jigsaw interlock - 4 sections (-51, 0), (-69, 0), (-70, 0), (-70, 5), (-68, 5), (-68, 10), (-68, 15), (-75, 15), (-80, 15), (-85, 15), (-92, 15), (-92, 10), (-92, 5), (-90, 5), (-90, 0), (-91,0),(-99,0),(-100,0) ] self.drawShape(canvas, controls, colors.green) def drawTopRight(self, canvas): controls = [(100, 70), (99, 70), (1, 70), (0, 70), (0, 69), (0, 51), (0, 50), (5, 50), (10, 45), (10, 40), (10, 35), (15, 30), (20, 30), (25, 30), (30, 25), (30, 20), (30, 15), (35, 10), (40, 10), (45, 10), (50, 5), (50, 0), (51, 0), (69, 0), (70, 0), (70, -5), (68, -5), (68, -10), (68, -15), (75, -15), (80, -15), (85, -15), (92, -15), (92, -10), (92, -5), (90, -5), (90, 0), (91, 0), (99, 0), (100, 0) ] self.drawShape(canvas, controls, colors.magenta) class Logo: """This draws a ReportLab Logo.""" def __init__(self, x, y, width, height): logo = RL_CorpLogo() logo.x = x logo.y = y logo.width = width logo.height = height self.logo = logo def drawOn(self, canvas): logo = self.logo x, y = logo.x, logo.y w, h = logo.width, logo.height D = Drawing(w, h) D.add(logo) D.drawOn(canvas, 0, 0) def run(): c = reportlab.pdfgen.canvas.Canvas('customshape.pdf') J = Jigsaw(300, 540, 2) J.drawOn(c) c.save() if __name__ == '__main__': run()
/reportlab-4.0.4.tar.gz/reportlab-4.0.4/tools/pythonpoint/customshapes.py
0.705379
0.647603
customshapes.py
pypi
__version__='3.3.0' # style_modern.py __doc__="""This is an example style sheet. You can create your own, and have them loaded by the presentation. A style sheet is just a dictionary, where they keys are style names and the values are ParagraphStyle objects. You must provide a function called "getParagraphStyles()" to return it. In future, we can put things like LineStyles, TableCellStyles etc. in the same modules. You might wish to have two parallel style sheets, one for colour and one for black and white, so you can switch your presentations easily. A style sheet MUST define a style called 'Normal'. """ from reportlab.lib import styles, enums def getParagraphStyles(): """Returns a dictionary of styles based on Helvetica""" stylesheet = {} para = styles.ParagraphStyle('Normal', None) #the ancestor of all para.fontName = 'Courier' para.fontSize = 24 para.leading = 28 stylesheet['Normal'] = para para = ParagraphStyle('BodyText', stylesheet['Normal']) para.spaceBefore = 12 stylesheet['BodyText'] = para para = ParagraphStyle('BigCentered', stylesheet['Normal']) para.spaceBefore = 12 para.alignment = enums.TA_CENTER stylesheet['BigCentered'] = para para = ParagraphStyle('Italic', stylesheet['BodyText']) para.fontName = 'Courier-Oblique' stylesheet['Italic'] = para para = ParagraphStyle('Title', stylesheet['Normal']) para.fontName = 'Courier' para.fontSize = 48 para.Leading = 58 para.spaceAfter = 36 para.alignment = enums.TA_CENTER stylesheet['Title'] = para para = ParagraphStyle('Heading1', stylesheet['Normal']) para.fontName = 'Courier-Bold' para.fontSize = 36 para.leading = 44 para.spaceAfter = 36 para.alignment = enums.TA_CENTER stylesheet['Heading1'] = para para = ParagraphStyle('Heading2', stylesheet['Normal']) para.fontName = 'Courier-Bold' para.fontSize = 28 para.leading = 34 para.spaceBefore = 24 para.spaceAfter = 12 stylesheet['Heading2'] = para para = ParagraphStyle('Heading3', stylesheet['Normal']) para.fontName = 'Courier-BoldOblique' para.spaceBefore = 24 para.spaceAfter = 12 stylesheet['Heading3'] = para para = ParagraphStyle('Bullet', stylesheet['Normal']) para.firstLineIndent = -18 para.leftIndent = 72 para.spaceBefore = 6 #para.bulletFontName = 'Symbol' para.bulletFontSize = 24 para.bulletIndent = 36 stylesheet['Bullet'] = para para = ParagraphStyle('Definition', stylesheet['Normal']) #use this for definition lists para.firstLineIndent = 0 para.leftIndent = 72 para.bulletIndent = 0 para.spaceBefore = 12 para.bulletFontName = 'Couruer-BoldOblique' stylesheet['Definition'] = para para = ParagraphStyle('Code', stylesheet['Normal']) para.fontName = 'Courier' para.fontSize = 16 para.leading = 18 para.leftIndent = 36 stylesheet['Code'] = para return stylesheet
/reportlab-4.0.4.tar.gz/reportlab-4.0.4/tools/pythonpoint/styles/horrible.py
0.573201
0.451871
horrible.py
pypi
__version__='3.3.0' # style_modern.py __doc__="""This is an example style sheet. You can create your own, and have them loaded by the presentation. A style sheet is just a dictionary, where they keys are style names and the values are ParagraphStyle objects. You must provide a function called "getParagraphStyles()" to return it. In future, we can put things like LineStyles, TableCellStyles etc. in the same modules. You might wish to have two parallel style sheets, one for colour and one for black and white, so you can switch your presentations easily. A style sheet MUST define a style called 'Normal'. """ from reportlab.lib import styles from reportlab.lib.enums import TA_CENTER def getParagraphStyles(): """Returns a dictionary of styles based on Helvetica""" stylesheet = {} ParagraphStyle = styles.ParagraphStyle para = ParagraphStyle('Normal', None) #the ancestor of all para.fontName = 'Helvetica' para.fontSize = 24 para.leading = 28 stylesheet['Normal'] = para para = ParagraphStyle('BodyText', stylesheet['Normal']) para.spaceBefore = 12 stylesheet['BodyText'] = para para = ParagraphStyle('Indent', stylesheet['Normal']) para.leftIndent = 36 para.firstLineIndent = 0 stylesheet['Indent'] = para para = ParagraphStyle('Centered', stylesheet['Normal']) para.alignment = TA_CENTER stylesheet['Centered'] = para para = ParagraphStyle('BigCentered', stylesheet['Normal']) para.spaceBefore = 12 para.alignment = TA_CENTER stylesheet['BigCentered'] = para para = ParagraphStyle('Italic', stylesheet['BodyText']) para.fontName = 'Helvetica-Oblique' stylesheet['Italic'] = para para = ParagraphStyle('Title', stylesheet['Normal']) para.fontName = 'Helvetica' para.fontSize = 48 para.Leading = 58 para.spaceAfter = 36 para.alignment = TA_CENTER stylesheet['Title'] = para para = ParagraphStyle('Heading1', stylesheet['Normal']) para.fontName = 'Helvetica-Bold' para.fontSize = 36 para.leading = 44 para.spaceAfter = 36 para.alignment = TA_CENTER stylesheet['Heading1'] = para para = ParagraphStyle('Heading2', stylesheet['Normal']) para.fontName = 'Helvetica-Bold' para.fontSize = 28 para.leading = 34 para.spaceBefore = 24 para.spaceAfter = 12 stylesheet['Heading2'] = para para = ParagraphStyle('Heading3', stylesheet['Normal']) para.fontName = 'Helvetica-BoldOblique' para.spaceBefore = 24 para.spaceAfter = 12 stylesheet['Heading3'] = para para = ParagraphStyle('Bullet', stylesheet['Normal']) para.firstLineIndent = -18 para.leftIndent = 72 para.spaceBefore = 6 para.bulletFontName = 'Symbol' para.bulletFontSize = 24 para.bulletIndent = 36 stylesheet['Bullet'] = para para = ParagraphStyle('Bullet2', stylesheet['Bullet']) para.firstLineIndent = 0 para.bulletIndent = 72 para.leftIndent = 108 stylesheet['Bullet2'] = para para = ParagraphStyle('Definition', stylesheet['Normal']) #use this for definition lists para.firstLineIndent = 0 para.leftIndent = 72 para.bulletIndent = 0 para.spaceBefore = 12 para.bulletFontName = 'Helvetica-BoldOblique' stylesheet['Definition'] = para para = ParagraphStyle('Code', stylesheet['Normal']) para.fontName = 'Courier' para.fontSize = 16 para.leading = 18 para.leftIndent = 36 stylesheet['Code'] = para return stylesheet
/reportlab-4.0.4.tar.gz/reportlab-4.0.4/tools/pythonpoint/styles/modern.py
0.516595
0.427277
modern.py
pypi
__version__='3.3.0' __doc__=""" PDFPathObject is an efficient way to draw paths on a Canvas. Do not instantiate directly, obtain one from the Canvas instead. Progress Reports: 8.83, 2000-01-13, gmcm: created from pdfgen.py """ from reportlab.pdfgen import pdfgeom from reportlab.lib.rl_accel import fp_str class PDFPathObject: """Represents a graphic path. There are certain 'modes' to PDF drawing, and making a separate object to expose Path operations ensures they are completed with no run-time overhead. Ask the Canvas for a PDFPath with getNewPathObject(); moveto/lineto/ curveto wherever you want; add whole shapes; and then add it back into the canvas with one of the relevant operators. Path objects are probably not long, so we pack onto one line the code argument allows a canvas to get the operations appended directly so avoiding the final getCode """ def __init__(self,code=None): self._code = (code,[])[code is None] self._code_append = self._init_code_append def _init_code_append(self,c): assert c.endswith(' m') or c.endswith(' re'), 'path must start with a moveto or rect' code_append = self._code.append code_append('n') code_append(c) self._code_append = code_append def getCode(self): "pack onto one line; used internally" return ' '.join(self._code) def moveTo(self, x, y): self._code_append('%s m' % fp_str(x,y)) def lineTo(self, x, y): self._code_append('%s l' % fp_str(x,y)) def curveTo(self, x1, y1, x2, y2, x3, y3): self._code_append('%s c' % fp_str(x1, y1, x2, y2, x3, y3)) def arc(self, x1,y1, x2,y2, startAng=0, extent=90): """Contributed to piddlePDF by Robert Kern, 28/7/99. Draw a partial ellipse inscribed within the rectangle x1,y1,x2,y2, starting at startAng degrees and covering extent degrees. Angles start with 0 to the right (+x) and increase counter-clockwise. These should have x1<x2 and y1<y2. The algorithm is an elliptical generalization of the formulae in Jim Fitzsimmon's TeX tutorial <URL: http://www.tinaja.com/bezarc1.pdf>.""" self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent)) def arcTo(self, x1,y1, x2,y2, startAng=0, extent=90): """Like arc, but draws a line from the current point to the start if the start is not the current point.""" self._curves(pdfgeom.bezierArc(x1,y1, x2,y2, startAng, extent),'lineTo') def rect(self, x, y, width, height): """Adds a rectangle to the path""" self._code_append('%s re' % fp_str((x, y, width, height))) def ellipse(self, x, y, width, height): """adds an ellipse to the path""" self._curves(pdfgeom.bezierArc(x, y, x + width,y + height, 0, 360)) def _curves(self,curves,initial='moveTo'): getattr(self,initial)(*curves[0][:2]) for curve in curves: self.curveTo(*curve[2:]) def circle(self, x_cen, y_cen, r): """adds a circle to the path""" x1 = x_cen - r y1 = y_cen - r width = height = 2*r self.ellipse(x1, y1, width, height) def roundRect(self, x, y, width, height, radius): """Draws a rectangle with rounded corners. The corners are approximately quadrants of a circle, with the given radius.""" #use a precomputed set of factors for the bezier approximation #to a circle. There are six relevant points on the x axis and y axis. #sketch them and it should all make sense! m = 0.4472 #radius multiplier xhi = x,x+width xlo, xhi = min(xhi), max(xhi) yhi = y,y+height ylo, yhi = min(yhi), max(yhi) if isinstance(radius,(list,tuple)): r = [max(0,r) for r in radius] if len(r)<4: r += (4-len(r))*[0] self.moveTo(xlo + r[2], ylo) #start at bottom left self.lineTo(xhi - r[3], ylo) #bottom row if r[3]>0: t = m*r[3] self.curveTo(xhi - t, ylo, xhi, ylo + t, xhi, ylo + r[3]) #bottom right self.lineTo(xhi, yhi - r[1]) #right edge if r[1]>0: t = m*r[1] self.curveTo(xhi, yhi - t, xhi - t, yhi, xhi - r[1], yhi) #top right self.lineTo(xlo + r[0], yhi) #top row if r[0]>0: t = m*r[0] self.curveTo(xlo + t, yhi, xlo, yhi - t, xlo, yhi - r[0]) #top left self.lineTo(xlo, ylo + r[2]) #left edge if r[2]>0: t = m*r[2] self.curveTo(xlo, ylo + t, xlo + t, ylo, xlo + r[2], ylo) #bottom left # 4 radii top left top right bittom left bottom right else: t = m * radius self.moveTo(xlo + radius, ylo) self.lineTo(xhi - radius, ylo) #bottom row self.curveTo(xhi - t, ylo, xhi, ylo + t, xhi, ylo + radius) #bottom right self.lineTo(xhi, yhi - radius) #right edge self.curveTo(xhi, yhi - t, xhi - t, yhi, xhi - radius, yhi) #top right self.lineTo(xlo + radius, yhi) #top row self.curveTo(xlo + t, yhi, xlo, yhi - t, xlo, yhi - radius) #top left self.lineTo(xlo, ylo + radius) #left edge self.curveTo(xlo, ylo + t, xlo + t, ylo, xlo + radius, ylo) #bottom left self.close() def close(self): "draws a line back to where it started" self._code_append('h')
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/pdfgen/pathobject.py
0.817611
0.594963
pathobject.py
pypi
__version__='3.3.0' __doc__=""" This module includes any mathematical methods needed for PIDDLE. It should have no dependencies beyond the Python library. So far, just Robert Kern's bezierArc. """ from math import sin, cos, pi, ceil def bezierArc(x1,y1, x2,y2, startAng=0, extent=90): """bezierArc(x1,y1, x2,y2, startAng=0, extent=90) --> List of Bezier curve control points. (x1, y1) and (x2, y2) are the corners of the enclosing rectangle. The coordinate system has coordinates that increase to the right and down. Angles, measured in degress, start with 0 to the right (the positive X axis) and increase counter-clockwise. The arc extends from startAng to startAng+extent. I.e. startAng=0 and extent=180 yields an openside-down semi-circle. The resulting coordinates are of the form (x1,y1, x2,y2, x3,y3, x4,y4) such that the curve goes from (x1, y1) to (x4, y4) with (x2, y2) and (x3, y3) as their respective Bezier control points.""" x1,y1, x2,y2 = min(x1,x2), max(y1,y2), max(x1,x2), min(y1,y2) if abs(extent) <= 90: arcList = [startAng] fragAngle = float(extent) Nfrag = 1 else: arcList = [] Nfrag = int(ceil(abs(extent)/90.)) fragAngle = float(extent) / Nfrag x_cen = (x1+x2)/2. y_cen = (y1+y2)/2. rx = (x2-x1)/2. ry = (y2-y1)/2. halfAng = fragAngle * pi / 360. kappa = abs(4. / 3. * (1. - cos(halfAng)) / sin(halfAng)) if fragAngle < 0: sign = -1 else: sign = 1 pointList = [] for i in range(Nfrag): theta0 = (startAng + i*fragAngle) * pi / 180. theta1 = (startAng + (i+1)*fragAngle) *pi / 180. if fragAngle > 0: pointList.append((x_cen + rx * cos(theta0), y_cen - ry * sin(theta0), x_cen + rx * (cos(theta0) - kappa * sin(theta0)), y_cen - ry * (sin(theta0) + kappa * cos(theta0)), x_cen + rx * (cos(theta1) + kappa * sin(theta1)), y_cen - ry * (sin(theta1) - kappa * cos(theta1)), x_cen + rx * cos(theta1), y_cen - ry * sin(theta1))) else: pointList.append((x_cen + rx * cos(theta0), y_cen - ry * sin(theta0), x_cen + rx * (cos(theta0) + kappa * sin(theta0)), y_cen - ry * (sin(theta0) - kappa * cos(theta0)), x_cen + rx * (cos(theta1) - kappa * sin(theta1)), y_cen - ry * (sin(theta1) + kappa * cos(theta1)), x_cen + rx * cos(theta1), y_cen - ry * sin(theta1))) return pointList
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/pdfgen/pdfgeom.py
0.863765
0.635534
pdfgeom.py
pypi
widths = {'A': 722, 'AE': 1000, 'Aacute': 722, 'Acircumflex': 722, 'Adieresis': 722, 'Agrave': 722, 'Aring': 722, 'Atilde': 722, 'B': 722, 'C': 722, 'Ccedilla': 722, 'D': 722, 'E': 667, 'Eacute': 667, 'Ecircumflex': 667, 'Edieresis': 667, 'Egrave': 667, 'Eth': 722, 'Euro': 556, 'F': 611, 'G': 778, 'H': 722, 'I': 278, 'Iacute': 278, 'Icircumflex': 278, 'Idieresis': 278, 'Igrave': 278, 'J': 556, 'K': 722, 'L': 611, 'Lslash': 611, 'M': 833, 'N': 722, 'Ntilde': 722, 'O': 778, 'OE': 1000, 'Oacute': 778, 'Ocircumflex': 778, 'Odieresis': 778, 'Ograve': 778, 'Oslash': 778, 'Otilde': 778, 'P': 667, 'Q': 778, 'R': 722, 'S': 667, 'Scaron': 667, 'T': 611, 'Thorn': 667, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 667, 'W': 944, 'X': 667, 'Y': 667, 'Yacute': 667, 'Ydieresis': 667, 'Z': 611, 'Zcaron': 611, 'a': 556, 'aacute': 556, 'acircumflex': 556, 'acute': 333, 'adieresis': 556, 'ae': 889, 'agrave': 556, 'ampersand': 722, 'aring': 556, 'asciicircum': 584, 'asciitilde': 584, 'asterisk': 389, 'at': 975, 'atilde': 556, 'b': 611, 'backslash': 278, 'bar': 280, 'braceleft': 389, 'braceright': 389, 'bracketleft': 333, 'bracketright': 333, 'breve': 333, 'brokenbar': 280, 'bullet': 350, 'c': 556, 'caron': 333, 'ccedilla': 556, 'cedilla': 333, 'cent': 556, 'circumflex': 333, 'colon': 333, 'comma': 278, 'copyright': 737, 'currency': 556, 'd': 611, 'dagger': 556, 'daggerdbl': 556, 'degree': 400, 'dieresis': 333, 'divide': 584, 'dollar': 556, 'dotaccent': 333, 'dotlessi': 278, 'e': 556, 'eacute': 556, 'ecircumflex': 556, 'edieresis': 556, 'egrave': 556, 'eight': 556, 'ellipsis': 1000, 'emdash': 1000, 'endash': 556, 'equal': 584, 'eth': 611, 'exclam': 333, 'exclamdown': 333, 'f': 333, 'fi': 611, 'five': 556, 'fl': 611, 'florin': 556, 'four': 556, 'fraction': 167, 'g': 611, 'germandbls': 611, 'grave': 333, 'greater': 584, 'guillemotleft': 556, 'guillemotright': 556, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 611, 'hungarumlaut': 333, 'hyphen': 333, 'i': 278, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 278, 'k': 556, 'l': 278, 'less': 584, 'logicalnot': 584, 'lslash': 278, 'm': 889, 'macron': 333, 'minus': 584, 'mu': 611, 'multiply': 584, 'n': 611, 'nine': 556, 'ntilde': 611, 'numbersign': 556, 'o': 611, 'oacute': 611, 'ocircumflex': 611, 'odieresis': 611, 'oe': 944, 'ogonek': 333, 'ograve': 611, 'one': 556, 'onehalf': 834, 'onequarter': 834, 'onesuperior': 333, 'ordfeminine': 370, 'ordmasculine': 365, 'oslash': 611, 'otilde': 611, 'p': 611, 'paragraph': 556, 'parenleft': 333, 'parenright': 333, 'percent': 889, 'period': 278, 'periodcentered': 278, 'perthousand': 1000, 'plus': 584, 'plusminus': 584, 'q': 611, 'question': 611, 'questiondown': 611, 'quotedbl': 474, 'quotedblbase': 500, 'quotedblleft': 500, 'quotedblright': 500, 'quoteleft': 278, 'quoteright': 278, 'quotesinglbase': 278, 'quotesingle': 238, 'r': 389, 'registered': 737, 'ring': 333, 's': 556, 'scaron': 556, 'section': 556, 'semicolon': 333, 'seven': 556, 'six': 556, 'slash': 278, 'space': 278, 'sterling': 556, 't': 333, 'thorn': 611, 'three': 556, 'threequarters': 834, 'threesuperior': 333, 'tilde': 333, 'trademark': 1000, 'two': 556, 'twosuperior': 333, 'u': 611, 'uacute': 611, 'ucircumflex': 611, 'udieresis': 611, 'ugrave': 611, 'underscore': 556, 'v': 556, 'w': 778, 'x': 556, 'y': 556, 'yacute': 556, 'ydieresis': 556, 'yen': 556, 'z': 500, 'zcaron': 500, 'zero': 556}
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/pdfbase/_fontdata_widths_helveticaboldoblique.py
0.563858
0.221035
_fontdata_widths_helveticaboldoblique.py
pypi
SymbolEncoding = ( None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, 'space', 'exclam', 'universal', 'numbersign', 'existential', 'percent', 'ampersand', 'suchthat', 'parenleft', 'parenright', 'asteriskmath', 'plus', 'comma', 'minus', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'congruent', 'Alpha', 'Beta', 'Chi', 'Delta', 'Epsilon', 'Phi', 'Gamma', 'Eta', 'Iota', 'theta1', 'Kappa', 'Lambda', 'Mu', 'Nu', 'Omicron', 'Pi', 'Theta', 'Rho', 'Sigma', 'Tau', 'Upsilon', 'sigma1', 'Omega', 'Xi', 'Psi', 'Zeta', 'bracketleft', 'therefore', 'bracketright', 'perpendicular', 'underscore', 'radicalex', 'alpha', 'beta', 'chi', 'delta', 'epsilon', 'phi', 'gamma', 'eta', 'iota', 'phi1', 'kappa', 'lambda', 'mu', 'nu', 'omicron', 'pi', 'theta', 'rho', 'sigma', 'tau', 'upsilon', 'omega1', 'omega', 'xi', 'psi', 'zeta', 'braceleft', 'bar', 'braceright', 'similar', None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, 'Euro', 'Upsilon1', 'minute', 'lessequal', 'fraction', 'infinity', 'florin', 'club', 'diamond', 'heart', 'spade', 'arrowboth', 'arrowleft', 'arrowup', 'arrowright', 'arrowdown', 'degree', 'plusminus', 'second', 'greaterequal', 'multiply', 'proportional', 'partialdiff', 'bullet', 'divide', 'notequal', 'equivalence', 'approxequal', 'ellipsis', 'arrowvertex', 'arrowhorizex', 'carriagereturn', 'aleph', 'Ifraktur', 'Rfraktur', 'weierstrass', 'circlemultiply', 'circleplus', 'emptyset', 'intersection', 'union', 'propersuperset', 'reflexsuperset', 'notsubset', 'propersubset', 'reflexsubset', 'element', 'notelement', 'angle', 'gradient', 'registerserif', 'copyrightserif', 'trademarkserif', 'product', 'radical', 'dotmath', 'logicalnot', 'logicaland', 'logicalor', 'arrowdblboth', 'arrowdblleft', 'arrowdblup', 'arrowdblright', 'arrowdbldown', 'lozenge', 'angleleft', 'registersans', 'copyrightsans', 'trademarksans', 'summation', 'parenlefttp', 'parenleftex', 'parenleftbt', 'bracketlefttp', 'bracketleftex', 'bracketleftbt', 'bracelefttp', 'braceleftmid', 'braceleftbt', 'braceex', None, 'angleright', 'integral', 'integraltp', 'integralex', 'integralbt', 'parenrighttp', 'parenrightex', 'parenrightbt', 'bracketrighttp', 'bracketrightex', 'bracketrightbt', 'bracerighttp', 'bracerightmid', 'bracerightbt', None)
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/pdfbase/_fontdata_enc_symbol.py
0.621311
0.246998
_fontdata_enc_symbol.py
pypi
widths = {'A': 600, 'AE': 600, 'Aacute': 600, 'Acircumflex': 600, 'Adieresis': 600, 'Agrave': 600, 'Aring': 600, 'Atilde': 600, 'B': 600, 'C': 600, 'Ccedilla': 600, 'D': 600, 'E': 600, 'Eacute': 600, 'Ecircumflex': 600, 'Edieresis': 600, 'Egrave': 600, 'Eth': 600, 'Euro': 600, 'F': 600, 'G': 600, 'H': 600, 'I': 600, 'Iacute': 600, 'Icircumflex': 600, 'Idieresis': 600, 'Igrave': 600, 'J': 600, 'K': 600, 'L': 600, 'Lslash': 600, 'M': 600, 'N': 600, 'Ntilde': 600, 'O': 600, 'OE': 600, 'Oacute': 600, 'Ocircumflex': 600, 'Odieresis': 600, 'Ograve': 600, 'Oslash': 600, 'Otilde': 600, 'P': 600, 'Q': 600, 'R': 600, 'S': 600, 'Scaron': 600, 'T': 600, 'Thorn': 600, 'U': 600, 'Uacute': 600, 'Ucircumflex': 600, 'Udieresis': 600, 'Ugrave': 600, 'V': 600, 'W': 600, 'X': 600, 'Y': 600, 'Yacute': 600, 'Ydieresis': 600, 'Z': 600, 'Zcaron': 600, 'a': 600, 'aacute': 600, 'acircumflex': 600, 'acute': 600, 'adieresis': 600, 'ae': 600, 'agrave': 600, 'ampersand': 600, 'aring': 600, 'asciicircum': 600, 'asciitilde': 600, 'asterisk': 600, 'at': 600, 'atilde': 600, 'b': 600, 'backslash': 600, 'bar': 600, 'braceleft': 600, 'braceright': 600, 'bracketleft': 600, 'bracketright': 600, 'breve': 600, 'brokenbar': 600, 'bullet': 600, 'c': 600, 'caron': 600, 'ccedilla': 600, 'cedilla': 600, 'cent': 600, 'circumflex': 600, 'colon': 600, 'comma': 600, 'copyright': 600, 'currency': 600, 'd': 600, 'dagger': 600, 'daggerdbl': 600, 'degree': 600, 'dieresis': 600, 'divide': 600, 'dollar': 600, 'dotaccent': 600, 'dotlessi': 600, 'e': 600, 'eacute': 600, 'ecircumflex': 600, 'edieresis': 600, 'egrave': 600, 'eight': 600, 'ellipsis': 600, 'emdash': 600, 'endash': 600, 'equal': 600, 'eth': 600, 'exclam': 600, 'exclamdown': 600, 'f': 600, 'fi': 600, 'five': 600, 'fl': 600, 'florin': 600, 'four': 600, 'fraction': 600, 'g': 600, 'germandbls': 600, 'grave': 600, 'greater': 600, 'guillemotleft': 600, 'guillemotright': 600, 'guilsinglleft': 600, 'guilsinglright': 600, 'h': 600, 'hungarumlaut': 600, 'hyphen': 600, 'i': 600, 'iacute': 600, 'icircumflex': 600, 'idieresis': 600, 'igrave': 600, 'j': 600, 'k': 600, 'l': 600, 'less': 600, 'logicalnot': 600, 'lslash': 600, 'm': 600, 'macron': 600, 'minus': 600, 'mu': 600, 'multiply': 600, 'n': 600, 'nine': 600, 'ntilde': 600, 'numbersign': 600, 'o': 600, 'oacute': 600, 'ocircumflex': 600, 'odieresis': 600, 'oe': 600, 'ogonek': 600, 'ograve': 600, 'one': 600, 'onehalf': 600, 'onequarter': 600, 'onesuperior': 600, 'ordfeminine': 600, 'ordmasculine': 600, 'oslash': 600, 'otilde': 600, 'p': 600, 'paragraph': 600, 'parenleft': 600, 'parenright': 600, 'percent': 600, 'period': 600, 'periodcentered': 600, 'perthousand': 600, 'plus': 600, 'plusminus': 600, 'q': 600, 'question': 600, 'questiondown': 600, 'quotedbl': 600, 'quotedblbase': 600, 'quotedblleft': 600, 'quotedblright': 600, 'quoteleft': 600, 'quoteright': 600, 'quotesinglbase': 600, 'quotesingle': 600, 'r': 600, 'registered': 600, 'ring': 600, 's': 600, 'scaron': 600, 'section': 600, 'semicolon': 600, 'seven': 600, 'six': 600, 'slash': 600, 'space': 600, 'sterling': 600, 't': 600, 'thorn': 600, 'three': 600, 'threequarters': 600, 'threesuperior': 600, 'tilde': 600, 'trademark': 600, 'two': 600, 'twosuperior': 600, 'u': 600, 'uacute': 600, 'ucircumflex': 600, 'udieresis': 600, 'ugrave': 600, 'underscore': 600, 'v': 600, 'w': 600, 'x': 600, 'y': 600, 'yacute': 600, 'ydieresis': 600, 'yen': 600, 'z': 600, 'zcaron': 600, 'zero': 600}
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/pdfbase/_fontdata_widths_courieroblique.py
0.620277
0.171338
_fontdata_widths_courieroblique.py
pypi
widths = {'A': 600, 'AE': 600, 'Aacute': 600, 'Acircumflex': 600, 'Adieresis': 600, 'Agrave': 600, 'Aring': 600, 'Atilde': 600, 'B': 600, 'C': 600, 'Ccedilla': 600, 'D': 600, 'E': 600, 'Eacute': 600, 'Ecircumflex': 600, 'Edieresis': 600, 'Egrave': 600, 'Eth': 600, 'Euro': 600, 'F': 600, 'G': 600, 'H': 600, 'I': 600, 'Iacute': 600, 'Icircumflex': 600, 'Idieresis': 600, 'Igrave': 600, 'J': 600, 'K': 600, 'L': 600, 'Lslash': 600, 'M': 600, 'N': 600, 'Ntilde': 600, 'O': 600, 'OE': 600, 'Oacute': 600, 'Ocircumflex': 600, 'Odieresis': 600, 'Ograve': 600, 'Oslash': 600, 'Otilde': 600, 'P': 600, 'Q': 600, 'R': 600, 'S': 600, 'Scaron': 600, 'T': 600, 'Thorn': 600, 'U': 600, 'Uacute': 600, 'Ucircumflex': 600, 'Udieresis': 600, 'Ugrave': 600, 'V': 600, 'W': 600, 'X': 600, 'Y': 600, 'Yacute': 600, 'Ydieresis': 600, 'Z': 600, 'Zcaron': 600, 'a': 600, 'aacute': 600, 'acircumflex': 600, 'acute': 600, 'adieresis': 600, 'ae': 600, 'agrave': 600, 'ampersand': 600, 'aring': 600, 'asciicircum': 600, 'asciitilde': 600, 'asterisk': 600, 'at': 600, 'atilde': 600, 'b': 600, 'backslash': 600, 'bar': 600, 'braceleft': 600, 'braceright': 600, 'bracketleft': 600, 'bracketright': 600, 'breve': 600, 'brokenbar': 600, 'bullet': 600, 'c': 600, 'caron': 600, 'ccedilla': 600, 'cedilla': 600, 'cent': 600, 'circumflex': 600, 'colon': 600, 'comma': 600, 'copyright': 600, 'currency': 600, 'd': 600, 'dagger': 600, 'daggerdbl': 600, 'degree': 600, 'dieresis': 600, 'divide': 600, 'dollar': 600, 'dotaccent': 600, 'dotlessi': 600, 'e': 600, 'eacute': 600, 'ecircumflex': 600, 'edieresis': 600, 'egrave': 600, 'eight': 600, 'ellipsis': 600, 'emdash': 600, 'endash': 600, 'equal': 600, 'eth': 600, 'exclam': 600, 'exclamdown': 600, 'f': 600, 'fi': 600, 'five': 600, 'fl': 600, 'florin': 600, 'four': 600, 'fraction': 600, 'g': 600, 'germandbls': 600, 'grave': 600, 'greater': 600, 'guillemotleft': 600, 'guillemotright': 600, 'guilsinglleft': 600, 'guilsinglright': 600, 'h': 600, 'hungarumlaut': 600, 'hyphen': 600, 'i': 600, 'iacute': 600, 'icircumflex': 600, 'idieresis': 600, 'igrave': 600, 'j': 600, 'k': 600, 'l': 600, 'less': 600, 'logicalnot': 600, 'lslash': 600, 'm': 600, 'macron': 600, 'minus': 600, 'mu': 600, 'multiply': 600, 'n': 600, 'nine': 600, 'ntilde': 600, 'numbersign': 600, 'o': 600, 'oacute': 600, 'ocircumflex': 600, 'odieresis': 600, 'oe': 600, 'ogonek': 600, 'ograve': 600, 'one': 600, 'onehalf': 600, 'onequarter': 600, 'onesuperior': 600, 'ordfeminine': 600, 'ordmasculine': 600, 'oslash': 600, 'otilde': 600, 'p': 600, 'paragraph': 600, 'parenleft': 600, 'parenright': 600, 'percent': 600, 'period': 600, 'periodcentered': 600, 'perthousand': 600, 'plus': 600, 'plusminus': 600, 'q': 600, 'question': 600, 'questiondown': 600, 'quotedbl': 600, 'quotedblbase': 600, 'quotedblleft': 600, 'quotedblright': 600, 'quoteleft': 600, 'quoteright': 600, 'quotesinglbase': 600, 'quotesingle': 600, 'r': 600, 'registered': 600, 'ring': 600, 's': 600, 'scaron': 600, 'section': 600, 'semicolon': 600, 'seven': 600, 'six': 600, 'slash': 600, 'space': 600, 'sterling': 600, 't': 600, 'thorn': 600, 'three': 600, 'threequarters': 600, 'threesuperior': 600, 'tilde': 600, 'trademark': 600, 'two': 600, 'twosuperior': 600, 'u': 600, 'uacute': 600, 'ucircumflex': 600, 'udieresis': 600, 'ugrave': 600, 'underscore': 600, 'v': 600, 'w': 600, 'x': 600, 'y': 600, 'yacute': 600, 'ydieresis': 600, 'yen': 600, 'z': 600, 'zcaron': 600, 'zero': 600}
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/pdfbase/_fontdata_widths_courierbold.py
0.620277
0.171338
_fontdata_widths_courierbold.py
pypi
widths = {'A': 600, 'AE': 600, 'Aacute': 600, 'Acircumflex': 600, 'Adieresis': 600, 'Agrave': 600, 'Aring': 600, 'Atilde': 600, 'B': 600, 'C': 600, 'Ccedilla': 600, 'D': 600, 'E': 600, 'Eacute': 600, 'Ecircumflex': 600, 'Edieresis': 600, 'Egrave': 600, 'Eth': 600, 'Euro': 600, 'F': 600, 'G': 600, 'H': 600, 'I': 600, 'Iacute': 600, 'Icircumflex': 600, 'Idieresis': 600, 'Igrave': 600, 'J': 600, 'K': 600, 'L': 600, 'Lslash': 600, 'M': 600, 'N': 600, 'Ntilde': 600, 'O': 600, 'OE': 600, 'Oacute': 600, 'Ocircumflex': 600, 'Odieresis': 600, 'Ograve': 600, 'Oslash': 600, 'Otilde': 600, 'P': 600, 'Q': 600, 'R': 600, 'S': 600, 'Scaron': 600, 'T': 600, 'Thorn': 600, 'U': 600, 'Uacute': 600, 'Ucircumflex': 600, 'Udieresis': 600, 'Ugrave': 600, 'V': 600, 'W': 600, 'X': 600, 'Y': 600, 'Yacute': 600, 'Ydieresis': 600, 'Z': 600, 'Zcaron': 600, 'a': 600, 'aacute': 600, 'acircumflex': 600, 'acute': 600, 'adieresis': 600, 'ae': 600, 'agrave': 600, 'ampersand': 600, 'aring': 600, 'asciicircum': 600, 'asciitilde': 600, 'asterisk': 600, 'at': 600, 'atilde': 600, 'b': 600, 'backslash': 600, 'bar': 600, 'braceleft': 600, 'braceright': 600, 'bracketleft': 600, 'bracketright': 600, 'breve': 600, 'brokenbar': 600, 'bullet': 600, 'c': 600, 'caron': 600, 'ccedilla': 600, 'cedilla': 600, 'cent': 600, 'circumflex': 600, 'colon': 600, 'comma': 600, 'copyright': 600, 'currency': 600, 'd': 600, 'dagger': 600, 'daggerdbl': 600, 'degree': 600, 'dieresis': 600, 'divide': 600, 'dollar': 600, 'dotaccent': 600, 'dotlessi': 600, 'e': 600, 'eacute': 600, 'ecircumflex': 600, 'edieresis': 600, 'egrave': 600, 'eight': 600, 'ellipsis': 600, 'emdash': 600, 'endash': 600, 'equal': 600, 'eth': 600, 'exclam': 600, 'exclamdown': 600, 'f': 600, 'fi': 600, 'five': 600, 'fl': 600, 'florin': 600, 'four': 600, 'fraction': 600, 'g': 600, 'germandbls': 600, 'grave': 600, 'greater': 600, 'guillemotleft': 600, 'guillemotright': 600, 'guilsinglleft': 600, 'guilsinglright': 600, 'h': 600, 'hungarumlaut': 600, 'hyphen': 600, 'i': 600, 'iacute': 600, 'icircumflex': 600, 'idieresis': 600, 'igrave': 600, 'j': 600, 'k': 600, 'l': 600, 'less': 600, 'logicalnot': 600, 'lslash': 600, 'm': 600, 'macron': 600, 'minus': 600, 'mu': 600, 'multiply': 600, 'n': 600, 'nine': 600, 'ntilde': 600, 'numbersign': 600, 'o': 600, 'oacute': 600, 'ocircumflex': 600, 'odieresis': 600, 'oe': 600, 'ogonek': 600, 'ograve': 600, 'one': 600, 'onehalf': 600, 'onequarter': 600, 'onesuperior': 600, 'ordfeminine': 600, 'ordmasculine': 600, 'oslash': 600, 'otilde': 600, 'p': 600, 'paragraph': 600, 'parenleft': 600, 'parenright': 600, 'percent': 600, 'period': 600, 'periodcentered': 600, 'perthousand': 600, 'plus': 600, 'plusminus': 600, 'q': 600, 'question': 600, 'questiondown': 600, 'quotedbl': 600, 'quotedblbase': 600, 'quotedblleft': 600, 'quotedblright': 600, 'quoteleft': 600, 'quoteright': 600, 'quotesinglbase': 600, 'quotesingle': 600, 'r': 600, 'registered': 600, 'ring': 600, 's': 600, 'scaron': 600, 'section': 600, 'semicolon': 600, 'seven': 600, 'six': 600, 'slash': 600, 'space': 600, 'sterling': 600, 't': 600, 'thorn': 600, 'three': 600, 'threequarters': 600, 'threesuperior': 600, 'tilde': 600, 'trademark': 600, 'two': 600, 'twosuperior': 600, 'u': 600, 'uacute': 600, 'ucircumflex': 600, 'udieresis': 600, 'ugrave': 600, 'underscore': 600, 'v': 600, 'w': 600, 'x': 600, 'y': 600, 'yacute': 600, 'ydieresis': 600, 'yen': 600, 'z': 600, 'zcaron': 600, 'zero': 600}
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/pdfbase/_fontdata_widths_courier.py
0.620277
0.171338
_fontdata_widths_courier.py
pypi
from reportlab.pdfbase.pdfdoc import PDFString, PDFStream, PDFDictionary, PDFName, PDFObject from reportlab.lib.colors import obj_R_G_B #==========================public interfaces def textFieldAbsolute(canvas, title, x, y, width, height, value="", maxlen=1000000, multiline=0): """Place a text field on the current page with name title at ABSOLUTE position (x,y) with dimensions (width, height), using value as the default value and maxlen as the maximum permissible length. If multiline is set make it a multiline field. """ theform = getForm(canvas) return theform.textField(canvas, title, x, y, x+width, y+height, value, maxlen, multiline) def textFieldRelative(canvas, title, xR, yR, width, height, value="", maxlen=1000000, multiline=0): "same as textFieldAbsolute except the x and y are relative to the canvas coordinate transform" (xA, yA) = canvas.absolutePosition(xR,yR) return textFieldAbsolute(canvas, title, xA, yA, width, height, value, maxlen, multiline) def buttonFieldAbsolute(canvas, title, value, x, y, width=16.7704, height=14.907): """Place a check button field on the current page with name title and default value value (one of "Yes" or "Off") at ABSOLUTE position (x,y). """ theform = getForm(canvas) return theform.buttonField(canvas, title, value, x, y, width=width, height=height) def buttonFieldRelative(canvas, title, value, xR, yR, width=16.7704, height=14.907): "same as buttonFieldAbsolute except the x and y are relative to the canvas coordinate transform" (xA, yA) = canvas.absolutePosition(xR,yR) return buttonFieldAbsolute(canvas, title, value, xA, yA, width=width, height=height) def selectFieldAbsolute(canvas, title, value, options, x, y, width, height): """Place a select field (drop down list) on the current page with name title and with options listed in the sequence options default value value (must be one of options) at ABSOLUTE position (x,y) with dimensions (width, height).""" theform = getForm(canvas) theform.selectField(canvas, title, value, options, x, y, x+width, y+height) def selectFieldRelative(canvas, title, value, options, xR, yR, width, height): "same as textFieldAbsolute except the x and y are relative to the canvas coordinate transform" (xA, yA) = canvas.absolutePosition(xR,yR) return selectFieldAbsolute(canvas, title, value, options, xA, yA, width, height) #==========================end of public interfaces from reportlab.pdfbase.pdfpattern import PDFPattern, PDFPatternIf def getForm(canvas): "get form from canvas, create the form if needed" try: return canvas.AcroForm except AttributeError: theform = canvas.AcroForm = AcroForm() # install the form in the document d = canvas._doc cat = d._catalog cat.AcroForm = theform return theform class AcroForm(PDFObject): def __init__(self): self.fields = [] def textField(self, canvas, title, xmin, ymin, xmax, ymax, value="", maxlen=1000000, multiline=0): # determine the page ref doc = canvas._doc page = doc.thisPageRef() # determine text info R, G, B = obj_R_G_B(canvas._fillColorObj) #print "rgb", (R,G,B) font = canvas. _fontname fontsize = canvas. _fontsize field = TextField(title, value, xmin, ymin, xmax, ymax, page, maxlen, font, fontsize, R, G, B, multiline) self.fields.append(field) canvas._addAnnotation(field) def selectField(self, canvas, title, value, options, xmin, ymin, xmax, ymax): # determine the page ref doc = canvas._doc page = doc.thisPageRef() # determine text info R, G, B = obj_R_G_B(canvas._fillColorObj) #print "rgb", (R,G,B) font = canvas. _fontname fontsize = canvas. _fontsize field = SelectField(title, value, options, xmin, ymin, xmax, ymax, page, font=font, fontsize=fontsize, R=R, G=G, B=B) self.fields.append(field) canvas._addAnnotation(field) def buttonField(self, canvas, title, value, xmin, ymin, width=16.7704, height=14.907): # determine the page ref doc = canvas._doc page = doc.thisPageRef() field = ButtonField(title, value, xmin, ymin, page, width=width, height=height) self.fields.append(field) canvas._addAnnotation(field) def format(self, document): from reportlab.pdfbase.pdfdoc import PDFArray proxy = PDFPattern(FormPattern, Resources=getattr(self,'resources',None) or FormResources(), NeedAppearances=getattr(self,'needAppearances','false'), fields=PDFArray(self.fields), SigFlags=getattr(self,'sigFlags',0)) return proxy.format(document) FormPattern = [ '<<\r\n', '/NeedAppearances ',['NeedAppearances'],'\r\n' '/DA ', PDFString('/Helv 0 Tf 0 g '), '\r\n', '/DR ',["Resources"],'\r\n', '/Fields ', ["fields"],'\r\n', PDFPatternIf('SigFlags',['\r\n/SigFlags ',['SigFlags']]), '>>' ] def FormFontsDictionary(): from reportlab.pdfbase.pdfdoc import PDFDictionary fontsdictionary = PDFDictionary() fontsdictionary.__RefOnly__ = 1 for fullname, shortname in FORMFONTNAMES.items(): fontsdictionary[shortname] = FormFont(fullname, shortname) fontsdictionary["ZaDb"] = PDFPattern(ZaDbPattern) return fontsdictionary def FormResources(): return PDFPattern(FormResourcesDictionaryPattern, Encoding=PDFPattern(EncodingPattern,PDFDocEncoding=PDFPattern(PDFDocEncodingPattern)), Font=FormFontsDictionary()) ZaDbPattern = [ ' <<' ' /BaseFont' ' /ZapfDingbats' ' /Name' ' /ZaDb' ' /Subtype' ' /Type1' ' /Type' ' /Font' '>>'] FormResourcesDictionaryPattern = [ '<<', ' /Encoding ', ["Encoding"], '\r\n', ' /Font ', ["Font"], '\r\n', '>>' ] FORMFONTNAMES = { "Helvetica": "Helv", "Helvetica-Bold": "HeBo", 'Courier': "Cour", 'Courier-Bold': "CoBo", 'Courier-Oblique': "CoOb", 'Courier-BoldOblique': "CoBO", 'Helvetica-Oblique': "HeOb", 'Helvetica-BoldOblique': "HeBO", 'Times-Roman': "Time", 'Times-Bold': "TiBo", 'Times-Italic': "TiIt", 'Times-BoldItalic': "TiBI", } EncodingPattern = [ '<<', ' /PDFDocEncoding ', ["PDFDocEncoding"], '\r\n', '>>', ] PDFDocEncodingPattern = [ '<<' ' /Differences' ' [' ' 24' ' /breve' ' /caron' ' /circumflex' ' /dotaccent' ' /hungarumlaut' ' /ogonek' ' /ring' ' /tilde' ' 39' ' /quotesingle' ' 96' ' /grave' ' 128' ' /bullet' ' /dagger' ' /daggerdbl' ' /ellipsis' ' /emdash' ' /endash' ' /florin' ' /fraction' ' /guilsinglleft' ' /guilsinglright' ' /minus' ' /perthousand' ' /quotedblbase' ' /quotedblleft' ' /quotedblright' ' /quoteleft' ' /quoteright' ' /quotesinglbase' ' /trademark' ' /fi' ' /fl' ' /Lslash' ' /OE' ' /Scaron' ' /Ydieresis' ' /Zcaron' ' /dotlessi' ' /lslash' ' /oe' ' /scaron' ' /zcaron' ' 160' ' /Euro' ' 164' ' /currency' ' 166' ' /brokenbar' ' 168' ' /dieresis' ' /copyright' ' /ordfeminine' ' 172' ' /logicalnot' ' /.notdef' ' /registered' ' /macron' ' /degree' ' /plusminus' ' /twosuperior' ' /threesuperior' ' /acute' ' /mu' ' 183' ' /periodcentered' ' /cedilla' ' /onesuperior' ' /ordmasculine' ' 188' ' /onequarter' ' /onehalf' ' /threequarters' ' 192' ' /Agrave' ' /Aacute' ' /Acircumflex' ' /Atilde' ' /Adieresis' ' /Aring' ' /AE' ' /Ccedilla' ' /Egrave' ' /Eacute' ' /Ecircumflex' ' /Edieresis' ' /Igrave' ' /Iacute' ' /Icircumflex' ' /Idieresis' ' /Eth' ' /Ntilde' ' /Ograve' ' /Oacute' ' /Ocircumflex' ' /Otilde' ' /Odieresis' ' /multiply' ' /Oslash' ' /Ugrave' ' /Uacute' ' /Ucircumflex' ' /Udieresis' ' /Yacute' ' /Thorn' ' /germandbls' ' /agrave' ' /aacute' ' /acircumflex' ' /atilde' ' /adieresis' ' /aring' ' /ae' ' /ccedilla' ' /egrave' ' /eacute' ' /ecircumflex' ' /edieresis' ' /igrave' ' /iacute' ' /icircumflex' ' /idieresis' ' /eth' ' /ntilde' ' /ograve' ' /oacute' ' /ocircumflex' ' /otilde' ' /odieresis' ' /divide' ' /oslash' ' /ugrave' ' /uacute' ' /ucircumflex' ' /udieresis' ' /yacute' ' /thorn' ' /ydieresis' ' ]' ' /Type' ' /Encoding' '>>'] def FormFont(BaseFont, Name): from reportlab.pdfbase.pdfdoc import PDFName return PDFPattern(FormFontPattern, BaseFont=PDFName(BaseFont), Name=PDFName(Name), Encoding=PDFPattern(PDFDocEncodingPattern)) FormFontPattern = [ '<<', ' /BaseFont ', ["BaseFont"], '\r\n', ' /Encoding ', ["Encoding"], '\r\n', ' /Name ', ["Name"], '\r\n', ' /Subtype ' ' /Type1 ' ' /Type ' ' /Font ' '>>' ] def resetPdfForm(): pass from reportlab.rl_config import register_reset register_reset(resetPdfForm) resetPdfForm() def TextField(title, value, xmin, ymin, xmax, ymax, page, maxlen=1000000, font="Helvetica-Bold", fontsize=9, R=0, G=0, B=0.627, multiline=0): from reportlab.pdfbase.pdfdoc import PDFString, PDFName Flags = 0 if multiline: Flags = Flags | (1<<12) # bit 13 is at position 12 :) fontname = FORMFONTNAMES[font] return PDFPattern(TextFieldPattern, value=PDFString(value), maxlen=maxlen, page=page, title=PDFString(title), xmin=xmin, ymin=ymin, xmax=xmax, ymax=ymax, fontname=PDFName(fontname), fontsize=fontsize, R=R, G=G, B=B, Flags=Flags) TextFieldPattern = [ '<<' ' /DA' ' (', ["fontname"],' ',["fontsize"],' Tf ',["R"],' ',["G"],' ',["B"],' rg)' ' /DV ', ["value"], '\r\n', ' /F 4 /FT /Tx' '/MK << /BC [ 0 0 0 ] >>' ' /MaxLen ', ["maxlen"], '\r\n', ' /P ', ["page"], '\r\n', ' /Rect ' ' [', ["xmin"], " ", ["ymin"], " ", ["xmax"], " ", ["ymax"], ' ]' '/Subtype /Widget' ' /T ', ["title"], '\r\n', ' /Type' ' /Annot' ' /V ', ["value"], '\r\n', ' /Ff ', ["Flags"],'\r\n', '>>'] def SelectField(title, value, options, xmin, ymin, xmax, ymax, page, font="Helvetica-Bold", fontsize=9, R=0, G=0, B=0.627): #print "ARGS", (title, value, options, xmin, ymin, xmax, ymax, page, font, fontsize, R, G, B) from reportlab.pdfbase.pdfdoc import PDFString, PDFName, PDFArray if value not in options: raise ValueError("value %s must be one of options %s" % (repr(value), repr(options))) fontname = FORMFONTNAMES[font] optionstrings = list(map(PDFString, options)) optionarray = PDFArray(optionstrings) return PDFPattern(SelectFieldPattern, Options=optionarray, Selected=PDFString(value), Page=page, Name=PDFString(title), xmin=xmin, ymin=ymin, xmax=xmax, ymax=ymax, fontname=PDFName(fontname), fontsize=fontsize, R=R, G=G, B=B) SelectFieldPattern = [ '<< % a select list\r\n' ' /DA ', ' (', ["fontname"],' ',["fontsize"],' Tf ',["R"],' ',["G"],' ',["B"],' rg)\r\n', #' (/Helv 12 Tf 0 g)\r\n', ' /DV ', ["Selected"],'\r\n', ' /F ', ' 4\r\n', ' /FT ', ' /Ch\r\n', ' /MK ', ' <<', ' /BC', ' [', ' 0', ' 0', ' 0', ' ]', ' /BG', ' [', ' 1', ' 1', ' 1', ' ]', ' >>\r\n', ' /Opt ', ["Options"],'\r\n', ' /P ', ["Page"],'\r\n', '/Rect', ' [',["xmin"], " ", ["ymin"], " ", ["xmax"], " ", ["ymax"], ' ] \r\n', '/Subtype', ' /Widget\r\n', ' /T ', ["Name"],'\r\n', ' /Type ', ' /Annot', ' /V ', ["Selected"],'\r\n', '>>'] def ButtonField(title, value, xmin, ymin, page, width=16.7704, height=14.907): if value not in ("Yes", "Off"): raise ValueError("button value must be 'Yes' or 'Off': "+repr(value)) fontSize = (11.3086/14.907)*height dx = (3.6017/16.7704)*width dy = (3.3881/14.907)*height return PDFPattern(ButtonFieldPattern, Name=PDFString(title), xmin=xmin, ymin=ymin, xmax=xmin+width, ymax=ymin+width, Hide=PDFPattern(['<< /S /Hide >>']), APDOff=ButtonStream('0.749 g 0 0 %(width)s %(height)s re f\r\n' % vars(), width=width, height=height), APDYes=ButtonStream('0.749 g 0 0 %(width)s %(height)s re f q 1 1 %(width)s %(height)s re W n BT /ZaDb %(fontSize)s Tf 0 g 1 0 0 1 %(dx)s %(dy)s Tm (4) Tj ET\r\n' % vars(), width=width, height=height), APNYes=ButtonStream('q 1 1 %(width)s %(height)s re W n BT /ZaDb %(fontSize)s Tf 0 g 1 0 0 1 %(dx)s %(dy)s Tm (4) Tj ET Q\r\n' % vars(), width=width, height=height), Value=PDFName(value), Page=page) ButtonFieldPattern = ['<< ', '/AA', ' <<', ' /D ', ["Hide"],'\r\n', #' %(imported.18.0)s', ' >> ', '/AP ', ' <<', ' /D', ' <<', ' /Off ', #' %(imported.40.0)s', ["APDOff"], '\r\n', ' /Yes ', #' %(imported.39.0)s', ["APDYes"], '\r\n', ' >>', '\r\n', ' /N', ' << ', ' /Yes ', #' %(imported.38.0)s', ["APNYes"], '\r\n', ' >>', ' >>\r\n', ' /AS ', ["Value"], '\r\n', ' /DA ', PDFString('/ZaDb 0 Tf 0 g'), '\r\n', '/DV ', ["Value"], '\r\n', '/F ', ' 4 ', '/FT ', ' /Btn ', '/H ', ' /T ', '/MK ', ' <<', ' /AC (\\376\\377)', #PDFString('\376\377'), ' /CA ', PDFString('4'), ' /RC ', PDFString('\376\377'), ' >> ','\r\n', '/P ', ["Page"], '\r\n', '/Rect', ' [',["xmin"], " ", ["ymin"], " ", ["xmax"], " ", ["ymax"], ' ] ','\r\n', '/Subtype', ' /Widget ', '/T ', ["Name"], '\r\n', '/Type', ' /Annot ', '/V ', ["Value"], '\r\n', ' >>'] def buttonStreamDictionary(width=16.7704, height=14.907): "everything except the length for the button appearance streams" result = PDFDictionary() result["SubType"] = "/Form" result["BBox"] = "[0 0 %(width)s %(height)s]" % vars() font = PDFDictionary() font["ZaDb"] = PDFPattern(ZaDbPattern) resources = PDFDictionary() resources["ProcSet"] = "[ /PDF /Text ]" resources["Font"] = font result["Resources"] = resources return result def ButtonStream(content, width=16.7704, height=14.907): result = PDFStream(buttonStreamDictionary(width=width,height=height), content) result.filters = [] return result
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/pdfbase/pdfform.py
0.613005
0.359772
pdfform.py
pypi
widths = {'A': 667, 'AE': 944, 'Aacute': 667, 'Acircumflex': 667, 'Adieresis': 667, 'Agrave': 667, 'Aring': 667, 'Atilde': 667, 'B': 667, 'C': 667, 'Ccedilla': 667, 'D': 722, 'E': 667, 'Eacute': 667, 'Ecircumflex': 667, 'Edieresis': 667, 'Egrave': 667, 'Eth': 722, 'Euro': 500, 'F': 667, 'G': 722, 'H': 778, 'I': 389, 'Iacute': 389, 'Icircumflex': 389, 'Idieresis': 389, 'Igrave': 389, 'J': 500, 'K': 667, 'L': 611, 'Lslash': 611, 'M': 889, 'N': 722, 'Ntilde': 722, 'O': 722, 'OE': 944, 'Oacute': 722, 'Ocircumflex': 722, 'Odieresis': 722, 'Ograve': 722, 'Oslash': 722, 'Otilde': 722, 'P': 611, 'Q': 722, 'R': 667, 'S': 556, 'Scaron': 556, 'T': 611, 'Thorn': 611, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 667, 'W': 889, 'X': 667, 'Y': 611, 'Yacute': 611, 'Ydieresis': 611, 'Z': 611, 'Zcaron': 611, 'a': 500, 'aacute': 500, 'acircumflex': 500, 'acute': 333, 'adieresis': 500, 'ae': 722, 'agrave': 500, 'ampersand': 778, 'aring': 500, 'asciicircum': 570, 'asciitilde': 570, 'asterisk': 500, 'at': 832, 'atilde': 500, 'b': 500, 'backslash': 278, 'bar': 220, 'braceleft': 348, 'braceright': 348, 'bracketleft': 333, 'bracketright': 333, 'breve': 333, 'brokenbar': 220, 'bullet': 350, 'c': 444, 'caron': 333, 'ccedilla': 444, 'cedilla': 333, 'cent': 500, 'circumflex': 333, 'colon': 333, 'comma': 250, 'copyright': 747, 'currency': 500, 'd': 500, 'dagger': 500, 'daggerdbl': 500, 'degree': 400, 'dieresis': 333, 'divide': 570, 'dollar': 500, 'dotaccent': 333, 'dotlessi': 278, 'e': 444, 'eacute': 444, 'ecircumflex': 444, 'edieresis': 444, 'egrave': 444, 'eight': 500, 'ellipsis': 1000, 'emdash': 1000, 'endash': 500, 'equal': 570, 'eth': 500, 'exclam': 389, 'exclamdown': 389, 'f': 333, 'fi': 556, 'five': 500, 'fl': 556, 'florin': 500, 'four': 500, 'fraction': 167, 'g': 500, 'germandbls': 500, 'grave': 333, 'greater': 570, 'guillemotleft': 500, 'guillemotright': 500, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 556, 'hungarumlaut': 333, 'hyphen': 333, 'i': 278, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 278, 'k': 500, 'l': 278, 'less': 570, 'logicalnot': 606, 'lslash': 278, 'm': 778, 'macron': 333, 'minus': 606, 'mu': 576, 'multiply': 570, 'n': 556, 'nine': 500, 'ntilde': 556, 'numbersign': 500, 'o': 500, 'oacute': 500, 'ocircumflex': 500, 'odieresis': 500, 'oe': 722, 'ogonek': 333, 'ograve': 500, 'one': 500, 'onehalf': 750, 'onequarter': 750, 'onesuperior': 300, 'ordfeminine': 266, 'ordmasculine': 300, 'oslash': 500, 'otilde': 500, 'p': 500, 'paragraph': 500, 'parenleft': 333, 'parenright': 333, 'percent': 833, 'period': 250, 'periodcentered': 250, 'perthousand': 1000, 'plus': 570, 'plusminus': 570, 'q': 500, 'question': 500, 'questiondown': 500, 'quotedbl': 555, 'quotedblbase': 500, 'quotedblleft': 500, 'quotedblright': 500, 'quoteleft': 333, 'quoteright': 333, 'quotesinglbase': 333, 'quotesingle': 278, 'r': 389, 'registered': 747, 'ring': 333, 's': 389, 'scaron': 389, 'section': 500, 'semicolon': 333, 'seven': 500, 'six': 500, 'slash': 278, 'space': 250, 'sterling': 500, 't': 278, 'thorn': 500, 'three': 500, 'threequarters': 750, 'threesuperior': 300, 'tilde': 333, 'trademark': 1000, 'two': 500, 'twosuperior': 300, 'u': 556, 'uacute': 556, 'ucircumflex': 556, 'udieresis': 556, 'ugrave': 556, 'underscore': 500, 'v': 444, 'w': 667, 'x': 500, 'y': 444, 'yacute': 444, 'ydieresis': 444, 'yen': 500, 'z': 389, 'zcaron': 389, 'zero': 500}
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/pdfbase/_fontdata_widths_timesbolditalic.py
0.560974
0.26389
_fontdata_widths_timesbolditalic.py
pypi
widths = {'A': 722, 'AE': 889, 'Aacute': 722, 'Acircumflex': 722, 'Adieresis': 722, 'Agrave': 722, 'Aring': 722, 'Atilde': 722, 'B': 667, 'C': 667, 'Ccedilla': 667, 'D': 722, 'E': 611, 'Eacute': 611, 'Ecircumflex': 611, 'Edieresis': 611, 'Egrave': 611, 'Eth': 722, 'Euro': 500, 'F': 556, 'G': 722, 'H': 722, 'I': 333, 'Iacute': 333, 'Icircumflex': 333, 'Idieresis': 333, 'Igrave': 333, 'J': 389, 'K': 722, 'L': 611, 'Lslash': 611, 'M': 889, 'N': 722, 'Ntilde': 722, 'O': 722, 'OE': 889, 'Oacute': 722, 'Ocircumflex': 722, 'Odieresis': 722, 'Ograve': 722, 'Oslash': 722, 'Otilde': 722, 'P': 556, 'Q': 722, 'R': 667, 'S': 556, 'Scaron': 556, 'T': 611, 'Thorn': 556, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 722, 'W': 944, 'X': 722, 'Y': 722, 'Yacute': 722, 'Ydieresis': 722, 'Z': 611, 'Zcaron': 611, 'a': 444, 'aacute': 444, 'acircumflex': 444, 'acute': 333, 'adieresis': 444, 'ae': 667, 'agrave': 444, 'ampersand': 778, 'aring': 444, 'asciicircum': 469, 'asciitilde': 541, 'asterisk': 500, 'at': 921, 'atilde': 444, 'b': 500, 'backslash': 278, 'bar': 200, 'braceleft': 480, 'braceright': 480, 'bracketleft': 333, 'bracketright': 333, 'breve': 333, 'brokenbar': 200, 'bullet': 350, 'c': 444, 'caron': 333, 'ccedilla': 444, 'cedilla': 333, 'cent': 500, 'circumflex': 333, 'colon': 278, 'comma': 250, 'copyright': 760, 'currency': 500, 'd': 500, 'dagger': 500, 'daggerdbl': 500, 'degree': 400, 'dieresis': 333, 'divide': 564, 'dollar': 500, 'dotaccent': 333, 'dotlessi': 278, 'e': 444, 'eacute': 444, 'ecircumflex': 444, 'edieresis': 444, 'egrave': 444, 'eight': 500, 'ellipsis': 1000, 'emdash': 1000, 'endash': 500, 'equal': 564, 'eth': 500, 'exclam': 333, 'exclamdown': 333, 'f': 333, 'fi': 556, 'five': 500, 'fl': 556, 'florin': 500, 'four': 500, 'fraction': 167, 'g': 500, 'germandbls': 500, 'grave': 333, 'greater': 564, 'guillemotleft': 500, 'guillemotright': 500, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 500, 'hungarumlaut': 333, 'hyphen': 333, 'i': 278, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 278, 'k': 500, 'l': 278, 'less': 564, 'logicalnot': 564, 'lslash': 278, 'm': 778, 'macron': 333, 'minus': 564, 'mu': 500, 'multiply': 564, 'n': 500, 'nine': 500, 'ntilde': 500, 'numbersign': 500, 'o': 500, 'oacute': 500, 'ocircumflex': 500, 'odieresis': 500, 'oe': 722, 'ogonek': 333, 'ograve': 500, 'one': 500, 'onehalf': 750, 'onequarter': 750, 'onesuperior': 300, 'ordfeminine': 276, 'ordmasculine': 310, 'oslash': 500, 'otilde': 500, 'p': 500, 'paragraph': 453, 'parenleft': 333, 'parenright': 333, 'percent': 833, 'period': 250, 'periodcentered': 250, 'perthousand': 1000, 'plus': 564, 'plusminus': 564, 'q': 500, 'question': 444, 'questiondown': 444, 'quotedbl': 408, 'quotedblbase': 444, 'quotedblleft': 444, 'quotedblright': 444, 'quoteleft': 333, 'quoteright': 333, 'quotesinglbase': 333, 'quotesingle': 180, 'r': 333, 'registered': 760, 'ring': 333, 's': 389, 'scaron': 389, 'section': 500, 'semicolon': 278, 'seven': 500, 'six': 500, 'slash': 278, 'space': 250, 'sterling': 500, 't': 278, 'thorn': 500, 'three': 500, 'threequarters': 750, 'threesuperior': 300, 'tilde': 333, 'trademark': 980, 'two': 500, 'twosuperior': 300, 'u': 500, 'uacute': 500, 'ucircumflex': 500, 'udieresis': 500, 'ugrave': 500, 'underscore': 500, 'v': 500, 'w': 722, 'x': 500, 'y': 500, 'yacute': 500, 'ydieresis': 500, 'yen': 500, 'z': 444, 'zcaron': 444, 'zero': 500}
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/pdfbase/_fontdata_widths_timesroman.py
0.558568
0.184327
_fontdata_widths_timesroman.py
pypi
widths = {'Alpha': 722, 'Beta': 667, 'Chi': 722, 'Delta': 612, 'Epsilon': 611, 'Eta': 722, 'Euro': 750, 'Gamma': 603, 'Ifraktur': 686, 'Iota': 333, 'Kappa': 722, 'Lambda': 686, 'Mu': 889, 'Nu': 722, 'Omega': 768, 'Omicron': 722, 'Phi': 763, 'Pi': 768, 'Psi': 795, 'Rfraktur': 795, 'Rho': 556, 'Sigma': 592, 'Tau': 611, 'Theta': 741, 'Upsilon': 690, 'Upsilon1': 620, 'Xi': 645, 'Zeta': 611, 'aleph': 823, 'alpha': 631, 'ampersand': 778, 'angle': 768, 'angleleft': 329, 'angleright': 329, 'apple': 790, 'approxequal': 549, 'arrowboth': 1042, 'arrowdblboth': 1042, 'arrowdbldown': 603, 'arrowdblleft': 987, 'arrowdblright': 987, 'arrowdblup': 603, 'arrowdown': 603, 'arrowhorizex': 1000, 'arrowleft': 987, 'arrowright': 987, 'arrowup': 603, 'arrowvertex': 603, 'asteriskmath': 500, 'bar': 200, 'beta': 549, 'braceex': 494, 'braceleft': 480, 'braceleftbt': 494, 'braceleftmid': 494, 'bracelefttp': 494, 'braceright': 480, 'bracerightbt': 494, 'bracerightmid': 494, 'bracerighttp': 494, 'bracketleft': 333, 'bracketleftbt': 384, 'bracketleftex': 384, 'bracketlefttp': 384, 'bracketright': 333, 'bracketrightbt': 384, 'bracketrightex': 384, 'bracketrighttp': 384, 'bullet': 460, 'carriagereturn': 658, 'chi': 549, 'circlemultiply': 768, 'circleplus': 768, 'club': 753, 'colon': 278, 'comma': 250, 'congruent': 549, 'copyrightsans': 790, 'copyrightserif': 790, 'degree': 400, 'delta': 494, 'diamond': 753, 'divide': 549, 'dotmath': 250, 'eight': 500, 'element': 713, 'ellipsis': 1000, 'emptyset': 823, 'epsilon': 439, 'equal': 549, 'equivalence': 549, 'eta': 603, 'exclam': 333, 'existential': 549, 'five': 500, 'florin': 500, 'four': 500, 'fraction': 167, 'gamma': 411, 'gradient': 713, 'greater': 549, 'greaterequal': 549, 'heart': 753, 'infinity': 713, 'integral': 274, 'integralbt': 686, 'integralex': 686, 'integraltp': 686, 'intersection': 768, 'iota': 329, 'kappa': 549, 'lambda': 549, 'less': 549, 'lessequal': 549, 'logicaland': 603, 'logicalnot': 713, 'logicalor': 603, 'lozenge': 494, 'minus': 549, 'minute': 247, 'mu': 576, 'multiply': 549, 'nine': 500, 'notelement': 713, 'notequal': 549, 'notsubset': 713, 'nu': 521, 'numbersign': 500, 'omega': 686, 'omega1': 713, 'omicron': 549, 'one': 500, 'parenleft': 333, 'parenleftbt': 384, 'parenleftex': 384, 'parenlefttp': 384, 'parenright': 333, 'parenrightbt': 384, 'parenrightex': 384, 'parenrighttp': 384, 'partialdiff': 494, 'percent': 833, 'period': 250, 'perpendicular': 658, 'phi': 521, 'phi1': 603, 'pi': 549, 'plus': 549, 'plusminus': 549, 'product': 823, 'propersubset': 713, 'propersuperset': 713, 'proportional': 713, 'psi': 686, 'question': 444, 'radical': 549, 'radicalex': 500, 'reflexsubset': 713, 'reflexsuperset': 713, 'registersans': 790, 'registerserif': 790, 'rho': 549, 'second': 411, 'semicolon': 278, 'seven': 500, 'sigma': 603, 'sigma1': 439, 'similar': 549, 'six': 500, 'slash': 278, 'space': 250, 'spade': 753, 'suchthat': 439, 'summation': 713, 'tau': 439, 'therefore': 863, 'theta': 521, 'theta1': 631, 'three': 500, 'trademarksans': 786, 'trademarkserif': 890, 'two': 500, 'underscore': 500, 'union': 768, 'universal': 713, 'upsilon': 576, 'weierstrass': 987, 'xi': 493, 'zero': 500, 'zeta': 494}
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/pdfbase/_fontdata_widths_symbol.py
0.650245
0.257549
_fontdata_widths_symbol.py
pypi
WinAnsiEncoding = ( None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'bullet', 'Euro', 'bullet', 'quotesinglbase', 'florin', 'quotedblbase', 'ellipsis', 'dagger', 'daggerdbl', 'circumflex', 'perthousand', 'Scaron', 'guilsinglleft', 'OE', 'bullet', 'Zcaron', 'bullet', 'bullet', 'quoteleft', 'quoteright', 'quotedblleft', 'quotedblright', 'bullet', 'endash', 'emdash', 'tilde', 'trademark', 'scaron', 'guilsinglright', 'oe', 'bullet', 'zcaron', 'Ydieresis', 'space', 'exclamdown', 'cent', 'sterling', 'currency', 'yen', 'brokenbar', 'section', 'dieresis', 'copyright', 'ordfeminine', 'guillemotleft', 'logicalnot', 'hyphen', 'registered', 'macron', 'degree', 'plusminus', 'twosuperior', 'threesuperior', 'acute', 'mu', 'paragraph', 'periodcentered', 'cedilla', 'onesuperior', 'ordmasculine', 'guillemotright', 'onequarter', 'onehalf', 'threequarters', 'questiondown', 'Agrave', 'Aacute', 'Acircumflex', 'Atilde', 'Adieresis', 'Aring', 'AE', 'Ccedilla', 'Egrave', 'Eacute', 'Ecircumflex', 'Edieresis', 'Igrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Eth', 'Ntilde', 'Ograve', 'Oacute', 'Ocircumflex', 'Otilde', 'Odieresis', 'multiply', 'Oslash', 'Ugrave', 'Uacute', 'Ucircumflex', 'Udieresis', 'Yacute', 'Thorn', 'germandbls', 'agrave', 'aacute', 'acircumflex', 'atilde', 'adieresis', 'aring', 'ae', 'ccedilla', 'egrave', 'eacute', 'ecircumflex', 'edieresis', 'igrave', 'iacute', 'icircumflex', 'idieresis', 'eth', 'ntilde', 'ograve', 'oacute', 'ocircumflex', 'otilde', 'odieresis', 'divide', 'oslash', 'ugrave', 'uacute', 'ucircumflex', 'udieresis', 'yacute', 'thorn', 'ydieresis')
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/pdfbase/_fontdata_enc_winansi.py
0.540439
0.153644
_fontdata_enc_winansi.py
pypi
widths = {'A': 600, 'AE': 600, 'Aacute': 600, 'Acircumflex': 600, 'Adieresis': 600, 'Agrave': 600, 'Aring': 600, 'Atilde': 600, 'B': 600, 'C': 600, 'Ccedilla': 600, 'D': 600, 'E': 600, 'Eacute': 600, 'Ecircumflex': 600, 'Edieresis': 600, 'Egrave': 600, 'Eth': 600, 'Euro': 600, 'F': 600, 'G': 600, 'H': 600, 'I': 600, 'Iacute': 600, 'Icircumflex': 600, 'Idieresis': 600, 'Igrave': 600, 'J': 600, 'K': 600, 'L': 600, 'Lslash': 600, 'M': 600, 'N': 600, 'Ntilde': 600, 'O': 600, 'OE': 600, 'Oacute': 600, 'Ocircumflex': 600, 'Odieresis': 600, 'Ograve': 600, 'Oslash': 600, 'Otilde': 600, 'P': 600, 'Q': 600, 'R': 600, 'S': 600, 'Scaron': 600, 'T': 600, 'Thorn': 600, 'U': 600, 'Uacute': 600, 'Ucircumflex': 600, 'Udieresis': 600, 'Ugrave': 600, 'V': 600, 'W': 600, 'X': 600, 'Y': 600, 'Yacute': 600, 'Ydieresis': 600, 'Z': 600, 'Zcaron': 600, 'a': 600, 'aacute': 600, 'acircumflex': 600, 'acute': 600, 'adieresis': 600, 'ae': 600, 'agrave': 600, 'ampersand': 600, 'aring': 600, 'asciicircum': 600, 'asciitilde': 600, 'asterisk': 600, 'at': 600, 'atilde': 600, 'b': 600, 'backslash': 600, 'bar': 600, 'braceleft': 600, 'braceright': 600, 'bracketleft': 600, 'bracketright': 600, 'breve': 600, 'brokenbar': 600, 'bullet': 600, 'c': 600, 'caron': 600, 'ccedilla': 600, 'cedilla': 600, 'cent': 600, 'circumflex': 600, 'colon': 600, 'comma': 600, 'copyright': 600, 'currency': 600, 'd': 600, 'dagger': 600, 'daggerdbl': 600, 'degree': 600, 'dieresis': 600, 'divide': 600, 'dollar': 600, 'dotaccent': 600, 'dotlessi': 600, 'e': 600, 'eacute': 600, 'ecircumflex': 600, 'edieresis': 600, 'egrave': 600, 'eight': 600, 'ellipsis': 600, 'emdash': 600, 'endash': 600, 'equal': 600, 'eth': 600, 'exclam': 600, 'exclamdown': 600, 'f': 600, 'fi': 600, 'five': 600, 'fl': 600, 'florin': 600, 'four': 600, 'fraction': 600, 'g': 600, 'germandbls': 600, 'grave': 600, 'greater': 600, 'guillemotleft': 600, 'guillemotright': 600, 'guilsinglleft': 600, 'guilsinglright': 600, 'h': 600, 'hungarumlaut': 600, 'hyphen': 600, 'i': 600, 'iacute': 600, 'icircumflex': 600, 'idieresis': 600, 'igrave': 600, 'j': 600, 'k': 600, 'l': 600, 'less': 600, 'logicalnot': 600, 'lslash': 600, 'm': 600, 'macron': 600, 'minus': 600, 'mu': 600, 'multiply': 600, 'n': 600, 'nine': 600, 'ntilde': 600, 'numbersign': 600, 'o': 600, 'oacute': 600, 'ocircumflex': 600, 'odieresis': 600, 'oe': 600, 'ogonek': 600, 'ograve': 600, 'one': 600, 'onehalf': 600, 'onequarter': 600, 'onesuperior': 600, 'ordfeminine': 600, 'ordmasculine': 600, 'oslash': 600, 'otilde': 600, 'p': 600, 'paragraph': 600, 'parenleft': 600, 'parenright': 600, 'percent': 600, 'period': 600, 'periodcentered': 600, 'perthousand': 600, 'plus': 600, 'plusminus': 600, 'q': 600, 'question': 600, 'questiondown': 600, 'quotedbl': 600, 'quotedblbase': 600, 'quotedblleft': 600, 'quotedblright': 600, 'quoteleft': 600, 'quoteright': 600, 'quotesinglbase': 600, 'quotesingle': 600, 'r': 600, 'registered': 600, 'ring': 600, 's': 600, 'scaron': 600, 'section': 600, 'semicolon': 600, 'seven': 600, 'six': 600, 'slash': 600, 'space': 600, 'sterling': 600, 't': 600, 'thorn': 600, 'three': 600, 'threequarters': 600, 'threesuperior': 600, 'tilde': 600, 'trademark': 600, 'two': 600, 'twosuperior': 600, 'u': 600, 'uacute': 600, 'ucircumflex': 600, 'udieresis': 600, 'ugrave': 600, 'underscore': 600, 'v': 600, 'w': 600, 'x': 600, 'y': 600, 'yacute': 600, 'ydieresis': 600, 'yen': 600, 'z': 600, 'zcaron': 600, 'zero': 600}
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/pdfbase/_fontdata_widths_courierboldoblique.py
0.620277
0.171338
_fontdata_widths_courierboldoblique.py
pypi
widths = {'A': 667, 'AE': 1000, 'Aacute': 667, 'Acircumflex': 667, 'Adieresis': 667, 'Agrave': 667, 'Aring': 667, 'Atilde': 667, 'B': 667, 'C': 722, 'Ccedilla': 722, 'D': 722, 'E': 667, 'Eacute': 667, 'Ecircumflex': 667, 'Edieresis': 667, 'Egrave': 667, 'Eth': 722, 'Euro': 556, 'F': 611, 'G': 778, 'H': 722, 'I': 278, 'Iacute': 278, 'Icircumflex': 278, 'Idieresis': 278, 'Igrave': 278, 'J': 500, 'K': 667, 'L': 556, 'Lslash': 556, 'M': 833, 'N': 722, 'Ntilde': 722, 'O': 778, 'OE': 1000, 'Oacute': 778, 'Ocircumflex': 778, 'Odieresis': 778, 'Ograve': 778, 'Oslash': 778, 'Otilde': 778, 'P': 667, 'Q': 778, 'R': 722, 'S': 667, 'Scaron': 667, 'T': 611, 'Thorn': 667, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 667, 'W': 944, 'X': 667, 'Y': 667, 'Yacute': 667, 'Ydieresis': 667, 'Z': 611, 'Zcaron': 611, 'a': 556, 'aacute': 556, 'acircumflex': 556, 'acute': 333, 'adieresis': 556, 'ae': 889, 'agrave': 556, 'ampersand': 667, 'aring': 556, 'asciicircum': 469, 'asciitilde': 584, 'asterisk': 389, 'at': 1015, 'atilde': 556, 'b': 556, 'backslash': 278, 'bar': 260, 'braceleft': 334, 'braceright': 334, 'bracketleft': 278, 'bracketright': 278, 'breve': 333, 'brokenbar': 260, 'bullet': 350, 'c': 500, 'caron': 333, 'ccedilla': 500, 'cedilla': 333, 'cent': 556, 'circumflex': 333, 'colon': 278, 'comma': 278, 'copyright': 737, 'currency': 556, 'd': 556, 'dagger': 556, 'daggerdbl': 556, 'degree': 400, 'dieresis': 333, 'divide': 584, 'dollar': 556, 'dotaccent': 333, 'dotlessi': 278, 'e': 556, 'eacute': 556, 'ecircumflex': 556, 'edieresis': 556, 'egrave': 556, 'eight': 556, 'ellipsis': 1000, 'emdash': 1000, 'endash': 556, 'equal': 584, 'eth': 556, 'exclam': 278, 'exclamdown': 333, 'f': 278, 'fi': 500, 'five': 556, 'fl': 500, 'florin': 556, 'four': 556, 'fraction': 167, 'g': 556, 'germandbls': 611, 'grave': 333, 'greater': 584, 'guillemotleft': 556, 'guillemotright': 556, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 556, 'hungarumlaut': 333, 'hyphen': 333, 'i': 222, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 222, 'k': 500, 'l': 222, 'less': 584, 'logicalnot': 584, 'lslash': 222, 'm': 833, 'macron': 333, 'minus': 584, 'mu': 556, 'multiply': 584, 'n': 556, 'nine': 556, 'ntilde': 556, 'numbersign': 556, 'o': 556, 'oacute': 556, 'ocircumflex': 556, 'odieresis': 556, 'oe': 944, 'ogonek': 333, 'ograve': 556, 'one': 556, 'onehalf': 834, 'onequarter': 834, 'onesuperior': 333, 'ordfeminine': 370, 'ordmasculine': 365, 'oslash': 611, 'otilde': 556, 'p': 556, 'paragraph': 537, 'parenleft': 333, 'parenright': 333, 'percent': 889, 'period': 278, 'periodcentered': 278, 'perthousand': 1000, 'plus': 584, 'plusminus': 584, 'q': 556, 'question': 556, 'questiondown': 611, 'quotedbl': 355, 'quotedblbase': 333, 'quotedblleft': 333, 'quotedblright': 333, 'quoteleft': 222, 'quoteright': 222, 'quotesinglbase': 222, 'quotesingle': 191, 'r': 333, 'registered': 737, 'ring': 333, 's': 500, 'scaron': 500, 'section': 556, 'semicolon': 278, 'seven': 556, 'six': 556, 'slash': 278, 'space': 278, 'sterling': 556, 't': 278, 'thorn': 556, 'three': 556, 'threequarters': 834, 'threesuperior': 333, 'tilde': 333, 'trademark': 1000, 'two': 556, 'twosuperior': 333, 'u': 556, 'uacute': 556, 'ucircumflex': 556, 'udieresis': 556, 'ugrave': 556, 'underscore': 556, 'v': 500, 'w': 722, 'x': 500, 'y': 500, 'yacute': 500, 'ydieresis': 500, 'yen': 556, 'z': 500, 'zcaron': 500, 'zero': 556}
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/pdfbase/_fontdata_widths_helvetica.py
0.572245
0.290893
_fontdata_widths_helvetica.py
pypi
widths = {'A': 722, 'AE': 1000, 'Aacute': 722, 'Acircumflex': 722, 'Adieresis': 722, 'Agrave': 722, 'Aring': 722, 'Atilde': 722, 'B': 667, 'C': 722, 'Ccedilla': 722, 'D': 722, 'E': 667, 'Eacute': 667, 'Ecircumflex': 667, 'Edieresis': 667, 'Egrave': 667, 'Eth': 722, 'Euro': 500, 'F': 611, 'G': 778, 'H': 778, 'I': 389, 'Iacute': 389, 'Icircumflex': 389, 'Idieresis': 389, 'Igrave': 389, 'J': 500, 'K': 778, 'L': 667, 'Lslash': 667, 'M': 944, 'N': 722, 'Ntilde': 722, 'O': 778, 'OE': 1000, 'Oacute': 778, 'Ocircumflex': 778, 'Odieresis': 778, 'Ograve': 778, 'Oslash': 778, 'Otilde': 778, 'P': 611, 'Q': 778, 'R': 722, 'S': 556, 'Scaron': 556, 'T': 667, 'Thorn': 611, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 722, 'W': 1000, 'X': 722, 'Y': 722, 'Yacute': 722, 'Ydieresis': 722, 'Z': 667, 'Zcaron': 667, 'a': 500, 'aacute': 500, 'acircumflex': 500, 'acute': 333, 'adieresis': 500, 'ae': 722, 'agrave': 500, 'ampersand': 833, 'aring': 500, 'asciicircum': 581, 'asciitilde': 520, 'asterisk': 500, 'at': 930, 'atilde': 500, 'b': 556, 'backslash': 278, 'bar': 220, 'braceleft': 394, 'braceright': 394, 'bracketleft': 333, 'bracketright': 333, 'breve': 333, 'brokenbar': 220, 'bullet': 350, 'c': 444, 'caron': 333, 'ccedilla': 444, 'cedilla': 333, 'cent': 500, 'circumflex': 333, 'colon': 333, 'comma': 250, 'copyright': 747, 'currency': 500, 'd': 556, 'dagger': 500, 'daggerdbl': 500, 'degree': 400, 'dieresis': 333, 'divide': 570, 'dollar': 500, 'dotaccent': 333, 'dotlessi': 278, 'e': 444, 'eacute': 444, 'ecircumflex': 444, 'edieresis': 444, 'egrave': 444, 'eight': 500, 'ellipsis': 1000, 'emdash': 1000, 'endash': 500, 'equal': 570, 'eth': 500, 'exclam': 333, 'exclamdown': 333, 'f': 333, 'fi': 556, 'five': 500, 'fl': 556, 'florin': 500, 'four': 500, 'fraction': 167, 'g': 500, 'germandbls': 556, 'grave': 333, 'greater': 570, 'guillemotleft': 500, 'guillemotright': 500, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 556, 'hungarumlaut': 333, 'hyphen': 333, 'i': 278, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 333, 'k': 556, 'l': 278, 'less': 570, 'logicalnot': 570, 'lslash': 278, 'm': 833, 'macron': 333, 'minus': 570, 'mu': 556, 'multiply': 570, 'n': 556, 'nine': 500, 'ntilde': 556, 'numbersign': 500, 'o': 500, 'oacute': 500, 'ocircumflex': 500, 'odieresis': 500, 'oe': 722, 'ogonek': 333, 'ograve': 500, 'one': 500, 'onehalf': 750, 'onequarter': 750, 'onesuperior': 300, 'ordfeminine': 300, 'ordmasculine': 330, 'oslash': 500, 'otilde': 500, 'p': 556, 'paragraph': 540, 'parenleft': 333, 'parenright': 333, 'percent': 1000, 'period': 250, 'periodcentered': 250, 'perthousand': 1000, 'plus': 570, 'plusminus': 570, 'q': 556, 'question': 500, 'questiondown': 500, 'quotedbl': 555, 'quotedblbase': 500, 'quotedblleft': 500, 'quotedblright': 500, 'quoteleft': 333, 'quoteright': 333, 'quotesinglbase': 333, 'quotesingle': 278, 'r': 444, 'registered': 747, 'ring': 333, 's': 389, 'scaron': 389, 'section': 500, 'semicolon': 333, 'seven': 500, 'six': 500, 'slash': 278, 'space': 250, 'sterling': 500, 't': 333, 'thorn': 556, 'three': 500, 'threequarters': 750, 'threesuperior': 300, 'tilde': 333, 'trademark': 1000, 'two': 500, 'twosuperior': 300, 'u': 556, 'uacute': 556, 'ucircumflex': 556, 'udieresis': 556, 'ugrave': 556, 'underscore': 500, 'v': 500, 'w': 722, 'x': 500, 'y': 500, 'yacute': 500, 'ydieresis': 500, 'yen': 500, 'z': 444, 'zcaron': 444, 'zero': 500}
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/pdfbase/_fontdata_widths_timesbold.py
0.5564
0.181953
_fontdata_widths_timesbold.py
pypi
widths = {'A': 722, 'AE': 1000, 'Aacute': 722, 'Acircumflex': 722, 'Adieresis': 722, 'Agrave': 722, 'Aring': 722, 'Atilde': 722, 'B': 722, 'C': 722, 'Ccedilla': 722, 'D': 722, 'E': 667, 'Eacute': 667, 'Ecircumflex': 667, 'Edieresis': 667, 'Egrave': 667, 'Eth': 722, 'Euro': 556, 'F': 611, 'G': 778, 'H': 722, 'I': 278, 'Iacute': 278, 'Icircumflex': 278, 'Idieresis': 278, 'Igrave': 278, 'J': 556, 'K': 722, 'L': 611, 'Lslash': 611, 'M': 833, 'N': 722, 'Ntilde': 722, 'O': 778, 'OE': 1000, 'Oacute': 778, 'Ocircumflex': 778, 'Odieresis': 778, 'Ograve': 778, 'Oslash': 778, 'Otilde': 778, 'P': 667, 'Q': 778, 'R': 722, 'S': 667, 'Scaron': 667, 'T': 611, 'Thorn': 667, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 667, 'W': 944, 'X': 667, 'Y': 667, 'Yacute': 667, 'Ydieresis': 667, 'Z': 611, 'Zcaron': 611, 'a': 556, 'aacute': 556, 'acircumflex': 556, 'acute': 333, 'adieresis': 556, 'ae': 889, 'agrave': 556, 'ampersand': 722, 'aring': 556, 'asciicircum': 584, 'asciitilde': 584, 'asterisk': 389, 'at': 975, 'atilde': 556, 'b': 611, 'backslash': 278, 'bar': 280, 'braceleft': 389, 'braceright': 389, 'bracketleft': 333, 'bracketright': 333, 'breve': 333, 'brokenbar': 280, 'bullet': 350, 'c': 556, 'caron': 333, 'ccedilla': 556, 'cedilla': 333, 'cent': 556, 'circumflex': 333, 'colon': 333, 'comma': 278, 'copyright': 737, 'currency': 556, 'd': 611, 'dagger': 556, 'daggerdbl': 556, 'degree': 400, 'dieresis': 333, 'divide': 584, 'dollar': 556, 'dotaccent': 333, 'dotlessi': 278, 'e': 556, 'eacute': 556, 'ecircumflex': 556, 'edieresis': 556, 'egrave': 556, 'eight': 556, 'ellipsis': 1000, 'emdash': 1000, 'endash': 556, 'equal': 584, 'eth': 611, 'exclam': 333, 'exclamdown': 333, 'f': 333, 'fi': 611, 'five': 556, 'fl': 611, 'florin': 556, 'four': 556, 'fraction': 167, 'g': 611, 'germandbls': 611, 'grave': 333, 'greater': 584, 'guillemotleft': 556, 'guillemotright': 556, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 611, 'hungarumlaut': 333, 'hyphen': 333, 'i': 278, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 278, 'k': 556, 'l': 278, 'less': 584, 'logicalnot': 584, 'lslash': 278, 'm': 889, 'macron': 333, 'minus': 584, 'mu': 611, 'multiply': 584, 'n': 611, 'nine': 556, 'ntilde': 611, 'numbersign': 556, 'o': 611, 'oacute': 611, 'ocircumflex': 611, 'odieresis': 611, 'oe': 944, 'ogonek': 333, 'ograve': 611, 'one': 556, 'onehalf': 834, 'onequarter': 834, 'onesuperior': 333, 'ordfeminine': 370, 'ordmasculine': 365, 'oslash': 611, 'otilde': 611, 'p': 611, 'paragraph': 556, 'parenleft': 333, 'parenright': 333, 'percent': 889, 'period': 278, 'periodcentered': 278, 'perthousand': 1000, 'plus': 584, 'plusminus': 584, 'q': 611, 'question': 611, 'questiondown': 611, 'quotedbl': 474, 'quotedblbase': 500, 'quotedblleft': 500, 'quotedblright': 500, 'quoteleft': 278, 'quoteright': 278, 'quotesinglbase': 278, 'quotesingle': 238, 'r': 389, 'registered': 737, 'ring': 333, 's': 556, 'scaron': 556, 'section': 556, 'semicolon': 333, 'seven': 556, 'six': 556, 'slash': 278, 'space': 278, 'sterling': 556, 't': 333, 'thorn': 611, 'three': 556, 'threequarters': 834, 'threesuperior': 333, 'tilde': 333, 'trademark': 1000, 'two': 556, 'twosuperior': 333, 'u': 611, 'uacute': 611, 'ucircumflex': 611, 'udieresis': 611, 'ugrave': 611, 'underscore': 556, 'v': 556, 'w': 778, 'x': 556, 'y': 556, 'yacute': 556, 'ydieresis': 556, 'yen': 556, 'z': 500, 'zcaron': 500, 'zero': 556}
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/pdfbase/_fontdata_widths_helveticabold.py
0.563858
0.221035
_fontdata_widths_helveticabold.py
pypi
widths = {'A': 611, 'AE': 889, 'Aacute': 611, 'Acircumflex': 611, 'Adieresis': 611, 'Agrave': 611, 'Aring': 611, 'Atilde': 611, 'B': 611, 'C': 667, 'Ccedilla': 667, 'D': 722, 'E': 611, 'Eacute': 611, 'Ecircumflex': 611, 'Edieresis': 611, 'Egrave': 611, 'Eth': 722, 'Euro': 500, 'F': 611, 'G': 722, 'H': 722, 'I': 333, 'Iacute': 333, 'Icircumflex': 333, 'Idieresis': 333, 'Igrave': 333, 'J': 444, 'K': 667, 'L': 556, 'Lslash': 556, 'M': 833, 'N': 667, 'Ntilde': 667, 'O': 722, 'OE': 944, 'Oacute': 722, 'Ocircumflex': 722, 'Odieresis': 722, 'Ograve': 722, 'Oslash': 722, 'Otilde': 722, 'P': 611, 'Q': 722, 'R': 611, 'S': 500, 'Scaron': 500, 'T': 556, 'Thorn': 611, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 611, 'W': 833, 'X': 611, 'Y': 556, 'Yacute': 556, 'Ydieresis': 556, 'Z': 556, 'Zcaron': 556, 'a': 500, 'aacute': 500, 'acircumflex': 500, 'acute': 333, 'adieresis': 500, 'ae': 667, 'agrave': 500, 'ampersand': 778, 'aring': 500, 'asciicircum': 422, 'asciitilde': 541, 'asterisk': 500, 'at': 920, 'atilde': 500, 'b': 500, 'backslash': 278, 'bar': 275, 'braceleft': 400, 'braceright': 400, 'bracketleft': 389, 'bracketright': 389, 'breve': 333, 'brokenbar': 275, 'bullet': 350, 'c': 444, 'caron': 333, 'ccedilla': 444, 'cedilla': 333, 'cent': 500, 'circumflex': 333, 'colon': 333, 'comma': 250, 'copyright': 760, 'currency': 500, 'd': 500, 'dagger': 500, 'daggerdbl': 500, 'degree': 400, 'dieresis': 333, 'divide': 675, 'dollar': 500, 'dotaccent': 333, 'dotlessi': 278, 'e': 444, 'eacute': 444, 'ecircumflex': 444, 'edieresis': 444, 'egrave': 444, 'eight': 500, 'ellipsis': 889, 'emdash': 889, 'endash': 500, 'equal': 675, 'eth': 500, 'exclam': 333, 'exclamdown': 389, 'f': 278, 'fi': 500, 'five': 500, 'fl': 500, 'florin': 500, 'four': 500, 'fraction': 167, 'g': 500, 'germandbls': 500, 'grave': 333, 'greater': 675, 'guillemotleft': 500, 'guillemotright': 500, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 500, 'hungarumlaut': 333, 'hyphen': 333, 'i': 278, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 278, 'k': 444, 'l': 278, 'less': 675, 'logicalnot': 675, 'lslash': 278, 'm': 722, 'macron': 333, 'minus': 675, 'mu': 500, 'multiply': 675, 'n': 500, 'nine': 500, 'ntilde': 500, 'numbersign': 500, 'o': 500, 'oacute': 500, 'ocircumflex': 500, 'odieresis': 500, 'oe': 667, 'ogonek': 333, 'ograve': 500, 'one': 500, 'onehalf': 750, 'onequarter': 750, 'onesuperior': 300, 'ordfeminine': 276, 'ordmasculine': 310, 'oslash': 500, 'otilde': 500, 'p': 500, 'paragraph': 523, 'parenleft': 333, 'parenright': 333, 'percent': 833, 'period': 250, 'periodcentered': 250, 'perthousand': 1000, 'plus': 675, 'plusminus': 675, 'q': 500, 'question': 500, 'questiondown': 500, 'quotedbl': 420, 'quotedblbase': 556, 'quotedblleft': 556, 'quotedblright': 556, 'quoteleft': 333, 'quoteright': 333, 'quotesinglbase': 333, 'quotesingle': 214, 'r': 389, 'registered': 760, 'ring': 333, 's': 389, 'scaron': 389, 'section': 500, 'semicolon': 333, 'seven': 500, 'six': 500, 'slash': 278, 'space': 250, 'sterling': 500, 't': 278, 'thorn': 500, 'three': 500, 'threequarters': 750, 'threesuperior': 300, 'tilde': 333, 'trademark': 980, 'two': 500, 'twosuperior': 300, 'u': 500, 'uacute': 500, 'ucircumflex': 500, 'udieresis': 500, 'ugrave': 500, 'underscore': 500, 'v': 444, 'w': 667, 'x': 444, 'y': 444, 'yacute': 444, 'ydieresis': 444, 'yen': 500, 'z': 389, 'zcaron': 389, 'zero': 500}
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/pdfbase/_fontdata_widths_timesitalic.py
0.546496
0.215516
_fontdata_widths_timesitalic.py
pypi
MacRomanEncoding = ( None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', None, 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis', 'Udieresis', 'aacute', 'agrave', 'acircumflex', 'adieresis', 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis', 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve', 'ocircumflex', 'odieresis', 'otilde', 'uacute', 'ugrave', 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section', 'bullet', 'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute', 'dieresis', None, 'AE', 'Oslash', None, 'plusminus', None, None, 'yen', 'mu', None, None, None, None, None, 'ordfeminine', 'ordmasculine', None, 'ae', 'oslash', 'questiondown', 'exclamdown', 'logicalnot', None, 'florin', None, None, 'guillemotleft', 'guillemotright', 'ellipsis', 'space', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash', 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft', 'quoteright', 'divide', None, 'ydieresis', 'Ydieresis', 'fraction', 'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered', 'quotesinglbase', 'quotedblbase', 'perthousand', 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', None, 'Ograve', 'Uacute', 'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron')
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/pdfbase/_fontdata_enc_macroman.py
0.529263
0.177401
_fontdata_enc_macroman.py
pypi
widths = {'A': 667, 'AE': 1000, 'Aacute': 667, 'Acircumflex': 667, 'Adieresis': 667, 'Agrave': 667, 'Aring': 667, 'Atilde': 667, 'B': 667, 'C': 722, 'Ccedilla': 722, 'D': 722, 'E': 667, 'Eacute': 667, 'Ecircumflex': 667, 'Edieresis': 667, 'Egrave': 667, 'Eth': 722, 'Euro': 556, 'F': 611, 'G': 778, 'H': 722, 'I': 278, 'Iacute': 278, 'Icircumflex': 278, 'Idieresis': 278, 'Igrave': 278, 'J': 500, 'K': 667, 'L': 556, 'Lslash': 556, 'M': 833, 'N': 722, 'Ntilde': 722, 'O': 778, 'OE': 1000, 'Oacute': 778, 'Ocircumflex': 778, 'Odieresis': 778, 'Ograve': 778, 'Oslash': 778, 'Otilde': 778, 'P': 667, 'Q': 778, 'R': 722, 'S': 667, 'Scaron': 667, 'T': 611, 'Thorn': 667, 'U': 722, 'Uacute': 722, 'Ucircumflex': 722, 'Udieresis': 722, 'Ugrave': 722, 'V': 667, 'W': 944, 'X': 667, 'Y': 667, 'Yacute': 667, 'Ydieresis': 667, 'Z': 611, 'Zcaron': 611, 'a': 556, 'aacute': 556, 'acircumflex': 556, 'acute': 333, 'adieresis': 556, 'ae': 889, 'agrave': 556, 'ampersand': 667, 'aring': 556, 'asciicircum': 469, 'asciitilde': 584, 'asterisk': 389, 'at': 1015, 'atilde': 556, 'b': 556, 'backslash': 278, 'bar': 260, 'braceleft': 334, 'braceright': 334, 'bracketleft': 278, 'bracketright': 278, 'breve': 333, 'brokenbar': 260, 'bullet': 350, 'c': 500, 'caron': 333, 'ccedilla': 500, 'cedilla': 333, 'cent': 556, 'circumflex': 333, 'colon': 278, 'comma': 278, 'copyright': 737, 'currency': 556, 'd': 556, 'dagger': 556, 'daggerdbl': 556, 'degree': 400, 'dieresis': 333, 'divide': 584, 'dollar': 556, 'dotaccent': 333, 'dotlessi': 278, 'e': 556, 'eacute': 556, 'ecircumflex': 556, 'edieresis': 556, 'egrave': 556, 'eight': 556, 'ellipsis': 1000, 'emdash': 1000, 'endash': 556, 'equal': 584, 'eth': 556, 'exclam': 278, 'exclamdown': 333, 'f': 278, 'fi': 500, 'five': 556, 'fl': 500, 'florin': 556, 'four': 556, 'fraction': 167, 'g': 556, 'germandbls': 611, 'grave': 333, 'greater': 584, 'guillemotleft': 556, 'guillemotright': 556, 'guilsinglleft': 333, 'guilsinglright': 333, 'h': 556, 'hungarumlaut': 333, 'hyphen': 333, 'i': 222, 'iacute': 278, 'icircumflex': 278, 'idieresis': 278, 'igrave': 278, 'j': 222, 'k': 500, 'l': 222, 'less': 584, 'logicalnot': 584, 'lslash': 222, 'm': 833, 'macron': 333, 'minus': 584, 'mu': 556, 'multiply': 584, 'n': 556, 'nine': 556, 'ntilde': 556, 'numbersign': 556, 'o': 556, 'oacute': 556, 'ocircumflex': 556, 'odieresis': 556, 'oe': 944, 'ogonek': 333, 'ograve': 556, 'one': 556, 'onehalf': 834, 'onequarter': 834, 'onesuperior': 333, 'ordfeminine': 370, 'ordmasculine': 365, 'oslash': 611, 'otilde': 556, 'p': 556, 'paragraph': 537, 'parenleft': 333, 'parenright': 333, 'percent': 889, 'period': 278, 'periodcentered': 278, 'perthousand': 1000, 'plus': 584, 'plusminus': 584, 'q': 556, 'question': 556, 'questiondown': 611, 'quotedbl': 355, 'quotedblbase': 333, 'quotedblleft': 333, 'quotedblright': 333, 'quoteleft': 222, 'quoteright': 222, 'quotesinglbase': 222, 'quotesingle': 191, 'r': 333, 'registered': 737, 'ring': 333, 's': 500, 'scaron': 500, 'section': 556, 'semicolon': 278, 'seven': 556, 'six': 556, 'slash': 278, 'space': 278, 'sterling': 556, 't': 278, 'thorn': 556, 'three': 556, 'threequarters': 834, 'threesuperior': 333, 'tilde': 333, 'trademark': 1000, 'two': 556, 'twosuperior': 333, 'u': 556, 'uacute': 556, 'ucircumflex': 556, 'udieresis': 556, 'ugrave': 556, 'underscore': 556, 'v': 500, 'w': 722, 'x': 500, 'y': 500, 'yacute': 500, 'ydieresis': 500, 'yen': 556, 'z': 500, 'zcaron': 500, 'zero': 556}
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/pdfbase/_fontdata_widths_helveticaoblique.py
0.572245
0.290893
_fontdata_widths_helveticaoblique.py
pypi
from reportlab.platypus.flowables import Flowable from reportlab.lib.units import inch from string import ascii_lowercase, ascii_uppercase, digits as string_digits class Barcode(Flowable): """Abstract Base for barcodes. Includes implementations of some methods suitable for the more primitive barcode types""" fontName = 'Courier' fontSize = 12 humanReadable = 0 def _humanText(self): return self.encoded def __init__(self, value='',**kwd): self.value = str(value) self._setKeywords(**kwd) if not hasattr(self, 'gap'): self.gap = None def _calculate(self): self.validate() self.encode() self.decompose() self.computeSize() def _setKeywords(self,**kwd): for (k, v) in kwd.items(): setattr(self, k, v) def validate(self): self.valid = 1 self.validated = self.value def encode(self): self.encoded = self.validated def decompose(self): self.decomposed = self.encoded def computeSize(self, *args): barWidth = self.barWidth wx = barWidth * self.ratio if self.gap == None: self.gap = barWidth w = 0.0 for c in self.decomposed: if c in 'sb': w = w + barWidth elif c in 'SB': w = w + wx else: # 'i' w = w + self.gap if self.barHeight is None: self.barHeight = w * 0.15 self.barHeight = max(0.25 * inch, self.barHeight) if self.bearers: self.barHeight = self.barHeight + self.bearers * 2.0 * barWidth if self.quiet: w += self.lquiet + self.rquiet self._height = self.barHeight self._width = w def width(self): self._calculate() return self._width width = property(width) def height(self): self._calculate() return self._height height = property(height) def draw(self): self._calculate() barWidth = self.barWidth wx = barWidth * self.ratio left = self.quiet and self.lquiet or 0 b = self.bearers * barWidth bb = b * 0.5 tb = self.barHeight - (b * 1.5) for c in self.decomposed: if c == 'i': left = left + self.gap elif c == 's': left = left + barWidth elif c == 'S': left = left + wx elif c == 'b': self.rect(left, bb, barWidth, tb) left = left + barWidth elif c == 'B': self.rect(left, bb, wx, tb) left = left + wx if self.bearers: if getattr(self,'bearerBox', None): canv = self.canv if hasattr(canv,'_Gadd'): #this is a widget rect takes other arguments canv.rect(bb, bb, self.width, self.barHeight-b, strokeWidth=b, strokeColor=self.barFillColor or self.barStrokeColor, fillColor=None) else: canv.saveState() canv.setLineWidth(b) canv.rect(bb, bb, self.width, self.barHeight-b, stroke=1, fill=0) canv.restoreState() else: w = self._width - (self.lquiet + self.rquiet) self.rect(self.lquiet, 0, w, b) self.rect(self.lquiet, self.barHeight - b, w, b) self.drawHumanReadable() def drawHumanReadable(self): if self.humanReadable: #we have text from reportlab.pdfbase.pdfmetrics import getAscent, stringWidth s = str(self._humanText()) fontSize = self.fontSize fontName = self.fontName w = stringWidth(s,fontName,fontSize) width = self._width if self.quiet: width -= self.lquiet+self.rquiet x = self.lquiet else: x = 0 if w>width: fontSize *= width/float(w) y = 1.07*getAscent(fontName)*fontSize/1000. self.annotate(x+width/2.,-y,s,fontName,fontSize) def rect(self, x, y, w, h): self.canv.rect(x, y, w, h, stroke=0, fill=1) def annotate(self,x,y,text,fontName,fontSize,anchor='middle'): canv = self.canv canv.saveState() canv.setFont(self.fontName,fontSize) if anchor=='middle': func = 'drawCentredString' elif anchor=='end': func = 'drawRightString' else: func = 'drawString' getattr(canv,func)(x,y,text) canv.restoreState() def _checkVal(self, name, v, allowed): if v not in allowed: raise ValueError('%s attribute %s is invalid %r\nnot in allowed %r' % ( self.__class__.__name__, name, v, allowed)) return v class MultiWidthBarcode(Barcode): """Base for variable-bar-width codes like Code93 and Code128""" def computeSize(self, *args): barWidth = self.barWidth oa, oA = ord('a') - 1, ord('A') - 1 w = 0.0 for c in self.decomposed: oc = ord(c) if c in ascii_lowercase: w = w + barWidth * (oc - oa) elif c in ascii_uppercase: w = w + barWidth * (oc - oA) if self.barHeight is None: self.barHeight = w * 0.15 self.barHeight = max(0.25 * inch, self.barHeight) if self.quiet: w += self.lquiet + self.rquiet self._height = self.barHeight self._width = w def draw(self): self._calculate() oa, oA = ord('a') - 1, ord('A') - 1 barWidth = self.barWidth left = self.quiet and self.lquiet or 0 for c in self.decomposed: oc = ord(c) if c in ascii_lowercase: left = left + (oc - oa) * barWidth elif c in ascii_uppercase: w = (oc - oA) * barWidth self.rect(left, 0, w, self.barHeight) left += w self.drawHumanReadable() class I2of5(Barcode): """ Interleaved 2 of 5 is a numeric-only barcode. It encodes an even number of digits; if an odd number is given, a 0 is prepended. Options that may be passed to constructor: value (int, or numeric string required.): The value to encode. barWidth (float, default .0075): X-Dimension, or width of the smallest element Minumum is .0075 inch (7.5 mils). ratio (float, default 2.2): The ratio of wide elements to narrow elements. Must be between 2.0 and 3.0 (or 2.2 and 3.0 if the barWidth is greater than 20 mils (.02 inch)) gap (float or None, default None): width of intercharacter gap. None means "use barWidth". barHeight (float, see default below): Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol's length. checksum (bool, default 1): Whether to compute and include the check digit bearers (float, in units of barWidth. default 3.0): Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 3 x-dimensions. Set to zero for no bearer bars. (Bearer bars help detect misscans, so it is suggested to leave them on). bearerBox (bool default False) if true draw a true rectangle of width bearers around the barcode. quiet (bool, default 1): Whether to include quiet zones in the symbol. lquiet (float, see default below): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or .15 times the symbol's length. rquiet (float, defaults as above): Quiet zone size to right left of code, if quiet is true. stop (bool, default 1): Whether to include start/stop symbols. Sources of Information on Interleaved 2 of 5: http://www.semiconductor.agilent.com/barcode/sg/Misc/i_25.html http://www.adams1.com/pub/russadam/i25code.html Official Spec, "ANSI/AIM BC2-1995, USS" is available for US$45 from http://www.aimglobal.org/aimstore/ """ patterns = { 'start' : 'bsbs', 'stop' : 'Bsb', 'B0' : 'bbBBb', 'S0' : 'ssSSs', 'B1' : 'BbbbB', 'S1' : 'SsssS', 'B2' : 'bBbbB', 'S2' : 'sSssS', 'B3' : 'BBbbb', 'S3' : 'SSsss', 'B4' : 'bbBbB', 'S4' : 'ssSsS', 'B5' : 'BbBbb', 'S5' : 'SsSss', 'B6' : 'bBBbb', 'S6' : 'sSSss', 'B7' : 'bbbBB', 'S7' : 'sssSS', 'B8' : 'BbbBb', 'S8' : 'SssSs', 'B9' : 'bBbBb', 'S9' : 'sSsSs' } barHeight = None barWidth = inch * 0.0075 ratio = 2.2 checksum = 1 bearers = 3.0 bearerBox = False quiet = 1 lquiet = None rquiet = None stop = 1 def __init__(self, value='', **args): if type(value) == type(1): value = str(value) for k, v in args.items(): setattr(self, k, v) if self.quiet: if self.lquiet is None: self.lquiet = min(inch * 0.25, self.barWidth * 10.0) self.rquiet = min(inch * 0.25, self.barWidth * 10.0) else: self.lquiet = self.rquiet = 0.0 Barcode.__init__(self, value) def validate(self): vval = "" self.valid = 1 for c in self.value.strip(): if c not in string_digits: self.valid = 0 continue vval = vval + c self.validated = vval return vval def encode(self): s = self.validated cs = self.checksum c = len(s) #ensure len(result)%2 == 0, checksum included if ((c % 2 == 0) and cs) or ((c % 2 == 1) and not cs): s = '0' + s c += 1 if cs: c = 3*sum([int(s[i]) for i in range(0,c,2)])+sum([int(s[i]) for i in range(1,c,2)]) s += str((10 - c) % 10) self.encoded = s def decompose(self): dval = self.stop and [self.patterns['start']] or [] a = dval.append for i in range(0, len(self.encoded), 2): b = self.patterns['B' + self.encoded[i]] s = self.patterns['S' + self.encoded[i+1]] for i in range(0, len(b)): a(b[i] + s[i]) if self.stop: a(self.patterns['stop']) self.decomposed = ''.join(dval) return self.decomposed class MSI(Barcode): """ MSI is a numeric-only barcode. Options that may be passed to constructor: value (int, or numeric string required.): The value to encode. barWidth (float, default .0075): X-Dimension, or width of the smallest element ratio (float, default 2.2): The ratio of wide elements to narrow elements. gap (float or None, default None): width of intercharacter gap. None means "use barWidth". barHeight (float, see default below): Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol's length. checksum (bool, default 1): Wether to compute and include the check digit bearers (float, in units of barWidth. default 0): Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 0 (no bearers). lquiet (float, see default below): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or 10 barWidths. rquiet (float, defaults as above): Quiet zone size to right left of code, if quiet is true. stop (bool, default 1): Whether to include start/stop symbols. Sources of Information on MSI Bar Code: http://www.semiconductor.agilent.com/barcode/sg/Misc/msi_code.html http://www.adams1.com/pub/russadam/plessy.html """ patterns = { 'start' : 'Bs', 'stop' : 'bSb', '0' : 'bSbSbSbS', '1' : 'bSbSbSBs', '2' : 'bSbSBsbS', '3' : 'bSbSBsBs', '4' : 'bSBsbSbS', '5' : 'bSBsbSBs', '6' : 'bSBsBsbS', '7' : 'bSBsBsBs', '8' : 'BsbSbSbS', '9' : 'BsbSbSBs' } stop = 1 barHeight = None barWidth = inch * 0.0075 ratio = 2.2 checksum = 1 bearers = 0.0 quiet = 1 lquiet = None rquiet = None def __init__(self, value="", **args): if type(value) == type(1): value = str(value) for k, v in args.items(): setattr(self, k, v) if self.quiet: if self.lquiet is None: self.lquiet = max(inch * 0.25, self.barWidth * 10.0) self.rquiet = max(inch * 0.25, self.barWidth * 10.0) else: self.lquiet = self.rquiet = 0.0 Barcode.__init__(self, value) def validate(self): vval = "" self.valid = 1 for c in self.value.strip(): if c not in string_digits: self.valid = 0 continue vval = vval + c self.validated = vval return vval def encode(self): s = self.validated if self.checksum: c = '' for i in range(1, len(s), 2): c = c + s[i] d = str(int(c) * 2) t = 0 for c in d: t = t + int(c) for i in range(0, len(s), 2): t = t + int(s[i]) c = 10 - (t % 10) s = s + str(c) self.encoded = s def decompose(self): dval = self.stop and [self.patterns['start']] or [] dval += [self.patterns[c] for c in self.encoded] if self.stop: dval.append(self.patterns['stop']) self.decomposed = ''.join(dval) return self.decomposed class Codabar(Barcode): """ Codabar is a numeric plus some puntuation ("-$:/.+") barcode with four start/stop characters (A, B, C, and D). Options that may be passed to constructor: value (string required.): The value to encode. barWidth (float, default .0065): X-Dimension, or width of the smallest element minimum is 6.5 mils (.0065 inch) ratio (float, default 2.0): The ratio of wide elements to narrow elements. gap (float or None, default None): width of intercharacter gap. None means "use barWidth". barHeight (float, see default below): Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol's length. checksum (bool, default 0): Whether to compute and include the check digit bearers (float, in units of barWidth. default 0): Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 0 (no bearers). quiet (bool, default 1): Whether to include quiet zones in the symbol. stop (bool, default 1): Whether to include start/stop symbols. lquiet (float, see default below): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or 10 barWidth rquiet (float, defaults as above): Quiet zone size to right left of code, if quiet is true. Sources of Information on Codabar http://www.semiconductor.agilent.com/barcode/sg/Misc/codabar.html http://www.barcodeman.com/codabar.html Official Spec, "ANSI/AIM BC3-1995, USS" is available for US$45 from http://www.aimglobal.org/aimstore/ """ patterns = { '0': 'bsbsbSB', '1': 'bsbsBSb', '2': 'bsbSbsB', '3': 'BSbsbsb', '4': 'bsBsbSb', '5': 'BsbsbSb', '6': 'bSbsbsB', '7': 'bSbsBsb', '8': 'bSBsbsb', '9': 'BsbSbsb', '-': 'bsbSBsb', '$': 'bsBSbsb', ':': 'BsbsBsB', '/': 'BsBsbsB', '.': 'BsBsBsb', '+': 'bsBsBsB', 'A': 'bsBSbSb', 'B': 'bSbSbsB', 'C': 'bsbSbSB', 'D': 'bsbSBSb' } values = { '0' : 0, '1' : 1, '2' : 2, '3' : 3, '4' : 4, '5' : 5, '6' : 6, '7' : 7, '8' : 8, '9' : 9, '-' : 10, '$' : 11, ':' : 12, '/' : 13, '.' : 14, '+' : 15, 'A' : 16, 'B' : 17, 'C' : 18, 'D' : 19 } chars = string_digits + "-$:/.+" stop = 1 barHeight = None barWidth = inch * 0.0065 ratio = 2.0 # XXX ? checksum = 0 bearers = 0.0 quiet = 1 lquiet = None rquiet = None def __init__(self, value='', **args): if type(value) == type(1): value = str(value) for k, v in args.items(): setattr(self, k, v) if self.quiet: if self.lquiet is None: self.lquiet = min(inch * 0.25, self.barWidth * 10.0) self.rquiet = min(inch * 0.25, self.barWidth * 10.0) else: self.lquiet = self.rquiet = 0.0 Barcode.__init__(self, value) def validate(self): vval = "" self.valid = 1 s = self.value.strip() for i in range(0, len(s)): c = s[i] if c not in self.chars: if ((i != 0) and (i != len(s) - 1)) or (c not in 'ABCD'): self.Valid = 0 continue vval = vval + c if self.stop: if vval[0] not in 'ABCD': vval = 'A' + vval if vval[-1] not in 'ABCD': vval = vval + vval[0] self.validated = vval return vval def encode(self): s = self.validated if self.checksum: v = sum([self.values[c] for c in s]) s += self.chars[v % 16] self.encoded = s def decompose(self): dval = ''.join([self.patterns[c]+'i' for c in self.encoded]) self.decomposed = dval[:-1] return self.decomposed class Code11(Barcode): """ Code 11 is an almost-numeric barcode. It encodes the digits 0-9 plus dash ("-"). 11 characters total, hence the name. value (int or string required.): The value to encode. barWidth (float, default .0075): X-Dimension, or width of the smallest element ratio (float, default 2.2): The ratio of wide elements to narrow elements. gap (float or None, default None): width of intercharacter gap. None means "use barWidth". barHeight (float, see default below): Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol's length. checksum (0 none, 1 1-digit, 2 2-digit, -1 auto, default -1): How many checksum digits to include. -1 ("auto") means 1 if the number of digits is 10 or less, else 2. bearers (float, in units of barWidth. default 0): Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 0 (no bearers). quiet (bool, default 1): Wether to include quiet zones in the symbol. lquiet (float, see default below): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or 10 barWidth rquiet (float, defaults as above): Quiet zone size to right left of code, if quiet is true. Sources of Information on Code 11: http://www.cwi.nl/people/dik/english/codes/barcodes.html """ chars = '0123456789-' patterns = { '0' : 'bsbsB', '1' : 'BsbsB', '2' : 'bSbsB', '3' : 'BSbsb', '4' : 'bsBsB', '5' : 'BsBsb', '6' : 'bSBsb', '7' : 'bsbSB', '8' : 'BsbSb', '9' : 'Bsbsb', '-' : 'bsBsb', 'S' : 'bsBSb' # Start/Stop } values = { '0' : 0, '1' : 1, '2' : 2, '3' : 3, '4' : 4, '5' : 5, '6' : 6, '7' : 7, '8' : 8, '9' : 9, '-' : 10, } stop = 1 barHeight = None barWidth = inch * 0.0075 ratio = 2.2 # XXX ? checksum = -1 # Auto bearers = 0.0 quiet = 1 lquiet = None rquiet = None def __init__(self, value='', **args): if type(value) == type(1): value = str(value) for k, v in args.items(): setattr(self, k, v) if self.quiet: if self.lquiet is None: self.lquiet = min(inch * 0.25, self.barWidth * 10.0) self.rquiet = min(inch * 0.25, self.barWidth * 10.0) else: self.lquiet = self.rquiet = 0.0 Barcode.__init__(self, value) def validate(self): vval = "" self.valid = 1 s = self.value.strip() for i in range(0, len(s)): c = s[i] if c not in self.chars: self.Valid = 0 continue vval = vval + c self.validated = vval return vval def _addCSD(self,s,m): # compute first checksum i = c = 0 v = 1 V = self.values while i < len(s): c += v * V[s[-(i+1)]] i += 1 v += 1 if v==m: v = 1 return s+self.chars[c % 11] def encode(self): s = self.validated tcs = self.checksum if tcs<0: self.checksum = tcs = 1+int(len(s)>10) if tcs > 0: s = self._addCSD(s,11) if tcs > 1: s = self._addCSD(s,10) self.encoded = self.stop and ('S' + s + 'S') or s def decompose(self): self.decomposed = ''.join([(self.patterns[c]+'i') for c in self.encoded])[:-1] return self.decomposed def _humanText(self): return self.stop and self.encoded[1:-1] or self.encoded
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/barcode/common.py
0.583085
0.304462
common.py
pypi
from reportlab.lib.units import inch from reportlab.lib.utils import asNative from reportlab.graphics.barcode.common import MultiWidthBarcode _patterns = { '0' : ('AcAaAb', 0), '1' : ('AaAbAc', 1), '2' : ('AaAcAb', 2), '3' : ('AaAdAa', 3), '4' : ('AbAaAc', 4), '5' : ('AbAbAb', 5), '6' : ('AbAcAa', 6), '7' : ('AaAaAd', 7), '8' : ('AcAbAa', 8), '9' : ('AdAaAa', 9), 'A' : ('BaAaAc', 10), 'B' : ('BaAbAb', 11), 'C' : ('BaAcAa', 12), 'D' : ('BbAaAb', 13), 'E' : ('BbAbAa', 14), 'F' : ('BcAaAa', 15), 'G' : ('AaBaAc', 16), 'H' : ('AaBbAb', 17), 'I' : ('AaBcAa', 18), 'J' : ('AbBaAb', 19), 'K' : ('AcBaAa', 20), 'L' : ('AaAaBc', 21), 'M' : ('AaAbBb', 22), 'N' : ('AaAcBa', 23), 'O' : ('AbAaBb', 24), 'P' : ('AcAaBa', 25), 'Q' : ('BaBaAb', 26), 'R' : ('BaBbAa', 27), 'S' : ('BaAaBb', 28), 'T' : ('BaAbBa', 29), 'U' : ('BbAaBa', 30), 'V' : ('BbBaAa', 31), 'W' : ('AaBaBb', 32), 'X' : ('AaBbBa', 33), 'Y' : ('AbBaBa', 34), 'Z' : ('AbCaAa', 35), '-' : ('AbAaCa', 36), '.' : ('CaAaAb', 37), ' ' : ('CaAbAa', 38), '$' : ('CbAaAa', 39), '/' : ('AaBaCa', 40), '+' : ('AaCaBa', 41), '%' : ('BaAaCa', 42), '#' : ('AbAbBa', 43), '!' : ('CaBaAa', 44), '=' : ('CaAaBa', 45), '&' : ('AbBbAa', 46), 'start' : ('AaAaDa', -1), 'stop' : ('AaAaDaA', -2) } _charsbyval = {} for k, v in _patterns.items(): _charsbyval[v[1]] = k _extended = { '\x00' : '!U', '\x01' : '#A', '\x02' : '#B', '\x03' : '#C', '\x04' : '#D', '\x05' : '#E', '\x06' : '#F', '\x07' : '#G', '\x08' : '#H', '\x09' : '#I', '\x0a' : '#J', '\x0b' : '#K', '\x0c' : '#L', '\x0d' : '#M', '\x0e' : '#N', '\x0f' : '#O', '\x10' : '#P', '\x11' : '#Q', '\x12' : '#R', '\x13' : '#S', '\x14' : '#T', '\x15' : '#U', '\x16' : '#V', '\x17' : '#W', '\x18' : '#X', '\x19' : '#Y', '\x1a' : '#Z', '\x1b' : '!A', '\x1c' : '!B', '\x1d' : '!C', '\x1e' : '!D', '\x1f' : '!E', '!' : '=A', '"' : '=B', '#' : '=C', '$' : '=D', '%' : '=E', '&' : '=F', '\'' : '=G', '(' : '=H', ')' : '=I', '*' : '=J', '+' : '=K', ',' : '=L', '/' : '=O', ':' : '=Z', ';' : '!F', '<' : '!G', '=' : '!H', '>' : '!I', '?' : '!J', '@' : '!V', '[' : '!K', '\\' : '!L', ']' : '!M', '^' : '!N', '_' : '!O', '`' : '!W', 'a' : '&A', 'b' : '&B', 'c' : '&C', 'd' : '&D', 'e' : '&E', 'f' : '&F', 'g' : '&G', 'h' : '&H', 'i' : '&I', 'j' : '&J', 'k' : '&K', 'l' : '&L', 'm' : '&M', 'n' : '&N', 'o' : '&O', 'p' : '&P', 'q' : '&Q', 'r' : '&R', 's' : '&S', 't' : '&T', 'u' : '&U', 'v' : '&V', 'w' : '&W', 'x' : '&X', 'y' : '&Y', 'z' : '&Z', '{' : '!P', '|' : '!Q', '}' : '!R', '~' : '!S', '\x7f' : '!T' } def _encode93(str): s = list(str) s.reverse() # compute 'C' checksum i = 0; v = 1; c = 0 while i < len(s): c = c + v * _patterns[s[i]][1] i = i + 1; v = v + 1 if v > 20: v = 1 s.insert(0, _charsbyval[c % 47]) # compute 'K' checksum i = 0; v = 1; c = 0 while i < len(s): c = c + v * _patterns[s[i]][1] i = i + 1; v = v + 1 if v > 15: v = 1 s.insert(0, _charsbyval[c % 47]) s.reverse() return ''.join(s) class _Code93Base(MultiWidthBarcode): barWidth = inch * 0.0075 lquiet = None rquiet = None quiet = 1 barHeight = None stop = 1 def __init__(self, value='', **args): if type(value) is type(1): value = asNative(value) for (k, v) in args.items(): setattr(self, k, v) if self.quiet: if self.lquiet is None: self.lquiet = max(inch * 0.25, self.barWidth * 10.0) self.rquiet = max(inch * 0.25, self.barWidth * 10.0) else: self.lquiet = self.rquiet = 0.0 MultiWidthBarcode.__init__(self, value) def decompose(self): dval = self.stop and [_patterns['start'][0]] or [] dval += [_patterns[c][0] for c in self.encoded] if self.stop: dval.append(_patterns['stop'][0]) self.decomposed = ''.join(dval) return self.decomposed class Standard93(_Code93Base): """ Code 93 is a Uppercase alphanumeric symbology with some punctuation. See Extended Code 93 for a variant that can represent the entire 128 characrter ASCII set. Options that may be passed to constructor: value (int, or numeric string. required.): The value to encode. barWidth (float, default .0075): X-Dimension, or width of the smallest element Minumum is .0075 inch (7.5 mils). barHeight (float, see default below): Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol's length. quiet (bool, default 1): Wether to include quiet zones in the symbol. lquiet (float, see default below): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or 10 barWidth rquiet (float, defaults as above): Quiet zone size to right left of code, if quiet is true. stop (bool, default 1): Whether to include start/stop symbols. Sources of Information on Code 93: http://www.semiconductor.agilent.com/barcode/sg/Misc/code_93.html Official Spec, "NSI/AIM BC5-1995, USS" is available for US$45 from http://www.aimglobal.org/aimstore/ """ def validate(self): vval = "" self.valid = 1 for c in self.value.upper(): if c not in _patterns: self.valid = 0 continue vval = vval + c self.validated = vval return vval def encode(self): self.encoded = _encode93(self.validated) return self.encoded class Extended93(_Code93Base): """ Extended Code 93 is a convention for encoding the entire 128 character set using pairs of characters to represent the characters missing in Standard Code 93. It is very much like Extended Code 39 in that way. See Standard93 for arguments. """ def validate(self): vval = [] self.valid = 1 a = vval.append for c in self.value: if c not in _patterns and c not in _extended: self.valid = 0 continue a(c) self.validated = ''.join(vval) return self.validated def encode(self): self.encoded = "" for c in self.validated: if c in _patterns: self.encoded = self.encoded + c elif c in _extended: self.encoded = self.encoded + _extended[c] else: raise ValueError self.encoded = _encode93(self.encoded) return self.encoded def _humanText(self): return self.validated+self.encoded[-2:]
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/barcode/code93.py
0.510008
0.449332
code93.py
pypi
import re import itertools try: from itertools import zip_longest except: from itertools import izip_longest as zip_longest try: unicode except NameError: # No unicode in Python 3 unicode = str class QR: valid = None bits = None group = 0 def __init__(self, data): if self.valid and not self.valid(data): raise ValueError self.data = data def __len__(self): return len(self.data) @property def bitlength(self): if self.bits is None: return 0 q, r = divmod(len(self), len(self.bits)) return q * sum(self.bits) + sum(self.bits[:r]) def getLengthBits(self, ver): if 0 < ver < 10: return self.lengthbits[0] elif ver < 27: return self.lengthbits[1] elif ver < 41: return self.lengthbits[2] raise ValueError("Unknown version: " + ver) def getLength(self): return len(self.data) def __repr__(self): return repr(self.data) def write_header(self, buffer, version): buffer.put(self.mode, 4) lenbits = self.getLengthBits(version) if lenbits: buffer.put(len(self.data), lenbits ) def write(self, buffer, version): self.write_header(buffer, version) for g in zip_longest(*[iter(self.data)] * self.group): bits = 0 n = 0 for i in range(self.group): if g[i] is not None: n *= len(self.chars) n += self.chars.index(g[i]) bits += self.bits[i] buffer.put(n, bits) class QRNumber(QR): valid = re.compile(u'[0-9]*$').match chars = u'0123456789' bits = (4,3,3) group = 3 mode = 0x1 lengthbits = (10, 12, 14) class QRAlphaNum(QR): valid = re.compile(u'[-0-9A-Z $%*+./:]*$').match chars = u'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:' bits = (6,5) group = 2 mode = 0x2 lengthbits = (9, 11, 13) class QR8bitByte(QR): bits = (8,) group = 1 mode = 0x4 lengthbits = (8, 16, 16) def __init__(self, data): if isinstance(data, unicode): self.data = data.encode('utf-8') # XXX This really needs an ECI too else: self.data = data # It'd better be byte data def write(self, buffer, version): self.write_header(buffer, version) for c in self.data: if isinstance(c, str): c = ord(c) buffer.put(c, 8) class QRKanji(QR): bits = (13,) group = 1 mode = 0x8 lengthbits = (8, 10, 12) def __init__(self, data): try: self.data = self.unicode_to_qrkanji(data) except UnicodeEncodeError: raise ValueError('Not valid kanji') def unicode_to_qrkanji(self, data): codes = [] for i,c in enumerate(data): try: c = c.encode('shift-jis') try: c,d = map(ord, c) except TypeError: # Python 3 c,d = c except UnicodeEncodeError as e: raise UnicodeEncodeError('qrkanji', data, i, i+1, e.args[4]) except ValueError: raise UnicodeEncodeError('qrkanji', data, i, i+1, 'illegal multibyte sequence') c = c << 8 | d if 0x8140 <= c <=0x9ffc: c -= 0x8140 c = (((c & 0xff00) >> 8) * 0xc0) + (c & 0xff) elif 0xe040 <= c <= 0xebbf: c -= 0xc140 c = (((c & 0xff00) >> 8) * 0xc0) + (c & 0xff) else: raise UnicodeEncodeError('qrkanji', data, i, i+1, 'illegal multibyte sequence') codes.append(c) return codes def write(self, buffer, version): self.write_header(buffer, version) for d in self.data: buffer.put(d, 13) class QRHanzi(QR): bits = (13,) group = 1 mode = 0xD lengthbits = (8, 10, 12) def __init__(self, data): try: self.data = self.unicode_to_qrhanzi(data) except UnicodeEncodeError: raise ValueError('Not valid hanzi') def unicode_to_qrhanzi(self, data): codes = [] for i,c in enumerate(data): try: c = c.encode('gb2312') try: c,d = map(ord, c) except TypeError: # Python 3 c,d = c except UnicodeEncodeError as e: raise UnicodeEncodeError('qrhanzi', data, i, i+1, e.args[4]) except ValueError: raise UnicodeEncodeError('qrhanzi', data, i, i+1, 'illegal multibyte sequence') c = c << 8 | d if 0xa1a1 <= c <=0xaafe: c -= 0xa1a1 c = (((c & 0xff00) >> 8) * 0x60) + (c & 0xff) elif 0xb0a1 <= c <= 0xfafe: c -= 0xa6a1 c = (((c & 0xff00) >> 8) * 0x60) + (c & 0xff) else: raise UnicodeEncodeError('qrhanzi', data, i, i+1, 'illegal multibyte sequence') codes.append(c) return codes def write_header(self, buffer, version): buffer.put(self.mode, 4) buffer.put(1, 4) # Subset 1: GB2312 encoding lenbits = self.getLengthBits(version) if lenbits: buffer.put(len(self.data), lenbits ) def write(self, buffer, version): self.write_header(buffer, version) for d in self.data: buffer.put(d, 13) # Special modes class QRECI(QR): mode = 0x7 lengthbits = (0, 0, 0) def __init__(self, data): if not 0 < data < 999999: # Spec says 999999, format supports up to 0x1fffff = 2097151 raise ValueError("ECI out of range") self.data = data def write(self, buffer, version): self.write_header(buffer, version) if self.data <= 0x7f: buffer.put(self.data, 8) elif self.data <= 0x3fff: buffer.put(self.data | 0x8000, 16) elif self.data <= 0x1fffff: buffer.put(self.data | 0xC00000, 24) class QRStructAppend(QR): mode = 0x3 lengthbits = (0, 0, 0) def __init__(self, part, total, parity): if not 0 < part <= 16: raise ValueError("part out of range [1,16]") if not 0 < total <= 16: raise ValueError("total out of range [1,16]") self.part = part self.total = total self.parity = parity def write(self, buffer, version): self.write_header(buffer, version) buffer.put(self.part, 4) buffer.put(self.total, 4) buffer.put(self.parity, 8) class QRFNC1First(QR): mode = 0x5 lengthbits = (0, 0, 0) def __init__(self): pass def write(self, buffer, version): self.write_header(buffer, version) class QRFNC1Second(QR): valid = re.compile('^([A-Za-z]|[0-9][0-9])$').match mode = 0x9 lengthbits = (0, 0, 0) def write(self, buffer, version): self.write_header(buffer, version) d = self.data if len(d) == 1: d = ord(d) + 100 else: d = int(d) buffer.put(d, 8) class QRCode: def __init__(self, version, errorCorrectLevel): self.version = version self.errorCorrectLevel = errorCorrectLevel self.modules = None self.moduleCount = 0 self.dataCache = None self.dataList = [] def addData(self, data): if isinstance(data, QR): newData = data else: for conv in (QRNumber, QRAlphaNum, QRKanji, QR8bitByte): try: newData = conv(data) break except ValueError: pass else: raise ValueError self.dataList.append(newData) self.dataCache = None def isDark(self, row, col): return self.modules[row][col] def getModuleCount(self): return self.moduleCount def calculate_version(self): # Calculate version for data to fit the QR Code capacity for version in range(1, 40): rsBlocks = QRRSBlock.getRSBlocks(version, self.errorCorrectLevel) totalDataCount = sum(block.dataCount for block in rsBlocks) length = 0 for data in self.dataList: length += 4 length += data.getLengthBits(version) length += data.bitlength if length <= totalDataCount * 8: break return version def make(self): if self.version is None: self.version = self.calculate_version() self.makeImpl(False, self.getBestMaskPattern()) def makeImpl(self, test, maskPattern): self.moduleCount = self.version * 4 + 17 self.modules = [ [False] * self.moduleCount for x in range(self.moduleCount) ] self.setupPositionProbePattern(0, 0) self.setupPositionProbePattern(self.moduleCount - 7, 0) self.setupPositionProbePattern(0, self.moduleCount - 7) self.setupPositionAdjustPattern() self.setupTimingPattern() self.setupTypeInfo(test, maskPattern) if (self.version >= 7): self.setupTypeNumber(test) if (self.dataCache == None): self.dataCache = QRCode.createData(self.version, self.errorCorrectLevel, self.dataList) self.mapData(self.dataCache, maskPattern) _positionProbePattern = [ [True, True, True, True, True, True, True], [True, False, False, False, False, False, True], [True, False, True, True, True, False, True], [True, False, True, True, True, False, True], [True, False, True, True, True, False, True], [True, False, False, False, False, False, True], [True, True, True, True, True, True, True], ] def setupPositionProbePattern(self, row, col): if row == 0: self.modules[row+7][col:col+7] = [False] * 7 if col == 0: self.modules[row+7][col+7] = False else: self.modules[row+7][col-1] = False else: # col == 0 self.modules[row-1][col:col+8] = [False] * 8 for r, data in enumerate(self._positionProbePattern): self.modules[row+r][col:col+7] = data if col == 0: self.modules[row+r][col+7] = False else: self.modules[row+r][col-1] = False def getBestMaskPattern(self): minLostPoint = 0 pattern = 0 for i in range(8): self.makeImpl(True, i); lostPoint = QRUtil.getLostPoint(self); if (i == 0 or minLostPoint > lostPoint): minLostPoint = lostPoint pattern = i return pattern def setupTimingPattern(self): for r in range(8, self.moduleCount - 8): self.modules[r][6] = (r % 2 == 0) self.modules[6][8:self.moduleCount - 8] = itertools.islice( itertools.cycle([True, False]), self.moduleCount - 16) _positionAdjustPattern = [ [True, True, True, True, True], [True, False, False, False, True], [True, False, True, False, True], [True, False, False, False, True], [True, True, True, True, True], ] def setupPositionAdjustPattern(self): pos = QRUtil.getPatternPosition(self.version) maxpos = self.moduleCount - 8 for row, col in itertools.product(pos, pos): if col <= 8 and (row <= 8 or row >= maxpos): continue elif col >= maxpos and row <= 8: continue for r, data in enumerate(self._positionAdjustPattern): self.modules[row + r - 2][col-2:col+3] = data def setupTypeNumber(self, test): bits = QRUtil.getBCHTypeNumber(self.version) for i in range(18): mod = (not test and ( (bits >> i) & 1) == 1) self.modules[i // 3][i % 3 + self.moduleCount - 8 - 3] = mod; for i in range(18): mod = (not test and ( (bits >> i) & 1) == 1) self.modules[i % 3 + self.moduleCount - 8 - 3][i // 3] = mod; def setupTypeInfo(self, test, maskPattern): data = (self.errorCorrectLevel << 3) | maskPattern bits = QRUtil.getBCHTypeInfo(data) # vertical for i in range(15): mod = (not test and ( (bits >> i) & 1) == 1) if (i < 6): self.modules[i][8] = mod elif (i < 8): self.modules[i + 1][8] = mod else: self.modules[self.moduleCount - 15 + i][8] = mod # horizontal for i in range(15): mod = (not test and ( (bits >> i) & 1) == 1); if (i < 8): self.modules[8][self.moduleCount - i - 1] = mod elif (i < 9): self.modules[8][15 - i - 1 + 1] = mod else: self.modules[8][15 - i - 1] = mod # fixed module self.modules[self.moduleCount - 8][8] = (not test) def _dataPosIterator(self): cols = itertools.chain(range(self.moduleCount - 1, 6, -2), range(5, 0, -2)) rows = (list(range(9, self.moduleCount - 8)), list(itertools.chain(range(6), range(7, self.moduleCount))), list(range(9, self.moduleCount))) rrows = tuple( list(reversed(r)) for r in rows) ppos = QRUtil.getPatternPosition(self.version) ppos = set(itertools.chain.from_iterable( (p-2, p-1, p, p+1, p+2) for p in ppos)) maxpos = self.moduleCount - 11 for col in cols: rows, rrows = rrows, rows if col <= 8: rowidx = 0 elif col >= self.moduleCount - 8: rowidx = 2 else: rowidx = 1 for row in rows[rowidx]: for c in range(2): c = col - c if self.version >= 7: if row < 6 and c >= self.moduleCount - 11: continue elif col < 6 and row >= self.moduleCount - 11: continue if row in ppos and c in ppos: if not (row < 11 and (c < 11 or c > maxpos) or c < 11 and (row < 11 or row > maxpos)): continue yield (c, row) _dataPosList = None def dataPosIterator(self): if not self._dataPosList: self._dataPosList = list(self._dataPosIterator()) return self._dataPosList def _dataBitIterator(self, data): for byte in data: for bit in [0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01]: yield bool(byte & bit) _dataBitList = None def dataBitIterator(self, data): if not self._dataBitList: self._dataBitList = list(self._dataBitIterator(data)) return iter(self._dataBitList) def mapData(self, data, maskPattern): bits = self.dataBitIterator(data) mask = QRUtil.getMask(maskPattern) for (col, row), dark in zip_longest(self.dataPosIterator(), bits, fillvalue=False): self.modules[row][col] = dark ^ mask(row, col) PAD0 = 0xEC PAD1 = 0x11 @staticmethod def createData(version, errorCorrectLevel, dataList): rsBlocks = QRRSBlock.getRSBlocks(version, errorCorrectLevel) buffer = QRBitBuffer(); for data in dataList: data.write(buffer, version) # calc num max data. totalDataCount = 0; for block in rsBlocks: totalDataCount += block.dataCount if (buffer.getLengthInBits() > totalDataCount * 8): raise Exception("code length overflow. (%d > %d)" % (buffer.getLengthInBits(), totalDataCount * 8)) # end code if (buffer.getLengthInBits() + 4 <= totalDataCount * 8): buffer.put(0, 4) # padding while (buffer.getLengthInBits() % 8 != 0): buffer.putBit(False) # padding while (True): if (buffer.getLengthInBits() >= totalDataCount * 8): break buffer.put(QRCode.PAD0, 8) if (buffer.getLengthInBits() >= totalDataCount * 8): break buffer.put(QRCode.PAD1, 8) return QRCode.createBytes(buffer, rsBlocks) @staticmethod def createBytes(buffer, rsBlocks): offset = 0 maxDcCount = 0 maxEcCount = 0 totalCodeCount = 0 dcdata = [] ecdata = [] for block in rsBlocks: totalCodeCount += block.totalCount dcCount = block.dataCount ecCount = block.totalCount - dcCount maxDcCount = max(maxDcCount, dcCount) maxEcCount = max(maxEcCount, ecCount) dcdata.append(buffer.buffer[offset:offset+dcCount]) offset += dcCount rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount) rawPoly = QRPolynomial(dcdata[-1], rsPoly.getLength() - 1) modPoly = rawPoly.mod(rsPoly) rLen = rsPoly.getLength() - 1 mLen = modPoly.getLength() ecdata.append([ (modPoly.get(i) if i >= 0 else 0) for i in range(mLen - rLen, mLen) ]) data = [ d for dd in itertools.chain( zip_longest(*dcdata), zip_longest(*ecdata)) for d in dd if d is not None] return data class QRErrorCorrectLevel: L = 1 M = 0 Q = 3 H = 2 class QRMaskPattern: PATTERN000 = 0 PATTERN001 = 1 PATTERN010 = 2 PATTERN011 = 3 PATTERN100 = 4 PATTERN101 = 5 PATTERN110 = 6 PATTERN111 = 7 class QRUtil: PATTERN_POSITION_TABLE = [ [], [6, 18], [6, 22], [6, 26], [6, 30], [6, 34], [6, 22, 38], [6, 24, 42], [6, 26, 46], [6, 28, 50], [6, 30, 54], [6, 32, 58], [6, 34, 62], [6, 26, 46, 66], [6, 26, 48, 70], [6, 26, 50, 74], [6, 30, 54, 78], [6, 30, 56, 82], [6, 30, 58, 86], [6, 34, 62, 90], [6, 28, 50, 72, 94], [6, 26, 50, 74, 98], [6, 30, 54, 78, 102], [6, 28, 54, 80, 106], [6, 32, 58, 84, 110], [6, 30, 58, 86, 114], [6, 34, 62, 90, 118], [6, 26, 50, 74, 98, 122], [6, 30, 54, 78, 102, 126], [6, 26, 52, 78, 104, 130], [6, 30, 56, 82, 108, 134], [6, 34, 60, 86, 112, 138], [6, 30, 58, 86, 114, 142], [6, 34, 62, 90, 118, 146], [6, 30, 54, 78, 102, 126, 150], [6, 24, 50, 76, 102, 128, 154], [6, 28, 54, 80, 106, 132, 158], [6, 32, 58, 84, 110, 136, 162], [6, 26, 54, 82, 110, 138, 166], [6, 30, 58, 86, 114, 142, 170] ] G15 = ((1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0)) G18 = ((1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0)) G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1) @staticmethod def getBCHTypeInfo(data): d = data << 10; while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) >= 0): d ^= (QRUtil.G15 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) ) ) return ( (data << 10) | d) ^ QRUtil.G15_MASK @staticmethod def getBCHTypeNumber(data): d = data << 12; while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) >= 0): d ^= (QRUtil.G18 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) ) ) return (data << 12) | d @staticmethod def getBCHDigit(data): digit = 0; while (data != 0): digit += 1 data >>= 1 return digit @staticmethod def getPatternPosition(version): return QRUtil.PATTERN_POSITION_TABLE[version - 1] maskPattern = { 0: lambda i,j: (i + j) % 2 == 0, 1: lambda i,j: i % 2 == 0, 2: lambda i,j: j % 3 == 0, 3: lambda i,j: (i + j) % 3 == 0, 4: lambda i,j: (i // 2 + j // 3) % 2 == 0, 5: lambda i,j: (i*j)%2 + (i*j)%3 == 0, 6: lambda i,j: ( (i * j) % 2 + (i * j) % 3) % 2 == 0, 7: lambda i,j: ( (i * j) % 3 + (i + j) % 2) % 2 == 0 } @classmethod def getMask(cls, maskPattern): return cls.maskPattern[maskPattern] @staticmethod def getErrorCorrectPolynomial(errorCorrectLength): a = QRPolynomial([1], 0); for i in range(errorCorrectLength): a = a.multiply(QRPolynomial([1, QRMath.gexp(i)], 0) ) return a @classmethod def maskScoreRule1vert(cls, modules): score = 0 lastCount = [0] lastRow = None for row in modules: # Vertical patterns if lastRow: changed = [a ^ b for a,b in zip(row, lastRow)] scores = [a and (b-4+3) for a,b in zip_longest(changed, lastCount, fillvalue=0) if b >= 4] score += sum(scores) lastCount = [0 if a else b + 1 for a,b in zip_longest(changed, lastCount, fillvalue=0)] lastRow = row score += sum([b-4+3 for b in lastCount if b >= 4]) # final counts return score @classmethod def maskScoreRule2(cls, modules): score = 0 lastRow = modules[0] for row in modules[1:]: lastCol0, lastCol1 = row[0], lastRow[0] for col0, col1 in zip(row[1:], lastRow[1:]): if col0 == col1 == lastCol0 == lastCol1: score += 3 lastCol0, lastCol1 = col0, col1 lastRow = row return score @classmethod def maskScoreRule3hor( cls, modules, pattern = [True, False, True, True, True, False, True, False, False, False, False]): patternlen = len(pattern) score = 0 for row in modules: j = 0 maxj = len(row) - patternlen while j < maxj: if row[j:j+patternlen] == pattern: score += 40 j += patternlen else: j += 1 return score @classmethod def maskScoreRule4(cls, modules): cellCount = len(modules)**2 count = sum(sum(row) for row in modules) return 10 * (abs(100 * count // cellCount - 50) // 5) @classmethod def getLostPoint(cls, qrCode): lostPoint = 0; # LEVEL1 lostPoint += cls.maskScoreRule1vert(qrCode.modules) lostPoint += cls.maskScoreRule1vert(zip(*qrCode.modules)) # LEVEL2 lostPoint += cls.maskScoreRule2(qrCode.modules) # LEVEL3 lostPoint += cls.maskScoreRule3hor(qrCode.modules) lostPoint += cls.maskScoreRule3hor(zip(*qrCode.modules)) # LEVEL4 lostPoint += cls.maskScoreRule4(qrCode.modules) return lostPoint class QRMath: @staticmethod def glog(n): if (n < 1): raise Exception("glog(" + n + ")") return LOG_TABLE[n]; @staticmethod def gexp(n): while n < 0: n += 255 while n >= 256: n -= 255 return EXP_TABLE[n]; EXP_TABLE = [x for x in range(256)] LOG_TABLE = [x for x in range(256)] for i in range(8): EXP_TABLE[i] = 1 << i; for i in range(8, 256): EXP_TABLE[i] = (EXP_TABLE[i - 4] ^ EXP_TABLE[i - 5] ^ EXP_TABLE[i - 6] ^ EXP_TABLE[i - 8]) for i in range(255): LOG_TABLE[EXP_TABLE[i] ] = i class QRPolynomial: def __init__(self, num, shift): if (len(num) == 0): raise Exception(len(num) + "/" + shift) offset = 0 while offset < len(num) and num[offset] == 0: offset += 1 self.num = num[offset:] + [0]*shift def get(self, index): return self.num[index] def getLength(self): return len(self.num) def multiply(self, e): num = [0] * (self.getLength() + e.getLength() - 1); for i in range(self.getLength()): for j in range(e.getLength()): num[i + j] ^= QRMath.gexp(QRMath.glog(self.get(i) ) + QRMath.glog(e.get(j) ) ) return QRPolynomial(num, 0); def mod(self, e): if (self.getLength() < e.getLength()): return self; ratio = QRMath.glog(self.num[0] ) - QRMath.glog(e.num[0] ) num = [nn ^ QRMath.gexp(QRMath.glog(en) + ratio) for nn,en in zip(self.num, e.num)] num += self.num[e.getLength():] # recursive call return QRPolynomial(num, 0).mod(e); class QRRSBlock: RS_BLOCK_TABLE = [ # L # M # Q # H # 1 [1, 26, 19], [1, 26, 16], [1, 26, 13], [1, 26, 9], # 2 [1, 44, 34], [1, 44, 28], [1, 44, 22], [1, 44, 16], # 3 [1, 70, 55], [1, 70, 44], [2, 35, 17], [2, 35, 13], # 4 [1, 100, 80], [2, 50, 32], [2, 50, 24], [4, 25, 9], # 5 [1, 134, 108], [2, 67, 43], [2, 33, 15, 2, 34, 16], [2, 33, 11, 2, 34, 12], # 6 [2, 86, 68], [4, 43, 27], [4, 43, 19], [4, 43, 15], # 7 [2, 98, 78], [4, 49, 31], [2, 32, 14, 4, 33, 15], [4, 39, 13, 1, 40, 14], # 8 [2, 121, 97], [2, 60, 38, 2, 61, 39], [4, 40, 18, 2, 41, 19], [4, 40, 14, 2, 41, 15], # 9 [2, 146, 116], [3, 58, 36, 2, 59, 37], [4, 36, 16, 4, 37, 17], [4, 36, 12, 4, 37, 13], # 10 [2, 86, 68, 2, 87, 69], [4, 69, 43, 1, 70, 44], [6, 43, 19, 2, 44, 20], [6, 43, 15, 2, 44, 16], # 11 [4, 101, 81], [1, 80, 50, 4, 81, 51], [4, 50, 22, 4, 51, 23], [3, 36, 12, 8, 37, 13], # 12 [2, 116, 92, 2, 117, 93], [6, 58, 36, 2, 59, 37], [4, 46, 20, 6, 47, 21], [7, 42, 14, 4, 43, 15], # 13 [4, 133, 107], [8, 59, 37, 1, 60, 38], [8, 44, 20, 4, 45, 21], [12, 33, 11, 4, 34, 12], # 14 [3, 145, 115, 1, 146, 116], [4, 64, 40, 5, 65, 41], [11, 36, 16, 5, 37, 17], [11, 36, 12, 5, 37, 13], # 15 [5, 109, 87, 1, 110, 88], [5, 65, 41, 5, 66, 42], [5, 54, 24, 7, 55, 25], [11, 36, 12], # 16 [5, 122, 98, 1, 123, 99], [7, 73, 45, 3, 74, 46], [15, 43, 19, 2, 44, 20], [3, 45, 15, 13, 46, 16], # 17 [1, 135, 107, 5, 136, 108], [10, 74, 46, 1, 75, 47], [1, 50, 22, 15, 51, 23], [2, 42, 14, 17, 43, 15], # 18 [5, 150, 120, 1, 151, 121], [9, 69, 43, 4, 70, 44], [17, 50, 22, 1, 51, 23], [2, 42, 14, 19, 43, 15], # 19 [3, 141, 113, 4, 142, 114], [3, 70, 44, 11, 71, 45], [17, 47, 21, 4, 48, 22], [9, 39, 13, 16, 40, 14], # 20 [3, 135, 107, 5, 136, 108], [3, 67, 41, 13, 68, 42], [15, 54, 24, 5, 55, 25], [15, 43, 15, 10, 44, 16], # 21 [4, 144, 116, 4, 145, 117], [17, 68, 42], [17, 50, 22, 6, 51, 23], [19, 46, 16, 6, 47, 17], # 22 [2, 139, 111, 7, 140, 112], [17, 74, 46], [7, 54, 24, 16, 55, 25], [34, 37, 13], # 23 [4, 151, 121, 5, 152, 122], [4, 75, 47, 14, 76, 48], [11, 54, 24, 14, 55, 25], [16, 45, 15, 14, 46, 16], # 24 [6, 147, 117, 4, 148, 118], [6, 73, 45, 14, 74, 46], [11, 54, 24, 16, 55, 25], [30, 46, 16, 2, 47, 17], # 25 [8, 132, 106, 4, 133, 107], [8, 75, 47, 13, 76, 48], [7, 54, 24, 22, 55, 25], [22, 45, 15, 13, 46, 16], # 26 [10, 142, 114, 2, 143, 115], [19, 74, 46, 4, 75, 47], [28, 50, 22, 6, 51, 23], [33, 46, 16, 4, 47, 17], # 27 [8, 152, 122, 4, 153, 123], [22, 73, 45, 3, 74, 46], [8, 53, 23, 26, 54, 24], [12, 45, 15, 28, 46, 16], # 28 [3, 147, 117, 10, 148, 118], [3, 73, 45, 23, 74, 46], [4, 54, 24, 31, 55, 25], [11, 45, 15, 31, 46, 16], # 29 [7, 146, 116, 7, 147, 117], [21, 73, 45, 7, 74, 46], [1, 53, 23, 37, 54, 24], [19, 45, 15, 26, 46, 16], # 30 [5, 145, 115, 10, 146, 116], [19, 75, 47, 10, 76, 48], [15, 54, 24, 25, 55, 25], [23, 45, 15, 25, 46, 16], # 31 [13, 145, 115, 3, 146, 116], [2, 74, 46, 29, 75, 47], [42, 54, 24, 1, 55, 25], [23, 45, 15, 28, 46, 16], # 32 [17, 145, 115], [10, 74, 46, 23, 75, 47], [10, 54, 24, 35, 55, 25], [19, 45, 15, 35, 46, 16], # 33 [17, 145, 115, 1, 146, 116], [14, 74, 46, 21, 75, 47], [29, 54, 24, 19, 55, 25], [11, 45, 15, 46, 46, 16], # 34 [13, 145, 115, 6, 146, 116], [14, 74, 46, 23, 75, 47], [44, 54, 24, 7, 55, 25], [59, 46, 16, 1, 47, 17], # 35 [12, 151, 121, 7, 152, 122], [12, 75, 47, 26, 76, 48], [39, 54, 24, 14, 55, 25], [22, 45, 15, 41, 46, 16], # 36 [6, 151, 121, 14, 152, 122], [6, 75, 47, 34, 76, 48], [46, 54, 24, 10, 55, 25], [2, 45, 15, 64, 46, 16], # 37 [17, 152, 122, 4, 153, 123], [29, 74, 46, 14, 75, 47], [49, 54, 24, 10, 55, 25], [24, 45, 15, 46, 46, 16], # 38 [4, 152, 122, 18, 153, 123], [13, 74, 46, 32, 75, 47], [48, 54, 24, 14, 55, 25], [42, 45, 15, 32, 46, 16], # 39 [20, 147, 117, 4, 148, 118], [40, 75, 47, 7, 76, 48], [43, 54, 24, 22, 55, 25], [10, 45, 15, 67, 46, 16], # 40 [19, 148, 118, 6, 149, 119], [18, 75, 47, 31, 76, 48], [34, 54, 24, 34, 55, 25], [20, 45, 15, 61, 46, 16] ] def __init__(self, totalCount, dataCount): self.totalCount = totalCount self.dataCount = dataCount @staticmethod def getRSBlocks(version, errorCorrectLevel): rsBlock = QRRSBlock.getRsBlockTable(version, errorCorrectLevel); if rsBlock == None: raise Exception("bad rs block @ version:" + version + "/errorCorrectLevel:" + errorCorrectLevel) length = len(rsBlock) // 3 list = [] for i in range(length): count = rsBlock[i * 3 + 0] totalCount = rsBlock[i * 3 + 1] dataCount = rsBlock[i * 3 + 2] for j in range(count): list.append(QRRSBlock(totalCount, dataCount)) return list; @staticmethod def getRsBlockTable(version, errorCorrectLevel): if errorCorrectLevel == QRErrorCorrectLevel.L: return QRRSBlock.RS_BLOCK_TABLE[(version - 1) * 4 + 0]; elif errorCorrectLevel == QRErrorCorrectLevel.M: return QRRSBlock.RS_BLOCK_TABLE[(version - 1) * 4 + 1]; elif errorCorrectLevel == QRErrorCorrectLevel.Q: return QRRSBlock.RS_BLOCK_TABLE[(version - 1) * 4 + 2]; elif errorCorrectLevel == QRErrorCorrectLevel.H: return QRRSBlock.RS_BLOCK_TABLE[(version - 1) * 4 + 3]; else: return None; class QRBitBuffer: def __init__(self): self.buffer = [] self.length = 0 def __repr__(self): return ".".join([str(n) for n in self.buffer]) def get(self, index): bufIndex = index // 8 return ( (self.buffer[bufIndex] >> (7 - index % 8) ) & 1) == 1 def put(self, num, length): for i in range(length): self.putBit( ( (num >> (length - i - 1) ) & 1) == 1) def getLengthInBits(self): return self.length def putBit(self, bit): bufIndex = self.length // 8 if len(self.buffer) <= bufIndex: self.buffer.append(0) if bit: self.buffer[bufIndex] |= (0x80 >> (self.length % 8) ) self.length += 1
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/barcode/qrencoder.py
0.436142
0.187653
qrencoder.py
pypi
from __future__ import print_function __version__='3.3.0' __all__ = ('USPS_4State',) from reportlab.graphics.barcode.common import Barcode from reportlab.lib.utils import asNative def nhex(i): 'normalized hex' r = hex(i) r = r[:2]+r[2:].lower() if r.endswith('l'): r = r[:-1] return r class USPS_4State(Barcode): ''' USPS 4-State OneView (TM) barcode. All info from USPS-B-3200A ''' _widthSize = 1 _heightSize = 1 _fontSize = 11 _humanReadable = 0 if True: tops = dict( F = (0.0625,0.0825), T = (0.0195,0.0285), A = (0.0625,0.0825), D = (0.0195,0.0285), ) bottoms = dict( F = (-0.0625,-0.0825), T = (-0.0195,-0.0285), D = (-0.0625,-0.0825), A = (-0.0195,-0.0285), ) dimensions = dict( width = (0.015, 0.025), pitch = (0.0416, 0.050), hcz = (0.125,0.125), vcz = (0.028,0.028), ) else: tops = dict( F = (0.067,0.115), T = (0.021,0.040), A = (0.067,0.115), D = (0.021,0.040), ) bottoms = dict( F = (-0.067,-0.115), D = (-0.067,-0.115), T = (-0.021,-0.040), A = (-0.021,-0.040), ) dimensions = dict( width = (0.015, 0.025), pitch = (0.0416,0.050), hcz = (0.125,0.125), vcz = (0.040,0.040), ) def __init__(self,value='01234567094987654321',routing='',**kwd): self._init() value = str(value) if isinstance(value,int) else asNative(value) if not routing: #legal values for combined tracking + routing if len(value) in (20,25,29,31): value, routing = value[:20], value[20:] else: raise ValueError('value+routing length must be 20, 25, 29 or 31 digits not %d' % len(value)) elif len(routing) not in (5,9,11): raise ValueError('routing length must be 5, 9 or 11 digits not %d' % len(routing)) self._tracking = value self._routing = routing self._setKeywords(**kwd) def _init(self): self._bvalue = None self._codewords = None self._characters = None self._barcodes = None def scale(kind,D,s): V = D[kind] return 72*(V[0]*(1-s)+s*V[1]) scale = staticmethod(scale) def tracking(self,tracking): self._init() self._tracking = tracking tracking = property(lambda self: self._tracking,tracking) def routing(self,routing): self._init() self._routing = routing routing = property(lambda self: self._routing,routing) def widthSize(self,value): self._sized = None self._widthSize = min(max(0,value),1) widthSize = property(lambda self: self._widthSize,widthSize) def heightSize(self,value): self._sized = None self._heightSize = value heightSize = property(lambda self: self._heightSize,heightSize) def fontSize(self,value): self._sized = None self._fontSize = value fontSize = property(lambda self: self._fontSize,fontSize) def humanReadable(self,value): self._sized = None self._humanReadable = value humanReadable = property(lambda self: self._humanReadable,humanReadable) def binary(self): '''convert the 4 state string values to binary >>> print(nhex(USPS_4State('01234567094987654321','').binary)) 0x1122103b5c2004b1 >>> print(nhex(USPS_4State('01234567094987654321','01234').binary)) 0xd138a87bab5cf3804b1 >>> print(nhex(USPS_4State('01234567094987654321','012345678').binary)) 0x202bdc097711204d21804b1 >>> print(nhex(USPS_4State('01234567094987654321','01234567891').binary)) 0x16907b2a24abc16a2e5c004b1 ''' value = self._bvalue if not value: routing = self.routing n = len(routing) try: if n==0: value = 0 elif n==5: value = int(routing)+1 elif n==9: value = int(routing)+100001 elif n==11: value = int(routing)+1000100001 else: raise ValueError except: raise ValueError('Problem converting %s, routing code must be 0, 5, 9 or 11 digits' % routing) tracking = self.tracking svalue = tracking[0:2] try: value *= 10 value += int(svalue[0]) value *= 5 value += int(svalue[1]) except: raise ValueError('Problem converting %s, barcode identifier must be 2 digits' % svalue) i = 2 for name,nd in (('special services',3), ('customer identifier',6), ('sequence number',9)): j = i i += nd svalue = tracking[j:i] try: if len(svalue)!=nd: raise ValueError for j in range(nd): value *= 10 value += int(svalue[j]) except: raise ValueError('Problem converting %s, %s must be %d digits' % (svalue,name,nd)) self._bvalue = value return value binary = property(binary) def codewords(self): '''convert binary value into codewords >>> print(USPS_4State('01234567094987654321','01234567891').codewords) (673, 787, 607, 1022, 861, 19, 816, 1294, 35, 602) ''' if not self._codewords: value = self.binary A, J = divmod(value,636) A, I = divmod(A,1365) A, H = divmod(A,1365) A, G = divmod(A,1365) A, F = divmod(A,1365) A, E = divmod(A,1365) A, D = divmod(A,1365) A, C = divmod(A,1365) A, B = divmod(A,1365) assert 0<=A<=658, 'improper value %s passed to _2codewords A-->%s' % (hex(int(value)),A) self._fcs = _crc11(value) if self._fcs&1024: A += 659 J *= 2 self._codewords = tuple(map(int,(A,B,C,D,E,F,G,H,I,J))) return self._codewords codewords = property(codewords) def table1(self): self.__class__.table1 = _initNof13Table(5,1287) return self.__class__.table1 table1 = property(table1) def table2(self): self.__class__.table2 = _initNof13Table(2,78) return self.__class__.table2 table2 = property(table2) def characters(self): ''' convert own codewords to characters >>> print(' '.join(hex(c)[2:] for c in USPS_4State('01234567094987654321','01234567891').characters)) dcb 85c 8e4 b06 6dd 1740 17c6 1200 123f 1b2b ''' if not self._characters: codewords = self.codewords fcs = self._fcs C = [] aC = C.append table1 = self.table1 table2 = self.table2 for i in range(10): cw = codewords[i] if cw<=1286: c = table1[cw] else: c = table2[cw-1287] if (fcs>>i)&1: c = ~c & 0x1fff aC(c) self._characters = tuple(C) return self._characters characters = property(characters) def barcodes(self): '''Get 4 state bar codes for current routing and tracking >>> print(USPS_4State('01234567094987654321','01234567891').barcodes) AADTFFDFTDADTAADAATFDTDDAAADDTDTTDAFADADDDTFFFDDTTTADFAAADFTDAADA ''' if not self._barcodes: C = self.characters B = [] aB = B.append bits2bars = self._bits2bars for dc,db,ac,ab in self.table4: aB(bits2bars[((C[dc]>>db)&1)+2*((C[ac]>>ab)&1)]) self._barcodes = ''.join(B) return self._barcodes barcodes = property(barcodes) table4 = ((7, 2, 4, 3), (1, 10, 0, 0), (9, 12, 2, 8), (5, 5, 6, 11), (8, 9, 3, 1), (0, 1, 5, 12), (2, 5, 1, 8), (4, 4, 9, 11), (6, 3, 8, 10), (3, 9, 7, 6), (5, 11, 1, 4), (8, 5, 2, 12), (9, 10, 0, 2), (7, 1, 6, 7), (3, 6, 4, 9), (0, 3, 8, 6), (6, 4, 2, 7), (1, 1, 9, 9), (7, 10, 5, 2), (4, 0, 3, 8), (6, 2, 0, 4), (8, 11, 1, 0), (9, 8, 3, 12), (2, 6, 7, 7), (5, 1, 4, 10), (1, 12, 6, 9), (7, 3, 8, 0), (5, 8, 9, 7), (4, 6, 2, 10), (3, 4, 0, 5), (8, 4, 5, 7), (7, 11, 1, 9), (6, 0, 9, 6), (0, 6, 4, 8), (2, 1, 3, 2), (5, 9, 8, 12), (4, 11, 6, 1), (9, 5, 7, 4), (3, 3, 1, 2), (0, 7, 2, 0), (1, 3, 4, 1), (6, 10, 3, 5), (8, 7, 9, 4), (2, 11, 5, 6), (0, 8, 7, 12), (4, 2, 8, 1), (5, 10, 3, 0), (9, 3, 0, 9), (6, 5, 2, 4), (7, 8, 1, 7), (5, 0, 4, 5), (2, 3, 0, 10), (6, 12, 9, 2), (3, 11, 1, 6), (8, 8, 7, 9), (5, 4, 0, 11), (1, 5, 2, 2), (9, 1, 4, 12), (8, 3, 6, 6), (7, 0, 3, 7), (4, 7, 7, 5), (0, 12, 1, 11), (2, 9, 9, 0), (6, 8, 5, 3), (3, 10, 8, 2)) _bits2bars = 'T','D','A','F' horizontalClearZone = property(lambda self: self.scale('hcz',self.dimensions,self.widthScale)) verticalClearZone = property(lambda self: self.scale('vcz',self.dimensions,self.heightScale)) @property def barWidth(self): if '_barWidth' in self.__dict__: return self.__dict__['_barWidth'] return self.scale('width',self.dimensions,self.widthScale) @barWidth.setter def barWidth(self,value): n, x = self.dimensions['width'] self.__dict__['_barWidth'] = 72*min(max(value/72.0,n),x) @property def pitch(self): if '_pitch' in self.__dict__: return self.__dict__['_pitch'] return self.scale('pitch',self.dimensions,self.widthScale) @pitch.setter def pitch(self,value): n, x = self.dimensions['pitch'] self.__dict__['_pitch'] = 72*min(max(value/72.0,n),x) @property def barHeight(self): if '_barHeight' in self.__dict__: return self.__dict__['_barHeight'] return self.scale('F',self.tops,self.heightScale) - self.scale('F',self.bottoms,self.heightScale) @barHeight.setter def barHeight(self,value): n = self.tops['F'][0] - self.bottoms['F'][0] x = self.tops['F'][1] - self.bottoms['F'][1] value = self.__dict__['_barHeight'] = 72*min(max(value/72.0,n),x) self.heightSize = (value - n)/(x-n) widthScale = property(lambda self: min(1,max(0,self.widthSize))) heightScale = property(lambda self: min(1,max(0,self.heightSize))) def width(self): self.computeSize() return self._width width = property(width) def height(self): self.computeSize() return self._height height = property(height) def computeSize(self): if not getattr(self,'_sized',None): ws = self.widthScale hs = self.heightScale barHeight = self.barHeight barWidth = self.barWidth pitch = self.pitch hcz = self.horizontalClearZone vcz = self.verticalClearZone self._width = 2*hcz + barWidth + 64*pitch self._height = 2*vcz+barHeight if self.humanReadable: self._height += self.fontSize*1.2+vcz self._sized = True def wrap(self,aW,aH): self.computeSize() return self.width, self.height def _getBarVInfo(self,y0=0): vInfo = {} hs = self.heightScale for b in ('T','D','A','F'): y = self.scale(b,self.bottoms,hs)+y0 vInfo[b] = y,self.scale(b,self.tops,hs)+y0 - y return vInfo def draw(self): self.computeSize() hcz = self.horizontalClearZone vcz = self.verticalClearZone bw = self.barWidth x = hcz y0 = vcz+self.barHeight*0.5 dw = self.pitch vInfo = self._getBarVInfo(y0) for b in self.barcodes: yb, hb = vInfo[b] self.rect(x,yb,bw,hb) x += dw self.drawHumanReadable() def value(self): tracking = self.tracking routing = self.routing routing = routing and (routing,) or () return ' '.join((tracking[0:2],tracking[2:5],tracking[5:11],tracking[11:])+routing) value = property(value,lambda self,value: self.__dict__.__setitem__('tracking',value)) def drawHumanReadable(self): if self.humanReadable: hcz = self.horizontalClearZone vcz = self.verticalClearZone fontName = self.fontName fontSize = self.fontSize y = self.barHeight+2*vcz+0.2*fontSize self.annotate(hcz,y,self.value,fontName,fontSize) def annotate(self,x,y,text,fontName,fontSize,anchor='middle'): Barcode.annotate(self,x,y,text,fontName,fontSize,anchor='start') def _crc11(value): ''' >>> usps = [USPS_4State('01234567094987654321',x).binary for x in ('','01234','012345678','01234567891')] >>> print(' '.join(nhex(x) for x in usps)) 0x1122103b5c2004b1 0xd138a87bab5cf3804b1 0x202bdc097711204d21804b1 0x16907b2a24abc16a2e5c004b1 >>> print(' '.join(nhex(_crc11(x)) for x in usps)) 0x51 0x65 0x606 0x751 ''' hexbytes = nhex(int(value))[2:] hexbytes = '0'*(26-len(hexbytes))+hexbytes gp = 0x0F35 fcs = 0x07FF data = int(hexbytes[:2],16)<<5 for b in range(2,8): if (fcs ^ data)&0x400: fcs = (fcs<<1)^gp else: fcs = fcs<<1 fcs &= 0x7ff data <<= 1 for x in range(2,2*13,2): data = int(hexbytes[x:x+2],16)<<3 for b in range(8): if (fcs ^ data)&0x400: fcs = (fcs<<1)^gp else: fcs = fcs<<1 fcs &= 0x7ff data <<= 1 return fcs def _ru13(i): '''reverse unsigned 13 bit number >>> print(_ru13(7936), _ru13(31), _ru13(47), _ru13(7808)) 31 7936 7808 47 ''' r = 0 for x in range(13): r <<= 1 r |= i & 1 i >>= 1 return r def _initNof13Table(N,lenT): '''create and return table of 13 bit values with N bits on >>> T = _initNof13Table(5,1287) >>> print(' '.join('T[%d]=%d' % (i, T[i]) for i in (0,1,2,3,4,1271,1272,1284,1285,1286))) T[0]=31 T[1]=7936 T[2]=47 T[3]=7808 T[4]=55 T[1271]=6275 T[1272]=6211 T[1284]=856 T[1285]=744 T[1286]=496 ''' T = lenT*[None] l = 0 u = lenT-1 for c in range(8192): bc = 0 for b in range(13): bc += (c&(1<<b))!=0 if bc!=N: continue r = _ru13(c) if r<c: continue #we already looked at this pair if r==c: T[u] = c u -= 1 else: T[l] = c l += 1 T[l] = r l += 1 assert l==(u+1), 'u+1(%d)!=l(%d) for %d of 13 table' % (u+1,l,N) return T def _test(): import doctest return doctest.testmod() if __name__ == "__main__": _test()
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/barcode/usps4s.py
0.468791
0.240189
usps4s.py
pypi
from reportlab.graphics.barcode.code39 import Standard39 from reportlab.lib import colors from reportlab.lib.units import cm from string import ascii_uppercase, digits as string_digits class BaseLTOLabel(Standard39) : """ Base class for LTO labels. Specification taken from "IBM LTO Ultrium Cartridge Label Specification, Revision 3" available on May 14th 2008 from : http://www-1.ibm.com/support/docview.wss?rs=543&context=STCVQ6R&q1=ssg1*&uid=ssg1S7000429&loc=en_US&cs=utf-8&lang=en+en """ LABELWIDTH = 7.9 * cm LABELHEIGHT = 1.7 * cm LABELROUND = 0.15 * cm CODERATIO = 2.75 CODENOMINALWIDTH = 7.4088 * cm CODEBARHEIGHT = 1.11 * cm CODEBARWIDTH = 0.0432 * cm CODEGAP = CODEBARWIDTH CODELQUIET = 10 * CODEBARWIDTH CODERQUIET = 10 * CODEBARWIDTH def __init__(self, prefix="", number=None, subtype="1", border=None, checksum=False, availheight=None) : """ Initializes an LTO label. prefix : Up to six characters from [A-Z][0-9]. Defaults to "". number : Label's number or None. Defaults to None. subtype : LTO subtype string , e.g. "1" for LTO1. Defaults to "1". border : None, or the width of the label's border. Defaults to None. checksum : Boolean indicates if checksum char has to be printed. Defaults to False. availheight : Available height on the label, or None for automatic. Defaults to None. """ self.height = max(availheight, self.CODEBARHEIGHT) self.border = border if (len(subtype) != 1) \ or (subtype not in ascii_uppercase + string_digits) : raise ValueError("Invalid subtype '%s'" % subtype) if ((not number) and (len(prefix) > 6)) \ or not prefix.isalnum() : raise ValueError("Invalid prefix '%s'" % prefix) label = "%sL%s" % ((prefix + str(number or 0).zfill(6 - len(prefix)))[:6], subtype) if len(label) != 8 : raise ValueError("Invalid set of parameters (%s, %s, %s)" \ % (prefix, number, subtype)) self.label = label Standard39.__init__(self, label, ratio=self.CODERATIO, barHeight=self.height, barWidth=self.CODEBARWIDTH, gap=self.CODEGAP, lquiet=self.CODELQUIET, rquiet=self.CODERQUIET, quiet=True, checksum=checksum) def drawOn(self, canvas, x, y) : """Draws the LTO label onto the canvas.""" canvas.saveState() canvas.translate(x, y) if self.border : canvas.setLineWidth(self.border) canvas.roundRect(0, 0, self.LABELWIDTH, self.LABELHEIGHT, self.LABELROUND) Standard39.drawOn(self, canvas, (self.LABELWIDTH-self.CODENOMINALWIDTH)/2.0, self.LABELHEIGHT-self.height) canvas.restoreState() class VerticalLTOLabel(BaseLTOLabel) : """ A class for LTO labels with rectangular blocks around the tape identifier. """ LABELFONT = ("Helvetica-Bold", 14) BLOCKWIDTH = 1*cm BLOCKHEIGHT = 0.45*cm LINEWIDTH = 0.0125 NBBLOCKS = 7 COLORSCHEME = ("red", "yellow", "lightgreen", "lightblue", "grey", "orangered", "pink", "darkgreen", "orange", "purple") def __init__(self, *args, **kwargs) : """ Initializes the label. colored : boolean to determine if blocks have to be colorized. """ if "colored" in kwargs: self.colored = kwargs["colored"] del kwargs["colored"] else : self.colored = False kwargs["availheight"] = self.LABELHEIGHT-self.BLOCKHEIGHT BaseLTOLabel.__init__(self, *args, **kwargs) def drawOn(self, canvas, x, y) : """Draws some blocks around the identifier's characters.""" BaseLTOLabel.drawOn(self, canvas, x, y) canvas.saveState() canvas.setLineWidth(self.LINEWIDTH) canvas.setStrokeColorRGB(0, 0, 0) canvas.translate(x, y) xblocks = (self.LABELWIDTH-(self.NBBLOCKS*self.BLOCKWIDTH))/2.0 for i in range(self.NBBLOCKS) : (font, size) = self.LABELFONT newfont = self.LABELFONT if i == (self.NBBLOCKS - 1) : part = self.label[i:] (font, size) = newfont size /= 2.0 newfont = (font, size) else : part = self.label[i] canvas.saveState() canvas.translate(xblocks+(i*self.BLOCKWIDTH), 0) if self.colored and part.isdigit() : canvas.setFillColorRGB(*getattr(colors, self.COLORSCHEME[int(part)], colors.Color(1, 1, 1)).rgb()) else: canvas.setFillColorRGB(1, 1, 1) canvas.rect(0, 0, self.BLOCKWIDTH, self.BLOCKHEIGHT, fill=True) canvas.translate((self.BLOCKWIDTH+canvas.stringWidth(part, *newfont))/2.0, (self.BLOCKHEIGHT/2.0)) canvas.rotate(90.0) canvas.setFont(*newfont) canvas.setFillColorRGB(0, 0, 0) canvas.drawCentredString(0, 0, part) canvas.restoreState() canvas.restoreState() def test() : """Test this.""" from reportlab.pdfgen.canvas import Canvas from reportlab.lib import pagesizes canvas = Canvas("labels.pdf", pagesize=pagesizes.A4) canvas.setFont("Helvetica", 30) (width, height) = pagesizes.A4 canvas.drawCentredString(width/2.0, height-4*cm, "Sample LTO labels") xpos = xorig = 2 * cm ypos = yorig = 2 * cm colwidth = 10 * cm lineheight = 3.9 * cm count = 1234 BaseLTOLabel("RL", count, "3").drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 BaseLTOLabel("RL", count, "3", border=0.0125).drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 VerticalLTOLabel("RL", count, "3").drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 VerticalLTOLabel("RL", count, "3", border=0.0125).drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 VerticalLTOLabel("RL", count, "3", colored=True).drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 VerticalLTOLabel("RL", count, "3", border=0.0125, colored=True).drawOn(canvas, xpos, ypos) canvas.showPage() canvas.save() if __name__ == "__main__" : test()
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/barcode/lto.py
0.740737
0.255924
lto.py
pypi
__all__ = ('QrCodeWidget') import itertools from reportlab.platypus.flowables import Flowable from reportlab.graphics.shapes import Group, Rect from reportlab.lib import colors from reportlab.lib.validators import isNumber, isNumberOrNone, isColor, Validator from reportlab.lib.attrmap import AttrMap, AttrMapValue from reportlab.graphics.widgetbase import Widget from reportlab.lib.units import mm from reportlab.lib.utils import asUnicodeEx, isUnicode from reportlab.graphics.barcode import qrencoder class isLevel(Validator): def test(self, x): return x in ['L', 'M', 'Q', 'H'] isLevel = isLevel() class isUnicodeOrQRList(Validator): def _test(self, x): if isUnicode(x): return True if all(isinstance(v, qrencoder.QR) for v in x): return True return False def test(self, x): return self._test(x) or self.normalizeTest(x) def normalize(self, x): if self._test(x): return x try: return asUnicodeEx(x) except UnicodeError: raise ValueError("Can't convert to unicode: %r" % x) isUnicodeOrQRList = isUnicodeOrQRList() class SRect(Rect): def __init__(self, x, y, width, height, fillColor=colors.black): Rect.__init__(self, x, y, width, height, fillColor=fillColor, strokeColor=None, strokeWidth=0) class QrCodeWidget(Widget): codeName = "QR" _attrMap = AttrMap( BASE = Widget, value = AttrMapValue(isUnicodeOrQRList, desc='QRCode data'), x = AttrMapValue(isNumber, desc='x-coord'), y = AttrMapValue(isNumber, desc='y-coord'), barFillColor = AttrMapValue(isColor, desc='bar color'), barWidth = AttrMapValue(isNumber, desc='Width of bars.'), # maybe should be named just width? barHeight = AttrMapValue(isNumber, desc='Height of bars.'), # maybe should be named just height? barBorder = AttrMapValue(isNumber, desc='Width of QR border.'), # maybe should be named qrBorder? barLevel = AttrMapValue(isLevel, desc='QR Code level.'), # maybe should be named qrLevel qrVersion = AttrMapValue(isNumberOrNone, desc='QR Code version. None for auto'), # Below are ignored, they make no sense barStrokeWidth = AttrMapValue(isNumber, desc='Width of bar borders.'), barStrokeColor = AttrMapValue(isColor, desc='Color of bar borders.'), ) x = 0 y = 0 barFillColor = colors.black barStrokeColor = None barStrokeWidth = 0 barHeight = 32*mm barWidth = 32*mm barBorder = 4 barLevel = 'L' qrVersion = None value = None def __init__(self, value='Hello World', **kw): self.value = isUnicodeOrQRList.normalize(value) for k, v in kw.items(): setattr(self, k, v) ec_level = getattr(qrencoder.QRErrorCorrectLevel, self.barLevel) self.__dict__['qr'] = qrencoder.QRCode(self.qrVersion, ec_level) if isUnicode(self.value): self.addData(self.value) elif self.value: for v in self.value: self.addData(v) def addData(self, value): self.qr.addData(value) def draw(self): self.qr.make() g = Group() color = self.barFillColor border = self.barBorder width = self.barWidth height = self.barHeight x = self.x y = self.y g.add(SRect(x, y, width, height, fillColor=None)) moduleCount = self.qr.getModuleCount() minwh = float(min(width, height)) boxsize = minwh / (moduleCount + border * 2.0) offsetX = x + (width - minwh) / 2.0 offsetY = y + (minwh - height) / 2.0 for r, row in enumerate(self.qr.modules): row = map(bool, row) c = 0 for t, tt in itertools.groupby(row): isDark = t count = len(list(tt)) if isDark: x = (c + border) * boxsize y = (r + border + 1) * boxsize s = SRect(offsetX + x, offsetY + height - y, count * boxsize, boxsize, fillColor=color) g.add(s) c += count return g # Flowable version class QrCode(Flowable): height = 32*mm width = 32*mm qrBorder = 4 qrLevel = 'L' qrVersion = None value = None def __init__(self, value=None, **kw): self.value = isUnicodeOrQRList.normalize(value) for k, v in kw.items(): setattr(self, k, v) ec_level = getattr(qrencoder.QRErrorCorrectLevel, self.qrLevel) self.qr = qrencoder.QRCode(self.qrVersion, ec_level) if isUnicode(self.value): self.addData(self.value) elif self.value: for v in self.value: self.addData(v) def addData(self, value): self.qr.addData(value) def draw(self): self.qr.make() moduleCount = self.qr.getModuleCount() border = self.qrBorder xsize = self.width / (moduleCount + border * 2.0) ysize = self.height / (moduleCount + border * 2.0) for r, row in enumerate(self.qr.modules): row = map(bool, row) c = 0 for t, tt in itertools.groupby(row): isDark = t count = len(list(tt)) if isDark: x = (c + border) * xsize y = self.height - (r + border + 1) * ysize self.rect(x, y, count * xsize, ysize * 1.05) c += count def rect(self, x, y, w, h): self.canv.rect(x, y, w, h, stroke=0, fill=1)
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/barcode/qr.py
0.540196
0.250071
qr.py
pypi
try: from pylibdmtx import pylibdmtx except ImportError: pylibdmtx = None __all__ = () else: __all__=('DataMatrix',) from reportlab.graphics.barcode.common import Barcode from reportlab.lib.utils import asBytes from reportlab.platypus.paraparser import _num as paraparser_num from reportlab.graphics.widgetbase import Widget from reportlab.lib.validators import isColor, isString, isColorOrNone, isNumber, isBoxAnchor from reportlab.lib.attrmap import AttrMap, AttrMapValue from reportlab.lib.colors import toColor from reportlab.graphics.shapes import Group, Rect def _numConv(x): return x if isinstance(x,(int,float)) else paraparser_num(x) class _DMTXCheck: @classmethod def pylibdmtx_check(cls): if not pylibdmtx: raise ValueError('The %s class requires package pylibdmtx' % cls.__name__) class DataMatrix(Barcode,_DMTXCheck): def __init__(self, value='', **kwds): self.pylibdmtx_check() self._recalc = True self.value = value self.cellSize = kwds.pop('cellSize','5x5') self.size = kwds.pop('size','SquareAuto') self.encoding = kwds.pop('encoding','Ascii') self.anchor = kwds.pop('anchor','sw') self.color = kwds.pop('color',(0,0,0)) self.bgColor = kwds.pop('bgColor',None) self.x = kwds.pop('x',0) self.y = kwds.pop('y',0) self.border = kwds.pop('border',5) @property def value(self): return self._value @value.setter def value(self,v): self._value = asBytes(v) self._recalc = True @property def size(self): return self._size @size.setter def size(self,v): self._size = self._checkVal('size', v, pylibdmtx.ENCODING_SIZE_NAMES) self._recalc = True @property def border(self): return self._border @border.setter def border(self,v): self._border = _numConv(v) self._recalc = True @property def x(self): return self._x @x.setter def x(self,v): self._x = _numConv(v) self._recalc = True @property def y(self): return self._y @y.setter def y(self,v): self._y = _numConv(v) self._recalc = True @property def cellSize(self): return self._cellSize @size.setter def cellSize(self,v): self._cellSize = v self._recalc = True @property def encoding(self): return self._encoding @encoding.setter def encoding(self,v): self._encoding = self._checkVal('encoding', v, pylibdmtx.ENCODING_SCHEME_NAMES) self._recalc = True @property def anchor(self): return self._anchor @anchor.setter def anchor(self,v): self._anchor = self._checkVal('anchor', v, ('n','ne','e','se','s','sw','w','nw','c')) self._recalc = True def recalc(self): if not self._recalc: return data = self._value size = self._size encoding = self._encoding e = pylibdmtx.encode(data, size=size, scheme=encoding) iW = e.width iH = e.height p = e.pixels iCellSize = 5 bpp = 3 #bytes per pixel rowLen = iW*bpp cellLen = iCellSize*bpp assert len(p)//rowLen == iH matrix = list(filter(None, (''.join( (('x' if p[j:j+bpp] != b'\xff\xff\xff' else ' ') for j in range(i,i+rowLen,cellLen))).strip() for i in range(0,iH*rowLen,rowLen*iCellSize)))) self._nRows = len(matrix) self._nCols = len(matrix[-1]) self._matrix = '\n'.join(matrix) cellWidth = self._cellSize if cellWidth: cellWidth = cellWidth.split('x') if len(cellWidth)>2: raise ValueError('cellSize needs to be distance x distance not %r' % self._cellSize) elif len(cellWidth)==2: cellWidth, cellHeight = cellWidth else: cellWidth = cellHeight = cellWidth[0] cellWidth = _numConv(cellWidth) cellHeight = _numConv(cellHeight) else: cellWidth = cellHeight = iCellSize self._cellWidth = cellWidth self._cellHeight = cellHeight self._recalc = False self._bord = max(self.border,cellWidth,cellHeight) self._width = cellWidth*self._nCols + 2*self._bord self._height = cellHeight*self._nRows + 2*self._bord @property def matrix(self): self.recalc() return self._matrix @property def width(self): self.recalc() return self._width @property def height(self): self.recalc() return self._height @property def cellWidth(self): self.recalc() return self._cellWidth @property def cellHeight(self): self.recalc() return self._cellHeight def draw(self): self.recalc() canv = self.canv w = self.width h = self.height x = self.x y = self.y b = self._bord anchor = self.anchor if anchor in ('nw','n','ne'): y -= h elif anchor in ('c','e','w'): y -= h//2 if anchor in ('ne','e','se'): x -= w elif anchor in ('n','c','s'): x -= w//2 canv.saveState() if self.bgColor: canv.setFillColor(toColor(self.bgColor)) canv.rect(x, y-h, w, h, fill=1, stroke=0) canv.setFillColor(toColor(self.color)) canv.setStrokeColor(None) cellWidth = self.cellWidth cellHeight = self.cellHeight yr = y - b - cellHeight x += b for row in self.matrix.split('\n'): xr = x for c in row: if c=='x': canv.rect(xr, yr, cellWidth, cellHeight, fill=1, stroke=0) xr += cellWidth yr -= cellHeight canv.restoreState() class DataMatrixWidget(Widget,_DMTXCheck): codeName = "DataMatrix" _attrMap = AttrMap( BASE = Widget, value = AttrMapValue(isString, desc='Datamatrix data'), x = AttrMapValue(isNumber, desc='x-coord'), y = AttrMapValue(isNumber, desc='y-coord'), color = AttrMapValue(isColor, desc='foreground color'), bgColor = AttrMapValue(isColorOrNone, desc='background color'), encoding = AttrMapValue(isString, desc='encoding'), size = AttrMapValue(isString, desc='size'), cellSize = AttrMapValue(isString, desc='cellSize'), anchor = AttrMapValue(isBoxAnchor, desc='anchor pooint for x,y'), ) _defaults = dict( x = ('0',_numConv), y = ('0',_numConv), color = ('black',toColor), bgColor = (None,lambda _: toColor(_) if _ is not None else _), encoding = ('Ascii',None), size = ('SquareAuto',None), cellSize = ('5x5',None), anchor = ('sw', None), ) def __init__(self,value='Hello Cruel World!', **kwds): self.pylibdmtx_check() self.value = value for k,(d,c) in self._defaults.items(): v = kwds.pop(k,d) if c: v = c(v) setattr(self,k,v) def rect(self, x, y, w, h, fill=1, stroke=0): self._gadd(Rect(x,y,w,h,strokeColor=None,fillColor=self._fillColor)) def saveState(self,*args,**kwds): pass restoreState = setStrokeColor = saveState def setFillColor(self,c): self._fillColor = c def draw(self): m = DataMatrix(value=self.value,**{k: getattr(self,k) for k in self._defaults}) m.canv = self m.y += m.height g = Group() self._gadd = g.add m.draw() return g
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/barcode/dmtx.py
0.663669
0.252718
dmtx.py
pypi
from reportlab.lib.units import inch from reportlab.graphics.barcode.common import Barcode from string import digits as string_digits, whitespace as string_whitespace from reportlab.lib.utils import asNative _fim_patterns = { 'A' : "|| | ||", 'B' : "| || || |", 'C' : "|| | | ||", 'D' : "||| | |||", # XXX There is an E. # The below has been seen, but dunno if it is E or not: # 'E' : '|||| ||||' } _postnet_patterns = { '1' : "...||", '2' : "..|.|", '3' : "..||.", '4' : ".|..|", '5' : ".|.|.", '6' : ".||..", '7' : "|...|", '8' : "|..|.", '9' : "|.|..", '0' : "||...", 'S' : "|", } class FIM(Barcode): """ FIM (Facing ID Marks) encode only one letter. There are currently four defined: A Courtesy reply mail with pre-printed POSTNET B Business reply mail without pre-printed POSTNET C Business reply mail with pre-printed POSTNET D OCR Readable mail without pre-printed POSTNET Options that may be passed to constructor: value (single character string from the set A - D. required.): The value to encode. quiet (bool, default 0): Whether to include quiet zones in the symbol. The following may also be passed, but doing so will generate nonstandard symbols which should not be used. This is mainly documented here to show the defaults: barHeight (float, default 5/8 inch): Height of the code. This might legitimately be overriden to make a taller symbol that will 'bleed' off the edge of the paper, leaving 5/8 inch remaining. lquiet (float, default 1/4 inch): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or .15 times the symbol's length. rquiet (float, default 15/32 inch): Quiet zone size to right left of code, if quiet is true. Sources of information on FIM: USPS Publication 25, A Guide to Business Mail Preparation http://new.usps.com/cpim/ftp/pubs/pub25.pdf """ barWidth = inch * (1.0/32.0) spaceWidth = inch * (1.0/16.0) barHeight = inch * (5.0/8.0) rquiet = inch * (0.25) lquiet = inch * (15.0/32.0) quiet = 0 def __init__(self, value='', **args): value = str(value) if isinstance(value,int) else asNative(value) for k, v in args.items(): setattr(self, k, v) Barcode.__init__(self, value) def validate(self): self.valid = 1 self.validated = '' for c in self.value: if c in string_whitespace: continue elif c in "abcdABCD": self.validated = self.validated + c.upper() else: self.valid = 0 if len(self.validated) != 1: raise ValueError("Input must be exactly one character") return self.validated def decompose(self): self.decomposed = '' for c in self.encoded: self.decomposed = self.decomposed + _fim_patterns[c] return self.decomposed def computeSize(self): self._width = (len(self.decomposed) - 1) * self.spaceWidth + self.barWidth if self.quiet: self._width += self.lquiet + self.rquiet self._height = self.barHeight def draw(self): self._calculate() left = self.quiet and self.lquiet or 0 for c in self.decomposed: if c == '|': self.rect(left, 0.0, self.barWidth, self.barHeight) left += self.spaceWidth self.drawHumanReadable() def _humanText(self): return self.value class POSTNET(Barcode): """ POSTNET is used in the US to encode "zip codes" (postal codes) on mail. It can encode 5, 9, or 11 digit codes. I've read that it's pointless to do 5 digits, since USPS will just have to re-print them with 9 or 11 digits. Sources of information on POSTNET: USPS Publication 25, A Guide to Business Mail Preparation http://new.usps.com/cpim/ftp/pubs/pub25.pdf """ quiet = 0 shortHeight = inch * 0.050 barHeight = inch * 0.125 barWidth = inch * 0.018 spaceWidth = inch * 0.0275 def __init__(self, value='', **args): value = str(value) if isinstance(value,int) else asNative(value) for k, v in args.items(): setattr(self, k, v) Barcode.__init__(self, value) def validate(self): self.validated = '' self.valid = 1 count = 0 for c in self.value: if c in (string_whitespace + '-'): pass elif c in string_digits: count = count + 1 if count == 6: self.validated = self.validated + '-' self.validated = self.validated + c else: self.valid = 0 if len(self.validated) not in [5, 10, 12]: self.valid = 0 return self.validated def encode(self): self.encoded = "S" check = 0 for c in self.validated: if c in string_digits: self.encoded = self.encoded + c check = check + int(c) elif c == '-': pass else: raise ValueError("Invalid character in input") check = (10 - check) % 10 self.encoded = self.encoded + repr(check) + 'S' return self.encoded def decompose(self): self.decomposed = '' for c in self.encoded: self.decomposed = self.decomposed + _postnet_patterns[c] return self.decomposed def computeSize(self): self._width = len(self.decomposed) * self.barWidth + (len(self.decomposed) - 1) * self.spaceWidth self._height = self.barHeight def draw(self): self._calculate() sdown = self.barHeight - self.shortHeight left = 0 for c in self.decomposed: if c == '.': h = self.shortHeight else: h = self.barHeight self.rect(left, 0.0, self.barWidth, h) left = left + self.barWidth + self.spaceWidth self.drawHumanReadable() def _humanText(self): return self.encoded[1:-1]
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/barcode/usps.py
0.692954
0.352759
usps.py
pypi
__version__='3.3.0' __all__= ( 'BarcodeI2of5', 'BarcodeCode128', 'BarcodeStandard93', 'BarcodeExtended93', 'BarcodeStandard39', 'BarcodeExtended39', 'BarcodeMSI', 'BarcodeCodabar', 'BarcodeCode11', 'BarcodeFIM', 'BarcodePOSTNET', 'BarcodeUSPS_4State', ) from reportlab.lib.validators import isInt, isNumber, isString, isColorOrNone, isBoolean, EitherOr, isNumberOrNone from reportlab.lib.attrmap import AttrMap, AttrMapValue from reportlab.lib.colors import black from reportlab.lib.utils import rl_exec from reportlab.graphics.shapes import Rect, Group, String from reportlab.graphics.charts.areas import PlotArea ''' #snippet #first make your Drawing from reportlab.graphics.shapes import Drawing d= Drawing(100,50) #create and set up the widget from reportlab.graphics.barcode.widgets import BarcodeStandard93 bc = BarcodeStandard93() bc.value = 'RGB-123456' #add to the drawing and save d.add(bc) # d.save(formats=['gif','pict'],fnRoot='bc_sample') ''' class _BarcodeWidget(PlotArea): _attrMap = AttrMap(BASE=PlotArea, barStrokeColor = AttrMapValue(isColorOrNone, desc='Color of bar borders.'), barFillColor = AttrMapValue(isColorOrNone, desc='Color of bar interior areas.'), barStrokeWidth = AttrMapValue(isNumber, desc='Width of bar borders.'), value = AttrMapValue(EitherOr((isString,isNumber)), desc='Value.'), textColor = AttrMapValue(isColorOrNone, desc='Color of human readable text.'), valid = AttrMapValue(isBoolean), validated = AttrMapValue(isString,desc="validated form of input"), encoded = AttrMapValue(None,desc="encoded form of input"), decomposed = AttrMapValue(isString,desc="decomposed form of input"), canv = AttrMapValue(None,desc="temporarily used for internal methods"), gap = AttrMapValue(isNumberOrNone, desc='Width of inter character gaps.'), ) textColor = barFillColor = black barStrokeColor = None barStrokeWidth = 0 _BCC = None def __init__(self,_value='',**kw): PlotArea.__init__(self) if 'width' in self.__dict__: del self.__dict__['width'] if 'height' in self.__dict__: del self.__dict__['height'] self.x = self.y = 0 kw.setdefault('value',_value) self._BCC.__init__(self,**kw) def rect(self,x,y,w,h,**kw): #this allows the base code to draw rectangles for us using self.rect #using direct keyword argument overrides see eg common.py line 140 on for k,v in (('strokeColor',self.barStrokeColor), ('strokeWidth',self.barStrokeWidth), ('fillColor',self.barFillColor)): kw.setdefault(k,v) self._Gadd(Rect(self.x+x,self.y+y,w,h, **kw)) def draw(self): if not self._BCC: raise NotImplementedError("Abstract class %s cannot be drawn" % self.__class__.__name__) self.canv = self G = Group() self._Gadd = G.add self._Gadd(Rect(self.x,self.y,self.width,self.height,fillColor=None,strokeColor=None,strokeWidth=0.0001)) self._BCC.draw(self) del self.canv, self._Gadd return G def annotate(self,x,y,text,fontName,fontSize,anchor='middle'): self._Gadd(String(self.x+x,self.y+y,text,fontName=fontName,fontSize=fontSize, textAnchor=anchor,fillColor=self.textColor)) def _BCW(doc,codeName,attrMap,mod,value,**kwds): """factory for Barcode Widgets""" _pre_init = kwds.pop('_pre_init','') _methods = kwds.pop('_methods','') name = 'Barcode'+codeName ns = vars().copy() code = 'from %s import %s' % (mod,codeName) rl_exec(code,ns) ns['_BarcodeWidget'] = _BarcodeWidget ns['doc'] = ("\n\t'''%s'''" % doc) if doc else '' code = '''class %(name)s(_BarcodeWidget,%(codeName)s):%(doc)s \t_BCC = %(codeName)s \tcodeName = %(codeName)r \tdef __init__(self,**kw):%(_pre_init)s \t\t_BarcodeWidget.__init__(self,%(value)r,**kw)%(_methods)s''' % ns rl_exec(code,ns) Klass = ns[name] if attrMap: Klass._attrMap = attrMap for k, v in kwds.items(): setattr(Klass,k,v) return Klass BarcodeI2of5 = _BCW( """Interleaved 2 of 5 is used in distribution and warehouse industries. It encodes an even-numbered sequence of numeric digits. There is an optional module 10 check digit; if including this, the total length must be odd so that it becomes even after including the check digit. Otherwise the length must be even. Since the check digit is optional, our library does not check it. """, "I2of5", AttrMap(BASE=_BarcodeWidget, barWidth = AttrMapValue(isNumber,'''(float, default .0075): X-Dimension, or width of the smallest element Minumum is .0075 inch (7.5 mils).'''), ratio = AttrMapValue(isNumber,'''(float, default 2.2): The ratio of wide elements to narrow elements. Must be between 2.0 and 3.0 (or 2.2 and 3.0 if the barWidth is greater than 20 mils (.02 inch))'''), gap = AttrMapValue(isNumberOrNone,'''(float or None, default None): width of intercharacter gap. None means "use barWidth".'''), barHeight = AttrMapValue(isNumber,'''(float, see default below): Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol's length.'''), checksum = AttrMapValue(isBoolean,'''(bool, default 1): Whether to compute and include the check digit'''), bearers = AttrMapValue(isNumber,'''(float, in units of barWidth. default 3.0): Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 3 x-dimensions. Set to zero for no bearer bars. (Bearer bars help detect misscans, so it is suggested to leave them on).'''), bearerBox = AttrMapValue(isBoolean,'''(bool, default 0): if True turn bearers into a box'''), quiet = AttrMapValue(isBoolean,'''(bool, default 1): Whether to include quiet zones in the symbol.'''), lquiet = AttrMapValue(isNumber,'''(float, see default below): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or .15 times the symbol's length.'''), rquiet = AttrMapValue(isNumber,'''(float, defaults as above): Quiet zone size to right left of code, if quiet is true.'''), fontName = AttrMapValue(isString, desc='human readable font'), fontSize = AttrMapValue(isNumber, desc='human readable font size'), humanReadable = AttrMapValue(isBoolean, desc='if human readable'), stop = AttrMapValue(isBoolean, desc='if we use start/stop symbols (default 1)'), ), 'reportlab.graphics.barcode.common', 1234, _tests = [ '12', '1234', '123456', '12345678', '1234567890' ], ) BarcodeCode128 = _BCW("""Code 128 encodes any number of characters in the ASCII character set.""", "Code128", AttrMap(BASE=BarcodeI2of5,UNWANTED=('bearers','checksum','ratio','checksum','stop')), 'reportlab.graphics.barcode.code128', "AB-12345678", _tests = ['ReportLab Rocks!', 'PFWZF'], ) BarcodeCode128Auto = _BCW( 'Modified Code128 to use auto encoding', 'Code128Auto', AttrMap(BASE=BarcodeCode128), 'reportlab.graphics.barcode.code128', 'XY149740345GB' ) BarcodeStandard93=_BCW("""This is a compressed form of Code 39""", "Standard93", AttrMap(BASE=BarcodeCode128, stop = AttrMapValue(isBoolean, desc='if we use start/stop symbols (default 1)'), ), 'reportlab.graphics.barcode.code93', "CODE 93", ) BarcodeExtended93=_BCW("""This is a compressed form of Code 39, allowing the full ASCII charset""", "Extended93", AttrMap(BASE=BarcodeCode128, stop = AttrMapValue(isBoolean, desc='if we use start/stop symbols (default 1)'), ), 'reportlab.graphics.barcode.code93', "L@@K! Code 93 ;-)", ) BarcodeStandard39=_BCW("""Code39 is widely used in non-retail, especially US defence and health. Allowed characters are 0-9, A-Z (caps only), space, and -.$/+%*.""", "Standard39", AttrMap(BASE=BarcodeI2of5), 'reportlab.graphics.barcode.code39', "A012345B%R", ) BarcodeExtended39=_BCW("""Extended 39 encodes the full ASCII character set by encoding characters as pairs of Code 39 characters; $, /, % and + are used as shift characters.""", "Extended39", AttrMap(BASE=BarcodeI2of5), 'reportlab.graphics.barcode.code39', "A012345B}", ) BarcodeMSI=_BCW("""MSI is used for inventory control in retail applications. There are several methods for calculating check digits so we do not implement one. """, "MSI", AttrMap(BASE=BarcodeI2of5), 'reportlab.graphics.barcode.common', 1234, ) BarcodeCodabar=_BCW("""Used in blood banks, photo labs and FedEx labels. Encodes 0-9, -$:/.+, and four start/stop characters A-D.""", "Codabar", AttrMap(BASE=BarcodeI2of5), 'reportlab.graphics.barcode.common', "A012345B", ) BarcodeCode11=_BCW("""Used mostly for labelling telecommunications equipment. It encodes numeric digits.""", 'Code11', AttrMap(BASE=BarcodeI2of5, checksum = AttrMapValue(isInt,'''(integer, default 2): Whether to compute and include the check digit(s). (0 none, 1 1-digit, 2 2-digit, -1 auto, default -1): How many checksum digits to include. -1 ("auto") means 1 if the number of digits is 10 or less, else 2.'''), ), 'reportlab.graphics.barcode.common', "01234545634563", ) BarcodeFIM=_BCW(""" FIM was developed as part of the POSTNET barcoding system. FIM (Face Identification Marking) is used by the cancelling machines to sort mail according to whether or not they have bar code and their postage requirements. There are four types of FIM called FIM A, FIM B, FIM C, and FIM D. The four FIM types have the following meanings: FIM A- Postage required pre-barcoded FIM B - Postage pre-paid, no bar code exists FIM C- Postage prepaid prebarcoded FIM D- Postage required, no bar code exists""", "FIM", AttrMap(BASE=_BarcodeWidget, barWidth = AttrMapValue(isNumber,'''(float, default 1/32in): the bar width.'''), spaceWidth = AttrMapValue(isNumber,'''(float or None, default 1/16in): width of intercharacter gap. None means "use barWidth".'''), barHeight = AttrMapValue(isNumber,'''(float, default 5/8in): The bar height.'''), quiet = AttrMapValue(isBoolean,'''(bool, default 0): Whether to include quiet zones in the symbol.'''), lquiet = AttrMapValue(isNumber,'''(float, default: 15/32in): Quiet zone size to left of code, if quiet is true.'''), rquiet = AttrMapValue(isNumber,'''(float, default 1/4in): Quiet zone size to right left of code, if quiet is true.'''), fontName = AttrMapValue(isString, desc='human readable font'), fontSize = AttrMapValue(isNumber, desc='human readable font size'), humanReadable = AttrMapValue(isBoolean, desc='if human readable'), ), 'reportlab.graphics.barcode.usps', "A", ) BarcodePOSTNET=_BCW('', "POSTNET", AttrMap(BASE=_BarcodeWidget, barWidth = AttrMapValue(isNumber,'''(float, default 0.018*in): the bar width.'''), spaceWidth = AttrMapValue(isNumber,'''(float or None, default 0.0275in): width of intercharacter gap.'''), shortHeight = AttrMapValue(isNumber,'''(float, default 0.05in): The short bar height.'''), barHeight = AttrMapValue(isNumber,'''(float, default 0.125in): The full bar height.'''), fontName = AttrMapValue(isString, desc='human readable font'), fontSize = AttrMapValue(isNumber, desc='human readable font size'), humanReadable = AttrMapValue(isBoolean, desc='if human readable'), ), 'reportlab.graphics.barcode.usps', "78247-1043", ) BarcodeUSPS_4State=_BCW('', "USPS_4State", AttrMap(BASE=_BarcodeWidget, widthSize = AttrMapValue(isNumber,'''(float, default 1): the bar width size adjustment between 0 and 1.'''), heightSize = AttrMapValue(isNumber,'''(float, default 1): the bar height size adjustment between 0 and 1.'''), fontName = AttrMapValue(isString, desc='human readable font'), fontSize = AttrMapValue(isNumber, desc='human readable font size'), tracking = AttrMapValue(isString, desc='tracking data'), routing = AttrMapValue(isString, desc='routing data'), humanReadable = AttrMapValue(isBoolean, desc='if human readable'), barWidth = AttrMapValue(isNumber, desc='barWidth'), barHeight = AttrMapValue(isNumber, desc='barHeight'), pitch = AttrMapValue(isNumber, desc='pitch'), ), 'reportlab.graphics.barcode.usps4s', '01234567094987654321', _pre_init="\n\t\tkw.setdefault('routing','01234567891')\n", _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" ) BarcodeECC200DataMatrix = _BCW( 'ECC200DataMatrix', 'ECC200DataMatrix', AttrMap(BASE=_BarcodeWidget, x=AttrMapValue(isNumber, desc='X position of the lower-left corner of the barcode.'), y=AttrMapValue(isNumber, desc='Y position of the lower-left corner of the barcode.'), barWidth=AttrMapValue(isNumber, desc='Size of data modules.'), barFillColor=AttrMapValue(isColorOrNone, desc='Color of data modules.'), value=AttrMapValue(EitherOr((isString,isNumber)), desc='Value.'), height=AttrMapValue(None, desc='ignored'), width=AttrMapValue(None, desc='ignored'), strokeColor=AttrMapValue(None, desc='ignored'), strokeWidth=AttrMapValue(None, desc='ignored'), fillColor=AttrMapValue(None, desc='ignored'), background=AttrMapValue(None, desc='ignored'), debug=AttrMapValue(None, desc='ignored'), gap=AttrMapValue(None, desc='ignored'), row_modules=AttrMapValue(None, desc='???'), col_modules=AttrMapValue(None, desc='???'), row_regions=AttrMapValue(None, desc='???'), col_regions=AttrMapValue(None, desc='???'), cw_data=AttrMapValue(None, desc='???'), cw_ecc=AttrMapValue(None, desc='???'), row_usable_modules = AttrMapValue(None, desc='???'), col_usable_modules = AttrMapValue(None, desc='???'), valid = AttrMapValue(None, desc='???'), validated = AttrMapValue(None, desc='???'), decomposed = AttrMapValue(None, desc='???'), ), 'reportlab.graphics.barcode.ecc200datamatrix', 'JGB 0204H20B012722900021AC35B2100001003241014241014TPS01 WJ067073605GB185 MOUNT PLEASANT MAIL CENTER EC1A1BB9ZGBREC1A1BB EC1A1BB STEST FILE FOR SPEC ' ) if __name__=='__main__': raise ValueError('widgets.py has no script function')
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/barcode/widgets.py
0.680029
0.206354
widgets.py
pypi
from reportlab.lib.units import inch from reportlab.lib.utils import asNative from reportlab.graphics.barcode.common import Barcode from string import ascii_uppercase, ascii_lowercase, digits as string_digits _patterns = { '0': ("bsbSBsBsb", 0), '1': ("BsbSbsbsB", 1), '2': ("bsBSbsbsB", 2), '3': ("BsBSbsbsb", 3), '4': ("bsbSBsbsB", 4), '5': ("BsbSBsbsb", 5), '6': ("bsBSBsbsb", 6), '7': ("bsbSbsBsB", 7), '8': ("BsbSbsBsb", 8), '9': ("bsBSbsBsb", 9), 'A': ("BsbsbSbsB", 10), 'B': ("bsBsbSbsB", 11), 'C': ("BsBsbSbsb", 12), 'D': ("bsbsBSbsB", 13), 'E': ("BsbsBSbsb", 14), 'F': ("bsBsBSbsb", 15), 'G': ("bsbsbSBsB", 16), 'H': ("BsbsbSBsb", 17), 'I': ("bsBsbSBsb", 18), 'J': ("bsbsBSBsb", 19), 'K': ("BsbsbsbSB", 20), 'L': ("bsBsbsbSB", 21), 'M': ("BsBsbsbSb", 22), 'N': ("bsbsBsbSB", 23), 'O': ("BsbsBsbSb", 24), 'P': ("bsBsBsbSb", 25), 'Q': ("bsbsbsBSB", 26), 'R': ("BsbsbsBSb", 27), 'S': ("bsBsbsBSb", 28), 'T': ("bsbsBsBSb", 29), 'U': ("BSbsbsbsB", 30), 'V': ("bSBsbsbsB", 31), 'W': ("BSBsbsbsb", 32), 'X': ("bSbsBsbsB", 33), 'Y': ("BSbsBsbsb", 34), 'Z': ("bSBsBsbsb", 35), '-': ("bSbsbsBsB", 36), '.': ("BSbsbsBsb", 37), ' ': ("bSBsbsBsb", 38), '*': ("bSbsBsBsb", None), '$': ("bSbSbSbsb", 39), '/': ("bSbSbsbSb", 40), '+': ("bSbsbSbSb", 41), '%': ("bsbSbSbSb", 42) } _stdchrs = string_digits + ascii_uppercase + "-. $/+%" _extended = { '\0': "%U", '\01': "$A", '\02': "$B", '\03': "$C", '\04': "$D", '\05': "$E", '\06': "$F", '\07': "$G", '\010': "$H", '\011': "$I", '\012': "$J", '\013': "$K", '\014': "$L", '\015': "$M", '\016': "$N", '\017': "$O", '\020': "$P", '\021': "$Q", '\022': "$R", '\023': "$S", '\024': "$T", '\025': "$U", '\026': "$V", '\027': "$W", '\030': "$X", '\031': "$Y", '\032': "$Z", '\033': "%A", '\034': "%B", '\035': "%C", '\036': "%D", '\037': "%E", '!': "/A", '"': "/B", '#': "/C", '$': "/D", '%': "/E", '&': "/F", '\'': "/G", '(': "/H", ')': "/I", '*': "/J", '+': "/K", ',': "/L", '/': "/O", ':': "/Z", ';': "%F", '<': "%G", '=': "%H", '>': "%I", '?': "%J", '@': "%V", '[': "%K", '\\': "%L", ']': "%M", '^': "%N", '_': "%O", '`': "%W", 'a': "+A", 'b': "+B", 'c': "+C", 'd': "+D", 'e': "+E", 'f': "+F", 'g': "+G", 'h': "+H", 'i': "+I", 'j': "+J", 'k': "+K", 'l': "+L", 'm': "+M", 'n': "+N", 'o': "+O", 'p': "+P", 'q': "+Q", 'r': "+R", 's': "+S", 't': "+T", 'u': "+U", 'v': "+V", 'w': "+W", 'x': "+X", 'y': "+Y", 'z': "+Z", '{': "%P", '|': "%Q", '}': "%R", '~': "%S", '\177': "%T" } _extchrs = _stdchrs + ascii_lowercase + \ "\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017" + \ "\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" + \ "*!'#&\"(),:;<=>?@[\\]^_`{|}~\177" def _encode39(value, cksum, stop): v = sum([_patterns[c][1] for c in value]) % 43 if cksum: value += _stdchrs[v] if stop: value = '*'+value+'*' return value class _Code39Base(Barcode): barWidth = inch * 0.0075 lquiet = None rquiet = None quiet = 1 gap = None barHeight = None ratio = 2.2 checksum = 1 bearers = 0.0 stop = 1 def __init__(self, value = "", **args): value = asNative(value) for k, v in args.items(): setattr(self, k, v) if self.quiet: if self.lquiet is None: self.lquiet = max(inch * 0.25, self.barWidth * 10.0) self.rquiet = max(inch * 0.25, self.barWidth * 10.0) else: self.lquiet = self.rquiet = 0.0 Barcode.__init__(self, value) def decompose(self): dval = "" for c in self.encoded: dval = dval + _patterns[c][0] + 'i' self.decomposed = dval[:-1] return self.decomposed def _humanText(self): return self.stop and self.encoded[1:-1] or self.encoded class Standard39(_Code39Base): """ Options that may be passed to constructor: value (int, or numeric string required.): The value to encode. barWidth (float, default .0075): X-Dimension, or width of the smallest element Minumum is .0075 inch (7.5 mils). ratio (float, default 2.2): The ratio of wide elements to narrow elements. Must be between 2.0 and 3.0 (or 2.2 and 3.0 if the barWidth is greater than 20 mils (.02 inch)) gap (float or None, default None): width of intercharacter gap. None means "use barWidth". barHeight (float, see default below): Height of the symbol. Default is the height of the two bearer bars (if they exist) plus the greater of .25 inch or .15 times the symbol's length. checksum (bool, default 1): Wether to compute and include the check digit bearers (float, in units of barWidth. default 0): Height of bearer bars (horizontal bars along the top and bottom of the barcode). Default is 0 (no bearers). quiet (bool, default 1): Wether to include quiet zones in the symbol. lquiet (float, see default below): Quiet zone size to left of code, if quiet is true. Default is the greater of .25 inch, or .15 times the symbol's length. rquiet (float, defaults as above): Quiet zone size to right left of code, if quiet is true. stop (bool, default 1): Whether to include start/stop symbols. Sources of Information on Code 39: http://www.semiconductor.agilent.com/barcode/sg/Misc/code_39.html http://www.adams1.com/pub/russadam/39code.html http://www.barcodeman.com/c39_1.html Official Spec, "ANSI/AIM BC1-1995, USS" is available for US$45 from http://www.aimglobal.org/aimstore/ """ def validate(self): vval = [].append self.valid = 1 for c in self.value: if c in ascii_lowercase: c = c.upper() if c not in _stdchrs: self.valid = 0 continue vval(c) self.validated = ''.join(vval.__self__) return self.validated def encode(self): self.encoded = _encode39(self.validated, self.checksum, self.stop) return self.encoded class Extended39(_Code39Base): """ Extended Code 39 is a convention for encoding additional characters not present in stanmdard Code 39 by using pairs of characters to represent the characters missing in Standard Code 39. See Standard39 for arguments. Sources of Information on Extended Code 39: http://www.semiconductor.agilent.com/barcode/sg/Misc/xcode_39.html http://www.barcodeman.com/c39_ext.html """ def validate(self): vval = "" self.valid = 1 for c in self.value: if c not in _extchrs: self.valid = 0 continue vval = vval + c self.validated = vval return vval def encode(self): self.encoded = "" for c in self.validated: if c in _extended: self.encoded = self.encoded + _extended[c] elif c in _stdchrs: self.encoded = self.encoded + c else: raise ValueError self.encoded = _encode39(self.encoded, self.checksum,self.stop) return self.encoded
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/barcode/code39.py
0.42919
0.47926
code39.py
pypi
__version__='3.3.0' __doc__='''This module defines a Area mixin classes''' from reportlab.lib.validators import isNumber, isColorOrNone, isNoneOrShape from reportlab.graphics.widgetbase import Widget from reportlab.graphics.shapes import Rect, Group, Line, Polygon from reportlab.lib.attrmap import AttrMap, AttrMapValue from reportlab.lib.colors import grey class PlotArea(Widget): "Abstract base class representing a chart's plot area, pretty unusable by itself." _attrMap = AttrMap( x = AttrMapValue(isNumber, desc='X position of the lower-left corner of the chart.'), y = AttrMapValue(isNumber, desc='Y position of the lower-left corner of the chart.'), width = AttrMapValue(isNumber, desc='Width of the chart.'), height = AttrMapValue(isNumber, desc='Height of the chart.'), strokeColor = AttrMapValue(isColorOrNone, desc='Color of the plot area border.'), strokeWidth = AttrMapValue(isNumber, desc='Width plot area border.'), fillColor = AttrMapValue(isColorOrNone, desc='Color of the plot area interior.'), background = AttrMapValue(isNoneOrShape, desc='Handle to background object e.g. Rect(0,0,width,height).'), debug = AttrMapValue(isNumber, desc='Used only for debugging.'), ) def __init__(self): self.x = 20 self.y = 10 self.height = 85 self.width = 180 self.strokeColor = None self.strokeWidth = 1 self.fillColor = None self.background = None self.debug = 0 def makeBackground(self): if self.background is not None: BG = self.background if isinstance(BG,Group): g = BG for bg in g.contents: bg.x = self.x bg.y = self.y bg.width = self.width bg.height = self.height else: g = Group() if type(BG) not in (type(()),type([])): BG=(BG,) for bg in BG: bg.x = self.x bg.y = self.y bg.width = self.width bg.height = self.height g.add(bg) return g else: strokeColor,strokeWidth,fillColor=self.strokeColor, self.strokeWidth, self.fillColor if (strokeWidth and strokeColor) or fillColor: g = Group() _3d_dy = getattr(self,'_3d_dy',None) x = self.x y = self.y h = self.height w = self.width if _3d_dy is not None: _3d_dx = self._3d_dx if fillColor and not strokeColor: from reportlab.lib.colors import Blacker c = Blacker(fillColor, getattr(self,'_3d_blacken',0.7)) else: c = strokeColor if not strokeWidth: strokeWidth = 0.5 if fillColor or strokeColor or c: bg = Polygon([x,y,x,y+h,x+_3d_dx,y+h+_3d_dy,x+w+_3d_dx,y+h+_3d_dy,x+w+_3d_dx,y+_3d_dy,x+w,y], strokeColor=strokeColor or c or grey, strokeWidth=strokeWidth, fillColor=fillColor) g.add(bg) g.add(Line(x,y,x+_3d_dx,y+_3d_dy, strokeWidth=0.5, strokeColor=c)) g.add(Line(x+_3d_dx,y+_3d_dy, x+_3d_dx,y+h+_3d_dy,strokeWidth=0.5, strokeColor=c)) fc = Blacker(c, getattr(self,'_3d_blacken',0.8)) g.add(Polygon([x,y,x+_3d_dx,y+_3d_dy,x+w+_3d_dx,y+_3d_dy,x+w,y], strokeColor=strokeColor or c or grey, strokeWidth=strokeWidth, fillColor=fc)) bg = Line(x+_3d_dx,y+_3d_dy, x+w+_3d_dx,y+_3d_dy,strokeWidth=0.5, strokeColor=c) else: bg = None else: bg = Rect(x, y, w, h, strokeColor=strokeColor, strokeWidth=strokeWidth, fillColor=fillColor) if bg: g.add(bg) return g else: return None
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/charts/areas.py
0.821331
0.218211
areas.py
pypi
from reportlab.lib.colors import _PCMYK_black from reportlab.graphics.charts.textlabels import Label from reportlab.graphics.shapes import Circle, Drawing, Group, Line, Rect, String from reportlab.graphics.widgetbase import Widget from reportlab.lib.attrmap import * from reportlab.lib.validators import * from reportlab.lib.units import cm from reportlab.pdfbase.pdfmetrics import getFont from reportlab.graphics.charts.lineplots import _maxWidth class DotBox(Widget): """Returns a dotbox widget.""" #Doesn't use TypedPropertyCollection for labels - this can be a later improvement _attrMap = AttrMap( xlabels = AttrMapValue(isNoneOrListOfNoneOrStrings, desc="List of text labels for boxes on left hand side"), ylabels = AttrMapValue(isNoneOrListOfNoneOrStrings, desc="Text label for second box on left hand side"), labelFontName = AttrMapValue(isString, desc="Name of font used for the labels"), labelFontSize = AttrMapValue(isNumber, desc="Size of font used for the labels"), labelOffset = AttrMapValue(isNumber, desc="Space between label text and grid edge"), strokeWidth = AttrMapValue(isNumber, desc='Width of the grid and dot outline'), gridDivWidth = AttrMapValue(isNumber, desc="Width of each 'box'"), gridColor = AttrMapValue(isColor, desc='Colour for the box and gridding'), dotDiameter = AttrMapValue(isNumber, desc="Diameter of the circle used for the 'dot'"), dotColor = AttrMapValue(isColor, desc='Colour of the circle on the box'), dotXPosition = AttrMapValue(isNumber, desc='X Position of the circle'), dotYPosition = AttrMapValue(isNumber, desc='X Position of the circle'), x = AttrMapValue(isNumber, desc='X Position of dotbox'), y = AttrMapValue(isNumber, desc='Y Position of dotbox'), ) def __init__(self): self.xlabels=["Value", "Blend", "Growth"] self.ylabels=["Small", "Medium", "Large"] self.labelFontName = "Helvetica" self.labelFontSize = 6 self.labelOffset = 5 self.strokeWidth = 0.5 self.gridDivWidth=0.5*cm self.gridColor=colors.Color(25/255.0,77/255.0,135/255.0) self.dotDiameter=0.4*cm self.dotColor=colors.Color(232/255.0,224/255.0,119/255.0) self.dotXPosition = 1 self.dotYPosition = 1 self.x = 30 self.y = 5 def _getDrawingDimensions(self): leftPadding=rightPadding=topPadding=bottomPadding=5 #find width of grid tx=len(self.xlabels)*self.gridDivWidth #add padding (and offset) tx=tx+leftPadding+rightPadding+self.labelOffset #add in maximum width of text tx=tx+_maxWidth(self.xlabels, self.labelFontName, self.labelFontSize) #find height of grid ty=len(self.ylabels)*self.gridDivWidth #add padding (and offset) ty=ty+topPadding+bottomPadding+self.labelOffset #add in maximum width of text ty=ty+_maxWidth(self.ylabels, self.labelFontName, self.labelFontSize) #print (tx, ty) return (tx,ty) def demo(self,drawing=None): if not drawing: tx,ty=self._getDrawingDimensions() drawing = Drawing(tx,ty) drawing.add(self.draw()) return drawing def draw(self): g = Group() #box g.add(Rect(self.x,self.y,len(self.xlabels)*self.gridDivWidth,len(self.ylabels)*self.gridDivWidth, strokeColor=self.gridColor, strokeWidth=self.strokeWidth, fillColor=None)) #internal gridding for f in range (1,len(self.ylabels)): #horizontal g.add(Line(strokeColor=self.gridColor, strokeWidth=self.strokeWidth, x1 = self.x, y1 = self.y+f*self.gridDivWidth, x2 = self.x+len(self.xlabels)*self.gridDivWidth, y2 = self.y+f*self.gridDivWidth)) for f in range (1,len(self.xlabels)): #vertical g.add(Line(strokeColor=self.gridColor, strokeWidth=self.strokeWidth, x1 = self.x+f*self.gridDivWidth, y1 = self.y, x2 = self.x+f*self.gridDivWidth, y2 = self.y+len(self.ylabels)*self.gridDivWidth)) # draw the 'dot' g.add(Circle(strokeColor=self.gridColor, strokeWidth=self.strokeWidth, fillColor=self.dotColor, cx = self.x+(self.dotXPosition*self.gridDivWidth), cy = self.y+(self.dotYPosition*self.gridDivWidth), r = self.dotDiameter/2.0)) #used for centering y-labels (below) ascent=getFont(self.labelFontName).face.ascent if ascent==0: ascent=0.718 # default (from helvetica) ascent=ascent*self.labelFontSize # normalize #do y-labels if self.ylabels != None: for f in range (len(self.ylabels)-1,-1,-1): if self.ylabels[f]!= None: g.add(String(strokeColor=self.gridColor, text = self.ylabels[f], fontName = self.labelFontName, fontSize = self.labelFontSize, fillColor=_PCMYK_black, x = self.x-self.labelOffset, y = self.y+(f*self.gridDivWidth+(self.gridDivWidth-ascent)/2.0), textAnchor = 'end')) #do x-labels if self.xlabels != None: for f in range (0,len(self.xlabels)): if self.xlabels[f]!= None: l=Label() l.x=self.x+(f*self.gridDivWidth)+(self.gridDivWidth+ascent)/2.0 l.y=self.y+(len(self.ylabels)*self.gridDivWidth)+self.labelOffset l.angle=90 l.textAnchor='start' l.fontName = self.labelFontName l.fontSize = self.labelFontSize l.fillColor = _PCMYK_black l.setText(self.xlabels[f]) l.boxAnchor = 'sw' l.draw() g.add(l) return g if __name__ == "__main__": d = DotBox() d.demo().save(fnRoot="dotbox")
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/charts/dotbox.py
0.609408
0.25767
dotbox.py
pypi
__version__='3.3.0' __doc__="Utilities used here and there." from time import mktime, gmtime, strftime from math import log10, pi, floor, sin, cos, hypot import weakref from reportlab.graphics.shapes import transformPoints, inverse, Ellipse, Group, String, numericXShift from reportlab.lib.utils import flatten from reportlab.pdfbase.pdfmetrics import stringWidth ### Dinu's stuff used in some line plots (likely to vansih). def mkTimeTuple(timeString): "Convert a 'dd/mm/yyyy' formatted string to a tuple for use in the time module." L = [0] * 9 dd, mm, yyyy = list(map(int, timeString.split('/'))) L[:3] = [yyyy, mm, dd] return tuple(L) def str2seconds(timeString): "Convert a number of seconds since the epoch into a date string." return mktime(mkTimeTuple(timeString)) def seconds2str(seconds): "Convert a date string into the number of seconds since the epoch." return strftime('%Y-%m-%d', gmtime(seconds)) ### Aaron's rounding function for making nice values on axes. def nextRoundNumber(x): """Return the first 'nice round number' greater than or equal to x Used in selecting apropriate tick mark intervals; we say we want an interval which places ticks at least 10 points apart, work out what that is in chart space, and ask for the nextRoundNumber(). Tries the series 1,2,5,10,20,50,100.., going up or down as needed. """ #guess to nearest order of magnitude if x in (0, 1): return x if x < 0: return -1.0 * nextRoundNumber(-x) else: lg = int(log10(x)) if lg == 0: if x < 1: base = 0.1 else: base = 1.0 elif lg < 0: base = 10.0 ** (lg - 1) else: base = 10.0 ** lg # e.g. base(153) = 100 # base will always be lower than x if base >= x: return base * 1.0 elif (base * 2) >= x: return base * 2.0 elif (base * 5) >= x: return base * 5.0 else: return base * 10.0 _intervals=(.1, .2, .25, .5) _j_max=len(_intervals)-1 def find_interval(lo,hi,I=5): 'determine tick parameters for range [lo, hi] using I intervals' if lo >= hi: if lo==hi: if lo==0: lo = -.1 hi = .1 else: lo = 0.9*lo hi = 1.1*hi else: raise ValueError("lo>hi") x=(hi - lo)/float(I) b= (x>0 and (x<1 or x>10)) and 10**floor(log10(x)) or 1 b = b while 1: a = x/b if a<=_intervals[-1]: break b = b*10 j = 0 while a>_intervals[j]: j = j + 1 while 1: ss = _intervals[j]*b n = lo/ss l = int(n)-(n<0) n = ss*l x = ss*(l+I) a = I*ss if n>0: if a>=hi: n = 0.0 x = a elif hi<0: a = -a if lo>a: n = a x = 0 if hi<=x and n<=lo: break j = j + 1 if j>_j_max: j = 0 b = b*10 return n, x, ss, lo - n + x - hi def find_good_grid(lower,upper,n=(4,5,6,7,8,9), grid=None): if grid: t = divmod(lower,grid)[0] * grid hi, z = divmod(upper,grid) if z>1e-8: hi = hi+1 hi = hi*grid else: try: n[0] except TypeError: n = range(max(1,n-2),max(n+3,2)) w = 1e308 for i in n: z=find_interval(lower,upper,i) if z[3]<w: t, hi, grid = z[:3] w=z[3] return t, hi, grid def ticks(lower, upper, n=(4,5,6,7,8,9), split=1, percent=0, grid=None, labelVOffset=0): ''' return tick positions and labels for range lower<=x<=upper n=number of intervals to try (can be a list or sequence) split=1 return ticks then labels else (tick,label) pairs ''' t, hi, grid = find_good_grid(lower, upper, n, grid) power = floor(log10(grid)) if power==0: power = 1 w = grid/10.**power w = int(w)!=w if power > 3 or power < -3: format = '%+'+repr(w+7)+'.0e' else: if power >= 0: digits = int(power)+w format = '%' + repr(digits)+'.0f' else: digits = w-int(power) format = '%'+repr(digits+2)+'.'+repr(digits)+'f' if percent: format=format+'%%' T = [] n = int(float(hi-t)/grid+0.1)+1 if split: labels = [] for i in range(n): v = t+grid*i T.append(v) labels.append(format % (v+labelVOffset)) return T, labels else: for i in range(n): v = t+grid*i T.append((v, format % (v+labelVOffset))) return T def findNones(data): m = len(data) if None in data: b = 0 while b<m and data[b] is None: b += 1 if b==m: return data l = m-1 while data[l] is None: l -= 1 l+=1 if b or l: data = data[b:l] I = [i for i in range(len(data)) if data[i] is None] for i in I: data[i] = 0.5*(data[i-1]+data[i+1]) return b, l, data return 0,m,data def pairFixNones(pairs): Y = [x[1] for x in pairs] b,l,nY = findNones(Y) m = len(Y) if b or l<m or nY!=Y: if b or l<m: pairs = pairs[b:l] pairs = [(x[0],y) for x,y in zip(pairs,nY)] return pairs def maverage(data,n=6): data = (n-1)*[data[0]]+data data = [float(sum(data[i-n:i]))/n for i in range(n,len(data)+1)] return data def pairMaverage(data,n=6): return [(x[0],s) for x,s in zip(data, maverage([x[1] for x in data],n))] class DrawTimeCollector: ''' generic mechanism for collecting information about nodes at the time they are about to be drawn ''' def __init__(self,formats=['gif']): self._nodes = weakref.WeakKeyDictionary() self.clear() self._pmcanv = None self.formats = formats self.disabled = False def clear(self): self._info = [] self._info_append = self._info.append def record(self,func,node,*args,**kwds): self._nodes[node] = (func,args,kwds) node.__dict__['_drawTimeCallback'] = self def __call__(self,node,canvas,renderer): func = self._nodes.get(node,None) if func: func, args, kwds = func i = func(node,canvas,renderer, *args, **kwds) if i is not None: self._info_append(i) @staticmethod def rectDrawTimeCallback(node,canvas,renderer,**kwds): A = getattr(canvas,'ctm',None) if not A: return x1 = node.x y1 = node.y x2 = x1 + node.width y2 = y1 + node.height D = kwds.copy() D['rect']=DrawTimeCollector.transformAndFlatten(A,((x1,y1),(x2,y2))) return D @staticmethod def transformAndFlatten(A,p): ''' transform an flatten a list of points A transformation matrix p points [(x0,y0),....(xk,yk).....] ''' if tuple(A)!=(1,0,0,1,0,0): iA = inverse(A) p = transformPoints(iA,p) return tuple(flatten(p)) @property def pmcanv(self): if not self._pmcanv: import renderPM self._pmcanv = renderPM.PMCanvas(1,1) return self._pmcanv def wedgeDrawTimeCallback(self,node,canvas,renderer,**kwds): A = getattr(canvas,'ctm',None) if not A: return if isinstance(node,Ellipse): c = self.pmcanv c.ellipse(node.cx, node.cy, node.rx,node.ry) p = c.vpath p = [(x[1],x[2]) for x in p] else: p = node.asPolygon().points p = [(p[i],p[i+1]) for i in range(0,len(p),2)] D = kwds.copy() D['poly'] = self.transformAndFlatten(A,p) return D def save(self,fnroot): ''' save the current information known to this collector fnroot is the root name of a resource to name the saved info override this to get the right semantics for your collector ''' import pprint f=open(fnroot+'.default-collector.out','w') try: pprint.pprint(self._info,f) finally: f.close() def xyDist(xxx_todo_changeme, xxx_todo_changeme1 ): '''return distance between two points''' (x0,y0) = xxx_todo_changeme (x1,y1) = xxx_todo_changeme1 return hypot((x1-x0),(y1-y0)) def lineSegmentIntersect(xxx_todo_changeme2, xxx_todo_changeme3, xxx_todo_changeme4, xxx_todo_changeme5 ): (x00,y00) = xxx_todo_changeme2 (x01,y01) = xxx_todo_changeme3 (x10,y10) = xxx_todo_changeme4 (x11,y11) = xxx_todo_changeme5 p = x00,y00 r = x01-x00,y01-y00 q = x10,y10 s = x11-x10,y11-y10 rs = float(r[0]*s[1]-r[1]*s[0]) qp = q[0]-p[0],q[1]-p[1] qpr = qp[0]*r[1]-qp[1]*r[0] qps = qp[0]*s[1]-qp[1]*s[0] if abs(rs)<1e-8: if abs(qpr)<1e-8: return 'collinear' return None t = qps/rs u = qpr/rs if 0<=t<=1 and 0<=u<=1: return p[0]+t*r[0], p[1]+t*r[1] def makeCircularString(x, y, radius, angle, text, fontName, fontSize, inside=0, G=None,textAnchor='start'): '''make a group with circular text in it''' if not G: G = Group() angle %= 360 pi180 = pi/180 phi = angle*pi180 width = stringWidth(text, fontName, fontSize) sig = inside and -1 or 1 hsig = sig*0.5 sig90 = sig*90 if textAnchor!='start': if textAnchor=='middle': phi += sig*(0.5*width)/radius elif textAnchor=='end': phi += sig*float(width)/radius elif textAnchor=='numeric': phi += sig*float(numericXShift(textAnchor,text,width,fontName,fontSize,None))/radius for letter in text: width = stringWidth(letter, fontName, fontSize) beta = float(width)/radius h = Group() h.add(String(0, 0, letter, fontName=fontName,fontSize=fontSize,textAnchor="start")) h.translate(x+cos(phi)*radius,y+sin(phi)*radius) #translate to radius and angle h.rotate((phi-hsig*beta)/pi180-sig90) # rotate as needed G.add(h) #add to main group phi -= sig*beta #increment return G class CustomDrawChanger: ''' a class to simplify making changes at draw time ''' def __init__(self): self.store = None def __call__(self,change,obj): if change: self.store = self._changer(obj) assert isinstance(self.store,dict), '%s.changer should return a dict of changed attributes' % self.__class__.__name__ elif self.store is not None: for a,v in self.store.items(): setattr(obj,a,v) self.store = None def _changer(self,obj): ''' When implemented this method should return a dictionary of original attribute values so that a future self(False,obj) can restore them. ''' raise RuntimeError('Abstract method _changer called') class FillPairedData(list): def __init__(self,v,other=0): list.__init__(self,v) self.other = other
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/charts/utils.py
0.541045
0.34308
utils.py
pypi
__version__='3.3.0' __doc__="""This will be a collection of legends to be used with charts.""" import copy from reportlab.lib import colors from reportlab.lib.validators import isNumber, OneOf, isString, isColorOrNone,\ isNumberOrNone, isListOfNumbersOrNone, isBoolean,\ EitherOr, NoneOr, AutoOr, isAuto, Auto, isBoxAnchor, SequenceOf, isInstanceOf from reportlab.lib.attrmap import * from reportlab.pdfbase.pdfmetrics import stringWidth, getFont from reportlab.graphics.widgetbase import Widget, TypedPropertyCollection, PropHolder from reportlab.graphics.shapes import Drawing, Group, String, Rect, Line, STATE_DEFAULTS from reportlab.graphics.widgets.markers import uSymbol2Symbol, isSymbol from reportlab.lib.utils import isSeq, find_locals, isStr, asNative from reportlab.graphics.shapes import _baseGFontName def _transMax(n,A): X = n*[0] m = 0 for a in A: m = max(m,len(a)) for i,x in enumerate(a): X[i] = max(X[i],x) X = [0] + X[:m] for i in range(m): X[i+1] += X[i] return X def _objStr(s): if isStr(s): return asNative(s) else: return str(s) def _getStr(s): if isSeq(s): return list(map(_getStr,s)) else: return _objStr(s) def _getLines(s): if isSeq(s): return tuple([(x or '').split('\n') for x in s]) else: return (s or '').split('\n') def _getLineCount(s): T = _getLines(s) if isSeq(s): return max([len(x) for x in T]) else: return len(T) def _getWidths(i,s, fontName, fontSize, subCols): S = [] aS = S.append if isSeq(s): for j,t in enumerate(s): sc = subCols[j,i] fN = getattr(sc,'fontName',fontName) fS = getattr(sc,'fontSize',fontSize) m = [stringWidth(x, fN, fS) for x in t.split('\n')] m = max(sc.minWidth,m and max(m) or 0) aS(m) aS(sc.rpad) del S[-1] else: sc = subCols[0,i] fN = getattr(sc,'fontName',fontName) fS = getattr(sc,'fontSize',fontSize) m = [stringWidth(x, fN, fS) for x in s.split('\n')] aS(max(sc.minWidth,m and max(m) or 0)) return S class SubColProperty(PropHolder): dividerLines = 0 _attrMap = AttrMap( minWidth = AttrMapValue(isNumber,desc="minimum width for this subcol"), rpad = AttrMapValue(isNumber,desc="right padding for this subcol"), align = AttrMapValue(OneOf('left','right','center','centre','numeric'),desc='alignment in subCol'), fontName = AttrMapValue(isString, desc="Font name of the strings"), fontSize = AttrMapValue(isNumber, desc="Font size of the strings"), leading = AttrMapValue(isNumberOrNone, desc="leading for the strings"), fillColor = AttrMapValue(isColorOrNone, desc="fontColor"), underlines = AttrMapValue(EitherOr((NoneOr(isInstanceOf(Line)),SequenceOf(isInstanceOf(Line),emptyOK=0,lo=0,hi=0x7fffffff))), desc="underline definitions"), overlines = AttrMapValue(EitherOr((NoneOr(isInstanceOf(Line)),SequenceOf(isInstanceOf(Line),emptyOK=0,lo=0,hi=0x7fffffff))), desc="overline definitions"), dx = AttrMapValue(isNumber, desc="x offset from default position"), dy = AttrMapValue(isNumber, desc="y offset from default position"), vAlign = AttrMapValue(OneOf('top','bottom','middle'),desc='vertical alignment in the row'), ) class LegendCallout: def _legendValues(legend,*args): '''return a tuple of values from the first function up the stack with isinstance(self,legend)''' L = find_locals(lambda L: L.get('self',None) is legend and L or None) return tuple([L[a] for a in args]) _legendValues = staticmethod(_legendValues) def _selfOrLegendValues(self,legend,*args): L = find_locals(lambda L: L.get('self',None) is legend and L or None) return tuple([getattr(self,a,L[a]) for a in args]) def __call__(self,legend,g,thisx,y,colName): col, name = colName class LegendSwatchCallout(LegendCallout): def __call__(self,legend,g,thisx,y,i,colName,swatch): col, name = colName class LegendColEndCallout(LegendCallout): def __call__(self,legend, g, x, xt, y, width, lWidth): pass class Legend(Widget): """A simple legend containing rectangular swatches and strings. The swatches are filled rectangles whenever the respective color object in 'colorNamePairs' is a subclass of Color in reportlab.lib.colors. Otherwise the object passed instead is assumed to have 'x', 'y', 'width' and 'height' attributes. A legend then tries to set them or catches any error. This lets you plug-in any widget you like as a replacement for the default rectangular swatches. Strings can be nicely aligned left or right to the swatches. """ _attrMap = AttrMap( x = AttrMapValue(isNumber, desc="x-coordinate of upper-left reference point"), y = AttrMapValue(isNumber, desc="y-coordinate of upper-left reference point"), deltax = AttrMapValue(isNumberOrNone, desc="x-distance between neighbouring swatches"), deltay = AttrMapValue(isNumberOrNone, desc="y-distance between neighbouring swatches"), dxTextSpace = AttrMapValue(isNumber, desc="Distance between swatch rectangle and text"), autoXPadding = AttrMapValue(isNumber, desc="x Padding between columns if deltax=None",advancedUsage=1), autoYPadding = AttrMapValue(isNumber, desc="y Padding between rows if deltay=None",advancedUsage=1), yGap = AttrMapValue(isNumber, desc="Additional gap between rows",advancedUsage=1), dx = AttrMapValue(isNumber, desc="Width of swatch rectangle"), dy = AttrMapValue(isNumber, desc="Height of swatch rectangle"), columnMaximum = AttrMapValue(isNumber, desc="Max. number of items per column"), alignment = AttrMapValue(OneOf("left", "right"), desc="Alignment of text with respect to swatches"), colorNamePairs = AttrMapValue(None, desc="List of color/name tuples (color can also be widget)"), fontName = AttrMapValue(isString, desc="Font name of the strings"), fontSize = AttrMapValue(isNumber, desc="Font size of the strings"), leading = AttrMapValue(isNumberOrNone, desc="text leading"), fillColor = AttrMapValue(isColorOrNone, desc="swatches filling color"), strokeColor = AttrMapValue(isColorOrNone, desc="Border color of the swatches"), strokeWidth = AttrMapValue(isNumber, desc="Width of the border color of the swatches"), swatchMarker = AttrMapValue(NoneOr(AutoOr(isSymbol)), desc="None, Auto() or makeMarker('Diamond') ...",advancedUsage=1), callout = AttrMapValue(None, desc="a user callout(self,g,x,y,(color,text))",advancedUsage=1), boxAnchor = AttrMapValue(isBoxAnchor,'Anchor point for the legend area'), variColumn = AttrMapValue(isBoolean,'If true column widths may vary (default is false)',advancedUsage=1), dividerLines = AttrMapValue(OneOf(0,1,2,3,4,5,6,7),'If 1 we have dividers between the rows | 2 for extra top | 4 for bottom',advancedUsage=1), dividerWidth = AttrMapValue(isNumber, desc="dividerLines width",advancedUsage=1), dividerColor = AttrMapValue(isColorOrNone, desc="dividerLines color",advancedUsage=1), dividerDashArray = AttrMapValue(isListOfNumbersOrNone, desc='Dash array for dividerLines.',advancedUsage=1), dividerOffsX = AttrMapValue(SequenceOf(isNumber,emptyOK=0,lo=2,hi=2), desc='divider lines X offsets',advancedUsage=1), dividerOffsY = AttrMapValue(isNumber, desc="dividerLines Y offset",advancedUsage=1), colEndCallout = AttrMapValue(None, desc="a user callout(self,g, x, xt, y,width, lWidth)",advancedUsage=1), subCols = AttrMapValue(None,desc="subColumn properties"), swatchCallout = AttrMapValue(None, desc="a user swatch callout(self,g,x,y,i,(col,name),swatch)",advancedUsage=1), swdx = AttrMapValue(isNumber, desc="x position adjustment for the swatch"), swdy = AttrMapValue(isNumber, desc="y position adjustment for the swatch"), ) def __init__(self): # Upper-left reference point. self.x = 0 self.y = 0 # Alginment of text with respect to swatches. self.alignment = "left" # x- and y-distances between neighbouring swatches. self.deltax = 75 self.deltay = 20 self.autoXPadding = 5 self.autoYPadding = 2 # Size of swatch rectangle. self.dx = 10 self.dy = 10 self.swdx = 0 self.swdy = 0 # Distance between swatch rectangle and text. self.dxTextSpace = 10 # Max. number of items per column. self.columnMaximum = 3 # Color/name pairs. self.colorNamePairs = [ (colors.red, "red"), (colors.blue, "blue"), (colors.green, "green"), (colors.pink, "pink"), (colors.yellow, "yellow") ] # Font name and size of the labels. self.fontName = STATE_DEFAULTS['fontName'] self.fontSize = STATE_DEFAULTS['fontSize'] self.leading = None #will be used as 1.2*fontSize self.fillColor = STATE_DEFAULTS['fillColor'] self.strokeColor = STATE_DEFAULTS['strokeColor'] self.strokeWidth = STATE_DEFAULTS['strokeWidth'] self.swatchMarker = None self.boxAnchor = 'nw' self.yGap = 0 self.variColumn = 0 self.dividerLines = 0 self.dividerWidth = 0.5 self.dividerDashArray = None self.dividerColor = colors.black self.dividerOffsX = (0,0) self.dividerOffsY = 0 self.colEndCallout = None self._init_subCols() def _init_subCols(self): sc = self.subCols = TypedPropertyCollection(SubColProperty) sc.rpad = 1 sc.dx = sc.dy = sc.minWidth = 0 sc.align = 'right' sc[0].align = 'left' sc.vAlign = 'top' #that's current sc.leading = None def _getChartStyleName(self,chart): for a in 'lines', 'bars', 'slices', 'strands': if hasattr(chart,a): return a return None def _getChartStyle(self,chart): return getattr(chart,self._getChartStyleName(chart),None) def _getTexts(self,colorNamePairs): if not isAuto(colorNamePairs): texts = [_getStr(p[1]) for p in colorNamePairs] else: chart = getattr(colorNamePairs,'chart',getattr(colorNamePairs,'obj',None)) texts = [chart.getSeriesName(i,'series %d' % i) for i in range(chart._seriesCount)] return texts def _calculateMaxBoundaries(self, colorNamePairs): "Calculate the maximum width of some given strings." fontName = self.fontName fontSize = self.fontSize subCols = self.subCols M = [_getWidths(i, m, fontName, fontSize, subCols) for i,m in enumerate(self._getTexts(colorNamePairs))] if not M: return [0,0] n = max([len(m) for m in M]) if self.variColumn: columnMaximum = self.columnMaximum return [_transMax(n,M[r:r+columnMaximum]) for r in range(0,len(M),self.columnMaximum)] else: return _transMax(n,M) def _calcHeight(self): dy = self.dy yGap = self.yGap thisy = upperlefty = self.y - dy fontSize = self.fontSize fontName = self.fontName ascent=getFont(fontName).face.ascent/1000. if ascent==0: ascent=0.718 # default (from helvetica) ascent *= fontSize leading = fontSize*1.2 deltay = self.deltay if not deltay: deltay = max(dy,leading)+self.autoYPadding columnCount = 0 count = 0 lowy = upperlefty lim = self.columnMaximum - 1 for name in self._getTexts(self.colorNamePairs): y0 = thisy+(dy-ascent)*0.5 y = y0 - _getLineCount(name)*leading leadingMove = 2*y0-y-thisy newy = thisy-max(deltay,leadingMove)-yGap lowy = min(y,newy,lowy) if count==lim: count = 0 thisy = upperlefty columnCount += 1 else: thisy = newy count = count+1 return upperlefty - lowy def _defaultSwatch(self,x,thisy,dx,dy,fillColor,strokeWidth,strokeColor): return Rect(x, thisy, dx, dy, fillColor = fillColor, strokeColor = strokeColor, strokeWidth = strokeWidth, ) def draw(self): colorNamePairs = self.colorNamePairs autoCP = isAuto(colorNamePairs) if autoCP: chart = getattr(colorNamePairs,'chart',getattr(colorNamePairs,'obj',None)) swatchMarker = None autoCP = Auto(obj=chart) n = chart._seriesCount chartTexts = self._getTexts(colorNamePairs) else: swatchMarker = getattr(self,'swatchMarker',None) if isAuto(swatchMarker): chart = getattr(swatchMarker,'chart',getattr(swatchMarker,'obj',None)) swatchMarker = Auto(obj=chart) n = len(colorNamePairs) dx = self.dx dy = self.dy alignment = self.alignment columnMaximum = self.columnMaximum deltax = self.deltax deltay = self.deltay dxTextSpace = self.dxTextSpace fontName = self.fontName fontSize = self.fontSize fillColor = self.fillColor strokeWidth = self.strokeWidth strokeColor = self.strokeColor subCols = self.subCols leading = fontSize*1.2 yGap = self.yGap if not deltay: deltay = max(dy,leading)+self.autoYPadding ba = self.boxAnchor maxWidth = self._calculateMaxBoundaries(colorNamePairs) nCols = int((n+columnMaximum-1)/(columnMaximum*1.0)) xW = dx+dxTextSpace+self.autoXPadding variColumn = self.variColumn if variColumn: width = sum([m[-1] for m in maxWidth])+xW*nCols else: deltax = max(maxWidth[-1]+xW,deltax) width = nCols*deltax maxWidth = nCols*[maxWidth] thisx = self.x thisy = self.y - self.dy if ba not in ('ne','n','nw','autoy'): height = self._calcHeight() if ba in ('e','c','w'): thisy += height/2. else: thisy += height if ba not in ('nw','w','sw','autox'): if ba in ('n','c','s'): thisx -= width/2 else: thisx -= width upperlefty = thisy g = Group() ascent=getFont(fontName).face.ascent/1000. if ascent==0: ascent=0.718 # default (from helvetica) ascent *= fontSize # normalize lim = columnMaximum - 1 callout = getattr(self,'callout',None) scallout = getattr(self,'swatchCallout',None) dividerLines = self.dividerLines if dividerLines: dividerWidth = self.dividerWidth dividerColor = self.dividerColor dividerDashArray = self.dividerDashArray dividerOffsX = self.dividerOffsX dividerOffsY = self.dividerOffsY for i in range(n): if autoCP: col = autoCP col.index = i name = chartTexts[i] else: col, name = colorNamePairs[i] if isAuto(swatchMarker): col = swatchMarker col.index = i if isAuto(name): name = getattr(swatchMarker,'chart',getattr(swatchMarker,'obj',None)).getSeriesName(i,'series %d' % i) T = _getLines(name) S = [] aS = S.append j = int(i/(columnMaximum*1.0)) jOffs = maxWidth[j] # thisy+dy/2 = y+leading/2 y = y0 = thisy+(dy-ascent)*0.5 if callout: callout(self,g,thisx,y,(col,name)) if alignment == "left": x = thisx xn = thisx+jOffs[-1]+dxTextSpace elif alignment == "right": x = thisx+dx+dxTextSpace xn = thisx else: raise ValueError("bad alignment") if not isSeq(name): T = [T] lineCount = _getLineCount(name) yd = y for k,lines in enumerate(T): y = y0 kk = k*2 x1 = x+jOffs[kk] x2 = x+jOffs[kk+1] sc = subCols[k,i] anchor = sc.align scdx = sc.dx scdy = sc.dy fN = getattr(sc,'fontName',fontName) fS = getattr(sc,'fontSize',fontSize) fC = getattr(sc,'fillColor',fillColor) fL = sc.leading or 1.2*fontSize if fN==fontName: fA = (ascent*fS)/fontSize else: fA = getFont(fontName).face.ascent/1000. if fA==0: fA=0.718 fA *= fS vA = sc.vAlign if vA=='top': vAdy = 0 else: vAdy = -fL * (lineCount - len(lines)) if vA=='middle': vAdy *= 0.5 if anchor=='left': anchor = 'start' xoffs = x1 elif anchor=='right': anchor = 'end' xoffs = x2 elif anchor=='numeric': xoffs = x2 else: anchor = 'middle' xoffs = 0.5*(x1+x2) for t in lines: aS(String(xoffs+scdx,y+scdy+vAdy,t,fontName=fN,fontSize=fS,fillColor=fC, textAnchor = anchor)) y -= fL yd = min(yd,y) y += fL for iy, a in ((y-max(fL-fA,0),'underlines'),(y+fA,'overlines')): il = getattr(sc,a,None) if il: if not isinstance(il,(tuple,list)): il = (il,) for l in il: l = copy.copy(l) l.y1 += iy l.y2 += iy l.x1 += x1 l.x2 += x2 aS(l) x = xn y = yd leadingMove = 2*y0-y-thisy if dividerLines: xd = thisx+dx+dxTextSpace+jOffs[-1]+dividerOffsX[1] yd = thisy+dy*0.5+dividerOffsY if ((dividerLines&1) and i%columnMaximum) or ((dividerLines&2) and not i%columnMaximum): g.add(Line(thisx+dividerOffsX[0],yd,xd,yd, strokeColor=dividerColor, strokeWidth=dividerWidth, strokeDashArray=dividerDashArray)) if (dividerLines&4) and (i%columnMaximum==lim or i==(n-1)): yd -= max(deltay,leadingMove)+yGap g.add(Line(thisx+dividerOffsX[0],yd,xd,yd, strokeColor=dividerColor, strokeWidth=dividerWidth, strokeDashArray=dividerDashArray)) # Make a 'normal' color swatch... swatchX = x + getattr(self,'swdx',0) swatchY = thisy + getattr(self,'swdy',0) if isAuto(col): chart = getattr(col,'chart',getattr(col,'obj',None)) c = chart.makeSwatchSample(getattr(col,'index',i),swatchX,swatchY,dx,dy) elif isinstance(col, colors.Color): if isSymbol(swatchMarker): c = uSymbol2Symbol(swatchMarker,swatchX+dx/2.,swatchY+dy/2.,col) else: c = self._defaultSwatch(swatchX,swatchY,dx,dy,fillColor=col,strokeWidth=strokeWidth,strokeColor=strokeColor) elif col is not None: try: c = copy.deepcopy(col) c.x = swatchX c.y = swatchY c.width = dx c.height = dy except: c = None else: c = None if c: g.add(c) if scallout: scallout(self,g,thisx,y0,i,(col,name),c) for s in S: g.add(s) if self.colEndCallout and (i%columnMaximum==lim or i==(n-1)): if alignment == "left": xt = thisx else: xt = thisx+dx+dxTextSpace yd = thisy+dy*0.5+dividerOffsY - (max(deltay,leadingMove)+yGap) self.colEndCallout(self, g, thisx, xt, yd, jOffs[-1], jOffs[-1]+dx+dxTextSpace) if i%columnMaximum==lim: if variColumn: thisx += jOffs[-1]+xW else: thisx = thisx+deltax thisy = upperlefty else: thisy = thisy-max(deltay,leadingMove)-yGap return g def demo(self): "Make sample legend." d = Drawing(200, 100) legend = Legend() legend.alignment = 'left' legend.x = 0 legend.y = 100 legend.dxTextSpace = 5 items = 'red green blue yellow pink black white'.split() items = [(getattr(colors, i), i) for i in items] legend.colorNamePairs = items d.add(legend, 'legend') return d class TotalAnnotator(LegendColEndCallout): def __init__(self, lText='Total', rText='0.0', fontName=_baseGFontName, fontSize=10, fillColor=colors.black, strokeWidth=0.5, strokeColor=colors.black, strokeDashArray=None, dx=0, dy=0, dly=0, dlx=(0,0)): self.lText = lText self.rText = rText self.fontName = fontName self.fontSize = fontSize self.fillColor = fillColor self.dy = dy self.dx = dx self.dly = dly self.dlx = dlx self.strokeWidth = strokeWidth self.strokeColor = strokeColor self.strokeDashArray = strokeDashArray def __call__(self,legend, g, x, xt, y, width, lWidth): from reportlab.graphics.shapes import String, Line fontSize = self.fontSize fontName = self.fontName fillColor = self.fillColor strokeColor = self.strokeColor strokeWidth = self.strokeWidth ascent=getFont(fontName).face.ascent/1000. if ascent==0: ascent=0.718 # default (from helvetica) ascent *= fontSize leading = fontSize*1.2 yt = y+self.dy-ascent*1.3 if self.lText and fillColor: g.add(String(xt,yt,self.lText, fontName=fontName, fontSize=fontSize, fillColor=fillColor, textAnchor = "start")) if self.rText: g.add(String(xt+width,yt,self.rText, fontName=fontName, fontSize=fontSize, fillColor=fillColor, textAnchor = "end")) if strokeWidth and strokeColor: yL = y+self.dly-leading g.add(Line(x+self.dlx[0],yL,x+self.dlx[1]+lWidth,yL, strokeColor=strokeColor, strokeWidth=strokeWidth, strokeDashArray=self.strokeDashArray)) class LineSwatch(Widget): """basically a Line with properties added so it can be used in a LineLegend""" _attrMap = AttrMap( x = AttrMapValue(isNumber, desc="x-coordinate for swatch line start point"), y = AttrMapValue(isNumber, desc="y-coordinate for swatch line start point"), width = AttrMapValue(isNumber, desc="length of swatch line"), height = AttrMapValue(isNumber, desc="used for line strokeWidth"), strokeColor = AttrMapValue(isColorOrNone, desc="color of swatch line"), strokeDashArray = AttrMapValue(isListOfNumbersOrNone, desc="dash array for swatch line"), ) def __init__(self): from reportlab.lib.colors import red self.x = 0 self.y = 0 self.width = 20 self.height = 1 self.strokeColor = red self.strokeDashArray = None def draw(self): l = Line(self.x,self.y,self.x+self.width,self.y) l.strokeColor = self.strokeColor l.strokeDashArray = self.strokeDashArray l.strokeWidth = self.height return l class LineLegend(Legend): """A subclass of Legend for drawing legends with lines as the swatches rather than rectangles. Useful for lineCharts and linePlots. Should be similar in all other ways the the standard Legend class. """ def __init__(self): Legend.__init__(self) # Size of swatch rectangle. self.dx = 10 self.dy = 2 def _defaultSwatch(self,x,thisy,dx,dy,fillColor,strokeWidth,strokeColor): l = LineSwatch() l.x = x l.y = thisy l.width = dx l.height = dy l.strokeColor = fillColor return l
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/charts/legends.py
0.778018
0.232898
legends.py
pypi
from reportlab.graphics.shapes import Drawing, Polygon, Line def _getShaded(col,shd=None,shading=0.1): if shd is None: from reportlab.lib.colors import Blacker if col: shd = Blacker(col,1-shading) return shd def _getLit(col,shd=None,lighting=0.1): if shd is None: from reportlab.lib.colors import Whiter if col: shd = Whiter(col,1-lighting) return shd def _draw_3d_bar(G, x1, x2, y0, yhigh, xdepth, ydepth, fillColor=None, fillColorShaded=None, strokeColor=None, strokeWidth=1, shading=0.1): fillColorShaded = _getShaded(fillColor,None,shading) fillColorShadedTop = _getShaded(fillColor,None,shading/2.0) def _add_3d_bar(x1, x2, y1, y2, xoff, yoff, G=G,strokeColor=strokeColor, strokeWidth=strokeWidth, fillColor=fillColor): G.add(Polygon((x1,y1, x1+xoff,y1+yoff, x2+xoff,y2+yoff, x2,y2), strokeWidth=strokeWidth, strokeColor=strokeColor, fillColor=fillColor,strokeLineJoin=1)) usd = max(y0, yhigh) if xdepth or ydepth: if y0!=yhigh: #non-zero height _add_3d_bar( x2, x2, y0, yhigh, xdepth, ydepth, fillColor=fillColorShaded) #side _add_3d_bar(x1, x2, usd, usd, xdepth, ydepth, fillColor=fillColorShadedTop) #top G.add(Polygon((x1,y0,x2,y0,x2,yhigh,x1,yhigh), strokeColor=strokeColor, strokeWidth=strokeWidth, fillColor=fillColor,strokeLineJoin=1)) #front if xdepth or ydepth: G.add(Line( x1, usd, x2, usd, strokeWidth=strokeWidth, strokeColor=strokeColor or fillColorShaded)) class _YStrip: def __init__(self,y0,y1, slope, fillColor, fillColorShaded, shading=0.1): self.y0 = y0 self.y1 = y1 self.slope = slope self.fillColor = fillColor self.fillColorShaded = _getShaded(fillColor,fillColorShaded,shading) def _ystrip_poly( x0, x1, y0, y1, xoff, yoff): return [x0,y0,x0+xoff,y0+yoff,x1+xoff,y1+yoff,x1,y1] def _make_3d_line_info( G, x0, x1, y0, y1, z0, z1, theta_x, theta_y, fillColor, fillColorShaded=None, tileWidth=1, strokeColor=None, strokeWidth=None, strokeDashArray=None, shading=0.1): zwidth = abs(z1-z0) xdepth = zwidth*theta_x ydepth = zwidth*theta_y depth_slope = xdepth==0 and 1e150 or -ydepth/float(xdepth) x = float(x1-x0) slope = x==0 and 1e150 or (y1-y0)/x c = slope>depth_slope and _getShaded(fillColor,fillColorShaded,shading) or fillColor zy0 = z0*theta_y zx0 = z0*theta_x tileStrokeWidth = 0.6 if tileWidth is None: D = [(x1,y1)] else: T = ((y1-y0)**2+(x1-x0)**2)**0.5 tileStrokeWidth *= tileWidth if T<tileWidth: D = [(x1,y1)] else: n = int(T/float(tileWidth))+1 dx = float(x1-x0)/n dy = float(y1-y0)/n D = [] a = D.append for i in range(1,n): a((x0+dx*i,y0+dy*i)) a = G.add x_0 = x0+zx0 y_0 = y0+zy0 for x,y in D: x_1 = x+zx0 y_1 = y+zy0 P = Polygon(_ystrip_poly(x_0, x_1, y_0, y_1, xdepth, ydepth), fillColor = c, strokeColor=c, strokeWidth=tileStrokeWidth) a((0,z0,z1,x_0,y_0,P)) x_0 = x_1 y_0 = y_1 from math import pi _pi_2 = pi*0.5 _2pi = 2*pi _180_pi=180./pi def _2rad(angle): return angle/_180_pi def mod_2pi(radians): radians = radians % _2pi if radians<-1e-6: radians += _2pi return radians def _2deg(o): return o*_180_pi def _360(a): a %= 360 if a<-1e-6: a += 360 return a _ZERO = 1e-8 _ONE = 1-_ZERO class _Segment: def __init__(self,s,i,data): S = data[s] x0 = S[i-1][0] y0 = S[i-1][1] x1 = S[i][0] y1 = S[i][1] if x1<x0: x0,y0,x1,y1 = x1,y1,x0,y0 # (y-y0)*(x1-x0) = (y1-y0)*(x-x0) # (x1-x0)*y + (y0-y1)*x = y0*(x1-x0)+x0*(y0-y1) # a*y+b*x = c self.a = float(x1-x0) self.b = float(y1-y0) self.x0 = x0 self.x1 = x1 self.y0 = y0 self.y1 = y1 self.series = s self.i = i self.s = s def __str__(self): return '[(%s,%s),(%s,%s)]' % (self.x0,self.y0,self.x1,self.y1) __repr__ = __str__ def intersect(self,o,I): '''try to find an intersection with _Segment o ''' x0 = self.x0 ox0 = o.x0 assert x0<=ox0 if ox0>self.x1: return 1 if o.s==self.s and o.i in (self.i-1,self.i+1): return a = self.a b = self.b oa = o.a ob = o.b det = ob*a - oa*b if -1e-8<det<1e-8: return dx = x0 - ox0 dy = self.y0 - o.y0 u = (oa*dy - ob*dx)/det ou = (a*dy - b*dx)/det if u<0 or u>1 or ou<0 or ou>1: return x = x0 + u*a y = self.y0 + u*b if _ZERO<u<_ONE: t = self.s,self.i,x,y if t not in I: I.append(t) if _ZERO<ou<_ONE: t = o.s,o.i,x,y if t not in I: I.append(t) def _segKey(a): return (a.x0,a.x1,a.y0,a.y1,a.s,a.i) def find_intersections(data,small=0): ''' data is a sequence of series each series is a list of (x,y) coordinates where x & y are ints or floats find_intersections returns a sequence of 4-tuples i, j, x, y where i is a data index j is an insertion position for data[i] and x, y are coordinates of an intersection of series data[i] with some other series. If correctly implemented we get all such intersections. We don't count endpoint intersections and consider parallel lines as non intersecting (even when coincident). We ignore segments that have an estimated size less than small. ''' #find all line segments S = [] a = S.append for s in range(len(data)): ds = data[s] if not ds: continue n = len(ds) if n==1: continue for i in range(1,n): seg = _Segment(s,i,data) if seg.a+abs(seg.b)>=small: a(seg) S.sort(key=_segKey) I = [] n = len(S) for i in range(0,n-1): s = S[i] for j in range(i+1,n): if s.intersect(S[j],I)==1: break I.sort() return I if __name__=='__main__': from reportlab.graphics.shapes import Drawing from reportlab.lib.colors import lightgrey, pink D = Drawing(300,200) _draw_3d_bar(D, 10, 20, 10, 50, 5, 5, fillColor=lightgrey, strokeColor=pink) _draw_3d_bar(D, 30, 40, 10, 45, 5, 5, fillColor=lightgrey, strokeColor=pink) D.save(formats=['pdf'],outDir='.',fnRoot='_draw_3d_bar') print(find_intersections([[(0,0.5),(1,0.5),(0.5,0),(0.5,1)],[(.2666666667,0.4),(0.1,0.4),(0.1,0.2),(0,0),(1,1)],[(0,1),(0.4,0.1),(1,0.1)]])) print(find_intersections([[(0.1, 0.2), (0.1, 0.4)], [(0, 1), (0.4, 0.1)]])) print(find_intersections([[(0.2, 0.4), (0.1, 0.4)], [(0.1, 0.8), (0.4, 0.1)]])) print(find_intersections([[(0,0),(1,1)],[(0.4,0.1),(1,0.1)]])) print(find_intersections([[(0,0.5),(1,0.5),(0.5,0),(0.5,1)],[(0,0),(1,1)],[(0.1,0.8),(0.4,0.1),(1,0.1)]]))
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/charts/utils3d.py
0.493164
0.432603
utils3d.py
pypi
__version__='3.3.0' from reportlab.lib import colors from reportlab.lib.utils import simpleSplit from reportlab.lib.validators import isNumber, isNumberOrNone, OneOf, isColorOrNone, isString, \ isTextAnchor, isBoxAnchor, isBoolean, NoneOr, isInstanceOf, isNoneOrString, isNoneOrCallable, \ isSubclassOf from reportlab.lib.attrmap import * from reportlab.pdfbase.pdfmetrics import stringWidth, getAscentDescent from reportlab.graphics.shapes import Drawing, Group, Circle, Rect, String, STATE_DEFAULTS from reportlab.graphics.widgetbase import Widget, PropHolder from reportlab.graphics.shapes import DirectDraw from reportlab.platypus import XPreformatted, Flowable from reportlab.lib.styles import ParagraphStyle, PropertySet from reportlab.lib.enums import TA_LEFT, TA_RIGHT, TA_CENTER _ta2al = dict(start=TA_LEFT,end=TA_RIGHT,middle=TA_CENTER) from ..utils import text2Path as _text2Path #here for continuity _A2BA= { 'x': {0:'n', 45:'ne', 90:'e', 135:'se', 180:'s', 225:'sw', 270:'w', 315: 'nw', -45: 'nw'}, 'y': {0:'e', 45:'se', 90:'s', 135:'sw', 180:'w', 225:'nw', 270:'n', 315: 'ne', -45: 'ne'}, } try: from rlextra.graphics.canvasadapter import DirectDrawFlowable except ImportError: DirectDrawFlowable = None _BA2TA={'w':'start','nw':'start','sw':'start','e':'end', 'ne': 'end', 'se':'end', 'n':'middle','s':'middle','c':'middle'} class Label(Widget): """A text label to attach to something else, such as a chart axis. This allows you to specify an offset, angle and many anchor properties relative to the label's origin. It allows, for example, angled multiline axis labels. """ # fairly straight port of Robin Becker's textbox.py to new widgets # framework. _attrMap = AttrMap( x = AttrMapValue(isNumber,desc=''), y = AttrMapValue(isNumber,desc=''), dx = AttrMapValue(isNumber,desc='delta x - offset'), dy = AttrMapValue(isNumber,desc='delta y - offset'), angle = AttrMapValue(isNumber,desc='angle of label: default (0), 90 is vertical, 180 is upside down, etc'), boxAnchor = AttrMapValue(isBoxAnchor,desc='anchoring point of the label'), boxStrokeColor = AttrMapValue(isColorOrNone,desc='border color of the box'), boxStrokeWidth = AttrMapValue(isNumber,desc='border width'), boxFillColor = AttrMapValue(isColorOrNone,desc='the filling color of the box'), boxTarget = AttrMapValue(OneOf('normal','anti','lo','hi'),desc="one of ('normal','anti','lo','hi')"), fillColor = AttrMapValue(isColorOrNone,desc='label text color'), strokeColor = AttrMapValue(isColorOrNone,desc='label text border color'), strokeWidth = AttrMapValue(isNumber,desc='label text border width'), text = AttrMapValue(isString,desc='the actual text to display'), fontName = AttrMapValue(isString,desc='the name of the font used'), fontSize = AttrMapValue(isNumber,desc='the size of the font'), leading = AttrMapValue(isNumberOrNone,desc=''), width = AttrMapValue(isNumberOrNone,desc='the width of the label'), maxWidth = AttrMapValue(isNumberOrNone,desc='maximum width the label can grow to'), height = AttrMapValue(isNumberOrNone,desc='the height of the text'), textAnchor = AttrMapValue(isTextAnchor,desc='the anchoring point of the text inside the label'), visible = AttrMapValue(isBoolean,desc="True if the label is to be drawn"), topPadding = AttrMapValue(isNumber,desc='padding at top of box'), leftPadding = AttrMapValue(isNumber,desc='padding at left of box'), rightPadding = AttrMapValue(isNumber,desc='padding at right of box'), bottomPadding = AttrMapValue(isNumber,desc='padding at bottom of box'), useAscentDescent = AttrMapValue(isBoolean,desc="If True then the font's Ascent & Descent will be used to compute default heights and baseline."), customDrawChanger = AttrMapValue(isNoneOrCallable,desc="An instance of CustomDrawChanger to modify the behavior at draw time", _advancedUsage=1), ddf = AttrMapValue(NoneOr(isSubclassOf(DirectDraw),'NoneOrDirectDraw'),desc="A DirectDrawFlowable instance", _advancedUsage=1), ddfKlass = AttrMapValue(NoneOr(isSubclassOf(Flowable),'NoneOrDirectDraw'),desc="A Flowable class for direct drawing (default is XPreformatted", _advancedUsage=1), ddfStyle = AttrMapValue(NoneOr((isSubclassOf(PropertySet),isInstanceOf(PropertySet))),desc="A style or style class for a ddfKlass or None", _advancedUsage=1), ) def __init__(self,**kw): self._setKeywords(**kw) self._setKeywords( _text = 'Multi-Line\nString', boxAnchor = 'c', angle = 0, x = 0, y = 0, dx = 0, dy = 0, topPadding = 0, leftPadding = 0, rightPadding = 0, bottomPadding = 0, boxStrokeWidth = 0.5, boxStrokeColor = None, boxTarget = 'normal', strokeColor = None, boxFillColor = None, leading = None, width = None, maxWidth = None, height = None, fillColor = STATE_DEFAULTS['fillColor'], fontName = STATE_DEFAULTS['fontName'], fontSize = STATE_DEFAULTS['fontSize'], strokeWidth = 0.1, textAnchor = 'start', visible = 1, useAscentDescent = False, ddf = DirectDrawFlowable, ddfKlass = None, ddfStyle = None, ) def setText(self, text): """Set the text property. May contain embedded newline characters. Called by the containing chart or axis.""" self._text = text def setOrigin(self, x, y): """Set the origin. This would be the tick mark or bar top relative to which it is defined. Called by the containing chart or axis.""" self.x = x self.y = y def demo(self): """This shows a label positioned with its top right corner at the top centre of the drawing, and rotated 45 degrees.""" d = Drawing(200, 100) # mark the origin of the label d.add(Circle(100,90, 5, fillColor=colors.green)) lab = Label() lab.setOrigin(100,90) lab.boxAnchor = 'ne' lab.angle = 45 lab.dx = 0 lab.dy = -20 lab.boxStrokeColor = colors.green lab.setText('Another\nMulti-Line\nString') d.add(lab) return d def _getBoxAnchor(self): '''hook for allowing special box anchor effects''' ba = self.boxAnchor if ba in ('autox', 'autoy'): angle = self.angle na = (int((angle%360)/45.)*45)%360 if not (na % 90): # we have a right angle case da = (angle - na) % 360 if abs(da)>5: na = na + (da>0 and 45 or -45) ba = _A2BA[ba[-1]][na] return ba def _getBaseLineRatio(self): if self.useAscentDescent: self._ascent, self._descent = getAscentDescent(self.fontName,self.fontSize) self._baselineRatio = self._ascent/(self._ascent-self._descent) else: self._baselineRatio = 1/1.2 def _computeSizeEnd(self,objH): self._height = self.height or (objH + self.topPadding + self.bottomPadding) self._ewidth = (self._width-self.leftPadding-self.rightPadding) self._eheight = (self._height-self.topPadding-self.bottomPadding) boxAnchor = self._getBoxAnchor() if boxAnchor in ['n','ne','nw']: self._top = -self.topPadding elif boxAnchor in ['s','sw','se']: self._top = self._height-self.topPadding else: self._top = 0.5*self._eheight self._bottom = self._top - self._eheight if boxAnchor in ['ne','e','se']: self._left = self.leftPadding - self._width elif boxAnchor in ['nw','w','sw']: self._left = self.leftPadding else: self._left = -self._ewidth*0.5 self._right = self._left+self._ewidth def computeSize(self): # the thing will draw in its own coordinate system ddfKlass = getattr(self,'ddfKlass',None) if not ddfKlass: self._lineWidths = [] self._lines = simpleSplit(self._text,self.fontName,self.fontSize,self.maxWidth) if not self.width: self._width = self.leftPadding+self.rightPadding if self._lines: self._lineWidths = [stringWidth(line,self.fontName,self.fontSize) for line in self._lines] self._width += max(self._lineWidths) else: self._width = self.width self._getBaseLineRatio() if self.leading: self._leading = self.leading elif self.useAscentDescent: self._leading = self._ascent - self._descent else: self._leading = self.fontSize*1.2 objH = self._leading*len(self._lines) else: if self.ddf is None: raise RuntimeError('DirectDrawFlowable class is not available you need the rlextra package as well as reportlab') sty = dict( name='xlabel-generated', fontName=self.fontName, fontSize=self.fontSize, fillColor=self.fillColor, strokeColor=self.strokeColor, ) if not self.ddfStyle: sty = ParagraphStyle(**sty) elif issubclass(self.ddfStyle,PropertySet): sty = self.ddfStyle(**sty) else: sty = self.ddfStyle.clone() self._style = sty self._getBaseLineRatio() if self.useAscentDescent: sty.autoLeading = True sty.leading = self._ascent - self._descent else: sty.leading = self.leading if self.leading else self.fontSize*1.2 self._leading = sty.leading ta = self._getTextAnchor() aW = self.maxWidth or 0x7fffffff if ta!='start': sty.alignment = TA_LEFT obj = ddfKlass(self._text,style=sty) _, objH = obj.wrap(aW,0x7fffffff) aW = self.maxWidth or obj._width_max sty.alignment = _ta2al[ta] self._ddfObj = obj = ddfKlass(self._text,style=sty) _, objH = obj.wrap(aW,0x7fffffff) if not self.width: self._width = self.leftPadding+self.rightPadding self._width += obj._width_max else: self._width = self.width self._computeSizeEnd(objH) def _getTextAnchor(self): '''This can be overridden to allow special effects''' ta = self.textAnchor if ta=='boxauto': ta = _BA2TA[self._getBoxAnchor()] return ta def _rawDraw(self): _text = self._text self._text = _text or '' self.computeSize() self._text = _text g = Group() g.translate(self.x + self.dx, self.y + self.dy) g.rotate(self.angle) ddfKlass = getattr(self,'ddfKlass',None) if ddfKlass: x = self._left else: y = self._top - self._leading*self._baselineRatio textAnchor = self._getTextAnchor() if textAnchor == 'start': x = self._left elif textAnchor == 'middle': x = self._left + self._ewidth*0.5 else: x = self._right # paint box behind text just in case they # fill it if self.boxFillColor or (self.boxStrokeColor and self.boxStrokeWidth): g.add(Rect( self._left-self.leftPadding, self._bottom-self.bottomPadding, self._width, self._height, strokeColor=self.boxStrokeColor, strokeWidth=self.boxStrokeWidth, fillColor=self.boxFillColor) ) if ddfKlass: g1 = Group() g1.translate(x,self._top-self._eheight) g1.add(self.ddf(self._ddfObj)) g.add(g1) else: fillColor, fontName, fontSize = self.fillColor, self.fontName, self.fontSize strokeColor, strokeWidth, leading = self.strokeColor, self.strokeWidth, self._leading svgAttrs=getattr(self,'_svgAttrs',{}) if strokeColor: for line in self._lines: s = _text2Path(line, x, y, fontName, fontSize, textAnchor) s.fillColor = fillColor s.strokeColor = strokeColor s.strokeWidth = strokeWidth g.add(s) y -= leading else: for line in self._lines: s = String(x, y, line, _svgAttrs=svgAttrs) s.textAnchor = textAnchor s.fontName = fontName s.fontSize = fontSize s.fillColor = fillColor g.add(s) y -= leading return g def draw(self): customDrawChanger = getattr(self,'customDrawChanger',None) if customDrawChanger: customDrawChanger(True,self) try: return self._rawDraw() finally: customDrawChanger(False,self) else: return self._rawDraw() class LabelDecorator: _attrMap = AttrMap( x = AttrMapValue(isNumberOrNone,desc=''), y = AttrMapValue(isNumberOrNone,desc=''), dx = AttrMapValue(isNumberOrNone,desc=''), dy = AttrMapValue(isNumberOrNone,desc=''), angle = AttrMapValue(isNumberOrNone,desc=''), boxAnchor = AttrMapValue(isBoxAnchor,desc=''), boxStrokeColor = AttrMapValue(isColorOrNone,desc=''), boxStrokeWidth = AttrMapValue(isNumberOrNone,desc=''), boxFillColor = AttrMapValue(isColorOrNone,desc=''), fillColor = AttrMapValue(isColorOrNone,desc=''), strokeColor = AttrMapValue(isColorOrNone,desc=''), strokeWidth = AttrMapValue(isNumberOrNone),desc='', fontName = AttrMapValue(isNoneOrString,desc=''), fontSize = AttrMapValue(isNumberOrNone,desc=''), leading = AttrMapValue(isNumberOrNone,desc=''), width = AttrMapValue(isNumberOrNone,desc=''), maxWidth = AttrMapValue(isNumberOrNone,desc=''), height = AttrMapValue(isNumberOrNone,desc=''), textAnchor = AttrMapValue(isTextAnchor,desc=''), visible = AttrMapValue(isBoolean,desc="True if the label is to be drawn"), ) def __init__(self): self.textAnchor = 'start' self.boxAnchor = 'w' for a in self._attrMap.keys(): if not hasattr(self,a): setattr(self,a,None) def decorate(self,l,L): chart,g,rowNo,colNo,x,y,width,height,x00,y00,x0,y0 = l._callOutInfo L.setText(chart.categoryAxis.categoryNames[colNo]) g.add(L) def __call__(self,l): L = Label() for a,v in self.__dict__.items(): if v is None: v = getattr(l,a,None) setattr(L,a,v) self.decorate(l,L) isOffsetMode=OneOf('high','low','bar','axis') class LabelOffset(PropHolder): _attrMap = AttrMap( posMode = AttrMapValue(isOffsetMode,desc="Where to base +ve offset"), pos = AttrMapValue(isNumber,desc='Value for positive elements'), negMode = AttrMapValue(isOffsetMode,desc="Where to base -ve offset"), neg = AttrMapValue(isNumber,desc='Value for negative elements'), ) def __init__(self): self.posMode=self.negMode='axis' self.pos = self.neg = 0 def _getValue(self, chart, val): flipXY = chart._flipXY A = chart.categoryAxis jA = A.joinAxis if val>=0: mode = self.posMode delta = self.pos else: mode = self.negMode delta = self.neg if flipXY: v = A._x else: v = A._y if jA: if flipXY: _v = jA._x else: _v = jA._y if mode=='high': v = _v + jA._length elif mode=='low': v = _v elif mode=='bar': v = _v+val return v+delta NoneOrInstanceOfLabelOffset=NoneOr(isInstanceOf(LabelOffset)) class PMVLabel(Label): _attrMap = AttrMap( BASE=Label, ) def __init__(self, **kwds): Label.__init__(self, **kwds) self._pmv = 0 def _getBoxAnchor(self): a = Label._getBoxAnchor(self) if self._pmv<0: a = {'nw':'se','n':'s','ne':'sw','w':'e','c':'c','e':'w','sw':'ne','s':'n','se':'nw'}[a] return a def _getTextAnchor(self): a = Label._getTextAnchor(self) if self._pmv<0: a = {'start':'end', 'middle':'middle', 'end':'start'}[a] return a class BarChartLabel(PMVLabel): """ An extended Label allowing for nudging, lines visibility etc """ _attrMap = AttrMap( BASE=PMVLabel, lineStrokeWidth = AttrMapValue(isNumberOrNone, desc="Non-zero for a drawn line"), lineStrokeColor = AttrMapValue(isColorOrNone, desc="Color for a drawn line"), fixedEnd = AttrMapValue(NoneOrInstanceOfLabelOffset, desc="None or fixed draw ends +/-"), fixedStart = AttrMapValue(NoneOrInstanceOfLabelOffset, desc="None or fixed draw starts +/-"), nudge = AttrMapValue(isNumber, desc="Non-zero sign dependent nudge"), boxTarget = AttrMapValue(OneOf('normal','anti','lo','hi','mid'),desc="one of ('normal','anti','lo','hi','mid')"), ) def __init__(self, **kwds): PMVLabel.__init__(self, **kwds) self.lineStrokeWidth = 0 self.lineStrokeColor = None self.fixedStart = self.fixedEnd = None self.nudge = 0 class NA_Label(BarChartLabel): """ An extended Label allowing for nudging, lines visibility etc """ _attrMap = AttrMap( BASE=BarChartLabel, text = AttrMapValue(isNoneOrString, desc="Text to be used for N/A values"), ) def __init__(self): BarChartLabel.__init__(self) self.text = 'n/a' NoneOrInstanceOfNA_Label=NoneOr(isInstanceOf(NA_Label)) from reportlab.graphics.charts.utils import CustomDrawChanger class RedNegativeChanger(CustomDrawChanger): def __init__(self,fillColor=colors.red): CustomDrawChanger.__init__(self) self.fillColor = fillColor def _changer(self,obj): R = {} if obj._text.startswith('-'): R['fillColor'] = obj.fillColor obj.fillColor = self.fillColor return R class XLabel(Label): '''like label but uses XPreFormatted/Paragraph to draw the _text''' _attrMap = AttrMap(BASE=Label, ) def __init__(self,*args,**kwds): Label.__init__(self,*args,**kwds) self.ddfKlass = kwds.pop('ddfKlass',XPreformatted) self.ddf = kwds.pop('directDrawClass',self.ddf) if False: def __init__(self,*args,**kwds): self._flowableClass = kwds.pop('flowableClass',XPreformatted) ddf = kwds.pop('directDrawClass',DirectDrawFlowable) if ddf is None: raise RuntimeError('DirectDrawFlowable class is not available you need the rlextra package as well as reportlab') self._ddf = ddf Label.__init__(self,*args,**kwds) def computeSize(self): # the thing will draw in its own coordinate system self._lineWidths = [] sty = self._style = ParagraphStyle('xlabel-generated', fontName=self.fontName, fontSize=self.fontSize, fillColor=self.fillColor, strokeColor=self.strokeColor, ) self._getBaseLineRatio() if self.useAscentDescent: sty.autoLeading = True sty.leading = self._ascent - self._descent else: sty.leading = self.leading if self.leading else self.fontSize*1.2 self._leading = sty.leading ta = self._getTextAnchor() aW = self.maxWidth or 0x7fffffff if ta!='start': sty.alignment = TA_LEFT obj = self._flowableClass(self._text,style=sty) _, objH = obj.wrap(aW,0x7fffffff) aW = self.maxWidth or obj._width_max sty.alignment = _ta2al[ta] self._obj = obj = self._flowableClass(self._text,style=sty) _, objH = obj.wrap(aW,0x7fffffff) if not self.width: self._width = self.leftPadding+self.rightPadding self._width += self._obj._width_max else: self._width = self.width self._computeSizeEnd(objH) def _rawDraw(self): _text = self._text self._text = _text or '' self.computeSize() self._text = _text g = Group() g.translate(self.x + self.dx, self.y + self.dy) g.rotate(self.angle) x = self._left # paint box behind text just in case they # fill it if self.boxFillColor or (self.boxStrokeColor and self.boxStrokeWidth): g.add(Rect( self._left-self.leftPadding, self._bottom-self.bottomPadding, self._width, self._height, strokeColor=self.boxStrokeColor, strokeWidth=self.boxStrokeWidth, fillColor=self.boxFillColor) ) g1 = Group() g1.translate(x,self._top-self._eheight) g1.add(self._ddf(self._obj)) g.add(g1) return g
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/charts/textlabels.py
0.567337
0.242026
textlabels.py
pypi
from reportlab.graphics.charts.legends import Legend from reportlab.graphics.charts.lineplots import ScatterPlot from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin from reportlab.graphics.charts.textlabels import Label from reportlab.graphics.samples.excelcolors import * class Bubble(_DrawingEditorMixin,Drawing): def __init__(self,width=200,height=150,*args,**kw): Drawing.__init__(self,width,height,*args,**kw) self._add(self,ScatterPlot(),name='chart',validate=None,desc="The main chart") self.chart.width = 115 self.chart.height = 80 self.chart.x = 30 self.chart.y = 40 self.chart.lines[0].strokeColor = color01 self.chart.lines[1].strokeColor = color02 self.chart.lines[2].strokeColor = color03 self.chart.lines[3].strokeColor = color04 self.chart.lines[4].strokeColor = color05 self.chart.lines[5].strokeColor = color06 self.chart.lines[6].strokeColor = color07 self.chart.lines[7].strokeColor = color08 self.chart.lines[8].strokeColor = color09 self.chart.lines[9].strokeColor = color10 self.chart.lines.symbol.kind ='Circle' self.chart.lines.symbol.size = 15 self.chart.fillColor = backgroundGrey self.chart.lineLabels.fontName = 'Helvetica' self.chart.xValueAxis.labels.fontName = 'Helvetica' self.chart.xValueAxis.labels.fontSize = 7 self.chart.xValueAxis.forceZero = 0 self.chart.data = [((100,100), (200,200), (250,210), (300,300), (350,450))] self.chart.xValueAxis.avoidBoundFrac = 1 self.chart.xValueAxis.gridEnd = 115 self.chart.xValueAxis.tickDown = 3 self.chart.xValueAxis.visibleGrid = 1 self.chart.yValueAxis.tickLeft = 3 self.chart.yValueAxis.labels.fontName = 'Helvetica' self.chart.yValueAxis.labels.fontSize = 7 self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") self.Title.fontName = 'Helvetica-Bold' self.Title.fontSize = 7 self.Title.x = 100 self.Title.y = 135 self.Title._text = 'Chart Title' self.Title.maxWidth = 180 self.Title.height = 20 self.Title.textAnchor ='middle' self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") self.Legend.colorNamePairs = [(color01, 'Widgets')] self.Legend.fontName = 'Helvetica' self.Legend.fontSize = 7 self.Legend.x = 153 self.Legend.y = 85 self.Legend.dxTextSpace = 5 self.Legend.dy = 5 self.Legend.dx = 5 self.Legend.deltay = 5 self.Legend.alignment ='right' self.chart.lineLabelFormat = None self.chart.xLabel = 'X Axis' self.chart.y = 30 self.chart.yLabel = 'Y Axis' self.chart.yValueAxis.labelTextFormat = '%d' self.chart.yValueAxis.forceZero = 1 self.chart.xValueAxis.forceZero = 1 self._add(self,0,name='preview',validate=None,desc=None) if __name__=="__main__": #NORUNTESTS Bubble().save(formats=['pdf'],outDir=None,fnRoot='bubble')
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/samples/bubble.py
0.679285
0.153613
bubble.py
pypi
from reportlab.graphics.charts.piecharts import Pie from reportlab.graphics.samples.excelcolors import * from reportlab.graphics.widgets.grids import ShadedRect from reportlab.graphics.charts.legends import Legend from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin from reportlab.graphics.charts.textlabels import Label class ExplodedPie(_DrawingEditorMixin,Drawing): def __init__(self,width=200,height=150,*args,**kw): Drawing.__init__(self,width,height,*args,**kw) self._add(self,Pie(),name='chart',validate=None,desc="The main chart") self.chart.width = 100 self.chart.height = 100 self.chart.x = 25 self.chart.y = 25 self.chart.slices[0].fillColor = color01 self.chart.slices[1].fillColor = color02 self.chart.slices[2].fillColor = color03 self.chart.slices[3].fillColor = color04 self.chart.slices[4].fillColor = color05 self.chart.slices[5].fillColor = color06 self.chart.slices[6].fillColor = color07 self.chart.slices[7].fillColor = color08 self.chart.slices[8].fillColor = color09 self.chart.slices[9].fillColor = color10 self.chart.data = (100, 150, 180) self.chart.startAngle = -90 self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") self.Title.fontName = 'Helvetica-Bold' self.Title.fontSize = 7 self.Title.x = 100 self.Title.y = 135 self.Title._text = 'Chart Title' self.Title.maxWidth = 180 self.Title.height = 20 self.Title.textAnchor ='middle' self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") self.Legend.colorNamePairs = [(color01, 'North'), (color02, 'South'), (color03, 'Central')] self.Legend.fontName = 'Helvetica' self.Legend.fontSize = 7 self.Legend.x = 160 self.Legend.y = 85 self.Legend.dxTextSpace = 5 self.Legend.dy = 5 self.Legend.dx = 5 self.Legend.deltay = 5 self.Legend.alignment ='right' self.Legend.columnMaximum = 10 self.chart.slices.strokeWidth = 1 self.chart.slices.fontName = 'Helvetica' self.background = ShadedRect() self.background.fillColorStart = backgroundGrey self.background.fillColorEnd = backgroundGrey self.background.numShades = 1 self.background.strokeWidth = 0.5 self.background.x = 20 self.background.y = 20 self.chart.slices.popout = 5 self.background.height = 110 self.background.width = 110 self._add(self,0,name='preview',validate=None,desc=None) if __name__=="__main__": #NORUNTESTS ExplodedPie().save(formats=['pdf'],outDir=None,fnRoot='exploded_pie')
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/samples/exploded_pie.py
0.634883
0.16896
exploded_pie.py
pypi
from reportlab.graphics.charts.piecharts import Pie from reportlab.graphics.widgets.grids import ShadedRect from reportlab.graphics.charts.legends import Legend from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin from reportlab.graphics.charts.textlabels import Label from reportlab.graphics.samples.excelcolors import * class SimplePie(_DrawingEditorMixin,Drawing): def __init__(self,width=200,height=150,*args,**kw): Drawing.__init__(self,width,height,*args,**kw) self._add(self,Pie(),name='chart',validate=None,desc="The main chart") self.chart.width = 100 self.chart.height = 100 self.chart.x = 25 self.chart.y = 25 self.chart.slices[0].fillColor = color01 self.chart.slices[1].fillColor = color02 self.chart.slices[2].fillColor = color03 self.chart.slices[3].fillColor = color04 self.chart.slices[4].fillColor = color05 self.chart.slices[5].fillColor = color06 self.chart.slices[6].fillColor = color07 self.chart.slices[7].fillColor = color08 self.chart.slices[8].fillColor = color09 self.chart.slices[9].fillColor = color10 self.chart.data = (100, 150, 180) self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") self.Title.fontName = 'Helvetica-Bold' self.Title.fontSize = 7 self.Title.x = 100 self.Title.y = 135 self.Title._text = 'Chart Title' self.Title.maxWidth = 180 self.Title.height = 20 self.Title.textAnchor ='middle' self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") self.Legend.colorNamePairs = [(color01, 'North'), (color02, 'South'),(color03, 'Central')] self.Legend.fontName = 'Helvetica' self.Legend.fontSize = 7 self.Legend.x = 160 self.Legend.y = 85 self.Legend.dxTextSpace = 5 self.Legend.dy = 5 self.Legend.dx = 5 self.Legend.deltay = 5 self.Legend.alignment ='right' self.chart.slices.strokeWidth = 1 self.chart.slices.fontName = 'Helvetica' self.background = ShadedRect() self.background.fillColorStart = backgroundGrey self.background.fillColorEnd = backgroundGrey self.background.numShades = 1 self.background.strokeWidth = 0.5 self.background.x = 25 self.background.y = 25 self.Legend.columnMaximum = 10 self._add(self,0,name='preview',validate=None,desc=None) if __name__=="__main__": #NORUNTESTS SimplePie().save(formats=['pdf'],outDir=None,fnRoot=None)
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/samples/simple_pie.py
0.627267
0.176069
simple_pie.py
pypi
__version__='3.3.0' __doc__="""This file is a collection of widgets to produce some common signs and symbols. Widgets include: - ETriangle (an equilateral triangle), - RTriangle (a right angled triangle), - Octagon, - Crossbox, - Tickbox, - SmileyFace, - StopSign, - NoEntry, - NotAllowed (the red roundel from 'no smoking' signs), - NoSmoking, - DangerSign (a black exclamation point in a yellow triangle), - YesNo (returns a tickbox or a crossbox depending on a testvalue), - FloppyDisk, - ArrowOne, and - ArrowTwo - CrossHair """ from reportlab.lib import colors from reportlab.lib.validators import * from reportlab.lib.attrmap import * from reportlab.lib.utils import isStr, asUnicode from reportlab.graphics import shapes from reportlab.graphics.widgetbase import Widget from reportlab.graphics import renderPDF class _Symbol(Widget): """Abstract base widget possible attributes: 'x', 'y', 'size', 'fillColor', 'strokeColor' """ _nodoc = 1 _attrMap = AttrMap( x = AttrMapValue(isNumber,desc='symbol x coordinate'), y = AttrMapValue(isNumber,desc='symbol y coordinate'), dx = AttrMapValue(isNumber,desc='symbol x coordinate adjustment'), dy = AttrMapValue(isNumber,desc='symbol x coordinate adjustment'), size = AttrMapValue(isNumber), fillColor = AttrMapValue(isColorOrNone), strokeColor = AttrMapValue(isColorOrNone), strokeWidth = AttrMapValue(isNumber), ) def __init__(self): assert self.__class__.__name__!='_Symbol', 'Abstract class _Symbol instantiated' self.x = self.y = self.dx = self.dy = 0 self.size = 100 self.fillColor = colors.red self.strokeColor = None self.strokeWidth = 0.1 def demo(self): D = shapes.Drawing(200, 100) s = float(self.size) ob = self.__class__() ob.x=50 ob.y=0 ob.draw() D.add(ob) D.add(shapes.String(ob.x+(s/2),(ob.y-12), ob.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=10)) return D class ETriangle(_Symbol): """This draws an equilateral triangle.""" def __init__(self): _Symbol.__init__(self) def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # Triangle specific bits ae = s*0.125 #(ae = 'an eighth') triangle = shapes.Polygon(points = [ self.x, self.y, self.x+s, self.y, self.x+(s/2),self.y+s], fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth=s/50.) g.add(triangle) return g class RTriangle(_Symbol): """This draws a right-angled triangle. possible attributes: 'x', 'y', 'size', 'fillColor', 'strokeColor' """ def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.fillColor = colors.green self.strokeColor = None def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # Triangle specific bits ae = s*0.125 #(ae = 'an eighth') triangle = shapes.Polygon(points = [ self.x, self.y, self.x+s, self.y, self.x,self.y+s], fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth=s/50.) g.add(triangle) return g class Octagon(_Symbol): """This widget draws an Octagon. possible attributes: 'x', 'y', 'size', 'fillColor', 'strokeColor' """ def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.fillColor = colors.yellow self.strokeColor = None def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # Octagon specific bits athird=s/3 octagon = shapes.Polygon(points=[self.x+athird, self.y, self.x, self.y+athird, self.x, self.y+(athird*2), self.x+athird, self.y+s, self.x+(athird*2), self.y+s, self.x+s, self.y+(athird*2), self.x+s, self.y+athird, self.x+(athird*2), self.y], strokeColor = self.strokeColor, fillColor = self.fillColor, strokeWidth=10) g.add(octagon) return g class Crossbox(_Symbol): """This draws a black box with a red cross in it - a 'checkbox'. possible attributes: 'x', 'y', 'size', 'crossColor', 'strokeColor', 'crosswidth' """ _attrMap = AttrMap(BASE=_Symbol, crossColor = AttrMapValue(isColorOrNone), crosswidth = AttrMapValue(isNumber), ) def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.fillColor = colors.white self.crossColor = colors.red self.strokeColor = colors.black self.crosswidth = 10 def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # crossbox specific bits box = shapes.Rect(self.x+1, self.y+1, s-2, s-2, fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth=2) g.add(box) crossLine1 = shapes.Line(self.x+(s*0.15), self.y+(s*0.15), self.x+(s*0.85), self.y+(s*0.85), fillColor = self.crossColor, strokeColor = self.crossColor, strokeWidth = self.crosswidth) g.add(crossLine1) crossLine2 = shapes.Line(self.x+(s*0.15), self.y+(s*0.85), self.x+(s*0.85) ,self.y+(s*0.15), fillColor = self.crossColor, strokeColor = self.crossColor, strokeWidth = self.crosswidth) g.add(crossLine2) return g class Tickbox(_Symbol): """This draws a black box with a red tick in it - another 'checkbox'. possible attributes: 'x', 'y', 'size', 'tickColor', 'strokeColor', 'tickwidth' """ _attrMap = AttrMap(BASE=_Symbol, tickColor = AttrMapValue(isColorOrNone), tickwidth = AttrMapValue(isNumber), ) def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.tickColor = colors.red self.strokeColor = colors.black self.fillColor = colors.white self.tickwidth = 10 def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # tickbox specific bits box = shapes.Rect(self.x+1, self.y+1, s-2, s-2, fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth=2) g.add(box) tickLine = shapes.PolyLine(points = [self.x+(s*0.15), self.y+(s*0.35), self.x+(s*0.35), self.y+(s*0.15), self.x+(s*0.35), self.y+(s*0.15), self.x+(s*0.85) ,self.y+(s*0.85)], fillColor = self.tickColor, strokeColor = self.tickColor, strokeWidth = self.tickwidth) g.add(tickLine) return g class SmileyFace(_Symbol): """This draws a classic smiley face. possible attributes: 'x', 'y', 'size', 'fillColor' """ def __init__(self): _Symbol.__init__(self) self.x = 0 self.y = 0 self.size = 100 self.fillColor = colors.yellow self.strokeColor = colors.black def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # SmileyFace specific bits g.add(shapes.Circle(cx=self.x+(s/2), cy=self.y+(s/2), r=s/2, fillColor=self.fillColor, strokeColor=self.strokeColor, strokeWidth=max(s/38.,self.strokeWidth))) for i in (1,2): g.add(shapes.Ellipse(self.x+(s/3)*i,self.y+(s/3)*2, s/30, s/10, fillColor=self.strokeColor, strokeColor = self.strokeColor, strokeWidth=max(s/38.,self.strokeWidth))) # calculate a pointslist for the mouth # THIS IS A HACK! - don't use if there is a 'shapes.Arc' centerx=self.x+(s/2) centery=self.y+(s/2) radius=s/3 yradius = radius xradius = radius startangledegrees=200 endangledegrees=340 degreedelta = 1 pointslist = [] a = pointslist.append from math import sin, cos, pi degreestoradians = pi/180.0 radiansdelta = degreedelta*degreestoradians startangle = startangledegrees*degreestoradians endangle = endangledegrees*degreestoradians while endangle<startangle: endangle = endangle+2*pi angle = startangle while angle<endangle: x = centerx + cos(angle)*radius y = centery + sin(angle)*yradius a(x); a(y) angle = angle+radiansdelta # make the mouth smile = shapes.PolyLine(pointslist, fillColor = self.strokeColor, strokeColor = self.strokeColor, strokeWidth = max(s/38.,self.strokeWidth)) g.add(smile) return g class StopSign(_Symbol): """This draws a (British) stop sign. possible attributes: 'x', 'y', 'size' """ _attrMap = AttrMap(BASE=_Symbol, stopColor = AttrMapValue(isColorOrNone,desc='color of the word stop'), ) def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.strokeColor = colors.black self.fillColor = colors.orangered self.stopColor = colors.ghostwhite def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # stop-sign specific bits athird=s/3 outerOctagon = shapes.Polygon(points=[self.x+athird, self.y, self.x, self.y+athird, self.x, self.y+(athird*2), self.x+athird, self.y+s, self.x+(athird*2), self.y+s, self.x+s, self.y+(athird*2), self.x+s, self.y+athird, self.x+(athird*2), self.y], strokeColor = self.strokeColor, fillColor = None, strokeWidth=1) g.add(outerOctagon) innerOctagon = shapes.Polygon(points=[self.x+athird+(s/75), self.y+(s/75), self.x+(s/75), self.y+athird+(s/75), self.x+(s/75), self.y+(athird*2)-(s/75), self.x+athird+(s/75), self.y+s-(s/75), self.x+(athird*2)-(s/75), (self.y+s)-(s/75), (self.x+s)-(s/75), self.y+(athird*2)-(s/75), (self.x+s)-(s/75), self.y+athird+(s/75), self.x+(athird*2)-(s/75), self.y+(s/75)], strokeColor = None, fillColor = self.fillColor, strokeWidth=0) g.add(innerOctagon) if self.stopColor: g.add(shapes.String(self.x+(s*0.5),self.y+(s*0.4), 'STOP', fillColor=self.stopColor, textAnchor='middle', fontSize=s/3, fontName="Helvetica-Bold")) return g class NoEntry(_Symbol): """This draws a (British) No Entry sign - a red circle with a white line on it. possible attributes: 'x', 'y', 'size' """ _attrMap = AttrMap(BASE=_Symbol, innerBarColor = AttrMapValue(isColorOrNone,desc='color of the inner bar'), ) def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.strokeColor = colors.black self.fillColor = colors.orangered self.innerBarColor = colors.ghostwhite def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # no-entry-sign specific bits if self.strokeColor: g.add(shapes.Circle(cx = (self.x+(s/2)), cy = (self.y+(s/2)), r = s/2, fillColor = None, strokeColor = self.strokeColor, strokeWidth=1)) if self.fillColor: g.add(shapes.Circle(cx = (self.x+(s/2)), cy =(self.y+(s/2)), r = ((s/2)-(s/50)), fillColor = self.fillColor, strokeColor = None, strokeWidth=0)) innerBarColor = self.innerBarColor if innerBarColor: g.add(shapes.Rect(self.x+(s*0.1), self.y+(s*0.4), width=s*0.8, height=s*0.2, fillColor = innerBarColor, strokeColor = innerBarColor, strokeLineCap = 1, strokeWidth = 0)) return g class NotAllowed(_Symbol): """This draws a 'forbidden' roundel (as used in the no-smoking sign). possible attributes: 'x', 'y', 'size' """ _attrMap = AttrMap(BASE=_Symbol, ) def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.strokeColor = colors.red self.fillColor = colors.white def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() strokeColor = self.strokeColor # not=allowed specific bits outerCircle = shapes.Circle(cx = (self.x+(s/2)), cy = (self.y+(s/2)), r = (s/2)-(s/10), fillColor = self.fillColor, strokeColor = strokeColor, strokeWidth=s/10.) g.add(outerCircle) centerx=self.x+s centery=self.y+(s/2)-(s/6) radius=s-(s/6) yradius = radius/2 xradius = radius/2 startangledegrees=100 endangledegrees=-80 degreedelta = 90 pointslist = [] a = pointslist.append from math import sin, cos, pi degreestoradians = pi/180.0 radiansdelta = degreedelta*degreestoradians startangle = startangledegrees*degreestoradians endangle = endangledegrees*degreestoradians while endangle<startangle: endangle = endangle+2*pi angle = startangle while angle<endangle: x = centerx + cos(angle)*radius y = centery + sin(angle)*yradius a(x); a(y) angle = angle+radiansdelta crossbar = shapes.PolyLine(pointslist, fillColor = strokeColor, strokeColor = strokeColor, strokeWidth = s/10.) g.add(crossbar) return g class NoSmoking(NotAllowed): """This draws a no-smoking sign. possible attributes: 'x', 'y', 'size' """ def __init__(self): NotAllowed.__init__(self) def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = NotAllowed.draw(self) # no-smoking-sign specific bits newx = self.x+(s/2)-(s/3.5) newy = self.y+(s/2)-(s/32) cigarrette1 = shapes.Rect(x = newx, y = newy, width = (s/2), height =(s/16), fillColor = colors.ghostwhite, strokeColor = colors.gray, strokeWidth=0) newx=newx+(s/2)+(s/64) g.insert(-1,cigarrette1) cigarrette2 = shapes.Rect(x = newx, y = newy, width = (s/80), height =(s/16), fillColor = colors.orangered, strokeColor = None, strokeWidth=0) newx= newx+(s/35) g.insert(-1,cigarrette2) cigarrette3 = shapes.Rect(x = newx, y = newy, width = (s/80), height =(s/16), fillColor = colors.orangered, strokeColor = None, strokeWidth=0) newx= newx+(s/35) g.insert(-1,cigarrette3) cigarrette4 = shapes.Rect(x = newx, y = newy, width = (s/80), height =(s/16), fillColor = colors.orangered, strokeColor = None, strokeWidth=0) newx= newx+(s/35) g.insert(-1,cigarrette4) return g class DangerSign(_Symbol): """This draws a 'danger' sign: a yellow box with a black exclamation point. possible attributes: 'x', 'y', 'size', 'strokeColor', 'fillColor', 'strokeWidth' """ def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.strokeColor = colors.black self.fillColor = colors.gold self.strokeWidth = self.size*0.125 def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() ew = self.strokeWidth ae = s*0.125 #(ae = 'an eighth') # danger sign specific bits ew = self.strokeWidth ae = s*0.125 #(ae = 'an eighth') outerTriangle = shapes.Polygon(points = [ self.x, self.y, self.x+s, self.y, self.x+(s/2),self.y+s], fillColor = None, strokeColor = self.strokeColor, strokeWidth=0) g.add(outerTriangle) innerTriangle = shapes.Polygon(points = [ self.x+(s/50), self.y+(s/75), (self.x+s)-(s/50), self.y+(s/75), self.x+(s/2),(self.y+s)-(s/50)], fillColor = self.fillColor, strokeColor = None, strokeWidth=0) g.add(innerTriangle) exmark = shapes.Polygon(points=[ ((self.x+s/2)-ew/2), self.y+ae*2.5, ((self.x+s/2)+ew/2), self.y+ae*2.5, ((self.x+s/2)+((ew/2))+(ew/6)), self.y+ae*5.5, ((self.x+s/2)-((ew/2))-(ew/6)), self.y+ae*5.5], fillColor = self.strokeColor, strokeColor = None) g.add(exmark) exdot = shapes.Polygon(points=[ ((self.x+s/2)-ew/2), self.y+ae, ((self.x+s/2)+ew/2), self.y+ae, ((self.x+s/2)+ew/2), self.y+ae*2, ((self.x+s/2)-ew/2), self.y+ae*2], fillColor = self.strokeColor, strokeColor = None) g.add(exdot) return g class YesNo(_Symbol): """This widget draw a tickbox or crossbox depending on 'testValue'. If this widget is supplied with a 'True' or 1 as a value for testValue, it will use the tickbox widget. Otherwise, it will produce a crossbox. possible attributes: 'x', 'y', 'size', 'tickcolor', 'crosscolor', 'testValue' """ _attrMap = AttrMap(BASE=_Symbol, tickcolor = AttrMapValue(isColor), crosscolor = AttrMapValue(isColor), testValue = AttrMapValue(isBoolean), ) def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.tickcolor = colors.green self.crosscolor = colors.red self.testValue = 1 def draw(self): if self.testValue: yn=Tickbox() yn.tickColor=self.tickcolor else: yn=Crossbox() yn.crossColor=self.crosscolor yn.x=self.x yn.y=self.y yn.size=self.size yn.draw() return yn def demo(self): D = shapes.Drawing(200, 100) yn = YesNo() yn.x = 15 yn.y = 25 yn.size = 70 yn.testValue = 0 yn.draw() D.add(yn) yn2 = YesNo() yn2.x = 120 yn2.y = 25 yn2.size = 70 yn2.testValue = 1 yn2.draw() D.add(yn2) labelFontSize = 8 D.add(shapes.String(yn.x+(yn.size/2),(yn.y-(1.2*labelFontSize)), 'testValue=0', fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) D.add(shapes.String(yn2.x+(yn2.size/2),(yn2.y-(1.2*labelFontSize)), 'testValue=1', fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) labelFontSize = 10 D.add(shapes.String(yn.x+85,(yn.y-20), self.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) return D class FloppyDisk(_Symbol): """This widget draws an icon of a floppy disk. possible attributes: 'x', 'y', 'size', 'diskcolor' """ _attrMap = AttrMap(BASE=_Symbol, diskColor = AttrMapValue(isColor), ) def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.diskColor = colors.black def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # floppy disk specific bits diskBody = shapes.Rect(x=self.x, y=self.y+(s/100), width=s, height=s-(s/100), fillColor = self.diskColor, strokeColor = None, strokeWidth=0) g.add(diskBody) label = shapes.Rect(x=self.x+(s*0.1), y=(self.y+s)-(s*0.5), width=s*0.8, height=s*0.48, fillColor = colors.whitesmoke, strokeColor = None, strokeWidth=0) g.add(label) labelsplash = shapes.Rect(x=self.x+(s*0.1), y=(self.y+s)-(s*0.1), width=s*0.8, height=s*0.08, fillColor = colors.royalblue, strokeColor = None, strokeWidth=0) g.add(labelsplash) line1 = shapes.Line(x1=self.x+(s*0.15), y1=self.y+(0.6*s), x2=self.x+(s*0.85), y2=self.y+(0.6*s), fillColor = colors.black, strokeColor = colors.black, strokeWidth=0) g.add(line1) line2 = shapes.Line(x1=self.x+(s*0.15), y1=self.y+(0.7*s), x2=self.x+(s*0.85), y2=self.y+(0.7*s), fillColor = colors.black, strokeColor = colors.black, strokeWidth=0) g.add(line2) line3 = shapes.Line(x1=self.x+(s*0.15), y1=self.y+(0.8*s), x2=self.x+(s*0.85), y2=self.y+(0.8*s), fillColor = colors.black, strokeColor = colors.black, strokeWidth=0) g.add(line3) metalcover = shapes.Rect(x=self.x+(s*0.2), y=(self.y), width=s*0.5, height=s*0.35, fillColor = colors.silver, strokeColor = None, strokeWidth=0) g.add(metalcover) coverslot = shapes.Rect(x=self.x+(s*0.28), y=(self.y)+(s*0.035), width=s*0.12, height=s*0.28, fillColor = self.diskColor, strokeColor = None, strokeWidth=0) g.add(coverslot) return g class ArrowOne(_Symbol): """This widget draws an arrow (style one). possible attributes: 'x', 'y', 'size', 'fillColor' """ def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.fillColor = colors.red self.strokeWidth = 0 self.strokeColor = None def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() x = self.x y = self.y s2 = s/2 s3 = s/3 s5 = s/5 g.add(shapes.Polygon(points = [ x,y+s3, x,y+2*s3, x+s2,y+2*s3, x+s2,y+4*s5, x+s,y+s2, x+s2,y+s5, x+s2,y+s3, ], fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth = self.strokeWidth, ) ) return g class ArrowTwo(ArrowOne): """This widget draws an arrow (style two). possible attributes: 'x', 'y', 'size', 'fillColor' """ def __init__(self): self.x = 0 self.y = 0 self.size = 100 self.fillColor = colors.blue self.strokeWidth = 0 self.strokeColor = None def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() # arrow specific bits x = self.x y = self.y s2 = s/2 s3 = s/3 s5 = s/5 s24 = s/24 g.add(shapes.Polygon( points = [ x,y+11*s24, x,y+13*s24, x+18.75*s24, y+13*s24, x+2*s3, y+2*s3, x+s, y+s2, x+2*s3, y+s3, x+18.75*s24, y+11*s24, ], fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth = self.strokeWidth) ) return g class CrossHair(_Symbol): """This draws an equilateral triangle.""" _attrMap = AttrMap(BASE=_Symbol, innerGap = AttrMapValue(EitherOr((isString,isNumberOrNone)),desc=' gap at centre as "x%" or points or None'), ) def __init__(self): self.x = self.y = self.dx = self.dy = 0 self.size = 10 self.fillColor = None self.strokeColor = colors.black self.strokeWidth = 0.5 self.innerGap = '20%' def draw(self): # general widget bits s = float(self.size) # abbreviate as we will use this a lot g = shapes.Group() ig = self.innerGap x = self.x+self.dx y = self.y+self.dy hsize = 0.5*self.size if not ig: L = [(x-hsize,y,x+hsize,y), (x,y-hsize,x,y+hsize)] else: if isStr(ig): ig = asUnicode(ig) if ig.endswith(u'%'): gs = hsize*float(ig[:-1])/100.0 else: gs = float(ig)*0.5 else: gs = ig*0.5 L = [(x-hsize,y,x-gs,y), (x+gs,y,x+hsize,y), (x,y-hsize,x,y-gs), (x,y+gs,x,y+hsize)] P = shapes.Path(strokeWidth=self.strokeWidth,strokeColor=self.strokeColor) for x0,y0,x1,y1 in L: P.moveTo(x0,y0) P.lineTo(x1,y1) g.add(P) return g def test(): """This function produces a pdf with examples of all the signs and symbols from this file. """ labelFontSize = 10 D = shapes.Drawing(450,650) cb = Crossbox() cb.x = 20 cb.y = 530 D.add(cb) D.add(shapes.String(cb.x+(cb.size/2),(cb.y-(1.2*labelFontSize)), cb.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) tb = Tickbox() tb.x = 170 tb.y = 530 D.add(tb) D.add(shapes.String(tb.x+(tb.size/2),(tb.y-(1.2*labelFontSize)), tb.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) yn = YesNo() yn.x = 320 yn.y = 530 D.add(yn) tempstring = yn.__class__.__name__ + '*' D.add(shapes.String(yn.x+(tb.size/2),(yn.y-(1.2*labelFontSize)), tempstring, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) D.add(shapes.String(130,6, "(The 'YesNo' widget returns a tickbox if testvalue=1, and a crossbox if testvalue=0)", fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize*0.75)) ss = StopSign() ss.x = 20 ss.y = 400 D.add(ss) D.add(shapes.String(ss.x+(ss.size/2), ss.y-(1.2*labelFontSize), ss.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) ne = NoEntry() ne.x = 170 ne.y = 400 D.add(ne) D.add(shapes.String(ne.x+(ne.size/2),(ne.y-(1.2*labelFontSize)), ne.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) sf = SmileyFace() sf.x = 320 sf.y = 400 D.add(sf) D.add(shapes.String(sf.x+(sf.size/2),(sf.y-(1.2*labelFontSize)), sf.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) ds = DangerSign() ds.x = 20 ds.y = 270 D.add(ds) D.add(shapes.String(ds.x+(ds.size/2),(ds.y-(1.2*labelFontSize)), ds.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) na = NotAllowed() na.x = 170 na.y = 270 D.add(na) D.add(shapes.String(na.x+(na.size/2),(na.y-(1.2*labelFontSize)), na.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) ns = NoSmoking() ns.x = 320 ns.y = 270 D.add(ns) D.add(shapes.String(ns.x+(ns.size/2),(ns.y-(1.2*labelFontSize)), ns.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) a1 = ArrowOne() a1.x = 20 a1.y = 140 D.add(a1) D.add(shapes.String(a1.x+(a1.size/2),(a1.y-(1.2*labelFontSize)), a1.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) a2 = ArrowTwo() a2.x = 170 a2.y = 140 D.add(a2) D.add(shapes.String(a2.x+(a2.size/2),(a2.y-(1.2*labelFontSize)), a2.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) fd = FloppyDisk() fd.x = 320 fd.y = 140 D.add(fd) D.add(shapes.String(fd.x+(fd.size/2),(fd.y-(1.2*labelFontSize)), fd.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) renderPDF.drawToFile(D, 'signsandsymbols.pdf', 'signsandsymbols.py') print('wrote file: signsandsymbols.pdf') if __name__=='__main__': test()
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/widgets/signsandsymbols.py
0.908339
0.42483
signsandsymbols.py
pypi
__version__='3.3.0' from reportlab.lib import colors from reportlab.lib.validators import isNumber, isColorOrNone, isBoolean, isListOfNumbers, OneOf, isListOfColors, isNumberOrNone from reportlab.lib.attrmap import AttrMap, AttrMapValue from reportlab.graphics.shapes import Drawing, Group, Line, Rect, LineShape, definePath, EmptyClipPath from reportlab.graphics.widgetbase import Widget def frange(start, end=None, inc=None): "A range function, that does accept float increments..." if end == None: end = start + 0.0 start = 0.0 if inc == None: inc = 1.0 L = [] end = end - inc*0.0001 #to avoid numrical problems while 1: next = start + len(L) * inc if inc > 0 and next >= end: break elif inc < 0 and next <= end: break L.append(next) return L def makeDistancesList(list): """Returns a list of distances between adjacent numbers in some input list. E.g. [1, 1, 2, 3, 5, 7] -> [0, 1, 1, 2, 2] """ d = [] for i in range(len(list[:-1])): d.append(list[i+1] - list[i]) return d class Grid(Widget): """This makes a rectangular grid of equidistant stripes. The grid contains an outer border rectangle, and stripes inside which can be drawn with lines and/or as solid tiles. The drawing order is: outer rectangle, then lines and tiles. The stripes' width is indicated as 'delta'. The sequence of stripes can have an offset named 'delta0'. Both values need to be positive! """ _attrMap = AttrMap( x = AttrMapValue(isNumber, desc="The grid's lower-left x position."), y = AttrMapValue(isNumber, desc="The grid's lower-left y position."), width = AttrMapValue(isNumber, desc="The grid's width."), height = AttrMapValue(isNumber, desc="The grid's height."), orientation = AttrMapValue(OneOf(('vertical', 'horizontal')), desc='Determines if stripes are vertical or horizontal.'), useLines = AttrMapValue(OneOf((0, 1)), desc='Determines if stripes are drawn with lines.'), useRects = AttrMapValue(OneOf((0, 1)), desc='Determines if stripes are drawn with solid rectangles.'), delta = AttrMapValue(isNumber, desc='Determines the width/height of the stripes.'), delta0 = AttrMapValue(isNumber, desc='Determines the stripes initial width/height offset.'), deltaSteps = AttrMapValue(isListOfNumbers, desc='List of deltas to be used cyclically.'), stripeColors = AttrMapValue(isListOfColors, desc='Colors applied cyclically in the right or upper direction.'), fillColor = AttrMapValue(isColorOrNone, desc='Background color for entire rectangle.'), strokeColor = AttrMapValue(isColorOrNone, desc='Color used for lines.'), strokeWidth = AttrMapValue(isNumber, desc='Width used for lines.'), rectStrokeColor = AttrMapValue(isColorOrNone, desc='Color for outer rect stroke.'), rectStrokeWidth = AttrMapValue(isNumberOrNone, desc='Width for outer rect stroke.'), ) def __init__(self): self.x = 0 self.y = 0 self.width = 100 self.height = 100 self.orientation = 'vertical' self.useLines = 0 self.useRects = 1 self.delta = 20 self.delta0 = 0 self.deltaSteps = [] self.fillColor = colors.white self.stripeColors = [colors.red, colors.green, colors.blue] self.strokeColor = colors.black self.strokeWidth = 2 def demo(self): D = Drawing(100, 100) g = Grid() D.add(g) return D def makeOuterRect(self): strokeColor = getattr(self,'rectStrokeColor',self.strokeColor) strokeWidth = getattr(self,'rectStrokeWidth',self.strokeWidth) if self.fillColor or (strokeColor and strokeWidth): rect = Rect(self.x, self.y, self.width, self.height) rect.fillColor = self.fillColor rect.strokeColor = strokeColor rect.strokeWidth = strokeWidth return rect else: return None def makeLinePosList(self, start, isX=0): "Returns a list of positions where to place lines." w, h = self.width, self.height if isX: length = w else: length = h if self.deltaSteps: r = [start + self.delta0] i = 0 while 1: if r[-1] > start + length: del r[-1] break r.append(r[-1] + self.deltaSteps[i % len(self.deltaSteps)]) i = i + 1 else: r = frange(start + self.delta0, start + length, self.delta) r.append(start + length) if self.delta0 != 0: r.insert(0, start) #print 'Grid.makeLinePosList() -> %s' % r return r def makeInnerLines(self): # inner grid lines group = Group() w, h = self.width, self.height if self.useLines == 1: if self.orientation == 'vertical': r = self.makeLinePosList(self.x, isX=1) for x in r: line = Line(x, self.y, x, self.y + h) line.strokeColor = self.strokeColor line.strokeWidth = self.strokeWidth group.add(line) elif self.orientation == 'horizontal': r = self.makeLinePosList(self.y, isX=0) for y in r: line = Line(self.x, y, self.x + w, y) line.strokeColor = self.strokeColor line.strokeWidth = self.strokeWidth group.add(line) return group def makeInnerTiles(self): # inner grid lines group = Group() w, h = self.width, self.height # inner grid stripes (solid rectangles) if self.useRects == 1: cols = self.stripeColors if self.orientation == 'vertical': r = self.makeLinePosList(self.x, isX=1) elif self.orientation == 'horizontal': r = self.makeLinePosList(self.y, isX=0) dist = makeDistancesList(r) i = 0 for j in range(len(dist)): if self.orientation == 'vertical': x = r[j] stripe = Rect(x, self.y, dist[j], h) elif self.orientation == 'horizontal': y = r[j] stripe = Rect(self.x, y, w, dist[j]) stripe.fillColor = cols[i % len(cols)] stripe.strokeColor = None group.add(stripe) i = i + 1 return group def draw(self): # general widget bits group = Group() group.add(self.makeOuterRect()) group.add(self.makeInnerTiles()) group.add(self.makeInnerLines(),name='_gridLines') return group class DoubleGrid(Widget): """This combines two ordinary Grid objects orthogonal to each other. """ _attrMap = AttrMap( x = AttrMapValue(isNumber, desc="The grid's lower-left x position."), y = AttrMapValue(isNumber, desc="The grid's lower-left y position."), width = AttrMapValue(isNumber, desc="The grid's width."), height = AttrMapValue(isNumber, desc="The grid's height."), grid0 = AttrMapValue(None, desc="The first grid component."), grid1 = AttrMapValue(None, desc="The second grid component."), ) def __init__(self): self.x = 0 self.y = 0 self.width = 100 self.height = 100 g0 = Grid() g0.x = self.x g0.y = self.y g0.width = self.width g0.height = self.height g0.orientation = 'vertical' g0.useLines = 1 g0.useRects = 0 g0.delta = 20 g0.delta0 = 0 g0.deltaSteps = [] g0.fillColor = colors.white g0.stripeColors = [colors.red, colors.green, colors.blue] g0.strokeColor = colors.black g0.strokeWidth = 1 g1 = Grid() g1.x = self.x g1.y = self.y g1.width = self.width g1.height = self.height g1.orientation = 'horizontal' g1.useLines = 1 g1.useRects = 0 g1.delta = 20 g1.delta0 = 0 g1.deltaSteps = [] g1.fillColor = colors.white g1.stripeColors = [colors.red, colors.green, colors.blue] g1.strokeColor = colors.black g1.strokeWidth = 1 self.grid0 = g0 self.grid1 = g1 ## # This gives an AttributeError: ## # DoubleGrid instance has no attribute 'grid0' ## def __setattr__(self, name, value): ## if name in ('x', 'y', 'width', 'height'): ## setattr(self.grid0, name, value) ## setattr(self.grid1, name, value) def demo(self): D = Drawing(100, 100) g = DoubleGrid() D.add(g) return D def draw(self): group = Group() g0, g1 = self.grid0, self.grid1 # Order groups to make sure both v and h lines # are visible (works only when there is only # one kind of stripes, v or h). G = g0.useRects == 1 and g1.useRects == 0 and (g0,g1) or (g1,g0) for g in G: group.add(g.makeOuterRect()) for g in G: group.add(g.makeInnerTiles()) group.add(g.makeInnerLines(),name='_gridLines') return group class ShadedRect(Widget): """This makes a rectangle with shaded colors between two colors. Colors are interpolated linearly between 'fillColorStart' and 'fillColorEnd', both of which appear at the margins. If 'numShades' is set to one, though, only 'fillColorStart' is used. """ _attrMap = AttrMap( x = AttrMapValue(isNumber, desc="The grid's lower-left x position."), y = AttrMapValue(isNumber, desc="The grid's lower-left y position."), width = AttrMapValue(isNumber, desc="The grid's width."), height = AttrMapValue(isNumber, desc="The grid's height."), orientation = AttrMapValue(OneOf(('vertical', 'horizontal')), desc='Determines if stripes are vertical or horizontal.'), numShades = AttrMapValue(isNumber, desc='The number of interpolating colors.'), fillColorStart = AttrMapValue(isColorOrNone, desc='Start value of the color shade.'), fillColorEnd = AttrMapValue(isColorOrNone, desc='End value of the color shade.'), strokeColor = AttrMapValue(isColorOrNone, desc='Color used for border line.'), strokeWidth = AttrMapValue(isNumber, desc='Width used for lines.'), cylinderMode = AttrMapValue(isBoolean, desc='True if shading reverses in middle.'), ) def __init__(self,**kw): self.x = 0 self.y = 0 self.width = 100 self.height = 100 self.orientation = 'vertical' self.numShades = 20 self.fillColorStart = colors.pink self.fillColorEnd = colors.black self.strokeColor = colors.black self.strokeWidth = 2 self.cylinderMode = 0 self.setProperties(kw) def demo(self): D = Drawing(100, 100) g = ShadedRect() D.add(g) return D def _flipRectCorners(self): "Flip rectangle's corners if width or height is negative." x, y, width, height, fillColorStart, fillColorEnd = self.x, self.y, self.width, self.height, self.fillColorStart, self.fillColorEnd if width < 0 and height > 0: x = x + width width = -width if self.orientation=='vertical': fillColorStart, fillColorEnd = fillColorEnd, fillColorStart elif height<0 and width>0: y = y + height height = -height if self.orientation=='horizontal': fillColorStart, fillColorEnd = fillColorEnd, fillColorStart elif height < 0 and height < 0: x = x + width width = -width y = y + height height = -height return x, y, width, height, fillColorStart, fillColorEnd def draw(self): # general widget bits group = Group() x, y, w, h, c0, c1 = self._flipRectCorners() numShades = self.numShades if self.cylinderMode: if not numShades%2: numShades = numShades+1 halfNumShades = int((numShades-1)/2) + 1 num = float(numShades) # must make it float! vertical = self.orientation == 'vertical' if vertical: if numShades == 1: V = [x] else: V = frange(x, x + w, w/num) else: if numShades == 1: V = [y] else: V = frange(y, y + h, h/num) for v in V: stripe = vertical and Rect(v, y, w/num, h) or Rect(x, v, w, h/num) if self.cylinderMode: if V.index(v)>=halfNumShades: col = colors.linearlyInterpolatedColor(c1,c0,V[halfNumShades],V[-1], v) else: col = colors.linearlyInterpolatedColor(c0,c1,V[0],V[halfNumShades], v) else: col = colors.linearlyInterpolatedColor(c0,c1,V[0],V[-1], v) stripe.fillColor = col stripe.strokeColor = col stripe.strokeWidth = 1 group.add(stripe) if self.strokeColor and self.strokeWidth>=0: rect = Rect(x, y, w, h) rect.strokeColor = self.strokeColor rect.strokeWidth = self.strokeWidth rect.fillColor = None group.add(rect) return group def colorRange(c0, c1, n): "Return a range of intermediate colors between c0 and c1" if n==1: return [c0] C = [] if n>1: lim = n-1 for i in range(n): C.append(colors.linearlyInterpolatedColor(c0,c1,0,lim, i)) return C def centroid(P): '''compute average point of a set of points''' cx = 0 cy = 0 for x,y in P: cx+=x cy+=y n = float(len(P)) return cx/n, cy/n def rotatedEnclosingRect(P, angle, rect): ''' given P a sequence P of x,y coordinate pairs and an angle in degrees find the centroid of P and the axis at angle theta through it find the extreme points of P wrt axis parallel distance and axis orthogonal distance. Then compute the least rectangle that will still enclose P when rotated by angle. The class R ''' from math import pi, cos, sin x0, y0 = centroid(P) theta = (angle/180.)*pi s,c=sin(theta),cos(theta) def parallelAxisDist(xy,s=s,c=c,x0=x0,y0=y0): x,y = xy return (s*(y-y0)+c*(x-x0)) def orthogonalAxisDist(xy,s=s,c=c,x0=x0,y0=y0): x,y = xy return (c*(y-y0)+s*(x-x0)) L = list(map(parallelAxisDist,P)) L.sort() a0, a1 = L[0], L[-1] L = list(map(orthogonalAxisDist,P)) L.sort() b0, b1 = L[0], L[-1] rect.x, rect.width = a0, a1-a0 rect.y, rect.height = b0, b1-b0 g = Group(transform=(c,s,-s,c,x0,y0)) g.add(rect) return g class ShadedPolygon(Widget,LineShape): _attrMap = AttrMap(BASE=LineShape, angle = AttrMapValue(isNumber,desc="Shading angle"), fillColorStart = AttrMapValue(isColorOrNone), fillColorEnd = AttrMapValue(isColorOrNone), numShades = AttrMapValue(isNumber, desc='The number of interpolating colors.'), cylinderMode = AttrMapValue(isBoolean, desc='True if shading reverses in middle.'), points = AttrMapValue(isListOfNumbers), ) def __init__(self,**kw): self.angle = 90 self.fillColorStart = colors.red self.fillColorEnd = colors.green self.cylinderMode = 0 self.numShades = 50 self.points = [-1,-1,2,2,3,-1] LineShape.__init__(self,kw) def draw(self): P = self.points P = list(map(lambda i, P=P:(P[i],P[i+1]),range(0,len(P),2))) path = definePath([('moveTo',)+P[0]]+[('lineTo',)+x for x in P[1:]]+['closePath'], fillColor=None, strokeColor=None) path.isClipPath = 1 g = Group() g.add(path) angle = self.angle orientation = 'vertical' if angle==180: angle = 0 elif angle in (90,270): orientation ='horizontal' angle = 0 rect = ShadedRect(strokeWidth=0,strokeColor=None,orientation=orientation) for k in 'fillColorStart', 'fillColorEnd', 'numShades', 'cylinderMode': setattr(rect,k,getattr(self,k)) g.add(rotatedEnclosingRect(P, angle, rect)) g.add(EmptyClipPath) path = path.copy() path.isClipPath = 0 path.strokeColor = self.strokeColor path.strokeWidth = self.strokeWidth g.add(path) return g if __name__=='__main__': #noruntests angle=45 D = Drawing(120,120) D.add(ShadedPolygon(points=(10,10,60,60,110,10),strokeColor=None,strokeWidth=1,angle=90,numShades=50,cylinderMode=0)) D.save(formats=['gif'],fnRoot='shobj',outDir='/tmp')
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/widgets/grids.py
0.609059
0.444324
grids.py
pypi
__version__='3.3.0' __doc__="""This file is a collection of flag graphics as widgets. All flags are represented at the ratio of 1:2, even where the official ratio for the flag is something else (such as 3:5 for the German national flag). The only exceptions are for where this would look _very_ wrong, such as the Danish flag whose (ratio is 28:37), or the Swiss flag (which is square). Unless otherwise stated, these flags are all the 'national flags' of the countries, rather than their state flags, naval flags, ensigns or any other variants. (National flags are the flag flown by civilians of a country and the ones usually used to represent a country abroad. State flags are the variants used by the government and by diplomatic missions overseas). To check on how close these are to the 'official' representations of flags, check the World Flag Database at http://www.flags.ndirect.co.uk/ The flags this file contains are: EU Members: United Kingdom, Austria, Belgium, Denmark, Finland, France, Germany, Greece, Ireland, Italy, Luxembourg, Holland (The Netherlands), Spain, Sweden Others: USA, Czech Republic, European Union, Switzerland, Turkey, Brazil (Brazilian flag contributed by Publio da Costa Melo [publio@planetarium.com.br]). """ from reportlab.lib import colors from reportlab.lib.validators import * from reportlab.lib.attrmap import * from reportlab.graphics.shapes import Line, Rect, Polygon, Drawing, Group, String, Circle, Wedge from reportlab.graphics import renderPDF from reportlab.graphics.widgets.signsandsymbols import _Symbol import copy from math import sin, cos, pi validFlag=OneOf(None, 'UK', 'USA', 'Afghanistan', 'Austria', 'Belgium', 'China', 'Cuba', 'Denmark', 'Finland', 'France', 'Germany', 'Greece', 'Ireland', 'Italy', 'Japan', 'Luxembourg', 'Holland', 'Palestine', 'Portugal', 'Russia', 'Spain', 'Sweden', 'Norway', 'CzechRepublic', 'Turkey', 'Switzerland', 'EU', 'Brazil' ) _size = 100. class Star(_Symbol): """This draws a 5-pointed star. possible attributes: 'x', 'y', 'size', 'fillColor', 'strokeColor' """ _attrMap = AttrMap(BASE=_Symbol, angle = AttrMapValue(isNumber, desc='angle in degrees'), ) _size = 100. def __init__(self): _Symbol.__init__(self) self.size = 100 self.fillColor = colors.yellow self.strokeColor = None self.angle = 0 def demo(self): D = Drawing(200, 100) et = Star() et.x=50 et.y=0 D.add(et) labelFontSize = 10 D.add(String(et.x+(et.size/2.0),(et.y-(1.2*labelFontSize)), et.__class__.__name__, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) return D def draw(self): s = float(self.size) #abbreviate as we will use this a lot g = Group() # new algorithm from markers.StarFive R = float(self.size)/2 r = R*sin(18*(pi/180.0))/cos(36*(pi/180.0)) P = [] angle = 90 for i in range(5): for radius in R, r: theta = angle*(pi/180.0) P.append(radius*cos(theta)) P.append(radius*sin(theta)) angle = angle + 36 # star specific bits star = Polygon(P, fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth=s/50) g.rotate(self.angle) g.shift(self.x+self.dx,self.y+self.dy) g.add(star) return g class Flag(_Symbol): """This is a generic flag class that all the flags in this file use as a basis. This class basically provides edges and a tidy-up routine to hide any bits of line that overlap the 'outside' of the flag possible attributes: 'x', 'y', 'size', 'fillColor' """ _attrMap = AttrMap(BASE=_Symbol, fillColor = AttrMapValue(isColor, desc='Background color'), border = AttrMapValue(isBoolean, 'Whether a background is drawn'), kind = AttrMapValue(validFlag, desc='Which flag'), ) _cache = {} def __init__(self,**kw): _Symbol.__init__(self) self.kind = None self.size = 100 self.fillColor = colors.white self.border=1 self.setProperties(kw) def availableFlagNames(self): '''return a list of the things we can display''' return [x for x in self._attrMap['kind'].validate._enum if x is not None] def _Flag_None(self): s = _size # abbreviate as we will use this a lot g = Group() g.add(Rect(0, 0, s*2, s, fillColor = colors.purple, strokeColor = colors.black, strokeWidth=0)) return g def _borderDraw(self,f): s = self.size # abbreviate as we will use this a lot g = Group() g.add(f) x, y, sW = self.x+self.dx, self.y+self.dy, self.strokeWidth/2. g.insert(0,Rect(-sW, -sW, width=getattr(self,'_width',2*s)+3*sW, height=getattr(self,'_height',s)+2*sW, fillColor = None, strokeColor = self.strokeColor, strokeWidth=sW*2)) g.shift(x,y) g.scale(s/_size, s/_size) return g def draw(self): kind = self.kind or 'None' f = self._cache.get(kind) if not f: f = getattr(self,'_Flag_'+kind)() self._cache[kind] = f._explode() return self._borderDraw(f) def clone(self): return copy.copy(self) def demo(self): D = Drawing(200, 100) name = self.availableFlagNames() import time name = name[int(time.time()) % len(name)] fx = Flag() fx.kind = name fx.x = 0 fx.y = 0 D.add(fx) labelFontSize = 10 D.add(String(fx.x+(fx.size/2.0),(fx.y-(1.2*labelFontSize)), name, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) labelFontSize = int(fx.size/4.0) D.add(String(fx.x+(fx.size),(fx.y+((fx.size/2.0))), "SAMPLE", fillColor=colors.gold, textAnchor='middle', fontSize=labelFontSize, fontName="Helvetica-Bold")) return D def _Flag_UK(self): s = _size g = Group() w = s*2 g.add(Rect(0, 0, w, s, fillColor = colors.navy, strokeColor = colors.black, strokeWidth=0)) g.add(Polygon([0,0, s*.225,0, w,s*(1-.1125), w,s, w-s*.225,s, 0, s*.1125], fillColor = colors.mintcream, strokeColor=None, strokeWidth=0)) g.add(Polygon([0,s*(1-.1125), 0, s, s*.225,s, w, s*.1125, w,0, w-s*.225,0], fillColor = colors.mintcream, strokeColor=None, strokeWidth=0)) g.add(Polygon([0, s-(s/15.0), (s-((s/10.0)*4)), (s*0.65), (s-(s/10.0)*3), (s*0.65), 0, s], fillColor = colors.red, strokeColor = None, strokeWidth=0)) g.add(Polygon([0, 0, (s-((s/10.0)*3)), (s*0.35), (s-((s/10.0)*2)), (s*0.35), (s/10.0), 0], fillColor = colors.red, strokeColor = None, strokeWidth=0)) g.add(Polygon([w, s, (s+((s/10.0)*3)), (s*0.65), (s+((s/10.0)*2)), (s*0.65), w-(s/10.0), s], fillColor = colors.red, strokeColor = None, strokeWidth=0)) g.add(Polygon([w, (s/15.0), (s+((s/10.0)*4)), (s*0.35), (s+((s/10.0)*3)), (s*0.35), w, 0], fillColor = colors.red, strokeColor = None, strokeWidth=0)) g.add(Rect(((s*0.42)*2), 0, width=(0.16*s)*2, height=s, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0)) g.add(Rect(0, (s*0.35), width=w, height=s*0.3, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0)) g.add(Rect(((s*0.45)*2), 0, width=(0.1*s)*2, height=s, fillColor = colors.red, strokeColor = None, strokeWidth=0)) g.add(Rect(0, (s*0.4), width=w, height=s*0.2, fillColor = colors.red, strokeColor = None, strokeWidth=0)) return g def _Flag_USA(self): s = _size # abbreviate as we will use this a lot g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) g.add(box) for stripecounter in range (13,0, -1): stripeheight = s/13.0 if not (stripecounter%2 == 0): stripecolor = colors.red else: stripecolor = colors.mintcream redorwhiteline = Rect(0, (s-(stripeheight*stripecounter)), width=s*2, height=stripeheight, fillColor = stripecolor, strokeColor = None, strokeWidth=20) g.add(redorwhiteline) bluebox = Rect(0, (s-(stripeheight*7)), width=0.8*s, height=stripeheight*7, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) g.add(bluebox) lss = s*0.045 lss2 = lss/2.0 s9 = s/9.0 s7 = s/7.0 for starxcounter in range(5): for starycounter in range(4): ls = Star() ls.size = lss ls.x = 0-s/22.0+lss/2.0+s7+starxcounter*s7 ls.fillColor = colors.mintcream ls.y = s-(starycounter+1)*s9+lss2 g.add(ls) for starxcounter in range(6): for starycounter in range(5): ls = Star() ls.size = lss ls.x = 0-(s/22.0)+lss/2.0+s/14.0+starxcounter*s7 ls.fillColor = colors.mintcream ls.y = s-(starycounter+1)*s9+(s/18.0)+lss2 g.add(ls) return g def _Flag_Afghanistan(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) g.add(box) greenbox = Rect(0, ((s/3.0)*2.0), width=s*2.0, height=s/3.0, fillColor = colors.limegreen, strokeColor = None, strokeWidth=0) g.add(greenbox) blackbox = Rect(0, 0, width=s*2.0, height=s/3.0, fillColor = colors.black, strokeColor = None, strokeWidth=0) g.add(blackbox) return g def _Flag_Austria(self): s = _size # abbreviate as we will use this a lot g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) g.add(box) redbox1 = Rect(0, 0, width=s*2.0, height=s/3.0, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redbox1) redbox2 = Rect(0, ((s/3.0)*2.0), width=s*2.0, height=s/3.0, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redbox2) return g def _Flag_Belgium(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.black, strokeColor = colors.black, strokeWidth=0) g.add(box) box1 = Rect(0, 0, width=(s/3.0)*2.0, height=s, fillColor = colors.black, strokeColor = None, strokeWidth=0) g.add(box1) box2 = Rect(((s/3.0)*2.0), 0, width=(s/3.0)*2.0, height=s, fillColor = colors.gold, strokeColor = None, strokeWidth=0) g.add(box2) box3 = Rect(((s/3.0)*4.0), 0, width=(s/3.0)*2.0, height=s, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(box3) return g def _Flag_China(self): s = _size g = Group() self._width = w = s*1.5 g.add(Rect(0, 0, w, s, fillColor=colors.red, strokeColor=None, strokeWidth=0)) def addStar(x,y,size,angle,g=g,w=s/20.0,x0=0,y0=s/2.0): s = Star() s.fillColor=colors.yellow s.angle = angle s.size = size*w*2 s.x = x*w+x0 s.y = y*w+y0 g.add(s) addStar(5,5,3, 0) addStar(10,1,1,36.86989765) addStar(12,3,1,8.213210702) addStar(12,6,1,16.60154960) addStar(10,8,1,53.13010235) return g def _Flag_Cuba(self): s = _size g = Group() for i in range(5): stripe = Rect(0, i*s/5.0, width=s*2, height=s/5.0, fillColor = [colors.darkblue, colors.mintcream][i%2], strokeColor = None, strokeWidth=0) g.add(stripe) redwedge = Polygon(points = [ 0, 0, 4*s/5.0, (s/2.0), 0, s], fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redwedge) star = Star() star.x = 2.5*s/10.0 star.y = s/2.0 star.size = 3*s/10.0 star.fillColor = colors.white g.add(star) box = Rect(0, 0, s*2, s, fillColor = None, strokeColor = colors.black, strokeWidth=0) g.add(box) return g def _Flag_Denmark(self): s = _size g = Group() self._width = w = s*1.4 box = Rect(0, 0, w, s, fillColor = colors.red, strokeColor = colors.black, strokeWidth=0) g.add(box) whitebox1 = Rect(((s/5.0)*2), 0, width=s/6.0, height=s, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(whitebox1) whitebox2 = Rect(0, ((s/2.0)-(s/12.0)), width=w, height=s/6.0, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(whitebox2) return g def _Flag_Finland(self): s = _size g = Group() # crossbox specific bits box = Rect(0, 0, s*2, s, fillColor = colors.ghostwhite, strokeColor = colors.black, strokeWidth=0) g.add(box) blueline1 = Rect((s*0.6), 0, width=0.3*s, height=s, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) g.add(blueline1) blueline2 = Rect(0, (s*0.4), width=s*2, height=s*0.3, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) g.add(blueline2) return g def _Flag_France(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.navy, strokeColor = colors.black, strokeWidth=0) g.add(box) bluebox = Rect(0, 0, width=((s/3.0)*2.0), height=s, fillColor = colors.blue, strokeColor = None, strokeWidth=0) g.add(bluebox) whitebox = Rect(((s/3.0)*2.0), 0, width=((s/3.0)*2.0), height=s, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(whitebox) redbox = Rect(((s/3.0)*4.0), 0, width=((s/3.0)*2.0), height=s, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redbox) return g def _Flag_Germany(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.gold, strokeColor = colors.black, strokeWidth=0) g.add(box) blackbox1 = Rect(0, ((s/3.0)*2.0), width=s*2.0, height=s/3.0, fillColor = colors.black, strokeColor = None, strokeWidth=0) g.add(blackbox1) redbox1 = Rect(0, (s/3.0), width=s*2.0, height=s/3.0, fillColor = colors.orangered, strokeColor = None, strokeWidth=0) g.add(redbox1) return g def _Flag_Greece(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.gold, strokeColor = colors.black, strokeWidth=0) g.add(box) for stripecounter in range (9,0, -1): stripeheight = s/9.0 if not (stripecounter%2 == 0): stripecolor = colors.deepskyblue else: stripecolor = colors.mintcream blueorwhiteline = Rect(0, (s-(stripeheight*stripecounter)), width=s*2, height=stripeheight, fillColor = stripecolor, strokeColor = None, strokeWidth=20) g.add(blueorwhiteline) bluebox1 = Rect(0, ((s)-stripeheight*5), width=(stripeheight*5), height=stripeheight*5, fillColor = colors.deepskyblue, strokeColor = None, strokeWidth=0) g.add(bluebox1) whiteline1 = Rect(0, ((s)-stripeheight*3), width=stripeheight*5, height=stripeheight, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(whiteline1) whiteline2 = Rect((stripeheight*2), ((s)-stripeheight*5), width=stripeheight, height=stripeheight*5, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(whiteline2) return g def _Flag_Ireland(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.forestgreen, strokeColor = colors.black, strokeWidth=0) g.add(box) whitebox = Rect(((s*2.0)/3.0), 0, width=(2.0*(s*2.0)/3.0), height=s, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(whitebox) orangebox = Rect(((2.0*(s*2.0)/3.0)), 0, width=(s*2.0)/3.0, height=s, fillColor = colors.darkorange, strokeColor = None, strokeWidth=0) g.add(orangebox) return g def _Flag_Italy(self): s = _size g = Group() g.add(Rect(0,0,s*2,s,fillColor=colors.forestgreen,strokeColor=None, strokeWidth=0)) g.add(Rect((2*s)/3.0, 0, width=(s*4)/3.0, height=s, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0)) g.add(Rect((4*s)/3.0, 0, width=(s*2)/3.0, height=s, fillColor = colors.red, strokeColor = None, strokeWidth=0)) return g def _Flag_Japan(self): s = _size g = Group() w = self._width = s*1.5 g.add(Rect(0,0,w,s,fillColor=colors.mintcream,strokeColor=None, strokeWidth=0)) g.add(Circle(cx=w/2.0,cy=s/2.0,r=0.3*w,fillColor=colors.red,strokeColor=None, strokeWidth=0)) return g def _Flag_Luxembourg(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) g.add(box) redbox = Rect(0, ((s/3.0)*2.0), width=s*2.0, height=s/3.0, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redbox) bluebox = Rect(0, 0, width=s*2.0, height=s/3.0, fillColor = colors.dodgerblue, strokeColor = None, strokeWidth=0) g.add(bluebox) return g def _Flag_Holland(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) g.add(box) redbox = Rect(0, ((s/3.0)*2.0), width=s*2.0, height=s/3.0, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redbox) bluebox = Rect(0, 0, width=s*2.0, height=s/3.0, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) g.add(bluebox) return g def _Flag_Portugal(self): return Group() def _Flag_Russia(self): s = _size g = Group() w = self._width = s*1.5 t = s/3.0 g.add(Rect(0, 0, width=w, height=t, fillColor = colors.red, strokeColor = None, strokeWidth=0)) g.add(Rect(0, t, width=w, height=t, fillColor = colors.blue, strokeColor = None, strokeWidth=0)) g.add(Rect(0, 2*t, width=w, height=t, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0)) return g def _Flag_Spain(self): s = _size g = Group() w = self._width = s*1.5 g.add(Rect(0, 0, width=w, height=s, fillColor = colors.red, strokeColor = None, strokeWidth=0)) g.add(Rect(0, (s/4.0), width=w, height=s/2.0, fillColor = colors.yellow, strokeColor = None, strokeWidth=0)) return g def _Flag_Sweden(self): s = _size g = Group() self._width = s*1.4 box = Rect(0, 0, self._width, s, fillColor = colors.dodgerblue, strokeColor = colors.black, strokeWidth=0) g.add(box) box1 = Rect(((s/5.0)*2), 0, width=s/6.0, height=s, fillColor = colors.gold, strokeColor = None, strokeWidth=0) g.add(box1) box2 = Rect(0, ((s/2.0)-(s/12.0)), width=self._width, height=s/6.0, fillColor = colors.gold, strokeColor = None, strokeWidth=0) g.add(box2) return g def _Flag_Norway(self): s = _size g = Group() self._width = s*1.4 box = Rect(0, 0, self._width, s, fillColor = colors.red, strokeColor = colors.black, strokeWidth=0) g.add(box) box = Rect(0, 0, self._width, s, fillColor = colors.red, strokeColor = colors.black, strokeWidth=0) g.add(box) whiteline1 = Rect(((s*0.2)*2), 0, width=s*0.2, height=s, fillColor = colors.ghostwhite, strokeColor = None, strokeWidth=0) g.add(whiteline1) whiteline2 = Rect(0, (s*0.4), width=self._width, height=s*0.2, fillColor = colors.ghostwhite, strokeColor = None, strokeWidth=0) g.add(whiteline2) blueline1 = Rect(((s*0.225)*2), 0, width=0.1*s, height=s, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) g.add(blueline1) blueline2 = Rect(0, (s*0.45), width=self._width, height=s*0.1, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) g.add(blueline2) return g def _Flag_CzechRepublic(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) g.add(box) redbox = Rect(0, 0, width=s*2, height=s/2.0, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redbox) bluewedge = Polygon(points = [ 0, 0, s, (s/2.0), 0, s], fillColor = colors.darkblue, strokeColor = None, strokeWidth=0) g.add(bluewedge) return g def _Flag_Palestine(self): s = _size g = Group() box = Rect(0, s/3.0, s*2, s/3.0, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(box) greenbox = Rect(0, 0, width=s*2, height=s/3.0, fillColor = colors.limegreen, strokeColor = None, strokeWidth=0) g.add(greenbox) blackbox = Rect(0, 2*s/3.0, width=s*2, height=s/3.0, fillColor = colors.black, strokeColor = None, strokeWidth=0) g.add(blackbox) redwedge = Polygon(points = [ 0, 0, 2*s/3.0, (s/2.0), 0, s], fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redwedge) return g def _Flag_Turkey(self): s = _size g = Group() box = Rect(0, 0, s*2, s, fillColor = colors.red, strokeColor = colors.black, strokeWidth=0) g.add(box) whitecircle = Circle(cx=((s*0.35)*2), cy=s/2.0, r=s*0.3, fillColor = colors.mintcream, strokeColor = None, strokeWidth=0) g.add(whitecircle) redcircle = Circle(cx=((s*0.39)*2), cy=s/2.0, r=s*0.24, fillColor = colors.red, strokeColor = None, strokeWidth=0) g.add(redcircle) ws = Star() ws.angle = 15 ws.size = s/5.0 ws.x = (s*0.5)*2+ws.size/2.0 ws.y = (s*0.5) ws.fillColor = colors.mintcream ws.strokeColor = None g.add(ws) return g def _Flag_Switzerland(self): s = _size g = Group() self._width = s g.add(Rect(0, 0, s, s, fillColor = colors.red, strokeColor = colors.black, strokeWidth=0)) g.add(Line((s/2.0), (s/5.5), (s/2), (s-(s/5.5)), fillColor = colors.mintcream, strokeColor = colors.mintcream, strokeWidth=(s/5.0))) g.add(Line((s/5.5), (s/2.0), (s-(s/5.5)), (s/2.0), fillColor = colors.mintcream, strokeColor = colors.mintcream, strokeWidth=s/5.0)) return g def _Flag_EU(self): s = _size g = Group() w = self._width = 1.5*s g.add(Rect(0, 0, w, s, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0)) centerx=w/2.0 centery=s/2.0 radius=s/3.0 yradius = radius xradius = radius nStars = 12 delta = 2*pi/nStars for i in range(nStars): rad = i*delta gs = Star() gs.x=cos(rad)*radius+centerx gs.y=sin(rad)*radius+centery gs.size=s/10.0 gs.fillColor=colors.gold g.add(gs) return g def _Flag_Brazil(self): s = _size # abbreviate as we will use this a lot g = Group() m = s/14.0 self._width = w = (m * 20) def addStar(x,y,size, g=g, w=w, s=s, m=m): st = Star() st.fillColor=colors.mintcream st.size = size*m st.x = (w/2.0) + (x * (0.35 * m)) st.y = (s/2.0) + (y * (0.35 * m)) g.add(st) g.add(Rect(0, 0, w, s, fillColor = colors.green, strokeColor = None, strokeWidth=0)) g.add(Polygon(points = [ 1.7*m, (s/2.0), (w/2.0), s-(1.7*m), w-(1.7*m),(s/2.0),(w/2.0), 1.7*m], fillColor = colors.yellow, strokeColor = None, strokeWidth=0)) g.add(Circle(cx=w/2.0, cy=s/2.0, r=3.5*m, fillColor=colors.blue,strokeColor=None, strokeWidth=0)) g.add(Wedge((w/2.0)-(2*m), 0, 8.5*m, 50, 98.1, 8.5*m, fillColor=colors.mintcream,strokeColor=None, strokeWidth=0)) g.add(Wedge((w/2.0), (s/2.0), 3.501*m, 156, 352, 3.501*m, fillColor=colors.mintcream,strokeColor=None, strokeWidth=0)) g.add(Wedge((w/2.0)-(2*m), 0, 8*m, 48.1, 100, 8*m, fillColor=colors.blue,strokeColor=None, strokeWidth=0)) g.add(Rect(0, 0, w, (s/4.0) + 1.7*m, fillColor = colors.green, strokeColor = None, strokeWidth=0)) g.add(Polygon(points = [ 1.7*m,(s/2.0), (w/2.0),s/2.0 - 2*m, w-(1.7*m),(s/2.0) , (w/2.0),1.7*m], fillColor = colors.yellow, strokeColor = None, strokeWidth=0)) g.add(Wedge(w/2.0, s/2.0, 3.502*m, 166, 342.1, 3.502*m, fillColor=colors.blue,strokeColor=None, strokeWidth=0)) addStar(3.2,3.5,0.3) addStar(-8.5,1.5,0.3) addStar(-7.5,-3,0.3) addStar(-4,-5.5,0.3) addStar(0,-4.5,0.3) addStar(7,-3.5,0.3) addStar(-3.5,-0.5,0.25) addStar(0,-1.5,0.25) addStar(1,-2.5,0.25) addStar(3,-7,0.25) addStar(5,-6.5,0.25) addStar(6.5,-5,0.25) addStar(7,-4.5,0.25) addStar(-5.5,-3.2,0.25) addStar(-6,-4.2,0.25) addStar(-1,-2.75,0.2) addStar(2,-5.5,0.2) addStar(4,-5.5,0.2) addStar(5,-7.5,0.2) addStar(5,-5.5,0.2) addStar(6,-5.5,0.2) addStar(-8.8,-3.2,0.2) addStar(2.5,0.5,0.2) addStar(-0.2,-3.2,0.14) addStar(-7.2,-2,0.14) addStar(0,-8,0.1) sTmp = "ORDEM E PROGRESSO" nTmp = len(sTmp) delta = 0.850848010347/nTmp radius = 7.9 *m centerx = (w/2.0)-(2*m) centery = 0 for i in range(nTmp): rad = 2*pi - i*delta -4.60766922527 x=cos(rad)*radius+centerx y=sin(rad)*radius+centery if i == 6: z = 0.35*m else: z= 0.45*m g2 = Group(String(x, y, sTmp[i], fontName='Helvetica-Bold', fontSize = z,strokeColor=None,fillColor=colors.green)) g2.rotate(rad) g.add(g2) return g def makeFlag(name): flag = Flag() flag.kind = name return flag def test(): """This function produces three pdf files with examples of all the signs and symbols from this file. """ # page 1 labelFontSize = 10 X = (20,245) flags = [ 'UK', 'USA', 'Afghanistan', 'Austria', 'Belgium', 'Denmark', 'Cuba', 'Finland', 'France', 'Germany', 'Greece', 'Ireland', 'Italy', 'Luxembourg', 'Holland', 'Palestine', 'Portugal', 'Spain', 'Sweden', 'Norway', 'CzechRepublic', 'Turkey', 'Switzerland', 'EU', 'Brazil', ] y = Y0 = 530 f = 0 D = None for name in flags: if not D: D = Drawing(450,650) flag = makeFlag(name) i = flags.index(name) flag.x = X[i%2] flag.y = y D.add(flag) D.add(String(flag.x+(flag.size/2.0),(flag.y-(1.2*labelFontSize)), name, fillColor=colors.black, textAnchor='middle', fontSize=labelFontSize)) if i%2: y = y - 125 if (i%2 and y<0) or name==flags[-1]: renderPDF.drawToFile(D, 'flags%02d.pdf'%f, 'flags.py - Page #%d'%(f+1)) y = Y0 f = f+1 D = None if __name__=='__main__': test()
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/widgets/flags.py
0.764276
0.523664
flags.py
pypi
__version__='3.3.0' __doc__="""This modules defines a collection of markers used in charts. """ from reportlab.graphics.shapes import Rect, Circle, Polygon, Drawing, Group from reportlab.graphics.widgets.signsandsymbols import SmileyFace from reportlab.graphics.widgetbase import Widget from reportlab.lib.validators import isNumber, isColorOrNone, OneOf, Validator from reportlab.lib.attrmap import AttrMap, AttrMapValue from reportlab.lib.colors import black from reportlab.lib.utils import isClass from reportlab.graphics.widgets.flags import Flag, _Symbol from math import sin, cos, pi _toradians = pi/180.0 class Marker(Widget): '''A polymorphic class of markers''' _attrMap = AttrMap(BASE=Widget, kind = AttrMapValue( OneOf(None, 'Square', 'Diamond', 'Circle', 'Cross', 'Triangle', 'StarSix', 'Pentagon', 'Hexagon', 'Heptagon', 'Octagon', 'StarFive', 'FilledSquare', 'FilledCircle', 'FilledDiamond', 'FilledCross', 'FilledTriangle','FilledStarSix', 'FilledPentagon', 'FilledHexagon', 'FilledHeptagon', 'FilledOctagon', 'FilledStarFive', 'Smiley','ArrowHead', 'FilledArrowHead'), desc='marker type name'), size = AttrMapValue(isNumber,desc='marker size'), x = AttrMapValue(isNumber,desc='marker x coordinate'), y = AttrMapValue(isNumber,desc='marker y coordinate'), dx = AttrMapValue(isNumber,desc='marker x coordinate adjustment'), dy = AttrMapValue(isNumber,desc='marker y coordinate adjustment'), angle = AttrMapValue(isNumber,desc='marker rotation'), fillColor = AttrMapValue(isColorOrNone, desc='marker fill colour'), strokeColor = AttrMapValue(isColorOrNone, desc='marker stroke colour'), strokeWidth = AttrMapValue(isNumber, desc='marker stroke width'), arrowBarbDx = AttrMapValue(isNumber, desc='arrow only the delta x for the barbs'), arrowHeight = AttrMapValue(isNumber, desc='arrow only height'), ) def __init__(self,*args,**kw): self.setProperties(kw) self._setKeywords( kind = None, strokeColor = black, strokeWidth = 0.1, fillColor = None, size = 5, x = 0, y = 0, dx = 0, dy = 0, angle = 0, arrowBarbDx = -1.25, arrowHeight = 1.875, ) def clone(self,**kwds): n = self.__class__(**self.__dict__) if kwds: n.__dict__.update(kwds) return n def _Smiley(self): x, y = self.x+self.dx, self.y+self.dy d = self.size/2.0 s = SmileyFace() s.fillColor = self.fillColor s.strokeWidth = self.strokeWidth s.strokeColor = self.strokeColor s.x = x-d s.y = y-d s.size = d*2 return s def _Square(self): x, y = self.x+self.dx, self.y+self.dy d = self.size/2.0 s = Rect(x-d,y-d,2*d,2*d,fillColor=self.fillColor,strokeColor=self.strokeColor,strokeWidth=self.strokeWidth) return s def _Diamond(self): d = self.size/2.0 return self._doPolygon((-d,0,0,d,d,0,0,-d)) def _Circle(self): x, y = self.x+self.dx, self.y+self.dy s = Circle(x,y,self.size/2.0,fillColor=self.fillColor,strokeColor=self.strokeColor,strokeWidth=self.strokeWidth) return s def _Cross(self): x, y = self.x+self.dx, self.y+self.dy s = float(self.size) h, s = s/2, s/6 return self._doPolygon((-s,-h,-s,-s,-h,-s,-h,s,-s,s,-s,h,s,h,s,s,h,s,h,-s,s,-s,s,-h)) def _Triangle(self): x, y = self.x+self.dx, self.y+self.dy r = float(self.size)/2 c = 30*_toradians s = sin(30*_toradians)*r c = cos(c)*r return self._doPolygon((0,r,-c,-s,c,-s)) def _StarSix(self): r = float(self.size)/2 c = 30*_toradians s = sin(c)*r c = cos(c)*r z = s/2 g = c/2 return self._doPolygon((0,r,-z,s,-c,s,-s,0,-c,-s,-z,-s,0,-r,z,-s,c,-s,s,0,c,s,z,s)) def _StarFive(self): R = float(self.size)/2 r = R*sin(18*_toradians)/cos(36*_toradians) P = [] angle = 90 for i in range(5): for radius in R, r: theta = angle*_toradians P.append(radius*cos(theta)) P.append(radius*sin(theta)) angle = angle + 36 return self._doPolygon(P) def _Pentagon(self): return self._doNgon(5) def _Hexagon(self): return self._doNgon(6) def _Heptagon(self): return self._doNgon(7) def _Octagon(self): return self._doNgon(8) def _ArrowHead(self): s = self.size h = self.arrowHeight b = self.arrowBarbDx return self._doPolygon((0,0,b,-h,s,0,b,h)) def _doPolygon(self,P): x, y = self.x+self.dx, self.y+self.dy if x or y: P = list(map(lambda i,P=P,A=[x,y]: P[i] + A[i&1], list(range(len(P))))) return Polygon(P, strokeWidth =self.strokeWidth, strokeColor=self.strokeColor, fillColor=self.fillColor) def _doFill(self): old = self.fillColor if old is None: self.fillColor = self.strokeColor r = (self.kind and getattr(self,'_'+self.kind[6:]) or Group)() self.fillColor = old return r def _doNgon(self,n): P = [] size = float(self.size)/2 for i in range(n): r = (2.*i/n+0.5)*pi P.append(size*cos(r)) P.append(size*sin(r)) return self._doPolygon(P) _FilledCircle = _doFill _FilledSquare = _doFill _FilledDiamond = _doFill _FilledCross = _doFill _FilledTriangle = _doFill _FilledStarSix = _doFill _FilledPentagon = _doFill _FilledHexagon = _doFill _FilledHeptagon = _doFill _FilledOctagon = _doFill _FilledStarFive = _doFill _FilledArrowHead = _doFill def draw(self): if self.kind: m = getattr(self,'_'+self.kind) if self.angle: _x, _dx, _y, _dy = self.x, self.dx, self.y, self.dy self.x, self.dx, self.y, self.dy = 0,0,0,0 try: m = m() finally: self.x, self.dx, self.y, self.dy = _x, _dx, _y, _dy if not isinstance(m,Group): _m, m = m, Group() m.add(_m) if self.angle: m.rotate(self.angle) x, y = _x+_dx, _y+_dy if x or y: m.shift(x,y) else: m = m() else: m = Group() return m def uSymbol2Symbol(uSymbol,x,y,color): if isClass(uSymbol) and issubclass(uSymbol,Widget): size = 10. symbol = uSymbol() symbol.x = x - (size/2) symbol.y = y - (size/2) try: symbol.size = size symbol.color = color except: pass elif isinstance(uSymbol,Marker) or isinstance(uSymbol,_Symbol): symbol = uSymbol.clone() if isinstance(uSymbol,Marker): symbol.fillColor = symbol.fillColor or color symbol.x, symbol.y = x, y elif callable(uSymbol): symbol = uSymbol(x, y, 5, color) else: symbol = None return symbol class _isSymbol(Validator): def test(self,x): return hasattr(x,'__call__') or isinstance(x,Marker) or isinstance(x,_Symbol) or (isClass(x) and issubclass(x,Widget)) isSymbol = _isSymbol() def makeMarker(name,**kw): if Marker._attrMap['kind'].validate(name): m = Marker(**kw) m.kind = name elif name[-5:]=='_Flag' and Flag._attrMap['kind'].validate(name[:-5]): m = Flag(**kw) m.kind = name[:-5] m.size = 10 else: raise ValueError("Invalid marker name %s" % name) return m if __name__=='__main__': D = Drawing() D.add(Marker()) D.save(fnRoot='Marker',formats=['pdf'], outDir='/tmp')
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/widgets/markers.py
0.869361
0.342819
markers.py
pypi
__version__='3.3.0' from reportlab.graphics.widgetbase import Widget from reportlab.graphics import shapes from reportlab.lib import colors from reportlab.lib.validators import * from reportlab.lib.attrmap import * from reportlab.graphics.shapes import Drawing class TableWidget(Widget): """A two dimensions table of labels """ _attrMap = AttrMap( x = AttrMapValue(isNumber, desc="x position of left edge of table"), y = AttrMapValue(isNumber, desc="y position of bottom edge of table"), width = AttrMapValue(isNumber, desc="table width"), height = AttrMapValue(isNumber, desc="table height"), borderStrokeColor = AttrMapValue(isColorOrNone, desc="table border color"), fillColor = AttrMapValue(isColorOrNone, desc="table fill color"), borderStrokeWidth = AttrMapValue(isNumber, desc="border line width"), horizontalDividerStrokeColor = AttrMapValue(isColorOrNone, desc="table inner horizontal lines color"), verticalDividerStrokeColor = AttrMapValue(isColorOrNone, desc="table inner vertical lines color"), horizontalDividerStrokeWidth = AttrMapValue(isNumber, desc="table inner horizontal lines width"), verticalDividerStrokeWidth = AttrMapValue(isNumber, desc="table inner vertical lines width"), dividerDashArray = AttrMapValue(isListOfNumbersOrNone, desc='Dash array for dividerLines.'), data = AttrMapValue(None, desc="a list of list of strings to be displayed in the cells"), boxAnchor = AttrMapValue(isBoxAnchor, desc="location of the table anchoring point"), fontName = AttrMapValue(isString, desc="text font in the table"), fontSize = AttrMapValue(isNumber, desc="font size of the table"), fontColor = AttrMapValue(isColorOrNone, desc="font color"), alignment = AttrMapValue(OneOf("left", "right"), desc="Alignment of text within cells"), textAnchor = AttrMapValue(OneOf('start','middle','end','numeric'), desc="Alignment of text within cells"), ) def __init__(self, x=10, y=10, **kw): self.x = x self.y = y self.width = 200 self.height = 100 self.borderStrokeColor = colors.black self.fillColor = None self.borderStrokeWidth = 0.5 self.horizontalDividerStrokeColor = colors.black self.verticalDividerStrokeColor = colors.black self.horizontalDividerStrokeWidth = 0.5 self.verticalDividerStrokeWidth = 0.25 self.dividerDashArray = None self.data = [['North','South','East','West'],[100,110,120,130],['A','B','C','D']] # list of rows each row is a list of columns self.boxAnchor = 'nw' #self.fontName = None self.fontSize = 8 self.fontColor = colors.black self.alignment = 'right' self.textAnchor = 'start' for k, v in kw.items(): if k in list(self.__class__._attrMap.keys()): setattr(self, k, v) else: raise ValueError('invalid argument supplied for class %s'%self.__class__) def demo(self): """ returns a sample of this widget with data """ d = Drawing(400, 200) t = TableWidget() d.add(t, name='table') d.table.dividerDashArray = (1, 3, 2) d.table.verticalDividerStrokeColor = None d.table.borderStrokeWidth = 0 d.table.borderStrokeColor = colors.red return d def draw(self): """ returns a group of shapes """ g = shapes.Group() #overall border and fill if self.borderStrokeColor or self.fillColor: # adds border and filling color rect = shapes.Rect(self.x, self.y, self.width, self.height) rect.fillColor = self.fillColor rect.strokeColor = self.borderStrokeColor rect.strokeWidth = self.borderStrokeWidth g.add(rect) #special case - for an empty table we want to avoid divide-by-zero data = self.preProcessData(self.data) rows = len(self.data) cols = len(self.data[0]) #print "(rows,cols)=(%s, %s)"%(rows,cols) row_step = self.height / float(rows) col_step = self.width / float(cols) #print "(row_step,col_step)=(%s, %s)"%(row_step,col_step) # draw the grid if self.horizontalDividerStrokeColor: for i in range(rows): # make horizontal lines x1 = self.x x2 = self.x + self.width y = self.y + row_step*i #print 'line (%s, %s), (%s, %s)'%(x1, y, x2, y) line = shapes.Line(x1, y, x2, y) line.strokeDashArray = self.dividerDashArray line.strokeWidth = self.horizontalDividerStrokeWidth line.strokeColor = self.horizontalDividerStrokeColor g.add(line) if self.verticalDividerStrokeColor: for i in range(cols): # make vertical lines x = self.x+col_step*i y1 = self.y y2 = self.y + self.height #print 'line (%s, %s), (%s, %s)'%(x, y1, x, y2) line = shapes.Line(x, y1, x, y2) line.strokeDashArray = self.dividerDashArray line.strokeWidth = self.verticalDividerStrokeWidth line.strokeColor = self.verticalDividerStrokeColor g.add(line) # since we plot data from down up, we reverse the list self.data.reverse() for (j, row) in enumerate(self.data): y = self.y + j*row_step + 0.5*row_step - 0.5 * self.fontSize for (i, datum) in enumerate(row): if datum: x = self.x + i*col_step + 0.5*col_step s = shapes.String(x, y, str(datum), textAnchor=self.textAnchor) s.fontName = self.fontName s.fontSize = self.fontSize s.fillColor = self.fontColor g.add(s) return g def preProcessData(self, data): """preprocess and return a new array with at least one row and column (use a None) if needed, and all rows the same length (adding Nones if needed) """ if not data: return [[None]] #make all rows have similar number of cells, append None when needed max_row = max( [len(x) for x in data] ) for rowNo, row in enumerate(data): if len(row) < max_row: row.extend([None]*(max_row-len(row))) return data #test if __name__ == '__main__': d = TableWidget().demo() import os d.save(formats=['pdf'],outDir=os.getcwd(),fnRoot=None)
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/widgets/table.py
0.5144
0.35883
table.py
pypi
from reportlab.lib import colors from reportlab.lib.validators import * from reportlab.lib.attrmap import * from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin, Group, Polygon from reportlab.graphics.widgetbase import Widget class AdjustableArrow(Widget): """This widget draws an arrow (style one). possible attributes: 'x', 'y', 'size', 'fillColor' """ _attrMap = AttrMap( x = AttrMapValue(isNumber,desc='symbol x coordinate'), y = AttrMapValue(isNumber,desc='symbol y coordinate'), dx = AttrMapValue(isNumber,desc='symbol x coordinate adjustment'), dy = AttrMapValue(isNumber,desc='symbol x coordinate adjustment'), stemThickness = AttrMapValue(isNumber, 'width of the stem'), stemLength = AttrMapValue(isNumber, 'length of the stem'), headProjection = AttrMapValue(isNumber, 'how much the head projects from the stem'), headLength = AttrMapValue(isNumber, 'length of the head'), headSweep = AttrMapValue(isNumber, 'howmuch the head sweeps back (-ve) or forwards (+ve)'), scale = AttrMapValue(isNumber, 'scaling factor'), fillColor = AttrMapValue(isColorOrNone), strokeColor = AttrMapValue(isColorOrNone), strokeWidth = AttrMapValue(isNumber), boxAnchor = AttrMapValue(isBoxAnchor,desc='anchoring point of the label'), right =AttrMapValue(isBoolean,desc='If True (default) the arrow is horizontal pointing right\nFalse means it points up'), angle = AttrMapValue(isNumber, desc='angle of arrow default (0), right True 0 is horizontal to right else vertical up'), ) def __init__(self,**kwds): self._setKeywords(**kwds) self._setKeywords(**dict( x = 0, y = 0, fillColor = colors.red, strokeWidth = 0, strokeColor = None, boxAnchor = 'c', angle = 0, stemThickness = 33, stemLength = 50, headProjection = 15, headLength = 50, headSweep = 0, scale = 1., right=True, )) def draw(self): # general widget bits g = Group() x = self.x y = self.y scale = self.scale stemThickness = self.stemThickness*scale stemLength = self.stemLength*scale headProjection = self.headProjection*scale headLength = self.headLength*scale headSweep = self.headSweep*scale w = stemLength+headLength h = 2*headProjection+stemThickness # shift to the boxAnchor boxAnchor = self.boxAnchor if self.right: if boxAnchor in ('sw','w','nw'): dy = -h elif boxAnchor in ('s','c','n'): dy = -h*0.5 else: dy = 0 if boxAnchor in ('w','c','e'): dx = -w*0.5 elif boxAnchor in ('nw','n','ne'): dx = -w else: dx = 0 points = [ dx, dy+headProjection+stemThickness, dx+stemLength, dy+headProjection+stemThickness, dx+stemLength+headSweep, dy+2*headProjection+stemThickness, dx+stemLength+headLength, dy+0.5*stemThickness+headProjection, dx+stemLength+headSweep, dy, dx+stemLength, dy+headProjection, dx, dy+headProjection, ] else: w,h = h,w if boxAnchor in ('nw','n','ne'): dy = -h elif boxAnchor in ('w','c','e'): dy = -h*0.5 else: dy = 0 if boxAnchor in ('ne','e','se'): dx = -w elif boxAnchor in ('n','c','s'): dx = -w*0.5 else: dx = 0 points = [ dx+headProjection, dy, #sw dx+headProjection+stemThickness, dy, #se dx+headProjection+stemThickness, dy+stemLength, dx+w, dy+stemLength+headSweep, dx+headProjection+0.5*stemThickness, dy+h, dx, dy+stemLength+headSweep, dx+headProjection, dy+stemLength, ] g.add(Polygon( points = points, fillColor = self.fillColor, strokeColor = self.strokeColor, strokeWidth = self.strokeWidth, )) g.translate(x,y) g.rotate(self.angle) return g class AdjustableArrowDrawing(_DrawingEditorMixin,Drawing): def __init__(self,width=100,height=63,*args,**kw): Drawing.__init__(self,width,height,*args,**kw) self._add(self,AdjustableArrow(),name='adjustableArrow',validate=None,desc=None)
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/graphics/widgets/adjustableArrow.py
0.506347
0.235757
adjustableArrow.py
pypi
__version__='3.4.34' __doc__='''Utility functions to position and resize boxes within boxes''' def rectCorner(x, y, width, height, anchor='sw', dims=False): '''given rectangle controlled by x,y width and height return the corner corresponding to the anchor''' if anchor not in ('nw','w','sw'): if anchor in ('n','c','s'): x += width/2. else: x += width if anchor not in ('sw','s','se'): if anchor in ('w','c','e'): y += height/2. else: y += height return (x,y,width,height) if dims else (x,y) def aspectRatioFix(preserve,anchor,x,y,width,height,imWidth,imHeight,anchorAtXY=False): """This function helps position an image within a box. It first normalizes for two cases: - if the width is None, it assumes imWidth - ditto for height - if width or height is negative, it adjusts x or y and makes them positive Given (a) the enclosing box (defined by x,y,width,height where x,y is the \ lower left corner) which you wish to position the image in, and (b) the image size (imWidth, imHeight), and (c) the 'anchor point' as a point of the compass - n,s,e,w,ne,se etc \ and c for centre, this should return the position at which the image should be drawn, as well as a scale factor indicating what scaling has happened. It returns the parameters which would be used to draw the image without any adjustments: x,y, width, height, scale used in canvas.drawImage and drawInlineImage """ scale = 1.0 if width is None: width = imWidth if height is None: height = imHeight if width<0: width = -width x -= width if height<0: height = -height y -= height if preserve: imWidth = abs(imWidth) imHeight = abs(imHeight) scale = min(width/float(imWidth),height/float(imHeight)) owidth = width oheight = height width = scale*imWidth-1e-8 height = scale*imHeight-1e-8 if not anchorAtXY: # if anchor not in ('nw','w','sw'): # dx = owidth-width # if anchor in ('n','c','s'): # x += dx/2. # else: # x += dx # if anchor not in ('sw','s','se'): # dy = oheight-height # if anchor in ('w','c','e'): # y += dy/2. # else: # y += dy x, y = rectCorner(x,y,owidth-width,oheight-height,anchor) if anchorAtXY: if anchor not in ('sw','s','se'): y -= height/2. if anchor in ('e','c','w') else height if anchor not in ('nw','w','sw'): x -= width/2. if anchor in ('n','c','s') else width return x,y, width, height, scale
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/lib/boxstuff.py
0.459076
0.482307
boxstuff.py
pypi
__version__='3.3.0' __doc__=""" Module to analyze Python source code; for syntax coloring tools. Interface:: tags = fontify(pytext, searchfrom, searchto) - The 'pytext' argument is a string containing Python source code. - The (optional) arguments 'searchfrom' and 'searchto' may contain a slice in pytext. - The returned value is a list of tuples, formatted like this:: [('keyword', 0, 6, None), ('keyword', 11, 17, None), ('comment', 23, 53, None), etc. ] - The tuple contents are always like this:: (tag, startindex, endindex, sublist) - tag is one of 'keyword', 'string', 'comment' or 'identifier' - sublist is not used, hence always None. """ # Based on FontText.py by Mitchell S. Chapman, # which was modified by Zachary Roadhouse, # then un-Tk'd by Just van Rossum. # Many thanks for regular expression debugging & authoring are due to: # Tim (the-incredib-ly y'rs) Peters and Cristian Tismer # So, who owns the copyright? ;-) How about this: # Copyright 1996-2001: # Mitchell S. Chapman, # Zachary Roadhouse, # Tim Peters, # Just van Rossum __version__ = "0.4" import re # First a little helper, since I don't like to repeat things. (Tismer speaking) def replace(src, sep, rep): return rep.join(src.split(sep)) # This list of keywords is taken from ref/node13.html of the # Python 1.3 HTML documentation. ("access" is intentionally omitted.) keywordsList = [ "as", "assert", "exec", "del", "from", "lambda", "return", "and", "elif", "global", "not", "try", "break", "else", "if", "or", "while", "class", "except", "import", "pass", "continue", "finally", "in", "print", "def", "for", "is", "raise", "yield", "with"] # Build up a regular expression which will match anything # interesting, including multi-line triple-quoted strings. commentPat = r"#[^\n]*" pat = r"q[^\\q\n]*(\\[\000-\377][^\\q\n]*)*q" quotePat = replace(pat, "q", "'") + "|" + replace(pat, 'q', '"') # Way to go, Tim! pat = r""" qqq [^\\q]* ( ( \\[\000-\377] | q ( \\[\000-\377] | [^\q] | q ( \\[\000-\377] | [^\\q] ) ) ) [^\\q]* )* qqq """ pat = ''.join(pat.split()) # get rid of whitespace tripleQuotePat = replace(pat, "q", "'") + "|" + replace(pat, 'q', '"') # Build up a regular expression which matches all and only # Python keywords. This will let us skip the uninteresting # identifier references. # nonKeyPat identifies characters which may legally precede # a keyword pattern. nonKeyPat = r"(^|[^a-zA-Z0-9_.\"'])" keyPat = nonKeyPat + "(" + "|".join(keywordsList) + ")" + nonKeyPat matchPat = commentPat + "|" + keyPat + "|" + tripleQuotePat + "|" + quotePat matchRE = re.compile(matchPat) idKeyPat = "[ \t]*[A-Za-z_][A-Za-z_0-9.]*" # Ident w. leading whitespace. idRE = re.compile(idKeyPat) def fontify(pytext, searchfrom = 0, searchto = None): if searchto is None: searchto = len(pytext) # Cache a few attributes for quicker reference. search = matchRE.search idSearch = idRE.search tags = [] tags_append = tags.append commentTag = 'comment' stringTag = 'string' keywordTag = 'keyword' identifierTag = 'identifier' start = 0 end = searchfrom while 1: m = search(pytext, end) if m is None: break # EXIT LOOP start = m.start() if start >= searchto: break # EXIT LOOP match = m.group(0) end = start + len(match) c = match[0] if c not in "#'\"": # Must have matched a keyword. if start != searchfrom: # there's still a redundant char before and after it, strip! match = match[1:-1] start = start + 1 else: # this is the first keyword in the text. # Only a space at the end. match = match[:-1] end = end - 1 tags_append((keywordTag, start, end, None)) # If this was a defining keyword, look ahead to the # following identifier. if match in ["def", "class"]: m = idSearch(pytext, end) if m is not None: start = m.start() if start == end: match = m.group(0) end = start + len(match) tags_append((identifierTag, start, end, None)) elif c == "#": tags_append((commentTag, start, end, None)) else: tags_append((stringTag, start, end, None)) return tags def test(path): f = open(path) text = f.read() f.close() tags = fontify(text) for tag, start, end, sublist in tags: print(tag, repr(text[start:end]))
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/lib/PyFontify.py
0.577495
0.361475
PyFontify.py
pypi
__version__='3.5.33' __doc__="""Standard verifying functions used by attrmap.""" import codecs, re from reportlab.lib.utils import isSeq, isBytes, isStr from reportlab.lib import colors try: _re_Pattern = re.Pattern except AttributeError: _re_Pattern = re._pattern_type class Percentage(float): pass class Validator: "base validator class" def __call__(self,x): return self.test(x) def __str__(self): return getattr(self,'_str',self.__class__.__name__) def normalize(self,x): return x def normalizeTest(self,x): try: self.normalize(x) return True except: return False class _isAnything(Validator): def test(self,x): return True class _isNothing(Validator): def test(self,x): return False class _isBoolean(Validator): def test(self,x): if isinstance(int,bool): return x in (0,1) return self.normalizeTest(x) def normalize(self,x): if x in (0,1): return x try: S = x.upper() except: raise ValueError('Must be boolean not %s' % ascii(s)) if S in ('YES','TRUE'): return True if S in ('NO','FALSE',None): return False raise ValueError('Must be boolean not %s' % ascii(s)) class _isString(Validator): def test(self,x): return isStr(x) class _isCodec(Validator): def test(self,x): if not isStr(x): return False try: a,b,c,d = codecs.lookup(x) return True except LookupError: return False class _isNumber(Validator): def test(self,x): if isinstance(x,(float,int)): return True return self.normalizeTest(x) def normalize(self,x): try: return float(x) except: return int(x) class _isInt(Validator): def test(self,x): if not isinstance(x,int) and not isStr(x): return False return self.normalizeTest(x) def normalize(self,x): return int(x.decode('utf8') if isBytes(x) else x) class _isNumberOrNone(_isNumber): def test(self,x): return x is None or isNumber(x) def normalize(self,x): if x is None: return x return _isNumber.normalize(x) class _isListOfNumbersOrNone(Validator): "ListOfNumbersOrNone validator class." def test(self, x): if x is None: return True return isListOfNumbers(x) class isNumberInRange(_isNumber): def __init__(self, min, max): self.min = min self.max = max def test(self, x): try: n = self.normalize(x) if self.min <= n <= self.max: return True except ValueError: pass return False class _isListOfShapes(Validator): "ListOfShapes validator class." def test(self, x): from reportlab.graphics.shapes import Shape if isSeq(x): answer = 1 for e in x: if not isinstance(e, Shape): answer = 0 return answer else: return False class _isListOfStringsOrNone(Validator): "ListOfStringsOrNone validator class." def test(self, x): if x is None: return True return isListOfStrings(x) class _isTransform(Validator): "Transform validator class." def test(self, x): if isSeq(x): if len(x) == 6: for element in x: if not isNumber(element): return False return True else: return False else: return False class _isColor(Validator): "Color validator class." def test(self, x): return isinstance(x, colors.Color) class _isColorOrNone(Validator): "ColorOrNone validator class." def test(self, x): if x is None: return True return isColor(x) from reportlab.lib.normalDate import NormalDate class _isNormalDate(Validator): def test(self,x): if isinstance(x,NormalDate): return True return x is not None and self.normalizeTest(x) def normalize(self,x): return NormalDate(x) class _isValidChild(Validator): "ValidChild validator class." def test(self, x): """Is this child allowed in a drawing or group? I.e. does it descend from Shape or UserNode? """ from reportlab.graphics.shapes import UserNode, Shape return isinstance(x, UserNode) or isinstance(x, Shape) class _isValidChildOrNone(_isValidChild): def test(self,x): return _isValidChild.test(self,x) or x is None class _isCallable(Validator): def test(self, x): return hasattr(x,'__call__') class OneOf(Validator): """Make validator functions for list of choices. Usage: f = reportlab.lib.validators.OneOf('happy','sad') or f = reportlab.lib.validators.OneOf(('happy','sad')) f('sad'),f('happy'), f('grumpy') (1,1,0) """ def __init__(self, enum,*args): if isSeq(enum): if args!=(): raise ValueError("Either all singleton args or a single sequence argument") self._enum = tuple(enum)+args else: self._enum = (enum,)+args self._patterns = tuple((_ for _ in self._enum if isinstance(_,_re_Pattern))) if self._patterns: self._enum = tuple((_ for _ in self._enum if not isinstance(_,_re_Pattern))) self.test = self._test_patterns def test(self, x): return x in self._enum def _test_patterns(self, x): v = x in self._enum #print(f'{x=} {self._enum=!r} {self._patterns=!r} {v=}') if v: return True for p in self._patterns: v = p.match(x) if v: return True return False class SequenceOf(Validator): def __init__(self,elemTest,name=None,emptyOK=1, NoneOK=0, lo=0,hi=0x7fffffff): self._elemTest = elemTest self._emptyOK = emptyOK self._NoneOK = NoneOK self._lo, self._hi = lo, hi if name: self._str = name def test(self, x): if not isSeq(x): if x is None: return self._NoneOK return False if x==[] or x==(): return self._emptyOK elif not self._lo<=len(x)<=self._hi: return False for e in x: if not self._elemTest(e): return False return True class EitherOr(Validator): def __init__(self,tests,name=None): if not isSeq(tests): tests = (tests,) self._tests = tests if name: self._str = name def test(self, x): for t in self._tests: if t(x): return True return False class NoneOr(EitherOr): def test(self, x): return x is None or super().test(x) class NotSetOr(EitherOr): _not_set = object() def test(self, x): return x is NotSetOr._not_set or super().test(x) @staticmethod def conditionalValue(v,a): return a if v is NotSetOr._not_set else v class _isNotSet(Validator): def test(self,x): return x is NotSetOr._not_set class Auto(Validator): def __init__(self,**kw): self.__dict__.update(kw) def test(self,x): return x is self.__class__ or isinstance(x,self.__class__) class AutoOr(EitherOr): def test(self,x): return isAuto(x) or super().test(x) class isInstanceOf(Validator): def __init__(self,klass=None): self._klass = klass def test(self,x): return isinstance(x,self._klass) class isSubclassOf(Validator): def __init__(self,klass=None): self._klass = klass def test(self,x): return issubclass(x,self._klass) class matchesPattern(Validator): """Matches value, or its string representation, against regex""" def __init__(self, pattern): self._pattern = re.compile(pattern) def test(self,x): x = str(x) print('testing %s against %s' % (x, self._pattern)) return (self._pattern.match(x) != None) class DerivedValue: """This is used for magic values which work themselves out. An example would be an "inherit" property, so that one can have drawing.chart.categoryAxis.labels.fontName = inherit and pick up the value from the top of the drawing. Validators will permit this provided that a value can be pulled in which satisfies it. And the renderer will have special knowledge of these so they can evaluate themselves. """ def getValue(self, renderer, attr): """Override this. The renderers will pass the renderer, and the attribute name. Algorithms can then backtrack up through all the stuff the renderer provides, including a correct stack of parent nodes.""" return None class Inherit(DerivedValue): def __repr__(self): return "inherit" def getValue(self, renderer, attr): return renderer.getStateValue(attr) inherit = Inherit() class NumericAlign(str): '''for creating the numeric string value for anchors etc etc dp is the character to align on (the last occurrence will be used) dpLen is the length of characters after the dp ''' def __new__(cls,dp='.',dpLen=0): self = str.__new__(cls,'numeric') self._dp=dp self._dpLen = dpLen return self isAuto = Auto() isBoolean = _isBoolean() isString = _isString() isCodec = _isCodec() isNumber = _isNumber() isInt = _isInt() isNoneOrInt = NoneOr(isInt,'isNoneOrInt') isNumberOrNone = _isNumberOrNone() isTextAnchor = OneOf('start','middle','end','boxauto') isListOfNumbers = SequenceOf(isNumber,'isListOfNumbers') isListOfNoneOrNumber = SequenceOf(isNumberOrNone,'isListOfNoneOrNumber') isListOfListOfNoneOrNumber = SequenceOf(isListOfNoneOrNumber,'isListOfListOfNoneOrNumber') isListOfNumbersOrNone = _isListOfNumbersOrNone() isListOfShapes = _isListOfShapes() isListOfStrings = SequenceOf(isString,'isListOfStrings') isListOfStringsOrNone = _isListOfStringsOrNone() isTransform = _isTransform() isColor = _isColor() isListOfColors = SequenceOf(isColor,'isListOfColors') isColorOrNone = _isColorOrNone() isShape = isValidChild = _isValidChild() isNoneOrShape = isValidChildOrNone = _isValidChildOrNone() isAnything = _isAnything() isNothing = _isNothing() isXYCoord = SequenceOf(isNumber,lo=2,hi=2,emptyOK=0) isBoxAnchor = OneOf('nw','n','ne','w','c','e','sw','s','se', 'autox', 'autoy') isNoneOrString = NoneOr(isString,'NoneOrString') isNoneOrListOfNoneOrStrings=SequenceOf(isNoneOrString,'isNoneOrListOfNoneOrStrings',NoneOK=1) isListOfNoneOrString=SequenceOf(isNoneOrString,'isListOfNoneOrString',NoneOK=0) isNoneOrListOfNoneOrNumbers=SequenceOf(isNumberOrNone,'isNoneOrListOfNoneOrNumbers',NoneOK=1) isCallable = _isCallable() isNoneOrCallable = NoneOr(isCallable) isStringOrCallable=EitherOr((isString,isCallable),'isStringOrCallable') isStringOrCallableOrNone=NoneOr(isStringOrCallable,'isStringOrCallableNone') isStringOrNone=NoneOr(isString,'isStringOrNone') isNormalDate=_isNormalDate() isNotSet=_isNotSet()
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/src/reportlab/lib/validators.py
0.518546
0.237068
validators.py
pypi
from tools.docco.rl_doc_utils import * #begin chapter oon paragraphs heading1("Paragraphs") disc(""" The $reportlab.platypus.Paragraph$ class is one of the most useful of the Platypus $Flowables$; it can format fairly arbitrary text and provides for inline font style and colour changes using an XML style markup. The overall shape of the formatted text can be justified, right or left ragged or centered. The XML markup can even be used to insert greek characters or to do subscripts. """) disc("""The following text creates an instance of the $Paragraph$ class:""") eg("""Paragraph(text, style, bulletText=None)""") disc("""The $text$ argument contains the text of the paragraph; excess white space is removed from the text at the ends and internally after linefeeds. This allows easy use of indented triple quoted text in <b>Python</b> scripts. The $bulletText$ argument provides the text of a default bullet for the paragraph. The font and other properties for the paragraph text and bullet are set using the style argument. """) disc(""" The $style$ argument should be an instance of class $ParagraphStyle$ obtained typically using""") eg(""" from reportlab.lib.styles import ParagraphStyle """) disc(""" this container class provides for the setting of multiple default paragraph attributes in a structured way. The styles are arranged in a dictionary style object called a $stylesheet$ which allows for the styles to be accessed as $stylesheet['BodyText']$. A sample style sheet is provided. """) eg(""" from reportlab.lib.styles import getSampleStyleSheet stylesheet=getSampleStyleSheet() normalStyle = stylesheet['Normal'] """) disc(""" The options which can be set for a $Paragraph$ can be seen from the $ParagraphStyle$ defaults. The values with leading underscore ('_') are derived from the defaults in module $reportlab.rl_config$ which are derived from module $reportlab.rl_settings$. """) heading4("$class ParagraphStyle$") eg(""" class ParagraphStyle(PropertySet): defaults = { 'fontName':_baseFontName, 'fontSize':10, 'leading':12, 'leftIndent':0, 'rightIndent':0, 'firstLineIndent':0, 'alignment':TA_LEFT, 'spaceBefore':0, 'spaceAfter':0, 'bulletFontName':_baseFontName, 'bulletFontSize':10, 'bulletIndent':0, 'textColor': black, 'backColor':None, 'wordWrap':None, 'borderWidth': 0, 'borderPadding': 0, 'borderColor': None, 'borderRadius': None, 'allowWidows': 1, 'allowOrphans': 0, 'textTransform':None, 'endDots':None, 'splitLongWords':1, 'underlineWidth': _baseUnderlineWidth, 'bulletAnchor': 'start', 'justifyLastLine': 0, 'justifyBreaks': 0, 'spaceShrinkage': _spaceShrinkage, 'strikeWidth': _baseStrikeWidth, #stroke width 'underlineOffset': _baseUnderlineOffset, #fraction of fontsize to offset underlines 'underlineGap': _baseUnderlineGap, #gap for double/triple underline 'strikeOffset': _baseStrikeOffset, #fraction of fontsize to offset strikethrough 'strikeGap': _baseStrikeGap, #gap for double/triple strike 'linkUnderline': _platypus_link_underline, #'underlineColor': None, #'strikeColor': None, 'hyphenationLang': _hyphenationLang, 'uriWasteReduce': _uriWasteReduce, 'embeddedHyphenation': _embeddedHyphenation, } """) heading2("Using Paragraph Styles") #this will be used in the ParaBox demos. sample = """You are hereby charged that on the 28th day of May, 1970, you did willfully, unlawfully, and with malice of forethought, publish an alleged English-Hungarian phrase book with intent to cause a breach of the peace. How do you plead?""" disc("""The $Paragraph$ and $ParagraphStyle$ classes together handle most common formatting needs. The following examples draw paragraphs in various styles, and add a bounding box so that you can see exactly what space is taken up.""") s1 = ParagraphStyle('Normal') parabox(sample, s1, 'The default $ParagraphStyle$') disc("""The two attributes $spaceBefore$ and $spaceAfter$ do what they say, except at the top or bottom of a frame. At the top of a frame, $spaceBefore$ is ignored, and at the bottom, $spaceAfter$ is ignored. This means that you could specify that a 'Heading2' style had two inches of space before when it occurs in mid-page, but will not get acres of whitespace at the top of a page. These two attributes should be thought of as 'requests' to the Frame and are not part of the space occupied by the Paragraph itself.""") disc("""The $fontSize$ and $fontName$ tags are obvious, but it is important to set the $leading$. This is the spacing between adjacent lines of text; a good rule of thumb is to make this 20% larger than the point size. To get double-spaced text, use a high $leading$. If you set $autoLeading$(default $"off"$) to $"min"$(use observed leading even if smaller than specified) or $"max"$(use the larger of observed and specified) then an attempt is made to determine the leading on a line by line basis. This may be useful if the lines contain different font sizes etc.""") disc("""The figure below shows space before and after and an increased leading:""") parabox(sample, ParagraphStyle('Spaced', spaceBefore=6, spaceAfter=6, leading=16), 'Space before and after and increased leading' ) disc("""The attribute $borderPadding$ adjusts the padding between the paragraph and the border of its background. This can either be a single value or a tuple containing 2 to 4 values. These values are applied the same way as in Cascading Style Sheets (CSS). If a single value is given, that value is applied to all four sides. If more than one value is given, they are applied in clockwise order to the sides starting at the top. If two or three values are given, the missing values are taken from the opposite side(s). Note that in the following example the yellow box is drawn by the paragraph itself.""") parabox(sample, ParagraphStyle('padded', borderPadding=(7, 2, 20), borderColor='#000000', borderWidth=1, backColor='#FFFF00'), 'Variable padding' ) disc("""The $leftIndent$ and $rightIndent$ attributes do exactly what you would expect; $firstLineIndent$ is added to the $leftIndent$ of the first line. If you want a straight left edge, remember to set $firstLineIndent$ equal to 0.""") parabox(sample, ParagraphStyle('indented', firstLineIndent=+24, leftIndent=24, rightIndent=24), 'one third inch indents at left and right, two thirds on first line' ) disc("""Setting $firstLineIndent$ equal to a negative number, $leftIndent$ much higher, and using a different font (we'll show you how later!) can give you a definition list:.""") parabox('<b><i>Judge Pickles: </i></b>' + sample, ParagraphStyle('dl', leftIndent=36), 'Definition Lists' ) disc("""There are four possible values of $alignment$, defined as constants in the module <i>reportlab.lib.enums</i>. These are TA_LEFT, TA_CENTER or TA_CENTRE, TA_RIGHT and TA_JUSTIFY, with values of 0, 1, 2 and 4 respectively. These do exactly what you would expect.""") disc("""Set $wordWrap$ to $'CJK'$ to get Asian language linewrapping. For normal western text you can change the way the line breaking algorithm handles <i>widows</i> and <i>orphans</i> with the $allowWidows$ and $allowOrphans$ values. Both should normally be set to $0$, but for historical reasons we have allowed <i>widows</i>. The default color of the text can be set with $textColor$ and the paragraph background colour can be set with $backColor$. The paragraph's border properties may be changed using $borderWidth$, $borderPadding$, $borderColor$ and $borderRadius$.""") disc("""The $textTransform$ attribute can be <b><i>None</i></b>, <i>'uppercase'</i> or <i>'lowercase'</i> to get the obvious result and <i>'capitalize'</i> to get initial letter capitalization.""") disc("""Attribute $endDots$ can be <b><i>None</i></b>, a string, or an object with attributes text and optional fontName, fontSize, textColor, backColor and dy(y offset) to specify trailing matter on the last line of left/right justified paragraphs.""") disc("""The $splitLongWords$ attribute can be set to a false value to avoid splitting very long words.""") disc("""Attribute $bulletAnchor$ can be <i>'start'</i>, <i>'middle'</i>, <i>'end'</i> or <i>'numeric'</i> to control where the bullet is anchored.""") disc("""The $justifyBreaks$ attribute controls whether lines deliberately broken with a $&lt;br/&gt;$ tag should be justified""") disc("""Attribute $spaceShrinkage$ is a fractional number specifiying by how much the space of a paragraph line may be shrunk in order to make it fit; typically it is something like 0.05""") disc("""The $underlineWidth$, $underlineOffset$, $underlineGap$ &amp; $underlineColor$ attributes control the underline behaviour when the $&lt;u&gt;$ or a linking tag is used. Those tags can have override values of these attributes. The attribute value for width &amp; offset is a $fraction * Letter$ where letter can be one of $P$, $L$, $f$ or $F$ representing fontSize proportions. $P$ uses the fontsize at the tag, $F$ is the maximum fontSize in the tag, $f$ is the initial fontsize inside the tag. $L$ means the global (paragrpah style) font size. $strikeWidth$, $strikeOffset$, $strikeGap$ &amp; $strikeColor$ attributes do the same for strikethrough lines. """) disc("""Attribute $linkUnderline$ controls whether link tags are automatically underlined.""") disc("""If the $pyphen$ python module is installed attribute $hyphenationLang$ controls which language will be used to hyphenate words without explicit embedded hyphens.""") disc("""If $embeddedHyphenation$ is set then attempts will be made to split words with embedded hyphens.""") disc("""Attribute $uriWasteReduce$ controls how we attempt to split long uri's. It is the fraction of a line that we regard as too much waste. The default in module $reportlab.rl_settings$ is <i>0.5</i> which means that we will try and split a word that looks like a uri if we would waste at least half of the line.""") disc("""Currently the hyphenation and uri splitting are turned off by default. You need to modify the default settings by using the file $~/.rl_settings$ or adding a module $reportlab_settings.py$ to the python path. Suitable values are""") eg(""" hyphenationLanguage='en_GB' embeddedHyphenation=1 uriWasteReduce=0.3 """) heading2("Paragraph XML Markup Tags") disc("""XML markup can be used to modify or specify the overall paragraph style, and also to specify intra- paragraph markup.""") heading3("The outermost &lt; para &gt; tag") disc(""" The paragraph text may optionally be surrounded by &lt;para attributes....&gt; &lt;/para&gt; tags. The attributes if any of the opening &lt;para&gt; tag affect the style that is used with the $Paragraph$ $text$ and/or $bulletText$. """) disc(" ") from reportlab.platypus.paraparser import _addAttributeNames, _paraAttrMap, _bulletAttrMap def getAttrs(A): _addAttributeNames(A) S={} for k, v in A.items(): a = v[0] if a not in S: S[a] = [k] else: S[a].append(k) K = list(sorted(S.keys())) K.sort() D=[('Attribute','Synonyms')] for k in K: D.append((k,", ".join(list(sorted(S[k]))))) cols=2*[None] rows=len(D)*[None] return D,cols,rows t=Table(*getAttrs(_paraAttrMap)) t.setStyle(TableStyle([ ('FONT',(0,0),(-1,1),'Times-Bold',10,12), ('FONT',(0,1),(-1,-1),'Courier',8,8), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ])) getStory().append(t) caption("""Table <seq template="%(Chapter)s-%(Table+)s"/> - Synonyms for style attributes""") disc("""Some useful synonyms have been provided for our Python attribute names, including lowercase versions, and the equivalent properties from the HTML standard where they exist. These additions make it much easier to build XML-printing applications, since much intra-paragraph markup may not need translating. The table below shows the allowed attributes and synonyms in the outermost paragraph tag.""") CPage(1) heading2("Intra-paragraph markup") disc("""<![CDATA[Within each paragraph, we use a basic set of XML tags to provide markup. The most basic of these are bold (<b>...</b>), italic (<i>...</i>) and underline (<u>...</u>). Other tags which are allowed are strong (<strong>...</strong>), and strike through (<strike>...</strike>). The <link> and <a> tags may be used to refer to URIs, documents or bookmarks in the current document. The a variant of the <a> tag can be used to mark a position in a document. A break (<br/>) tag is also allowed.]]> """) parabox2("""<b>You are hereby charged</b> that on the 28th day of May, 1970, you did willfully, unlawfully, and <i>with malice of forethought</i>, publish an alleged English-Hungarian phrase book with intent to cause a breach of the peace. <u>How do you plead</u>?""", "Simple bold and italic tags") parabox2("""This <a href="#MYANCHOR" color="blue">is a link to</a> an anchor tag ie <a name="MYANCHOR"/><font color="green">here</font>. This <link href="#MYANCHOR" color="blue" fontName="Helvetica">is another link to</link> the same anchor tag.""", "anchors and links") disc("""The <b>link</b> tag can be used as a reference, but not as an anchor. The a and link hyperlink tags have additional attributes <i>fontName</i>, <i>fontSize</i>, <i>color</i> &amp; <i>backColor</i> attributes. The hyperlink reference can have a scheme of <b>http:</b><i>(external webpage)</i>, <b>pdf:</b><i>(different pdf document)</i> or <b>document:</b><i>(same pdf document)</i>; a missing scheme is treated as <b>document</b> as is the case when the reference starts with # (in which case the anchor should omit it). Any other scheme is treated as some kind of URI. """) parabox2("""<strong>You are hereby charged</strong> that on the 28th day of May, 1970, you did willfully, unlawfully, <strike>and with malice of forethought</strike>, <br/>publish an alleged English-Hungarian phrase book with intent to cause a breach of the peace. How do you plead?""", "Strong, strike, and break tags") heading3("The $&lt;font&gt;$ tag") disc("""The $&lt;font&gt;$ tag can be used to change the font name, size and text color for any substring within the paragraph. Legal attributes are $size$, $face$, $name$ (which is the same as $face$), $color$, and $fg$ (which is the same as $color$). The $name$ is the font family name, without any 'bold' or 'italic' suffixes. Colors may be HTML color names or a hex string encoded in a variety of ways; see ^reportlab.lib.colors^ for the formats allowed.""") parabox2("""<font face="times" color="red">You are hereby charged</font> that on the 28th day of May, 1970, you did willfully, unlawfully, and <font size=14>with malice of forethought</font>, publish an alleged English-Hungarian phrase book with intent to cause a breach of the peace. How do you plead?""", "The $font$ tag") heading3("Superscripts and Subscripts") disc("""Superscripts and subscripts are supported with the <![CDATA[<super>/<sup> and <sub> tags, which work exactly as you might expect. Additionally these three tags have attributes rise and size to optionally set the rise/descent and font size for the superscript/subscript text. In addition, most greek letters can be accessed by using the <greek></greek> tag, or with mathML entity names.]]>""") ##parabox2("""<greek>epsilon</greek><super><greek>iota</greek> ##<greek>pi</greek></super> = -1""", "Greek letters and subscripts") parabox2("""Equation (&alpha;): <greek>e</greek> <super rise=9 size=6><greek>ip</greek></super> = -1""", "Greek letters and superscripts") heading3("Inline Images") disc("""We can embed images in a paragraph with the &lt;img/&gt; tag which has attributes $src$, $width$, $height$ whose meanings are obvious. The $valign$ attribute may be set to a css like value from "baseline", "sub", "super", "top", "text-top", "middle", "bottom", "text-bottom"; the value may also be a numeric percentage or an absolute value. """) parabox2("""<para autoLeading="off" fontSize=12>This &lt;img/&gt; <img src="../images/testimg.gif" valign="top"/> is aligned <b>top</b>.<br/><br/> This &lt;img/&gt; <img src="../images/testimg.gif" valign="bottom"/> is aligned <b>bottom</b>.<br/><br/> This &lt;img/&gt; <img src="../images/testimg.gif" valign="middle"/> is aligned <b>middle</b>.<br/><br/> This &lt;img/&gt; <img src="../images/testimg.gif" valign="-4"/> is aligned <b>-4</b>.<br/><br/> This &lt;img/&gt; <img src="../images/testimg.gif" valign="+4"/> is aligned <b>+4</b>.<br/><br/> This &lt;img/&gt; <img src="../images/testimg.gif" width="10"/> has width <b>10</b>.<br/><br/> </para>""","Inline images") disc("""The $src$ attribute can refer to a remote location eg $src="https://www.reportlab.com/images/logo.gif"$. By default we set $rl_config.trustedShemes$ to $['https','http', 'file', 'data', 'ftp']$ and $rl_config.trustedHosts=None$ the latter meaning no-restriction. You can modify these variables using one of the override files eg $reportlab_settings.py$ or $~/.reportlab_settings$. Or as comma separated strings in the environment variables $RL_trustedSchemes$ &amp; $RL_trustedHosts$. Note that the $trustedHosts$ values may contain <b>glob</b> wild cars so <i>*.reportlab.com</i> will match the obvious domains. <br/><span color="red"><b>*NB*</b></span> use of <i>trustedHosts</i> and or <i>trustedSchemes</i> may not control behaviour &amp; actions when $URI$ patterns are detected by the viewer application.""") heading3("The $&lt;u&gt;$ &amp; $&lt;strike&gt;$ tags") disc("""These tags can be used to carry out explicit underlineing or strikethroughs. These tags have attributes $width$, $offset$, $color$, $gap$ &amp; $kind$. The $kind$ attribute controls how many lines will be drawn (default $kind=1$) and when $kind>1$ the $gap$ attribute controls the disatnce between lines.""") heading3("The $&lt;nobr&gt;$ tag") disc("""If hyphenation is in operation the $&lt;nobr&gt;$ tag suppresses it so $&lt;nobr&gt;averylongwordthatwontbebroken&lt;/nobr&gt;$ won't be broken.""") heading3("Numbering Paragraphs and Lists") disc("""The $&lt;seq&gt;$ tag provides comprehensive support for numbering lists, chapter headings and so on. It acts as an interface to the $Sequencer$ class in ^reportlab.lib.sequencer^. These are used to number headings and figures throughout this document. You may create as many separate 'counters' as you wish, accessed with the $id$ attribute; these will be incremented by one each time they are accessed. The $seqreset$ tag resets a counter. If you want it to resume from a number other than 1, use the syntax &lt;seqreset id="mycounter" base="42"&gt;. Let's have a go:""") parabox2("""<seq id="spam"/>, <seq id="spam"/>, <seq id="spam"/>. Reset<seqreset id="spam"/>. <seq id="spam"/>, <seq id="spam"/>, <seq id="spam"/>.""", "Basic sequences") disc("""You can save specifying an ID by designating a counter ID as the <i>default</i> using the &lt;seqdefault id="Counter"&gt; tag; it will then be used whenever a counter ID is not specified. This saves some typing, especially when doing multi-level lists; you just change counter ID when stepping in or out a level.""") parabox2("""<seqdefault id="spam"/>Continued... <seq/>, <seq/>, <seq/>, <seq/>, <seq/>, <seq/>, <seq/>.""", "The default sequence") disc("""Finally, one can access multi-level sequences using a variation of Python string formatting and the $template$ attribute in a &lt;seq&gt; tags. This is used to do the captions in all of the figures, as well as the level two headings. The substring $%(counter)s$ extracts the current value of a counter without incrementing it; appending a plus sign as in $%(counter)s$ increments the counter. The figure captions use a pattern like the one below:""") parabox2("""Figure <seq template="%(Chapter)s-%(FigureNo+)s"/> - Multi-level templates""", "Multi-level templates") disc("""We cheated a little - the real document used 'Figure', but the text above uses 'FigureNo' - otherwise we would have messed up our numbering!""") heading2("Bullets and Paragraph Numbering") disc("""In addition to the three indent properties, some other parameters are needed to correctly handle bulleted and numbered lists. We discuss this here because you have now seen how to handle numbering. A paragraph may have an optional ^bulletText^ argument passed to its constructor; alternatively, bullet text may be placed in a $<![CDATA[<bullet>..</bullet>]]>$ tag at its head. This text will be drawn on the first line of the paragraph, with its x origin determined by the $bulletIndent$ attribute of the style, and in the font given in the $bulletFontName$ attribute. The "bullet" may be a single character such as (doh!) a bullet, or a fragment of text such as a number in some numbering sequence, or even a short title as used in a definition list. Fonts may offer various bullet characters but we suggest first trying the Unicode bullet ($&bull;$), which may be written as $&amp;bull;$, $&amp;#x2022;$ or (in utf8) $\\xe2\\x80\\xa2$):""") t=Table(*getAttrs(_bulletAttrMap)) t.setStyle([ ('FONT',(0,0),(-1,1),'Times-Bold',10,12), ('FONT',(0,1),(-1,-1),'Courier',8,8), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ]) getStory().append(t) caption("""Table <seq template="%(Chapter)s-%(Table+)s"/> - &lt;bullet&gt; attributes &amp; synonyms""") disc("""The &lt;bullet&gt; tag is only allowed once in a given paragraph and its use overrides the implied bullet style and ^bulletText^ specified in the ^Paragraph^ creation. """) parabox("""<bullet>&bull;</bullet>this is a bullet point. Spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam """, styleSheet['Bullet'], 'Basic use of bullet points') disc("""Exactly the same technique is used for numbers, except that a sequence tag is used. It is also possible to put a multi-character string in the bullet; with a deep indent and bold bullet font, you can make a compact definition list.""")
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/docs/userguide/ch5_paragraphs.py
0.651577
0.467089
ch5_paragraphs.py
pypi
from tools.docco.rl_doc_utils import * Appendix1("ReportLab Demos") disc("""In the subdirectories of $reportlab/demos$ there are a number of working examples showing almost all aspects of reportlab in use.""") heading2("""Odyssey""") disc(""" The three scripts odyssey.py, dodyssey.py and fodyssey.py all take the file odyssey.txt and produce PDF documents. The included odyssey.txt is short; a longer and more testing version can be found at ftp://ftp.reportlab.com/odyssey.full.zip. """) eg(""" Windows cd reportlab\\demos\\odyssey python odyssey.py start odyssey.pdf Linux cd reportlab/demos/odyssey python odyssey.py acrord odyssey.pdf """) disc("""Simple formatting is shown by the odyssey.py script. It runs quite fast, but all it does is gather the text and force it onto the canvas pages. It does no paragraph manipulation at all so you get to see the XML &lt; &amp; &gt; tags. """) disc("""The scripts fodyssey.py and dodyssey.py handle paragraph formatting so you get to see colour changes etc. Both scripts use the document template class and the dodyssey.py script shows the ability to do dual column layout and uses multiple page templates. """) heading2("""Standard Fonts and Colors""") disc("""In $reportlab/demos/stdfonts$ the script stdfonts.py can be used to illustrate ReportLab's standard fonts. Run the script using""") eg(""" cd reportlab\\demos\\stdfonts python stdfonts.py """) disc(""" to produce two PDF documents, StandardFonts_MacRoman.pdf &amp; StandardFonts_WinAnsi.pdf which show the two most common built in font encodings. """) disc("""The colortest.py script in $reportlab/demos/colors$ demonstrates the different ways in which reportlab can set up and use colors.""") disc("""Try running the script and viewing the output document, colortest.pdf. This shows different color spaces and a large selection of the colors which are named in the $reportlab.lib.colors$ module. """) heading2("""Py2pdf""") disc("""Dinu Gherman contributed this useful script which uses reportlab to produce nicely colorized PDF documents from Python scripts including bookmarks for classes, methods and functions. To get a nice version of the main script try""") eg(""" cd reportlab/demos/py2pdf python py2pdf.py py2pdf.py acrord py2pdf.pdf """) disc("""i.e. we used py2pdf to produce a nice version of py2pdf.py in the document with the same rootname and a .pdf extension. """) disc(""" The py2pdf.py script has many options which are beyond the scope of this simple introduction; consult the comments at the start of the script. """) heading2("Gadflypaper") disc(""" The Python script, gfe.py, in $reportlab/demos/gadflypaper$ uses an inline style of document preparation. The script almost entirely produced by Aaron Watters produces a document describing Aaron's $gadfly$ in memory database for Python. To generate the document use """) eg(""" cd reportlab\\gadflypaper python gfe.py start gfe.pdf """) disc(""" everything in the PDF document was produced by the script which is why this is an inline style of document production. So, to produce a header followed by some text the script uses functions $header$ and $p$ which take some text and append to a global story list. """) eg(''' header("Conclusion") p("""The revamped query engine design in Gadfly 2 supports .......... and integration.""") ''') heading2("""Pythonpoint""") disc("""Andy Robinson has refined the pythonpoint.py script (in $reportlab\\demos\\pythonpoint$) until it is a really useful script. It takes an input file containing an XML markup and uses an xmllib style parser to map the tags into PDF slides. When run in its own directory pythonpoint.py takes as a default input the file pythonpoint.xml and produces pythonpoint.pdf which is documentation for Pythonpoint! You can also see it in action with an older paper """) eg(""" cd reportlab\\demos\\pythonpoint python pythonpoint.py monterey.xml start monterey.pdf """) disc(""" Not only is pythonpoint self documenting, but it also demonstrates reportlab and PDF. It uses many features of reportlab (document templates, tables etc). Exotic features of PDF such as fadeins and bookmarks are also shown to good effect. The use of an XML document can be contrasted with the <i>inline</i> style of the gadflypaper demo; the content is completely separate from the formatting """)
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/docs/userguide/app_demos.py
0.613121
0.332825
app_demos.py
pypi
__version__='3.3.0' from tools.docco.rl_doc_utils import * from reportlab.graphics.shapes import * from reportlab.graphics.widgets import signsandsymbols heading2("Widgets") disc(""" We now describe widgets and how they relate to shapes. Using many examples it is shown how widgets make reusable graphics components. """) heading3("Shapes vs. Widgets") disc("""Up until now, Drawings have been 'pure data'. There is no code in them to actually do anything, except assist the programmer in checking and inspecting the drawing. In fact, that's the cornerstone of the whole concept and is what lets us achieve portability - a renderer only needs to implement the primitive shapes.""") disc("""We want to build reusable graphic objects, including a powerful chart library. To do this we need to reuse more tangible things than rectangles and circles. We should be able to write objects for other to reuse - arrows, gears, text boxes, UML diagram nodes, even fully fledged charts.""") disc(""" The Widget standard is a standard built on top of the shapes module. Anyone can write new widgets, and we can build up libraries of them. Widgets support the $getProperties()$ and $setProperties()$ methods, so you can inspect and modify as well as document them in a uniform way. """) bullet("A widget is a reusable shape ") bullet("""it can be initialized with no arguments when its $draw()$ method is called it creates a primitive Shape or a Group to represent itself""") bullet("""It can have any parameters you want, and they can drive the way it is drawn""") bullet("""it has a $demo()$ method which should return an attractively drawn example of itself in a 200x100 rectangle. This is the cornerstone of the automatic documentation tools. The $demo()$ method should also have a well written docstring, since that is printed too!""") disc("""Widgets run contrary to the idea that a drawing is just a bundle of shapes; surely they have their own code? The way they work is that a widget can convert itself to a group of primitive shapes. If some of its components are themselves widgets, they will get converted too. This happens automatically during rendering; the renderer will not see your chart widget, but just a collection of rectangles, lines and strings. You can also explicitly 'flatten out' a drawing, causing all widgets to be converted to primitives.""") heading3("Using a Widget") disc(""" Let's imagine a simple new widget. We will use a widget to draw a face, then show how it was implemented.""") eg(""" >>> from reportlab.lib import colors >>> from reportlab.graphics import shapes >>> from reportlab.graphics import widgetbase >>> from reportlab.graphics import renderPDF >>> d = shapes.Drawing(200, 100) >>> f = widgetbase.Face() >>> f.skinColor = colors.yellow >>> f.mood = "sad" >>> d.add(f) >>> renderPDF.drawToFile(d, 'face.pdf', 'A Face') """) from reportlab.graphics import widgetbase d = Drawing(200, 120) f = widgetbase.Face() f.x = 50 f.y = 10 f.skinColor = colors.yellow f.mood = "sad" d.add(f) draw(d, 'A sample widget') disc(""" Let's see what properties it has available, using the $setProperties()$ method we have seen earlier: """) eg(""" >>> f.dumpProperties() eyeColor = Color(0.00,0.00,1.00) mood = sad size = 80 skinColor = Color(1.00,1.00,0.00) x = 10 y = 10 >>> """) disc(""" One thing which seems strange about the above code is that we did not set the size or position when we made the face. This is a necessary trade-off to allow a uniform interface for constructing widgets and documenting them - they cannot require arguments in their $__init__()$ method. Instead, they are generally designed to fit in a 200 x 100 window, and you move or resize them by setting properties such as x, y, width and so on after creation. """) disc(""" In addition, a widget always provides a $demo()$ method. Simple ones like this always do something sensible before setting properties, but more complex ones like a chart would not have any data to plot. The documentation tool calls $demo()$ so that your fancy new chart class can create a drawing showing what it can do. """) disc(""" Here are a handful of simple widgets available in the module <i>signsandsymbols.py</i>: """) from reportlab.graphics.shapes import Drawing from reportlab.graphics.widgets import signsandsymbols d = Drawing(230, 230) ne = signsandsymbols.NoEntry() ds = signsandsymbols.DangerSign() fd = signsandsymbols.FloppyDisk() ns = signsandsymbols.NoSmoking() ne.x, ne.y = 10, 10 ds.x, ds.y = 120, 10 fd.x, fd.y = 10, 120 ns.x, ns.y = 120, 120 d.add(ne) d.add(ds) d.add(fd) d.add(ns) draw(d, 'A few samples from signsandsymbols.py') disc(""" And this is the code needed to generate them as seen in the drawing above: """) eg(""" from reportlab.graphics.shapes import Drawing from reportlab.graphics.widgets import signsandsymbols d = Drawing(230, 230) ne = signsandsymbols.NoEntry() ds = signsandsymbols.DangerSign() fd = signsandsymbols.FloppyDisk() ns = signsandsymbols.NoSmoking() ne.x, ne.y = 10, 10 ds.x, ds.y = 120, 10 fd.x, fd.y = 10, 120 ns.x, ns.y = 120, 120 d.add(ne) d.add(ds) d.add(fd) d.add(ns) """) heading3("Compound Widgets") disc("""Let's imagine a compound widget which draws two faces side by side. This is easy to build when you have the Face widget.""") eg(""" >>> tf = widgetbase.TwoFaces() >>> tf.faceOne.mood 'happy' >>> tf.faceTwo.mood 'sad' >>> tf.dumpProperties() faceOne.eyeColor = Color(0.00,0.00,1.00) faceOne.mood = happy faceOne.size = 80 faceOne.skinColor = None faceOne.x = 10 faceOne.y = 10 faceTwo.eyeColor = Color(0.00,0.00,1.00) faceTwo.mood = sad faceTwo.size = 80 faceTwo.skinColor = None faceTwo.x = 100 faceTwo.y = 10 >>> """) disc("""The attributes 'faceOne' and 'faceTwo' are deliberately exposed so you can get at them directly. There could also be top-level attributes, but there aren't in this case.""") heading3("Verifying Widgets") disc("""The widget designer decides the policy on verification, but by default they work like shapes - checking every assignment - if the designer has provided the checking information.""") heading3("Implementing Widgets") disc("""We tried to make it as easy to implement widgets as possible. Here's the code for a Face widget which does not do any type checking:""") eg(""" class Face(Widget): \"\"\"This draws a face with two eyes, mouth and nose.\"\"\" def __init__(self): self.x = 10 self.y = 10 self.size = 80 self.skinColor = None self.eyeColor = colors.blue self.mood = 'happy' def draw(self): s = self.size # abbreviate as we will use this a lot g = shapes.Group() g.transform = [1,0,0,1,self.x, self.y] # background g.add(shapes.Circle(s * 0.5, s * 0.5, s * 0.5, fillColor=self.skinColor)) # CODE OMITTED TO MAKE MORE SHAPES return g """) disc("""We left out all the code to draw the shapes in this document, but you can find it in the distribution in $widgetbase.py$.""") disc("""By default, any attribute without a leading underscore is returned by setProperties. This is a deliberate policy to encourage consistent coding conventions.""") disc("""Once your widget works, you probably want to add support for verification. This involves adding a dictionary to the class called $_verifyMap$, which map from attribute names to 'checking functions'. The $widgetbase.py$ module defines a bunch of checking functions with names like $isNumber$, $isListOfShapes$ and so on. You can also simply use $None$, which means that the attribute must be present but can have any type. And you can and should write your own checking functions. We want to restrict the "mood" custom attribute to the values "happy", "sad" or "ok". So we do this:""") eg(""" class Face(Widget): \"\"\"This draws a face with two eyes. It exposes a couple of properties to configure itself and hides all other details\"\"\" def checkMood(moodName): return (moodName in ('happy','sad','ok')) _verifyMap = { 'x': shapes.isNumber, 'y': shapes.isNumber, 'size': shapes.isNumber, 'skinColor':shapes.isColorOrNone, 'eyeColor': shapes.isColorOrNone, 'mood': checkMood } """) disc("""This checking will be performed on every attribute assignment; or, if $config.shapeChecking$ is off, whenever you call $myFace.verify()$.""") heading3("Documenting Widgets") disc(""" We are working on a generic tool to document any Python package or module; this is already checked into ReportLab and will be used to generate a reference for the ReportLab package. When it encounters widgets, it adds extra sections to the manual including:""") bullet("the doc string for your widget class ") bullet("the code snippet from your <i>demo()</i> method, so people can see how to use it") bullet("the drawing produced by the <i>demo()</i> method ") bullet("the property dump for the widget in the drawing. ") disc(""" This tool will mean that we can have guaranteed up-to-date documentation on our widgets and charts, both on the web site and in print; and that you can do the same for your own widgets, too! """) heading3("Widget Design Strategies") disc("""We could not come up with a consistent architecture for designing widgets, so we are leaving that problem to the authors! If you do not like the default verification strategy, or the way $setProperties/getProperties$ works, you can override them yourself.""") disc("""For simple widgets it is recommended that you do what we did above: select non-overlapping properties, initialize every property on $__init__$ and construct everything when $draw()$ is called. You can instead have $__setattr__$ hooks and have things updated when certain attributes are set. Consider a pie chart. If you want to expose the individual slices, you might write code like this:""") eg(""" from reportlab.graphics.charts import piecharts pc = piecharts.Pie() pc.defaultColors = [navy, blue, skyblue] #used in rotation pc.data = [10,30,50,25] pc.slices[7].strokeWidth = 5 """) #removed 'pc.backColor = yellow' from above code example disc("""The last line is problematic as we have only created four slices - in fact we might not have created them yet. Does $pc.slices[7]$ raise an error? Is it a prescription for what should happen if a seventh wedge is defined, used to override the default settings? We dump this problem squarely on the widget author for now, and recommend that you get a simple one working before exposing 'child objects' whose existence depends on other properties' values :-)""") disc("""We also discussed rules by which parent widgets could pass properties to their children. There seems to be a general desire for a global way to say that 'all slices get their lineWidth from the lineWidth of their parent' without a lot of repetitive coding. We do not have a universal solution, so again leave that to widget authors. We hope people will experiment with push-down, pull-down and pattern-matching approaches and come up with something nice. In the meantime, we certainly can write monolithic chart widgets which work like the ones in, say, Visual Basic and Delphi.""") disc("""For now have a look at the following sample code using an early version of a pie chart widget and the output it generates:""") eg(""" from reportlab.lib.colors import * from reportlab.graphics import shapes,renderPDF from reportlab.graphics.charts.piecharts import Pie d = Drawing(400,200) d.add(String(100,175,"Without labels", textAnchor="middle")) d.add(String(300,175,"With labels", textAnchor="middle")) pc = Pie() pc.x = 25 pc.y = 50 pc.data = [10,20,30,40,50,60] pc.slices[0].popout = 5 d.add(pc, 'pie1') pc2 = Pie() pc2.x = 150 pc2.y = 50 pc2.data = [10,20,30,40,50,60] pc2.labels = ['a','b','c','d','e','f'] d.add(pc2, 'pie2') pc3 = Pie() pc3.x = 275 pc3.y = 50 pc3.data = [10,20,30,40,50,60] pc3.labels = ['a','b','c','d','e','f'] pc3.slices.labelRadius = 0.65 pc3.slices.fontName = "Helvetica-Bold" pc3.slices.fontSize = 16 pc3.slices.fontColor = colors.yellow d.add(pc3, 'pie3') """) # Hack to force a new paragraph before the todo() :-( disc("") from reportlab.lib.colors import * from reportlab.graphics import shapes,renderPDF from reportlab.graphics.charts.piecharts import Pie d = Drawing(400,200) d.add(String(100,175,"Without labels", textAnchor="middle")) d.add(String(300,175,"With labels", textAnchor="middle")) pc = Pie() pc.x = 25 pc.y = 50 pc.data = [10,20,30,40,50,60] pc.slices[0].popout = 5 d.add(pc, 'pie1') pc2 = Pie() pc2.x = 150 pc2.y = 50 pc2.data = [10,20,30,40,50,60] pc2.labels = ['a','b','c','d','e','f'] d.add(pc2, 'pie2') pc3 = Pie() pc3.x = 275 pc3.y = 50 pc3.data = [10,20,30,40,50,60] pc3.labels = ['a','b','c','d','e','f'] pc3.slices.labelRadius = 0.65 pc3.slices.fontName = "Helvetica-Bold" pc3.slices.fontSize = 16 pc3.slices.fontColor = colors.yellow d.add(pc3, 'pie3') draw(d, 'Some sample Pies')
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/docs/userguide/graph_widgets.py
0.767603
0.555978
graph_widgets.py
pypi
from tools.docco.rl_doc_utils import * heading1("Writing your own $Flowable$ Objects") disc(""" Flowables are intended to be an open standard for creating reusable report content, and you can easily create your own objects. We hope that over time we will build up a library of contributions, giving reportlab users a rich selection of charts, graphics and other "report widgets" they can use in their own reports. This section shows you how to create your own flowables.""") todo("""we should put the Figure class in the standard library, as it is a very useful base.""") heading2("A very simple $Flowable$") disc(""" Recall the $hand$ function from the $pdfgen$ section of this user guide which generated a drawing of a hand as a closed figure composed from Bezier curves. """) illust(examples.hand, "a hand") disc(""" To embed this or any other drawing in a Platypus flowable we must define a subclass of $Flowable$ with at least a $wrap$ method and a $draw$ method. """) eg(examples.testhandannotation) disc(""" The $wrap$ method must provide the size of the drawing -- it is used by the Platypus mainloop to decide whether this element fits in the space remaining on the current frame. The $draw$ method performs the drawing of the object after the Platypus mainloop has translated the $(0,0)$ origin to an appropriate location in an appropriate frame. """) disc(""" Below are some example uses of the $HandAnnotation$ flowable. """) from reportlab.lib.colors import blue, pink, yellow, cyan, brown from reportlab.lib.units import inch handnote() disc("""The default.""") handnote(size=inch) disc("""Just one inch high.""") handnote(xoffset=3*inch, size=inch, strokecolor=blue, fillcolor=cyan) disc("""One inch high and shifted to the left with blue and cyan.""") heading2("Modifying a Built in $Flowable$") disc("""To modify an existing flowable, you should create a derived class and override the methods you need to change to get the desired behaviour""") disc("""As an example to create a rotated image you need to override the wrap and draw methods of the existing Image class""") import os from reportlab.platypus import * I = '../images/replogo.gif' EmbeddedCode(""" class RotatedImage(Image): def wrap(self,availWidth,availHeight): h, w = Image.wrap(self,availHeight,availWidth) return w, h def draw(self): self.canv.rotate(90) Image.draw(self) I = RotatedImage('%s') I.hAlign = 'CENTER' """ % I,'I')
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/docs/userguide/ch7_custom.py
0.63114
0.513851
ch7_custom.py
pypi
from tools.docco.rl_doc_utils import * heading1("Exposing PDF Special Capabilities") disc("""PDF provides a number of features to make electronic document viewing more efficient and comfortable, and our library exposes a number of these.""") heading2("Forms") disc("""The Form feature lets you create a block of graphics and text once near the start of a PDF file, and then simply refer to it on subsequent pages. If you are dealing with a run of 5000 repetitive business forms - for example, one-page invoices or payslips - you only need to store the backdrop once and simply draw the changing text on each page. Used correctly, forms can dramatically cut file size and production time, and apparently even speed things up on the printer. """) disc("""Forms do not need to refer to a whole page; anything which might be repeated often should be placed in a form.""") disc("""The example below shows the basic sequence used. A real program would probably define the forms up front and refer to them from another location.""") eg(examples.testforms) heading2("Links and Destinations") disc("""PDF supports internal hyperlinks. There is a very wide range of link types, destination types and events which can be triggered by a click. At the moment we just support the basic ability to jump from one part of a document to another, and to control the zoom level of the window after the jump. The bookmarkPage method defines a destination that is the endpoint of a jump.""") #todo("code example here...") eg(""" canvas.bookmarkPage(name, fit="Fit", left=None, top=None, bottom=None, right=None, zoom=None ) """) disc(""" By default the $bookmarkPage$ method defines the page itself as the destination. After jumping to an endpoint defined by bookmarkPage, the PDF browser will display the whole page, scaling it to fit the screen:""") eg("""canvas.bookmarkPage(name)""") disc("""The $bookmarkPage$ method can be instructed to display the page in a number of different ways by providing a $fit$ parameter.""") eg("") t = Table([ ['fit','Parameters Required','Meaning'], ['Fit',None,'Entire page fits in window (the default)'], ['FitH','top','Top coord at top of window, width scaled to fit'], ['FitV','left','Left coord at left of window, height scaled to fit'], ['FitR','left bottom right top','Scale window to fit the specified rectangle'], ['XYZ','left top zoom','Fine grained control. If you omit a parameter\nthe PDF browser interprets it as "leave as is"'] ]) t.setStyle(TableStyle([ ('FONT',(0,0),(-1,1),'Times-Bold',10,12), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ])) getStory().append(t) caption("""Table <seq template="%(Chapter)s-%(Table+)s"/> - Required attributes for different fit types""") disc(""" Note : $fit$ settings are case-sensitive so $fit="FIT"$ is invalid """) disc(""" Sometimes you want the destination of a jump to be some part of a page. The $FitR$ fit allows you to identify a particular rectangle, scaling the area to fit the entire page. """) disc(""" To set the display to a particular x and y coordinate of the page and to control the zoom directly use fit="XYZ". """) eg(""" canvas.bookmarkPage('my_bookmark',fit="XYZ",left=0,top=200) """) disc(""" This destination is at the leftmost of the page with the top of the screen at position 200. Because $zoom$ was not set the zoom remains at whatever the user had it set to. """) eg(""" canvas.bookmarkPage('my_bookmark',fit="XYZ",left=0,top=200,zoom=2) """) disc("""This time zoom is set to expand the page 2X its normal size.""") disc(""" Note : Both $XYZ$ and $FitR$ fit types require that their positional parameters ($top, bottom, left, right$) be specified in terms of the default user space. They ignore any geometric transform in effect in the canvas graphic state. """) pencilnote() disc(""" <i>Note:</i> Two previous bookmark methods are supported but deprecated now that bookmarkPage is so general. These are $bookmarkHorizontalAbsolute$ and $bookmarkHorizontal$. """) heading3("Defining internal links") eg(""" canvas.linkAbsolute(contents, destinationname, Rect=None, addtopage=1, name=None, thickness=0, color=None, dashArray=None, **kw) """) disc(""" The $linkAbsolute$ method defines a starting point for a jump. When the user is browsing the generated document using a dynamic viewer (such as Acrobat Reader) when the mouse is clicked when the pointer is within the rectangle specified by $Rect$ the viewer will jump to the endpoint associated with $destinationname$. As in the case with $bookmarkHorizontalAbsolute$ the rectangle $Rect$ must be specified in terms of the default user space. The $contents$ parameter specifies a chunk of text which displays in the viewer if the user left-clicks on the region. """) disc(""" The rectangle $Rect$ must be specified in terms of a tuple ^(x1,y1,x2,y2)^ identifying the lower left and upper right points of the rectangle in default user space. """) disc(""" For example the code """) eg(""" canvas.bookmarkPage("Meaning_of_life") """) disc(""" defines a location as the whole of the current page with the identifier $Meaning_of_life$. To create a rectangular link to it while drawing a possibly different page, we would use this code: """) eg(""" canvas.linkAbsolute("Find the Meaning of Life", "Meaning_of_life", (inch, inch, 6*inch, 2*inch)) """) disc(""" By default during interactive viewing a rectangle appears around the link. Use the keyword argument $Border='[0 0 0]'$ to suppress the visible rectangle around the during viewing link. For example """) eg(""" canvas.linkAbsolute("Meaning of Life", "Meaning_of_life", (inch, inch, 6*inch, 2*inch), Border='[0 0 0]') """) disc("""The $thickness$, $color$ and $dashArray$ arguments may be used alternately to specify a border if no Border argument is specified. If Border is specified it must be either a string representation of a PDF array or a $PDFArray$ (see the pdfdoc module). The $color$ argument (which should be a $Color$ instance) is equivalent to a keyword argument $C$ which should resolve to a PDF color definition (Normally a three entry PDF array). """) disc("""The $canvas.linkRect$ method is similar in intent to the $linkAbsolute$ method, but has an extra argument $relative=1$ so is intended to obey the local userspace transformation.""") heading2("Outline Trees") disc("""Acrobat Reader has a navigation page which can hold a document outline; it should normally be visible when you open this guide. We provide some simple methods to add outline entries. Typically, a program to make a document (such as this user guide) will call the method $canvas.addOutlineEntry(^self, title, key, level=0, closed=None^)$ as it reaches each heading in the document. """) disc("""^title^ is the caption which will be displayed in the left pane. The ^key^ must be a string which is unique within the document and which names a bookmark, as with the hyperlinks. The ^level^ is zero - the uppermost level - unless otherwise specified, and it is an error to go down more than one level at a time (for example to follow a level 0 heading by a level 2 heading). Finally, the ^closed^ argument specifies whether the node in the outline pane is closed or opened by default.""") disc("""The snippet below is taken from the document template that formats this user guide. A central processor looks at each paragraph in turn, and makes a new outline entry when a new chapter occurs, taking the chapter heading text as the caption text. The key is obtained from the chapter number (not shown here), so Chapter 2 has the key 'ch2'. The bookmark to which the outline entry points aims at the whole page, but it could as easily have been an individual paragraph. """) eg(""" #abridged code from our document template if paragraph.style == 'Heading1': self.chapter = paragraph.getPlainText() key = 'ch%d' % self.chapterNo self.canv.bookmarkPage(key) self.canv.addOutlineEntry(paragraph.getPlainText(), key, 0, 0) """) heading2("Page Transition Effects") eg(""" canvas.setPageTransition(self, effectname=None, duration=1, direction=0,dimension='H',motion='I') """) disc(""" The $setPageTransition$ method specifies how one page will be replaced with the next. By setting the page transition effect to "dissolve" for example the current page will appear to melt away when it is replaced by the next page during interactive viewing. These effects are useful in spicing up slide presentations, among other places. Please see the reference manual for more detail on how to use this method. """) heading2("Internal File Annotations") eg(""" canvas.setAuthor(name) canvas.setTitle(title) canvas.setSubject(subj) """) disc(""" These methods have no automatically seen visible effect on the document. They add internal annotations to the document. These annotations can be viewed using the "Document Info" menu item of the browser and they also can be used as a simple standard way of providing basic information about the document to archiving software which need not parse the entire file. To find the annotations view the $*.pdf$ output file using a standard text editor (such as $notepad$ on MS/Windows or $vi$ or $emacs$ on unix) and look for the string $/Author$ in the file contents. """) eg(examples.testannotations) disc(""" If you want the subject, title, and author to automatically display in the document when viewed and printed you must paint them onto the document like any other text. """) illust(examples.annotations, "Setting document internal annotations") heading2("Encryption") heading3("About encrypting PDF files") disc(""" Adobe's PDF standard allows you to do three related things to a PDF file when you encrypt it: """) bullet("""Apply password protection to it, so a user must supply a valid password before being able to read it, """) bullet("""Encrypt the contents of the file to make it useless until it is decrypted, and """) bullet("""Control whether the user can print, copy and paste or modify the document while viewing it. """) disc(""" The PDF security handler allows two different passwords to be specified for a document: """) bullet("""The 'owner' password (aka the 'security password' or 'master password') """) bullet("""The 'user' password (aka the 'open password') """) disc(""" When a user supplies either one of these passwords, the PDF file will be opened, decrypted and displayed on screen. """) disc(""" If the owner password is supplied, then the file is opened with full control - you can do anything to it, including changing the security settings and passwords, or re-encrypting it with a new password. """) disc(""" If the user password was the one that was supplied, you open it up in a more restricted mode. The restrictions were put in place when the file was encrypted, and will either allow or deny the user permission to do the following: """) bullet(""" Modifying the document's contents """) bullet(""" Copying text and graphics from the document """) bullet(""" Adding or modifying text annotations and interactive form fields """) bullet(""" Printing the document """) disc(""" Note that all password protected PDF files are encrypted, but not all encrypted PDFs are password protected. If a document's user password is an empty string, there will be no prompt for the password when the file is opened. If you only secure a document with the owner password, there will also not be a prompt for the password when you open the file. If the owner and user passwords are set to the same string when encrypting the PDF file, the document will always open with the user access privileges. This means that it is possible to create a file which, for example, is impossible for anyone to print out, even the person who created it. """) t = Table([ ['Owner Password \nset?','User Password \nset?','Result'], ['Y','-','No password required when opening file. \nRestrictions apply to everyone.'], ['-','Y','User password required when opening file. \nRestrictions apply to everyone.'], ['Y','Y','A password required when opening file. \nRestrictions apply only if user password supplied.'], ],[90, 90, 260]) t.setStyle(TableStyle([ ('FONT',(0,0),(-1,0),'Times-Bold',10,12), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ])) getStory().append(t) disc(""" When a PDF file is encrypted, encryption is applied to all the strings and streams in the file. This prevents people who don't have the password from simply removing the password from the PDF file to gain access to it - it renders the file useless unless you actually have the password. """) disc(""" PDF's standard encryption methods use the MD5 message digest algorithm (as described in RFC 1321, The MD5 Message-Digest Algorithm) and an encryption algorithm known as RC4. RC4 is a symmetric stream cipher - the same algorithm is used both for encryption and decryption, and the algorithm does not change the length of the data. """) heading3("How To Use Encryption") disc(""" Documents can be encrypted by passing an argument to the canvas object. """) disc(""" If the argument is a string object, it is used as the User password to the PDF. """) disc(""" The argument can also be an instance of the class $reportlab.lib.pdfencrypt.StandardEncryption$, which allows more finegrained control over encryption settings. """) disc(""" The $StandardEncryption$ constructor takes the following arguments: """) eg(""" def __init__(self, userPassword, ownerPassword=None, canPrint=1, canModify=1, canCopy=1, canAnnotate=1, strength=40): """) disc(""" The $userPassword$ and $ownerPassword$ parameters set the relevant password on the encrypted PDF. """) disc(""" The boolean flags $canPrint$, $canModify$, $canCopy$, $canAnnotate$ determine wether a user can perform the corresponding actions on the PDF when only a user password has been supplied. """) disc(""" If the user supplies the owner password while opening the PDF, all actions can be performed regardless of the flags. """) heading3("Example") disc(""" To create a document named hello.pdf with a user password of 'rptlab' on which printing is not allowed, use the following code: """) eg(""" from reportlab.pdfgen import canvas from reportlab.lib import pdfencrypt enc=pdfencrypt.StandardEncryption("rptlab",canPrint=0) def hello(c): c.drawString(100,100,"Hello World") c = canvas.Canvas("hello.pdf",encrypt=enc) hello(c) c.showPage() c.save() """) heading2("Interactive Forms") heading3("Overview of Interactive Forms") disc("""The PDF standard allows for various kinds of interactive elements, the ReportLab toolkit currently supports only a fraction of the possibilities and should be considered a work in progress. At present we allow choices with <i>checkbox</i>, <i>radio</i>, <i>choice</i> &amp; <i>listbox</i> widgets; text values can be entered with a <i>textfield</i> widget. All the widgets are created by calling methods on the <i>canvas.acroform</i> property.""" ) heading3("Example") disc("This shows the basic mechanism of creating an interactive element on the current page.") eg(""" canvas.acroform.checkbox( name='CB0', tooltip='Field CB0', checked=True, x=72,y=72+4*36, buttonStyle='diamond', borderStyle='bevelled', borderWidth=2, borderColor=red, fillColor=green, textColor=blue, forceBorder=True) """) alStyle=TableStyle([ ('SPAN',(0,0),(-1,0)), ('FONT',(0,0),(-1,0),'Helvetica-Bold',10,12), ('FONT',(0,1),(-1,1),'Helvetica-BoldOblique',8,9.6), ('FONT',(0,2),(0,-1),'Helvetica-Bold',7,8.4), ('FONT',(1,2),(1,-1),'Helvetica',7,8.4), ('FONT',(2,2),(2,-1),'Helvetica-Oblique',7,8.4), ('ALIGN',(0,0),(-1,0),'CENTER'), ('ALIGN',(1,1),(1,1),'CENTER'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ]) disc("""<b>NB</b> note that the <i>acroform</i> canvas property is created automatically on demand and that there is only one form allowd in a document.""") heading3("Checkbox Usage") disc("""The <i>canvas.acroform.checkbox</i> method creates a <i>checkbox</i> widget on the current page. The value of the checkbox is either <b>YES</b> or <b>OFF</b>. The arguments are""") t = Table([ ['canvas.acroform.checkbox parameters','',''], ['Parameter','Meaning','Default'], ["name","the parameter's name","None"], ["x","the horizontal position on the page (absolute coordinates)","0"], ["y","the vertical position on the page (absolute coordinates)","0"], ["size","The outline dimensions size x size","20"], ["checked","if True the checkbox is initially checked","False"], ["buttonStyle","the checkbox style (see below)","'check'"], ["shape","The outline of the widget (see below)","'square'"], ["fillColor","colour to be used to fill the widget","None"], ["textColor","the colour of the symbol or text","None"], ["borderWidth","as it says","1"], ["borderColor","the widget's border colour","None"], ["borderStyle","The border style name","'solid'"], ["tooltip","The text to display when hovering over the widget","None"], ["annotationFlags","blank separated string of annotation flags","'print'"], ["fieldFlags","Blank separated field flags (see below)","'required'"], ["forceBorder","when true a border force a border to be drawn","False"], ["relative","if true obey the current canvas transform","False"], ["dashLen ","the dashline to be used if the borderStyle=='dashed'","3"], ],[90, 260, 90],style=alStyle,repeatRows=2) getStory().append(t) heading3("Radio Usage") disc("""The <i>canvas.acroform.radio</i> method creates a <i>radio</i> widget on the current page. The value of the radio is the value of the radio group's selected value or <b>OFF</b> if none are selected. The arguments are""") t = Table([ ['canvas.acroform.radio parameters','',''], ['Parameter','Meaning','Default'], ["name","the radio's group (ie parameter) name","None"], ["value","the radio's group name","None"], ["x","the horizontal position on the page (absolute coordinates)","0"], ["y","the vertical position on the page (absolute coordinates)","0"], ["size","The outline dimensions size x size","20"], ["selected","if True this radio is the selected one in its group","False"], ["buttonStyle","the checkbox style (see below)","'check'"], ["shape","The outline of the widget (see below)","'square'"], ["fillColor","colour to be used to fill the widget","None"], ["textColor","the colour of the symbol or text","None"], ["borderWidth","as it says","1"], ["borderColor","the widget's border colour","None"], ["borderStyle","The border style name","'solid'"], ["tooltip","The text to display when hovering over the widget","None"], ["annotationFlags","blank separated string of annotation flags","'print'"], ["fieldFlags","Blank separated field flags (see below)","'noToggleToOff required radio'"], ["forceBorder","when true a border force a border to be drawn","False"], ["relative","if true obey the current canvas transform","False"], ["dashLen ","the dashline to be used if the borderStyle=='dashed'","3"], ],[90, 260, 90],style=alStyle,repeatRows=2) getStory().append(t) heading3("Listbox Usage") disc("""The <i>canvas.acroform.listbox</i> method creates a <i>listbox</i> widget on the current page. The listbox contains a list of options one or more of which (depending on fieldFlags) may be selected. """) t = Table([ ['canvas.acroform.listbox parameters','',''], ['Parameter','Meaning','Default'], ["name","the radio's group (ie parameter) name","None"], ["options","List or tuple of avaiable options","[]"], ["value","Singleton or list of strings of selected options","[]"], ["x","the horizontal position on the page (absolute coordinates)","0"], ["y","the vertical position on the page (absolute coordinates)","0"], ["width","The widget width","120"], ["height","The widget height","36"], ["fontName","The name of the type 1 font to be used","'Helvetica'"], ["fontSize","The size of font to be used","12"], ["fillColor","colour to be used to fill the widget","None"], ["textColor","the colour of the symbol or text","None"], ["borderWidth","as it says","1"], ["borderColor","the widget's border colour","None"], ["borderStyle","The border style name","'solid'"], ["tooltip","The text to display when hovering over the widget","None"], ["annotationFlags","blank separated string of annotation flags","'print'"], ["fieldFlags","Blank separated field flags (see below)","''"], ["forceBorder","when true a border force a border to be drawn","False"], ["relative","if true obey the current canvas transform","False"], ["dashLen ","the dashline to be used if the borderStyle=='dashed'","3"], ],[90, 260, 90],style=alStyle,repeatRows=2) getStory().append(t) heading3("Choice Usage") disc("""The <i>canvas.acroform.choice</i> method creates a <i>dropdown</i> widget on the current page. The dropdown contains a list of options one or more of which (depending on fieldFlags) may be selected. If you add <i>edit</i> to the <i>fieldFlags</i> then the result may be edited. """) t = Table([ ['canvas.acroform.choice parameters','',''], ['Parameter','Meaning','Default'], ["name","the radio's group (ie parameter) name","None"], ["options","List or tuple of avaiable options","[]"], ["value","Singleton or list of strings of selected options","[]"], ["x","the horizontal position on the page (absolute coordinates)","0"], ["y","the vertical position on the page (absolute coordinates)","0"], ["width","The widget width","120"], ["height","The widget height","36"], ["fontName","The name of the type 1 font to be used","'Helvetica'"], ["fontSize","The size of font to be used","12"], ["fillColor","colour to be used to fill the widget","None"], ["textColor","the colour of the symbol or text","None"], ["borderWidth","as it says","1"], ["borderColor","the widget's border colour","None"], ["borderStyle","The border style name","'solid'"], ["tooltip","The text to display when hovering over the widget","None"], ["annotationFlags","blank separated string of annotation flags","'print'"], ["fieldFlags","Blank separated field flags (see below)","'combo'"], ["forceBorder","when true a border force a border to be drawn","False"], ["relative","if true obey the current canvas transform","False"], ["dashLen ","the dashline to be used if the borderStyle=='dashed'","3"], ["maxlen ","None or maximum length of the widget value","None"], ],[90, 260, 90],style=alStyle,repeatRows=2) getStory().append(t) heading3("Textfield Usage") disc("""The <i>canvas.acroform.textfield</i> method creates a <i>textfield</i> entry widget on the current page. The textfield may be edited to change tha value of the widget """) t = Table([ ['canvas.acroform.textfield parameters','',''], ['Parameter','Meaning','Default'], ["name","the radio's group (ie parameter) name","None"], ["value","Value of the text field","''"], ["maxlen ","None or maximum length of the widget value","100"], ["x","the horizontal position on the page (absolute coordinates)","0"], ["y","the vertical position on the page (absolute coordinates)","0"], ["width","The widget width","120"], ["height","The widget height","36"], ["fontName","The name of the type 1 font to be used","'Helvetica'"], ["fontSize","The size of font to be used","12"], ["fillColor","colour to be used to fill the widget","None"], ["textColor","the colour of the symbol or text","None"], ["borderWidth","as it says","1"], ["borderColor","the widget's border colour","None"], ["borderStyle","The border style name","'solid'"], ["tooltip","The text to display when hovering over the widget","None"], ["annotationFlags","blank separated string of annotation flags","'print'"], ["fieldFlags","Blank separated field flags (see below)","''"], ["forceBorder","when true a border force a border to be drawn","False"], ["relative","if true obey the current canvas transform","False"], ["dashLen ","the dashline to be used if the borderStyle=='dashed'","3"], ],[90, 260, 90],style=alStyle,repeatRows=2) getStory().append(t) heading3("Button styles") disc("""The button style argument indicates what style of symbol should appear in the button when it is selected. There are several choices""") eg(""" check cross circle star diamond """) disc("""note that the document renderer can make some of these symbols wrong for their intended application. Acrobat reader prefers to use its own rendering on top of what the specification says should be shown (especially when the forms hihlighting features are used""") heading3("Widget shape") disc("""The shape argument describes how the outline of the checkbox or radio widget should appear you can use""") eg(""" circle square """) disc("""The renderer may make its own decisions about how the widget should look; so Acrobat Reader prefers circular outlines for radios.""") heading3("Border style") disc("""The borderStyle argument changes the 3D appearance of the widget on the page alternatives are""") eg(""" solid dashed inset bevelled underlined """) heading3("fieldFlags Argument") disc("""The fieldFlags arguments can be an integer or a string containing blank separate tokens the values are shown in the table below. For more information consult the PDF specification.""") t = Table([ ['Field Flag Tokens and values','',''], ['Token','Meaning','Value'], ["readOnly","The widget is read only","1<<0"], ["required","the widget is required","1<<1"], ["noExport","don't export the widget value","1<<2"], ["noToggleToOff","radios one only must be on","1<<14"], ["radio","added by the radio method","1<<15"], ["pushButton","if the button is a push button","1<<16"], ["radiosInUnison","radios with the same value toggle together","1<<25"], ["multiline","for multiline text widget","1<<12"], ["password","password textfield","1<<13"], ["fileSelect","file selection widget","1<<20"], #1.4 ["doNotSpellCheck","as it says","1<<22"], #1.4 ["doNotScroll","text fields do not scroll","1<<23"], #1.4 ["comb","make a comb style text based on the maxlen value","1<<24"], #1.5 ["richText","if rich text is used","1<<25"], #1.5 ["combo","for choice fields","1<<17"], ["edit","if the choice is editable","1<<18"], ["sort","if the values should be sorted","1<<19"], ["multiSelect","if the choice allows multi-select","1<<21"], #1.4 ["commitOnSelChange","not used by reportlab","1<<26"], #1.5 ],[90, 260, 90],style=alStyle,repeatRows=2) getStory().append(t) heading3("annotationFlags Argument") disc("""PDF widgets are annotations and have annotation properties these are shown in the table below""") t = Table([ ['Annotation Flag Tokens and values','',''], ['Token','Meaning','Value'], ["invisible","The widget is not shown","1<<0"], ["hidden","The widget is hidden","1<<1"], ["print","The widget will print","1<<2"], ["nozoom","The annotation will notscale with the rendered page","1<<3"], ["norotate","The widget won't rotate with the page","1<<4"], ["noview","Don't render the widget","1<<5"], ["readonly","Widget cannot be interacted with","1<<6"], ["locked","The widget cannot be changed","1<<7"], #1.4 ["togglenoview","Teh widget may be viewed after some events","1<<8"], #1.9 ["lockedcontents","The contents of the widget are fixed","1<<9"], #1.7 ],[90, 260, 90],style=alStyle) getStory().append(t)
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/docs/userguide/ch3_pdffeatures.py
0.632389
0.535281
ch3_pdffeatures.py
pypi
from tools.docco.rl_doc_utils import * #####################################################################################################3 heading1("PLATYPUS - Page Layout and Typography Using Scripts") heading2("Design Goals") disc(""" Platypus stands for &quot;Page Layout and Typography Using Scripts&quot;. It is a high level page layout library which lets you programmatically create complex documents with a minimum of effort. """) disc(""" The design of Platypus seeks to separate "high level" layout decisions from the document content as much as possible. Thus, for example, paragraphs are constructed using paragraph styles and pages are constructed using page templates with the intention that hundreds of documents with thousands of pages can be reformatted to different style specifications with the modifications of a few lines in a single shared file which contains the paragraph styles and page layout specifications. """) disc(""" The overall design of Platypus can be thought of has having several layers, top down, these are""") disc("<b>$DocTemplates$</b> the outermost container for the document;") disc("<b>$PageTemplates$</b> specifications for layouts of pages of various kinds;") disc("<b>$Frames$</b> specifications of regions in pages that can contain flowing text or graphics.") disc("""<b>$Flowables$</b> text or graphic elements that should be "flowed into the document (i.e. things like images, paragraphs and tables, but not things like page footers or fixed page graphics).""") disc("""<b>$pdfgen.Canvas$</b> the lowest level which ultimately receives the painting of the document from the other layers.""") illust(examples.doctemplateillustration, "Illustration of DocTemplate structure") disc(""" The illustration above graphically illustrates the concepts of $DocTemplates$, $PageTemplates$ and $Flowables$. It is deceptive, however, because each of the $PageTemplates$ actually may specify the format for any number of pages (not just one as might be inferred from the diagram). """) disc(""" $DocTemplates$ contain one or more $PageTemplates$ each of which contain one or more $Frames$. $Flowables$ are things which can be <i>flowed</i> into a $Frame$ e.g. a $Paragraph$ or a $Table$. """) disc(""" To use platypus you create a document from a $DocTemplate$ class and pass a list of $Flowable$s to its $build$ method. The document $build$ method knows how to process the list of flowables into something reasonable. """) disc(""" Internally the $DocTemplate$ class implements page layout and formatting using various events. Each of the events has a corresponding handler method called $handle_XXX$ where $XXX$ is the event name. A typical event is $frameBegin$ which occurs when the machinery begins to use a frame for the first time. """) disc(""" A Platypus story consists of a sequence of basic elements called $Flowables$ and these elements drive the data driven Platypus formatting engine. To modify the behavior of the engine a special kind of flowable, $ActionFlowables$, tell the layout engine to, for example, skip to the next column or change to another $PageTemplate$. """) heading2("""Getting started""") disc("""Consider the following code sequence which provides a very simple "hello world" example for Platypus.""") eg(examples.platypussetup) disc("""First we import some constructors, some paragraph styles and other conveniences from other modules.""") eg(examples.platypusfirstpage) disc("""We define the fixed features of the first page of the document with the function above.""") eg(examples.platypusnextpage) disc("""Since we want pages after the first to look different from the first we define an alternate layout for the fixed features of the other pages. Note that the two functions above use the $pdfgen$ level canvas operations to paint the annotations for the pages. """) eg(examples.platypusgo) disc(""" Finally, we create a story and build the document. Note that we are using a "canned" document template here which comes pre-built with page templates. We are also using a pre-built paragraph style. We are only using two types of flowables here -- $Spacers$ and $Paragraphs$. The first $Spacer$ ensures that the Paragraphs skip past the title string. """) disc(""" To see the output of this example program run the module $tools/docco/examples.py$ (from the ReportLab $source$ distribution) as a "top level script". The script interpretation $python examples.py$ will generate the Platypus output $phello.pdf$. """) heading2("$Flowables$") disc(""" $Flowables$ are things which can be drawn and which have $wrap$, $draw$ and perhaps $split$ methods. $Flowable$ is an abstract base class for things to be drawn and an instance knows its size and draws in its own coordinate system (this requires the base API to provide an absolute coordinate system when the $Flowable.draw$ method is called). To get an instance use $f=Flowable()$. """) disc(""" It should be noted that the $Flowable$ class is an <i>abstract</i> class and is normally only used as a base class. """) k=startKeep() disc(""" To illustrate the general way in which $Flowables$ are used we show how a derived class $Paragraph$ is used and drawn on a canvas. $Paragraphs$ are so important they will get a whole chapter to themselves. """) eg(""" from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import Paragraph from reportlab.pdfgen.canvas import Canvas styleSheet = getSampleStyleSheet() style = styleSheet['BodyText'] P=Paragraph('This is a very silly example',style) canv = Canvas('doc.pdf') aW = 460 # available width and height aH = 800 w,h = P.wrap(aW, aH) # find required space if w<=aW and h<=aH: P.drawOn(canv,0,aH) aH = aH - h # reduce the available height canv.save() else: raise ValueError, "Not enough room" """) endKeep(k) heading3("$Flowable$ User Methods") eg(""" Flowable.draw() """) disc("""This will be called to ask the flowable to actually render itself. The $Flowable$ class does not implement $draw$. The calling code should ensure that the flowable has an attribute $canv$ which is the $pdfgen.Canvas$ which should be drawn to an that the $Canvas$ is in an appropriate state (as regards translations rotations, etc). Normally this method will only be called internally by the $drawOn$ method. Derived classes must implement this method. """) eg(""" Flowable.drawOn(canvas,x,y) """) disc(""" This is the method which controlling programs use to render the flowable to a particular canvas. It handles the translation to the canvas coordinate (<i>x</i>,<i>y</i>) and ensuring that the flowable has a $canv$ attribute so that the $draw$ method (which is not implemented in the base class) can render in an absolute coordinate frame. """) eg(""" Flowable.wrap(availWidth, availHeight) """) disc("""This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.""") eg(""" Flowable.split(self, availWidth, availheight): """) disc("""This will be called by more sophisticated frames when wrap fails. Stupid flowables should return [] meaning that they are unable to split. Clever flowables should split themselves and return a list of flowables. It is up to the client code to ensure that repeated attempts to split are avoided. If the space is sufficient the split method should return [self]. Otherwise the flowable should rearrange itself and return a list $[f0,...]$ of flowables which will be considered in order. The implemented split method should avoid changing $self$ as this will allow sophisticated layout mechanisms to do multiple passes over a list of flowables. """) heading2("Guidelines for flowable positioning") disc("""Two methods, which by default return zero, provide guidance on vertical spacing of flowables: """) eg(""" Flowable.getSpaceAfter(self): Flowable.getSpaceBefore(self): """) disc("""These methods return how much space should follow or precede the flowable. The space doesn't belong to the flowable itself i.e. the flowable's $draw$ method shouldn't consider it when rendering. Controlling programs will use the values returned in determining how much space is required by a particular flowable in context. """) disc("""All flowables have an $hAlign$ property: $('LEFT', 'RIGHT', 'CENTER' or 'CENTRE')$. For paragraphs, which fill the full width of the frame, this has no effect. For tables, images or other objects which are less than the width of the frame, this determines their horizontal placement. """) disc("""The chapters which follow will cover the most important specific types of flowables: Paragraphs and Tables.""") heading2("Frames") disc(""" $Frames$ are active containers which are themselves contained in $PageTemplates$. $Frames$ have a location and size and maintain a concept of remaining drawable space. The command """) eg(""" Frame(x1, y1, width,height, leftPadding=6, bottomPadding=6, rightPadding=6, topPadding=6, id=None, showBoundary=0) """) disc("""creates a $Frame$ instance with lower left hand corner at coordinate $(x1,y1)$ (relative to the canvas at use time) and with dimensions $width$ x $height$. The $Padding$ arguments are positive quantities used to reduce the space available for drawing. The $id$ argument is an identifier for use at runtime e.g. 'LeftColumn' or 'RightColumn' etc. If the $showBoundary$ argument is non-zero then the boundary of the frame will get drawn at run time (this is useful sometimes). """) heading3("$Frame$ User Methods") eg(""" Frame.addFromList(drawlist, canvas) """) disc("""consumes $Flowables$ from the front of $drawlist$ until the frame is full. If it cannot fit one object, raises an exception.""") eg(""" Frame.split(flowable,canv) """) disc('''Asks the flowable to split using up the available space and return the list of flowables. ''') eg(""" Frame.drawBoundary(canvas) """) disc("draws the frame boundary as a rectangle (primarily for debugging).") heading3("Using $Frames$") disc(""" $Frames$ can be used directly with canvases and flowables to create documents. The $Frame.addFromList$ method handles the $wrap$ &amp; $drawOn$ calls for you. You don't need all of the Platypus machinery to get something useful into PDF. """) eg(""" from reportlab.pdfgen.canvas import Canvas from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.units import inch from reportlab.platypus import Paragraph, Frame styles = getSampleStyleSheet() styleN = styles['Normal'] styleH = styles['Heading1'] story = [] #add some flowables story.append(Paragraph("This is a Heading",styleH)) story.append(Paragraph("This is a paragraph in <i>Normal</i> style.", styleN)) c = Canvas('mydoc.pdf') f = Frame(inch, inch, 6*inch, 9*inch, showBoundary=1) f.addFromList(story,c) c.save() """) heading2("Documents and Templates") disc(""" The $BaseDocTemplate$ class implements the basic machinery for document formatting. An instance of the class contains a list of one or more $PageTemplates$ that can be used to describe the layout of information on a single page. The $build$ method can be used to process a list of $Flowables$ to produce a <b>PDF</b> document. """) CPage(3.0) heading3("The $BaseDocTemplate$ class") eg(""" BaseDocTemplate(self, filename, pagesize=defaultPageSize, pageTemplates=[], showBoundary=0, leftMargin=inch, rightMargin=inch, topMargin=inch, bottomMargin=inch, allowSplitting=1, title=None, author=None, _pageBreakQuick=1, encrypt=None) """) disc(""" creates a document template suitable for creating a basic document. It comes with quite a lot of internal machinery, but no default page templates. The required $filename$ can be a string, the name of a file to receive the created <b>PDF</b> document; alternatively it can be an object which has a $write$ method such as a $BytesIO$ or $file$ or $socket$. """) disc(""" The allowed arguments should be self explanatory, but $showBoundary$ controls whether or not $Frame$ boundaries are drawn which can be useful for debugging purposes. The $allowSplitting$ argument determines whether the builtin methods should try to <i>split</i> individual $Flowables$ across $Frames$. The $_pageBreakQuick$ argument determines whether an attempt to do a page break should try to end all the frames on the page or not, before ending the page. The encrypt argument determines wether or not and how the document is encrypted. By default, the document is not encrypted. If $encrypt$ is a string object, it is used as the user password for the pdf. If $encrypt$ is an instance of $reportlab.lib.pdfencrypt.StandardEncryption$, this object is used to encrypt the pdf. This allows more finegrained control over the encryption settings. """) heading4("User $BaseDocTemplate$ Methods") disc("""These are of direct interest to client programmers in that they are normally expected to be used. """) eg(""" BaseDocTemplate.addPageTemplates(self,pageTemplates) """) disc(""" This method is used to add one or a list of $PageTemplates$ to an existing documents. """) eg(""" BaseDocTemplate.build(self, flowables, filename=None, canvasmaker=canvas.Canvas) """) disc(""" This is the main method which is of interest to the application programmer. Assuming that the document instance is correctly set up the $build$ method takes the <i>story</i> in the shape of the list of flowables (the $flowables$ argument) and loops through the list forcing the flowables one at a time through the formatting machinery. Effectively this causes the $BaseDocTemplate$ instance to issue calls to the instance $handle_XXX$ methods to process the various events. """) heading4("User Virtual $BaseDocTemplate$ Methods") disc(""" These have no semantics at all in the base class. They are intended as pure virtual hooks into the layout machinery. Creators of immediately derived classes can override these without worrying about affecting the properties of the layout engine. """) eg(""" BaseDocTemplate.afterInit(self) """) disc(""" This is called after initialisation of the base class; a derived class could overide the method to add default $PageTemplates$. """) eg(""" BaseDocTemplate.afterPage(self) """) disc("""This is called after page processing, and immediately after the afterDrawPage method of the current page template. A derived class could use this to do things which are dependent on information in the page such as the first and last word on the page of a dictionary. """) eg(""" BaseDocTemplate.beforeDocument(self) """) disc("""This is called before any processing is done on the document, but after the processing machinery is ready. It can therefore be used to do things to the instance\'s $pdfgen.canvas$ and the like. """) eg(""" BaseDocTemplate.beforePage(self) """) disc("""This is called at the beginning of page processing, and immediately before the beforeDrawPage method of the current page template. It could be used to reset page specific information holders.""") eg(""" BaseDocTemplate.filterFlowables(self,flowables) """) disc("""This is called to filter flowables at the start of the main handle_flowable method. Upon return if flowables[0] has been set to None it is discarded and the main method returns immediately. """) eg(""" BaseDocTemplate.afterFlowable(self, flowable) """) disc("""Called after a flowable has been rendered. An interested class could use this hook to gather information about what information is present on a particular page or frame.""") heading4("$BaseDocTemplate$ Event handler Methods") disc(""" These methods constitute the greater part of the layout engine. Programmers shouldn't have to call or override these methods directly unless they are trying to modify the layout engine. Of course, the experienced programmer who wants to intervene at a particular event, $XXX$, which does not correspond to one of the virtual methods can always override and call the base method from the drived class version. We make this easy by providing a base class synonym for each of the handler methods with the same name prefixed by an underscore '_'. """) eg(""" def handle_pageBegin(self): doStuff() BaseDocTemplate.handle_pageBegin(self) doMoreStuff() #using the synonym def handle_pageEnd(self): doStuff() self._handle_pageEnd() doMoreStuff() """) disc(""" Here we list the methods only as an indication of the events that are being handled. Interested programmers can take a look at the source. """) eg(""" handle_currentFrame(self,fx) handle_documentBegin(self) handle_flowable(self,flowables) handle_frameBegin(self,*args) handle_frameEnd(self) handle_nextFrame(self,fx) handle_nextPageTemplate(self,pt) handle_pageBegin(self) handle_pageBreak(self) handle_pageEnd(self) """) disc(""" Using document templates can be very easy; $SimpleDoctemplate$ is a class derived from $BaseDocTemplate$ which provides its own $PageTemplate$ and $Frame$ setup. """) eg(""" from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.pagesizes import letter from reportlab.platypus import Paragraph, SimpleDocTemplate styles = getSampleStyleSheet() styleN = styles['Normal'] styleH = styles['Heading1'] story = [] #add some flowables story.append(Paragraph("This is a Heading",styleH)) story.append(Paragraph("This is a paragraph in <i>Normal</i> style.", styleN)) doc = SimpleDocTemplate('mydoc.pdf',pagesize = letter) doc.build(story) """) heading3("$PageTemplates$") disc(""" The $PageTemplate$ class is a container class with fairly minimal semantics. Each instance contains a list of $Frames$ and has methods which should be called at the start and end of each page. """) eg("PageTemplate(id=None,frames=[],onPage=_doNothing,onPageEnd=_doNothing)") disc(""" is used to initialize an instance, the $frames$ argument should be a list of $Frames$ whilst the optional $onPage$ and $onPageEnd$ arguments are callables which should have signature $def XXX(canvas,document)$ where $canvas$ and $document$ are the canvas and document being drawn. These routines are intended to be used to paint non-flowing (i.e. standard) parts of pages. These attribute functions are exactly parallel to the pure virtual methods $PageTemplate.beforPage$ and $PageTemplate.afterPage$ which have signature $beforPage(self,canvas,document)$. The methods allow class derivation to be used to define standard behaviour, whilst the attributes allow instance changes. The $id$ argument is used at run time to perform $PageTemplate$ switching so $id='FirstPage'$ or $id='TwoColumns'$ are typical. """)
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/docs/userguide/ch4_platypus_concepts.py
0.741019
0.584538
ch4_platypus_concepts.py
pypi
from reportlab.platypus import PageTemplate, BaseDocTemplate, Frame, Paragraph from reportlab.lib.units import inch from reportlab.lib.sequencer import Sequencer from reportlab.rl_config import defaultPageSize class FrontCoverTemplate(PageTemplate): def __init__(self, id, pageSize=defaultPageSize): self.pageWidth = pageSize[0] self.pageHeight = pageSize[1] frame1 = Frame(inch, 3*inch, self.pageWidth - 2*inch, self.pageHeight - 518, id='cover') PageTemplate.__init__(self, id, [frame1]) # note lack of onPage def afterDrawPage(self, canvas, doc): canvas.saveState() canvas.drawImage('../images/replogo.gif',2*inch, 8*inch) canvas.setFont('Times-Roman', 10) canvas.line(inch, 120, self.pageWidth - inch, 120) canvas.drawString(inch, 100, 'ReportLab') canvas.drawString(inch, 88, 'Wimbletech') canvas.drawString(inch, 76, '35 Wimbledon Hill Road') canvas.drawString(inch, 64, 'London SW19 7NB, UK') canvas.restoreState() class OneColumnTemplate(PageTemplate): def __init__(self, id, pageSize=defaultPageSize): self.pageWidth = pageSize[0] self.pageHeight = pageSize[1] frame1 = Frame(inch, inch, self.pageWidth - 2*inch, self.pageHeight - 2*inch, id='normal') PageTemplate.__init__(self, id, [frame1]) # note lack of onPage def afterDrawPage(self, canvas, doc): y = self.pageHeight - 50 canvas.saveState() canvas.setFont('Times-Roman', 10) canvas.drawString(inch, y+8, doc.title) canvas.drawRightString(self.pageWidth - inch, y+8, doc.chapter) canvas.line(inch, y, self.pageWidth - inch, y) canvas.drawCentredString(doc.pagesize[0] / 2, 0.75*inch, 'Page %d' % canvas.getPageNumber()) canvas.restoreState() class TOCTemplate(PageTemplate): def __init__(self, id, pageSize=defaultPageSize): self.pageWidth = pageSize[0] self.pageHeight = pageSize[1] frame1 = Frame(inch, inch, self.pageWidth - 2*inch, self.pageHeight - 2*inch, id='normal') PageTemplate.__init__(self, id, [frame1]) # note lack of onPage def afterDrawPage(self, canvas, doc): y = self.pageHeight - 50 canvas.saveState() canvas.setFont('Times-Roman', 10) canvas.drawString(inch, y+8, doc.title) canvas.drawRightString(self.pageWidth - inch, y+8, 'Table of contents') canvas.line(inch, y, self.pageWidth - inch, y) canvas.drawCentredString(doc.pagesize[0] / 2, 0.75*inch, 'Page %d' % canvas.getPageNumber()) canvas.restoreState() class TwoColumnTemplate(PageTemplate): def __init__(self, id, pageSize=defaultPageSize): self.pageWidth = pageSize[0] self.pageHeight = pageSize[1] colWidth = 0.5 * (self.pageWidth - 2.25*inch) frame1 = Frame(inch, inch, colWidth, self.pageHeight - 2*inch, id='leftCol') frame2 = Frame(0.5 * self.pageWidth + 0.125, inch, colWidth, self.pageHeight - 2*inch, id='rightCol') PageTemplate.__init__(self, id, [frame1, frame2]) # note lack of onPage def afterDrawPage(self, canvas, doc): y = self.pageHeight - 50 canvas.saveState() canvas.setFont('Times-Roman', 10) canvas.drawString(inch, y+8, doc.title) canvas.drawRightString(self.pageWidth - inch, y+8, doc.chapter) canvas.line(inch, y, self.pageWidth - inch, y*inch) canvas.drawCentredString(doc.pagesize[0] / 2, 0.75*inch, 'Page %d' % canvas.getPageNumber()) canvas.restoreState() class RLDocTemplate(BaseDocTemplate): def afterInit(self): self.addPageTemplates(FrontCoverTemplate('Cover', self.pagesize)) self.addPageTemplates(TOCTemplate('TOC', self.pagesize)) self.addPageTemplates(OneColumnTemplate('Normal', self.pagesize)) self.addPageTemplates(TwoColumnTemplate('TwoColumn', self.pagesize)) self.seq = Sequencer() def beforeDocument(self): self.canv.showOutline() self.title = "(Document Title Goes Here)" self.chapter = "(No chapter yet)" self.seq.reset('section') self.seq.reset('chapter') def afterFlowable(self, flowable): """Detect Level 1 and 2 headings, build outline, and track chapter title.""" if isinstance(flowable, Paragraph): style = flowable.style.name txt = flowable.getPlainText() if style == 'Title': self.title = txt elif style == 'Heading1': self.chapter = txt key = 'ch%s' % self.seq.nextf('chapter') self.canv.bookmarkPage(key) self.canv.addOutlineEntry(txt, key, 0, 0) self.seq.reset("section") self.notify('TOCEntry', (0, txt, self.page, key)) elif style == 'Heading2': self.section = flowable.text key = 'ch%ss%s' % (self.seq.thisf("chapter"), self.seq.nextf("section")) self.canv.bookmarkPage(key) self.canv.addOutlineEntry(txt, key, 1, 0) self.notify('TOCEntry', (1, txt, self.page, key))
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/tools/docco/rltemplate.py
0.400515
0.169784
rltemplate.py
pypi
__version__='3.3.0' # xml parser stuff for PythonPoint # PythonPoint Markup Language! __doc__=""" This demonstrates a custom shape for use with the <customshape> tag. The shape must fulfil a very simple interface, which may change in future. The XML tag currently has this form: <customshape module="customshapes.py" class = "MyShape" initargs="(100,200,3)" /> PythonPoint will look in the given module for the given class, evaluate the arguments string and pass it to the constructor. Then, it will call object.drawOn(canvas) Thus your object must be fully defined by the constructor. For this one, we pass three argumenyts: x, y and scale. This does a five-tile jigsaw over which words can be overlaid; based on work done for a customer's presentation. """ import reportlab.pdfgen.canvas from reportlab.lib import colors from reportlab.lib.corp import RL_CorpLogo from reportlab.graphics.shapes import Drawing ## custom shape for use with PythonPoint. class Jigsaw: """This draws a jigsaw patterm. By default it is centred on 0,0 and has dimensions of 200 x 140; use the x/y/scale attributes to move it around.""" #Using my usual bulldozer coding style - I am sure a mathematician could #derive an elegant way to draw this, but I just took a ruler, guessed at #the control points, and reflected a few lists at the interactive prompt. def __init__(self, x, y, scale=1): self.width = 200 self.height = 140 self.x = x self.y = y self.scale = scale def drawOn(self, canvas): canvas.saveState() canvas.setFont('Helvetica-Bold',24) canvas.drawString(600, 100, 'A Custom Shape') canvas.translate(self.x, self.y) canvas.scale(self.scale, self.scale) self.drawBounds(canvas) self.drawCentre(canvas) self.drawTopLeft(canvas) self.drawBottomLeft(canvas) self.drawBottomRight(canvas) self.drawTopRight(canvas) canvas.restoreState() def curveThrough(self, path, pointlist): """Helper to curve through set of control points.""" assert len(pointlist) % 3 == 1, "No. of points must be 3n+1 for integer n" (x,y) = pointlist[0] path.moveTo(x, y) idx = 1 while idx < len(pointlist)-2: p1, p2, p3 = pointlist[idx:idx+3] path.curveTo(p1[0], p1[1], p2[0], p2[1], p3[0], p3[1]) idx = idx + 3 def drawShape(self, canvas, controls, color): """Utlity to draw a closed shape through a list of control points; extends the previous proc""" canvas.setFillColor(color) p = canvas.beginPath() self.curveThrough(p, controls) p.close() canvas.drawPath(p, stroke=1, fill=1) def drawBounds(self, canvas): """Guidelines to help me draw - not needed in production""" canvas.setStrokeColor(colors.red) canvas.rect(-100,-70,200,140) canvas.line(-100,0,100,0) canvas.line(0,70,0,-70) canvas.setStrokeColor(colors.black) def drawCentre(self, canvas): controls = [ (0,50), #top #top right edge - duplicated for that corner piece (5,50),(10,45),(10,40), (10,35),(15,30),(20,30), (25,30),(30,25),(30,20), (30,15),(35,10),(40,10), (45,10),(50,5),(50,0), #bottom right edge (50, -5), (45,-10), (40,-10), (35,-10), (30,-15), (30, -20), (30,-25), (25,-30), (20,-30), (15,-30), (10,-35), (10,-40), (10,-45),(5,-50),(0,-50), #bottom left (-5,-50),(-10,-45),(-10,-40), (-10,-35),(-15,-30),(-20,-30), (-25,-30),(-30,-25),(-30,-20), (-30,-15),(-35,-10),(-40,-10), (-45,-10),(-50,-5),(-50,0), #top left (-50,5),(-45,10),(-40,10), (-35,10),(-30,15),(-30,20), (-30,25),(-25,30),(-20,30), (-15,30),(-10,35),(-10,40), (-10,45),(-5,50),(0,50) ] self.drawShape(canvas, controls, colors.yellow) def drawTopLeft(self, canvas): controls = [(-100,70), (-100,69),(-100,1),(-100,0), (-99,0),(-91,0),(-90,0), #jigsaw interlock - 4 sections (-90,5),(-92,5),(-92,10), (-92,15), (-85,15), (-80,15), (-75,15),(-68,15),(-68,10), (-68,5),(-70,5),(-70,0), (-69,0),(-51,0),(-50,0), #five distinct curves (-50,5),(-45,10),(-40,10), (-35,10),(-30,15),(-30,20), (-30,25),(-25,30),(-20,30), (-15,30),(-10,35),(-10,40), (-10,45),(-5,50),(0,50), (0,51),(0,69),(0,70), (-1,70),(-99,70),(-100,70) ] self.drawShape(canvas, controls, colors.teal) def drawBottomLeft(self, canvas): controls = [(-100,-70), (-99,-70),(-1,-70),(0,-70), (0,-69),(0,-51),(0,-50), #wavyline (-5,-50),(-10,-45),(-10,-40), (-10,-35),(-15,-30),(-20,-30), (-25,-30),(-30,-25),(-30,-20), (-30,-15),(-35,-10),(-40,-10), (-45,-10),(-50,-5),(-50,0), #jigsaw interlock - 4 sections (-51, 0), (-69, 0), (-70, 0), (-70, 5), (-68, 5), (-68, 10), (-68, 15), (-75, 15), (-80, 15), (-85, 15), (-92, 15), (-92, 10), (-92, 5), (-90, 5), (-90, 0), (-91,0),(-99,0),(-100,0) ] self.drawShape(canvas, controls, colors.green) def drawBottomRight(self, canvas): controls = [ (100,-70), (100,-69),(100,-1),(100,0), (99,0),(91,0),(90,0), #jigsaw interlock - 4 sections (90, -5), (92, -5), (92, -10), (92, -15), (85, -15), (80, -15), (75, -15), (68, -15), (68, -10), (68, -5), (70, -5), (70, 0), (69, 0), (51, 0), (50, 0), #wavyline (50, -5), (45,-10), (40,-10), (35,-10), (30,-15), (30, -20), (30,-25), (25,-30), (20,-30), (15,-30), (10,-35), (10,-40), (10,-45),(5,-50),(0,-50), (0,-51), (0,-69), (0,-70), (1,-70),(99,-70),(100,-70) ] self.drawShape(canvas, controls, colors.navy) def drawBottomLeft(self, canvas): controls = [(-100,-70), (-99,-70),(-1,-70),(0,-70), (0,-69),(0,-51),(0,-50), #wavyline (-5,-50),(-10,-45),(-10,-40), (-10,-35),(-15,-30),(-20,-30), (-25,-30),(-30,-25),(-30,-20), (-30,-15),(-35,-10),(-40,-10), (-45,-10),(-50,-5),(-50,0), #jigsaw interlock - 4 sections (-51, 0), (-69, 0), (-70, 0), (-70, 5), (-68, 5), (-68, 10), (-68, 15), (-75, 15), (-80, 15), (-85, 15), (-92, 15), (-92, 10), (-92, 5), (-90, 5), (-90, 0), (-91,0),(-99,0),(-100,0) ] self.drawShape(canvas, controls, colors.green) def drawTopRight(self, canvas): controls = [(100, 70), (99, 70), (1, 70), (0, 70), (0, 69), (0, 51), (0, 50), (5, 50), (10, 45), (10, 40), (10, 35), (15, 30), (20, 30), (25, 30), (30, 25), (30, 20), (30, 15), (35, 10), (40, 10), (45, 10), (50, 5), (50, 0), (51, 0), (69, 0), (70, 0), (70, -5), (68, -5), (68, -10), (68, -15), (75, -15), (80, -15), (85, -15), (92, -15), (92, -10), (92, -5), (90, -5), (90, 0), (91, 0), (99, 0), (100, 0) ] self.drawShape(canvas, controls, colors.magenta) class Logo: """This draws a ReportLab Logo.""" def __init__(self, x, y, width, height): logo = RL_CorpLogo() logo.x = x logo.y = y logo.width = width logo.height = height self.logo = logo def drawOn(self, canvas): logo = self.logo x, y = logo.x, logo.y w, h = logo.width, logo.height D = Drawing(w, h) D.add(logo) D.drawOn(canvas, 0, 0) def run(): c = reportlab.pdfgen.canvas.Canvas('customshape.pdf') J = Jigsaw(300, 540, 2) J.drawOn(c) c.save() if __name__ == '__main__': run()
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/tools/pythonpoint/customshapes.py
0.705379
0.647603
customshapes.py
pypi
__version__='3.3.0' # style_modern.py __doc__="""This is an example style sheet. You can create your own, and have them loaded by the presentation. A style sheet is just a dictionary, where they keys are style names and the values are ParagraphStyle objects. You must provide a function called "getParagraphStyles()" to return it. In future, we can put things like LineStyles, TableCellStyles etc. in the same modules. You might wish to have two parallel style sheets, one for colour and one for black and white, so you can switch your presentations easily. A style sheet MUST define a style called 'Normal'. """ from reportlab.lib import styles, enums def getParagraphStyles(): """Returns a dictionary of styles based on Helvetica""" stylesheet = {} para = styles.ParagraphStyle('Normal', None) #the ancestor of all para.fontName = 'Courier' para.fontSize = 24 para.leading = 28 stylesheet['Normal'] = para para = ParagraphStyle('BodyText', stylesheet['Normal']) para.spaceBefore = 12 stylesheet['BodyText'] = para para = ParagraphStyle('BigCentered', stylesheet['Normal']) para.spaceBefore = 12 para.alignment = enums.TA_CENTER stylesheet['BigCentered'] = para para = ParagraphStyle('Italic', stylesheet['BodyText']) para.fontName = 'Courier-Oblique' stylesheet['Italic'] = para para = ParagraphStyle('Title', stylesheet['Normal']) para.fontName = 'Courier' para.fontSize = 48 para.Leading = 58 para.spaceAfter = 36 para.alignment = enums.TA_CENTER stylesheet['Title'] = para para = ParagraphStyle('Heading1', stylesheet['Normal']) para.fontName = 'Courier-Bold' para.fontSize = 36 para.leading = 44 para.spaceAfter = 36 para.alignment = enums.TA_CENTER stylesheet['Heading1'] = para para = ParagraphStyle('Heading2', stylesheet['Normal']) para.fontName = 'Courier-Bold' para.fontSize = 28 para.leading = 34 para.spaceBefore = 24 para.spaceAfter = 12 stylesheet['Heading2'] = para para = ParagraphStyle('Heading3', stylesheet['Normal']) para.fontName = 'Courier-BoldOblique' para.spaceBefore = 24 para.spaceAfter = 12 stylesheet['Heading3'] = para para = ParagraphStyle('Bullet', stylesheet['Normal']) para.firstLineIndent = -18 para.leftIndent = 72 para.spaceBefore = 6 #para.bulletFontName = 'Symbol' para.bulletFontSize = 24 para.bulletIndent = 36 stylesheet['Bullet'] = para para = ParagraphStyle('Definition', stylesheet['Normal']) #use this for definition lists para.firstLineIndent = 0 para.leftIndent = 72 para.bulletIndent = 0 para.spaceBefore = 12 para.bulletFontName = 'Couruer-BoldOblique' stylesheet['Definition'] = para para = ParagraphStyle('Code', stylesheet['Normal']) para.fontName = 'Courier' para.fontSize = 16 para.leading = 18 para.leftIndent = 36 stylesheet['Code'] = para return stylesheet
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/tools/pythonpoint/styles/horrible.py
0.573201
0.451871
horrible.py
pypi
__version__='3.3.0' # style_modern.py __doc__="""This is an example style sheet. You can create your own, and have them loaded by the presentation. A style sheet is just a dictionary, where they keys are style names and the values are ParagraphStyle objects. You must provide a function called "getParagraphStyles()" to return it. In future, we can put things like LineStyles, TableCellStyles etc. in the same modules. You might wish to have two parallel style sheets, one for colour and one for black and white, so you can switch your presentations easily. A style sheet MUST define a style called 'Normal'. """ from reportlab.lib import styles from reportlab.lib.enums import TA_CENTER def getParagraphStyles(): """Returns a dictionary of styles based on Helvetica""" stylesheet = {} ParagraphStyle = styles.ParagraphStyle para = ParagraphStyle('Normal', None) #the ancestor of all para.fontName = 'Helvetica' para.fontSize = 24 para.leading = 28 stylesheet['Normal'] = para para = ParagraphStyle('BodyText', stylesheet['Normal']) para.spaceBefore = 12 stylesheet['BodyText'] = para para = ParagraphStyle('Indent', stylesheet['Normal']) para.leftIndent = 36 para.firstLineIndent = 0 stylesheet['Indent'] = para para = ParagraphStyle('Centered', stylesheet['Normal']) para.alignment = TA_CENTER stylesheet['Centered'] = para para = ParagraphStyle('BigCentered', stylesheet['Normal']) para.spaceBefore = 12 para.alignment = TA_CENTER stylesheet['BigCentered'] = para para = ParagraphStyle('Italic', stylesheet['BodyText']) para.fontName = 'Helvetica-Oblique' stylesheet['Italic'] = para para = ParagraphStyle('Title', stylesheet['Normal']) para.fontName = 'Helvetica' para.fontSize = 48 para.Leading = 58 para.spaceAfter = 36 para.alignment = TA_CENTER stylesheet['Title'] = para para = ParagraphStyle('Heading1', stylesheet['Normal']) para.fontName = 'Helvetica-Bold' para.fontSize = 36 para.leading = 44 para.spaceAfter = 36 para.alignment = TA_CENTER stylesheet['Heading1'] = para para = ParagraphStyle('Heading2', stylesheet['Normal']) para.fontName = 'Helvetica-Bold' para.fontSize = 28 para.leading = 34 para.spaceBefore = 24 para.spaceAfter = 12 stylesheet['Heading2'] = para para = ParagraphStyle('Heading3', stylesheet['Normal']) para.fontName = 'Helvetica-BoldOblique' para.spaceBefore = 24 para.spaceAfter = 12 stylesheet['Heading3'] = para para = ParagraphStyle('Bullet', stylesheet['Normal']) para.firstLineIndent = -18 para.leftIndent = 72 para.spaceBefore = 6 para.bulletFontName = 'Symbol' para.bulletFontSize = 24 para.bulletIndent = 36 stylesheet['Bullet'] = para para = ParagraphStyle('Bullet2', stylesheet['Bullet']) para.firstLineIndent = 0 para.bulletIndent = 72 para.leftIndent = 108 stylesheet['Bullet2'] = para para = ParagraphStyle('Definition', stylesheet['Normal']) #use this for definition lists para.firstLineIndent = 0 para.leftIndent = 72 para.bulletIndent = 0 para.spaceBefore = 12 para.bulletFontName = 'Helvetica-BoldOblique' stylesheet['Definition'] = para para = ParagraphStyle('Code', stylesheet['Normal']) para.fontName = 'Courier' para.fontSize = 16 para.leading = 18 para.leftIndent = 36 stylesheet['Code'] = para return stylesheet
/reportlab2-3.6.11.tar.gz/reportlab2-3.6.11/tools/pythonpoint/styles/modern.py
0.516595
0.427277
modern.py
pypi
from mss import mss from reportportal_behave.entities.feature import Feature from reportportal_behave.entities.scenario import Scenario from reportportal_behave.entities.step import Step from reportportal_behave.reportportal_service import * class BehaveIntegrationService: def __init__(self, rp_endpoint, rp_project, rp_token, rp_launch_name, rp_launch_description, rp_enable=True, step_based=False, add_screenshot=False, verify_ssl=False): self.rp_endpoint = rp_endpoint self.rp_project = rp_project self.rp_token = rp_token self.rp_launch_name = rp_launch_name self.rp_launch_description = rp_launch_description self.rp_enable = rp_enable self.step_based = step_based self.add_screenshot = add_screenshot self.service = IntegrationService(rp_endpoint=rp_endpoint, rp_project=rp_project, rp_token=rp_token, rp_launch_name=rp_launch_name, rp_launch_description=rp_launch_description, verify_ssl=verify_ssl) def log_step_error_result(self, step_name, item_id, error_msg=None): """ Log errors in steps if it happens :param step_name: the name of the step :param item_id: the id of the step execution :param error_msg: the error message :return: None """ if self.add_screenshot: with mss() as sct: screenshot_name = sct.shot() # Logs assertion message with attachment and ERROR level it step was failed. self.service.log_step_result(end_time=timestamp(), message=error_msg, level='ERROR', attachment={ 'name': step_name, 'data': open(screenshot_name, 'rb'), 'mime': 'application/octet-stream' }, item_id=item_id ) else: self.service.log_step_result(end_time=timestamp(), message=error_msg, level='ERROR', item_id=item_id) def launch_service(self, tags, attributes): """ Start the service that will communicate results to ReportPortal :param tags: the tags the test execution was triggered with :return: the id of the launch required to mark it complete """ if self.rp_enable: return self.service.start_launcher(name=self.rp_launch_name, start_time=timestamp(), tags=tags, attributes=attributes, description=self.rp_launch_description ) def before_feature(self, feature): """ Log the start of a feature execution :param feature: the feature passed from behave :return: the id of the feature execution required to mark it complete """ if self.rp_enable: feature_info = Feature(feature) return self.service.start_feature_test(name=feature_info.name, description=feature_info.description, tags=feature_info.tags, start_time=timestamp(), item_type=feature_info.item_type, parent_item_id=None) def before_scenario(self, scenario, feature_id): """ Log the start of a scenario execution :param scenario: the behave scenario :param feature_id: the id of the feature execution :return: the id of te scenario execution required to mark it complete """ if self.rp_enable: scenario_info = Scenario(scenario, feature_id=feature_id) return self.service.start_scenario_test(name=scenario_info.name, description=scenario_info.description, tags=scenario_info.tags, start_time=timestamp(), item_type=scenario_info.item_type, parent_item_id=scenario_info.feature_id) def before_step(self, step, scenario_id): """ Logs the start of a step execution. This method is ran only if step_based logging is enabled :param step: the behave step :param scenario_id: the id of the scenario execution the step belongs to :return: the id of the step execution required to mark it complete """ if self.rp_enable and self.step_based: step_info = Step(step, scenario_id=scenario_id) return self.service.start_step_test(name=f"{step_info.keyword} {step_info.name}", start_time=timestamp(), item_type=step_info.item_type, description=step_info.description, parent_item_id=step_info.scenario_id) def after_step(self, step, step_id): """ Mark the step as complete and set the status for it :param step: the behave step :param step_id: the id of the step execution received from the before_step :return: response of the step completion if available """ step_info = Step(step, step_id=step_id) if self.rp_enable and self.step_based: # Finishes step if step.status == 'failed': # Takes a demo screenshot of desktop (can be removed) self.log_step_error_result(error_msg=f"{step.exception}", step_name=step_info.name, item_id=step_info.step_id) return self.service.finish_step_test(end_time=timestamp(), status='FAILED', item_id=step_info.step_id) else: return self.service.finish_step_test(end_time=timestamp(), status='PASSED', item_id=step_info.step_id) # Else SCENARIO based logging will be used elif self.rp_enable: # Creates text log message with INFO level. if step.table: message = '%s %s\n~~~~~~~~~~~~~~~~~~~~~~~~~\nStep data table:\n%s' % ( step_info.keyword, step_info.name, step_info.description) elif step.text: message = '%s %s\n~~~~~~~~~~~~~~~~~~~~~~~~~\nStep data text:\n%s' % ( step_info.keyword, step_info.name, step_info.description) else: message = step_info.description self.service.log_step_result(end_time=timestamp(), message=message, level='INFO', item_id=step_info.step_id) if step.status == 'failed': # Logs assertion message with attachment and ERROR level it step was failed. self.log_step_error_result(error_msg=f"{step.exception}", step_name=step_info.name, item_id=step_info.step_id) def after_scenario(self, scenario, scenario_id): """ Mark scenario as complete and set the status accordingly :param scenario: the behave scenario :param scenario_id: the id of the scenario execution received from before scenario :return: response of the scenario completion if available """ if self.rp_enable: scenario_info = Scenario(scenario, scenario_id=scenario_id) for step in scenario.steps: if step.status.name == 'undefined': # Logs scenario if it is undefined self.service.log_step_result(end_time=timestamp(), message='%s %s - step is undefined.\n' % ( step.keyword, step.name), level='WARN', item_id=scenario_info.scenario_id) # Logs scenario as skipped if it is marked for skip # For example scenario marked by @skip tag and --tags=~@skip specified in params of run elif step.status.name == 'skipped': self.service.log_step_result(end_time=timestamp(), message='%s %s - %s' % ( step.keyword, step.name, step.status.name.capitalize()), level='TRACE', item_id=scenario_info.scenario_id) # Finishes scenario if scenario.status == 'failed': status = "FAILED" else: status = "PASSED" return self.service.finish_scenario_test(end_time=timestamp(), status=status, item_id=scenario_info.scenario_id) def after_feature(self, feature, feature_id): """ Mark the feature as complete and set the status accordingly :param feature: the behave feature :param feature_id: the id of the feature execution in order to mark it complete :return: response of the feature completion if available """ if self.rp_enable: feature_info = Feature(feature, feature_id=feature_id) for scenario in feature.scenarios: try: if 'skip' in scenario.tags: scenario_id = self.service.start_scenario_test(name='Scenario: %s' % scenario.name, description=scenario.description, tags=feature_info.tags, start_time=timestamp(), item_type='SCENARIO', parent_item_id=feature_info.feature_id) self.service.finish_scenario_test(end_time=timestamp(), tatus='SKIPPED', item_id=scenario_id) except IndexError: pass # Finishes feature if feature.status == 'failed': status = "FAILED" else: status = "PASSED" return self.service.finish_feature(end_time=timestamp(), status=status, item_id=feature_info.feature_id) def after_all(self, launch_id): """ Finish the test execution and terminate the RP service :param launch_id: the id of the execution :return: response of the test execution completion if available """ if self.rp_enable: launch_completion = self.service.finish_launcher(end_time=timestamp(), launch_id=launch_id) self.service.terminate_service() return launch_completion
/reportportal-behave-client-custom-2.tar.gz/reportportal-behave-client-custom-2/reportportal_behave/behave_integration_service.py
0.642545
0.193776
behave_integration_service.py
pypi
import inspect import json import logging import time import uuid from platform import machine, processor, system import six from pkg_resources import DistributionNotFound, get_distribution from .static.defines import ATTRIBUTE_LENGTH_LIMIT logger = logging.getLogger(__name__) def generate_uuid(): """Generate UUID.""" return str(uuid.uuid4()) def convert_string(value): """Support and convert strings in py2 and py3. :param value: input string :return value: converted string """ if isinstance(value, six.text_type): # Don't try to encode 'unicode' in Python 2. return value return str(value) def dict_to_payload(dictionary): """Convert incoming dictionary to the list of dictionaries. This function transforms the given dictionary of tags/attributes into the format required by the Report Portal API. Also, we add the system key to every tag/attribute that indicates that the key should be hidden from the user in UI. :param dictionary: Dictionary containing tags/attributes :return list: List of tags/attributes in the required format """ hidden = dictionary.pop('system', False) return [ {'key': key, 'value': convert_string(value), 'system': hidden} for key, value in sorted(dictionary.items()) ] def gen_attributes(rp_attributes): """Generate list of attributes for the API request. Example of input list: ['tag_name:tag_value1', 'tag_value2'] Output of the function for the given input list: [{'key': 'tag_name', 'value': 'tag_value1'}, {'value': 'tag_value2'}] :param rp_attributes: List of attributes(tags) :return: Correctly created list of dictionaries to be passed to RP """ attrs = [] for rp_attr in rp_attributes: try: key, value = rp_attr.split(':') attr_dict = {'key': key, 'value': value} except ValueError as exc: logger.debug(str(exc)) attr_dict = {'value': rp_attr} if all(attr_dict.values()): attrs.append(attr_dict) continue logger.debug('Failed to process "{0}" attribute, attribute value' ' should not be empty.'.format(rp_attr)) return attrs def get_launch_sys_attrs(): """Generate attributes for the launch containing system information. :return: dict {'os': 'Windows', 'cpu': 'AMD', 'machine': 'Windows10_pc'} """ return { 'os': system(), 'cpu': processor() or 'unknown', 'machine': machine(), 'system': True # This one is the flag for RP to hide these attributes } def get_package_version(package_name): """Get version of the given package. :param package_name: Name of the package :return: Version of the package """ try: package_version = get_distribution(package_name).version except DistributionNotFound: package_version = 'not found' return package_version def verify_value_length(attributes): """Verify length of the attribute value. The length of the attribute value should have size from '1' to '128'. Otherwise HTTP response will return an error. Example of the input list: [{'key': 'tag_name', 'value': 'tag_value1'}, {'value': 'tag_value2'}] :param attributes: List of attributes(tags) :return: List of attributes with corrected value length """ if attributes is not None: for pair in attributes: if not isinstance(pair, dict): continue attr_value = pair.get('value') if attr_value is None: continue try: pair['value'] = attr_value[:ATTRIBUTE_LENGTH_LIMIT] except TypeError: continue return attributes def timestamp(): """Return string representation of the current time in milliseconds.""" return str(int(time.time() * 1000)) def uri_join(*uri_parts): """Join uri parts. Avoiding usage of urlparse.urljoin and os.path.join as it does not clearly join parts. Args: *uri_parts: tuple of values for join, can contain back and forward slashes (will be stripped up). Returns: An uri string. """ return '/'.join(str(s).strip('/').strip('\\') for s in uri_parts) def get_function_params(func, args, kwargs): """Extract argument names from the function and combine them with values. :param func: the function to get arg names :param args: function's arg values :param kwargs: function's kwargs :return: a dictionary of values """ if six.PY2: # Use deprecated method for python 2.7 compatibility arg_spec = inspect.getargspec(func) else: arg_spec = inspect.getfullargspec(func) result = dict() for i, arg_name in enumerate(arg_spec.args): if i >= len(args): break result[arg_name] = args[i] for arg_name, arg_value in kwargs.items(): result[arg_name] = arg_value return result if len(result.items()) > 0 else None TYPICAL_MULTIPART_BOUNDARY = '--972dbca3abacfd01fb4aea0571532b52' TYPICAL_JSON_PART_HEADER = TYPICAL_MULTIPART_BOUNDARY + '''\r Content-Disposition: form-data; name="json_request_part"\r Content-Type: application/json\r \r ''' TYPICAL_FILE_PART_HEADER = TYPICAL_MULTIPART_BOUNDARY + '''\r Content-Disposition: form-data; name="file"; filename="{0}"\r Content-Type: {1}\r \r ''' TYPICAL_JSON_PART_HEADER_LENGTH = len(TYPICAL_JSON_PART_HEADER) TYPICAL_MULTIPART_FOOTER = '\r\n' + TYPICAL_MULTIPART_BOUNDARY + '--' TYPICAL_MULTIPART_FOOTER_LENGTH = len(TYPICAL_MULTIPART_FOOTER) TYPICAL_JSON_ARRAY = '[]' TYPICAL_JSON_ARRAY_LENGTH = len(TYPICAL_JSON_ARRAY) TYPICAL_JSON_ARRAY_ELEMENT = ',' TYPICAL_JSON_ARRAY_ELEMENT_LENGTH = len(TYPICAL_JSON_ARRAY_ELEMENT) def calculate_json_part_size(json_dict): """Predict a JSON part size of Multipart request. :param json_dict: a dictionary representing the JSON :return: Multipart request part size """ size = len(json.dumps(json_dict)) size += TYPICAL_JSON_PART_HEADER_LENGTH size += TYPICAL_JSON_ARRAY_LENGTH size += TYPICAL_JSON_ARRAY_ELEMENT_LENGTH return size def calculate_file_part_size(file): """Predict a file part size of Multipart request. :param file: RPFile class instance :return: Multipart request part size """ if file is None: return 0 size = len(TYPICAL_FILE_PART_HEADER.format(file.name, file.content_type)) size += len(file.content) return size
/reportportal-client-5.4.0.tar.gz/reportportal-client-5.4.0/reportportal_client/helpers.py
0.667364
0.265666
helpers.py
pypi
import logging from reportportal_client.static.defines import NOT_FOUND logger = logging.getLogger(__name__) class RPMessage(object): """Model for the message returned by RP API.""" __slots__ = ['message', 'error_code'] def __init__(self, data): """Initialize instance attributes. :param data: Dictionary representation of the API response """ self.error_code = data.get('error_code', NOT_FOUND) self.message = data.get('message', NOT_FOUND) def __str__(self): """Change string representation of the class.""" if self.error_code is NOT_FOUND: return self.message return '{error_code}: {message}'.format(error_code=self.error_code, message=self.message) @property def is_empty(self): """Check if returned message is empty.""" return self.message is NOT_FOUND class RPResponse(object): """Class representing RP API response.""" __slots__ = ['_data', '_resp'] def __init__(self, data): """Initialize instance attributes. :param data: requests.Response object """ self._data = self._get_json(data) self._resp = data @staticmethod def _get_json(data): """Get response in dictionary. :param data: requests.Response object :return: dict """ return data.json() @property def id(self): """Get value of the 'id' key.""" return self.json.get('id', NOT_FOUND) @property def is_success(self): """Check if response to API has been successful.""" return self._resp.ok def _iter_messages(self): """Generate RPMessage for each response.""" data = self.json.get('responses', [self.json]) for chunk in data: message = RPMessage(chunk) if not message.is_empty: yield message @property def json(self): """Get the response in dictionary.""" return self._data @property def message(self): """Get value of the 'message' key.""" return self.json.get('message', NOT_FOUND) @property def messages(self): """Get list of messages received.""" return tuple(self._iter_messages())
/reportportal-client-5.4.0.tar.gz/reportportal-client-5.4.0/reportportal_client/core/rp_responses.py
0.874681
0.151655
rp_responses.py
pypi
class Issue(object): """This class represents an issue that can be attached to test result.""" def __init__(self, issue_type, comment=None, auto_analyzed=False, ignore_analyzer=True): """Initialize instance attributes. :param issue_type: Issue type locator. Allowable values: "pb***", "ab***", "si***", "ti***", "nd001". Where *** is locator id. :param comment: Issue comments :param auto_analyzed: Indicator that the issue has been marked with the RP auto analyzer :param ignore_analyzer: Flag that forces RP analyzer to ignore this issue """ self._external_issues = [] self.auto_analyzed = auto_analyzed self.comment = comment self.ignore_analyzer = ignore_analyzer self.issue_type = issue_type def external_issue_add(self, issue): """Add external system issue to the issue.""" self._external_issues.append(issue.payload) @property def payload(self): """Form the correct dictionary for the issue.""" return { 'autoAnalyzed': self.auto_analyzed, 'comment': self.comment, 'externalSystemIssues': self._external_issues, 'ignoreAnalyzer': self.ignore_analyzer, 'issueType': self.issue_type } class ExternalIssue(object): """This class represents external(BTS) system issue.""" def __init__(self, bts_url=None, bts_project=None, submit_date=None, ticket_id=None, url=None): """Initialize instance attributes. :param bts_url: Bug tracker system URL :param bts_project: Bug tracker system project :param submit_date: Bug submission date :param ticket_id: Unique ID of the ticket at the BTS :param url: URL to the ticket(bug) """ self.bts_url = bts_url self.bts_project = bts_project self.submit_date = submit_date self.ticket_id = ticket_id self.url = url @property def payload(self): """Form the correct dictionary for the BTS issue.""" return { 'btsUrl': self.bts_url, 'btsProject': self.bts_project, 'submitDate': self.submit_date, 'ticketId': self.ticket_id, 'url': self.url }
/reportportal-client-5.4.0.tar.gz/reportportal-client-5.4.0/reportportal_client/core/rp_issues.py
0.908373
0.219066
rp_issues.py
pypi
from functools import wraps from reportportal_client._local import current from reportportal_client.helpers import get_function_params, timestamp NESTED_STEP_ITEMS = ('step', 'scenario', 'before_class', 'before_groups', 'before_method', 'before_suite', 'before_test', 'after_test', 'after_suite', 'after_class', 'after_groups', 'after_method') # noinspection PyUnresolvedReferences class StepReporter: """Nested Steps context handling class.""" def __init__(self, rp_client): """Initialize required attributes. :param rp_client: Report Portal client which will be used to report steps """ self.client = rp_client def start_nested_step(self, name, start_time, parameters=None, **kwargs): """Start Nested Step on Report Portal. :param name: Nested Step name :param start_time: Nested Step start time :param parameters: Nested Step parameters """ parent_id = self.client.current_item() if not parent_id: return return self.client.start_test_item(name, start_time, 'step', has_stats=False, parameters=parameters, parent_item_id=parent_id) def finish_nested_step(self, item_id, end_time, status=None, **kwargs): """Finish a Nested Step on Report Portal. :param item_id: Nested Step item ID :param end_time: Nested Step finish time :param status: Nested Step finish status """ return self.client.finish_test_item(item_id, end_time, status=status) class Step: """Step context handling class.""" def __init__(self, name, params, status, rp_client): """Initialize required attributes. :param name: Nested Step name :param params: Nested Step parameters :param status: Nested Step status which will be reported on successful step finish :param rp_client: Report Portal client which will be used to report the step """ self.name = name self.params = params self.status = status self.client = rp_client self.__item_id = None def __enter__(self): """Enter the runtime context related to this object.""" # Cannot call _local.current() early since it will be initialized # before client put something in there rp_client = self.client or current() if not rp_client: return self.__item_id = rp_client.step_reporter \ .start_nested_step(self.name, timestamp(), parameters=self.params) if self.params: param_list = [ str(key) + ": " + str(value) for key, value in sorted(self.params.items()) ] param_str = 'Parameters: ' + '; '.join(param_list) rp_client.log(timestamp(), param_str, level='INFO', item_id=self.__item_id) def __exit__(self, exc_type, exc_val, exc_tb): """Exit the runtime context related to this object.""" # Cannot call _local.current() early since it will be initialized # before client put something in there rp_client = self.client or current() if not rp_client: return # Avoid failure in case if 'rp_client' was 'None' on function start if not self.__item_id: return step_status = self.status if any((exc_type, exc_val, exc_tb)): step_status = 'FAILED' rp_client.step_reporter \ .finish_nested_step(self.__item_id, timestamp(), step_status) def __call__(self, func): """Wrap and call a function reference. :param func: function reference """ @wraps(func) def wrapper(*args, **kwargs): __tracebackhide__ = True params = self.params if params is None: params = get_function_params(func, args, kwargs) with Step(self.name, params, self.status, self.client): return func(*args, **kwargs) return wrapper def step(name_source, params=None, status='PASSED', rp_client=None): """Nested step report function. Create a Nested Step inside a test method on Report Portal. :param name_source: a function or string which will be used as step's name :param params: nested step parameters which will be reported as the first step entry. If 'name_source' is a function reference and this parameter is not specified, they will be taken from the function. :param status: the status which will be reported after the step passed. Can be any of legal Report Portal statuses. E.G.: PASSED, WARN, INFO, etc. Default value is PASSED :param rp_client: overrides Report Portal client which will be used in step reporting :return: a step context object """ if callable(name_source): name = name_source.__name__ return Step(name, params, status, rp_client)(name_source) return Step(str(name_source), params, status, rp_client)
/reportportal-client-5.4.0.tar.gz/reportportal-client-5.4.0/reportportal_client/steps/__init__.py
0.812012
0.176991
__init__.py
pypi