def makeSwatchSample(self,rowNo, x, y, width, height): baseStyle = self.lines styleIdx = rowNo % len(baseStyle) style = baseStyle[styleIdx] color = style.strokeColor yh2 = y+height/2. lineStyle = getattr(style,'lineStyle',None) if lineStyle=='bar': dash = getattr(style, 'strokeDashArray', getattr(baseStyle,'strokeDashArray',None)) strokeWidth= getattr(style, 'strokeWidth', getattr(style, 'strokeWidth',None)) L = Rect(x,y,width,height,strokeWidth=strokeWidth,strokeColor=color,strokeLineCap=0,strokeDashArray=dash,fillColor=getattr(style,'fillColor',color)) elif self.joinedLines or lineStyle=='joinedLine': dash = getattr(style, 'strokeDashArray', getattr(baseStyle,'strokeDashArray',None)) strokeWidth= getattr(style, 'strokeWidth', getattr(style, 'strokeWidth',None)) L = Line(x,yh2,x+width,yh2,strokeColor=color,strokeLineCap=0) if strokeWidth: L.strokeWidth = strokeWidth if dash: L.strokeDashArray = dash else: L = None if hasattr(style, 'symbol'): S = style.symbol elif hasattr(baseStyle, 'symbol'): S = baseStyle.symbol else: S = None if S: S = uSymbol2Symbol(S,x+width/2.,yh2,color) if S and L: g = Group() g.add(L) g.add(S) return g return S or L
def makeInnerTiles(self): # inner grid lines group = Group() w, h = self.width, self.height # inner grid stripes (solid rectangles) if self.useRects == 1: cols = self.stripeColors if self.orientation == 'vertical': r = self.makeLinePosList(self.x, isX=1) elif self.orientation == 'horizontal': r = self.makeLinePosList(self.y, isX=0) dist = makeDistancesList(r) i = 0 for j in range(len(dist)): if self.orientation == 'vertical': x = r[j] stripe = Rect(x, self.y, dist[j], h) elif self.orientation == 'horizontal': y = r[j] stripe = Rect(self.x, y, w, dist[j]) stripe.fillColor = cols[i % len(cols)] stripe.strokeColor = None group.add(stripe) i = i + 1 return group
def create_header(self): headerCanvas = Drawing() headerRect = Rect(0, 0, width=self.width, height=50) headerRect.fillColor = HexColor("#607D8B") headerRect.strokeColor = HexColor("#607D8B") headerCanvas.add(headerRect) renderPDF.draw(headerCanvas, self.c, 0, self.height - 50) _header_styles = ParagraphStyle( "Header", parent=self.styles["Heading1"], textColor=white, fontName='Helvetica' ) p = Paragraph("Kit Trading Fund Report", style = _header_styles) p.wrapOn(self.c, self.width, self.height - 50) p.drawOn(self.c, *self.coord(75, 10, mm)) _sub_header_styles = ParagraphStyle( "SubHeader", parent=self.styles["Heading4"], textColor=white, fontName='Helvetica' ) p = Paragraph("Monthly Report: January 2016", style = _sub_header_styles) p.wrapOn(self.c, self.width, self.height - 50) p.drawOn(self.c, *self.coord(85, 16, mm))
def _draw_segment(self, cur_drawing): """Draw the current chromosome segment. """ # set the coordinates of the segment -- it'll take up the MIDDLE part # of the space we have. segment_y = self.end_y_position segment_width = (self.end_x_position - self.start_x_position) \ * self.chr_percent segment_height = self.start_y_position - self.end_y_position segment_x = self.start_x_position \ + 0.5 * (self.end_x_position - self.start_x_position - segment_width) # first draw the sides of the segment right_line = Line(segment_x, segment_y, segment_x, segment_y + segment_height) left_line = Line(segment_x + segment_width, segment_y, segment_x + segment_width, segment_y + segment_height) cur_drawing.add(right_line) cur_drawing.add(left_line) # now draw the box, if it is filled in if self.fill_color is not None: fill_rectangle = Rect(segment_x, segment_y, segment_width, segment_height) fill_rectangle.fillColor = self.fill_color fill_rectangle.strokeColor = None cur_drawing.add(fill_rectangle)
def colorTest(self): from reportlab.graphics.shapes import Rect from reportlab.graphics.charts.textlabels import Label self.colorRangeStatic(130) dim=25 width = self.PAGE_WIDTH-150 inrow = 8 #int(width/dim) height = int(len(self.colors)/inrow) if len(self.colors)%inrow > 0: height +=1 height *= dim drawing = Drawing(width, height) for i,col in enumerate(self.colors): x = (i%inrow)*dim y = int(i/inrow)*dim rec = Rect(x=x,y=y,width=dim,height=dim) rec.fillColor = col drawing.add(rec) lab = Label() lab.x=x+dim/2 lab.y=y+dim/2 lab.setText('%d'%i) drawing.add(lab) return drawing
def _draw_square(self, color): "draws a square" square = Drawing(5, 5) sqr = Rect(0, 2.5, 5, 5) sqr.fillColor = color sqr.strokeColor = color square.add(sqr) return square
def makeEmptySquare(x, y, size, color): "Make an empty square marker." d = size/2.0 rect = Rect(x-d, y-d, 2*d, 2*d) rect.strokeColor = color rect.fillColor = None return rect
def makeFilledSquare(x, y, size, color): "Make a filled square marker." d = size/2.0 rect = Rect(x-d, y-d, 2*d, 2*d) rect.strokeColor = color rect.fillColor = color return rect
def draw_square(color): "draws a square" from reportlab.graphics.shapes import Rect from reportlab.graphics.shapes import Drawing square = Drawing(5, 5) sqr = Rect(0, 2.5, 5, 5) sqr.fillColor = color sqr.strokeColor = color square.add(sqr) return square
def makeOuterRect(self): strokeColor = getattr(self,'rectStrokeColor',self.strokeColor) strokeWidth = getattr(self,'rectStrokeWidth',self.strokeWidth) if self.fillColor or (strokeColor and strokeWidth): rect = Rect(self.x, self.y, self.width, self.height) rect.fillColor = self.fillColor rect.strokeColor = strokeColor rect.strokeWidth = strokeWidth return rect else: return None
def draw(self): # general widget bits group = Group() x, y, w, h, c0, c1 = self._flipRectCorners() numShades = self.numShades if self.cylinderMode: if not numShades % 2: numShades = numShades + 1 halfNumShades = (numShades - 1) / 2 + 1 num = float(numShades) # must make it float! vertical = self.orientation == 'vertical' if vertical: if numShades == 1: V = [x] else: V = frange(x, x + w, w / num) else: if numShades == 1: V = [y] else: V = frange(y, y + h, h / num) for v in V: stripe = vertical and Rect(v, y, w / num, h) or Rect( x, v, w, h / num) if self.cylinderMode: if V.index(v) >= halfNumShades: col = colors.linearlyInterpolatedColor( c1, c0, V[halfNumShades], V[-1], v) else: col = colors.linearlyInterpolatedColor( c0, c1, V[0], V[halfNumShades], v) else: col = colors.linearlyInterpolatedColor(c0, c1, V[0], V[-1], v) stripe.fillColor = col stripe.strokeColor = col stripe.strokeWidth = 1 group.add(stripe) if self.strokeColor and self.strokeWidth >= 0: rect = Rect(x, y, w, h) rect.strokeColor = self.strokeColor rect.strokeWidth = self.strokeWidth rect.fillColor = None group.add(rect) return group
def create_performance_chart_header(self): _width = self.width _height = 20 headerCanvas = Drawing() headerRect = Rect(0, 0, width = _width, height = _height) headerRect.fillColor = HexColor("#607D8B") headerRect.strokeColor = HexColor("#607D8B") headerCanvas.add(headerRect) renderPDF.draw(headerCanvas, self.c, 0, self.height - 217) _summary_styles = ParagraphStyle( "PERFORMANCE CHART", parent=self.styles["Heading5"], textColor=white, fontName='Helvetica' ) p = Paragraph("PERFORMANCE", style = _summary_styles) p.wrapOn(self.c, _width, _height) p.drawOn(self.c, *self.coord(4, 75, mm))
def create_risk_header(self): _width = self.width / 2 - 10 _height = 20 headerCanvas = Drawing() headerRect = Rect(0, 0, width = _width, height = _height) headerRect.fillColor = HexColor("#607D8B") headerRect.strokeColor = HexColor("#607D8B") headerCanvas.add(headerRect) renderPDF.draw(headerCanvas, self.c, x = _width + 20, y = self.height - 75) _summary_styles = ParagraphStyle( "RISKS", parent=self.styles["Heading5"], textColor=white, fontName='Helvetica' ) p = Paragraph("RISKS", style = _summary_styles) p.wrapOn(self.c, _width, _height) p.drawOn(self.c, *self.coord(115, 25, mm))
def add_vdimstr(arrow, dim, scale, x, y, boundsln_len): """Add a measurement label to the given vertical dimension arrow.""" dim_scaled = dim * inch * scale dim_str = String(x + boundsln_len / 2 + 2, y + dim_scaled / 2 - 4, dimstr(dim) + '"', textAnchor='end', fontSize=9) bnds = dim_str.getBounds() whiteout_r = Rect(bnds[0], bnds[1], bnds[2] - bnds[0], dim_str.fontSize, fillColor=colors.white, strokeColor=colors.white) arrow.add(whiteout_r) arrow.add(dim_str) return arrow
def draw(self): if not self._BCC: raise NotImplementedError("Abstract class %s cannot be drawn" % self.__class__.__name__) self.canv = self G = Group() self._Gadd = G.add self._Gadd( Rect(self.x, self.y, self.width, self.height, fillColor=None, strokeColor=None, strokeWidth=0.0001)) self._BCC.draw(self) del self.canv, self._Gadd return G
def add_hdimstr(arrow, dim, scale, x, y): """Add a measurement label to the given horizontal dimension arrow.""" dim_scaled = dim * inch * scale dim_str = String(x + dim_scaled / 2, y - 3, dimstr(dim) + '"', textAnchor='middle', fontSize=9) bounds_rect = dim_str.getBounds() whiteout_rect = Rect(bounds_rect[0], bounds_rect[1], bounds_rect[2] - bounds_rect[0], bounds_rect[3] - bounds_rect[1], fillColor=colors.white, strokeColor=colors.white) arrow.add(whiteout_rect) arrow.add(dim_str) return arrow
def draw(self): ascent = getFont(self.xValueAxis.labels.fontName).face.ascent if ascent == 0: ascent = 0.718 # default (from helvetica) ascent = ascent * self.xValueAxis.labels.fontSize # normalize #basic LinePlot - does the Axes, Ticks etc lp = LinePlot.draw(self) xLabel = self.xLabel if xLabel: #Overall label for the X-axis xl = Label() xl.x = (self.x + self.width) / 2.0 xl.y = 0 xl.fontName = self.xValueAxis.labels.fontName xl.fontSize = self.xValueAxis.labels.fontSize xl.setText(xLabel) lp.add(xl) yLabel = self.yLabel if yLabel: #Overall label for the Y-axis yl = Label() yl.angle = 90 yl.x = 0 yl.y = (self.y + self.height / 2.0) yl.fontName = self.yValueAxis.labels.fontName yl.fontSize = self.yValueAxis.labels.fontSize yl.setText(yLabel) lp.add(yl) # do a bounding box - in the same style as the axes if self.outerBorderOn: lp.add( Rect(self.x, self.y, self.width, self.height, strokeColor=self.outerBorderColor, strokeWidth=self.yValueAxis.strokeWidth, fillColor=None)) lp.shift(self.leftPadding, self.bottomPadding) return lp
def __init__(self,width=200,height=100,*args,**kw): Drawing.__init__(self,width,height,*args,**kw) self.transform = (1,0,0,1,0,0) self.add(Rect(0,90,10,10,rx=0,ry=0,fillColor=Color(1,0,0,1),fillOpacity=None,strokeColor=Color(0,0,0,1),strokeWidth=1,strokeLineCap=0,strokeLineJoin=0,strokeMiterLimit=0,strokeDashArray=None,strokeOpacity=None)) self.add(String(15,91.585,'red',textAnchor='start',fontName='Times-Roman',fontSize=10,fillColor=Color(0,0,0,1))) self.add(Rect(0,70,10,10,rx=0,ry=0,fillColor=Color(0,.501961,0,1),fillOpacity=None,strokeColor=Color(0,0,0,1),strokeWidth=1,strokeLineCap=0,strokeLineJoin=0,strokeMiterLimit=0,strokeDashArray=None,strokeOpacity=None)) self.add(String(15,71.585,'green',textAnchor='start',fontName='Times-Roman',fontSize=10,fillColor=Color(0,0,0,1))) self.add(Rect(0,50,10,10,rx=0,ry=0,fillColor=Color(0,0,1,1),fillOpacity=None,strokeColor=Color(0,0,0,1),strokeWidth=1,strokeLineCap=0,strokeLineJoin=0,strokeMiterLimit=0,strokeDashArray=None,strokeOpacity=None)) self.add(String(15,51.585,'blue',textAnchor='start',fontName='Times-Roman',fontSize=10,fillColor=Color(0,0,0,1))) self.add(Rect(75,90,10,10,rx=0,ry=0,fillColor=Color(1,1,0,1),fillOpacity=None,strokeColor=Color(0,0,0,1),strokeWidth=1,strokeLineCap=0,strokeLineJoin=0,strokeMiterLimit=0,strokeDashArray=None,strokeOpacity=None)) self.add(String(90,91.585,'yellow',textAnchor='start',fontName='Times-Roman',fontSize=10,fillColor=Color(0,0,0,1))) self.add(Rect(75,70,10,10,rx=0,ry=0,fillColor=Color(1,.752941,.796078,1),fillOpacity=None,strokeColor=Color(0,0,0,1),strokeWidth=1,strokeLineCap=0,strokeLineJoin=0,strokeMiterLimit=0,strokeDashArray=None,strokeOpacity=None)) self.add(String(90,71.585,'pink',textAnchor='start',fontName='Times-Roman',fontSize=10,fillColor=Color(0,0,0,1))) self.add(Rect(75,50,10,10,rx=0,ry=0,fillColor=Color(0,0,0,1),fillOpacity=None,strokeColor=Color(0,0,0,1),strokeWidth=1,strokeLineCap=0,strokeLineJoin=0,strokeMiterLimit=0,strokeDashArray=None,strokeOpacity=None)) self.add(String(90,51.585,'black',textAnchor='start',fontName='Times-Roman',fontSize=10,fillColor=Color(0,0,0,1))) self.add(Rect(150,90,10,10,rx=0,ry=0,fillColor=Color(1,1,1,1),fillOpacity=None,strokeColor=Color(0,0,0,1),strokeWidth=1,strokeLineCap=0,strokeLineJoin=0,strokeMiterLimit=0,strokeDashArray=None,strokeOpacity=None)) self.add(String(165,91.585,'white',textAnchor='start',fontName='Times-Roman',fontSize=10,fillColor=Color(0,0,0,1)))
def add_vdimstr_iso(arrow, dim, scale, x, y, boundsln_len): """Add a measurement label to the given isometric vert dimension arrow.""" dim_scaled = dim * inch * scale off = math.sqrt((boundsln_len / 2)**2 / 2) dim_str = String(x - off - 2, y + dim_scaled / 2 - 4, dimstr(dim) + '"', textAnchor='start', fontSize=9) bnds = dim_str.getBounds() whiteout_r = Rect(bnds[0], bnds[1], bnds[2] - bnds[0], dim_str.fontSize, fillColor=colors.white, strokeColor=colors.white) arrow.add(whiteout_r) arrow.add(dim_str) return arrow
def draw(self): dx = self.width / 16.0 dy = self.height / 16.0 g = Group() g.add( Rect(self.x, self.y, self.width, self.height, fillColor=None, strokeColor=colors.black)) for x in range(16): for y in range(16): charValue = y * 16 + x if charValue > 32: s = String(self.x + x * dx, self.y + (self.height - y * dy), chr(charValue)) g.add(s) return g
def panel_drawing(name, hdim, vdim, scale=DEFAULT_PANEL_SCALE, padding=6, material=None, thickness=None): """Create an individual panel Drawing of the named panel.""" # Calculate the width and height of the panel rectangle in points. hdim_scaled = hdim * inch * scale vdim_scaled = vdim * inch * scale # We might need 36 pts of space on left of rectangle to be safe, # for a long vdim_str, like 23 13/16-". result = Drawing(hdim_scaled + 2 * padding + 36, vdim_scaled + 2 * padding + 14 + 4 + 10) # Coordinates of the lower left corner of the rectangle rx = padding + 36 ry = padding + 14 # For the background color, use a little less red variation of # linen (0xfaf0e6). background_clr = colors.HexColor(0xf8f0e6) result.add( Rect(rx, ry, hdim_scaled, vdim_scaled, fillColor=background_clr, strokeWidth=0.75)) # Add the panel name to the top of the drawing. result.add( String(rx + hdim_scaled / 2, ry + vdim_scaled + 4, name, textAnchor='middle')) boundsln_len = 10 result.add(hdimarrow_str(hdim, scale, rx, ry - 9, 0.67, boundsln_len)) result.add(vdimarrow_str(vdim, scale, rx - 9, ry, 0.67, boundsln_len)) if material is not None and thickness is not None: thick_str, matl_str = matl_thick_strs(material, thickness, rx, ry, hdim_scaled, vdim_scaled) result.add(thick_str) result.add(matl_str) return result
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 reportlab.rl_config import invariant as rl_invariant if rl_invariant: import random random.seed(1919315535) 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')
def _Flag_Japan(self): s = _size g = Group() w = self._width = s * 1.5 g.add( Rect(0, 0, w, s, fillColor=colors.mintcream, strokeColor=None, strokeWidth=0)) g.add( Circle(cx=w / 2, cy=s / 2, r=0.3 * w, fillColor=colors.red, strokeColor=None, strokeWidth=0)) return g
def draw(self): fillColor = self.fillColor strokeColor = self.strokeColor g = Group() bg = self.background bd = self.border bdw = self.borderWidth shadow = self.shadow x, y = self.x, self.y if bg: if shadow is not None and 0<=shadow<1: shadow = Color(bg.red*shadow,bg.green*shadow,bg.blue*shadow) self._paintLogo(g,dy=-2.5, dx=2,fillColor=shadow) self._paintLogo(g,fillColor=fillColor,strokeColor=strokeColor, _ocolors=getattr(self,'_ocolors',None),_pagecolors=getattr(self,'_pagecolors',None)) g.skew(kx=self.skewX, ky=self.skewY) g.shift(self._dx,self._dy) G = Group() G.add(g) _w, _h = 130, 86 w, h = self.width, self.height if bg or (bd and bdw): G.insert(0,Rect(0,0,_w,_h,fillColor=bg,strokeColor=bd,strokeWidth=bdw)) if w!=_w or h!=_h: G.scale(w/float(_w),h/float(_h)) angle = self.angle if self.angle: w, h = w/2., h/2. G.shift(-w,-h) G.rotate(angle) G.shift(w,h) xFlip = getattr(self,'xFlip',0) and -1 or 0 yFlip = getattr(self,'yFlip',0) and -1 or 0 if xFlip or yFlip: sx = xFlip or 1 sy = yFlip or 1 G.shift(sx*x+w*xFlip,sy*y+yFlip*h) G = Group(G,transform=(sx,0,0,sy,0,0)) else: G.shift(x,y) return G
def makeSwatchSample(self, rowNo, x, y, width, height): baseStyle = self.strands styleIdx = rowNo % len(baseStyle) style = baseStyle[styleIdx] strokeColor = getattr(style, 'strokeColor', getattr(baseStyle, 'strokeColor', None)) fillColor = getattr(style, 'fillColor', getattr(baseStyle, 'fillColor', None)) strokeDashArray = getattr(style, 'strokeDashArray', getattr(baseStyle, 'strokeDashArray', None)) strokeWidth = getattr(style, 'strokeWidth', getattr(baseStyle, 'strokeWidth', 0)) symbol = getattr(style, 'symbol', getattr(baseStyle, 'symbol', None)) ym = y + height / 2.0 if fillColor is None and strokeColor is not None and strokeWidth > 0: bg = Line(x, ym, x + width, ym, strokeWidth=strokeWidth, strokeColor=strokeColor, strokeDashArray=strokeDashArray) elif fillColor is not None: bg = Rect(x, y, width, height, strokeWidth=strokeWidth, strokeColor=strokeColor, strokeDashArray=strokeDashArray, fillColor=fillColor) else: bg = None if symbol: symbol = uSymbol2Symbol(symbol, x + width / 2., ym, color) if bg: g = Group() g.add(bg) g.add(symbol) return g return symbol or bg
def ab_square(self, **kwargs): """return a drawing the a^2+b^2 part of the pythagorean""" show_grid = kwargs.get('show_grid', 0) count_squares = kwargs.get('count_squares', 0) drawing = Drawing(self.size, self.size) apb = self.a + self.b step = 1. * self.size / apb if show_grid: for i in range(1, apb): drawing.add( Line(0, i * step, self.size, i * step, strokeColor=self.grid_color)) drawing.add( Line(i * step, 0, i * step, self.size, strokeColor=self.grid_color)) drawing.add( Line(0, self.b * step, self.size, self.b * step, strokeColor=self.stroke_color)) drawing.add( Line(self.a * step, 0, self.a * step, self.size, strokeColor=self.stroke_color)) drawing.add( Rect(0, 0, self.size, self.size, fillColor=self.fill_color, strokeColor=self.stroke_color)) return drawing
def autoLegender(chart, title=''): width = 448 height = 230 d = Drawing(width, height) lab = Label() lab.x = 220 #x和y是文字的位置坐标 lab.y = 210 lab.setText(title) lab.fontName = 'msyh' #增加对中文字体的支持 lab.fontSize = 20 d.add(lab) d.background = Rect(0, 0, width, height, strokeWidth=1.5, strokeColor="#000000", fillColor=None) #边框颜色 d.add(chart) return d
def _Flag_China(self): s = _size g = Group() self._width = w = s*1.5 g.add(Rect(0, 0, w, s, fillColor=colors.red, strokeColor=None, strokeWidth=0)) def addStar(x,y,size,angle,g=g,w=s/20,x0=0,y0=s/2): s = Star() s.fillColor=colors.yellow s.angle = angle s.size = size*w*2 s.x = x*w+x0 s.y = y*w+y0 g.add(s) addStar(5,5,3, 0) addStar(10,1,1,36.86989765) addStar(12,3,1,8.213210702) addStar(12,6,1,16.60154960) addStar(10,8,1,53.13010235) return g
def draw(self): g = super(AddedPlot, self).draw() for i in self.g.contents: if isinstance(i, Rect): x = self.xValueAxis.scale(i.x) width = self.xValueAxis.scale( i.width) - self.xValueAxis.scale(0) y = self.yValueAxis.scale(i.y) height = self.yValueAxis.scale( i.height) - self.yValueAxis.scale(0) g.add( Rect(x, y, width, height, strokeColor=i.strokeColor, strokeWidth=i.strokeWidth, fillColor=i.fillColor)) else: g.add(i) return g
def histogram(data, colors, alpha=0.6, bins=40): hist = [] maxx, maxy = None, None for d in data: dx = np.array(d) dmax = dx.max() if dx.shape[0] != 0 else 0.0 if maxx is None or dmax > maxx: maxx = dmax for d in data: dx = np.array(d) cnts = np.zeros(bins) for x in dx: if maxx == 0.0: idx = 0 else: idx = int(np.floor(bins * x / maxx)) if idx == bins: idx = bins - 1 cnts[idx] += 1 cnts = cnts / float(cnts.sum()) hist.append(cnts) if maxy is None or cnts.max() > maxy: maxy = cnts.max() if maxx is None: maxx, maxy = 1.0, 1.0 lpt = PGPlot.blank_plot(maxx, maxy) wid = maxx / bins stkc = HexColor("#111111") stkc.alpha = alpha for h, c in zip(hist, colors): c.alpha = alpha for ii, i in enumerate(h): if i > 0: rc = Rect(ii * wid, 0, wid, i, strokeColor=stkc, strokeWidth=1.0, fillColor=c) lpt.g.add(rc) return lpt
def _logo(self, text): d = Drawing(400, 400) d.add(Rect(50, 50, 300, 300, fillColor=colors.green)) d.add( String( 100, 200, text, fontName="Helvetica-Bold", fontSize=96, fillColor=colors.black, )) d.add( String( 75, 100, "Produced by cve-bin-tool", fontName="Helvetica", fontSize=24, fillColor=colors.black, )) return d
def draw(self): sx = 0.5 fillColor = self.fillColor strokeColor = self.strokeColor shadow = Color(fillColor.red*sx,fillColor.green*sx,fillColor.blue*sx) g = Group() g2= Group() g.add(Rect(fillColor=fillColor, strokeColor=fillColor, x=0, y=0, width=self._w, height=self._h)) sx = (self._w-2)/self._sw() g2.scale(sx,1) self._addPage(g2,strokeWidth=3,dx=2,dy=-2.5,color=shadow) self._addPage(g2,strokeWidth=3,color=strokeColor) g2.scale(1/sx,1) g2.add(self._getText(x=1,y=0,color=shadow)) g2.add(self._getText(x=0,y=1,color=strokeColor)) g2.scale(sx,1) g2.skew(kx=10, ky=0) g2.shift(0,38) g.add(g2) g.scale(self.width/self._w,self.height/self._h) g.shift(self.x,self.y) return g
def autoLegender(chart, title='', width=448, height=230, order='off', categories=[], use_colors=[]): d = Drawing(width, height) d.add(chart) lab = Label() lab.x = width / 2 #x和y是title文字的位置坐标 lab.y = 21 / 23 * height lab.fontName = 'song' #增加对中文字体的支持 lab.fontSize = 20 lab.setText(title) d.add(lab) #颜色图例说明等 if categories != [] and use_colors != []: leg = Legend() leg.x = 500 # 说明的x轴坐标 leg.y = 0 # 说明的y轴坐标 leg.boxAnchor = 'se' # leg.strokeWidth = 4 leg.strokeColor = None leg.subCols[1].align = 'right' leg.columnMaximum = 10 # 图例说明一列最多显示的个数 leg.fontName = 'song' leg.alignment = 'right' leg.colorNamePairs = list(zip(use_colors, tuple(categories))) d.add(leg) if order == 'on': d.background = Rect(0, 0, width, height, strokeWidth=1, strokeColor="#868686", fillColor=None) #边框颜色 return d
def add_ddimstr_iso(arrow, dim, scale, x, y, boundsln_len): """Add a measurement label to the given isometric depth dimension arrow.""" dim_scaled = dim * inch * scale # `iso45' is divided by 2 below because that is how it's calculated # in the isometric_view, above. iso45 = math.sin(math.radians(45)) * dim_scaled / 2 xmid, ymid = x + iso45 / 2, y + iso45 / 2 dim_str = String(xmid - boundsln_len / 2 - 4, ymid - 4, dimstr(dim) + '"', textAnchor='start', fontSize=9) bnds = dim_str.getBounds() whiteout_r = Rect(bnds[0], bnds[1], bnds[2] - bnds[0], dim_str.fontSize, fillColor=colors.white, strokeColor=colors.white) arrow.add(whiteout_r) arrow.add(dim_str) return arrow
def test_11_drawing(self): from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph from reportlab.pdfbase import pdfmetrics from reportlab.graphics.shapes import Drawing, Rect from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) stylesheet = getSampleStyleSheet() elements = [] doc = SimpleDocTemplate("demo.pdf") elements.append(Paragraph('<font name="chsFont">JY.zenist.song - 俊毅</font>', stylesheet['Title'])) elements.append(Spacer(1,12)) d = Drawing(400,200) d.add(Rect(50,50,300,100, fillColor=colors.yellow)) elements.append(d) doc.build(elements)
def _Flag_EU(self): s = _size g = Group() w = self._width = 1.5*s g.add(Rect(0, 0, w, s, fillColor = colors.darkblue, strokeColor = None, strokeWidth=0)) centerx=w/2 centery=s/2 radius=s/3 yradius = radius xradius = radius nStars = 12 delta = 2*pi/nStars for i in range(nStars): rad = i*delta gs = Star() gs.x=cos(rad)*radius+centerx gs.y=sin(rad)*radius+centery gs.size=s/10 gs.fillColor=colors.gold g.add(gs) return g
def _Flag_Turkey(self): s = _size g = Group() box = Rect(0, 0, s * 2, s, fillColor=colors.red, strokeColor=colors.black, strokeWidth=0) g.add(box) whitecircle = Circle(cx=((s * 0.35) * 2), cy=s / 2, r=s * 0.3, fillColor=colors.mintcream, strokeColor=None, strokeWidth=0) g.add(whitecircle) redcircle = Circle(cx=((s * 0.39) * 2), cy=s / 2, r=s * 0.24, fillColor=colors.red, strokeColor=None, strokeWidth=0) g.add(redcircle) ws = Star() ws.angle = 15 ws.size = s / 5 ws.x = (s * 0.5) * 2 + ws.size / 2 ws.y = (s * 0.5) ws.fillColor = colors.mintcream ws.strokeColor = None g.add(ws) return g
def test1(self): #test from Wietse Jacobs from reportlab.lib.styles import ParagraphStyle from reportlab.graphics.shapes import Drawing, Rect normal = ParagraphStyle(name='Normal', fontName='Helvetica', fontSize=8.5, leading=11) header = ParagraphStyle(name='Heading1', parent=normal, fontSize=14, leading=19, spaceAfter=6, keepWithNext=1) d = Drawing(400, 200) d.add(Rect(50, 50, 300, 100)) story = [ Paragraph("The section header", header), d, ] doc = SimpleDocTemplate(outputfile('test_drawing_keepwithnext.pdf')) doc.build(story)
def __init__(self, width=400, height=200, *args, **kw): Drawing.__init__(self, width, height, *args, **kw) self.transform = (1, 0, 0, 1, 0, 0) self.add( Rect(50, 50, 300, 100, rx=0, ry=0, fillColor=Color(1, 1, 0, 1), fillOpacity=None, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=0, strokeDashArray=None, strokeOpacity=None)) self.add( String(180, 100, 'Hello World', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(1, 0, 0, 1))) self.add( String( 180, 86, b'Special characters \xc2\xa2\xc2\xa9\xc2\xae\xc2\xa3\xce\xb1\xce\xb2', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(1, 0, 0, 1)))
def _draw_chart_rect(d, x, y, width, height, format_json): r = Rect(x, y, width, height, fillColor=Color(0.95, 0.95, 0.95, 1)) d.add(r) width += 40 height += 40 text_format = { "rect": [int(width / 2), int(height / 2), width, height], "content": "暂无数据", "position": "middle", "font_name": DefaultFontName, "font_size": 30, "font_color": Color(0.5, 0.5, 0.5, 1) } t = PDFTemplate._draw_text(text_format) d.add(t) if "main_title" in format_json: text_format = { "rect": [0, height, width, height - 15], "content": format_json['main_title'], "position": "start", "font_name": DefaultFontName, "font_size": 15, "font_color": Color(0.5, 0.5, 0.5, 1) } if "main_title_font_name" in format_json: text_format['font_name'] = format_json['main_title_font_name'] if "main_title_font_size" in format_json: text_format['font_size'] = format_json['main_title_font_size'] if "main_title_font_color" in format_json: text_format['font_color'] = format_json[ 'main_title_font_color'] main_title = PDFTemplate._draw_text(text_format) d.add(main_title)
def _Flag_Switzerland(self): s = _size g = Group() self._width = s g.add( Rect(0, 0, s, s, fillColor=colors.red, strokeColor=colors.black, strokeWidth=0)) g.add( Line((s / 2), (s / 5.5), (s / 2), (s - (s / 5.5)), fillColor=colors.mintcream, strokeColor=colors.mintcream, strokeWidth=(s / 5))) g.add( Line((s / 5.5), (s / 2), (s - (s / 5.5)), (s / 2), fillColor=colors.mintcream, strokeColor=colors.mintcream, strokeWidth=s / 5)) return g
def _overdraw_subcomponents(self, cur_drawing): """Draw any annotated features on the chromosome segment. Assumes _draw_segment already called to fill out the basic shape, and assmes that uses the same boundaries. """ # set the coordinates of the segment -- it'll take up the MIDDLE part # of the space we have. segment_y = self.end_y_position segment_width = (self.end_x_position - self.start_x_position) \ * self.chr_percent label_sep = (self.end_x_position - self.start_x_position) \ * self.label_sep_percent segment_height = self.start_y_position - self.end_y_position segment_x = self.start_x_position \ + 0.5 * (self.end_x_position - self.start_x_position - segment_width) left_labels = [] right_labels = [] for f in self.features: try: # Assume SeqFeature objects start = f.location.start end = f.location.end strand = f.strand try: # Handles Artemis colour integers, HTML colors, etc color = _color_trans.translate(f.qualifiers['color'][0]) except Exception: # TODO: ValueError? color = self.default_feature_color fill_color = color name = "" for qualifier in self.name_qualifiers: if qualifier in f.qualifiers: name = f.qualifiers[qualifier][0] break except AttributeError: # Assume tuple of ints, string, and color start, end, strand, name, color = f[:5] color = _color_trans.translate(color) if len(f) > 5: fill_color = _color_trans.translate(f[5]) else: fill_color = color assert 0 <= start <= end <= self.bp_length if strand == +1: # Right side only x = segment_x + segment_width * 0.6 w = segment_width * 0.4 elif strand == -1: # Left side only x = segment_x w = segment_width * 0.4 else: # Both or neither - full width x = segment_x w = segment_width local_scale = segment_height / self.bp_length fill_rectangle = Rect(x, segment_y + segment_height - local_scale * start, w, local_scale * (start - end)) fill_rectangle.fillColor = fill_color fill_rectangle.strokeColor = color cur_drawing.add(fill_rectangle) if name: if fill_color == color: back_color = None else: back_color = fill_color value = (segment_y + segment_height - local_scale * start, color, back_color, name) if strand == -1: self._left_labels.append(value) else: self._right_labels.append(value)
""" >>> from reportlab.graphics.shapes import Rect >>> from reportlab.lib.colors import red, green >>> r = Rect(5, 5, 200, 100) >>> r.fillColor = red >>> r.strokeColor = green >>> r.strokeWidth = 3 >>> """ ) from reportlab.graphics.shapes import Rect from reportlab.lib.colors import red, green d = Drawing(220, 120) r = Rect(5, 5, 200, 100) r.fillColor = red r.strokeColor = green r.strokeWidth = 3 d.add(r) draw(d, "red rectangle with green border") disc( """ <i>Note: In future examples we will omit the import statements.</i> """ ) disc( """ All shapes have a number of properties which can be set.
def __init__(self, width=400, height=200, *args, **kw): Drawing.__init__(self, width, height, *args, **kw) self.transform = (1, 0, 0, 1, 0, 0) self.add( Rect(50, 50, 300, 125, rx=0, ry=0, fillColor=None, fillOpacity=None, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=0, strokeDashArray=None, strokeOpacity=None)) self.add( Rect(50, 52.97619, 50, 11.90476, rx=0, ry=0, fillColor=Color(1, 0, 0, 1), fillOpacity=None, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=0, strokeDashArray=None, strokeOpacity=None)) self.add( Rect(50, 115.4762, 300, 11.90476, rx=0, ry=0, fillColor=Color(1, 0, 0, 1), fillOpacity=None, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=0, strokeDashArray=None, strokeOpacity=None)) self.add( Rect(50, 67.85714, 100, 11.90476, rx=0, ry=0, fillColor=Color(0, .501961, 0, 1), fillOpacity=None, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=0, strokeDashArray=None, strokeOpacity=None)) self.add( Rect(50, 130.3571, 250, 11.90476, rx=0, ry=0, fillColor=Color(0, .501961, 0, 1), fillOpacity=None, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=0, strokeDashArray=None, strokeOpacity=None)) self.add( Rect(50, 82.7381, 150, 11.90476, rx=0, ry=0, fillColor=Color(0, 0, 1, 1), fillOpacity=None, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=0, strokeDashArray=None, strokeOpacity=None)) self.add( Rect(50, 145.2381, 200, 11.90476, rx=0, ry=0, fillColor=Color(0, 0, 1, 1), fillOpacity=None, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=0, strokeDashArray=None, strokeOpacity=None)) self.add( Rect(50, 97.61905, 200, 11.90476, rx=0, ry=0, fillColor=Color(1, 0, 0, 1), fillOpacity=None, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=0, strokeDashArray=None, strokeOpacity=None)) self.add( Rect(50, 160.119, 150, 11.90476, rx=0, ry=0, fillColor=Color(1, 0, 0, 1), fillOpacity=None, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=0, strokeDashArray=None, strokeOpacity=None)) self.add( Line(49, 50, 49, 175, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=0, strokeDashArray=None, strokeOpacity=None)) self.add( Line(49, 50, 44, 50, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=10, strokeDashArray=None, strokeOpacity=None)) self.add( Line(49, 112.5, 44, 112.5, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=10, strokeDashArray=None, strokeOpacity=None)) self.add( Line(49, 175, 44, 175, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=10, strokeDashArray=None, strokeOpacity=None)) v0 = self._nn(Group()) v0.transform = (1, 0, 0, 1, 44, 81.25) v0.add( String(-20, -4, 'Ying', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) v0 = self._nn(Group()) v0.transform = (1, 0, 0, 1, 44, 143.75) v0.add( String(-21.66, -4, 'Yang', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) self.add( Line(50, 50, 350, 50, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=0, strokeDashArray=None, strokeOpacity=None)) self.add( Line(50, 50, 50, 45, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=10, strokeDashArray=None, strokeOpacity=None)) self.add( Line(125, 50, 125, 45, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=10, strokeDashArray=None, strokeOpacity=None)) self.add( Line(200, 50, 200, 45, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=10, strokeDashArray=None, strokeOpacity=None)) self.add( Line(275, 50, 275, 45, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=10, strokeDashArray=None, strokeOpacity=None)) self.add( Line(350, 50, 350, 45, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=10, strokeDashArray=None, strokeOpacity=None)) v0 = self._nn(Group()) v0.transform = (1, 0, 0, 1, 50, 45) v0.add( String(-2.5, -10, '0', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) v0 = self._nn(Group()) v0.transform = (1, 0, 0, 1, 125, 45) v0.add( String(-5, -10, '15', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) v0 = self._nn(Group()) v0.transform = (1, 0, 0, 1, 200, 45) v0.add( String(-5, -10, '30', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) v0 = self._nn(Group()) v0.transform = (1, 0, 0, 1, 275, 45) v0.add( String(-5, -10, '45', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) v0 = self._nn(Group()) v0.transform = (1, 0, 0, 1, 350, 45) v0.add( String(-5, -10, '60', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1)))
def draw(self): g = Group() colorNamePairs = self.colorNamePairs thisx = upperleftx = self.x thisy = upperlefty = self.y - self.dy dx, dy, alignment, columnMaximum = self.dx, self.dy, self.alignment, self.columnMaximum deltax, deltay, dxTextSpace = self.deltax, self.deltay, self.dxTextSpace fontName, fontSize, fillColor = self.fontName, self.fontSize, self.fillColor strokeWidth, strokeColor = self.strokeWidth, self.strokeColor leading = fontSize*1.2 if not deltay: deltay = max(dy,leading)+self.autoYPadding if not deltax: maxWidth = self._calculateMaxWidth(colorNamePairs) deltax = maxWidth+dx+dxTextSpace+self.autoXPadding else: if alignment=='left': maxWidth = self._calculateMaxWidth(colorNamePairs) def gAdd(t,g=g,fontName=fontName,fontSize=fontSize,fillColor=fillColor): t.fontName = fontName t.fontSize = fontSize t.fillColor = fillColor return g.add(t) ascent=getFont(fontName).face.ascent/1000. if ascent==0: ascent=0.718 # default (from helvetica) ascent=ascent*fontSize # normalize columnCount = 0 count = 0 callout = getattr(self,'callout',None) for col, name in colorNamePairs: T = string.split(name and str(name) or '','\n') S = [] # thisy+dy/2 = y+leading/2 y = thisy+(dy-ascent)*0.5 if callout: callout(self,g,thisx,y,colorNamePairs[count]) if alignment == "left": for t in T: # align text to left s = String(thisx+maxWidth,y,t) s.textAnchor = "end" S.append(s) y = y-leading x = thisx+maxWidth+dxTextSpace elif alignment == "right": for t in T: # align text to right s = String(thisx+dx+dxTextSpace, y, t) s.textAnchor = "start" S.append(s) y = y-leading x = thisx else: raise ValueError, "bad alignment" # Make a 'normal' color swatch... if isinstance(col, colors.Color): r = Rect(x, thisy, dx, dy) r.fillColor = col r.strokeColor = strokeColor r.strokeWidth = strokeWidth g.add(r) else: #try and see if we should do better. try: c = copy.deepcopy(col) c.x = x c.y = thisy c.width = dx c.height = dy g.add(c) except: pass map(gAdd,S) if count%columnMaximum == columnMaximum-1: thisx = thisx+deltax thisy = upperlefty columnCount = columnCount + 1 else: thisy = thisy-max(deltay,len(S)*leading) count = count+1 return g
def __init__(self, x, y, width, height, fillColor=colors.black): Rect.__init__(self, x, y, width, height, fillColor=fillColor, strokeColor=None, strokeWidth=0)
from reportlab.graphics.charts.lineplots import SimpleTimeSeriesPlot from reportlab.graphics.charts.legends import Legend from reportlab.graphics.charts.piecharts import Pie from reportlab.lib.colors import PCMYKColor, HexColor from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin, Rect if __name__ == "__main__": c = canvas.Canvas("report.pdf", pagesize=letter) # move the origin up and to the left #c.translate(inch,inch) #c.setFillColorRGB(1,0,1) headerCanvas = Drawing() headerRect = Rect(0, 0, width=650, height=50) headerRect.fillColor = HexColor("#607D8B") headerRect.strokeColor = HexColor("#607D8B") headerCanvas.add(headerRect) renderPDF.draw(headerCanvas, c, 0, 750) c.drawImage("kit-logo.png", 50, 650, width=100, height=100) headerText = c.beginText(200, 750) headerText.textLine("Header Test Text") c.drawText(headerText) chartCanvas = Drawing() chartCanvas.hAlign = 'CENTER' chart = SimpleTimeSeriesPlot()