def sample1a(): "A line plot with non-equidistant points in x-axis." drawing = Drawing(400, 200) data = [((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)), ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6))] lp = LinePlot() lp.x = 50 lp.y = 50 lp.height = 125 lp.width = 300 lp.data = data lp.joinedLines = 1 lp.strokeColor = colors.black lp.lines.symbol = makeMarker("UK_Flag") lp.lines[0].strokeWidth = 2 lp.lines[1].strokeWidth = 4 lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 5 lp.xValueAxis.valueStep = 1 lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 7 lp.yValueAxis.valueStep = 1 drawing.add(lp) return drawing
def __init__(self, width=600, height=250, *args, **kwargs): Drawing.__init__(self, width, height, *args, **kwargs) self.add(VerticalBarChart(), name='chart') self.add(HorizontalLineChart(), name='plot') self.chart.x = 10 self.chart.y = 10 self.chart.width = 500 self.chart.height = 225 self.chart.strokeColor = None self.chart.valueAxis.valueMin = 0 #self.chart.valueAxis.valueMax = 50 #self.chart.valueAxis.valueStep = 10 self.chart.data = [(1, 2, 5), ] self.chart.categoryAxis.visible = 1 self.chart.bars[0].fillColor = colors.green self.chart.bars[1].fillColor = colors.pink self.chart.bars[2].fillColor = colors.red self.chart.categoryAxis.categoryNames = [''] self.plot.x = 10 self.plot.y = 10 self.plot.width = 500 self.plot.height = 225 self.plot.valueAxis.visible = 0 #self.plot.valueAxis.valueMin = 0 #print dir(self.plot.valueAxis) self.plot.lines[0].strokeColor = colors.blue
def sample2(): "Make a spider chart with markers, but no fill" d = Drawing(400, 400) sp = SpiderChart() sp.x = 50 sp.y = 50 sp.width = 300 sp.height = 300 sp.data = [[10,12,14,16,14,12], [6,8,10,12,9,15],[7,8,17,4,12,8]] sp.labels = ['U','V','W','X','Y','Z'] sp.strands.strokeWidth = 1 sp.strands[0].fillColor = colors.pink sp.strands[1].fillColor = colors.lightblue sp.strands[2].fillColor = colors.palegreen sp.strands[0].strokeColor = colors.red sp.strands[1].strokeColor = colors.blue sp.strands[2].strokeColor = colors.green sp.strands.symbol = "FilledDiamond" sp.strands[1].symbol = makeMarker("Circle") sp.strands[1].symbol.strokeWidth = 0.5 sp.strands[1].symbol.fillColor = colors.yellow sp.strands.symbolSize = 6 sp.strandLabels[0,3]._text = 'special' sp.strandLabels[0,1]._text = 'one' sp.strandLabels[0,0]._text = 'zero' sp.strandLabels[1,0]._text = 'Earth' sp.strandLabels[2,2]._text = 'Mars' sp.strandLabels.format = 'values' sp.strandLabels.dR = -5 d.add(sp) return d
def demo(self): """Shows basic use of a line chart.""" drawing = Drawing(400, 200) data = [((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)), ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6))] lp = LinePlot() lp.x = 50 lp.y = 50 lp.height = 125 lp.width = 300 lp.data = data lp.joinedLines = 1 lp.lineLabelFormat = "%2.0f" lp.strokeColor = colors.black lp.lines[0].strokeColor = colors.red lp.lines[0].symbol = makeMarker("FilledCircle") lp.lines[1].strokeColor = colors.blue lp.lines[1].symbol = makeMarker("FilledDiamond") lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 5 lp.xValueAxis.valueStep = 1 lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 7 lp.yValueAxis.valueStep = 1 drawing.add(lp) return drawing
def demo(self): D = Drawing(100, 100) g = Grid() D.add(g) return D
def demo(self): d = Drawing(200, 100) pc = Pie() pc.x = 50 pc.y = 10 pc.width = 100 pc.height = 80 pc.data = [10,20,30,40,50,60] pc.labels = ['a','b','c','d','e','f'] pc.slices.strokeWidth=0.5 pc.slices[3].popout = 10 pc.slices[3].strokeWidth = 2 pc.slices[3].strokeDashArray = [2,2] pc.slices[3].labelRadius = 1.75 pc.slices[3].fontColor = colors.red pc.slices[0].fillColor = colors.darkcyan pc.slices[1].fillColor = colors.blueviolet pc.slices[2].fillColor = colors.blue pc.slices[3].fillColor = colors.cyan pc.slices[4].fillColor = colors.aquamarine pc.slices[5].fillColor = colors.cadetblue pc.slices[6].fillColor = colors.lightcoral self.slices[1].visible = 0 self.slices[3].visible = 1 self.slices[4].visible = 1 self.slices[5].visible = 1 self.slices[6].visible = 0 d.add(pc) return d
def sample2(): "Make a pie chart with nine slices." d = Drawing(400, 200) pc = Pie() pc.x = 125 pc.y = 25 pc.data = [0.31, 0.148, 0.108, 0.076, 0.033, 0.03, 0.019, 0.126, 0.15] pc.labels = ['1', '2', '3', '4', '5', '6', '7', '8', 'X'] pc.width = 150 pc.height = 150 pc.slices.strokeWidth=1#0.5 pc.slices[0].fillColor = colors.steelblue pc.slices[1].fillColor = colors.thistle pc.slices[2].fillColor = colors.cornflower pc.slices[3].fillColor = colors.lightsteelblue pc.slices[4].fillColor = colors.aquamarine pc.slices[5].fillColor = colors.cadetblue pc.slices[6].fillColor = colors.lightcoral pc.slices[7].fillColor = colors.tan pc.slices[8].fillColor = colors.darkseagreen d.add(pc) return d
def demo(self): d = Drawing(200, 100) dn = Doughnut() dn.x = 50 dn.y = 10 dn.width = 100 dn.height = 80 dn.data = [10, 20, 30, 40, 50, 60] dn.labels = ["a", "b", "c", "d", "e", "f"] dn.slices.strokeWidth = 0.5 dn.slices[3].popout = 10 dn.slices[3].strokeWidth = 2 dn.slices[3].strokeDashArray = [2, 2] dn.slices[3].labelRadius = 1.75 dn.slices[3].fontColor = colors.red dn.slices[0].fillColor = colors.darkcyan dn.slices[1].fillColor = colors.blueviolet dn.slices[2].fillColor = colors.blue dn.slices[3].fillColor = colors.cyan dn.slices[4].fillColor = colors.aquamarine dn.slices[5].fillColor = colors.cadetblue dn.slices[6].fillColor = colors.lightcoral d.add(dn) return d
class PieRender(IRender): def __init__(self, width, height, labels, data): IRender.__init__(self, width, height, labels, data) #self.w = self.width #self.h = self.height #data = {} #for value in self.data: # data[value[0]] = int(value[1]) #plot = cairoplot.PiePlot('/tmp/tmp.png', data, self.w*2, self.h*2, gradient=True) ##plot.font_size *= 2 #plot.render() #plot.commit() #with open('/tmp/tmp.png') as f: # self.image = Image(StringIO(f.read()), self.w, self.h) pc = Pie() pc.width = min(self.height,self.width - 150) pc.height = min(self.height - 50,self.width) pc.width = pc.height = min(pc.height, pc.width) pc.x = self.width / 2 - pc.width / 2 pc.y = self.height / 2 - pc.height / 2 pc.data = [int(line[1]) for line in self.data] pc.labels = [line[0] for line in self.data] for i in xrange(len(self.data)): pc.slices[i].fillColor = COLORS[i % len(COLORS)] pc.slices[i].strokeColor = COLORS[i % len(COLORS)] self.drawing = Drawing(self.width, self.height) self.drawing.add(pc) def render(self): return self.drawing
def sample2(): "Make a spider chart with markers, but no fill" d = Drawing(400, 400) pc = SpiderChart() pc.x = 50 pc.y = 50 pc.width = 300 pc.height = 300 pc.data = [[10,12,14,16,14,12], [6,8,10,12,9,15],[7,8,17,4,12,8,3]] pc.labels = ['U','V','W','X','Y','Z'] pc.strands.strokeWidth = 2 pc.strands[0].fillColor = None pc.strands[1].fillColor = None pc.strands[2].fillColor = None pc.strands[0].strokeColor = colors.red pc.strands[1].strokeColor = colors.blue pc.strands[2].strokeColor = colors.green pc.strands.markers = 1 pc.strands.markerType = "FilledDiamond" pc.strands.markerSize = 6 d.add(pc) return d
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)
def demo(self,drawing=None): from reportlab.lib import colors if not drawing: drawing = Drawing(400, 200) lp = AdjLinePlot() lp.x = 50 lp.y = 50 lp.height = 125 lp.width = 300 lp.data = _monthlyIndexData lp.joinedLines = 1 lp.strokeColor = colors.black c0 = colors.PCMYKColor(100,65,0,30, spotName='PANTONE 288 CV', density=100) lp.lines[0].strokeColor = c0 lp.lines[0].strokeWidth = 2 lp.lines[0].strokeDashArray = None c1 = colors.PCMYKColor(0,79,91,0, spotName='PANTONE Wm Red CV', density=100) lp.lines[1].strokeColor = c1 lp.lines[1].strokeWidth = 1 lp.lines[1].strokeDashArray = [3,1] lp.xValueAxis.labels.fontSize = 10 lp.xValueAxis.labels.textAnchor = 'start' lp.xValueAxis.labels.boxAnchor = 'w' lp.xValueAxis.labels.angle = -45 lp.xValueAxis.labels.dx = 0 lp.xValueAxis.labels.dy = -8 lp.xValueAxis.xLabelFormat = '{mm}/{yy}' lp.yValueAxis.labelTextFormat = '%5d%% ' lp.yValueAxis.tickLeft = 5 lp.yValueAxis.labels.fontSize = 10 lp.background = Grid() lp.background.stripeColors = [colors.pink, colors.lightblue] lp.background.orientation = 'vertical' drawing.add(lp,'plot') return drawing
def sample1b(): "A line plot with non-equidistant points in x-axis." drawing = Drawing(400, 200) data = [ ((1,1), (2,2), (2.5,1), (3,3), (4,5)), ((1,2), (2,3), (2.5,2), (3.5,5), (4,6)) ] lp = LinePlot() lp.x = 50 lp.y = 50 lp.height = 125 lp.width = 300 lp.data = data lp.joinedLines = 1 lp.lines.symbol = makeMarker('Circle') lp.lineLabelFormat = '%2.0f' lp.strokeColor = colors.black lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 5 lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5] lp.xValueAxis.labelTextFormat = '%2.1f' lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 7 lp.yValueAxis.valueStep = 1 drawing.add(lp) return drawing
def sample3(): drawing = Drawing(400, 200) data = [ (13, 5, 20, 22, 37, 45, 19, 4), (5, 20, 46, 38, 23, 21, 6, 14) ] lc = HorizontalLineChart() lc.x = 50 lc.y = 50 lc.height = 125 lc.width = 300 lc.data = data lc.joinedLines = 1 lc.lineLabelFormat = '%2.0f' lc.strokeColor = colors.black lc.lines[0].symbol = makeMarker('Smiley') lc.lines[1].symbol = NoEntry lc.lines[0].strokeWidth = 2 lc.lines[1].strokeWidth = 4 catNames = 'Jan Feb Mar Apr May Jun Jul Aug'.split(' ') lc.categoryAxis.categoryNames = catNames lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 15 drawing.add(lc) return drawing
def drawOn(self, canvas): logo = self.logo x, y = logo.x, logo.y w, h = logo.width, logo.height D = Drawing(w, h) D.add(logo) D.drawOn(canvas, 0, 0)
def get_drawing(self, chart): """Create and returns the drawing, to be generated""" drawing = Drawing(self.width, self.height) # Make the title title = self.make_title(drawing) # Setting chart dimensions chart.height = self.height chart.width = self.width # Make the legend legend = self.make_legend(drawing, chart) if title: chart.height -= self.title.get('height', DEFAULT_TITLE_HEIGHT) self.top += self.title.get('height', DEFAULT_TITLE_HEIGHT) # Setting additional chart attributes self.set_chart_style(chart) # Adds the chart to drawing to return drawing.add(chart) # Resizes to make sure everything is fitting drawing = drawing.resized() return drawing
def sample1a(): drawing = Drawing(400, 200) data = [ (13, 5, 20, 22, 37, 45, 19, 4), (5, 20, 46, 38, 23, 21, 6, 14) ] lc = SampleHorizontalLineChart() lc.x = 50 lc.y = 50 lc.height = 125 lc.width = 300 lc.data = data lc.joinedLines = 1 lc.strokeColor = colors.white lc.fillColor = colors.HexColor(0xCCCCCC) lc.lines.symbol = makeMarker('FilledDiamond') lc.lineLabelFormat = '%2.0f' catNames = 'Jan Feb Mar Apr May Jun Jul Aug'.split(' ') lc.categoryAxis.categoryNames = catNames lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 15 drawing.add(lc) return drawing
def test(outDir='out-svg'): # print all drawings and their doc strings from the test # file if not os.path.isdir(outDir): os.mkdir(outDir) #grab all drawings from the test module from reportlab.graphics import testshapes drawings = [] for funcname in dir(testshapes): #if funcname[0:11] == 'getDrawing2': # print 'hacked to only show drawing 2' if funcname[0:10] == 'getDrawing': drawing = eval('testshapes.' + funcname + '()') docstring = eval('testshapes.' + funcname + '.__doc__') drawings.append((drawing, docstring)) i = 0 for (d, docstring) in drawings: filename = os.path.join(outDir,'renderSVG_%d.svg' % i) drawToFile(d, filename) i += 1 from reportlab.graphics.testshapes import getDrawing01 d = getDrawing01() drawToFile(d, os.path.join(outDir,"test.svg")) from reportlab.lib.corp import RL_CorpLogo from reportlab.graphics.shapes import Drawing rl = RL_CorpLogo() d = Drawing(rl.width,rl.height) d.add(rl) drawToFile(d, os.path.join(outDir,"corplogo.svg"))
def __init__(self,width=200,height=150,*args,**kw): Drawing.__init__(self,width,height,*args,**kw) self._add(self,ScatterPlot(),name='chart',validate=None,desc="The main chart") self.chart.width = 115 self.chart.height = 80 self.chart.x = 30 self.chart.y = 40 self.chart.lines[0].strokeColor = color01 self.chart.lines[1].strokeColor = color02 self.chart.lines[2].strokeColor = color03 self.chart.lines[3].strokeColor = color04 self.chart.lines[4].strokeColor = color05 self.chart.lines[5].strokeColor = color06 self.chart.lines[6].strokeColor = color07 self.chart.lines[7].strokeColor = color08 self.chart.lines[8].strokeColor = color09 self.chart.lines[9].strokeColor = color10 self.chart.fillColor = backgroundGrey self.chart.lineLabels.fontName = 'Helvetica' self.chart.xValueAxis.labels.fontName = 'Helvetica' self.chart.xValueAxis.labels.fontSize = 7 self.chart.xValueAxis.forceZero = 0 self.chart.data = [((100,100), (200,200), (250,210), (300,300), (400,500)), ((100,200), (200,300), (250,200), (300,400), (400, 600))] self.chart.xValueAxis.avoidBoundFrac = 1 self.chart.xValueAxis.gridEnd = 115 self.chart.xValueAxis.tickDown = 3 self.chart.xValueAxis.visibleGrid = 1 self.chart.yValueAxis.tickLeft = 3 self.chart.yValueAxis.labels.fontName = 'Helvetica' self.chart.yValueAxis.labels.fontSize = 7 self._add(self,Label(),name='Title',validate=None,desc="The title at the top of the chart") self.Title.fontName = 'Helvetica-Bold' self.Title.fontSize = 7 self.Title.x = 100 self.Title.y = 135 self.Title._text = 'Chart Title' self.Title.maxWidth = 180 self.Title.height = 20 self.Title.textAnchor ='middle' self._add(self,Legend(),name='Legend',validate=None,desc="The legend or key for the chart") self.Legend.colorNamePairs = [(color01, 'Widgets'), (color02, 'Sprockets')] self.Legend.fontName = 'Helvetica' self.Legend.fontSize = 7 self.Legend.x = 153 self.Legend.y = 85 self.Legend.dxTextSpace = 5 self.Legend.dy = 5 self.Legend.dx = 5 self.Legend.deltay = 5 self.Legend.alignment ='right' self.chart.lineLabelFormat = None self.chart.xLabel = 'X Axis' self.chart.y = 30 self.chart.yLabel = 'Y Axis' self.chart.yValueAxis.labelTextFormat = '%d' self.chart.yValueAxis.forceZero = 1 self.chart.xValueAxis.forceZero = 1 self._add(self,0,name='preview',validate=None,desc=None)
def conversion_chart(data, labels): """Create chart that can be drawn as a gif with given data/labels""" drawing = Drawing(500, 400) bc = VerticalBarChart() bc.x = 80 bc.y = 80 bc.height = 290 bc.width = 390 bc.data = data bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 100 bc.valueAxis.valueStep = 10 bc.valueAxis.labelTextFormat = '%2.2f' bc.barLabels.fontSize = 15 bc.barLabelFormat = '%2.2f' bc.barLabels.boxAnchor = 's' bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = 2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = labels drawing.add(bc) return drawing
def draw_bar_chart(pdf_text, page_height): '''Currently generates a dummy graph. Next, need to pass in data that shall be the reactors temp throughout the sequence. ''' pdf_text.showPage() drawing = Drawing(400, 200) data = [ (13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5) ] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = ['Jan-99','Feb-99','Mar-99','Apr-99','May-99','Jun-99','Jul-99','Aug-99'] drawing.add(bc) renderPDF.draw(drawing, pdf_text, inch, inch) return page_height
def print_chunks_chart(self): nChunks = len(self.filechunks) d = Drawing(400, 140) traffic_MB = [n/(1024*1024) for n in self.traffic] data = [traffic_MB] bc = VerticalBarChart() ## bc.x = 0 ## bc.y = 10 bc.height = 100 bc.width = 370 bc.data = data bc.categoryAxis.tickUp = 0.5 bc.categoryAxis.tickDown = 1.5 bc.categoryAxis.categoryNames = [] for n in range(nChunks): if n%5 == 0: bc.categoryAxis.categoryNames.append( str(n) ) else: bc.categoryAxis.categoryNames.append('') bc.bars.strokeWidth = 0.3 bc.valueAxis.labels.fontSize = 6 bc.categoryAxis.labels.fontSize = 6 bc.bars[0].fillColor = colors.lightblue bc.valueAxis.valueMin = 0 d.add(bc) drawing = GraphicsDrawing(d, 'Traffic per chunk in MB') self.story.append(drawing) self.story.append(Spacer(0.01,1.0*cm))
def draw_time_repartition(mandate): drawing = Drawing(width=180*mm, height=120*mm) pdf_chart_colors = [HexColor("#fa9d00"), HexColor("#006884"), HexColor("#00909e"), HexColor("#ffd08d"), ] pie = Pie() pie.x = 60*mm pie.y = 35*mm pie.width = 60*mm pie.height = 60*mm pie.slices.strokeWidth = 0.5 pie.slices.fontName = 'Helvetica' pie.slices.fontSize = 8 pie.data = [] pie.labels = [] titles = [] add_data_and_titles_to_pie(pie, titles, mandate.research_percent, 'research_percent') add_data_and_titles_to_pie(pie, titles, mandate.tutoring_percent, 'tutoring_percent') add_data_and_titles_to_pie(pie, titles, mandate.service_activities_percent, 'service_activities_percent') add_data_and_titles_to_pie(pie, titles, mandate.formation_activities_percent, 'formation_activities_percent') if len(pie.data) > 0: drawing.add(pie) add_legend_to_pie(drawing) n = len(pie.data) set_items(n, pie.slices, 'fillColor', pdf_chart_colors) drawing.legend.colorNamePairs = \ [(pie.slices[i].fillColor, (titles[i], '%0.f' % pie.data[i] + '%')) for i in range(n)] return drawing
def draw_qr_global_id(canvas, survey): if survey.global_id is None: raise AssertionError # Only allow ascii value = survey.global_id.encode('ascii') y = survey.defs.paper_height - defs.corner_mark_bottom x = (survey.defs.paper_width - defs.corner_mark_right + defs.corner_mark_left) / 2 qr_code = qr.QrCodeWidget(value, barLevel='H') bounds = qr_code.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] # Squeeze into the space between corner mark and content size = defs.bottom_page_margin - defs.corner_mark_bottom code_y = y code_x = x - size / 2.0 d = Drawing(size*mm, size*mm, transform=[float(size*mm)/width,0,0,-float(size*mm)/height,0,0]) d.add(qr_code) renderPDF.draw(d, canvas, code_x*mm, code_y*mm)
def draw_qr_sdaps_info(canvas, survey, page): # The page number is one based here already # The survey_id is a 32bit number, which means we need # 10 decimal digits to encode it, then we need to encode the # the page with at least 3 digits(just in case someone is insane enough # to have a questionnaire with more than 99 pages. # So use 10+4 digits value = "%010d%04d" % (survey.survey_id, page) y = survey.defs.paper_height - defs.corner_mark_bottom x = survey.defs.paper_width - defs.corner_mark_right qr_code = qr.QrCodeWidget(value, barLevel='H') bounds = qr_code.getBounds() width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] # Squeeze into the space between corner mark and content size = defs.bottom_page_margin - defs.corner_mark_bottom code_y = y code_x = x - size d = Drawing(size*mm, size*mm, transform=[float(size*mm)/width,0,0,-float(size*mm)/height,0,0]) d.add(qr_code) renderPDF.draw(d, canvas, code_x*mm, code_y*mm)
def demo(self,drawing=None): from reportlab.lib import colors if not drawing: tx,ty=self._getDrawingDimensions() drawing = Drawing(tx,ty) drawing.add(self.draw()) return drawing
def __add_graph(self): drawing = Drawing(200, 100) data = list() labels = list() self.c.drawString(370, 730, 'Distribucion en pesos'.encode('utf-8')) for acc in self.accounts: balance = acc.balance if acc.currency == 'USD': balance = balance * self.dolar data.append(balance) labels.append(acc.name) pie = Pie() pie.x = 280 pie.y = 630 pie.height = 100 pie.width = 100 pie.data = data pie.labels = labels pie.simpleLabels = 1 pie.slices.strokeWidth = 1 pie.slices.strokeColor = black pie.slices.label_visible = 0 legend = Legend() legend.x = 400 legend.y = 680 legend.dx = 8 legend.dy = 8 legend.fontName = 'Helvetica' legend.fontSize = 7 legend.boxAnchor = 'w' legend.columnMaximum = 10 legend.strokeWidth = 1 legend.strokeColor = black legend.deltax = 75 legend.deltay = 10 legend.autoXPadding = 5 legend.yGap = 0 legend.dxTextSpace = 5 legend.alignment = 'right' legend.dividerLines = 1|2|4 legend.dividerOffsY = 4.5 legend.subCols.rpad = 30 n = len(pie.data) self.__setItems(n,pie.slices, 'fillColor',self.pdf_chart_colors) legend.colorNamePairs = [(pie.slices[i].fillColor, (pie.labels[i][0:20],'$%0.2f' % pie.data[i])) for i in xrange(n)] drawing.add(pie) drawing.add(legend) x, y = 0, 0 renderPDF.draw(drawing, self.c, x, y, showBoundary=False)
def createBarCodes(path, barcode_value): from reportlab.graphics.barcode import eanbc from reportlab.graphics.shapes import Drawing from reportlab.pdfgen import canvas from reportlab.graphics import renderPDF from reportlab.lib.units import cm, mm from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus.para import Paragraph # draw the eanbc13 code barcode_eanbc13 = eanbc.Ean13BarcodeWidget(barcode_value) bounds = barcode_eanbc13.getBounds() barcode_eanbc13.barHeight = 19*mm width = bounds[2] - bounds[0] height = bounds[3] - bounds[1] d = Drawing() d.add(barcode_eanbc13) c = canvas.Canvas(path, pagesize=(43*mm, 25*mm)) # print width, height text = "%s.%s" % (150, '00') p = Paragraph(text, getSampleStyleSheet()["Normal"]) p.wrapOn(c, 43*mm, 5*mm) p.drawOn(c, 16*mm, 20*mm) renderPDF.draw(d, c, 3*mm, 1*mm) c.save()
def sample2(): "A line plot with non-equidistant points in x-axis." drawing = Drawing(400, 200) data = [ ( ("25/11/1991", 1), ("30/11/1991", 1.000933333), ("31/12/1991", 1.0062), ("31/01/1992", 1.0112), ("29/02/1992", 1.0158), ("31/03/1992", 1.020733333), ("30/04/1992", 1.026133333), ("31/05/1992", 1.030266667), ("30/06/1992", 1.034466667), ("31/07/1992", 1.038733333), ("31/08/1992", 1.0422), ("30/09/1992", 1.045533333), ("31/10/1992", 1.049866667), ("30/11/1992", 1.054733333), ("31/12/1992", 1.061), ) ] data[0] = preprocessData(data[0]) lp = LinePlot() lp.x = 50 lp.y = 50 lp.height = 125 lp.width = 300 lp.data = data lp.joinedLines = 1 lp.lines.symbol = makeMarker("FilledDiamond") lp.strokeColor = colors.black start = mktime(mkTimeTuple("25/11/1991")) t0 = mktime(mkTimeTuple("30/11/1991")) t1 = mktime(mkTimeTuple("31/12/1991")) t2 = mktime(mkTimeTuple("31/03/1992")) t3 = mktime(mkTimeTuple("30/06/1992")) t4 = mktime(mkTimeTuple("30/09/1992")) end = mktime(mkTimeTuple("31/12/1992")) lp.xValueAxis.valueMin = start lp.xValueAxis.valueMax = end lp.xValueAxis.valueSteps = [start, t0, t1, t2, t3, t4, end] lp.xValueAxis.labelTextFormat = seconds2str lp.xValueAxis.labels[1].dy = -20 lp.xValueAxis.labels[2].dy = -35 lp.yValueAxis.labelTextFormat = "%4.2f" lp.yValueAxis.valueMin = 100 lp.yValueAxis.valueMax = 110 lp.yValueAxis.valueStep = 2 drawing.add(lp) return drawing
def barChart(daten,Versuch,Phaenomene,path=None,vMin=1,vMax=6): """ Plots data to a Drawing and returns the Drawing """ #Festlegen der Gesamtgröße in Pixel d = Drawing(500,160) #Daten für das Diagramm #daten = [(10,6,8)] #Anlegen des Diagramms diagramm = HorizontalBarChart() #Positionierung und Größe des Diagramms diagramm.x = 10 diagramm.y = 30 diagramm.height = 100 diagramm.width = 400 #Hinzufügen der Daten #diagramm.reversePlotOrder = 1 diagramm.data = daten #Y-Achse (in ReportLab „valueAxis“) formatieren diagramm.valueAxis.valueMin = vMin diagramm.valueAxis.valueMax = vMax diagramm.valueAxis.valueStep = 1 #X-Achse (in ReportLab „categoryAxis“) formatieren diagramm.categoryAxis.categoryNames = Phaenomene #Diagramm zeichnen d.add(diagramm) if not path == None: Versuch = path + Versuch renderPM.drawToFile(d, Versuch + ".png", 'PNG') #d = Paragraph(d, centered) d.scale(0.8,0.8) return d
symbol = None return symbol class _isSymbol(Validator): def test(self, x): return hasattr(x, '__call__') or isinstance(x, Marker) or isinstance( x, Flag) or (isinstance(x, type) and issubclass(x, Widget)) isSymbol = _isSymbol() def makeMarker(name, **kw): if Marker._attrMap['kind'].validate(name): m = Marker(**kw) m.kind = name elif name[-5:] == '_Flag' and Flag._attrMap['kind'].validate(name[:-5]): m = Flag(**kw) m.kind = name[:-5] m.size = 10 else: raise ValueError("Invalid marker name %s" % name) return m if __name__ == '__main__': D = Drawing() D.add(Marker()) D.save(fnRoot='Marker', formats=['pdf'], outDir='/tmp')
def genCrimesChart(width, height, title, data): # Title # This will draw a background to the text # 'Crimes per month - 3D Line Chart' backgroundRect = Rect( -2, height - 24, # x and y start position width + 5, 22, # width and height 4, # radius x to round corners stroke=1, fill=1, fillColor=colors.mediumpurple) # title shadow title1 = String( 2, height - 19, # x and y start position f'{title} - 3D Line Chart', fontSize=16, fontName='Helvetica-Bold', fillColor=colors.black) # title text title2 = String( 0, height - 18, # x and y start position f'{title} - 3D Line Chart', fontSize=16, fontName='Helvetica-Bold', fillColor=colors.white) # Chart # For a better understanding of this code please see: # Generate PDF with Python - Reportlab - Create Charts: https://youtu.be/FcZ9wTGmMrw chart = HorizontalLineChart3D() chart.data = [data[1]] chart.x = 5 # position at x chart.y = 20 # position at y chart.height = height - backgroundRect.height - 30 chart.width = width - 5 - 10 # x axis - Months names abbreviated chart.categoryAxis.categoryNames = data[0] # y axis minimum value chart.valueAxis.valueMin = 0 # y axis maximum value chart.valueAxis.valueMax = 500 # y axis, from 0 to 500 step 100, i.e. 0, 100, 200, 300, 400 and 500 chart.valueAxis.valueStep = 100 chart.lines[0].strokeWidth = 3.5 chart.lines[0].strokeColor = colors.red drawing = Drawing() drawing.add(backgroundRect) drawing.add(title1) drawing.add(title2) drawing.add(chart) res = Table([[drawing]], width, height) res.setStyle([ #styles.GRID_BLACK_T1_ALL, styles.LEFT_PADDING_ZERO_ALL, styles.BOTTOM_PADDING_ZERO_ALL, ]) return res
def demo(self): D = Drawing(self.width, self.height) D.add(self) return D
def test(): """This function produces a pdf with examples. """ #white on blue rl = RL_CorpLogo() rl.width = 129 rl.height = 86 D = Drawing(rl.width,rl.height) D.add(rl) D.__dict__['verbose'] = 1 D.save(fnRoot='corplogo_whiteonblue',formats=['pdf','eps','jpg','gif']) #blue on white rl = RL_CorpLogoReversed() rl.width = 129 rl.height = 86 D = Drawing(rl.width,rl.height) D.add(rl) D.__dict__['verbose'] = 1 D.save(fnRoot='corplogo_blueonwhite',formats=['pdf','eps','jpg','gif']) #gray on white rl = RL_CorpLogoReversed() rl.fillColor = Color(0.2, 0.2, 0.2) rl.width = 129 rl.height = 86 D = Drawing(rl.width,rl.height) D.add(rl) D.__dict__['verbose'] = 1 D.save(fnRoot='corplogo_grayonwhite',formats=['pdf','eps','jpg','gif']) rl = RL_BusinessCard() rl.x=25 rl.y=25 rl.border=1 D = Drawing(rl.width+50,rl.height+50) D.add(rl) D.__dict__['verbose'] = 1 D.save(fnRoot='RL_BusinessCard',formats=['pdf'])
def genBarDrawing(data, data_note, width=letter[0] * 0.8, height=letter[1] * 0.25): """ 函数功能:生成Drawing之用 :return: """ data_value = list(map(lambda x: x[1], data)) data_finale = [tuple(data_value)] drawing = Drawing(width=width, height=height) bc = VerticalBarChart() # bc.x = 50 # bc.y = 50 # bc.height = 125 bc.width = width bc.data = data_finale # bc.valueAxis.valueMin = 0 bc.barSpacing = 0 # bc.valueAxis.valueMax = 50 # bc.valueAxis.valueStep = 10 # bc.categoryAxis.style = 'stacked' bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 barFillColors = [ colors.red, colors.green, colors.white, colors.blue, colors.yellow, colors.pink, colors.purple, colors.lightgreen, colors.darkblue, colors.lightyellow, colors.fidred, colors.greenyellow, colors.gray, colors.blueviolet, colors.lightgoldenrodyellow ] for i in range(len(data_finale)): bc.bars[i].name = data_note[i] # 最多只支持15种颜色,多出的设置为红色 if i < 15: bc.bars[i].fillColor = barFillColors[i] else: bc.bars[i].fillColor = colors.red # x_min = data[0][0] # x_max = data[-1][0] # bc.xValueAxis.valueMin = x_min # lp.xValueAxis.valueMax = x_max # step = int(((x_max - x_min) / (60 * 60 * 24)) / 15) + 1 # bc.categoryAxis.categoryNames = [str(Sec2Datetime(x))[0:10] for x in range(int(x_min), int(x_max), 60 * 60 * 24 * step)] drawing.add(bc) # 增加legend # add_legend(drawing, bc, pos_x=10, pos_y=-10) return drawing
def genLPDrawing(data, data_note, width=letter[0] * 0.8, height=letter[1] * 0.25, time_axis='day', y_min_zero=False, line_width=1.5, marker_size=5): """ 函数功能:生成Drawing之用 :return: """ drawing = Drawing(width=width, height=height) lp = LinePlot() lp.height = height lp.width = width lp.data = data lp.joinedLines = 1 # 定义颜色集 barFillColors = [ colors.red, colors.green, colors.blue, colors.darkgoldenrod, colors.pink, colors.purple, colors.lightgreen, colors.darkblue, colors.lightyellow, colors.fidred, colors.greenyellow, colors.gray, colors.white, colors.blueviolet, colors.lightgoldenrodyellow ] for i in range(0, len(data)): lp.lines[i].name = data_note[i] lp.lines[i].symbol = makeMarker('FilledCircle', size=marker_size) lp.lines[i].strokeWidth = line_width lp.lines[i].strokeColor = barFillColors[i] # lp.lineLabelFormat = '%2.0f' # lp.strokeColor = colors.black x_min = data[0][0][0] x_max = data[0][-1][0] lp.xValueAxis.valueMin = x_min lp.xValueAxis.valueMax = x_max if time_axis == 'day': step = int(((x_max - x_min) / (60 * 60 * 24)) / 30) + 1 lp.xValueAxis.valueSteps = [ n for n in range(int(x_min), int(x_max), 60 * 60 * 24 * step) ] lp.xValueAxis.labelTextFormat = lambda x: str(Sec2Datetime(x)[0:10]) lp.xValueAxis.labels.angle = 90 lp.xValueAxis.labels.fontSize = 6 lp.xValueAxis.labels.dy = -18 if y_min_zero: lp.yValueAxis.valueMin = 0 # lp.yValueAxis.valueMax = 50 # lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6] elif time_axis == 'quarter': step = int(((x_max - x_min) / 0.25) / 30) + 1 lp.xValueAxis.valueSteps = [ n for n in range(int(x_min), int(x_max), int(math.ceil(0.25 * step))) ] lp.xValueAxis.labelTextFormat = lambda x: convertValue2Quarter(x) lp.xValueAxis.labels.angle = 90 lp.xValueAxis.labels.fontSize = 6 lp.xValueAxis.labels.dy = -18 if y_min_zero: lp.yValueAxis.valueMin = 0 elif time_axis == 'year': lp.xValueAxis.valueSteps = [ n for n in range(int(x_min), int(x_max), 1) ] lp.xValueAxis.labelTextFormat = lambda x: str(x) lp.xValueAxis.labels.angle = 90 lp.xValueAxis.labels.fontSize = 6 lp.xValueAxis.labels.dy = -18 if y_min_zero: lp.yValueAxis.valueMin = 0 elif time_axis == 'month': lp.xValueAxis.valueSteps = list(map(lambda x: x[0], data[0])) lp.xValueAxis.labelTextFormat = lambda x: str(Sec2Datetime(x))[0:7] lp.xValueAxis.labels.angle = 90 lp.xValueAxis.labels.fontSize = 6 lp.xValueAxis.labels.dy = -18 if y_min_zero: lp.yValueAxis.valueMin = 0 drawing.add(lp) add_legend(draw_obj=drawing, chart=lp, pos_x=10, pos_y=-20) return drawing
def addAcTemp(canvas_param, opc_df_today, pos_x, pos_y, width, height): total_df = opc_df_today total_df_OAT = total_df[total_df.browse_name == 'OA-T'] total_df_CSSWT = total_df[total_df.browse_name == 'CS-SWT'] total_df_CSRWT = total_df[total_df.browse_name == 'CS-RWT'] total_df_FSSWT = total_df[total_df.browse_name == 'FS-SWT'] total_df_FSRWT = total_df[total_df.browse_name == 'FS-RWT'] # 生成5个变量相应的点阵 data_OAT = ExtractPointFromDf_DateX( df_origin=total_df_OAT, date_col='present_value_source_timestamp', y_col='present_value_value') data_CSSWT = ExtractPointFromDf_DateX( df_origin=total_df_CSSWT, date_col='present_value_source_timestamp', y_col='present_value_value') data_CSRWT = ExtractPointFromDf_DateX( df_origin=total_df_CSRWT, date_col='present_value_source_timestamp', y_col='present_value_value') data_FSSWT = ExtractPointFromDf_DateX( df_origin=total_df_FSSWT, date_col='present_value_source_timestamp', y_col='present_value_value') data_FSRWT = ExtractPointFromDf_DateX( df_origin=total_df_FSRWT, date_col='present_value_source_timestamp', y_col='present_value_value') data_origin = [ tuple(data_OAT), tuple(data_CSSWT), tuple(data_CSRWT), tuple(data_FSSWT), tuple(data_FSRWT) ] # 定义各曲线标签 data_name_origin = ['室外温度', '冷却侧供水温度', '冷却侧回水温度', '冷冻侧供水温度', '冷冻侧回水温度'] # 处理某条线没有数据的情况,若不处理“没有数据”的情况,画线的时候会报错! data = [] data_name = [] for i in range(0, len(data_origin)): if len(data_origin[i]) != 0: data.append(data_origin[i]) data_name.append(data_name_origin[i]) if len(data) == 0: print('函数 addAcTemp:原始df解析后没有想要的温度数据!') return canvas_param c = canvas_param # c.setFont("song", 10) drawing = Drawing(width=width, height=height) lp = LinePlot() # lp.x = 50 # lp.y = 50 lp.height = height lp.width = width lp.data = data lp.joinedLines = 1 # 定义各曲线颜色 lp.lines[0].strokeColor = colors.blue lp.lines[1].strokeColor = colors.red lp.lines[2].strokeColor = colors.lightgreen lp.lines[3].strokeColor = colors.orange lp.lines[4].strokeColor = colors.darkgreen for i in range(0, len(data)): lp.lines[i].name = data_name[i] lp.lines[i].symbol = makeMarker('FilledCircle', size=0.5) lp.lines[i].strokeWidth = 0.2 # lp.lineLabelFormat = '%2.0f' # lp.strokeColor = colors.black lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 60 * 60 * 24 lp.xValueAxis.valueSteps = [n for n in range(0, 60 * 60 * 24, 60 * 60)] lp.xValueAxis.labelTextFormat = lambda x: str(s2t(x))[0:2] lp.yValueAxis.valueMin = 0 # lp.yValueAxis.valueMax = 50 # lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6] drawing.add(lp) add_legend(draw_obj=drawing, chart=lp, pos_x=10, pos_y=-10) renderPDF.draw(drawing=drawing, canvas=c, x=pos_x, y=pos_y)
def make_graphs(self, canvas=None, left_margin=None): #text=None): from reportlab.graphics import renderPDF from reportlab.lib.pagesizes import letter from reportlab.graphics.shapes import Drawing, String from reportlab.graphics.charts.legends import Legend from reportlab.graphics.charts.lineplots import LinePlot from reportlab.graphics.widgets.markers import makeMarker from reportlab.lib import colors from reportlab.lib.units import inch #help(colors) self.framework = { 4: dict(status=SpotClass.SPINDLE, color=colors.black), 5: dict(status=SpotClass.OVERLAP, color=colors.limegreen), 6: dict(status=SpotClass.OUTLIER, color=colors.greenyellow), 7: dict(status=SpotClass.ICE, color=colors.skyblue), } # set size and position width, height = letter #letter_landscape = (width,height) plot_dim = 3.0 * inch # construct scatter plot plot_dxdy_pos = (left_margin * inch, height - plot_dim - 0.5 * inch) plot_dxdy = LinePlot() plot_dxdy.data = self.plot_dxdy_data std_colors = {0: colors.darkred, 1: colors.red, 2: colors.salmon} for key in std_colors.keys(): plot_dxdy.lines[key].strokeColor = None plot_dxdy.lines[key].symbol = makeMarker('Circle') plot_dxdy.lines[key].symbol.strokeColor = None plot_dxdy.lines[key].symbol.fillColor = std_colors[key] plot_dxdy.lines[key].symbol.size = 1.2 for key in self.framework.keys(): plot_dxdy.lines[key].strokeColor = None plot_dxdy.lines[key].symbol = makeMarker('Circle') plot_dxdy.lines[key].symbol.strokeColor = None plot_dxdy.lines[key].symbol.fillColor = self.framework[key][ "color"] plot_dxdy.lines[key].symbol.size = 1.2 plot_dxdy.lines[3].strokeColor = None plot_dxdy.lines[3].symbol = makeMarker('Circle') plot_dxdy.lines[3].symbol.strokeColor = colors.blue plot_dxdy.lines[3].symbol.fillColor = None plot_dxdy.lines[3].symbol.strokeWidth = 0.6 plot_dxdy.lines[3].symbol.size = plot_dim * (self.sqrtr2) #print plot_dxdy.lines[3].symbol.getProperties() plot_dxdy.width = plot_dim plot_dxdy.height = plot_dim plot_dxdy.xValueAxis.valueMax = 1.0 plot_dxdy.xValueAxis.valueMin = -1.0 plot_dxdy.xValueAxis.joinAxis = plot_dxdy.yValueAxis plot_dxdy.xValueAxis.joinAxisMode = 'value' plot_dxdy.xValueAxis.joinAxisPos = -1.0 plot_dxdy.yValueAxis.valueMax = 1.0 plot_dxdy.yValueAxis.valueMin = -1.0 d_dxdy = Drawing(plot_dim, plot_dim) d_dxdy.add(plot_dxdy) # construct cdf plot plot_cdf_pos = (left_margin * inch, height - 2.0 * (plot_dim + 0.5 * inch)) plot_cdf = LinePlot() plot_cdf.data = self.plot_cdf_data plot_cdf.lines[0].strokeColor = colors.blue for key in std_colors.keys(): plot_cdf.lines[key + 1].strokeColor = None plot_cdf.lines[key + 1].symbol = makeMarker('Circle') plot_cdf.lines[key + 1].symbol.strokeColor = None plot_cdf.lines[key + 1].symbol.fillColor = std_colors[key] plot_cdf.lines[key + 1].symbol.size = 1.2 if (len(self.plot_cdf_data) == 5): plot_cdf.lines[4].strokeColor = colors.green plot_cdf.width = plot_dim plot_cdf.height = plot_dim plot_cdf.xValueAxis.valueMax = 1.0 plot_cdf.xValueAxis.valueMin = 0.0 plot_cdf.yValueAxis.valueMax = 1.0 plot_cdf.yValueAxis.valueMin = 0.0 d_cdf = Drawing(plot_dim, plot_dim) d_cdf.add(plot_cdf) # construct pdf plot plot_pdf_pos = (left_margin * inch, height - 3.0 * (plot_dim + 0.5 * inch)) plot_pdf = LinePlot() plot_pdf.data = self.plot_pdf_data plot_pdf.lines[1].strokeColor = colors.blue plot_pdf.lines[0].strokeColor = None plot_pdf.lines[0].symbol = makeMarker('Circle') plot_pdf.lines[0].symbol.strokeColor = colors.red plot_pdf.lines[0].symbol.size = 1 plot_pdf.width = plot_dim plot_pdf.height = plot_dim plot_pdf.xValueAxis.valueMax = 1.0 plot_pdf.xValueAxis.valueMin = 0.0 d_pdf = Drawing(2 * plot_dim, plot_dim) d_pdf.add(plot_pdf) # add legend legend = Legend() legend.alignment = 'right' legend.colorNamePairs = [ (std_colors[0], 'Inliers (%d' % int(self.fraction * 100.0) + '% used for fit)'), (std_colors[1], 'Other inliers'), (std_colors[2], 'Outliers, reject next round'), ] for key in self.framework.keys(): legend.colorNamePairs.append( (self.framework[key]["color"], "%s" % self.framework[key]["status"])) legend.x = plot_dim - 1.0 * inch legend.y = plot_dim legend.columnMaximum = 8 d_pdf.add(legend) # add titles title_pos = (plot_dim / 2.0, plot_dim + 0.25 * inch) title_dxdy = String(title_pos[0], title_pos[1], 'dx vs. dy (all)') title_dxdy.fontSize = 15 title_dxdy.textAnchor = 'middle' d_dxdy.add(title_dxdy) title_cdf = String(title_pos[0], title_pos[1], 'cdf (good)') title_cdf.fontSize = 15 title_cdf.textAnchor = 'middle' d_cdf.add(title_cdf) title_pdf = String(title_pos[0], title_pos[1], 'pdf (good)') title_pdf.fontSize = 15 title_pdf.textAnchor = 'middle' d_pdf.add(title_pdf) # draw everything renderPDF.draw(d_dxdy, canvas, plot_dxdy_pos[0], plot_dxdy_pos[1]) renderPDF.draw(d_cdf, canvas, plot_cdf_pos[0], plot_cdf_pos[1]) renderPDF.draw(d_pdf, canvas, plot_pdf_pos[0], plot_pdf_pos[1])
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, 51.5625, 65, 6.25, 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.1875, 25, 6.25, 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, 82.8125, 100, 6.25, 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, 98.4375, 110, 6.25, 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, 114.0625, 185, 6.25, 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, 129.6875, 225, 6.25, 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, 145.3125, 95, 6.25, 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.9375, 20, 6.25, 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, 57.8125, 70, 6.25, 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, 73.4375, 30, 6.25, 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, 89.0625, 105, 6.25, 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, 104.6875, 115, 6.25, 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, 120.3125, 190, 6.25, 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, 135.9375, 230, 6.25, 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, 151.5625, 100, 6.25, 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, 167.1875, 25, 6.25, 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( 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, 65.625, 44, 65.625, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=10, strokeDashArray=None, strokeOpacity=None)) self.add( Line(49, 81.25, 44, 81.25, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=10, strokeDashArray=None, strokeOpacity=None)) self.add( Line(49, 96.875, 44, 96.875, 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, 128.125, 44, 128.125, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=10, strokeDashArray=None, strokeOpacity=None)) self.add( Line(49, 143.75, 44, 143.75, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=10, strokeDashArray=None, strokeOpacity=None)) self.add( Line(49, 159.375, 44, 159.375, 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, 57.8125) v0.add( String(-26.66, -4, 'Jan-99', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) v0 = self._nn(Group()) v0.transform = (1, 0, 0, 1, 44, 73.4375) v0.add( String(-28.33, -4, 'Feb-99', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) v0 = self._nn(Group()) v0.transform = (1, 0, 0, 1, 44, 89.0625) v0.add( String(-29.99, -4, 'Mar-99', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) v0 = self._nn(Group()) v0.transform = (1, 0, 0, 1, 44, 104.6875) v0.add( String(-28.88, -4, 'Apr-99', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) v0 = self._nn(Group()) v0.transform = (1, 0, 0, 1, 44, 120.3125) v0.add( String(-31.66, -4, 'May-99', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) v0 = self._nn(Group()) v0.transform = (1, 0, 0, 1, 44, 135.9375) v0.add( String(-27.22, -4, 'Jun-99', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) v0 = self._nn(Group()) v0.transform = (1, 0, 0, 1, 44, 151.5625) v0.add( String(-25, -4, 'Jul-99', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) v0 = self._nn(Group()) v0.transform = (1, 0, 0, 1, 44, 167.1875) v0.add( String(-30.55, -4, 'Aug-99', 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)))
# -*- coding: utf-8 -*- """ Created on Thu Aug 30 18:21:27 2018 @author: DELL """ from reportlab.graphics.shapes import Drawing, String from reportlab.graphics import renderPDF d = Drawing(100, 100) #设置画布大小 s = String(50, 50, 'hello,world!', textAnchor='middle') #设置内容,格式 d.add(s) #画布上添加内容 renderPDF.drawToFile(d, 'hello.pdf', 'A simple PDF file') #生成文件
def get4PieChart(): legend = Legend() a = df2.iloc[i, 13] b = df2.iloc[i, 14] c = df2.iloc[i, 15] d = df2.iloc[i, 16] e = df2.iloc[i, 17] da = [a, b, c, d, e] x = 0 y = 0 for i9 in da: if i9 == "Attempted": x = x + 1 a = df2.iloc[i, 28] b = df2.iloc[i, 29] c = df2.iloc[i, 30] d = df2.iloc[i, 31] e = df2.iloc[i, 32] da = [a, b, c, d, e] for i9 in da: if i9 == "Correct": y = y + 1 z = 5 - x o = x - y data = [z, y, o] s = z + y + o u = round(z * 100 / s) v = round(y * 100 / s) r = round(o * 100 / s) h = [u, v, r] d = [] l = ["%.2f" % i9 for i9 in h] for i9 in l: k = i9.split(".") d.append(k[0]) e = [] j = 0 for i9 in d: w = i9 + "%" j = j + 1 w = i9 + "%" if j == 1: w = w + " (Unattempted)" if j == 2: w = w + " (Correct)" if j == 3: w = w + " (Incorrect)" e.append(w) drawing = Drawing(width=400, height=200) my_title = String(80, -20, 'Overall Performance against the test', fontSize=14) pie = Pie() pie.sideLabels = True pie.slices.popout = 3 pie.x = 150 pie.y = 10 pie.data = data pie.labels = [letter for letter in e] pie.slices.strokeWidth = 0.5 drawing.add(my_title) drawing.add(pie) n = len(pie.data) setItems(n, pie.slices, 'fillColor', pdf_chart_colors) legend.colorNamePairs = [(pie.slices[i9].fillColor, (pie.labels[i9][0:20], '%0.2f' % pie.data[i9])) for i9 in range(n)] add_legend(drawing, pie, data) return drawing
def createBarcode(self, data): print("Creating barcode {} {} {} {}".format(data['barcode'], data['sku'], data['design'], data['size'])) barcode = Ean13BarcodeWidget(data['barcode']) barcode.barWidth = 1.2 barcode.barHeight = self.image_height x0, y0, bw, bh = barcode.getBounds() barcode.x = self.label_x_start + (self.label_width - bw) / 2 barcode.y = self.image_y_start # self.label_height # self.label_y_start #self.barcode_y label_drawing = Drawing(self.label_width, self.label_height) sku = String(self.sku_x_start, self.sku_y_start, data['sku'].strip(), fontName="Helvetica", fontSize=7, textAnchor="start") size = String(self.size_x_start, self.size_y_start, data['size'].strip()[:14], fontName="Helvetica", fontSize=7, textAnchor="end") product = String(self.product_x_start, self.product_y_start, data['product'].strip()[:12], fontName="Helvetica", fontSize=7, textAnchor="start") design = String(self.design_x_start, self.design_y_start, data['design'].strip()[:12], fontName="Helvetica", fontSize=7, textAnchor="end") season = String(self.season_x_start, self.season_y_start, data['season'].strip()[:2], fontName="Helvetica", fontSize=7, textAnchor="middle") label_drawing.add(barcode) label_drawing.add(sku) label_drawing.add(size) label_drawing.add(product) label_drawing.add(design) label_drawing.add(season) return label_drawing
def getPieChart(): legend = Legend() a = df2.iloc[i, 38] b = df2.iloc[i, 39] c = df2.iloc[i, 40] d = df2.iloc[i, 41] e = df2.iloc[i, 42] data = [a, b, c, d, e] drawing = Drawing(width=400, height=200) my_title = String(81, 37, 'Time Spend as the Function of Total Time', fontSize=14) pie = Pie() pie.sideLabels = True pie.slices.popout = 2 pie.x = 135 pie.y = 55 pie.data = data s = a + b + c + d + e t = round(a * 100 / s) u = round(b * 100 / s) v = round(c * 100 / s) x = round(d * 100 / s) z = round(e * 100 / s) h = [t, u, v, x, z] d = [] l = ["%.2f" % i4 for i4 in h] for i4 in l: k = i4.split(".") d.append(k[0]) e = [] j = 0 for i4 in d: w = i4 + "%" j = j + 1 if j == 1: w = w + " (Q1)" if j == 2: w = w + " (Q2)" if j == 3: w = w + " (Q3)" if j == 4: w = w + " (Q4)" if j == 5: w = w + " (Q5)" e.append(w) pie.labels = [letter for letter in e] pie.slices.strokeWidth = 0.5 drawing.add(my_title) drawing.add(pie) n = len(pie.data) setItems(n, pie.slices, 'fillColor', pdf_chart_colors) legend.colorNamePairs = [(pie.slices[i4].fillColor, (pie.labels[i4][0:20], '%0.2f' % pie.data[i4])) for i4 in range(n)] add_legend(drawing, pie, data) return drawing
def run(): styles = getSampleStyleSheet() styleN = styles['Normal'] styleH = styles['Heading1'] story = [] storyAdd = story.append #for codeNames in code storyAdd(Paragraph('I2of5', styleN)) storyAdd(I2of5(1234, barWidth = inch*0.02, checksum=0)) storyAdd(Paragraph('MSI', styleN)) storyAdd(MSI(1234)) storyAdd(Paragraph('Codabar', styleN)) storyAdd(Codabar("A012345B", barWidth = inch*0.02)) storyAdd(Paragraph('Code 11', styleN)) storyAdd(Code11("01234545634563")) storyAdd(Paragraph('Code 39', styleN)) storyAdd(Standard39("A012345B%R")) storyAdd(Paragraph('Extended Code 39', styleN)) storyAdd(Extended39("A012345B}")) storyAdd(Paragraph('Code93', styleN)) storyAdd(Standard93("CODE 93")) storyAdd(Paragraph('Extended Code93', styleN)) storyAdd(Extended93("L@@K! Code 93 :-)")) #, barWidth=0.005 * inch)) storyAdd(Paragraph('Code 128', styleN)) storyAdd(Code128("AB-12345678")) storyAdd(Paragraph('Code 128 Auto', styleN)) storyAdd(Code128Auto("AB-12345678")) storyAdd(Paragraph('USPS FIM', styleN)) storyAdd(FIM("A")) storyAdd(Paragraph('USPS POSTNET', styleN)) storyAdd(POSTNET('78247-1043')) storyAdd(Paragraph('USPS 4 State', styleN)) storyAdd(USPS_4State('01234567094987654321','01234567891')) from reportlab.graphics.barcode import createBarcodeDrawing storyAdd(Paragraph('EAN13', styleN)) storyAdd(createBarcodeDrawing('EAN13', value='123456789012')) storyAdd(Paragraph('EAN13 quiet=False', styleN)) storyAdd(createBarcodeDrawing('EAN13', value='123456789012', quiet=False)) storyAdd(Paragraph('EAN8', styleN)) storyAdd(createBarcodeDrawing('EAN8', value='1234567')) storyAdd(PageBreak()) storyAdd(Paragraph('EAN5 price=True', styleN)) storyAdd(createBarcodeDrawing('EAN5', value='11299', price=True)) storyAdd(Paragraph('EAN5 price=True quiet=False', styleN)) storyAdd(createBarcodeDrawing('EAN5', value='11299', price=True, quiet=False)) storyAdd(Paragraph('EAN5 price=False', styleN)) storyAdd(createBarcodeDrawing('EAN5', value='11299', price=False)) storyAdd(Paragraph('ISBN alone', styleN)) storyAdd(createBarcodeDrawing('ISBN', value='9781565924796')) storyAdd(Paragraph('ISBN with ean5 price', styleN)) storyAdd(createBarcodeDrawing('ISBN', value='9781565924796',price='01299')) storyAdd(Paragraph('ISBN with ean5 price, quiet=False', styleN)) storyAdd(createBarcodeDrawing('ISBN', value='9781565924796',price='01299',quiet=False)) storyAdd(Paragraph('UPCA', styleN)) storyAdd(createBarcodeDrawing('UPCA', value='03600029145')) storyAdd(Paragraph('USPS_4State', styleN)) storyAdd(createBarcodeDrawing('USPS_4State', value='01234567094987654321',routing='01234567891')) storyAdd(Paragraph('QR', styleN)) storyAdd(createBarcodeDrawing('QR', value='01234567094987654321')) storyAdd(Paragraph('QR', styleN)) storyAdd(createBarcodeDrawing('QR', value='01234567094987654321',x=30,y=50)) def addCross(d,x,y,w=5,h=5, strokeColor='black', strokeWidth=0.5): w *= 0.5 h *= 0.5 d.add(Line(x-w,y,x+w,y,strokeWidth=0.5,strokeColor=colors.blue)) d.add(Line(x, y-h, x, y+h,strokeWidth=0.5,strokeColor=colors.blue)) storyAdd(Paragraph('QR in drawing at (0,0)', styleN)) d = Drawing(100,100) d.add(Rect(0,0,100,100,strokeWidth=1,strokeColor=colors.red,fillColor=None)) d.add(QrCodeWidget(value='01234567094987654321')) storyAdd(d) storyAdd(Paragraph('QR in drawing at (10,10)', styleN)) d = Drawing(100,100) d.add(Rect(0,0,100,100,strokeWidth=1,strokeColor=colors.red,fillColor=None)) addCross(d,10,10) d.add(QrCodeWidget(value='01234567094987654321',x=10,y=10)) storyAdd(d) storyAdd(Paragraph('Label Size', styleN)) storyAdd(XBox((2.0 + 5.0/8.0)*inch, 1 * inch, '1x2-5/8"')) storyAdd(Paragraph('Label Size', styleN)) storyAdd(XBox((1.75)*inch, .5 * inch, '1/2x1-3/4"')) if pylibdmtx: storyAdd(PageBreak()) storyAdd(Paragraph('DataMatrix in drawing at (10,10)', styleN)) d = Drawing(100,100) d.add(Rect(0,0,100,100,strokeWidth=1,strokeColor=colors.red,fillColor=None)) addCross(d,10,10) d.add(DataMatrixWidget(value='1234567890',x=10,y=10)) storyAdd(d) storyAdd(Paragraph('DataMatrix in drawing at (10,10)', styleN)) d = Drawing(100,100) d.add(Rect(0,0,100,100,strokeWidth=1,strokeColor=colors.red,fillColor=None)) addCross(d,10,10) d.add(DataMatrixWidget(value='1234567890',x=10,y=10,color='black',bgColor='lime')) storyAdd(d) storyAdd(Paragraph('DataMatrix in drawing at (90,90) anchor=ne', styleN)) d = Drawing(100,100) d.add(Rect(0,0,100,100,strokeWidth=1,strokeColor=colors.red,fillColor=None)) addCross(d,90,90) d.add(DataMatrixWidget(value='1234567890',x=90,y=90,color='darkblue',bgColor='yellow', anchor='ne')) storyAdd(d) SimpleDocTemplate('out.pdf').build(story) print('saved out.pdf')
eg(""" >>> from reportlab.lib import colors >>> from reportlab.graphics import shapes >>> from reportlab.graphics import widgetbase >>> from reportlab.graphics import renderPDF >>> d = shapes.Drawing(200, 100) >>> f = widgetbase.Face() >>> f.skinColor = colors.yellow >>> f.mood = "sad" >>> d.add(f) >>> renderPDF.drawToFile(d, 'face.pdf', 'A Face') """) from reportlab.graphics import widgetbase d = Drawing(200, 120) f = widgetbase.Face() f.x = 50 f.y = 10 f.skinColor = colors.yellow f.mood = "sad" d.add(f) draw(d, 'A sample widget') disc(""" Let's see what properties it has available, using the $setProperties()$ method we have seen earlier: """) eg(""" >>> f.dumpProperties()
def get3PieChart(): legend = Legend() a = df2.iloc[i, 13] b = df2.iloc[i, 14] c = df2.iloc[i, 15] d = df2.iloc[i, 16] e = df2.iloc[i, 17] da = [a, b, c, d, e] x = 0 y = 0 for i6 in da: if i6 == "Attempted": x = x + 1 a = df2.iloc[i, 28] b = df2.iloc[i, 29] c = df2.iloc[i, 30] d = df2.iloc[i, 31] e = df2.iloc[i, 32] da = [a, b, c, d, e] for i7 in da: if i7 == "Correct": y = y + 1 data = [y, x - y] u = round(y * 100 / x) v = round((x - y) * 100 / x) h = [u, v] d = [] l = ["%.2f" % i7 for i7 in h] for i7 in l: k = i7.split(".") d.append(k[0]) e = [] j = 0 for i7 in d: w = i7 + "%" j = j + 1 w = i7 + "%" if j == 1: w = w + " (Correct)" if j == 2: w = w + " (Incorrect)" e.append(w) drawing = Drawing(width=400, height=200) my_title = String(80, -20, 'Accuracy from attemptes questions', fontSize=14) pie = Pie() pie.sideLabels = True pie.slices.popout = 3 pie.x = 150 pie.y = 10 pie.data = data pie.labels = [letter for letter in e] pie.slices.strokeWidth = 0.5 drawing.add(my_title) n = len(pie.data) setItems(n, pie.slices, 'fillColor', pdf_chart_colors) legend.colorNamePairs = [(pie.slices[i7].fillColor, (pie.labels[i7][0:20], '%0.2f' % pie.data[i7])) for i7 in range(n)] drawing.add(pie) add_legend(drawing, pie, data) return drawing
def print_sensor_data(self, report_instance): buffer = self.buffer doc = SimpleDocTemplate(buffer, rightMargin=50, leftMargin=50, topMargin=20, bottomMargin=50, pagesize=self.pagesize) # A large collection of style sheets pre-made for us styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='centered', alignment=TA_CENTER)) style_Normal = styles["Normal"] style_Normal.textColor = colors.black style_Alerta = styles["Normal"] style_Alerta.textColor = colors.black style_Title = styles["Heading1"] style_Title.alignment = TA_LEFT style_Title_Center = styles["Heading1"] style_Title_Center.alignment = TA_CENTER # Our container for 'Flowable' objects elements = [] # Saltos de linea saltosDeLineax1 = Paragraph("<br/>", style_Title) saltosDeLineax2 = Paragraph("<br/><br/>", style_Title) saltosDeLineax3 = Paragraph("<br/><br/><br/>", style_Title) # ps = ParagraphStyle('title', fontSize=20, leading=24) # p1 = "here is some paragraph to see in large font" # Paragraph(p1, ps), # Tabla con reporte de incidencias y LOGOS. titulo_data = [] titulo_table = [] logo_cliente = Paragraph( '' + report_instance.sensor.arduino.project.enterprise.name, style_Normal) titulo_ciente = Paragraph( 'Reporte de incidencias<br/>Sensor ' + report_instance.sensor.description, style_Title_Center) img_sensait = Image("arduino/static/sensait/logos/Sensait_logo.png") img_sensait.drawHeight = 8 * mm img_sensait.drawWidth = 20 * mm titulo_data.append((logo_cliente, titulo_ciente, img_sensait)) titulo_table = Table(titulo_data, colWidths=(50 * mm, 100 * mm, 50 * mm)) titulo_table.setStyle( TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.white), ('BOX', (0, 0), (-1, -1), 0.25, colors.white)])) elements.append(titulo_table) elements.append(saltosDeLineax2) resumen_data = [] resumen_table = [] resumen_laboratorio = Paragraph( '<b>Laboratorio:</b><br/>' + report_instance.sensor.arduino.project.name, style_Normal) resumen_equipo = Paragraph( '<b>Equipo:</b><br/>' + report_instance.sensor.arduino.name, style_Normal) resumen_serie = Paragraph( '<b>Modelo:</b><br/>' + report_instance.sensor.arduino.modelo_transmisor, style_Normal) resumen_data.append( (resumen_laboratorio, resumen_equipo, resumen_serie)) resumen_periodo = Paragraph( '<b>Periodo:</b><br/>' + datetime.fromtimestamp( report_instance.fecha_inicial).strftime('%d/%m/%Y %H:%M:%S') + " al <br/>" + datetime.fromtimestamp( report_instance.fecha_final).strftime('%d/%m/%Y %H:%M:%S'), style_Normal) # Cantidad de Dias del reporte seleccionado. difEpochDias = (report_instance.fecha_final - report_instance.fecha_inicial) / 86400 periodoReporte = "Dia" if difEpochDias == 30: periodoReporte = "Mensual" elif difEpochDias == 15 or difEpochDias == 14: periodoReporte = "Quincenal" elif difEpochDias == 7 or difEpochDias == 6: periodoReporte = "Semanal" elif difEpochDias != 1: periodoReporte = str(difEpochDias) + " dias" else: periodoReporte = str(difEpochDias) + " Dia" resumen_rangodias = Paragraph( '<b>Periodo Generado:</b><br/>' + str(periodoReporte), style_Normal) resumen_void = Paragraph(" ", style_Normal) resumen_data.append((resumen_periodo, resumen_rangodias, resumen_void)) # resumen_proyecto = Paragraph('<b>Proyecto:</b><br/>' + report_instance.sensor.arduino.project.name, style_Normal) # resumen_transmisor = Paragraph('<b>Transmisor:</b><br/>' + report_instance.sensor.arduino.name, style_Normal) # resumen_void = Paragraph(" ", style_Normal) # resumen_data.append((resumen_proyecto, resumen_transmisor, resumen_void)) resumen_sensor = Paragraph( '<b>Sensor:</b><br/>' + report_instance.sensor.description, style_Normal) resumen_valmin = Paragraph( '<b>Valor Minimo:</b><br/>' + "%.2f" % report_instance.sensor.min_value, style_Normal) resumen_valmax = Paragraph( '<b>Valor Maximo:</b><br/>' + "%.2f" % report_instance.sensor.max_value, style_Normal) resumen_data.append((resumen_sensor, resumen_valmin, resumen_valmax)) # VALORES MINIMOS Y MAXIMOS CALCULO. min_value = report_instance.sensor.min_value max_value = report_instance.sensor.max_value totalAlertas = 0 promedioRegistros = 0.0 totalRegistros = 0 valmax = 0 valmin = 0 # Tabla de ejemplo main_table = [] dataTable_L = [] dataTable_R = [] table_data = [] all_alerts = [] alert_list = [] dataTable_L.append( ("Fecha y Hora", "Lectura", "Estado", "Numero incidencia")) sensorStatus = "Correcto" for num, data in enumerate(report_instance.sensor_data(), start=0): if str(data.data) != str("-127.00"): totalRegistros = num promedioRegistros += float(data.data) if num == 0: valmin = float(data.data) if float(data.data) > float(max_value) or float( min_value) > float(data.data): sensorStatus = "Fuera de Rango" alert_list.append(data) totalAlertas += 1 else: sensorStatus = "Correcto" if len(alert_list) > 0: # print "New List " + str(len(all_alerts)) all_alerts.append(list(alert_list)) alert_list = [] if float(data.data) > float(valmax): valmax = float(data.data) if float(valmin) > float(data.data): valmin = float(data.data) if len(alert_list) > 0: alerta_code = "Alerta # " + str(len(all_alerts)) else: alerta_code = " " dataTable_L.append((datetime.fromtimestamp( data.epoch).strftime('%d/%m/%Y %H:%M:%S'), data.data, sensorStatus, alerta_code)) table_L = Table(dataTable_L, colWidths=[(doc.width) / 4.0] * 4) table_L.setStyle( TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black)])) print promedioRegistros print totalRegistros if float(promedioRegistros) == 0 and float(promedioRegistros) == 0: val_promedio = 0 else: val_promedio = float(promedioRegistros) / float(totalRegistros) resumen_promedio = Paragraph( '<b>Temperatura Promedio:</b><br/>' + "%.2f" % val_promedio, style_Normal) resumen_minima = Paragraph( '<b>Temperatura Minimo Registrada:</b><br/>' + "%.2f" % valmin, style_Normal) resumen_maxima = Paragraph( '<b>Temperatura Maxima Registrada:</b><br/>' + "%.2f" % valmax, style_Normal) resumen_data.append((resumen_promedio, resumen_minima, resumen_maxima)) resumen_totalregistros = Paragraph( '<b>Total de Registros:</b><br/>' + "%.2f" % totalRegistros, style_Normal) resumen_totalfuera = Paragraph( '<b>Resumen Registros:</b><br/>' + "X %.2f" % totalAlertas + "<br/> + %.2f" % (totalRegistros - totalAlertas), style_Normal) resumen_alertasregistradas = Paragraph( '<b>Total alertas registradas:</b><br/>' + str(len(all_alerts)), style_Normal) resumen_void = Paragraph(" ", style_Normal) resumen_data.append((resumen_totalregistros, resumen_totalfuera, resumen_alertasregistradas)) resumen_table = Table(resumen_data, colWidths=[(doc.width) / 3.0] * 3, rowHeights=(16 * mm)) resumen_table.setStyle( TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.white), ('BOX', (0, 0), (-1, -1), 0.25, colors.white), ('VALIGN', (0, 0), (-1, -1), 'TOP')])) elements.append(resumen_table) # Informacion del reporte digamos LEGAL. # elements.append(Paragraph('La informacion que se despliega a continuacion son propiedad de la empresa que contrata el servicio de SENSAIT. La informacion que se despliega a continuacion son propiedad de la empresa que contrata el servicio de SENSAIT. ', styles['Normal'])) elements.append(saltosDeLineax3) valores_Correctos = int(totalRegistros - totalAlertas) drawing = Drawing(400, 200) data = [(valores_Correctos, int(totalAlertas))] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 200 bc.width = 400 bc.data = data bc.barSpacing = 2.5 bc.barWidth = 5 bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = int(totalRegistros) bc.valueAxis.valueStep = 50 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 # bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = [ 'Correctos = ' + str(valores_Correctos), 'Fuera de Rango = ' + str(totalAlertas) ] bc.bars[(0, 0)].fillColor = colors.green bc.bars[(0, 1)].fillColor = colors.red drawing.add(bc) elements.append(drawing) elements.append( Paragraph( 'Responsable ' + report_instance.sensor.arduino.project.nombre_encargado, style_Title)) elements.append(PageBreak()) # table_R = Table(dataTable_R, colWidths=[(doc.width) / 3.0] * 3) # table_R.setStyle(TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black)])) # dataTable_Main = [table_L] table_R # table_Main = Table(table_L, colWidths=[doc.width]) # table_Main.setStyle(TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.red), ('BOX', (0, 0), (-1, -1), 0.25, colors.red)])) # Tabla con todos los registros... elements.append( Paragraph( str(len(all_alerts)) + ' ALERTAS REGISTRADAS', style_Title_Center)) # Tablas POR ALERTA... alert_data_tables = [] alerts_tables = [] alert_content = [] alerts_onedata_data = [] alerts_onedata_table = [] # print "all_alerts.len()" # print len(all_alerts) alerts_onedata_data.append( ("Fecha Alerta", "# Registros en alerta ", "Valor")) alert_max_value = float(report_instance.sensor.max_value) alert_min_value = float(report_instance.sensor.min_value) for num, alertlist in enumerate(all_alerts, start=0): print str(len(alertlist)) # Esto genera la tabla para un rango de registros NO LO QUITARE jeje if len(alertlist) > 200: one_fecha = str( datetime.fromtimestamp( alertlist[len(alertlist) - 1].epoch).strftime('%d/%m/%Y %H:%M:%S')) one_registros = len(alertlist) one_value = str(alertlist[len(alertlist) - 1].data) alerts_onedata_data.append( (one_fecha, one_registros, one_value)) # alerts_onedata_data.append( alertlist[num] , drawing)) else: titulo = Paragraph('<b>Alerta # ' + str(num) + ' </b>', style_Normal) alert_data_tables = [] alert_content = [] alert_graph = [] alert_limit = [] alert_graph_dates = [] alerta_primer_registro = Paragraph( '<b>Fecha inicio alerta:</b><br/>' + str( datetime.fromtimestamp(alertlist[0].epoch).strftime( '%d/%m/%Y %H:%M:%S') + "<br/><br/>"), style_Normal) alerta_ultima_registro = Paragraph( '<b>Fecha final alerta:</b><br/>' + str( datetime.fromtimestamp(alertlist[len(alertlist) - 1].epoch). strftime('%d/%m/%Y %H:%M:%S') + "<br/><br/>"), style_Normal) tiempoAlerta = alertlist[0].epoch - alertlist[len(alertlist) - 1].epoch print "difEpoch: " + str(alertlist[len(alertlist) - 1].epoch) print "difEpochR: " + str(tiempoAlerta) print "difEpoch: " + str(alertlist[0].epoch) alerta_duracion = Paragraph( '<b>Duracion alerta:</b><br/>' + str( datetime.fromtimestamp(tiempoAlerta).strftime('%M:%S') + "<br/><br/>"), style_Normal) alerta_total_registros = Paragraph( '<b>Registros fuera de rango:</b><br/>' + str(len(alertlist)) + "<br/><br/>", style_Normal) rango_maximo = Paragraph( '<b>Valor Maximo:</b><br/>' + "%.2f" % report_instance.sensor.max_value + "<br/><br/>", style_Normal) rango_minimo = Paragraph( '<b>Valor Maximo:</b><br/>' + "%.2f" % report_instance.sensor.min_value + "<br/><br/>", style_Normal) alerta_comentarios = Paragraph( "<b>Comentarios:</b><br/>__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________<br/>", style_Normal) alerta_accioncorrectiva = Paragraph( "<b>Accion correctiva:</b><br/>__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________<br/>", style_Normal) alerta_data = [] alerta_table = [] alerta_data.append((titulo, " ")) alerta_data.append( (alerta_primer_registro, alerta_ultima_registro)) alerta_data.append((alerta_duracion, alerta_total_registros)) alerta_data.append((rango_maximo, rango_minimo)) alerta_data.append((" ", saltosDeLineax2)) # alerta_data.append((alerta_comentarios)) alerta_table = Table(alerta_data, colWidths=(50 * mm, 50 * mm)) alerta_table.setStyle( TableStyle([ ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.white), ('BOX', (0, 0), (-1, -1), 0.25, colors.white) ])) # alert_content.append(alerta_primer_registro) # alert_content.append(alerta_ultima_registro) # alert_content.append(alerta_duracion) # alert_content.append(alerta_total_registros) # alert_content.append(rango_maximo) # alert_content.append(rango_minimo) # alert_content.append(alerta_comentarios) # alert_content.append(saltosDeLineax2) valMax = 0 valMin = 0 valTmp = 0 for ids, alert in enumerate(alertlist, start=0): # print alert.data # datos = Paragraph(str(alert.data), style_Normal) valTmp = float(alert.data) # print "tmp: " + str(valTmp) # print "max: " + str(valMax) # print "min: " + str(valMin) if float(valTmp >= 0): if float(valTmp) > float(valMax): valMax = valTmp if valMin == 0: valMin = float(valTmp) if float(valMin) > float(valTmp): valMin = float(valTmp) else: if float(valTmp) < float(valMax): valMax = valTmp if valMin == 0: valMin = float(valTmp) if float(valTmp) > float(valMin): valMin = float(valTmp) valueData = float(alert.data) alert_graph.append(valueData) alert_limit.append(alert_max_value) alert_graph_dates.append( str( datetime.fromtimestamp( alert.epoch).strftime('%H:%M:%S'))) # END FOR print "tmp: " + str(valTmp) print "max: " + str(valMax) print "min: " + str(valMin) # CALCULAR BIEN LOS LIMITES DE LA GRAFICA if float(valMin) >= 0: lim_min = float(valMin - 1) elif float(valMax) >= 0: lim_max = float(valMax + 2) elif float(valMax) < 0: lim_max = float(valMax - 2) elif float(valMin) < 0: lim_min = float(valMin - 1) # END CALCULAR LIMITES lim_min = valMin lim_max = valMax print "lim_min: " + str(lim_min) print "lim_max: " + str(lim_max) drawing = Drawing(200, 220) data = [alert_graph, alert_limit] lc = HorizontalLineChart() lc.x = 10 lc.y = 30 lc.height = 150 lc.width = 220 lc.data = data # lc.strokeColor = colors.black catNames = alert_graph_dates lc.categoryAxis.categoryNames = catNames lc.categoryAxis.labels.dx = 0 lc.categoryAxis.labels.dy = -15 lc.categoryAxis.labels.angle = 75 lc.categoryAxis.labels.boxAnchor = 'n' lc.joinedLines = 1 lc.lines[0].symbol = makeMarker('FilledCircle') # lc.lineLabelFormat = '%2.0f' # lc.strokeColor = colors.black lc.valueAxis.valueMin = lim_min lc.valueAxis.valueMax = lim_max lc.valueAxis.valueStep = 1 lc.lines[0].strokeWidth = 2 # lc.lines[1].strokeWidth = 1.5 drawing.add(lc) # print "endFor" alert_data_tables.append((drawing, alerta_table)) alert_data_tables.append( (alerta_comentarios, alerta_accioncorrectiva)) alerts_tables = Table(alert_data_tables, colWidths=[(doc.width) / 2.0] * 2) alerts_tables.setStyle( TableStyle([ ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.white), ('BOX', (0, 0), (-1, -1), 0.25, colors.white) ])) elements.append(alerts_tables) # elements.append(PageBreak()) if len(alerts_onedata_data) > 1: elements.append( Paragraph('ALERTAS CON 5 REGISTROS O MENOS', style_Title_Center)) elements.append(saltosDeLineax1) alerts_onedata_table = Table(alerts_onedata_data, colWidths=[(doc.width) / 3.0] * 3) alerts_onedata_table.setStyle( TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black)])) elements.append(alerts_onedata_table) # elements.append(PageBreak()) elements.append(PageBreak()) elements.append(Paragraph('DETALLE DE REGISTROS', style_Title_Center)) elements.append(table_L) # elements.append(table_R) # Se agrega el llamado del header y footer doc.build(elements, onFirstPage=self._header_footer, onLaterPages=self._header_footer, canvasmaker=NumberedCanvas)
# coding=utf-8 from reportlab.graphics.shapes import Drawing, String from reportlab.graphics import renderPDF d = Drawing(100,100) #创建100*100大小的图纸 s = String(50,50,"hello world", textAnchor = "middle") #在整个图纸的什么位置,如何显示文本 d.add(s) #把文本放置在图纸上 renderPDF.drawToFile(d, 'hello.pdf', 'a simple pdf file') #在本地目录下输出一个pdf文件
def results_chart(self, control_mean, match_mean, treated_mean, att): """ Specify layout of the results chart and generate flowable object that can be added to the pdf """ drawing = Drawing() vbc = VerticalBarChart() # Offset chart from border and text vbc.x = self.chart_offset_x vbc.y = self.chart_offset_y # Set figure size vbc.height = self.chart_height vbc.width = self.chart_width # Specify chart -- list of lists -- list of series with enteries vbc.data = [[control_mean, match_mean, treated_mean, att]] #Set Y-Axis ranges #axis_range = self._calculate_y_axis(vbc.data) #vbc.valueAxis.valueMin = axis_range['min'] #vbc.valueAxis.valueMax = axis_range['max'] #vbc.valueAxis.valueStep = axis_range['step'] #Grid formatting vbc.valueAxis.visibleGrid = 1 vbc.valueAxis.gridStrokeColor = colors.lightgrey # Set bar characteristics vbc.bars[(0, 0)].fillColor = colors.blue vbc.bars[(0, 1)].fillColor = colors.yellow vbc.bars[(0, 2)].fillColor = colors.red vbc.bars[(0, 3)].fillColor = colors.green vbc.bars.strokeColor = None vbc.barSpacing = 2 # Create callout labels #vbc.barLabels.fontName = "Helvetica" vbc.barLabels.fontSize = 8 vbc.barLabels.fillColor = colors.black vbc.barLabelFormat = '%.2f' vbc.barLabels.nudge = 5 # X-axis labels #vbc.categoryAxis.labels.dy = -60 #vbc.valueAxis.labels.fontName = 'Helvetica' vbc.categoryAxis.categoryNames = [ 'Control Mean', 'Matched Control Mean', 'Treatment mean', 'ATT' ] lab = Label() lab.setOrigin(10, 155) lab.boxAnchor = 'ne' lab.angle = 90 lab.dx = 0 lab.dy = -15 #lab.boxStrokeColor = colors.green lab.setText('Result Values') drawing.add(lab) drawing.add(vbc) self.elements.append(drawing)
def __init__(self, width=200, height=150, *args, **kw): Drawing.__init__(self, width, height, *args, **kw) self._add(self, LinePlot(), name='chart', validate=None, desc="The main chart") self.chart.width = 115 self.chart.height = 80 self.chart.x = 30 self.chart.y = 40 self.chart.lines[0].strokeColor = color01 self.chart.lines[1].strokeColor = color02 self.chart.lines[2].strokeColor = color03 self.chart.lines[3].strokeColor = color04 self.chart.lines[4].strokeColor = color05 self.chart.lines[5].strokeColor = color06 self.chart.lines[6].strokeColor = color07 self.chart.lines[7].strokeColor = color08 self.chart.lines[8].strokeColor = color09 self.chart.lines[9].strokeColor = color10 self.chart.fillColor = backgroundGrey self.chart.lineLabels.fontName = 'Helvetica' self.chart.xValueAxis.labels.fontName = 'Helvetica' self.chart.xValueAxis.labels.fontSize = 7 self.chart.xValueAxis.forceZero = 0 self.chart.data = [((0, 50), (100, 100), (200, 200), (250, 210), (300, 300), (400, 500)), ((0, 150), (100, 200), (200, 300), (250, 200), (300, 400), (400, 600))] self.chart.xValueAxis.avoidBoundFrac = 1 self.chart.xValueAxis.gridEnd = 115 self.chart.xValueAxis.tickDown = 3 self.chart.xValueAxis.visibleGrid = 1 self.chart.yValueAxis.tickLeft = 3 self.chart.yValueAxis.labels.fontName = 'Helvetica' self.chart.yValueAxis.labels.fontSize = 7 self._add(self, Label(), name='Title', validate=None, desc="The title at the top of the chart") self.Title.fontName = 'Helvetica-Bold' self.Title.fontSize = 7 self.Title.x = 100 self.Title.y = 135 self.Title._text = 'Chart Title' self.Title.maxWidth = 180 self.Title.height = 20 self.Title.textAnchor = 'middle' self._add(self, Legend(), name='Legend', validate=None, desc="The legend or key for the chart") self.Legend.colorNamePairs = [(color01, 'Widgets'), (color02, 'Sprockets')] self.Legend.fontName = 'Helvetica' self.Legend.fontSize = 7 self.Legend.x = 153 self.Legend.y = 85 self.Legend.dxTextSpace = 5 self.Legend.dy = 5 self.Legend.dx = 5 self.Legend.deltay = 5 self.Legend.alignment = 'right' self._add(self, Label(), name='XLabel', validate=None, desc="The label on the horizontal axis") self.XLabel.fontName = 'Helvetica' self.XLabel.fontSize = 7 self.XLabel.x = 85 self.XLabel.y = 10 self.XLabel.textAnchor = 'middle' self.XLabel.maxWidth = 100 self.XLabel.height = 20 self.XLabel._text = "X Axis" self._add(self, Label(), name='YLabel', validate=None, desc="The label on the vertical axis") self.YLabel.fontName = 'Helvetica' self.YLabel.fontSize = 7 self.YLabel.x = 12 self.YLabel.y = 80 self.YLabel.angle = 90 self.YLabel.textAnchor = 'middle' self.YLabel.maxWidth = 100 self.YLabel.height = 20 self.YLabel._text = "Y Axis" self.chart.yValueAxis.forceZero = 1 self.chart.xValueAxis.forceZero = 1 self._add(self, 0, name='preview', validate=None, desc=None)
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, 60.41667, 18, 41.66667, 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, 122.9167, 60, 41.66667, 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(80, 50, 80, 45, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=10, strokeDashArray=None, strokeOpacity=None)) self.add( Line(170, 50, 170, 45, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=10, strokeDashArray=None, strokeOpacity=None)) self.add( Line(260, 50, 260, 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, 80, 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, 170, 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, 260, 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_line(self, x1, y1, x2, y2, line_color=colors.black): drawable_line = Drawing(x1, y1) drawable_line.add(Line(0, 0, x2, y2, fillColor=line_color)) return drawable_line
def demo(self, drawing=None): if not drawing: tx, ty = self._getDrawingDimensions() drawing = Drawing(tx, ty) drawing.add(self.draw()) return drawing
def balance_statistics_chart(self, control_vars, match_vars, var_names): """ Specify layout of the balance statistics chart and generate flowable object that can be added to the pdf """ drawing = Drawing() vbc = VerticalBarChart() # Chart position in document vbc.x = self.chart_offset_x vbc.y = self.chart_offset_y vbc.height = self.chart_height vbc.width = self.chart_width # Specify data # [[control_var1, control_var2], [match_var1, match_var2]] vbc.data = [control_vars, match_vars] #Set Y-Axis ranges #axis_range = self._calculate_y_axis(vbc.data) #vbc.valueAxis.valueMin = axis_range['min'] #vbc.valueAxis.valueMax = axis_range['max'] #vbc.valueAxis.valueStep = axis_range['step'] #Grid formatting vbc.valueAxis.visibleGrid = 1 vbc.valueAxis.gridStrokeColor = colors.lightgrey #Bar formatting vbc.bars[0].fillColor = colors.blue vbc.bars[1].fillColor = colors.yellow vbc.bars.strokeColor = None vbc.groupSpacing = 1 vbc.barWidth = 5 # Callout label formatting (numbers above bar) #vbc.barLabels.fontName = "Arial" vbc.barLabels.fontSize = 8 vbc.barLabels.fillColor = colors.black vbc.barLabelFormat = '%.2f' vbc.barLabels.nudge = 5 # Central axis vbc.categoryAxis.visibleTicks = 1 # X-axis labels #vbc.categoryAxis.labels.dy = -60 vbc.valueAxis.labels.fontName = 'Helvetica' vbc.categoryAxis.categoryNames = var_names lab = Label() lab.setOrigin(10, 155) lab.boxAnchor = 'ne' lab.angle = 90 lab.dx = 0 lab.dy = -15 #lab.boxStrokeColor = colors.green lab.setText('Percent Bias') drawing.add(lab) drawing.add(vbc) self.elements.append(drawing)
from reportlab.platypus import KeepTogether from reportlab.platypus import LongTable from client.pdfs import CustomPdf, format_number_thousand_decimal_points, right_align_bold_paragraph_style from client.pdfs import get_logo_and_qr_code_from_client, create_right_align_header, size_nine_helvetica_leading_10, \ add_new_line_to_string_at_index, get_reciver_address_list_from_object, size_nine_helvetica_bold, two_new_lines, \ get_delivery_address_html_string_from_object, size_nine_helvetica, Table, TableStyle, size_twelve_helvetica_bold, \ horizontal_line, size_ten_helvetica, underline from reportlab.platypus import Paragraph from reportlab.lib.enums import TA_RIGHT, TA_LEFT, TA_CENTER from reportlab.lib.styles import ParagraphStyle from order.models import Order from client.models import Client from reportlab.graphics.shapes import Drawing, Line, colors order_horizontal_line = Drawing(100, 1) order_horizontal_line.add(Line(0, 0, 423, 0)) class OrderPdfView(View): @property def order(self): return Order.objects.get(pk=self.kwargs.get("pk")) @property def client(self): client = Client.objects.get(pk=self.request.session.get("client")) return client def __init__(self, **kwargs): super().__init__(**kwargs)
lab.setOrigin(100,90) lab.boxAnchor = 'ne' lab.angle = 45 lab.dx = 0 lab.dy = -20 lab.boxStrokeColor = colors.green lab.setText('Some\nMulti-Line\nLabel') d.add(lab) """) from reportlab.graphics import shapes from reportlab.graphics.charts.textlabels import Label d = Drawing(200, 100) # mark the origin of the label d.add(Circle(100,90, 5, fillColor=colors.green)) lab = Label() lab.setOrigin(100,90) lab.boxAnchor = 'ne' lab.angle = 45 lab.dx = 0 lab.dy = -20 lab.boxStrokeColor = colors.green lab.setText('Some\nMulti-Line\nLabel') d.add(lab)
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( Line(50, 89.0625, 350, 89.0625, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=0, strokeDashArray=None, strokeOpacity=None)) self.add( Line(50, 89.0625, 50, 84.0625, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=10, strokeDashArray=None, strokeOpacity=None)) self.add( Line(125, 89.0625, 125, 84.0625, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=10, strokeDashArray=None, strokeOpacity=None)) self.add( Line(200, 89.0625, 200, 84.0625, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=10, strokeDashArray=None, strokeOpacity=None)) self.add( Line(275, 89.0625, 275, 84.0625, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=10, strokeDashArray=None, strokeOpacity=None)) self.add( Line(350, 89.0625, 350, 84.0625, 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, 87.5, 84.0625) v0.add( String(-9.44, -10, 'Beer', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) v0 = self._nn(Group()) v0.transform = (1, 0, 0, 1, 162.5, 84.0625) v0.add( String(-10.83, -10, 'Wine', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) v0 = self._nn(Group()) v0.transform = (1, 0, 0, 1, 237.5, 84.0625) v0.add( String(-10.275, -10, 'Meat', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) v0 = self._nn(Group()) v0.transform = (1, 0, 0, 1, 312.5, 84.0625) v0.add( String(-21.945, -10, 'Cannelloni', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) self.add( Line(50, 50, 50, 175, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=0, strokeDashArray=None, strokeOpacity=None)) self.add( Line(50, 50, 45, 50, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=10, strokeDashArray=None, strokeOpacity=None)) self.add( Line(50, 89.0625, 45, 89.0625, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=10, strokeDashArray=None, strokeOpacity=None)) self.add( Line(50, 128.125, 45, 128.125, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=0, strokeMiterLimit=10, strokeDashArray=None, strokeOpacity=None)) self.add( Line(50, 167.1875, 45, 167.1875, 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, 45, 50) v0.add( String(-10, -4, '10', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) v0 = self._nn(Group()) v0.transform = (1, 0, 0, 1, 45, 89.0625) v0.add( String(-10, -4, '20', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) v0 = self._nn(Group()) v0.transform = (1, 0, 0, 1, 45, 128.125) v0.add( String(-10, -4, '30', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) v0 = self._nn(Group()) v0.transform = (1, 0, 0, 1, 45, 167.1875) v0.add( String(-10, -4, '40', textAnchor='start', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1)))
def build_table(self): colwidths = [30, 68, 152, 60, 65, 65] right_align_paragraph_style = ParagraphStyle("adsadsa", alignment=TA_RIGHT, fontName="Helvetica", fontSize=9, rightIndent=17) header = [ Paragraph("<b>Pos</b>", style=size_nine_helvetica), Paragraph("<b>EAN / SKU</b>", style=size_nine_helvetica), Paragraph("<b>Bezeichnung</b>", style=size_nine_helvetica), Paragraph("<b>Menge</b>", style=right_align_paragraph_style), Paragraph("<b>Einzelpreis</b>", style=right_align_paragraph_style), Paragraph("<b>Betrag</b>", style=right_align_paragraph_style), ] data = [] data.append(header) pos = 1 for productorder in self.order.productorder_set.all(): data.append([ Paragraph(str(pos), style=size_nine_helvetica), Paragraph(productorder.get_ean_or_sku(), style=size_nine_helvetica), Paragraph(productorder.product.title, style=size_nine_helvetica), Paragraph(str(productorder.amount), style=right_align_paragraph_style), Paragraph(format_number_thousand_decimal_points( productorder.netto_price), style=right_align_paragraph_style), Paragraph(format_number_thousand_decimal_points( (productorder.netto_price * productorder.amount)), style=right_align_paragraph_style), ], ) pos += 1 table = LongTable(data, splitByRow=True, colWidths=colwidths, repeatRows=1) table.setStyle( TableStyle([ ('LEFTPADDING', (0, 0), (-1, -1), 0), ('RIGHTPADDING', (0, 0), (-1, -1), 0), ('VALIGN', (0, 0), (-1, -1), "TOP"), ])) total_netto = 0 for productorder in self.order.productorder_set.all(): total_netto += productorder.amount * productorder.netto_price horizontal_line_betrag = Drawing(20, 1) horizontal_line_betrag.add(Line(425, 0, 200, 0)) betrag_data = [ [ Paragraph(f"Nettobetrag", style=right_align_paragraph_style), Paragraph( f"{format_number_thousand_decimal_points(total_netto)} €", style=right_align_paragraph_style), ], [ Paragraph(f"+ Umsatzsteuer (19,00%)", style=right_align_paragraph_style), Paragraph( f"{format_number_thousand_decimal_points(total_netto*0.19)} €", style=right_align_paragraph_style), ], [ horizontal_line_betrag, ], [ Paragraph(f"GESAMT", style=right_align_bold_paragraph_style), Paragraph( f"{format_number_thousand_decimal_points(total_netto+(total_netto*0.19))} €", style=right_align_bold_paragraph_style), ] ] betrag_table = Table(betrag_data, colWidths=[None, 70, 75]) betrag_table.setStyle( TableStyle([ ('LEFTPADDING', (0, 0), (-1, -1), 0), ('RIGHTPADDING', (0, 0), (-1, -1), 0), ('VALIGN', (0, 0), (-1, -1), "TOP"), ])) self.story.extend( [table, order_horizontal_line, KeepTogether(betrag_table)])
from fontTools.ttLib import TTFont from reportlab.lib import colors path = sys.argv[1] glyphName = sys.argv[2] if (len(sys.argv) > 3): imageFile = sys.argv[3] else: imageFile = "%s.png" % glyphName font = TTFont( path) # it would work just as well with fontTools.t1Lib.T1Font gs = font.getGlyphSet() pen = ReportLabPen(gs, Path(fillColor=colors.red, strokeWidth=5)) g = gs[glyphName] g.draw(pen) w, h = g.width, 1000 from reportlab.graphics import renderPM from reportlab.graphics.shapes import Group, Drawing, scale # Everything is wrapped in a group to allow transformations. g = Group(pen.path) g.translate(0, 200) g.scale(0.3, 0.3) d = Drawing(w, h) d.add(g) renderPM.drawToFile(d, imageFile, fmt="PNG")
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( Wedge(200, 100, 50, 72.85714, 90, yradius=50, annular=False, fillColor=Color(0, .545098, .545098, 1), fillOpacity=None, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=1, strokeMiterLimit=0, strokeDashArray=None, strokeOpacity=None)) self.add( Wedge(200, 100, 50, 38.57143, 72.85714, yradius=50, annular=False, fillColor=Color(.541176, .168627, .886275, 1), fillOpacity=None, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=1, strokeMiterLimit=0, strokeDashArray=None, strokeOpacity=None)) self.add( Wedge(200, 100, 50, -12.85714, 38.57143, yradius=50, annular=False, fillColor=Color(0, 0, 1, 1), fillOpacity=None, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=1, strokeMiterLimit=0, strokeDashArray=None, strokeOpacity=None)) self.add( Wedge(213.6035, 85.33896, 50, -81.42857, -12.85714, yradius=50, annular=False, fillColor=Color(0, 1, 1, 1), fillOpacity=None, strokeColor=Color(0, 0, 0, 1), strokeWidth=2, strokeLineCap=0, strokeLineJoin=1, strokeMiterLimit=0, strokeDashArray=[2, 2], strokeOpacity=None)) self.add( Wedge(200, 100, 50, -167.1429, -81.42857, yradius=50, annular=False, fillColor=Color(1, .752941, .796078, 1), fillOpacity=None, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=1, strokeMiterLimit=0, strokeDashArray=None, strokeOpacity=None)) self.add( Wedge(200, 100, 50, -270, -167.1429, yradius=50, annular=False, fillColor=Color(1, 0, 1, 1), fillOpacity=None, strokeColor=Color(0, 0, 0, 1), strokeWidth=1, strokeLineCap=0, strokeLineJoin=1, strokeMiterLimit=0, strokeDashArray=None, strokeOpacity=None)) self.add( String(208.9425, 159.3298, 'a', textAnchor='middle', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) self.add( String(233.7992, 149.5743, 'b', textAnchor='middle', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) self.add( String(258.4957, 113.3513, 'c', textAnchor='middle', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) self.add( String(273.1186, 21.19692, 'd', textAnchor='middle', fontName='Times-Roman', fontSize=10, fillColor=Color(1, 0, 0, 1))) self.add( String(166.2008, 50.42567, 'e', textAnchor='middle', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1))) self.add( String(153.0901, 137.4094, 'f', textAnchor='middle', fontName='Times-Roman', fontSize=10, fillColor=Color(0, 0, 0, 1)))