Example #1
0
 def drawBoundary(self,canv):
     "draw the frame boundary as a rectangle (primarily for debugging)."
     from reportlab.lib.colors import Color, CMYKColor, toColor
     sb = self.showBoundary
     ss = type(sb) in (type(''),type(()),type([])) or isinstance(sb,Color)
     w = -1
     if ss:
         c = toColor(sb,self)
         ss = c is not self
     elif isinstance(sb,ShowBoundaryValue) and sb:
         c = toColor(sb.color,self)
         w = sb.width
         ss = c is not self
     if ss:
         canv.saveState()
         canv.setStrokeColor(c)
         if w>=0:
             canv.setLineWidth(w)
     canv.rect(
             self._x1,
             self._y1,
             self._x2 - self._x1,
             self._y2 - self._y1
             )
     if ss: canv.restoreState()
def test1():
    c  = Canvas('figures.pdf')
    f = Frame(inch, inch, 6*inch, 9*inch, showBoundary=1)
    v = PlatPropFigure1()
    v.captionTextColor = toColor('blue')
    v.captionBackColor = toColor('lightyellow')
    f.addFromList([v],c)
    c.save()
Example #3
0
 def __init__(self):
     AreaLinePlot.__init__(self)
     self.xValueAxis = NormalDateXValueAxis()
     self.yValueAxis = AdjYValueAxis()
     self.data=[(20030601,0.95,0.05,0.0),(20030701,0.95,0.05,0.0),(20030801,0.95,0.05,0.0),(20030901,0.95,0.05,0.0),(20031001,0.95,0.05,0.0),(20031101,0.95,0.05,0.0),(20031201,0.95,0.05,0.0),(20040101,0.95,0.05,0.0),(20040201,0.95,0.05,0.0),(20040301,0.95,0.05,0.0),(20040401,0.95,0.05,0.0),(20040501,0.95,0.05,0.0),(20040601,0.95,0.05,0.0),(20040701,0.95,0.05,0.0),(20040801,0.95,0.05,0.0),(20040901,0.95,0.05,0.0),(20041001,0.95,0.05,0.0),(20041101,0.95,0.05,0.0),(20041201,0.95,0.05,0.0),(20050101,0.95,0.05,0.0),(20050201,0.95,0.05,0.0),(20050301,0.95,0.05,0.0),(20050401,0.95,0.05,0.0),(20050501,0.95,0.05,0.0),(20050601,0.95,0.05,0.0),(20050701,0.95,0.05,0.0),(20050801,0.95,0.05,0.0),(20050901,0.95,0.05,0.0),(20051001,0.95,0.05,0.0),(20051101,0.95,0.05,0.0),(20051201,0.95,0.05,0.0),(20060101,0.95,0.05,0.0),(20060201,0.95,0.05,0.0),(20060301,0.95,0.05,0.0),(20060401,0.95,0.05,0.0),(20060501,0.95,0.05,0.0),(20060601,0.95,0.05,0.0),(20060701,0.95,0.05,0.0),(20060801,0.95,0.05,0.0),(20060901,0.95,0.05,0.0),(20061001,0.95,0.05,0.0),(20061101,0.95,0.05,0.0),(20061201,0.95,0.05,0.0),(20070101,0.95,0.05,0.0),(20070201,0.95,0.05,0.0),(20070301,0.95,0.05,0.0),(20070401,0.95,0.05,0.0),(20070501,0.95,0.05,0.0),(20070601,0.95,0.05,0.0),(20070701,0.95,0.05,0.0),(20070801,0.95,0.05,0.0),(20070901,0.95,0.05,0.0),(20071001,0.95,0.05,0.0),(20071101,0.95,0.05,0.0),(20071201,0.95,0.05,0.0),(20080101,0.95,0.05,0.0),(20080201,0.95,0.05,0.0),(20080301,0.95,0.05,0.0),(20080401,0.95,0.05,0.0),(20080501,0.95,0.05,0.0),(20080601,0.95,0.05,0.0),(20080701,0.95,0.05,0.0),(20080801,0.95,0.05,0.0),(20080901,0.95,0.05,0.0),(20081001,0.95,0.05,0.0),(20081101,0.95,0.05,0.0),(20081201,0.95,0.05,0.0),(20090101,0.95,0.05,0.0),(20090201,0.91,0.09,0.0),(20090301,0.91,0.09,0.0),(20090401,0.91,0.09,0.0),(20090501,0.91,0.09,0.0),(20090601,0.91,0.09,0.0),(20090701,0.91,0.09,0.0),(20090801,0.91,0.09,0.0),(20090901,0.91,0.09,0.0),(20091001,0.91,0.09,0.0),(20091101,0.91,0.09,0.0),(20091201,0.91,0.09,0.0),(20100101,0.91,0.09,0.0),(20100201,0.81,0.19,0.0),(20100301,0.81,0.19,0.0),(20100401,0.81,0.19,0.0),(20100501,0.81,0.19,0.0),(20100601,0.81,0.19,0.0),(20100701,0.81,0.19,0.0),(20100801,0.81,0.19,0.0),(20100901,0.81,0.19,0.0),(20101001,0.81,0.19,0.0),(20101101,0.81,0.19,0.0),(20101201,0.81,0.19,0.0),(20110101,0.81,0.19,0.0),(20110201,0.72,0.28,0.0),(20110301,0.72,0.28,0.0),(20110401,0.72,0.28,0.0),(20110501,0.72,0.28,0.0),(20110601,0.72,0.28,0.0),(20110701,0.72,0.28,0.0),(20110801,0.72,0.28,0.0),(20110901,0.72,0.28,0.0),(20111001,0.72,0.28,0.0),(20111101,0.72,0.28,0.0),(20111201,0.72,0.28,0.0),(20120101,0.72,0.28,0.0),(20120201,0.53,0.47,0.0),(20120301,0.53,0.47,0.0),(20120401,0.53,0.47,0.0),(20120501,0.53,0.47,0.0),(20120601,0.53,0.47,0.0),(20120701,0.53,0.47,0.0),(20120801,0.53,0.47,0.0),(20120901,0.53,0.47,0.0),(20121001,0.53,0.47,0.0),(20121101,0.53,0.47,0.0),(20121201,0.53,0.47,0.0),(20130101,0.53,0.47,0.0),(20130201,0.44,0.56,0.0),(20130301,0.44,0.56,0.0),(20130401,0.44,0.56,0.0),(20130501,0.44,0.56,0.0),(20130601,0.44,0.56,0.0),(20130701,0.44,0.56,0.0),(20130801,0.44,0.56,0.0),(20130901,0.44,0.56,0.0),(20131001,0.44,0.56,0.0),(20131101,0.44,0.56,0.0),(20131201,0.44,0.56,0.0),(20140101,0.44,0.56,0.0),(20140201,0.36,0.5,0.14),(20140301,0.36,0.5,0.14),(20140401,0.36,0.5,0.14),(20140501,0.36,0.5,0.14),(20140601,0.36,0.5,0.14),(20140701,0.36,0.5,0.14),(20140801,0.36,0.5,0.14),(20140901,0.36,0.5,0.14),(20141001,0.36,0.5,0.14),(20141101,0.36,0.5,0.14),(20141201,0.36,0.5,0.14),(20150101,0.36,0.5,0.14),(20150201,0.3,0.41,0.29),(20150301,0.3,0.41,0.29),(20150401,0.3,0.41,0.29),(20150501,0.3,0.41,0.29),(20150601,0.3,0.41,0.29),(20150701,0.3,0.41,0.29),(20150801,0.3,0.41,0.29),(20150901,0.3,0.41,0.29),(20151001,0.3,0.41,0.29),(20151101,0.3,0.41,0.29),(20151201,0.3,0.41,0.29),(20160101,0.3,0.41,0.29),(20160201,0.26,0.36,0.38),(20160301,0.26,0.36,0.38),(20160401,0.26,0.36,0.38),(20160501,0.26,0.36,0.38),(20160601,0.26,0.36,0.38),(20160701,0.26,0.36,0.38),(20160801,0.26,0.36,0.38),(20160901,0.26,0.36,0.38),(20161001,0.26,0.36,0.38),(20161101,0.26,0.36,0.38),(20161201,0.26,0.36,0.38),(20170101,0.26,0.36,0.38),(20170201,0.2,0.3,0.5),(20170301,0.2,0.3,0.5),(20170401,0.2,0.3,0.5),(20170501,0.2,0.3,0.5),(20170601,0.2,0.3,0.5),(20170701,0.2,0.3,0.5),(20170801,0.2,0.3,0.5),(20170901,0.2,0.3,0.5),(20171001,0.2,0.3,0.5),(20171101,0.2,0.3,0.5),(20171201,0.2,0.3,0.5),(20180101,0.2,0.3,0.5),(20180201,0.13,0.37,0.5),(20180301,0.13,0.37,0.5),(20180401,0.13,0.37,0.5),(20180501,0.13,0.37,0.5),(20180601,0.13,0.37,0.5),(20180701,0.13,0.37,0.5),(20180801,0.13,0.37,0.5),(20180901,0.13,0.37,0.5),(20181001,0.13,0.37,0.5),(20181101,0.13,0.37,0.5),(20181201,0.13,0.37,0.5),(20190101,0.13,0.37,0.5),(20190201,0.1,0.4,0.5),(20190301,0.1,0.4,0.5),(20190401,0.1,0.4,0.5),(20190501,0.1,0.4,0.5),(20190601,0.1,0.4,0.5),(20190701,0.1,0.4,0.5),(20190801,0.1,0.4,0.5),(20190901,0.1,0.4,0.5),(20191001,0.1,0.4,0.5),(20191101,0.1,0.4,0.5),(20191201,0.1,0.4,0.5),(20200101,0.1,0.4,0.5)]
     self.yValueAxis.requiredRange = None
     self.yValueAxis.leftAxisPercent = 0
     self.yValueAxis.leftAxisOrigShiftMin = 0
     self.yValueAxis.leftAxisOrigShiftIPC = 0
     self.lines[0].strokeColor = colors.toColor(0x0033cc)
     self.lines[1].strokeColor = colors.toColor(0x99c3ff)
     self.lines[2].strokeColor = colors.toColor(0xCC0033)
Example #4
0
def get_color_as_hexa(str_value, default='#000000'):
    value = str_value.strip()
    if value.startswith('rgb'):
        value = value.lstrip('rgb(').rstrip(')').split(',')
        value = [ int(i) for i in value ]
        tmp = []
        if len(value) == 3:
            # RGB
            for i in value:
                if i < 256:
                    tmp.append('%02x' % i)
                else:
                    print '(WW) the color "%s" is not well formed ' % str_value
                    return default
        value = '#%s' % ''.join(tmp)
    elif value.startswith('#'):
        value_length = len(value)
        if value_length == 4:
            # #aba -> #aabbaa
            r = value[1] * 2
            g = value[2] * 2
            b = value[3] * 2
            value = '#%s%s%s' % (r, g, b)
        elif value_length != 7:
            print '(WW) the color "%s" is not well formed ' % str_value
    else:
        # Warning getAllNamedColors() uses a singleton
        value = ('#%02x%02x%02x' %
                 colors.toColor(value, colors.black).bitmap_rgb())
    return value
Example #5
0
def getColor(value, default=None):
    """
    Convert to color value.
    This returns a Color object instance from a text bit.
    """

    if isinstance(value, Color):
        return value
    value = str(value).strip().lower()
    if value == "transparent" or value == "none":
        return default
    if value in COLOR_BY_NAME:
        return COLOR_BY_NAME[value]
    if value.startswith("#") and len(value) == 4:
        value = "#" + value[1] + value[1] + \
            value[2] + value[2] + value[3] + value[3]
    elif rgb_re.search(value):
        # e.g., value = "<css function: rgb(153, 51, 153)>", go figure:
        r, g, b = [int(x) for x in rgb_re.search(value).groups()]
        value = "#%02x%02x%02x" % (r, g, b)
    else:
        # Shrug
        pass

    return toColor(value, default)  # Calling the reportlab function
Example #6
0
def getCaptcha(n=5,fontName='Courier',fontSize=14,text=None,fillColor=None):
    '''return n random chars in a string and in a byte string structured
    as a GIF image'''
    from reportlab.graphics.shapes import Drawing, Group, String, \
        rotate, skewX, skewY, mmult, translate, Rect
    if not text:
        from random import randint, uniform
        text=''.join([_allowed[randint(0,_mx)] for i in range(n)])
    else:
        uniform = lambda l,h: 0.5*(l+h)
        n = len(text)
    baseline = 0
    x = 0
    G0 = Group()
    for c in text:
        x += 1
        A = translate(x,uniform(baseline-5,baseline+5))
        A = mmult(A,rotate(uniform(-15,15)))
        A = mmult(A,skewX(uniform(-8,8)))
        A = mmult(A,skewY(uniform(-8,8)))
        G = Group(transform=A)
        G.add(String(0,0,c,fontname=fontName,fontSize=fontSize))
        G0.add(G)
        x0,y0,x1,y1 = G0.getBounds()
        x = 1+x1
    G0.transform=translate(2-x0,2-y0)
    W = 4+x1-x0
    H = 4+y1-y0
    D = Drawing(W,H)
    if fillColor:
        from reportlab.lib.colors import toColor
        D.add(Rect(0,0,W,H, fillColor = toColor(fillColor),strokeColor=None))
    D.add(G0)
    return text, D.asString('gif')
Example #7
0
    def _rgbFind(self,color):
        "see if it matches any existing color in my list"
        C = self.cmykColors
        if isinstance(color,(list,tuple)):
            if len(color)==3: color = Color(color[0],color[1],color[2])
            elif len(color)==4: color = CMYKColor(color[0],color[1],color[2],color[3])
            else: raise ValueError("bad color %s"%repr(color))
        isCMYK = isinstance(color, CMYKColor)
        if not isCMYK:
            if isinstance(color,str):
                color = toColor(color)
            if colorDistance(color,black)<1e-8:
                isCMYK = 1
                color = PCMYKColor(0,0,0,100,100)
            elif colorDistance(color,white)<1e-8:
                isCMYK = 1
                color = PCMYKColor(0,0,0,0,100)
        rgb = color.red, color.green, color.blue
        if isCMYK:
            if color not in C: C.append(color)
            return self._setCMYKColor(color)
        else:
            for c in C:
                if (c.red, c.green, c.blue) == rgb:
                    return self._setCMYKColor(c)

        return '%s setrgbcolor' % fp_str(rgb)
Example #8
0
 def setFillColor(self, aColor, alpha=None):
     """Takes a color object, allowing colors to be referred to by name"""
     if self._enforceColorSpace:
         aColor = self._enforceColorSpace(aColor)
     if isinstance(aColor, CMYKColor):
         d = aColor.density
         c,m,y,k = (d*aColor.cyan, d*aColor.magenta, d*aColor.yellow, d*aColor.black)
         self._fillColorObj = aColor
         name = self._checkSeparation(aColor)
         if name:
             self._code.append('/%s cs %s scn' % (name,fp_str(d)))
         else:
             self._code.append('%s k' % fp_str(c, m, y, k))
     elif isinstance(aColor, Color):
         rgb = (aColor.red, aColor.green, aColor.blue)
         self._fillColorObj = aColor
         self._code.append('%s rg' % fp_str(rgb) )
     elif isinstance(aColor,(tuple,list)):
         l = len(aColor)
         if l==3:
             self._fillColorObj = aColor
             self._code.append('%s rg' % fp_str(aColor) )
         elif l==4:
             self._fillColorObj = aColor
             self._code.append('%s k' % fp_str(aColor))
         else:
             raise ValueError('Unknown color %r' % aColor)
     elif isStr(aColor):
         self.setFillColor(toColor(aColor))
     else:
         raise ValueError('Unknown color %r' % aColor)
     if alpha is not None:
         self.setFillAlpha(alpha)
     elif getattr(aColor, 'alpha', None) is not None:
         self.setFillAlpha(aColor.alpha)
    def test2(self):
        "Test toColor function on half a dozen ways to say 'red'."

        allRed = [colors.red, [1, 0, 0], (1, 0, 0), "red", "RED", "0xFF0000", "0xff0000"]

        for thing in allRed:
            assert colors.toColor(thing) == colors.red
Example #10
0
 def setStrokeColor(me, aColor):
     color = toColor( aColor)
     if color:
         me._strokeColorRGB = color.bitmap_rgb()
         me._set_pen()
     else:
         raise 'Unknown color', str(aColor)
Example #11
0
 def __init__(self, width, height, caption="",
              captionFont="Times-Italic", captionSize=12,
              background=None,
              captionTextColor=toColor('black'),
              captionBackColor=None,
              border=1,
              spaceBefore=12,
              spaceAfter=12,
              captionGap=None,
              ):
     Flowable.__init__(self)
     self.width = width
     self.figureHeight = height
     self.caption = caption
     self.captionFont = captionFont
     self.captionSize = captionSize
     self.captionTextColor = captionTextColor
     self.captionBackColor = captionBackColor
     self.captionGap = captionGap
     self._captionData = None
     self.captionHeight = 0  # work out later
     self.background = background
     self.border = border
     self.spaceBefore = spaceBefore
     self.spaceAfter = spaceAfter
Example #12
0
def _setCellStyle(cellStyles, i, j, op, values):
    #new = CellStyle('<%d, %d>' % (i,j), cellStyles[i][j])
    #cellStyles[i][j] = new
    ## modify in place!!!
    new = cellStyles[i][j]
    if op == 'FONT':
        n = len(values)
        new.fontname = values[0]
        if n>1:
            new.fontsize = values[1]
            if n>2:
                new.leading = values[2]
            else:
                new.leading = new.fontsize*1.2
    elif op in ('FONTNAME', 'FACE'):
        new.fontname = values[0]
    elif op in ('SIZE', 'FONTSIZE'):
        new.fontsize = values[0]
    elif op == 'LEADING':
        new.leading = values[0]
    elif op == 'TEXTCOLOR':
        new.color = colors.toColor(values[0], colors.Color(0,0,0))
    elif op in ('ALIGN', 'ALIGNMENT'):
        new.alignment = values[0]
    elif op == 'VALIGN':
        new.valign = values[0]
    elif op == 'LEFTPADDING':
        new.leftPadding = values[0]
    elif op == 'RIGHTPADDING':
        new.rightPadding = values[0]
    elif op == 'TOPPADDING':
        new.topPadding = values[0]
    elif op == 'BOTTOMPADDING':
        new.bottomPadding = values[0]
 def __init__(self, width, height, caption="",
              captionFont=_baseFontNameI, captionSize=12,
              background=None,
              captionTextColor=toColor('black'),
              captionBackColor=None,
              border=None,
              spaceBefore=12,
              spaceAfter=12,
              captionGap=None,
              captionAlign='centre',
              captionPosition='bottom',
              hAlign='CENTER',
              ):
     Flowable.__init__(self)
     self.width = width
     self.figureHeight = height
     self.caption = caption
     self.captionFont = captionFont
     self.captionSize = captionSize
     self.captionTextColor = captionTextColor
     self.captionBackColor = captionBackColor
     self.captionGap = captionGap or 0.5*captionSize
     self.captionAlign = captionAlign
     self.captionPosition = captionPosition
     self._captionData = None
     self.captionHeight = 0  # work out later
     self.background = background
     self.border = border
     self.spaceBefore = spaceBefore
     self.spaceAfter = spaceAfter
     self.hAlign=hAlign
     self._getCaptionPara()  #Larry Meyn's fix - otherwise they all get the number of the last chapter.
Example #14
0
    def __init__(self, width, height, caption="",
                 captionFont="Times-Italic", captionSize=12,
                 background=None,
                 captionTextColor=toColor('black'),
                 captionBackColor=None,
                 border=1,
                 spaceBefore=12,
                 spaceAfter=12,
                 captionGap=None,
                 ):
        Flowable.__init__(self)
        self.width = width
        self.figureHeight = height
        self.caption = caption
        self.captionFont = captionFont
        self.captionSize = captionSize
        self.captionTextColor = captionTextColor
        self.captionBackColor = captionBackColor
        self.captionGap = captionGap
        self._captionData = None
        self.captionHeight = 0  # work out later
        self.background = background
        self.border = border
        self.spaceBefore = spaceBefore
        self.spaceAfter = spaceAfter

        self._getCaptionPara()  #Larry Meyn's fix - otherwise they all get the number of the last chapter.
 def setStrokeColor(self, aColor, alpha=None):
     """Takes a color object, allowing colors to be referred to by name"""
     if self._enforceColorSpace:
         aColor = self._enforceColorSpace(aColor)
     if isinstance(aColor, CMYKColor):
         d = aColor.density
         c, m, y, k = (d * aColor.cyan, d * aColor.magenta, d * aColor.yellow, d * aColor.black)
         self._strokeColorObj = aColor
         name = self._checkSeparation(aColor)
         if name:
             self._code.append("/%s CS %s SCN" % (name, fp_str(d)))
         else:
             self._code.append("%s K" % fp_str(c, m, y, k))
     elif isinstance(aColor, Color):
         rgb = (aColor.red, aColor.green, aColor.blue)
         self._strokeColorObj = aColor
         self._code.append("%s RG" % fp_str(rgb))
     elif isinstance(aColor, (tuple, list)):
         l = len(aColor)
         if l == 3:
             self._strokeColorObj = aColor
             self._code.append("%s RG" % fp_str(aColor))
         elif l == 4:
             self._fillColorObj = aColor
             self._code.append("%s K" % fp_str(aColor))
         else:
             raise ValueError("Unknown color %r" % aColor)
     elif isinstance(aColor, basestring):
         self.setStrokeColor(toColor(aColor))
     else:
         raise ValueError("Unknown color %r" % aColor)
     if alpha is not None:
         self.setStrokeAlpha(alpha)
     elif getattr(aColor, "alpha", None) is not None:
         self.setStrokeAlpha(aColor.alpha)
Example #16
0
 def __init__(self,width=224,height=124,*args,**kw):
     Drawing.__init__(self,width,height,*args,**kw)
     points = [122.0, 87.0, 122.0, 88.0, 123.0, 88.0, 123.0, 89.0, 124.0, 89.0, 124.0, 90.0, 126.0, 90.0, 126.0, 89.0, 128.0, 88.0, 128.0, 89.0, 129.0, 89.0, 129.0, 91.0, 128.0, 91.0, 128.0, 92.0, 130.0, 99.0, 130.0, 100.0, 129.0, 100.0, 126.0, 103.0, 125.0, 103.0, 125.0, 104.0, 126.0, 106.0, 130.0, 87.0, 129.0, 87.0, 129.0, 86.0, 126.0, 86.0, 126.0, 87.0]
     grp = Group(Polygon(points, fillColor=toColor('red')))
     grp.scale(1, -1)
     grp.translate(0, -124)
     self.add(grp)
Example #17
0
    def translate(self, color=None, colour=None):
        """ translate(self, color)

            o color    Color defined as an int, a tuple of three ints 0->255
                       or a tuple of three floats 0 -> 1, or a string giving
                       one of the named colors defined by ReportLab, or a
                       ReportLab color object (returned as is).

                       (This argument is overridden by a backwards compatible
                       argument with UK spelling, colour).

            Returns a colors.Color object, determined semi-intelligently
            depending on the input values
        """
        #Let the UK spelling (colour) override the USA spelling (color)
        if colour is not None:
            color = colour

        if color is None:
            raise ValueError("Passed color (or colour) must be a valid color type")
        elif isinstance(color, int):
            color = self.scheme_color(color)
        elif isinstance(color, colors.Color):
            return color
        elif isinstance(color, basestring):
            #Assume its a named reportlab color like "red".
            color = colors.toColor(color)
        elif isinstance(color, tuple) and isinstance(color[0], float):
            color = self.float1_color(color)
        elif isinstance(color, tuple) and isinstance(color[0], int):
            color = self.int255_color(color)
        return color
Example #18
0
 def setFillColor(me, aColor):
     """Takes a color object, allowing colors to be referred to by name"""
     color = toColor( aColor)
     if color:
         me.recorder.SetTextForeground( *color.bitmap_rgb())
     else:
         raise 'Unknown color', str(aColor)
Example #19
0
def _toColor(s):
    from reportlab.lib.colors import toColor
    if s in ['','none','None',None]:
        return None
    try:
        return toColor(s)
    except:
        raise ValueError('Bad color value %r' % s)
    def test2(self):
        "Test toColor function on half a dozen ways to say 'red'."

        allRed = [colors.red, [1, 0, 0], (1, 0, 0),
                  'red', 'RED', '0xFF0000', '0xff0000','rgb(255,0,0)']

        for thing in allRed:
            assert colors.toColor(thing) == colors.red,"colors.toColor(%s)-->%s != colors.red(%s)" % (ascii(thing),ascii(colors.toColor(thing)),colors.red)
Example #21
0
    def setFillColor(me, aColor):
        '''Takes a color object, allowing colors to be referred to by name'''

        color = toColor( aColor)
        if color:
            me._fillColorRGB = color.bitmap_rgb()
            me._set_brush()
        else:
            raise 'Unknown color', str(aColor)
    def drawBackground(self, canv):
        color = toColor(self.background)

        canv.saveState()
        canv.setFillColor(color)
        canv.rect(
            self._x1, self._y1, self._x2 - self._x1, self._y2 - self._y1,
            stroke=0, fill=1
        )
        canv.restoreState()
 def drawBackground(self):
     """For use when using a figure on a differently coloured background.
     Allows you to specify a colour to be used as a background for the figure."""
     if isColor(self.background):
         self._doBackground(self.background)
     else:
         try:
             c = toColor(self.background)
             self._doBackground(c)
         except:
             pass
Example #24
0
def toColor(color):
    """ Convert a color string to an internal representation """
    if type(color) is unicode:
        color = color.encode("utf-8")

    try:
        c = colors.toColor(color)
    except:
        Warning("Color not found '%s'" % c)
        # Set to black
        c = colors.Color(0, 0, 0)

    return c
 def subStory(texts,fbg=0):
     style = [
         ('VALIGN',(0,0),(-1,-1),'TOP'),
         ('INNERGRID', (0,0), (-1,-1), 0.25, black),
         ('BOX', (0,0), (-1,-1), 0.25, black),
         ]
     if fbg:
         fbg1 = [FrameBG(start=0,color=toColor('limegreen'))]
         fbg0 = [FrameBG(start=0)]
     else:
         fbg0 = fbg1 = []
     return ([Paragraph(t,bt) for t in texts]
             +fbg1+[Table([('alignment', a.lower())],style = style,hAlign=a)
                 for a in ('LEFT','RIGHT','CENTER')]+fbg0)
Example #26
0
    def _drawBkgrnd(self):
        nrows = self._nrows
        ncols = self._ncols
        for cmd, (sc, sr), (ec, er), arg in self._bkgrndcmds:
            if sc < 0: sc = sc + ncols
            if ec < 0: ec = ec + ncols
            if sr < 0: sr = sr + nrows
            if er < 0: er = er + nrows
            x0 = self._colpositions[sc]
            y0 = self._rowpositions[sr]
            x1 = self._colpositions[min(ec+1,ncols)]
            y1 = self._rowpositions[min(er+1,nrows)]
            w, h = x1-x0, y1-y0
            canv = self.canv
            if callable(arg):
                apply(arg,(self,canv, x0, y0, w, h))
            elif cmd == 'ROWBACKGROUNDS':
                #Need a list of colors to cycle through.  The arguments
                #might be already colours, or convertible to colors, or
                # None, or the string 'None'.
                #It's very common to alternate a pale shade with None.
                #print 'rowHeights=', self._rowHeights
                colorCycle = map(colors.toColorOrNone, arg)
                count = len(colorCycle)
                rowCount = er - sr + 1
                for i in range(rowCount):
                    color = colorCycle[i%count]
                    h = self._rowHeights[sr + i]
                    if color:
                        canv.setFillColor(color)
                        canv.rect(x0, y0, w, -h, stroke=0,fill=1)
                    #print '    draw %0.0f, %0.0f, %0.0f, %0.0f' % (x0,y0,w,-h)
                    y0 = y0 - h

            elif cmd == 'COLBACKGROUNDS':
                #cycle through colours columnwise
                colorCycle = map(colors.toColorOrNone, arg)
                count = len(colorCycle)
                colCount = ec - sc + 1
                for i in range(colCount):
                    color = colorCycle[i%count]
                    w = self._colWidths[sc + i]
                    if color:
                        canv.setFillColor(color)
                        canv.rect(x0, y0, w, h, stroke=0,fill=1)
                    x0 = x0 +w
            else:   #cmd=='BACKGROUND'
                canv.setFillColor(colors.toColor(arg))
                canv.rect(x0, y0, w, h, stroke=0,fill=1)
Example #27
0
 def drawBoundary(self,canv):
     "draw the frame boundary as a rectangle (primarily for debugging)."
     from reportlab.lib.colors import Color, CMYKColor, toColor
     sb = self.showBoundary
     isColor = type(sb) in (type(''),type(()),type([])) or isinstance(sb,Color)
     if isColor:
         sb = toColor(sb,self)
         if sb is self: isColor = 0
         else:
             canv.saveState()
             canv.setStrokeColor(sb)
     canv.rect(
             self._x1,
             self._y1,
             self._x2 - self._x1,
             self._y2 - self._y1
             )
     if isColor: canv.restoreState()
Example #28
0
def _preview(d,preview):
    '''create a device dependent preview image from drawing d'''
    from reportlab.graphics import renderPM
    if isinstance(preview,(int,float)):
        assert preview>0, "negative scaling is forbidden"
        g = d
        d = Drawing(g.width*preview, g.height*preview)
        g.transform = (preview,0,0,preview,0,0) #scale so it fits
        d.add(g)
    pilf = getBytesIO()
    transparent = getattr(g,'preview_transparent',None) or rl_config.eps_preview_transparent
    kwds = dict(fmt='TIFF')
    if transparent:
        configPIL = {}
        bg = configPIL['transparent'] = toColor(transparent)
        kwds['configPIL'] = configPIL
        kwds['bg'] = bg.int_rgb()
    renderPM.drawToFile(d,pilf,**kwds)
    return pilf.getvalue()
Example #29
0
def _toColor(arg, default=None):
    '''try to map an arbitrary arg to a color instance'''
    if isinstance(arg, Color): return arg
    tArg = type(arg)
    if tArg in (types.ListType, types.TupleType):
        assert 3 <= len(arg) <= 4, 'Can only convert 3 and 4 sequences to color'
        assert 0 <= min(arg) and max(arg) <= 1
        return len(arg) == 3 and Color(arg[0], arg[1], arg[2]) or CMYKColor(arg[0], arg[1], arg[2], arg[3])
    elif tArg == types.StringType:
        C = getAllNamedColors()
        s = arg.lower()
        if C.has_key(s): return C[s]
        try:
            return toColor(eval(arg))
        except:
            pass
    try:
        return HexColor(arg)
    except:
        if default is None:
            raise ValueError('Invalid color value %r' % arg)
        return default
Example #30
0
 def setStrokeColor(self, aColor):
     """Takes a color object, allowing colors to be referred to by name"""
     if isinstance(aColor, CMYKColor):
         d = aColor.density
         c,m,y,k = (d*aColor.cyan, d*aColor.magenta, d*aColor.yellow, d*aColor.black)
         self._strokeColorCMYK = (c, m, y, k)
         self._code.append('%s K' % fp_str(c, m, y, k))
     elif isinstance(aColor, Color):
         rgb = (aColor.red, aColor.green, aColor.blue)
         self._strokeColorRGB = rgb
         self._code.append('%s RG' % fp_str(rgb) )
     elif type(aColor) in _SeqTypes:
         l = len(aColor)
         if l==3:
             self._strokeColorRGB = aColor
             self._code.append('%s RG' % fp_str(aColor) )
         elif l==4:
             self.setStrokeColorCMYK(aColor[0], aColor[1], aColor[2], aColor[3])
         else:
             raise 'Unknown color', str(aColor)
     elif type(aColor) is StringType:
         self.setStrokeColor(toColor(aColor))
     else:
         raise 'Unknown color', str(aColor)
Example #31
0
def main():
    LP = tuple(
        enumerate((None, 'top', 'top_right', 'right', 'bottom_right', 'bottom',
                   'bottom_left', 'left', 'top_left')))
    HLEGS = tuple(enumerate((None, False, True)))
    LEGENDMODES = tuple(enumerate((None, 'fullWidth', 'fullHeight')))
    ALLOWED_CHART_TYPES.sort()
    html = []
    for chartType in ALLOWED_CHART_TYPES:
        makeDrawing(html, '', chartType=chartType)

    makeDrawing(html,
                "0.1 Line chart should have both x and y gridlines",
                chartType='linechart',
                yAxisVisible=1,
                yAxisGridLines=1,
                xAxisVisible=1,
                xAxisGridLines=1)
    makeDrawing(html,
                "0.11 Line plot should have both x and y gridlines",
                chartType='lineplot',
                yAxisVisible=1,
                yAxisGridLines=1,
                xAxisVisible=1,
                xAxisGridLines=1,
                data=[[1.5, 3, 4.5], [1, 2, 3], [1.5, 2.5, 3.5]])
    makeDrawing(
        html,
        "0.12 0.1+yAxisLabelTextFormat='$%(decfmt(value*10000,2,'.',''))s'",
        chartType='linechart',
        yAxisVisible=1,
        yAxisGridLines=1,
        xAxisVisible=1,
        xAxisGridLines=1,
        yAxisLabelTextFormat="$%(decfmt(value*10000,2,'.',''))s")
    makeDrawing(
        html,
        "0.13 0.1+yAxisLabelTextFormat='$%(decfmt(value*10000,-2,'.',','))s'",
        chartType='linechart',
        yAxisVisible=1,
        yAxisGridLines=1,
        xAxisVisible=1,
        xAxisGridLines=1,
        yAxisLabelTextFormat="$%(decfmt(value*10000,-2,'.',','))s")
    makeDrawing(
        html,
        "0.14 0.1+yAxisLabelTextFormat='$%(decfmt(value*10000,(1 if notAllInt else 0),'.',','))s'",
        chartType='linechart',
        yAxisVisible=1,
        yAxisGridLines=1,
        xAxisVisible=1,
        xAxisGridLines=1,
        yAxisLabelTextFormat=
        "$%(decfmt(value*10000,(1 if notAllInt else 0),'.',','))s")
    makeDrawing(
        html,
        "0.15 0.1+yAxisLabelTextFormat='$%(decfmt(value*10000,2,',','.'))s'",
        chartType='linechart',
        yAxisVisible=1,
        yAxisGridLines=1,
        xAxisVisible=1,
        xAxisGridLines=1,
        yAxisLabelTextFormat="$%(decfmt(value*10000,2,',','.'))s")

    makeDrawing(
        html,
        '1.1 Clustered_bar with the yAxisVisible and yAxisGridlines on',
        chartType='clustered_bar',
        yAxisVisible=1,
        yAxisGridLines=1,
        xAxisVisible=0)
    makeDrawing(html,
                '1.2 Stacked_bar with the yAxisVisible and yAxisGridlines on',
                chartType='stacked_bar',
                yAxisVisible=1,
                yAxisGridLines=1,
                xAxisVisible=0)

    makeDrawing(
        html,
        '1.3 Clustered_bar with the xAxisVisible and xAxisGridlines on',
        chartType='clustered_bar',
        xAxisVisible=1,
        xAxisGridLines=1,
        yAxisVisible=0)
    makeDrawing(html,
                '1.4 Stacked_bar with the xAxisVisible and xAxisGridlines on',
                chartType='stacked_bar',
                xAxisVisible=1,
                xAxisGridLines=1,
                yAxisVisible=0)

    makeDrawing(
        html,
        '2.1 Clustered_bar with both the x Axis and y Axis invisible - should resize correctly',
        chartType='stacked_bar',
        xAxisVisible=0,
        yAxisVisible=0,
        showBoundaries=1)
    makeDrawing(
        html,
        '2.2 Stacked_bar with both the x Axis and y Axis invisible - should resize correctly',
        chartType='clustered_bar',
        xAxisVisible=0,
        yAxisVisible=0,
        showBoundaries=1)

    makeDrawing(html,
                '3.1 Stacked_bar with dataLabelsType set to None',
                chartType='stacked_bar',
                dataLabelsType=None)
    makeDrawing(html,
                '3.2 Clustered_bar with dataLabelsType set to None',
                chartType='clustered_bar',
                dataLabelsType=None)
    makeDrawing(html,
                '3.3 Pie with dataLabelsType set to None',
                chartType='pie',
                dataLabelsType=None)

    makeDrawing(html,
                "3.4 Stacked_bar with dataLabelsType set to 'values'",
                chartType='stacked_bar',
                dataLabelsType='values')
    makeDrawing(html,
                "3.5 Clustered_bar with dataLabelsType set to 'values'",
                chartType='clustered_bar',
                dataLabelsType='values')
    makeDrawing(html,
                "3.6 Pie with dataLabelsType set to 'values'",
                chartType='pie',
                dataLabelsType='values')

    makeDrawing(html,
                "3.7 Stacked_bar with dataLabelsType set to 'percent'",
                chartType='stacked_bar',
                dataLabelsType='percent')
    makeDrawing(html,
                "3.8 Clustered_bar with dataLabelsType set to 'percent'",
                chartType='clustered_bar',
                dataLabelsType='percent')
    makeDrawing(html,
                "3.9 Pie with dataLabelsType set to 'percent'",
                chartType='pie',
                dataLabelsType='percent')
    makeDrawing(html,
                "3.71 Stacked_bar with dataLabelsType set to 'percent,2'",
                chartType='stacked_bar',
                dataLabelsType='percent,2')
    makeDrawing(html,
                "3.81 Clustered_bar with dataLabelsType set to 'percent,2'",
                chartType='clustered_bar',
                dataLabelsType='percent,2')
    makeDrawing(html,
                "3.91 Pie with dataLabelsType set to 'percent,2'",
                chartType='pie',
                dataLabelsType='percent,2')
    makeDrawing(
        html,
        "3.72 Stacked_bar with dataLabelsType set to '%(percent).1f%%'",
        chartType='stacked_bar',
        dataLabelsType='%(percent).1f%%')
    makeDrawing(
        html,
        "3.82 Clustered_bar with dataLabelsType set to '%(percent).2f%%'",
        chartType='clustered_bar',
        dataLabelsType='%(percent).2f%%')
    makeDrawing(
        html,
        "3.92 Pie with dataLabelsType set to '%(percent).3f%% per Annum'",
        chartType='pie',
        dataLabelsType='%(percent).3f%% per Annum')
    makeDrawing(
        html,
        "3.73 Stacked_bar with dataLabelsType set to '$%(decfmt(value*10000,2,'.',''))s'",
        chartType='stacked_bar',
        dataLabelsType='$%(decfmt(value*10000,2,\'.\',\'\'))s')
    makeDrawing(
        html,
        "3.74 Stacked_bar with dataLabelsType set to '$%(decfmt(value*10000,2,'.',','))s'",
        chartType='stacked_bar',
        dataLabelsType='$%(decfmt(value*10000,2,\'.\',\',\'))s')
    makeDrawing(
        html,
        "3.83 Clustered_bar with dataLabelsType set to '$%(decfmt(value*14000,2,',','.'))s'",
        chartType='clustered_bar',
        dataLabelsType='$%(decfmt(value*14000,1,\',\',\'.\'))s')
    makeDrawing(
        html,
        "3.93 Pie with dataLabelsType set to '$%(decfmt(value*12000,2))s/Year'",
        chartType='pie',
        dataLabelsType='$%(decfmt(value*12000,2))s/Year')

    makeDrawing(
        html,
        "4.1 Pie with dataLabelsType unset - no datalabels should be printed",
        chartType='pie')
    makeDrawing(
        html,
        "4.2 Pie with dataLabelsType set to 'values' - values should be used for dataLabels",
        chartType='pie',
        dataLabelsType='values')
    makeDrawing(
        html,
        "4.3 Pie with dataLabelsType set to 'percent' - percentages should be used for dataLabels",
        chartType='pie',
        dataLabelsType='percent')
    makeDrawing(
        html,
        "4.4 Pie with with category names - set dataLabelsType '%(category)s'",
        chartType='pie',
        dataLabelsType='%(category)s',
        categoryNames=['A', 'B', 'C', 'D'])

    makeDrawing(html,
                "4.5.0 Pie with overlap",
                chartType='pie',
                dataLabelsType='%(percent).3f%% per Annum',
                data=[0.9, 1.1, 2.2, 40, 57],
                categoryNames=['0.9', '1.1', '2.2', '40', '57'])
    makeDrawing(html,
                "4.5.1 Pie with overlap orderMode='alternate'",
                chartType='pie',
                orderMode='alternate',
                dataLabelsType='%(percent).3f%% per Annum',
                data=[0.9, 1.1, 2.2, 40, 57],
                categoryNames=['0.9', '1.1', '2.2', '40', '57'])
    makeDrawing(html,
                "4.5.2 Pie with overlap checkLabelOverlap=1",
                chartType='pie',
                checkLabelOverlap=1,
                dataLabelsType='%(percent).3f%% per Annum',
                data=[0.9, 1.1, 2.2, 40, 57],
                categoryNames=['0.9', '1.1', '2.2', '40', '57'])
    makeDrawing(
        html,
        "4.5.3 Pie with overlap orderMode='alternate' checkLabelOverlap=1",
        chartType='pie',
        checkLabelOverlap=1,
        orderMode='alternate',
        dataLabelsType='%(percent).3f%% per Annum',
        data=[0.9, 1.1, 2.2, 40, 57],
        categoryNames=['0.9', '1.1', '2.2', '40', '57'])

    makeDrawing(html,
                "5.1 Title should be (ascent * 1.5) from the font base line ",
                chartType='pie',
                titleText="This is the Title")

    makeDrawing(
        html,
        "6.1 Bar with integer data - axis should display without decimals",
        chartType='bar',
        data=[[100, 200, 300, 400]],
        xAxisVisible=1,
        yAxisVisible=1)
    makeDrawing(
        html,
        "6.2 Column with integer data - axis should display without decimals",
        chartType='column',
        data=[[100, 200, 300, 400]],
        xAxisVisible=1,
        yAxisVisible=1)
    makeDrawing(
        html,
        "6.3 Bar with floating point data - axis should display with decimals",
        chartType='bar',
        data=[[0.01, 0.02, 0.03, 0.04]],
        xAxisVisible=1,
        yAxisVisible=1)
    makeDrawing(
        html,
        "6.4 Bar with floating point data - axis should display with decimals",
        chartType='column',
        data=[[0.01, 0.02, 0.03, 0.04]],
        xAxisVisible=1,
        yAxisVisible=1)

    makeDrawing(html,
                "7.1 x Axis and y Axis gridlines should be the same width",
                chartType='bar',
                xAxisVisible=1,
                yAxisVisible=1,
                xAxisGridLines=1,
                yAxisGridLines=1)
    makeDrawing(html,
                "7.2 x Axis and y Axis gridlines should be the same width",
                chartType='column',
                xAxisVisible=1,
                yAxisVisible=1,
                xAxisGridLines=1,
                yAxisGridLines=1)

    makeDrawing(
        html,
        "8.1 When using data = [[120,20]], the value axis should no longer show negative values of (-50,0,50,100,150)",
        chartType='column',
        data=[[120, 20]])
    makeDrawing(
        html,
        "8.1a When using data = [[120,20]], the value axis should no longer show negative values of (-50,0,50,100,150)",
        chartType='bar',
        data=[[120, 20]])
    makeDrawing(
        html,
        "8.2 When using negative data the gridline of the category axis should be correctly sized",
        chartType='column',
        data=[[-120, -20, 20]],
        xAxisGridLines=1)
    makeDrawing(
        html,
        "8.2a When using negative data the gridline of the category axis should be correctly sized",
        chartType='bar',
        data=[[-120, -20, 20]],
        yAxisGridLines=1)

    for k, legendMode in LEGENDMODES:
        for j, hleg in HLEGS:
            for i, p in LP:
                makeDrawing(
                    html,
                    "9.1.%d.%d.%d Blue border round background, no fill on background legendPos=%s hleg=%s legendMode=%s"
                    % (k, j, i, p, hleg, legendMode),
                    chartType='column',
                    bgColor=None,
                    bgStrokeColor='blue',
                    seriesNames=('A long series name',
                                 'Another very long series name'),
                    legendPos=p,
                    hleg=hleg,
                    legendMaxWFrac=0.5,
                    legendMaxHFrac=0.5,
                    legendMode=legendMode)
    makeDrawing(html,
                "9.2 Blue border round background, yellow fill on background",
                chartType='bar',
                bgColor='yellow',
                bgStrokeColor='blue')

    makeDrawing(
        html,
        "10.1 Test piechart with data of '[[230,340]]' and dataLabelsType of 'percent' (as per Nardi's test)",
        chartType='pie',
        data=[[230, 340]],
        categoryNames=['category1', 'category2'],
        seriesNames=[],
        bgColor=None,
        plotColor=CMYKColor(0, 0, 1, 0),
        legendPos='left',
        legendFontName='Helvetica',
        legendFontColor=CMYKColor(0, 0, 0, 2),
        titleText='This is the main title',
        titleFontName='Helvetica-Bold',
        titleFontSize=18,
        titleFontColor=CMYKColor(0, 1, 1, 1),
        dataLabelsType='percent',
        dataLabelsFontName='Helvetica',
        dataLabelsFontSize=14,
        dataLabelsFontColor=CMYKColor(0, 1, 1, 0))
    for k, legendMode in LEGENDMODES:
        for j, hleg in HLEGS:
            for i, p in LP:
                makeDrawing(
                    html,
                    "10.2.%d.%d.%d piechart with more than 10 slices legendPos=%s hleg=%s legendMode=%s"
                    % (k, j, i, p, hleg, legendMode),
                    chartType='exploded_pie',
                    data=[[
                        27.00000, 3.00000, 10.00000, 5.00000, 5.00000,
                        15.00000, 35.00000, 12, 17, 11, 19, 23, 32
                    ]],
                    categoryNames=[
                        'Category 1', 'Category 2', 'Category 3', 'Category 4',
                        'Category 5', 'Category 6', 'Category 7', 'Cat 8',
                        'Cat 9', 'Cat 10', 'Cat 11', 'Cat 12', 'Cat 13'
                    ],
                    seriesNames=[],
                    chartColors=[
                        CMYKColor(0.00, 1.00, 0.00, 0.00),
                        CMYKColor(1.00, 1.00, 0.00, 0.00),
                        CMYKColor(0.00, 0.00, 1.00, 0.00),
                        CMYKColor(0.00, 1.00, 1.00, 0.00),
                        CMYKColor(0.00, 0.80, 1.00, 0.00),
                        CMYKColor(0.00, 0.40, 1.00, 0.00),
                        CMYKColor(0.80, 0.00, 1.00, 0.00),
                        toColor('red'),
                        toColor('grey'),
                        toColor('brown'),
                        toColor('magenta'),
                        toColor('darkblue'),
                        toColor('pink')
                    ],
                    bgColor=None,
                    plotColor=None,
                    legendPos=p,
                    legendFontName='Helvetica',
                    legendFontSize=9.00,
                    legendFontColor=CMYKColor(0.05, 0.45, 1.00, 0.00),
                    titleText='',
                    titleFontName='Helvetica-Bold',
                    titleFontSize=14.00,
                    titleFontColor=CMYKColor(0.00, 0.00, 0.00, 1.00),
                    dataLabelsType='%.1f',
                    dataLabelsFontName='Helvetica',
                    dataLabelsFontSize=9.00,
                    dataLabelsFontColor=CMYKColor(0.05, 0.45, 1.00, 0.00),
                    width=401.54384,
                    height=150.86375,
                    hleg=hleg,
                    legendMaxWFrac=0.5,
                    legendMaxHFrac=0.5,
                    legendMode=legendMode)

    makeDrawing(html,
                "11.1 Test for black lines in 3D exploded piechart",
                chartType='exploded_pie3d',
                data=[[
                    27.00000, 3.00000, 10.00000, 5.00000, 5.00000, 15.00000,
                    35.00000
                ]],
                categoryNames=[
                    'Category 1', 'Category 2', 'Category 3', 'Category 4',
                    'Category 5', 'Category 6', 'Category 7'
                ],
                seriesNames=[],
                chartColors=[
                    CMYKColor(0.00, 1.00, 0.00, 0.00),
                    CMYKColor(1.00, 1.00, 0.00, 0.00),
                    CMYKColor(0.00, 0.00, 1.00, 0.00),
                    CMYKColor(0.00, 1.00, 1.00, 0.00),
                    CMYKColor(0.00, 0.80, 1.00, 0.00),
                    CMYKColor(0.00, 0.40, 1.00, 0.00),
                    CMYKColor(0.80, 0.00, 1.00, 0.00)
                ],
                bgColor=None,
                plotColor=None,
                legendPos='right',
                legendFontName='Helvetica',
                legendFontSize=9.00,
                legendFontColor=CMYKColor(0.05, 0.45, 1.00, 0.00),
                titleText='',
                titleFontName='Helvetica-Bold',
                titleFontSize=14.00,
                titleFontColor=CMYKColor(0.00, 0.00, 0.00, 1.00),
                dataLabelsType='%.1f',
                dataLabelsFontName='Helvetica',
                dataLabelsFontSize=9.00,
                dataLabelsFontColor=CMYKColor(0.05, 0.45, 1.00, 0.00),
                width=401.54384,
                height=150.86375)
    for k, legendMode in LEGENDMODES:
        for j, hleg in HLEGS:
            for i, p in LP:
                makeDrawing(
                    html,
                    "11.2.%d.%d.%d 3D exploded piechart with more than 10 slices legendPos=%s hleg=%s legendMode=%s"
                    % (k, j, i, p, hleg, legendMode),
                    chartType='exploded_pie3d',
                    data=[[
                        27.00000, 3.00000, 10.00000, 5.00000, 5.00000,
                        15.00000, 35.00000, 12, 17, 11, 19, 23, 32
                    ]],
                    categoryNames=[
                        'Category 1', 'Category 2', 'Category 3', 'Category 4',
                        'Category 5', 'Category 6', 'Category 7', 'Cat 8',
                        'Cat 9', 'Cat 10', 'Cat 11', 'Cat 12', 'Cat 13'
                    ],
                    seriesNames=[],
                    chartColors=[
                        CMYKColor(0.00, 1.00, 0.00, 0.00),
                        CMYKColor(1.00, 1.00, 0.00, 0.00),
                        CMYKColor(0.00, 0.00, 1.00, 0.00),
                        CMYKColor(0.00, 1.00, 1.00, 0.00),
                        CMYKColor(0.00, 0.80, 1.00, 0.00),
                        CMYKColor(0.00, 0.40, 1.00, 0.00),
                        CMYKColor(0.80, 0.00, 1.00, 0.00),
                        toColor('red'),
                        toColor('grey'),
                        toColor('brown'),
                        toColor('magenta'),
                        toColor('darkblue'),
                        toColor('pink')
                    ],
                    bgColor=None,
                    plotColor=None,
                    legendPos=p,
                    legendFontName='Helvetica',
                    legendFontSize=9.00,
                    legendFontColor=CMYKColor(0.05, 0.45, 1.00, 0.00),
                    titleText='',
                    titleFontName='Helvetica-Bold',
                    titleFontSize=14.00,
                    titleFontColor=CMYKColor(0.00, 0.00, 0.00, 1.00),
                    dataLabelsType='%.1f',
                    dataLabelsFontName='Helvetica',
                    dataLabelsFontSize=9.00,
                    dataLabelsFontColor=CMYKColor(0.05, 0.45, 1.00, 0.00),
                    width=401.54384,
                    height=150.86375,
                    hleg=hleg,
                    legendMaxWFrac=0.5,
                    legendMaxHFrac=0.5,
                    legendMode=legendMode)
    makeDrawing(
        html,
        "11.211 3D exploded piechart with more than 10 slices legend at top legendMaxHFrac=0.125",
        chartType='exploded_pie3d',
        legendMaxHFrac=0.125,
        data=[[
            27.00000, 3.00000, 10.00000, 5.00000, 5.00000, 15.00000, 35.00000,
            12, 17, 11, 19, 23, 32
        ]],
        categoryNames=[
            'Category 1', 'Category 2', 'Category 3', 'Category 4',
            'Category 5', 'Category 6', 'Category 7', 'Cat 8', 'Cat 9',
            'Cat 10', 'Cat 11', 'Cat 12', 'Cat 13'
        ],
        seriesNames=[],
        chartColors=[
            CMYKColor(0.00, 1.00, 0.00, 0.00),
            CMYKColor(1.00, 1.00, 0.00, 0.00),
            CMYKColor(0.00, 0.00, 1.00, 0.00),
            CMYKColor(0.00, 1.00, 1.00, 0.00),
            CMYKColor(0.00, 0.80, 1.00, 0.00),
            CMYKColor(0.00, 0.40, 1.00, 0.00),
            CMYKColor(0.80, 0.00, 1.00, 0.00),
            toColor('red'),
            toColor('grey'),
            toColor('brown'),
            toColor('magenta'),
            toColor('darkblue'),
            toColor('pink')
        ],
        bgColor=None,
        plotColor=None,
        legendPos='top',
        legendFontName='Helvetica',
        legendFontSize=9.00,
        legendFontColor=CMYKColor(0.05, 0.45, 1.00, 0.00),
        titleText='',
        titleFontName='Helvetica-Bold',
        titleFontSize=14.00,
        titleFontColor=CMYKColor(0.00, 0.00, 0.00, 1.00),
        dataLabelsType='%.1f',
        dataLabelsFontName='Helvetica',
        dataLabelsFontSize=9.00,
        dataLabelsFontColor=CMYKColor(0.05, 0.45, 1.00, 0.00),
        width=401.54384,
        height=150.86375)
    makeDrawing(
        html,
        "11.212 3D exploded piechart with more than 10 slices legend at top legendMaxHFrac=0.09",
        chartType='exploded_pie3d',
        legendMaxHFrac=0.09,
        data=[[
            27.00000, 3.00000, 10.00000, 5.00000, 5.00000, 15.00000, 35.00000,
            12, 17, 11, 19, 23, 32
        ]],
        categoryNames=[
            'Category 1', 'Category 2', 'Category 3', 'Category 4',
            'Category 5', 'Category 6', 'Category 7', 'Cat 8', 'Cat 9',
            'Cat 10', 'Cat 11', 'Cat 12', 'Cat 13'
        ],
        seriesNames=[],
        chartColors=[
            CMYKColor(0.00, 1.00, 0.00, 0.00),
            CMYKColor(1.00, 1.00, 0.00, 0.00),
            CMYKColor(0.00, 0.00, 1.00, 0.00),
            CMYKColor(0.00, 1.00, 1.00, 0.00),
            CMYKColor(0.00, 0.80, 1.00, 0.00),
            CMYKColor(0.00, 0.40, 1.00, 0.00),
            CMYKColor(0.80, 0.00, 1.00, 0.00),
            toColor('red'),
            toColor('grey'),
            toColor('brown'),
            toColor('magenta'),
            toColor('darkblue'),
            toColor('pink')
        ],
        bgColor=None,
        plotColor=None,
        legendPos='top',
        legendFontName='Helvetica',
        legendFontSize=9.00,
        legendFontColor=CMYKColor(0.05, 0.45, 1.00, 0.00),
        titleText='',
        titleFontName='Helvetica-Bold',
        titleFontSize=14.00,
        titleFontColor=CMYKColor(0.00, 0.00, 0.00, 1.00),
        dataLabelsType='%.1f',
        dataLabelsFontName='Helvetica',
        dataLabelsFontSize=9.00,
        dataLabelsFontColor=CMYKColor(0.05, 0.45, 1.00, 0.00),
        width=401.54384,
        height=150.86375)
    makeDrawing(
        html,
        "11.213 3D exploded piechart with more than 10 slices legend at top legendMaxWFrac=0.8",
        chartType='exploded_pie3d',
        legendMaxWFrac=0.8,
        data=[[
            27.00000, 3.00000, 10.00000, 5.00000, 5.00000, 15.00000, 35.00000,
            12, 17, 11, 19, 23, 32
        ]],
        categoryNames=[
            'Category 1', 'Category 2', 'Category 3', 'Category 4',
            'Category 5', 'Category 6', 'Category 7', 'Cat 8', 'Cat 9',
            'Cat 10', 'Cat 11', 'Cat 12', 'Cat 13'
        ],
        seriesNames=[],
        chartColors=[
            CMYKColor(0.00, 1.00, 0.00, 0.00),
            CMYKColor(1.00, 1.00, 0.00, 0.00),
            CMYKColor(0.00, 0.00, 1.00, 0.00),
            CMYKColor(0.00, 1.00, 1.00, 0.00),
            CMYKColor(0.00, 0.80, 1.00, 0.00),
            CMYKColor(0.00, 0.40, 1.00, 0.00),
            CMYKColor(0.80, 0.00, 1.00, 0.00),
            toColor('red'),
            toColor('grey'),
            toColor('brown'),
            toColor('magenta'),
            toColor('darkblue'),
            toColor('pink')
        ],
        bgColor=None,
        plotColor=None,
        legendPos='top',
        legendFontName='Helvetica',
        legendFontSize=9.00,
        legendFontColor=CMYKColor(0.05, 0.45, 1.00, 0.00),
        titleText='',
        titleFontName='Helvetica-Bold',
        titleFontSize=14.00,
        titleFontColor=CMYKColor(0.00, 0.00, 0.00, 1.00),
        dataLabelsType='%.1f',
        dataLabelsFontName='Helvetica',
        dataLabelsFontSize=9.00,
        dataLabelsFontColor=CMYKColor(0.05, 0.45, 1.00, 0.00),
        width=401.54384,
        height=150.86375)
    makeDrawing(html,
                "12.1 xAxisLabelAngle=-70",
                chartType='linechart',
                dataLabelsType='values',
                categoryNames=['Oranges', 'Lemons', 'Apples', 'Pears'],
                xAxisLabelAngle=-70)
    makeDrawing(html,
                "12.2 yAxisLabelAngle=-70",
                chartType='linechart',
                dataLabelsType='values',
                categoryNames=['Oranges', 'Lemons', 'Apples', 'Pears'],
                yAxisLabelAngle=-70)
    makeDrawing(html,
                "12.3 xAxisLabelAngle=70",
                chartType='linechart',
                dataLabelsType='values',
                categoryNames=['Oranges', 'Lemons', 'Apples', 'Pears'],
                xAxisLabelAngle=70)
    makeDrawing(html,
                "12.3 yAxisLabelAngle=70",
                chartType='linechart',
                dataLabelsType='values',
                categoryNames=['Oranges', 'Lemons', 'Apples', 'Pears'],
                yAxisLabelAngle=70)
    makeDrawing(html,
                "13.1 textData",
                chartType='linechart',
                dataLabelsType='values',
                textData="A B C D\na b c d")
    makeDrawing(html,
                "13.2 textData",
                chartType='column',
                dataLabelsType='values',
                textData="A B C D\na b c d")
    makeDrawing(html,
                "13.3 textData",
                chartType='bar',
                dataLabelsType='values',
                textData="A B C D\na b c d")
    makeDrawing(html,
                "14.1 Ron Error Empty Chart",
                chartType='clustered_column',
                data=[[0], [0], [0]],
                categoryNames=['Oct'],
                seriesNames=['Series 1', 'Series  2', 'Series 3'],
                chartColors=[
                    CMYKColor(0.00, 0.20, 0.34, 0.00),
                    CMYKColor(0.00, 0.00, 0.40, 0.00),
                    CMYKColor(0.20, 0.00, 0.09, 0.00)
                ],
                bgColor=None,
                plotColor=None,
                legendPos='right',
                legendFontName='Helvetica',
                legendFontColor=CMYKColor(0.00, 0.00, 0.00, 1.00),
                titleText='Banzai!',
                titleFontName='Helvetica-Bold',
                titleFontColor=CMYKColor(0.00, 0.00, 0.00, 1.00),
                xTitleText='',
                xTitleFontName='Helvetica',
                xTitleFontColor=CMYKColor(0.00, 0.00, 0.00, 1.00),
                yTitleText='',
                yTitleFontName='Helvetica',
                yTitleFontColor=CMYKColor(0.00, 0.00, 0.00, 1.00),
                xAxisVisible=1,
                xAxisLabelAngle=30,
                xAxisFontName='Helvetica',
                xAxisFontColor=CMYKColor(0.00, 0.00, 0.00, 1.00),
                yAxisVisible=1,
                yAxisFontName='Helvetica',
                yAxisFontColor=CMYKColor(0.00, 0.00, 0.00, 1.00),
                xAxisGridLines=0,
                yAxisGridLines=1,
                dataLabelsType=None,
                width=366.00000,
                height=347.50000)
    makeDrawing(html,
                "14.2 Liron Axis error",
                chartType='linechart',
                data=[[0.00, 0.00, 0.00, 0.00, -1.07]],
                categoryNames=['a', 'b', 'c', 'd', 'e'],
                seriesNames=['Series 1'],
                chartColors=[
                    Color(0.82, 0, 0),
                    Color(0.32, 0, 0),
                    Color(0.32, 0.16, 0.06),
                    Color(0.32, 0.16, 0.06),
                    Color(0.32, 0.16, 0.06)
                ],
                bgColor=None,
                plotColor=None,
                legendPos='right',
                legendFontName='Times-Roman',
                legendFontSize=12.00,
                legendFontColor=Color(0.00, 0.00, 0.00),
                titleText='',
                titleFontName='Times-Roman',
                titleFontSize=12.00,
                titleFontColor=Color(0.00, 0.00, 0.00),
                xTitleText='',
                xTitleFontName='Times-Roman',
                xTitleFontSize=12.00,
                xTitleFontColor=Color(0.00, 0.00, 0.00),
                yTitleText='',
                yTitleFontName='Times-Roman',
                yTitleFontSize=12.00,
                yTitleFontColor=Color(0.00, 0.00, 0.00),
                xAxisVisible=1,
                xAxisLabelAngle=30,
                xAxisFontName='Times-Roman',
                xAxisFontSize=12.00,
                xAxisFontColor=Color(0.00, 0.00, 0.00),
                yAxisVisible=1,
                yAxisFontName='Times-Roman',
                yAxisFontSize=12.00,
                yAxisFontColor=Color(0.00, 0.00, 0.00),
                xAxisGridLines=0,
                yAxisGridLines=0,
                dataLabelsType=None,
                width=431.00,
                height=343.00)
    import os, sys
    fn = os.path.join('pmout', 'qctests.html')
    open(fn, 'w').write('<html><head></head><body>%s</body></html>' %
                        ('<hr width=100%>'.join(html)))
    if sys.platform == 'mac':
        from reportlab.lib.utils import markfilename
        markfilename(fn, ext='HTML')
Example #32
0
def get_color(value):
    value = get_color_as_hexa(value)
    color = colors.toColor(value, colors.black)
    return color
def draw_wordcloud(drawing, cloud, x, y):
    for (word, count), font_size, position, orientation, color in cloud.layout_:
        drawing.add(String(x=x+position[1],y=y+position[0],text=word,fontSize=font_size,
                           fontName='Lato-Bold',fillColor=toColor(color)))
    def test0(self):
        "IndentTestCase test0"
        if rl_invariant: random.seed(1479316371)

        # Build story.
        story = []
        doc = MyDocTemplate(outputfile('test_platypus_indents.pdf'))
        storyAdd = story.append

        styleSheet = getSampleStyleSheet()
        h1 = styleSheet['Heading1']
        h1.spaceBefore = 18
        bt = styleSheet['BodyText']
        bt.spaceBefore = 6

        storyAdd(Paragraph('Test of context-relative indentation', h1))

        storyAdd(Spacer(18, 18))

        storyAdd(Indenter(0, 0))
        storyAdd(
            Paragraph(
                "This should be indented 0 points at each edge. " +
                ("spam " * 25), bt))
        storyAdd(Indenter(0, 0))

        storyAdd(Indenter(36, 0))
        storyAdd(
            Paragraph(
                "This should be indented 36 points at the left. " +
                ("spam " * 25), bt))
        storyAdd(Indenter(-36, 0))

        storyAdd(Indenter(0, 36))
        storyAdd(
            Paragraph(
                "This should be indented 36 points at the right. " +
                ("spam " * 25), bt))
        storyAdd(Indenter(0, -36))

        storyAdd(Indenter(36, 36))
        storyAdd(
            Paragraph(
                "This should be indented 36 points at each edge. " +
                ("spam " * 25), bt))
        storyAdd(Indenter(36, 36))
        storyAdd(
            Paragraph(
                "This should be indented a FURTHER 36 points at each edge. " +
                ("spam " * 25), bt))
        storyAdd(Indenter(-72, -72))

        storyAdd(
            Paragraph(
                "This should be back to normal at each edge. " +
                ("spam " * 25), bt))

        storyAdd(Indenter(36, 36))
        storyAdd(
            Paragraph(("""This should be indented 36 points at the left
        and right.  It should run over more than one page and the indent should
        continue on the next page. """ + (random.randint(0, 10) * 'x') + ' ') *
                      20, bt))
        storyAdd(Indenter(-36, -36))

        storyAdd(NextPageTemplate('updown'))
        storyAdd(FrameBreak())
        storyAdd(Paragraph('Another test of context-relative indentation', h1))
        storyAdd(NextPageTemplate(
            'normal'))  # so NEXT page is different template...
        storyAdd(
            Paragraph(
                """This time we see if the indent level is continued across
            frames...this page has 2 frames, let's see if it carries top to bottom. Then
            onto a totally different template.""", bt))

        storyAdd(Indenter(0, 0))
        storyAdd(
            Paragraph(
                "This should be indented 0 points at each edge. " +
                ("spam " * 25), bt))
        storyAdd(Indenter(0, 0))
        storyAdd(Indenter(36, 72))
        storyAdd(
            Paragraph(("""This should be indented 36 points at the left
        and 72 at the right.  It should run over more than one frame and one page, and the indent should
        continue on the next page. """ + (random.randint(0, 10) * 'x') + ' ') *
                      35, bt))

        storyAdd(Indenter(-36, -72))
        storyAdd(
            Paragraph(
                "This should be back to normal at each edge. " +
                ("spam " * 25), bt))
        storyAdd(PageBreak())

        storyAdd(PageBreak())
        storyAdd(
            Paragraph(
                "Below we should colour the background lightgreen and have a red border",
                bt))
        storyAdd(
            FrameBG(start=True,
                    color=lightgreen,
                    strokeColor=toColor('red'),
                    strokeWidth=1))
        storyAdd(Paragraph("We should have a light green background here", bt))
        storyAdd(Paragraph("We should have a light green background here", bt))
        storyAdd(Paragraph("We should have a light green background here", bt))
        storyAdd(Spacer(6, 6))
        storyAdd(FrameBG(start=False))

        storyAdd(
            Paragraph("Below we should colour the background lightgreen", bt))
        storyAdd(
            FrameBG(start=True,
                    color=lightgreen,
                    strokeColor=toColor('red'),
                    strokeWidth=None))
        storyAdd(Paragraph("We should have a light green background here", bt))
        storyAdd(Paragraph("We should have a light green background here", bt))
        storyAdd(Paragraph("We should have a light green background here", bt))
        storyAdd(Spacer(6, 6))
        storyAdd(FrameBG(start=False))

        storyAdd(
            Paragraph(
                "Below we split to two new frames with dark green borders",
                bt))
        storyAdd(FrameSplitter('templateX', ['XF4', 'XF5'],
                               adjustHeight=False))
        storyAdd(
            FrameBG(start=True,
                    color=lightgreen,
                    strokeColor=toColor('red'),
                    strokeWidth=1))
        for i in xrange(15):
            storyAdd(
                Paragraph(
                    "We should have a light green background here %d" % i, bt))
        storyAdd(Spacer(6, 6))
        storyAdd(FrameBG(start=False))
        storyAdd(NextPageTemplate('normal'))

        storyAdd(PageBreak())
        storyAdd(
            Paragraph("Below we should colour the background lightgreen", bt))
        storyAdd(FrameBG(start="frame", color=lightgreen))
        storyAdd(Paragraph("We should have a light green background here", bt))

        storyAdd(PageBreak())
        storyAdd(Paragraph("Here we should have no background.", bt))

        storyAdd(PageBreak())
        storyAdd(FrameBG(start="frame", color=lightblue))
        storyAdd(
            Paragraph(
                "We should have a light blue background here and the whole frame should be filled in.",
                bt))

        storyAdd(PageBreak())
        storyAdd(Paragraph("Here we should have no background again.", bt))

        storyAdd(
            Paragraph("Below we should colour the background lightgreen", bt))
        storyAdd(FrameBG(start="frame-permanent", color=lightgreen))
        storyAdd(Paragraph("We should have a light green background here", bt))

        storyAdd(PageBreak())
        storyAdd(
            Paragraph("Here we should still have a lightgreen background.",
                      bt))

        storyAdd(PageBreak())
        storyAdd(FrameBG(start="frame", color=lightblue, left=36, right=36))
        storyAdd(
            Paragraph("We should have a lighgreen/lightblue background.", bt))

        storyAdd(PageBreak())
        storyAdd(
            Paragraph("Here we should have only light green background.", bt))

        doc.multiBuild(story)
Example #35
0
 def strokeColor(self, c):
     self.__strokeColor = toColor(c) if c is not None else c
Example #36
0
def run():
    from reportlab.platypus import  BaseDocTemplate, PageTemplate, Image, Frame, PageTemplate, \
                                    ShowBoundaryValue, SimpleDocTemplate, FrameBG, Paragraph, \
                                    FrameBreak
    from reportlab.lib.colors import toColor
    from reportlab.lib.utils import haveImages, _RL_DIR, rl_isfile, open_for_read, fileName2FSEnc, asNative
    from reportlab.lib.styles import getSampleStyleSheet
    styleSheet = getSampleStyleSheet()
    if haveImages:
        _GIF = os.path.join(testsFolder, 'pythonpowered.gif')
        if not rl_isfile(_GIF): _GIF = None
        _GAPNG = os.path.join(testsFolder, 'gray-alpha.png')
        if not rl_isfile(_GAPNG): _GAPNG = None
    else:
        _GIF = None
    if _GIF: _GIFFSEnc = fileName2FSEnc(_GIF)
    if _GAPNG: _GAPNGFSEnc = fileName2FSEnc(_GAPNG)

    _JPG = os.path.join(testsFolder, '..', 'docs', 'images', 'lj8100.jpg')
    if not rl_isfile(_JPG): _JPG = None

    doc = SimpleDocTemplate(outputfile('test_platypus_images.pdf'))
    story = [
        FrameBG(color=toColor('lightblue'), start='frame-permanent'),
    ]
    if _GIF:
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string GIF filename.",
                styleSheet['Italic']))
        story.append(Image(_GIF))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a utf8 GIF filename.",
                styleSheet['Italic']))
        #story.append(Image(fileName2FSEnc(_GIF)))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string GIF file url.",
                styleSheet['Italic']))
        story.append(Image(getFurl(_GIF)))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from an open GIF file.",
                styleSheet['Italic']))
        story.append(Image(open_for_read(_GIF, 'b')))
        story.append(FrameBreak())
        try:
            img = Image('http://www.reportlab.com/rsrc/encryption.gif')
            story.append(
                Paragraph(
                    "Here is an Image flowable obtained from a string GIF http url.",
                    styleSheet['Italic']))
            story.append(img)
        except:
            story.append(
                Paragraph(
                    "The image could not be obtained from a string http GIF url.",
                    styleSheet['Italic']))
        story.append(FrameBreak())

    if _GAPNG:
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string PNGA filename.",
                styleSheet['Italic']))
        story.append(Image('rltw-icon-tr.png'))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string PNG filename.",
                styleSheet['Italic']))
        story.append(Image(_GAPNG))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a utf8 PNG filename.",
                styleSheet['Italic']))
        #story.append(Image(fileName2FSEnc(_GAPNG)))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string file PNG url.",
                styleSheet['Italic']))
        story.append(Image(getFurl(_GAPNG)))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from an open PNG file.",
                styleSheet['Italic']))
        story.append(Image(open_for_read(_GAPNG, 'b')))
        story.append(FrameBreak())

    if _JPG:
        img = Image(_JPG)
        story.append(
            Paragraph(
                "Here is an JPEG Image flowable obtained from a JPEG filename.",
                styleSheet['Italic']))
        story.append(img)
        story.append(
            Paragraph(
                "Here is an JPEG Image flowable obtained from an open JPEG file.",
                styleSheet['Italic']))
        img = Image(open_for_read(_JPG, 'b'))
        story.append(img)
        story.append(FrameBreak())
    doc.build(story)
Example #37
0
def genChart(width, height):

    chart = VerticalBarChart()
    chart.data = [(12, 11, 9, 6, 2, 22, 7)]

    # Vertical axis - Y axis
    chart.valueAxis.valueMin = 0
    chart.valueAxis.valueMax = 25
    chart.valueAxis.visible = 0  # hide

    # Horizontal axis - X axis
    chart.categoryAxis.categoryNames = [
        'Asia', 'Africa', 'North America', 'South America', 'Antarctica',
        'Europe', 'Australia'
    ]
    # We could hide X axis like we did with Y axis:
    #   example: chart.categoryAxis.visible = 0
    # Hidding the X axis will hide all the elements of X axis
    # and we want to see the labels!
    #   example: chart.categoryAxis.labels.visible = 1 # by default they are visible
    # So we just hide what we don't want to see!
    chart.categoryAxis.visibleAxis = 0  # hide line
    chart.categoryAxis.visibleTicks = 0  # hide line ticks
    chart.categoryAxis.labels.angle = 90  # rotate labels
    chart.categoryAxis.labels.dx = -30  # adjust labels position at x
    chart.categoryAxis.labels.dy = 30  # adjust labels position at y

    # Numbers above each bar
    chart.barLabelFormat = '%s'  # contains the provived string
    chart.barLabels.nudge = 15  # space between the bar and the text
    chart.barLabels.angle = -20  # rotate the text
    chart.barLabels.fontName = 'barText'  # registered font at report.py line 91
    chart.barLabels.fontSize = 20
    chart.barLabels.fillColor = colors.red

    chart.barWidth = 5
    chart.barSpacing = 8  # space between each bar
    # NOTE: bar list doesn't work like we could expect,
    # the first element apparently sets the configuration for all!
    chart.bars[0].fillColor = colors.toColor('hsl(240, 100%, 20%)')
    chart.bars[0].strokeColor = colors.white

    chart.x = width * 5 / 100  # starts at 5% of width space
    chart.y = height * 5 / 100  # starts at 5% of height space
    chart.width = width * 90 / 100  # uses 90% of width
    chart.height = height * 80 / 100  # uses 80% of height

    titleShadow = String(
        19,
        height * 60 / 100 - 1,  # x and y start point
        'Average JC attacks by continent',
        fontSize=20,
        fontName='chartTitle',  # registered font at report.py line 94
        fillColor=colors.red)

    title = String(
        20,
        height * 60 / 100,  # x and y start point
        'Average JC attacks by continent',
        fontSize=20,
        fontName='chartTitle',  # registered font at report.py line 94
        fillColor=colors.orange)

    bounds = title.getBounds()  # returns a tuple with (x1,y1,x2,y2)

    rectangle = Rect(
        bounds[0] - 3,
        bounds[1],  # x1 and y1
        bounds[2] - bounds[0] + 3,
        20  # x2 and y2
    )
    rectangle.fillColor = colors.black

    drawing = Drawing()
    drawing.add(rectangle)
    drawing.add(titleShadow)
    drawing.add(title)
    drawing.add(chart)

    # Bars bottom 'labels'
    # For a better understand of this coordinates please
    # see code guide
    charWidth = utils.getStringWidth('A')
    dataLen = len(chart.data[0])  # 7 elements

    startPoint = chart.getBounds()[0]
    barAndLabelWidth = chart.width / dataLen  # total width / 7 elements
    center = barAndLabelWidth / 2 - charWidth / 2

    yPos = chart.y - 10

    # Example:
    # drawing.add(String(startPoint + barAndLabelWidth * 0 + center, chart.y - 10, 'A'))
    # drawing.add(String(startPoint + barAndLabelWidth * 1 + center, chart.y - 10, 'B'))
    # ...
    # drawing.add(String(startPoint + barAndLabelWidth * 6 + center, chart.y - 10, 'G'))
    for index, char in enumerate('ABCDEFG', start=0):
        xPos = startPoint + barAndLabelWidth * index + center

        drawing.add(String(xPos, yPos, char))

    return drawing
    def createDoc(self):
        # add title page
        self.addTitlePage()

        # qndata is a dict of
        #   {qn:{dept:5tuple,...},...}
        # initialise empty dict for convenience
        qndata = {}
        for i in xrange(1, 111):
            qndata[i] = {}
            for d in depts:
                qndata[i][d] = [0.0, 0.0, 0.0, 0.0, 0.0]
        # connect to db and get all data
        data = self.sql.cur.execute('SELECT * FROM surveys')
        datafetchall = data.fetchall()
        for row in datafetchall:
            # unpack
            dic = eval(row[1])
            try:
                dept = eval(row[0])
            except:
                dept = row[0]

            if dept in depts:
                # collect data
                #sqlDeptDict={}
                for qnum, index in dic.iteritems():
                    if 1 <= qnum <= 110 and index >= 1:
                        qndata[qnum][dept][index - 1] += 1.0

        # Catch empty db or read error
        if len(qndata) == 0:
            print 'failed'
            return

        # make dict of qngroup data
        groupdata = {}
        g2qs_iter = list(g2qs.iteritems())
        for g, qns in g2qs_iter:
            # g is group name
            # qns is list of question nums in group
            groupdata[g] = {}
            for d in depts:
                groupdata[g][d] = [0.0, 0.0, 0.0, 0.0, 0.0]
                for q in qns:
                    for i in range(5):
                        groupdata[g][d][i] += qndata[q][d][i]

        # colors for the departments (page number is coloured)
        grpcolours = []
        nGrps = len(g2qs_iter)
        assert nGrps == 19  # REMOVE
        for i in range(nGrps):
            # Generate new color for each department
            c = toColor('hsl({},100%,40%)'.format(360 * (i + 1) /
                                                  float(nGrps)))
            grpcolours.append(c)

        # add data to pdf
        for tup, colour in zip(g2qs_iter, grpcolours):
            g, qns = tup
            # note:
            # addData(title,qndict,colour=colors.black)
            title = 'Results for ' + g
            # combine and normalize data
            normdata = self.normDeptData(groupdata[g])
            self.addData(title, normdata, colour)
            qns = list(qns)
            qns.sort()
            for q in qns:
                text = ` q ` + '. ' + textdict[q]
                normdata2 = self.normDeptData(qndata[q])
                self.addData(text, normdata2, colour)

        # close db connection
        self.sql.close()
        # save to PDF
        self.save()
Example #39
0
#     [(x,randint(90,100)) for x in range(0,2001,100)],
#     [(x,randint(30,80)) for x in range(0,2001,100)],
#     [(x,randint(5,20)) for x in range(0,2001,100)],
#     ]

# Create the drawing and the lineplot
drawing = Drawing(400, 200)
lp = LinePlot()
lp.x = 50
lp.y = 50
lp.height = 125
lp.width = 300
lp._inFill = 1
lp.data = result
for i in range(len(result)):
    lp.lines[i].strokeColor = colors.toColor('hsl(%s,80%%,40%%)' % (i * 60))

fontName = 'Helvetica'
fontSize = 7

lp.xValueAxis = NormalDateXValueAxis()
lp.xValueAxis.labels.fontName = fontName
lp.xValueAxis.labels.fontSize = fontSize - 1
lp.xValueAxis.forceEndDate = 1
lp.xValueAxis.forceFirstDate = 1
lp.xValueAxis.labels.boxAnchor = 'autox'
lp.xValueAxis.xLabelFormat = '{d}-{MMM}'
lp.xValueAxis.maximumTicks = 5
lp.xValueAxis.minimumTickSpacing = 0.5
lp.xValueAxis.niceMonth = 0
lp.xValueAxis.strokeWidth = 1
Example #40
0
 def fset(self, value):
     self._color = colors.toColor(str(value))
Example #41
0
def _test0(self):
    "This makes one long multi-page paragraph."

    # Build story.
    story = []
    a = story.append

    styleSheet = getSampleStyleSheet()
    h1 = styleSheet['Heading1']
    h1.pageBreakBefore = 1
    h1.keepWithNext = 1

    h2 = styleSheet['Heading2']
    h2.frameBreakBefore = 1
    h2.keepWithNext = 1

    h3 = styleSheet['Heading3']
    h3.backColor = colors.cyan
    h3.keepWithNext = 1

    bt = styleSheet['BodyText']
    a(
        Paragraph(
            """
        Subsequent pages test pageBreakBefore, frameBreakBefore and
        keepTogether attributes.  Generated at %s.  The number in brackets
        at the end of each paragraph is its position in the story. (%d)""" %
            (time.ctime(time.time()), len(story)), bt))

    for i in xrange(10):
        a(Paragraph('Heading 1 always starts a new page (%d)' % len(story),
                    h1))
        for j in xrange(3):
            a(
                Paragraph(
                    'Heading1 paragraphs should always'
                    'have a page break before.  Heading 2 on the other hand'
                    'should always have a FRAME break before (%d)' %
                    len(story), bt))
            a(
                Paragraph(
                    'Heading 2 always starts a new frame (%d)' % len(story),
                    h2))
            a(
                Paragraph(
                    'Heading1 paragraphs should always'
                    'have a page break before.  Heading 2 on the other hand'
                    'should always have a FRAME break before (%d)' %
                    len(story), bt))
            for j in xrange(3):
                a(
                    Paragraph(
                        randomText(theme=PYTHON, sentences=2) +
                        ' (%d)' % len(story), bt))
                a(
                    Paragraph(
                        'I should never be at the bottom of a frame (%d)' %
                        len(story), h3))
                a(
                    Paragraph(
                        randomText(theme=PYTHON, sentences=1) +
                        ' (%d)' % len(story), bt))

    a(Paragraph('Now we do &lt;br/&gt; tests', h1))
    a(Paragraph('First off no br tags', h3))
    a(Paragraph(_text1, bt))
    a(Paragraph("&lt;br/&gt; after 'the' in line 4", h3))
    a(Paragraph(_text1.replace('forms of the', 'forms of the<br/>', 1), bt))
    a(Paragraph("2*&lt;br/&gt; after 'the' in line 4", h3))
    a(
        Paragraph(_text1.replace('forms of the', 'forms of the<br/><br/>', 1),
                  bt))
    a(Paragraph("&lt;br/&gt; after 'I suggested ' in line 5", h3))
    a(Paragraph(_text1.replace('I suggested ', 'I suggested<br/>', 1), bt))
    a(Paragraph("2*&lt;br/&gt; after 'I suggested ' in line 5", h3))
    a(Paragraph(_text1.replace('I suggested ', 'I suggested<br/><br/>', 1),
                bt))
    a(Paragraph("&lt;br/&gt; at the end of the paragraph!", h3))
    a(Paragraph("""text one<br/>text two<br/>""", bt))
    a(Paragraph("Border with &lt;nr/&gt; at the end of the paragraph!", h3))
    bt1 = ParagraphStyle('bodyText1', bt)
    bt1.borderWidth = 0.5
    bt1.borderColor = colors.toColor('red')
    bt1.backColor = colors.pink
    bt1.borderRadius = 2
    bt1.borderPadding = 3
    a(Paragraph("""text one<br/>text two<br/>""", bt1))
    a(Paragraph("Border no &lt;nr/&gt; at the end of the paragraph!", h3))
    bt1 = ParagraphStyle('bodyText1', bt)
    bt1.borderWidth = 0.5
    bt1.borderColor = colors.toColor('red')
    bt1.backColor = colors.pink
    bt1.borderRadius = 2
    bt1.borderPadding = 3
    a(Paragraph("""text one<br/>text two""", bt1))
    a(Paragraph("Different border style!", h3))
    bt2 = ParagraphStyle('bodyText1', bt1)
    bt2.borderWidth = 1.5
    bt2.borderColor = colors.toColor('blue')
    bt2.backColor = colors.gray
    bt2.borderRadius = 3
    bt2.borderPadding = 3
    a(Paragraph("""text one<br/>text two<br/>""", bt2))

    doc = MyDocTemplate(outputfile('test_platypus_breaking.pdf'))
    doc.multiBuild(story)
Example #42
0
 def fillColor(self, c):
     self.__fillColor = toColor(c) if c is not None else c
Example #43
0
    def createDoc(self):
        # add title page
        self.addTitlePage()

        # qndata is a dict of
        #   {qn:{dept:5tuple,...},...}
        # initialise empty dict for convenience
        qndata = {}
        for i in xrange(1, 111):
            qndata[i] = {}
            for d in depts:
                qndata[i][d] = [0.0, 0.0, 0.0, 0.0, 0.0]
        # connect to db and get all data
        data = self.sql.cur.execute('SELECT * FROM surveys')
        datafetchall = data.fetchall()
        for row in datafetchall:
            dic = eval(row[1])
            try:
                dept = eval(row[0])
            except:
                dept = row[0]

            if dept in depts:
                # collect data
                #sqlDeptDict={}
                for qnum, index in dic.iteritems():
                    # if 1 <= qnum <= 110 and index >= 1:
                    if 1 <= qnum <= 110 and (
                            not qnum in g2qs['County Council']) and index >= 1:
                        assert (not qnum in (6, 29, 57, 87, 108))
                        qndata[qnum][dept][index - 1] += 1.0

        # Catch empty db or read error
        if len(qndata) == 0:
            print 'failed'
            return

        # make dict of qngroup data
        groupdata = {}
        tmp_g2qs = g2qs.pop('County Council')
        g2qs_iter = list(g2qs.iteritems())
        for g, qns in g2qs_iter:
            # g is group name
            # qns is list of question nums in group
            groupdata[g] = {}
            for d in depts:
                groupdata[g][d] = [0.0, 0.0, 0.0, 0.0, 0.0]
                for q in qns:
                    assert (not q in (6, 29, 57, 87, 108))
                    for i in range(5):
                        groupdata[g][d][i] += qndata[q][d][i]

        # colors for the departments (page number is coloured)
        grpcolours = []
        nGrps = len(g2qs_iter)
        for i in range(nGrps):
            # Generate new color for each department
            c = toColor('hsl({},100%,40%)'.format(360 * (i + 1) /
                                                  float(nGrps)))
            grpcolours.append(c)

        # add data to pdf
        # for (g,qns), colour in zip(g2qs.iteritems(),grpcolours):
        for tup, colour in zip(g2qs_iter, grpcolours):
            g, qns = tup
            # note:
            # addData(title,qndict,colour=colors.black)
            title = 'Results for ' + g
            # combine and normalize data
            normdata = self.normDeptData(groupdata[g])
            # add group data
            self.addGroupData(title, normdata, colour)
            # init question data
            qns = list(qns)
            qns.sort()
            # handle first 1 to 6 qns
            qs = []
            while len(qs) < 6:
                try:
                    qs.append(qns.pop(0))
                except IndexError:
                    break
            qdic = {}
            for q in qs:
                text = ` q ` + '. ' + textdict[q]
                normdata = self.normDeptData(qndata[q])
                qdic[q] = [text, normdata, colour]
            self.addQnData(qdic, startat=2)
            # find num of pages needed (8 qns per page)
            numqns = len(qns)
            numpages = int(ceil(numqns / 8.))
            for i in xrange(numpages):
                index = 8 * i + 8
                if index > numqns:
                    qs = qns[i * 8:]
                else:
                    qs = qns[i * 8:index]
                # add these quenstions to page
                qdic = {}
                for q in qs:
                    text = ` q ` + '. ' + textdict[q]
                    normdata = self.normDeptData(qndata[q])
                    qdic[q] = [text, normdata, colour]
                self.addQnData(qdic)
        # close db connection
        self.sql.close()
        # save to PDF
        self.save()
Example #44
0
    def __init__(self,
                 nlist,
                 posn,
                 chartsize,
                 pagesize=letter,
                 titletext='',
                 *args,
                 **kw):
        'nlist is a 5-tuple of answers'
        #
        pw, ph = pagesize
        cw, ch = chartsize
        cx, cy = posn
        total = float(sum(nlist))
        if total == 0: total = 1

        # Add Chart
        Drawing.__init__(self, pw, ph, *args, **kw)
        self._add(self,
                  VerticalBarChart(),
                  name='chart',
                  validate=None,
                  desc="Results for a department")
        #                       cw - axis_room - padding
        self.chart.width = cw - 25. - 5
        #                       ch - axis_room - title_room
        self.chart.height = ch - 20. - 15
        self.chart.x = cx + 25.
        self.chart.y = cy + 20.

        # Colors
        green = toColor('rgb(0,200,30)')
        blue = toColor('rgb(0,128,255)')
        offwhite = toColor('rgb(200,195,230)')
        yellow = toColor('rgb(235,215,20)')
        red = toColor('rgb(255,55,55)')

        # Colour the bars
        self.chart.bars[(0, 0)].fillColor = green
        self.chart.bars[(0, 1)].fillColor = blue
        self.chart.bars[(0, 2)].fillColor = yellow
        self.chart.bars[(0, 3)].fillColor = red
        self.chart.bars[(0, 4)].fillColor = offwhite

        # Configure Chart Options
        self.chart.fillColor = toColor('rgb(238,240,230)')
        self.chart.barSpacing = 1
        self.chart.barLabels.fontName = 'Helvetica'
        self.chart.valueAxis.labels.fontName = 'Helvetica'
        self.chart.valueAxis.labels.fontSize = 7
        self.chart.valueAxis.forceZero = 1
        self.chart.data = [nlist]
        self.chart.groupSpacing = 10
        self.chart.valueAxis.avoidBoundFrac = 1
        self.chart.valueAxis.tickLeft = 3
        self.chart.valueAxis.visibleGrid = 1
        self.chart.categoryAxis.categoryNames = [
            '%%%d Strongly\nAgree' % trunc(round(100 * nlist[0] / total)),
            '%%%d Agree' % trunc(round(100 * nlist[1] / total)),
            '%%%d Disagree' % trunc(round(100 * nlist[2] / total)),
            '%%%d Strongly\nDisagree' % trunc(round(100 * nlist[3] / total)),
            '%%%d Do Not\nKnow' % trunc(round(100 * nlist[4] / total))
        ]
        self.chart.categoryAxis.tickDown = 3
        self.chart.categoryAxis.labels.fontName = 'Helvetica'
        self.chart.categoryAxis.labels.textAnchor = 'middle'
        self.chart.categoryAxis.labels.fontSize = 6
        self.chart.categoryAxis.labels.dy = -2

        # Title
        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 = 12
        self.Title.x = cx + cw / 2.
        self.Title.y = cy + ch - 9
        self.Title._text = titletext
        self.Title.maxWidth = 180
        self.Title.height = 20
        self.Title.textAnchor = 'middle'
Example #45
0
 def __init__(self):
     AreaLinePlot.__init__(self)
     self.xValueAxis = NormalDateXValueAxis()
     self.yValueAxis = AdjYValueAxis()
     self.data = [
         (20030601, 0.95, 0.05, 0.0), (20030701, 0.95, 0.05, 0.0),
         (20030801, 0.95, 0.05, 0.0), (20030901, 0.95, 0.05, 0.0),
         (20031001, 0.95, 0.05, 0.0), (20031101, 0.95, 0.05, 0.0),
         (20031201, 0.95, 0.05, 0.0), (20040101, 0.95, 0.05, 0.0),
         (20040201, 0.95, 0.05, 0.0), (20040301, 0.95, 0.05, 0.0),
         (20040401, 0.95, 0.05, 0.0), (20040501, 0.95, 0.05, 0.0),
         (20040601, 0.95, 0.05, 0.0), (20040701, 0.95, 0.05, 0.0),
         (20040801, 0.95, 0.05, 0.0), (20040901, 0.95, 0.05, 0.0),
         (20041001, 0.95, 0.05, 0.0), (20041101, 0.95, 0.05, 0.0),
         (20041201, 0.95, 0.05, 0.0), (20050101, 0.95, 0.05, 0.0),
         (20050201, 0.95, 0.05, 0.0), (20050301, 0.95, 0.05, 0.0),
         (20050401, 0.95, 0.05, 0.0), (20050501, 0.95, 0.05, 0.0),
         (20050601, 0.95, 0.05, 0.0), (20050701, 0.95, 0.05, 0.0),
         (20050801, 0.95, 0.05, 0.0), (20050901, 0.95, 0.05, 0.0),
         (20051001, 0.95, 0.05, 0.0), (20051101, 0.95, 0.05, 0.0),
         (20051201, 0.95, 0.05, 0.0), (20060101, 0.95, 0.05, 0.0),
         (20060201, 0.95, 0.05, 0.0), (20060301, 0.95, 0.05, 0.0),
         (20060401, 0.95, 0.05, 0.0), (20060501, 0.95, 0.05, 0.0),
         (20060601, 0.95, 0.05, 0.0), (20060701, 0.95, 0.05, 0.0),
         (20060801, 0.95, 0.05, 0.0), (20060901, 0.95, 0.05, 0.0),
         (20061001, 0.95, 0.05, 0.0), (20061101, 0.95, 0.05, 0.0),
         (20061201, 0.95, 0.05, 0.0), (20070101, 0.95, 0.05, 0.0),
         (20070201, 0.95, 0.05, 0.0), (20070301, 0.95, 0.05, 0.0),
         (20070401, 0.95, 0.05, 0.0), (20070501, 0.95, 0.05, 0.0),
         (20070601, 0.95, 0.05, 0.0), (20070701, 0.95, 0.05, 0.0),
         (20070801, 0.95, 0.05, 0.0), (20070901, 0.95, 0.05, 0.0),
         (20071001, 0.95, 0.05, 0.0), (20071101, 0.95, 0.05, 0.0),
         (20071201, 0.95, 0.05, 0.0), (20080101, 0.95, 0.05, 0.0),
         (20080201, 0.95, 0.05, 0.0), (20080301, 0.95, 0.05, 0.0),
         (20080401, 0.95, 0.05, 0.0), (20080501, 0.95, 0.05, 0.0),
         (20080601, 0.95, 0.05, 0.0), (20080701, 0.95, 0.05, 0.0),
         (20080801, 0.95, 0.05, 0.0), (20080901, 0.95, 0.05, 0.0),
         (20081001, 0.95, 0.05, 0.0), (20081101, 0.95, 0.05, 0.0),
         (20081201, 0.95, 0.05, 0.0), (20090101, 0.95, 0.05, 0.0),
         (20090201, 0.91, 0.09, 0.0), (20090301, 0.91, 0.09, 0.0),
         (20090401, 0.91, 0.09, 0.0), (20090501, 0.91, 0.09, 0.0),
         (20090601, 0.91, 0.09, 0.0), (20090701, 0.91, 0.09, 0.0),
         (20090801, 0.91, 0.09, 0.0), (20090901, 0.91, 0.09, 0.0),
         (20091001, 0.91, 0.09, 0.0), (20091101, 0.91, 0.09, 0.0),
         (20091201, 0.91, 0.09, 0.0), (20100101, 0.91, 0.09, 0.0),
         (20100201, 0.81, 0.19, 0.0), (20100301, 0.81, 0.19, 0.0),
         (20100401, 0.81, 0.19, 0.0), (20100501, 0.81, 0.19, 0.0),
         (20100601, 0.81, 0.19, 0.0), (20100701, 0.81, 0.19, 0.0),
         (20100801, 0.81, 0.19, 0.0), (20100901, 0.81, 0.19, 0.0),
         (20101001, 0.81, 0.19, 0.0), (20101101, 0.81, 0.19, 0.0),
         (20101201, 0.81, 0.19, 0.0), (20110101, 0.81, 0.19, 0.0),
         (20110201, 0.72, 0.28, 0.0), (20110301, 0.72, 0.28, 0.0),
         (20110401, 0.72, 0.28, 0.0), (20110501, 0.72, 0.28, 0.0),
         (20110601, 0.72, 0.28, 0.0), (20110701, 0.72, 0.28, 0.0),
         (20110801, 0.72, 0.28, 0.0), (20110901, 0.72, 0.28, 0.0),
         (20111001, 0.72, 0.28, 0.0), (20111101, 0.72, 0.28, 0.0),
         (20111201, 0.72, 0.28, 0.0), (20120101, 0.72, 0.28, 0.0),
         (20120201, 0.53, 0.47, 0.0), (20120301, 0.53, 0.47, 0.0),
         (20120401, 0.53, 0.47, 0.0), (20120501, 0.53, 0.47, 0.0),
         (20120601, 0.53, 0.47, 0.0), (20120701, 0.53, 0.47, 0.0),
         (20120801, 0.53, 0.47, 0.0), (20120901, 0.53, 0.47, 0.0),
         (20121001, 0.53, 0.47, 0.0), (20121101, 0.53, 0.47, 0.0),
         (20121201, 0.53, 0.47, 0.0), (20130101, 0.53, 0.47, 0.0),
         (20130201, 0.44, 0.56, 0.0), (20130301, 0.44, 0.56, 0.0),
         (20130401, 0.44, 0.56, 0.0), (20130501, 0.44, 0.56, 0.0),
         (20130601, 0.44, 0.56, 0.0), (20130701, 0.44, 0.56, 0.0),
         (20130801, 0.44, 0.56, 0.0), (20130901, 0.44, 0.56, 0.0),
         (20131001, 0.44, 0.56, 0.0), (20131101, 0.44, 0.56, 0.0),
         (20131201, 0.44, 0.56, 0.0), (20140101, 0.44, 0.56, 0.0),
         (20140201, 0.36, 0.5, 0.14), (20140301, 0.36, 0.5, 0.14),
         (20140401, 0.36, 0.5, 0.14), (20140501, 0.36, 0.5, 0.14),
         (20140601, 0.36, 0.5, 0.14), (20140701, 0.36, 0.5, 0.14),
         (20140801, 0.36, 0.5, 0.14), (20140901, 0.36, 0.5, 0.14),
         (20141001, 0.36, 0.5, 0.14), (20141101, 0.36, 0.5, 0.14),
         (20141201, 0.36, 0.5, 0.14), (20150101, 0.36, 0.5, 0.14),
         (20150201, 0.3, 0.41, 0.29), (20150301, 0.3, 0.41, 0.29),
         (20150401, 0.3, 0.41, 0.29), (20150501, 0.3, 0.41, 0.29),
         (20150601, 0.3, 0.41, 0.29), (20150701, 0.3, 0.41, 0.29),
         (20150801, 0.3, 0.41, 0.29), (20150901, 0.3, 0.41, 0.29),
         (20151001, 0.3, 0.41, 0.29), (20151101, 0.3, 0.41, 0.29),
         (20151201, 0.3, 0.41, 0.29), (20160101, 0.3, 0.41, 0.29),
         (20160201, 0.26, 0.36, 0.38), (20160301, 0.26, 0.36, 0.38),
         (20160401, 0.26, 0.36, 0.38), (20160501, 0.26, 0.36, 0.38),
         (20160601, 0.26, 0.36, 0.38), (20160701, 0.26, 0.36, 0.38),
         (20160801, 0.26, 0.36, 0.38), (20160901, 0.26, 0.36, 0.38),
         (20161001, 0.26, 0.36, 0.38), (20161101, 0.26, 0.36, 0.38),
         (20161201, 0.26, 0.36, 0.38), (20170101, 0.26, 0.36, 0.38),
         (20170201, 0.2, 0.3, 0.5), (20170301, 0.2, 0.3, 0.5),
         (20170401, 0.2, 0.3, 0.5), (20170501, 0.2, 0.3, 0.5),
         (20170601, 0.2, 0.3, 0.5), (20170701, 0.2, 0.3, 0.5),
         (20170801, 0.2, 0.3, 0.5), (20170901, 0.2, 0.3, 0.5),
         (20171001, 0.2, 0.3, 0.5), (20171101, 0.2, 0.3, 0.5),
         (20171201, 0.2, 0.3, 0.5), (20180101, 0.2, 0.3, 0.5),
         (20180201, 0.13, 0.37, 0.5), (20180301, 0.13, 0.37, 0.5),
         (20180401, 0.13, 0.37, 0.5), (20180501, 0.13, 0.37, 0.5),
         (20180601, 0.13, 0.37, 0.5), (20180701, 0.13, 0.37, 0.5),
         (20180801, 0.13, 0.37, 0.5), (20180901, 0.13, 0.37, 0.5),
         (20181001, 0.13, 0.37, 0.5), (20181101, 0.13, 0.37, 0.5),
         (20181201, 0.13, 0.37, 0.5), (20190101, 0.13, 0.37, 0.5),
         (20190201, 0.1, 0.4, 0.5), (20190301, 0.1, 0.4, 0.5),
         (20190401, 0.1, 0.4, 0.5), (20190501, 0.1, 0.4, 0.5),
         (20190601, 0.1, 0.4, 0.5), (20190701, 0.1, 0.4, 0.5),
         (20190801, 0.1, 0.4, 0.5), (20190901, 0.1, 0.4, 0.5),
         (20191001, 0.1, 0.4, 0.5), (20191101, 0.1, 0.4, 0.5),
         (20191201, 0.1, 0.4, 0.5), (20200101, 0.1, 0.4, 0.5)
     ]
     self.yValueAxis.requiredRange = None
     self.yValueAxis.leftAxisPercent = 0
     self.yValueAxis.leftAxisOrigShiftMin = 0
     self.yValueAxis.leftAxisOrigShiftIPC = 0
     self.lines[0].strokeColor = colors.toColor(0x0033cc)
     self.lines[1].strokeColor = colors.toColor(0x99c3ff)
     self.lines[2].strokeColor = colors.toColor(0xCC0033)
def _test0(self):
    "This makes one long multi-page paragraph."

    # Build story.
    story = []
    a = story.append

    styleSheet = getSampleStyleSheet()
    h1 = styleSheet['Heading1']
    h1.pageBreakBefore = 1
    h1.keepWithNext = 1

    h2 = styleSheet['Heading2']
    h2.frameBreakBefore = 1
    h2.keepWithNext = 1

    h3 = styleSheet['Heading3']
    h3.backColor = colors.cyan
    h3.keepWithNext = 1

    bt = styleSheet['BodyText']
    btj = ParagraphStyle('bodyText1j', parent=bt, alignment=TA_JUSTIFY)
    btr = ParagraphStyle('bodyText1r', parent=bt, alignment=TA_RIGHT)
    btc = ParagraphStyle('bodyText1c', parent=bt, alignment=TA_CENTER)
    a(
        Paragraph(
            """
        <a name='top'/>Subsequent pages test pageBreakBefore, frameBreakBefore and
        keepTogether attributes.  Generated at %s.  The number in brackets
        at the end of each paragraph is its position in the story. (%d)""" %
            (time.ctime(time.time()), len(story)), bt))

    for i in xrange(10):
        a(Paragraph('Heading 1 always starts a new page (%d)' % len(story),
                    h1))
        for j in xrange(3):
            a(
                Paragraph(
                    'Heading1 paragraphs should always'
                    'have a page break before.  Heading 2 on the other hand'
                    'should always have a FRAME break before (%d)' %
                    len(story), bt))
            a(
                Paragraph(
                    'Heading 2 always starts a new frame (%d)' % len(story),
                    h2))
            a(
                Paragraph(
                    'Heading1 paragraphs should always'
                    'have a page break before.  Heading 2 on the other hand'
                    'should always have a FRAME break before (%d)' %
                    len(story), bt))
            for j in xrange(3):
                a(
                    Paragraph(
                        randomText(theme=PYTHON, sentences=2) +
                        ' (%d)' % len(story), bt))
                a(
                    Paragraph(
                        'I should never be at the bottom of a frame (%d)' %
                        len(story), h3))
                a(
                    Paragraph(
                        randomText(theme=PYTHON, sentences=1) +
                        ' (%d)' % len(story), bt))

    for align, bts in [('left', bt), ('JUSTIFIED', btj), ('RIGHT', btr),
                       ('CENTER', btc)]:
        a(Paragraph('Now we do &lt;br/&gt; tests(align=%s)' % align, h1))
        a(Paragraph('First off no br tags', h3))
        a(Paragraph(_text1, bts))
        a(Paragraph("&lt;br/&gt; after 'the' in line 4", h3))
        a(
            Paragraph(_text1.replace('forms of the', 'forms of the<br/>', 1),
                      bts))
        a(Paragraph("2*&lt;br/&gt; after 'the' in line 4", h3))
        a(
            Paragraph(
                _text1.replace('forms of the', 'forms of the<br/><br/>', 1),
                bts))
        a(Paragraph("&lt;br/&gt; after 'I suggested ' in line 5", h3))
        a(Paragraph(_text1.replace('I suggested ', 'I suggested<br/>', 1),
                    bts))
        a(Paragraph("2*&lt;br/&gt; after 'I suggested ' in line 5", h3))
        a(
            Paragraph(
                _text1.replace('I suggested ', 'I suggested<br/><br/>', 1),
                bts))
        a(Paragraph("&lt;br/&gt; at the end of the paragraph!", h3))
        a(Paragraph("""text one<br/>text two<br/>""", bts))
        a(Paragraph("Border with &lt;br/&gt; at the end of the paragraph!",
                    h3))
        bt1 = ParagraphStyle('bodyText1', bts)
        bt1.borderWidth = 0.5
        bt1.borderColor = colors.toColor('red')
        bt1.backColor = colors.pink
        bt1.borderRadius = 2
        bt1.borderPadding = 3
        a(Paragraph("""text one<br/>text two<br/>""", bt1))
        a(Paragraph("Border no &lt;br/&gt; at the end of the paragraph!", h3))
        bt1 = ParagraphStyle('bodyText1', bts)
        bt1.borderWidth = 0.5
        bt1.borderColor = colors.toColor('red')
        bt1.backColor = colors.pink
        bt1.borderRadius = 2
        bt1.borderPadding = 3
        a(Paragraph("""text one<br/>text two""", bt1))
        a(Paragraph("Different border style!", h3))
        bt2 = ParagraphStyle('bodyText1', bt1)
        bt2.borderWidth = 1.5
        bt2.borderColor = colors.toColor('blue')
        bt2.backColor = colors.gray
        bt2.borderRadius = 3
        bt2.borderPadding = 3
        a(Paragraph("""text one<br/>text two<br/>""", bt2))
    for i in 0, 1, 2:
        P = Paragraph(
            """This is a paragraph with <font color='blue'><a href='#top'>with an incredibly
long and boring link in side of it that
contains lots and lots of stupidly boring and worthless information.
So that we can split the link and see if we get problems like Dinu's.
I hope we don't, but you never do Know.</a></font>""", bt)
        a(P)

    doc = MyDocTemplate(outputfile('test_platypus_breaking.pdf'))
    doc.multiBuild(story)
Example #47
0
def main(opts):
    if opts.landscape and opts.radial:
        print("Ignoring radial for landscape mode")
        opts.radial = False

    pagesize = page_sizes[opts.pagesize]
    if opts.landscape:
        pagesize = pagesize[1], pagesize[0]

    opts.rules = [ x.split() for x in opts.rules ] if opts.rules else []
    opts.slants = [ x.split() for x in opts.slants ] if opts.slants else []
    opts.bleed = opts.bleed.lower()

    c = canvas.Canvas(opts.output, bottomup = 1, pagesize = pagesize, cropMarks = (opts.bleed == "crop"))
    if opts.bleed == "none":
        pagesize = ( pagesize[0] - 72, pagesize[1] - 72 )
        c.translate(36, 36)
    if opts.mirror:
        c.translate(pagesize[0], 0)
        c.scale(-1, 1)

    c.setAuthor(__AUTHOR__)
    if opts.title:
        try:
            opts.title = opts.title%(opts.nib_width)
        except:
            0
    else:
        opts.title = "%smm nib"%(opts.nib_width)
    c.setTitle(opts.title)

    def subj_list(x): return '[' + x + ']'
    opts.subject = ""
    if opts.line_weight != 1 or opts.line_alpha != 1:
        opts.subject += "Line:"
        if opts.line_alpha != 1:
            opts.subject += " alpha=%.1f"%opts.line_alpha
        if opts.line_weight != 1:
            opts.subject += "%s weight=%.1f"%(("," if opts.line_alpha != 1 else ""), opts.line_weight)
        opts.subject += "  "
    if opts.rules:
        opts.subject += "Rules: " + ", ".join(map(subj_list, (", ".join(x) for x in opts.rules)))
    if opts.gap:
        opts.subject += "  Gap: %.1f"%opts.gap
    if opts.slants:
        opts.subject += "  Slants: " + ", ".join(map(subj_list, (", ".join(x) for x in opts.slants)))
    if opts.font and opts.font_size and opts.letters:
        opts.subject += "  Font: " + opts.font
        if opts.font_size:
            opts.subject += "  Size: %.1f"%opts.font_size
    c.setSubject(opts.subject)

    while True:
        ink = toColor("black")
        c.setFillColor(ink)
        c.setStrokeColor(ink)

        if opts.font and opts.font_size:
            try:
                c.setFont(opts.font, opts.font_size)
            except:
                try:
                    pdfmetrics.registerFont(TTFont('myfont', opts.font))
                except:
                    pdfmetrics.registerFont(TTFont('myfont', opts.font + '.ttf'))
                c.setFont('myfont', opts.font_size)

        write_title_and_credits(c, opts, pagesize)

        if not opts.radial:
            draw_lines(c, opts, pagesize)
        else:
            x, y = pagesize
            center = (x/2.0, y/2.0)
            # draw_radial_width_markers(canvas, center, opts.nib_width)
            draw_circles(c, opts.nib_width, opts.rules, opts.gap, opts.rulings, opts.top_margin, center)

        c.showPage()

        if len(opts.letters) == 0:
            break

    c.save()
Example #48
0
 def __init__(self,
              deptdict,
              pagesize=landscape,
              titletext='Breakdown by Department',
              *args,
              **kw):
     '''
 container object for cluster vbc
 posn is 2-tuple of co-ordinates
 chartsize is 2-tuple of (width,hight)
 deptdict is {<dept>:(<num of SA>,...),...}
 deptdict example {"dept1":[23,43,12,1,34],
                   "dept2":[12,23,54,34,12],
                   ...}
 '''
     #
     pw, ph = pagesize
     cw, ch = (pw - inch, ph / 2.)
     cx, cy = (0.5 * inch, inch)
     # Init a drawing
     Drawing.__init__(self, pw, ph, *args, **kw)
     # Add a chart, set properties
     self._add(self,
               VerticalBarChart(),
               name='chart',
               validate=None,
               desc="A chart")
     #                       cw - axis_room - padding
     self.chart.width = cw - 15
     #                       ch - axis_room - title_room
     self.chart.height = ch - 40. - 10
     self.chart.x = cx + 15
     self.chart.y = cy + 15
     #
     nDepts = len(deptdict)
     # chartdata needs to be a 5-tuple (SA,A,..) of answers by dept (34,54,23,..)
     chartdata = []
     # legendpairs needs to be list of 2-tuples (color,deptname)
     legendpairs = []
     for (k, v), i in zip(deptdict.items(), range(nDepts)):
         # k is the dept name
         # v is an answer tuple for that dept
         # Generate new color for each department
         color = toColor('hsl({},100%,50%)'.format(360 * (i + 1) /
                                                   float(nDepts)))
         # Set chart bars to this color
         self.chart.bars[i].fillColor = color
         # Add 5-tuple of data to chart
         chartdata.append(v)
         legendpairs.append((color, k))
     # Axes
     self.chart.fillColor = toColor('rgb(238,240,230)')
     self.chart.barLabels.fontName = 'Helvetica'
     self.chart.valueAxis.labels.fontName = 'Helvetica'
     self.chart.valueAxis.labels.fontSize = 8
     self.chart.valueAxis.forceZero = 1
     self.chart.data = chartdata
     self.chart.groupSpacing = 10
     self.chart.valueAxis.avoidBoundFrac = 1
     self.chart.valueAxis.tickLeft = 3
     self.chart.valueAxis.visibleGrid = 1
     self.chart.categoryAxis.categoryNames = [
         'Strongly Agree', 'Agree', 'Disagree', 'Strongly Disagree',
         'Do Not Know'
     ]
     self.chart.categoryAxis.tickDown = 3
     self.chart.categoryAxis.labels.fontName = 'Helvetica'
     self.chart.categoryAxis.labels.textAnchor = 'middle'
     self.chart.categoryAxis.labels.fontSize = 8
     self.chart.categoryAxis.visibleGrid = 1
     # Title
     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 = 15
     self.Title.x = pw / 2.0
     self.Title.y = ch + cy - 25
     self.Title._text = titletext
     #self.Title.height     = 20
     self.Title.textAnchor = 'middle'
     # Legends
     for i in xrange(len(legendpairs)):  #xrange(7)
         self._add(self,
                   Legend(),
                   name='Legend',
                   validate=None,
                   desc="The legend or key for the chart")
         self.Legend.colorNamePairs = [legendpairs[i]]
         self.Legend.fontName = 'Helvetica'
         self.Legend.fontSize = 6
         self.Legend.x = cx + cw - 220
         self.Legend.y = 2 * ch - 110 - int(130 *
                                            (i / float(len(legendpairs))))
         self.Legend.alignment = 'right'
Example #49
0
def draw_lines(canvas, opts, pagesize):
    if opts.rules:
        ascenders = max(float(x[0]) for x in opts.rules) * opts.nib_width * mm
        descenders = -min(float(x[0]) for x in opts.rules) * opts.nib_width * mm
    else:
        ascenders = pagesize[1]
        descenders = 0

    line_height = ascenders + descenders
    gap = opts.gap * opts.nib_width * mm

    if not opts.slants_per_line:
        for param in opts.slants:
            tantheta = math.tan(parse_angle(param[0]))
            xstep = float(param[1]) * opts.nib_width * mm
            canvas.setLineWidth(float(param[2]) * opts.line_weight)
            set_dash_style(canvas, param[3])
            canvas.setStrokeColor(toColorAlpha(param[4], opts.line_alpha))

            ystep = xstep * tantheta
#           x = 0                                   # origin is at the top left
#           x = ((pagesize[0] - xstep) / 2) % xstep # origin is centre page and between two lines
            x = (pagesize[0] / 2) % xstep           # origin is centre page and on a line
            y = pagesize[1] - x * tantheta
            while x <= pagesize[0] and y >= 0:
                canvas.line(0, y, x, pagesize[1])
                x += xstep
                y -= ystep
            if y > 0:
                h = pagesize[0] * tantheta
                while y >= 0:
                    canvas.line(0, y, pagesize[0], y + h)
                    y -= ystep
                x = -y / tantheta
                y = (pagesize[0] - x) * tantheta
                while x < pagesize[0]:
                    canvas.line(x, 0, pagesize[0], y)
                    x += xstep
                    y -= ystep
            else:
                while x <= pagesize[0]:
                    canvas.line(-y / tantheta, 0, x, pagesize[1])
                    x += xstep
                    y -= ystep
                y = pagesize[1] - (x - pagesize[0]) * tantheta
                while y > 0:
                    canvas.line(pagesize[0], y, pagesize[0] - y / tantheta, 0)
                    y -= ystep

    if opts.top_colour and opts.top_margin > 0:
        canvas.saveState()
        canvas.setFillColor(toColorAlpha(opts.top_colour, opts.top_alpha))
        canvas.rect(0, pagesize[1], pagesize[0], -opts.top_margin * opts.nib_width * mm, stroke = 0, fill = 1)
        canvas.restoreState()

    offset = (2 * opts.bar_width + opts.offset * opts.nib_width) * mm
    position = pagesize[1] - (opts.top_margin * opts.nib_width * mm);
    while position >= line_height:
        position -= ascenders

        if opts.gap_colour and gap > 0:
            canvas.saveState()
            canvas.setFillColor(toColorAlpha(opts.gap_colour, opts.gap_alpha))
            canvas.rect(0, position - descenders, pagesize[0], -min(gap, position-descenders), stroke = 0, fill = 1)
            canvas.restoreState()

        if opts.letters:
            t = canvas.beginText()
            t.setTextOrigin(offset, position)
            t.textOut(opts.letters[0])
            canvas.drawText(t)
            opts.letters = opts.letters[1:]

        for param in opts.rules:
            if len(param) < 4:
                continue
            pos = position + float(param[0]) * opts.nib_width * mm
            canvas.setLineWidth(float(param[1]) * opts.line_weight)
            set_dash_style(canvas, param[2])
            canvas.setStrokeColor(toColorAlpha(param[3], opts.line_alpha))

            canvas.line(0, pos, pagesize[0], pos)

        if opts.slants_per_line:
            for param in opts.slants:
                tantheta = math.tan(parse_angle(param[0]))
                xstep = float(param[1]) * opts.nib_width * mm
                canvas.setLineWidth(float(param[2]) * opts.line_weight)
                set_dash_style(canvas, param[3])
                canvas.setStrokeColor(toColorAlpha(param[4], opts.line_alpha))

                x1 = offset - descenders * tantheta
                y1 = position - descenders
                x2 = offset + ascenders * tantheta
                y2 = position + ascenders
                while x1 < offset:
                    canvas.line(offset, y1 + (-x1 + offset) / tantheta, x2, y2)
                    x1 += xstep
                    x2 += xstep
                while x2 <= pagesize[0]:
                    canvas.line(x1, y1, x2, y2)
                    x1 += xstep
                    x2 += xstep
                while x1 < pagesize[0]:
                    canvas.line(x1, y1, pagesize[0], y2 - (x2 - pagesize[0]) / tantheta)
                    x1 += xstep
                    x2 += xstep

        canvas.setFillColor(toColor('black'))
        barpos = 0
        pos = position
        while pos < position + ascenders:
            barpos = (barpos + 1) % 2
            canvas.rect(barpos * opts.bar_width * mm, pos, opts.bar_width * mm, opts.nib_width * mm, stroke = 0, fill = 1)
            canvas.rect(pagesize[0] - barpos * opts.bar_width * mm, pos, opts.bar_width * mm, opts.nib_width * mm, stroke = 0, fill = 1)
            pos += opts.nib_width * mm

        barpos = 1
        pos = position
        while pos > position - descenders:
            barpos = (barpos + 1) % 2
            canvas.rect(barpos * opts.bar_width * mm, pos, opts.bar_width * mm, -opts.nib_width * mm, stroke = 0, fill = 1)
            canvas.rect(pagesize[0] - barpos * opts.bar_width * mm, pos, opts.bar_width * mm, -opts.nib_width * mm, stroke = 0, fill = 1)
            pos -= opts.nib_width * mm

        position -= descenders + opts.gap * opts.nib_width * mm
Example #50
0
def draw_story_front(c, story, positions, position=0, counter=0):
    c.saveState()
    pos = positions[position]
    size = SIZE
    c.translate(pos[0]*cm, pos[1]*cm)
    c.setStrokeColorRGB(0.2, 0.5, 0.3)
    c.rect(0, 0, size[0]*cm, size[1]*cm, fill=0)
    c.line(0, (SIZE[1]-TOP_HEIGHT)*cm, size[0]*cm, (SIZE[1]-TOP_HEIGHT)*cm)

    stylesheet = getSampleStyleSheet()
    normalStyle = stylesheet['Normal']
    # Color
    try:
        color = toColor(story.color)
    except ValueError:
        color = toColor("#ffffff")

    c.setFillColor(color)
    c.setStrokeColorRGB(0, 0, 0, alpha=0.1)
    c.rect(0.3*cm, (SIZE[1] - TOP_HEIGHT + 0.3)*cm, 15, (TOP_HEIGHT-0.6)*cm,
           fill=1)

    # theme
    p = Paragraph(u"<font color=gray size=15>{0}</font>".format(story.theme),
                  normalStyle)
    p.wrap(SIZE[0]*cm, 2*cm)
    p.drawOn(c, 1.1*cm, (SIZE[1]-TOP_HEIGHT+0.4)*cm)

    # Point
    if story.points >= 0:
        txt = "{0:.0f}".format(story.points)
        circle_color = toColor("#BBBBBB")
        txt_color = "white"
    else:
        txt = _("n/a")
        circle_color = toColor("#888888")
        txt_color = "black"
    c.setFillColor(circle_color)
    rad = 0.6
    c.setStrokeColorRGB(0, 0, 0, alpha=0.5)
    c.circle((SIZE[0]-rad - 0.3)*cm, (SIZE[1] - TOP_HEIGHT/2)*cm, rad*cm,
             fill=1)
    p = Paragraph(
        u"<para fontSize=20 textColor={0} alignment=center>{1}</font>".format(
            txt_color, txt
        ), normalStyle)
    p.wrap(rad*2*cm, 2*cm)
    p.drawOn(c, (SIZE[0]-(rad*2)-0.29)*cm, (SIZE[1] - TOP_HEIGHT/2 + 0.05)*cm)
    c.setStrokeColorRGB(0, 0, 0, alpha=1.0)

    # Code
    p = Paragraph(u"<font size=25>{0}</font>".format(story.code), normalStyle)
    p.wrap(5*cm, 2*cm)
    p.drawOn(c, 1.1*cm, (SIZE[1]-TOP_HEIGHT+1.5)*cm)

    # Description
    found = False
    font_size = 15
    leading = 20
    while not found:
        style = ParagraphStyle(name='Custom',
                               parent=normalStyle,
                               fontSize=font_size,
                               leading=leading,
                               rightIndent=20,
                               leftIndent=10,
                               spaceBefore=0,
                               spaceAfter=0,
                               alignment=TA_JUSTIFY)
        # print the html version of the story text
        t = loader.get_template("backlog/user_story_text.html")
        text = t.render(Context({
            'story': story,
            'request': {
                'LANGUAGE_CODE': "en"
            }
        }))
        p = Paragraph(text, style)
        aW = SIZE[0]*cm
        aH = (SIZE[1]-TOP_HEIGHT)*cm
        w, h = p.wrap(aW, aH)  # find required space
        if w <= aW and h <= aH:
            p.drawOn(c, 0, (SIZE[1]-TOP_HEIGHT)*cm - h - 0.1*cm)
            found = True
        else:
            font_size -= 1
            leading -= 1
            # raise ValueError("Not enough room")
    # print order
    c.setStrokeColorRGB(0, 0, 0, alpha=0.2)
    p = Paragraph(u"<font size=8 color=#cccccc>{0}</font>".format(
        counter), normalStyle)
    p.wrap(0.5*cm, 0.5*cm)
    p.drawOn(c, 0.2*cm, 0.1*cm)

    c.restoreState()