def generate_line_charts(self): self.elements.append( Paragraph( "<br/><br/><br/><br/><br/><br/><br/><u><b><font color=green>" "Line Chart for payment amounts in time." "</font></b></u>", ReportPDF.styleN) ) lc = HorizontalLineChart() lc.x = 0 lc.height = 150 lc.width = 450 lc.data = [tuple(self.lc_data)] lc.joinedLines = 1 lc.categoryAxis.categoryNames = tuple(self.cat_names) lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = int(max(self.lc_data)) lc.valueAxis.valueStep = int(max(self.lc_data)/10) lc.lines[0].strokeWidth = 2 lc.lines[1].strokeWidth = 1.5 d_lc = Drawing(350, 180) d_lc.add(lc) # add charts to PDF self.elements.append(d_lc)
def graficoLineal(pdf): querysetPagos = obtenerQuerysetPagos() print(querysetPagos) drawing = Drawing(400, 250) data = [(querysetPagos)] pdf = HorizontalLineChart() pdf.x = 50 pdf.y = 50 pdf.height = 300 pdf.width = 500 pdf.data = data pdf.joinedLines = 1 catNames = 'Ene Feb Marzo Abril Mayo Junio Julio Agosto Sep Nov Dic'.split( ' ') pdf.categoryAxis.categoryNames = catNames pdf.categoryAxis.labels.boxAnchor = 'n' #pdf.lineLabels.fontName = 'FreeSans' mayor = max(querysetPagos) pdf.valueAxis.valueMin = 0 pdf.valueAxis.valueMax = mayor pdf.valueAxis.valueStep = mayor / 10 pdf.lineLabelFormat = '%2.0f' pdf.lines[0].strokeWidth = 2 pdf.lines[1].strokeWidth = 1.5 drawing.add(pdf) #drawing.save(formats=['pdf'], outDir='.', fnRoot='Reporte_Cobros_por_mes') return drawing
def add_lineChart(self, title, data, size=(PAGE_WIDTH - 100, 300)): ''' 添加一个折线图 :param title: 折线图标题 :param data: 折线图数据 ''' __chart_width, __chart_heigh = size[0], size[1] __draw = Drawing(__chart_width, __chart_heigh) __draw.add( String(20, __chart_heigh - 10, title, fontName="chsFont", fontSize=18, fillColor=colors.black)) lc = HorizontalLineChart() lc.x, lc.y = 25, 50 lc.width, lc.height = __chart_width - 50, __chart_heigh - 100 lc.data = data lc.joinedLines = 1 lc.valueAxis.valueMin = min(data[0]) lc.valueAxis.valueMax = max(data[0]) valueRange = lc.valueAxis.valueMax - lc.valueAxis.valueMin lc.valueAxis.valueStep = valueRange / 10.0 __draw.add(lc) self.__content.append(__draw)
def getLineChart(): data = [(4, 2, 7), (7, 8, 6)] chart = HorizontalLineChart() chart.data = data chart.x = 5 chart.y = 5 chart.width = 240 chart.height = 100 chart.categoryAxis.categoryNames = ['A', 'B', 'C'] chart.valueAxis.valueMin = 0 chart.valueAxis.valueMax = 10 chart.valueAxis.valueStep = 2 chart.lines[0].strokeWidth = 3.5 chart.lines[1].strokeWidth = 1 chart.lines[0].strokeColor = colors.purple title = String(50, 110, 'Line Chart', fontSize=14) drawing = Drawing(240, 120) drawing.add(title) drawing.add(chart) return drawing
def drawdata(data, times, labels): drawing = Drawing(10000, 200) fontstep = 5.5 for i in range(0, size(labels)): drawing.add(String(40,(i+9.8)*fontstep,str(labels[i]), textAnchor="middle", fontSize=5)) #drawing.add(String(20,175,"labels", textAnchor="middle", fontSize=5)) #data = [1, 2, 3, 4, 5, 6] lc = HorizontalLineChart() #lc.valueAxis = 0 lc.x = 50 lc.y = 50 lc.height = 155 lc.width = 10000 lc.data = data lc.joinedLines = 1 #catNames = string.split('Jan Feb Mar Apr May Jun Jul Aug', ' ') #catNames = times #lc.categoryAxis.categoryNames = catNames #lc.categoryAxis.labels.boxAnchor = 'n' lc.categoryAxis.visible = 0 fontstep = 40 for i in range(0, size(times)): drawing.add(String((i+1.3)*fontstep,45,str(times[i]), textAnchor="middle", fontSize=5)) lc.lineLabelArray = ['1','2'] #lc.valueAxis.valueMin = 0 #lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 1 #lc.valueAxis.valueSteps = [1, 2, 3, 5, 6] lc.lines[0].strokeWidth = .5 lc.lines[1].strokeWidth = .5 drawing.add(lc) renderPDF.drawToFile(drawing, 'example1.pdf', 'EEG data') return drawing, lc
def sample1line(data=[(13, 5, 20, 22, 37, 45, 19, 4)]): drawing = Drawing(400, 200) bc = HorizontalLineChart() 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 = 60 bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 catNames = string.split('Jan Feb Mar Apr May Jun Jul Aug', ' ') catNames = map(lambda n:n+'-99', catNames) bc.categoryAxis.categoryNames = catNames drawing.add(bc) return drawing
def simple_line_chart(): d = Drawing(280, 250) line = HorizontalLineChart() line.x = 50 line.y = 85 line.height = 150 line.width = 250 data = [[1, 2, 3, None, None, None, 5], [10, 5, 2, 6, 8, 3, 5] ] line.data = data line.categoryAxis.categoryNames = [ 'Dogs', 'Cats', 'Mice', 'Hamsters', 'Parakeets', 'Gerbils', 'Fish' ] line.lines[0].strokeColor = colors.green line.lines[1].strokeColor = colors.blue line.lines[0].strokeWidth = 3 line.categoryAxis.labels.angle = 45 line.categoryAxis.labels.dy = -15 d.add(line, '') doc = SimpleDocTemplate('15.simple_line_chart.pdf') story = [] story.append(d) doc.build(story)
def add_line_chart(self, width, height, labels, data, minv=None, maxv=None): pad = 10 _min, _max = self._find_min_max(data) minv = _min if minv is None else minv maxv = _max if maxv is None else maxv lc = HorizontalLineChart() lc.x = pad * mm lc.y = pad * mm lc.width = (width - 2 * pad) * mm lc.height = (height - 2 * pad) * mm lc.categoryAxis.categoryNames = labels lc.data = data lc.valueAxis.valueMin = minv lc.valueAxis.valueMax = maxv lc.joinedLines = 1 lc.categoryAxis.labels.boxAnchor = "n" lc.lines.strokeWidth = 2 drawing = Drawing(width * mm, height * mm) drawing.hAlign = "CENTER" drawing.add(lc) self.story.append(drawing)
def sample1line(data=[(13, 5, 20, 22, 37, 45, 19, 4)]): drawing = Drawing(400, 200) bc = HorizontalLineChart() 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 = 60 bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 catNames = 'Jan Feb Mar Apr May Jun Jul Aug'.split(' ') catNames = [n+'-99' for n in catNames] bc.categoryAxis.categoryNames = catNames drawing.add(bc) return drawing
def makeLineChart(self, context, width, height, data, xvalues, backgroundColor, borderColor, labelAngles, labelXOffsets, labelYOffsets, lineColors, lineWidths, lineLabelFormat, yAxisMin, yAxisMax, yAxisStep): content = [] drawing = Drawing(width, height) lp = HorizontalLineChart() lp.x = 0 lp.y = 0 lp.height = height lp.width = width lp.data = data lp.joinedLines = 1 if backgroundColor: lp.fillColor = colors.HexColor(backgroundColor) if borderColor: lp.strokeColor = colors.HexColor(borderColor) if yAxisMin is not None: lp.valueAxis.valueMin = yAxisMin if yAxisMax is not None: lp.valueAxis.valueMax = yAxisMax if yAxisStep: lp.valueAxis.valueStep = yAxisStep if xvalues: lp.categoryAxis.categoryNames = xvalues if labelAngles is not None: self.handleSingleOrList(lp.categoryAxis.labels, labelAngles, 'angle', len(data[0])) if labelXOffsets is not None: self.handleSingleOrList(lp.categoryAxis.labels, labelXOffsets, 'dx', len(data[0])) if labelYOffsets is not None: self.handleSingleOrList(lp.categoryAxis.labels, labelYOffsets, 'dy', len(data[0])) if lineLabelFormat: lp.lineLabelFormat = lineLabelFormat if lineColors: self.handleSingleOrList(lp.lines, lineColors, 'strokeColor', len(data), colors.HexColor) if lineWidths: self.handleSingleOrList(lp.lines, lineWidths, 'strokeWidth', len(data)) drawing.add(lp) content.append( drawing ) return content
def draw_temper_pulse(value, step, x_coord, y_coord): drawing = Drawing(x_coord, y_coord) data = [] catNames = [] min_value = 0 max_value = 0 for k, v in value.items(): if k == 'data': data1 = tuple([i for i in v]) data.append(data1) if k == 'xtext': catNames = [i.replace(' ', '\n') for i in v] if k == 'min_max': min_value = v[0] - step max_value = v[1] + step lc = HorizontalLineChart() lc.x = 15 lc.y = 0 lc.height = 28 * mm lc.width = 250 * mm lc.data = data lc.joinedLines = 1 lc.strokeColor = colors.white lc.strokeColor = None # из markers lc.lines.symbol = makeMarker('FilledSquare') lc.lines.symbol.size = 4 # lineLabels - свойства надбисей линии из textlabels class Label(Widget): lc.lineLabels.fontSize = 9 lc.lineLabels.fontName = 'PTAstraSerifBold' lc.lineLabels.angle = 0 lc.lineLabels.dx = 2 lc.lineLabels.dy = 1 lc.lines[0].strokeColor = colors.black lc.lineLabelFormat = '%3.1f' lc.categoryAxis.categoryNames = catNames lc.categoryAxis.labels.boxAnchor = 'n' lc.categoryAxis.labels.angle = 0 lc.categoryAxis.labels.dy = -2 lc.categoryAxis.labels.dx = 0 lc.categoryAxis.labels.fontSize = 9 lc.categoryAxis.labels.fontName = 'PTAstraSerifReg' lc.categoryAxis.labels.leading = 8 lc.valueAxis.valueMin = min_value lc.valueAxis.valueMax = max_value lc.valueAxis.valueStep = step lc.valueAxis.labels.fontName = 'PTAstraSerifReg' lc.valueAxis.labels.fontSize = 9 drawing.add(lc) return drawing
def draw_test_burndown(not_run_line: List[int], passed_line: List[int], falied_line: List[int], start_date: date, end_date: date) -> Drawing: max_days = 10 days = (end_date - start_date).days + 1 assert days == \ len(not_run_line) == \ len(passed_line) == \ len(falied_line), "Line data for burndown should be equal to number of days" step_days = 1 if days > max_days: step_days = ceil(float(days) / max_days) step = timedelta(days=step_days) num_steps = int(ceil(float(days) / step_days)) start_dt = datetime.datetime.combine(start_date, datetime.time.min) end_dt = datetime.datetime.combine(end_date, datetime.time.min) category_dates = [(start_dt + step * n) for n in range(0, num_steps)] line1_data = [not_run_line[step_days * n] for n in range(0, num_steps)] line2_data = [passed_line[step_days * n] for n in range(0, num_steps)] line3_data = [falied_line[step_days * n] for n in range(0, num_steps)] if category_dates[-1] < end_dt: category_dates.append(end_dt) line1_data.append(not_run_line[-1]) line2_data.append(passed_line[-1]) line3_data.append(falied_line[-1]) d = Drawing(width=350, height=140) lc = HorizontalLineChart() lc.x = 0 lc.y = 0 lc.width = 350 lc.height = 140 lc.data = [line1_data, line2_data, line3_data] lc.lines[0].strokeColor = COLOR_GRAY lc.lines[1].strokeColor = COLOR_GREEN lc.lines[2].strokeColor = COLOR_RED lc.joinedLines = 1 lc.lines.strokeWidth = 2 lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = max(not_run_line) + 1 lc.valueAxis.labels.fontName = MAIN_FONT_NAME lc.valueAxis.labels.fontSize = AXIS_FONT_SIZE lc.categoryAxis.categoryNames = [ next_date.strftime('%Y-%m-%d') for next_date in category_dates ] lc.categoryAxis.labels.fontName = MAIN_FONT_NAME lc.categoryAxis.labels.fontSize = AXIS_FONT_SIZE lc.categoryAxis.labels.dy = -15 lc.categoryAxis.labels.angle = 30 d.add(lc) return d
def draw_pressure(value, step, x_coord, y_coord): drawing = Drawing(x_coord, y_coord) data = [] data_diastolic = value['Диастолическое давление (мм рт.с)'] data1 = [i for i in data_diastolic['data']] data.append(tuple(data1)) min_max = data_diastolic['min_max'] data_systolic = value['Систолическое давление (мм рт.с)'] data1 = [i for i in data_systolic['data']] data.append(tuple(data1)) catNames = [i.replace(' ', '\n') for i in data_diastolic['xtext']] min_max.extend(data_systolic['min_max']) min_value = min(min_max) - step max_value = max(min_max) + step lc = HorizontalLineChart() lc.x = 15 lc.y = 0 lc.height = 45 * mm lc.width = 250 * mm lc.data = data lc.joinedLines = 1 lc.strokeColor = colors.white # из markers lc.lines[0].symbol = makeMarker('FilledCircle') lc.lines.symbol = makeMarker('FilledSquare') lc.lines.symbol.size = 4 # lineLabels - свойства надбисей линии из textlabels class Label(Widget): lc.lineLabels.fontSize = 9 lc.lineLabels.fontName = 'PTAstraSerifBold' lc.lineLabels.angle = 0 lc.lineLabels.dx = 2 lc.lineLabels.dy = -1 lc.lines[0].strokeColor = colors.black lc.lines[1].strokeColor = colors.black lc.lines[0].strokeDashArray = [3, 3] lc.lineLabelFormat = '%3.1f' lc.categoryAxis.categoryNames = catNames lc.categoryAxis.labels.boxAnchor = 'n' lc.categoryAxis.labels.angle = 0 lc.categoryAxis.labels.dy = -2 lc.categoryAxis.labels.dx = 0 lc.categoryAxis.labels.fontSize = 9 lc.categoryAxis.labels.fontName = 'PTAstraSerifReg' lc.categoryAxis.labels.leading = 8 lc.valueAxis.valueMin = min_value lc.valueAxis.valueMax = max_value lc.valueAxis.valueStep = step lc.valueAxis.labels.fontName = 'PTAstraSerifReg' lc.valueAxis.labels.fontSize = 9 drawing.add(lc) return drawing
def get_drawing(self): drawing = Drawing(600, 250) lc = HorizontalLineChart() lc.x = 50 lc.y = 50 lc.height = 250 lc.width = 600 lc.data = self.data lc.joinedLines = 1 lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 2000 lc.valueAxis.valueStep = 500 lc.lines[0].strokeWidth = 2.5 drawing.add(lc) return drawing
def line_chart(doc, months, portfolioDate, monthlyInv, monthlyVal, Valuation, Investment): drawing = Drawing(doc.width / 2, doc.height / 2 - 80) data = [monthlyInv, monthlyVal] my_title = String(doc.width / 2 - 90, doc.height / 2, 'Performance Chart', fontSize=20) lc = HorizontalLineChart() lc.x = doc.leftMargin + 35 lc.y = doc.bottomMargin lc.height = doc.height / 2 - 60 lc.width = doc.width - 100 lc.data = data lc.joinedLines = 1 catNames = months[portfolioDate.month:] if portfolioDate.month > 1: catNames += months[:portfolioDate.month] lc.categoryAxis.categoryNames = catNames #lc.categoryAxis.labels.boxAnchor = 'autox' lc.valueAxis.valueMin = 0 roundedVal = Valuation if Valuation % 10 == 0 else Valuation + Valuation % 10 lc.valueAxis.valueMax = roundedVal lc.valueAxis.valueStep = int((roundedVal / 10) / 10) * 10 lc.lines[0].strokeWidth = 2 lc.lines[1].strokeWidth = 1.5 lc.lines[0].strokeColor = colors.blue lc.lines[ 1].strokeColor = colors.green if Valuation > Investment else colors.red lc.valueAxis.visibleGrid = 1 lc.valueAxis.gridStrokeColor = colors.lightgrey lc.lines[0].name = 'Investment Value' lc.lines[1].name = 'Closing Valuation' #lc.lineLabelFormat = '%2.0f' labels = ['Investment Value', 'Closing Valuation'] lc._seriesCount = len(labels) drawing.add(my_title) drawing.add(lc) add_legend1(drawing, lc, labels, doc) return drawing
def graphout(catnames, data): drawing = Drawing(400, 200) lc = HorizontalLineChart() lc.x = 30 lc.y = 50 lc.height = 125 lc.width = 350 lc.data = data catNames = catnames lc.categoryAxis.categoryNames = catNames lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 1500 lc.valueAxis.valueStep = 300 lc.lines[0].strokeWidth = 2 lc.lines[0].symbol = makeMarker('FilledCircle') # added to make filled circles. lc.lines[1].strokeWidth = 1.5 drawing.add(lc) return drawing
def horizontallinegraph(data, elements): drawing = Drawing(0, 175) # for indices lc = HorizontalLineChart() lc.x = 0 lc.y = 10 lc.height = 150 lc.width = 300 lc.data = data lc.joinedLines = 1 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 lc.lines[0].strokeWidth = 2 lc.lines[1].strokeWidth = 1.5 drawing.add(lc) elements.append(drawing)
def test_22_lineCharts(self): from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors from reportlab.lib.units import inch from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph from reportlab.pdfbase import pdfmetrics from reportlab.graphics.shapes import Drawing from reportlab.pdfbase.ttfonts import TTFont from reportlab.graphics.charts.linecharts import HorizontalLineChart import random pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) stylesheet = getSampleStyleSheet() elements = [] doc = SimpleDocTemplate("demo.pdf") elements.append( Paragraph('<font name="chsFont">JY.zenist.song - 俊毅</font>', stylesheet['Title'])) elements.append(Spacer(1, 1 * inch)) d = Drawing(400, 200) data = [ [13, 5, 20, 22, 37, 45, 19, 4], # [14,6,21,23,38,46,20,5] ] for i in range(500): data[0].append(random.randint(1, 100)) # data[1].append(random.randint(1,100)) lc = HorizontalLineChart() lc.x = 50 lc.y = 50 lc.height = 180 lc.width = 300 lc.data = data lc.joinedLines = 1 # lc.categoryAxis.categoryNames = data[0] d.add(lc) elements.append(d) doc.build(elements)
def create_graph(graph_data): color=[green,red,blue,yellow,black] color_index = 0 line_chart = Drawing(400, 200) data_length=len(graph_data["data"]) lc = HorizontalLineChart() lc.x = 50 lc.y = 50 lc.height = 125 lc.width = 300 lc.data = graph_data["data"] lc.fillColor=lightblue lc.joinedLines = 1 lc.categoryAxis.categoryNames = list(graph_data["label"][0]) lc.categoryAxis.labels.boxAnchor ='n' lc.valueAxis.valueMin = utils.get_least_pt(graph_data["data"]) lc.valueAxis.valueMax = utils.get_max_pt(graph_data["data"]) lc.valueAxis.valueStep = (lc.valueAxis.valueMax - lc.valueAxis.valueMin)/10 if (lc.valueAxis.valueMax - lc.valueAxis.valueMin) > 40 else (lc.valueAxis.valueMax - lc.valueAxis.valueMin)/5 for i in xrange(data_length): lc.lines[i].strokeWidth = 2 lc.lines[i].strokeColor = color[i] line_chart.add(lc) line_leg = LineLegend() line_leg.boxAnchor = 'sw' line_leg.x = 100 line_leg.y = -1 line_leg.columnMaximum = 1 line_leg.yGap = 0 line_leg.deltax = 50 line_leg.deltay = 0 line_leg.dx = 10 line_leg.dy = 1.5 line_leg.fontSize = 10 line_leg.alignment = 'right' line_leg.dxTextSpace = 5 line_leg.colorNamePairs = [(color[i],graph_data["legend"][0][i]) for i in xrange(data_length)] line_chart.add(line_leg) return line_chart
def test_22_lineCharts(self): from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors from reportlab.lib.units import inch from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph from reportlab.pdfbase import pdfmetrics from reportlab.graphics.shapes import Drawing from reportlab.pdfbase.ttfonts import TTFont from reportlab.graphics.charts.linecharts import HorizontalLineChart import random pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) stylesheet = getSampleStyleSheet() elements = [] doc = SimpleDocTemplate("demo.pdf") elements.append(Paragraph('<font name="chsFont">JY.zenist.song - 俊毅</font>', stylesheet['Title'])) elements.append(Spacer(1,1*inch)) d = Drawing(400,200) data = [ [13,5,20,22,37,45,19,4], # [14,6,21,23,38,46,20,5] ] for i in range(500): data[0].append(random.randint(1,100)) # data[1].append(random.randint(1,100)) lc = HorizontalLineChart() lc.x = 50 lc.y = 50 lc.height = 180 lc.width = 300 lc.data = data lc.joinedLines = 1 # lc.categoryAxis.categoryNames = data[0] d.add(lc) elements.append(d) doc.build(elements)
def add_lineChart(self, title, data, size=(PAGE_WIDTH-100, 300)): ''' 添加一个折线图 :param title: 折线图标题 :param data: 折线图数据 ''' __chart_width, __chart_heigh = size[0], size[1] __draw = Drawing(__chart_width, __chart_heigh) __draw.add(String(20, __chart_heigh-10, title, fontName="chsFont",fontSize=18, fillColor=colors.black)) lc = HorizontalLineChart() lc.x, lc.y = 25, 50 lc.width, lc.height = __chart_width-50, __chart_heigh-100 lc.data = data lc.joinedLines = 1 lc.valueAxis.valueMin = min(data[0]) lc.valueAxis.valueMax = max(data[0]) valueRange = lc.valueAxis.valueMax - lc.valueAxis.valueMin lc.valueAxis.valueStep = valueRange / 10.0 __draw.add(lc) self.__content.append(__draw)
def demo(): 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 catNames = string.split('Jan Feb Mar Apr May Jun Jul Aug', ' ') lc.categoryAxis.categoryNames = catNames lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 15 lc.lines[0].strokeWidth = 2 lc.lines[1].strokeWidth = 1.5 drawing.add(lc) renderPDF.drawToFile(drawing, 'example1.pdf', 'My First Drawing') return drawing
lc.lines[0].strokeWidth = 2 lc.lines[1].strokeWidth = 1.5 drawing.add(lc) """) from reportlab.graphics.charts.linecharts import HorizontalLineChart 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 catNames = string.split('Jan Feb Mar Apr May Jun Jul Aug', ' ') lc.categoryAxis.categoryNames = catNames lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 15 lc.lines[0].strokeWidth = 2 lc.lines[1].strokeWidth = 1.5 drawing.add(lc)
def line_chart(doc, months, portfolioDate, monthlyInv, monthlyVal, Valuation, Investment): drawing = Drawing(doc.width / 2, doc.height / 2 - 80) data = [monthlyInv, monthlyVal] my_title = String(doc.width / 2 - 90, doc.height / 2, 'Performance Chart', fontSize=20) lc = HorizontalLineChart() lc.x = doc.leftMargin + 35 lc.y = doc.bottomMargin lc.height = doc.height / 2 - 60 lc.width = doc.width - 100 lc.data = data lc.joinedLines = 1 catNames = months[portfolioDate.month:] if portfolioDate.month > 1: catNames += months[:portfolioDate.month] lc.categoryAxis.categoryNames = catNames #lc.categoryAxis.labels.boxAnchor = 'autox' lc.valueAxis.valueMin = 0 roundedVal = Valuation if Valuation % 10 == 0 else Valuation + Valuation % 10 lc.valueAxis.valueMax = roundedVal lc.valueAxis.valueStep = int((roundedVal / 10) / 10) * 10 lc.lines[0].strokeWidth = 2 lc.lines[1].strokeWidth = 1.5 lc.lines[0].strokeColor = colors.blue lc.lines[ 1].strokeColor = colors.green if Valuation > Investment else colors.red lc.valueAxis.visibleGrid = 1 lc.valueAxis.gridStrokeColor = colors.lightgrey lc.lines[0].name = 'Investment Value' lc.lines[1].name = 'Closing Valuation' #lc.lineLabelFormat = '%2.0f' labels = ['Investment Value', 'Closing Valuation'] lc._seriesCount = len(labels) drawing.add(my_title) drawing.add(lc) add_legend1(drawing, lc, labels, doc) return drawing ################### Old Function Call Segment####################### # FI=[4531082, 4892169, 206462, 4.56, 45.94] # Equity=[5218922,5362021.34,-62131.35,-1.19,50.36] # Investment=225323 # Valuation=865489 # monthlyInv=[23564,5782,84,79765,3243,65799,43344,5668,43,78900,3456,7543] # monthlyVal=[85265,578954,8656,87533,29754,264256,23244,23435,243234,5767,576854,574321] # equityTrades=[ # ['UBS BANK USA \n DEPOSIT ACCOUNT','IN8543975','Corporate','654','764.7','7643','764.97','245.65','9877','86','','','85.32%','1.69%'] # ] # bondTrades=[ # ['UBS BANK USA \n DEPOSIT ACCOUNT','IN8543975','Corporate','654','764.7','7643','764.97','245.65','9877','86','78','1/12/2021','85.32%','1.69%'] # ,['UBS BANK USA \n DEPOSIT ACCOUNT','IN8543975','Corporate','654','764.7','7643','764.97','245.65','9877','86','78','1/12/2021','85.32%','1.69%'] # ,['UBS BANK USA \n DEPOSIT ACCOUNT','IN8543975','Corporate','654','764.7','7643','764.97','245.65','9877','86','78','1/12/2021','85.32%','1.69%'] # ] # #Page 5 data # net_position=[ # ['Total Portfolio','','','','','','$9,967,814.44','$10,648,193.73','$145,102.43','1.46%','100%','100%'] # ] # generatePDF(FI,Equity,Investment,Valuation,monthlyInv,monthlyVal,equityTrades,bondTrades,net_position) ################### New Function Call Segment####################### # from helper_pdfgen import helperPdfgen , historyHelper , invAndVal # resp = helperPdfgen() # histdata = historyHelper() # FI= resp['FI'] # Equity= resp['Equity'] # iv = invAndVal() # Investment = iv['Investment'] # Valuation = iv['Valuation'] # monthlyInv = histdata['monthlyInv'] # monthlyVal = histdata['monthlyVal'] # labels = histdata['labels'] # equityTrades = resp['equityTrades'] # bondTrades= resp['bondTrades'] # URPL = Valuation - Investment # perURPL = URPL*100 / ( Valuation ) # #Page 5 data # net_position=[ # ['Total Portfolio','','','','','', Investment , Valuation , URPL , perURPL ,'100%','100%'] # ] # generatePDF(FI,Equity,Investment,Valuation,monthlyInv,monthlyVal,equityTrades,bondTrades,net_position,labels)
def _rawDraw(self, x, y): from reportlab.lib import colors from reportlab.graphics.shapes import Drawing, Line, String, STATE_DEFAULTS from reportlab.graphics.charts.linecharts import HorizontalLineChart, Label from reportlab.graphics.charts.barcharts import VerticalBarChart from reportlab.graphics.widgets.markers import makeMarker self._setScale([self.dataLine, self.dataBar]) (x1, y1, Width, Height) = self._getGraphRegion(x, y) #Build the graph self.drawing = Drawing(self.width, self.height) #Size of the Axis SizeXaxis = 14 SizeYaxis = 0.0 for n in range(int(self.valueMax / self.valueStep) + 1): eachValue = self.valueMin + n * self.valueStep SizeYaxis = max(SizeYaxis, self._stringWidth(str("%.1f Mbps" % eachValue), STATE_DEFAULTS['fontName'], STATE_DEFAULTS['fontSize']) ) # Bar chart of measured data bc = VerticalBarChart() SizeYaxis += bc.valueAxis.tickLeft bc.x = x1 - x + SizeYaxis bc.y = y1 - y + SizeXaxis bc.height = Height - SizeXaxis bc.width = Width - SizeYaxis self.graphCenterX = bc.x + bc.width/2 self.graphCenterY = bc.y + bc.height/2 if self.validData: # add valid data to chart bc.data = self.dataBar bc.categoryAxis.categoryNames = self.dataNames # add value labels above bars bc.barLabelFormat = "%.2f" bc.barLabels.dy = 0.08*inch bc.barLabels.fontSize = 6 else: # add message informing user there is no valid data bc.data = [ (0, ), ] bc.categoryAxis.categoryNames = [ '' ] Nodata = Label() Nodata.fontSize = 12 Nodata.angle = 0 Nodata.boxAnchor = 'c' Nodata.dx = self.graphCenterX Nodata.dy = self.graphCenterY Nodata.setText("NO VALID DATA") self.drawing.add(Nodata) # veriwave colors (R,G,B) = VeriwaveYellow bc.bars[0].fillColor = colors.Color(R,G,B) # set axis ranges bc.valueAxis.valueMin = self.valueMin bc.valueAxis.valueMax = self.valueMax bc.valueAxis.valueStep = self.valueStep bc.valueAxis.labelTextFormat = "%.1f Mbps" # set axis labels bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 0 # add bar chart self.drawing.add(bc) #Put the labels on the center of the graph self._drawLabels(self.title, "Frame Size", "") # Add Legend in upper left corner legendHeight = 9 legendX = bc.x + 5 legendY = bc.y + bc.height - 12 self.drawing.add(Line(legendX, legendY + 3 , legendX + 20, legendY + 3, strokeColor=bc.bars[0].fillColor, strokeWidth=3 )) self.drawing.add(String(legendX + 22, legendY, 'Offered Load', fontName='Helvetica', fontSize=8)) legendY -= legendHeight self.drawing.add(Line(legendX, legendY + 3 , legendX + 20, legendY + 3, strokeColor=bc.bars[1].fillColor, strokeWidth=3 )) self.drawing.add(String(legendX + 22, legendY, 'Forwarding Rate', fontName='Helvetica', fontSize=8)) legendY -= legendHeight # theoretical line chart if self.validData and len(self.dataLine[0]) > 0: # if one datapoint, draw horizontal line across chart DashArray = [2,2] if len(self.dataLine[0]) == 1: yPos = bc.height * (self.dataLine[0][0] - bc.valueAxis.valueMin) / (bc.valueAxis.valueMax - bc.valueAxis.valueMin) self.drawing.add(Line(bc.x, bc.y + yPos, bc.x + bc.width, bc.y + yPos, strokeColor=colors.red, strokeWidth=1, strokeDashArray = DashArray)) # theoretical line lc = HorizontalLineChart() lc.x = bc.x lc.y = bc.y lc.height = bc.height lc.width = bc.width # line axis values lc.valueAxis.valueMin = self.valueMin lc.valueAxis.valueMax = self.valueMax lc.valueAxis.valueStep = self.valueStep lc.valueAxis.visible = False lc.data = self.dataLine # line formatting lc.lines[0].strokeColor = colors.red lc.lines[0].strokeDashArray = DashArray lc.lines[0].symbol = makeMarker('FilledDiamond') lc.joinedLines = 1 self.drawing.add(lc) # add legend self.drawing.add(Line(legendX, legendY + 3, legendX + 20 , legendY + 3, strokeColor=colors.red, strokeWidth=1, strokeDashArray=DashArray)) self.drawing.add(String(legendX + 22, legendY, 'Theory', fontName='Helvetica', fontSize=8)) legendY -= legendHeight
def create_single_grade_pdf(student_id, class_id, assignment_count, grade_standard_dict, grade_student_dict, assignment_line_all, assignment_names, assignment_dict): '''--Variables--''' Story=[] Elements=[] buff = StringIO() formatted_time = time.ctime() minimum = 100 standard_averages=[[]] standard_table=[] #content_areas = [] '''------''' styles = getSampleStyleSheet() HeaderStyle = styles["Heading1"] #get the student Name #Create the name for the PDf being returned pdfName = get_student_name(student_id).first_name+"_"+get_student_name(student_id).last_name+"_SR"+".pdf" #set up the response headers so the browser knows to return a PDF document response.headers['Content-Type'] = 'application/pdf' response.headers['Content-Disposition'] ='attachment;filename=%s;'%pdfName doc = SimpleDocTemplate(buff,pagesize=letter,rightMargin=72,leftMargin=72,topMargin=72,bottomMargin=18) doc.title=pdfName #Set up some styles styles=getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) styles.add(ParagraphStyle(name='Indent', rightIndent=3)) styles.add(ParagraphStyle(name = 'Title2', parent = styles['Normal'], fontName = 'DejaVuSansCondensed', fontSize = 18, leading = 22, #alignment = TA_LEFT, spaceAfter = 6), alias = 'title2') #Time-Stamp ptext = '<font size=12>%s</font>' % formatted_time Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) #Administrator ptext='<font size=12><b>%s %s</b></font>'%(get_student_name(student_id).first_name, get_student_name(student_id).last_name) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) #Grade Number and Content Area ptext = '<font size=12><b>%s Student Report</b></font>'%(get_class_name(class_id).name) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 7)) Elements.extend(ptext) #Total Assignments ptext = '<font size=12>Total Assignments: %s</font>'%(assignment_count) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 7)) Elements.extend(ptext) Story.append(Spacer(1,20)) #Graph Title ptext = '<font size=15><b>Current Performance by Standard</b></font>' Story.append(Paragraph(ptext, styles["title"])) Story.append(Spacer(1,50)) #get all the standards for a specific grade and content area standard_query = ((db.classes.id == class_id)& (student_id == db.student.id)& (db.classes.id == db.student_classes.class_id)& (db.student.id == db.student_classes.student_id)& (db.student.id == db.student_grade.student_id)& (db.grade.id == db.student_grade.grade_id)& (db.grade.id == db.grade_standard.grade_id)& (db.standard.id == db.grade_standard.standard_id)& (db.classes.id == db.class_grade.class_id)& (db.grade.id == db.class_grade.grade_id)& (db.standard.content_area == db.contentarea.id)) standard_list = db(standard_query).select(db.standard.id, db.standard.short_name, db.standard.reference_number,db.student_grade.student_score, db.grade.score, db.contentarea.name) standard_ref_list=[] #Setup the Dictionary of standard averages standard_dict = {} standard_table = [] standard_averages=[[]] for row in standard_list: if row.standard.id in standard_dict.keys(): if((row.grade.score != 0.0) | (row.student_grade.student_score != 0.0)): max_score = standard_dict[row.standard.id][0] + row.grade.score student_score = standard_dict[row.standard.id][1] + row.student_grade.student_score standard_dict[row.standard.id] = [max_score, student_score, row.standard.reference_number, row.standard.short_name] else: standard_dict[row.standard.id] = [row.grade.score, row.student_grade.student_score, row.standard.reference_number, row.standard.short_name] i = 0 #set up the 2D list of Standard Averages for standard in sorted(standard_dict.keys()): standard_ref_list.append(standard_dict[standard][2]) standard_table.append([]) current_avg = (standard_dict[standard][1]/standard_dict[standard][0])*100 if minimum > current_avg: minimum = current_avg #int/round was here standard_table[i].append(standard_dict[standard][3]+": "+format((standard_dict[standard][1]/standard_dict[standard][0])*100,'.2f')+"%") #int/round was here standard_averages[0].append((standard_dict[standard][1]/standard_dict[standard][0])*100) for grade in grade_standard_dict.keys(): for standardId in grade_standard_dict[grade][1]: if(standardId == standard): standard_table[i].append(grade_standard_dict[grade][0]+":"+format((grade_student_dict[grade][1]/grade_student_dict[grade][0])*100, '.2f')+"%") i+=1 sorted(standard_table,key=lambda l:l[0]) '''---Graph---''' drawing = Drawing(600, 200) data = standard_averages bc = VerticalBarChart() #location in the document (x,y) bc.x = 10 bc.y = 30 #width and height of the graph bc.height = 225 bc.width = 400 bc.data = data bc.categoryAxis.drawGridLast=True bc.categoryAxis.gridStart=0 bc.categoryAxis.gridStrokeLineCap = 2 bc.categoryAxis.gridEnd=3 #bc.barLabels = #Update colors of the bars in the graph bc.bars.symbol = ShadedRect() bc.bars.symbol.fillColorStart = colors.lightblue bc.bars.symbol.fillColorEnd = colors.lightblue bc.bars.symbol.strokeWidth = 0 #this draws a line at the top of the graph to close it. bc.strokeColor = colors.black #Y-axis min, max, and steps. if minimum != 100: bc.valueAxis.valueMin = minimum -10 else: bc.valueAxis.valueMin = 50 bc.valueAxis.valueMax = 100 bc.valueAxis.valueStep = 5 #where to anchor the origin of the graph bc.categoryAxis.labels.boxAnchor = 'ne' #Locations of labels for the X-axis bc.categoryAxis.labels.dx = 2 bc.categoryAxis.labels.dy = -2 bc.barLabels.nudge = -10 bc.barLabelFormat = '%.2f%%' bc.barLabels.dx = 0 bc.barLabels.dy = 0 #The angle of the lables for the X-axis bc.categoryAxis.labels.angle = 30 #List of the categories to place on the X-axis bc.categoryAxis.categoryNames = standard_ref_list drawing.add(bc) '''------''' '''--Graph Legend--''' #Graph Legend legend = Legend() legend.alignment = 'right' legend.x = 420 legend.y = 150 legend.deltax = 60 legend.dxTextSpace = 10 legend.columnMaximum = 4 legend.colorNamePairs = [(colors.lightblue, 'grade average')] drawing.add(legend, 'legend') drawing_title = "Bar Graph" Story.append(drawing) Story.append(Spacer(1,15)) #LineGraph Title ptext = '<font size=15><b>Class Performance by Assignment</b></font>' Story.append(Paragraph(ptext, styles["title"])) Story.append(Spacer(1,30)) ''' Line Plot Graph ------ ''' assignment_data_all =[[],[]] for key in assignment_dict.keys(): assignment_data_all[0].append(assignment_dict[key][2]) assignment_data_all[1].append(assignment_dict[key][1]) drawing2 = Drawing(600, 200) data2 = assignment_data_all #lp = LinePlot() #data[0] = preprocessData(data[0]) lp = HorizontalLineChart() lp.x = -20 lp.y = 0 lp.height = 225 lp.width = 500 lp.data = data2 lp.joinedLines = 1 lp.lines.symbol = makeMarker('FilledCircle') lp.lines[0].strokeColor = colors.grey lp.lines[1].strokeColor = colors.lightblue lp.strokeColor = colors.black lp.categoryAxis.labels.fontSize = 7 lp.categoryAxis.categoryNames = assignment_names lp.categoryAxis.labels.boxAnchor = 'ne' lp.categoryAxis.labels.angle = 30 lp.categoryAxis.drawGridLast=True #lp.categoryAxis.gridStart=0 lp.categoryAxis.gridStrokeLineCap = 2 #lp.categoryAxis.gridEnd=3 #lp.categoryAxis.visibleGrid = 1 lp.valueAxis.visibleGrid = 1 lp.valueAxis.visible = 1 lp.valueAxis.drawGridLast=False #lp.valueAxis.gridStart = 0 #lp.valueAxis.gridEnd = 100 lp.valueAxis.gridStrokeColor = colors.black lp.valueAxis.valueMin = 0 lp.valueAxis.valueMax = 105 lp.valueAxis.valueStep = 10 lp.lineLabelFormat = '%2.0f' lp.strokeColor = colors.black lp.fillColor = colors.white drawing2.add(lp) legend = Legend() legend.alignment = 'right' legend.x = 482 legend.y = 150 legend.deltax = 60 legend.dxTextSpace = 2 legend.colorNamePairs = [(colors.lightblue, 'Student'),(colors.grey, 'Class')] drawing2.add(legend, 'legend') Story.append(drawing2) Story.append(Spacer(1,30)) ptext = '<font size=15><b>Assignments by Standard</b></font>' Story.append(Paragraph(ptext, styles["title"])) Story.append(Spacer(1,10)) t=Table(standard_table) t.setStyle(t.setStyle(TableStyle([('BOX', (0,0), (-1,-1), 0.25, colors.black), ('FONTSIZE', (0,0), (-1,-1), 7), ('BACKGROUND',(0,0),(0,-1),colors.lightgrey), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),]))) Story.append(t) #build PDF document and return it doc.build(Story) pdf = buff.getvalue() buff.close() return pdf
def _rawDraw(self, x, y): from reportlab.lib import colors from reportlab.graphics.shapes import Drawing, Line, String, STATE_DEFAULTS from reportlab.graphics.charts.linecharts import HorizontalLineChart, Label from reportlab.graphics.charts.barcharts import VerticalBarChart self._setScale([self.dataLine, self.dataBar]) (x1, y1, Width, Height) = self._getGraphRegion(x, y) self.drawing = Drawing(self.width, self.height) #Size of the Axis SizeXaxis = 14 SizeYaxis = 0.0 for n in range(int(self.valueMax / self.valueStep) + 1): eachValue = self.valueMin + n * self.valueStep SizeYaxis = max(SizeYaxis, self._stringWidth("%.3f%%" % (eachValue), STATE_DEFAULTS['fontName'], STATE_DEFAULTS['fontSize']) ) bc = VerticalBarChart() SizeYaxis += bc.valueAxis.tickLeft bc.x = x1 - x + SizeYaxis bc.y = y1 - y + SizeXaxis bc.height = Height - SizeXaxis bc.width = Width - SizeYaxis self.graphCenterX = bc.x + bc.width/2 self.graphCenterY = bc.y + bc.height/2 if self.validData: # add valid data to chart bc.data = self.dataBar bc.categoryAxis.categoryNames = self.dataNames # add value labels above bars bc.barLabelFormat = "%.2f" bc.barLabels.dy = 0.08*inch bc.barLabels.fontSize = 6 else: # no valid data bc.data = [ (0,), ] bc.categoryAxis.categoryNames = [ '' ] Nodata = Label() Nodata.fontSize = 12 Nodata.angle = 0 Nodata.boxAnchor = 'c' Nodata.dx = self.graphCenterX Nodata.dy = self.graphCenterY Nodata.setText("NO VALID DATA") self.drawing.add(Nodata) # format chart (R,G,B) = VeriwaveYellow bc.bars[0].fillColor = colors.Color(R,G,B) # axis values bc.valueAxis.valueMin = self.valueMin bc.valueAxis.valueMax = self.valueMax bc.valueAxis.valueStep = self.valueStep # axis formatting if self.valueStep >= 10.0: bc.valueAxis.labelTextFormat = "%.0f%%" elif self.valueStep >= 1.0: bc.valueAxis.labelTextFormat = "%.1f%%" elif self.valueStep >= 0.1: bc.valueAxis.labelTextFormat = "%.2f%%" else: bc.valueAxis.labelTextFormat = "%.3f%%" bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 0 self._drawLabels(self.title, "Frame Size", "Percent Loss") # What if all loss is Zero if self.valueMin == 0.0 and self.valueMax == self.valueStep and self.validData: bc.valueAxis.labelTextFormat = "%.3f%%" Label_Zero = Label() Label_Zero.fontSize = 12 Label_Zero.angle = 0 Label_Zero.dx = self.graphCenterX Label_Zero.dy = self.graphCenterY Label_Zero.boxAnchor = 'c' Label_Zero.setText("ALL DATA IS ZERO") self.drawing.add(Label_Zero) self.drawing.add(bc) # Add Legend in upper right corner legendHeight = 9 legendX = bc.x + 5 legendY = bc.y + bc.height - 12 if len(self.dataLine) > 0 and self.validData: # if one datapoint, draw horizontal line across chart DashArray = [2,2] if len(self.dataLine[0]) == 1: yPos = bc.height * (self.dataLine[0][0] - bc.valueAxis.valueMin) / (bc.valueAxis.valueMax - bc.valueAxis.valueMin) self.drawing.add(Line(bc.x, bc.y + yPos, bc.x + bc.width, bc.y + yPos, strokeColor=colors.red, strokeWidth=1, strokeDashArray = DashArray)) # theoretical line lc = HorizontalLineChart() lc.x = bc.x lc.y = bc.y lc.height = bc.height lc.width = bc.width # axis values lc.valueAxis.valueMin = self.valueMin lc.valueAxis.valueMax = self.valueMax lc.valueAxis.valueStep = self.valueStep lc.valueAxis.visible = False lc.data = self.dataLine # dashed line with diamond markers lc.lines[0].strokeDashArray = [2,2] lc.lines[0].symbol = makeMarker('FilledDiamond') lc.joinedLines = 1 self.drawing.add(lc) self.drawing.add(Line(legendX, legendY + 3, legendX + 20 , legendY + 3, strokeColor=lc.lines[0].strokeColor, strokeWidth=1, strokeDashArray = lc.lines[0].strokeDashArray)) self.drawing.add(String(legendX + 22, legendY, 'Theory', fontName='Helvetica', fontSize=8)) legendY -= legendHeight
def crear_informe(self): guion = [] d = Drawing(300, 200) tarta = Pie() tarta.x = 65 tarta.y = 15 tarta.width = 170 tarta.height = 170 tarta.data = [] tarta.labels = [] cores = [] follaEstilo = getSampleStyleSheet() _HEX = list('0123456789ABCDEF') j=False ventasMarca=metodosBase.metodosBase.listar_ventas_marca(self) for ventaMarca in ventasMarca: tarta.data.append(ventaMarca[0]) tarta.labels.append(ventaMarca[1]) color = '#' + ''.join(_HEX[random.randint(0, len(_HEX)-1)] for _ in range(6)) cores.append(colors.HexColor(color)) if ((tarta.data[0] is not None) and j==False): mayor = tarta.data[0] indice=0 j=True else: if(ventaMarca[0]>=mayor): mayor=ventaMarca[0] tarta.slices.strokeWidth = 0.2 # anchura das liñas tarta.sideLabels = 1 tarta.slices[tarta.data.index(mayor)].popout = 10 # destacase o gajo que pomos entre corchetes, o que ten maior valor de todos tarta.slices[tarta.data.index(mayor)].strokeWidth = 2 # a este gajo en concreto cambiamos o tamaño da liña tarta.slices[tarta.data.index(mayor)].labelRadius = 1.20 # radio da etiqueta , cambiamolo para este elemento tarta.slices[tarta.data.index(mayor)].fontColor = colors.red lenda = Legend() lenda.x = 370 lenda.y = 0 lenda.dx = 8 lenda.dy = 8 lenda.fontName = 'Helvetica' lenda.fontSize = 7 lenda.boxAnchor = 'n' lenda.columnMaximum = 10 lenda.strokeColor = colors.black lenda.strokeWidth = 1 lenda.deltax = 75 lenda.deltay = 10 lenda.autoXPadding = 5 lenda.yGap = 0 lenda.dxTextSpace = 5 lenda.alignment = 'right' lenda.dividerLines = 1 | 2 | 4 lenda.dividerOffsY = 4.5 lenda.subCols.rpad = 30 for i, color in enumerate(cores): tarta.slices[i].fillColor = color lenda.colorNamePairs = [(tarta.slices[i].fillColor, (tarta.labels[i][0:20], '%0.2f' % tarta.data[i]) ) for i in range(len(tarta.data))] '''parrafo 1 : cabeceira primeira grafica''' cabeceira = follaEstilo['Heading4'] # formato por defecto cabeceira.pageBreakBefore = 0 # con un uno a primeira folla queda en branco cabeceira.keepWitNext = 0 # para que non nos deixe a primeira paxina en branco cabeceira.backColor = colors.lightcyan parrafo = Paragraph("Informe de ventas por marcas", cabeceira) guion.append(parrafo) guion.append(Spacer(0, 40)) d.add(lenda) d.add(tarta) guion.append(d) guion.append(Spacer(0, 60)) '''parrafo 2:cabeceira segunda grafica''' cabeceira2 = follaEstilo['Heading4'] # formato por defecto cabeceira2.pageBreakBefore = 0 # con un uno a primeira folla queda en branco cabeceira2.keepWitNext = 0 # para que non nos deixe a primeira paxina en branco cabeceira2.backColor = colors.lightcyan parrafo2 = Paragraph("Informe de ventas por año de matriculación", cabeceira) guion.append(parrafo2) guion.append(Spacer(0, 40)) d2 = Drawing(400, 200) lc = HorizontalLineChart() lc.x = 30 lc.y = 50 lc.height = 125 lc.width = 350 lc.data = [] lista=[] lc.categoryAxis.categoryNames = [] ventasAno = metodosBase.metodosBase.listar_ventas_anoMatricula(self) for ventaAno in ventasAno: lista.append(ventaAno[0]) lc.categoryAxis.categoryNames.append(str(ventaAno[1])) lc.data.append(lista) lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 12 lc.valueAxis.valueStep = 2 lc.lines[0].strokeWidth = 2 lc.lines[0].symbol = makeMarker('FilledCircle') # círculos rellenos lc.lines[1].strokeWidth = 1.5 d2.add(lc) guion.append(d2) guion.append(Spacer(0, 20)) cabeceira3 = follaEstilo['Normal'] # formato por defecto parrafo3 = Paragraph(" COCHESJOSE S.L. CARRETERA INFINITA S/N , TELEFONO:986505050", cabeceira3) cabeceira3.keepWitNext = 0 # para que non nos deixe a primeira paxina en branco guion.append(parrafo3) guion.append(Spacer(0, 20)) doc = SimpleDocTemplate("informeVentas.pdf", pagesize=A4) doc.build(guion)
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)
#========== from reportlab.graphics.charts.linecharts import HorizontalLineChart titulo = Paragraph("PROCESOS REALIZADOS EN LINUX", estilo['title']) story.append(titulo) story.append(Spacer(0, inch * .20)) titulo = Paragraph( "Tiempos de ejecución proceso conversión a escala de grises", estilo['title']) story.append(titulo) story.append(Spacer(0, inch * .1)) d = Drawing(400, 200) lc = HorizontalLineChart() lc.x = 30 lc.y = 50 lc.height = 125 lc.width = 350 #lc.data = [[0.7,0.1,0.5,0.2]] datos = [] datos.append(tim_to_gray) lc.data = datos #lc.categoryAxis.categoryNames = ['Suspenso', 'Aprobado', 'Notable', # 'Sobresaliente'] lc.categoryAxis.categoryNames = imgs #lista de las imagenes lc.categoryAxis.labels.boxAnchor = 'n' lc.categoryAxis.labels.angle = 90 lc.categoryAxis.labels.dy = -45 lc.valueAxis.valueMin = 0
def generate_certificate(elements): style = TableStyle([('TEXTALIGN', (0, 0), (-1, -1), 'CENTER'), ('TEXTCOLOR', (0, 0), (-1, -1), colors.red), ('VALIGN', (0, 0), (0, -1), 'TOP'), ('INNERGRID', (0, 0), (-1, -1), 0.50, colors.red), ('BOX', (0, 0), (-1, -1), 0.50, colors.green), ('BACKGROUND', (0, 0), (-1, -1), colors.blue), ]) s = getSampleStyleSheet() s = s["BodyText"] s.wordWrap = "RGB" styles = ParagraphStyle( name='Normal', fontName='Helvetica-Bold', fontSize=15, alignment=1, ) elements.append(Spacer(1, 0.5 * inch)) i = Paragraph(str("candidate performance vs average performance"), styles) elements.append(i) elements.append(Spacer(1, 0.1 * inch)) drawing = Drawing(0, 200) # for indices data = [ (13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5) ] # data for drawing bar graphs bc = VerticalBarChart() bc.x = 0 # x,y define the left bottom of graph bc.y = 0 bc.height = 150 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 = 6 # next 3 lines is for naming indices bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 60 bc.categoryAxis.categoryNames = ['Jan-99', 'Feb-99', 'Mar-99', 'Apr-99', 'May-99', 'Jun-99', 'Jul-99', 'Aug-99'] drawing.add(bc) elements.append(drawing) elements.append(Spacer(1, 0.5 * inch)) drawing = Drawing(0, 175) # for indices lc = HorizontalLineChart() lc.x = 0 lc.y = 10 lc.height = 150 lc.width = 300 lc.data = data lc.joinedLines = 1 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 lc.lines[0].strokeWidth = 2 lc.lines[1].strokeWidth = 1.5 drawing.add(lc) elements.append(drawing) drawing = Drawing(0, 400) # for indices data = [ ((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)), ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6)) ] elements.append(Spacer(1, 0.1 * inch)) i = Paragraph(str("candidate performance vs average performance"), styles) elements.append(i) elements.append(Spacer(1, 0.1 * inch)) lp = LinePlot() lp.x = 0 lp.y = 50 lp.height = 300 lp.width = 600 lp.data = data lp.joinedLines = 1 lp.lines[0].symbol = makeMarker('FilledCircle') lp.lines[1].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.valueSteps = [1, 2, 3, 5, 6] drawing.add(lp) elements.append(drawing) elements.append(Spacer(1, 0.1 * inch)) drawing = Drawing(100, 350) pc = Pie() pc.x = 65 pc.y = 15 pc.width = 300 pc.height = 300 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 drawing.add(pc) elements.append(drawing) elements.append(Spacer(1, 0.5 * inch)) return elements
def generate_certificate(elements): styles = ParagraphStyle( name='Normal', fontName='Helvetica-Bold', fontSize=15, alignment=1, ) elements.append(Spacer(1, 0.5 * inch)) i = Paragraph(str("candidate performance vs average performance"), styles) elements.append(i) elements.append(Spacer(1, 0.1 * inch)) drawing = Drawing(0, 200) # for indices data = [ (13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5) ] # data for drawing bar graphs bc = VerticalBarChart() bc.x = 0 # x,y define the left bottom of graph bc.y = 0 bc.height = 150 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 = 6 # next 3 lines is for naming indices bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 60 bc.categoryAxis.categoryNames = ['Jan-99', 'Feb-99', 'Mar-99', 'Apr-99', 'May-99', 'Jun-99', 'Jul-99', 'Aug-99'] drawing.add(bc) elements.append(drawing) elements.append(Spacer(1, 0.5 * inch)) drawing = Drawing(0, 175) # for indices lc = HorizontalLineChart() lc.x = 0 lc.y = 10 lc.height = 150 lc.width = 300 lc.data = data lc.joinedLines = 1 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 lc.lines[0].strokeWidth = 2 lc.lines[1].strokeWidth = 1.5 drawing.add(lc) elements.append(drawing) drawing = Drawing(0, 400) # for indices data = [ ((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)), ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6)) ] elements.append(Spacer(1, 0.1 * inch)) i = Paragraph(str("candidate performance vs average performance"), styles) elements.append(i) elements.append(Spacer(1, 0.1 * inch)) lp = LinePlot() lp.x = 0 lp.y = 50 lp.height = 300 lp.width = 600 lp.data = data lp.joinedLines = 1 lp.lines[0].symbol = makeMarker('FilledCircle') lp.lines[1].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.valueSteps = [1, 2, 3, 5, 6] drawing.add(lp) elements.append(drawing) elements.append(Spacer(1, 0.1 * inch)) drawing = Drawing(100, 350) pc = Pie() pc.x = 65 pc.y = 15 pc.width = 300 pc.height = 300 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 drawing.add(pc) elements.append(drawing) elements.append(Spacer(1, 0.7 * inch)) styles = ParagraphStyle( name='Normal', fontName='Helvetica', fontSize=15, alignment=0, ) elements.append(Spacer(1, 0.5* inch)) i = Paragraph(str("Please click on black square to play the video."), styles) elements.append(i) elements.append(platypus.flowables.Macro('canvas.saveState()')) elements.append(platypus.flowables.Macro('canvas.linkURL("fun.mp4",(400,510,410,500),relative=0,thickness=10)')) elements.append(platypus.flowables.Macro('canvas.restoreState()')) return elements
def sample1line(datastring=""" 1997 1998 1999 2000 2001 , pink -10 11 40 22 30 , blue 11 40 22 30 -10, cyan 40 22 30 -10 11 """): # parse the data lines = datastring.split(",") titlestring = lines[0] titles = titlestring.split() data = [] alldata = [] linecolors = [] for dataline in lines[1:]: sline = dataline.split() linecolor = sline[0] numbers = list(map(float, sline[1:])) linecolors.append(linecolor) data.append(numbers) alldata.extend(numbers) drawing = Drawing(400, 200) bc = HorizontalLineChart() bc.x = 25 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = min(0, min(alldata)-5) #-10 bc.valueAxis.valueMax = max(20, max(alldata)+5) #40 bc.valueAxis.valueStep = 10 bc.valueAxis.visibleGrid = 1 bc.valueAxis.gridStrokeColor = colors.blue bc.valueAxis.gridStart = 0 bc.valueAxis.gridEnd = 300 bc.valueAxis.labelTextFormat ="%s%%" #bc.valueAxis.joinAxisPos = -10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 0 bc.categoryAxis.joinAxis = bc.valueAxis bc.categoryAxis.joinAxisMode = "bottom" bc.categoryAxis.visibleGrid = 1 #bc.lines[0].strokeColor = colors.pink #bc.lines[1].strokeColor = colors.lavender #bc.lines[2].strokeColor = colors.skyblue linenumber = 0 for colorname in linecolors: bc.lines[linenumber].strokeColor = getattr(colors, colorname) bc.lines[linenumber].strokeWidth = 3 linenumber = linenumber+1 catNames = titles bc.categoryAxis.categoryNames = catNames drawing.add(bc) return drawing
countries = [] for row in result.fetchall(): if c != unicode(row[0]): c = unicode(row[0]) countries.append(c) data_row += 1 data_col = 0 data_values.append([]) linelabels.append([]) data_values[data_row].append(float(str(row[4]))) if data_col == 0: linelabels[data_row].append(c) else: linelabels[data_row].append(None) data_col += 1 d = Drawing(800, 600) chart = HorizontalLineChart() chart.width = 740 chart.height = 560 chart.x = 50 chart.y = 20 chart.lineLabelArray = linelabels chart.lineLabelFormat = 'values' chart.data = data_values chart.categoryAxis.categoryNames = h_labels chart.valueAxis.valueMin = 0 d.add(chart) d.save(fnRoot='ghg-totals', formats=['png'])
def makeLineChart(self, context, width, height, data, xvalues, backgroundColor, borderColor, labelAngles, labelXOffsets, labelYOffsets, lineColors, lineWidths, lineLabelFormat, yAxisMin, yAxisMax, yAxisStep): content = [] drawing = Drawing(width, height) lp = HorizontalLineChart() lp.x = 0 lp.y = 0 lp.height = height lp.width = width lp.data = data lp.joinedLines = 1 if backgroundColor: lp.fillColor = colors.HexColor(backgroundColor) if borderColor: lp.strokeColor = colors.HexColor(borderColor) if yAxisMin: lp.valueAxis.valueMin = yAxisMin if yAxisMax: lp.valueAxis.valueMax = yAxisMax if yAxisStep: lp.valueAxis.valueStep = yAxisStep if xvalues: lp.categoryAxis.categoryNames = xvalues def handleSingleOrList(targetObject, value, propertyName, defaultLength, mapFunc=None): if isinstance(value, list): for i in range(0, len(value)): setattr(targetObject[i], propertyName, value[i] if not mapFunc else mapFunc(value[i])) else: for i in range(0, defaultLength): setattr(targetObject[i], propertyName, value if not mapFunc else mapFunc(value)) if labelAngles: handleSingleOrList(lp.categoryAxis.labels, labelAngles, 'angle', len(data[0])) if labelXOffsets: handleSingleOrList(lp.categoryAxis.labels, labelXOffsets, 'dx', len(data[0])) if labelYOffsets: handleSingleOrList(lp.categoryAxis.labels, labelYOffsets, 'dy', len(data[0])) if lineLabelFormat: lp.lineLabelFormat = lineLabelFormat if lineColors: handleSingleOrList(lp.lines, lineColors, 'strokeColor', len(data), colors.HexColor) if lineWidths: handleSingleOrList(lp.lines, lineWidths, 'strokeWidth', len(data)) drawing.add(lp) content.append(drawing) return content
def create_single_grade_pdf(student_id, class_id, assignment_count, grade_standard_dict, grade_student_dict, assignment_line_all, assignment_names, assignment_dict): '''--Variables--''' Story = [] Elements = [] buff = StringIO() formatted_time = time.ctime() minimum = 100 standard_averages = [[]] standard_table = [] #content_areas = [] '''------''' styles = getSampleStyleSheet() HeaderStyle = styles["Heading1"] #get the student Name #Create the name for the PDf being returned pdfName = get_student_name(student_id).first_name + "_" + get_student_name( student_id).last_name + "_SR" + ".pdf" #set up the response headers so the browser knows to return a PDF document response.headers['Content-Type'] = 'application/pdf' response.headers[ 'Content-Disposition'] = 'attachment;filename=%s;' % pdfName doc = SimpleDocTemplate(buff, pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) doc.title = pdfName #Set up some styles styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) styles.add(ParagraphStyle(name='Indent', rightIndent=3)) styles.add( ParagraphStyle( name='Title2', parent=styles['Normal'], fontName='DejaVuSansCondensed', fontSize=18, leading=22, #alignment = TA_LEFT, spaceAfter=6), alias='title2') #Time-Stamp ptext = '<font size=12>%s</font>' % formatted_time Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) #Administrator ptext = '<font size=12><b>%s %s</b></font>' % (get_student_name( student_id).first_name, get_student_name(student_id).last_name) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) #Grade Number and Content Area ptext = '<font size=12><b>%s Student Report</b></font>' % ( get_class_name(class_id).name) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 7)) Elements.extend(ptext) #Total Assignments ptext = '<font size=12>Total Assignments: %s</font>' % (assignment_count) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 7)) Elements.extend(ptext) Story.append(Spacer(1, 20)) #Graph Title ptext = '<font size=15><b>Current Performance by Standard</b></font>' Story.append(Paragraph(ptext, styles["title"])) Story.append(Spacer(1, 50)) #get all the standards for a specific grade and content area standard_query = ((db.classes.id == class_id) & (student_id == db.student.id) & (db.classes.id == db.student_classes.class_id) & (db.student.id == db.student_classes.student_id) & (db.student.id == db.student_grade.student_id) & (db.grade.id == db.student_grade.grade_id) & (db.grade.id == db.grade_standard.grade_id) & (db.standard.id == db.grade_standard.standard_id) & (db.classes.id == db.class_grade.class_id) & (db.grade.id == db.class_grade.grade_id) & (db.standard.content_area == db.contentarea.id)) standard_list = db(standard_query).select( db.standard.id, db.standard.short_name, db.standard.reference_number, db.student_grade.student_score, db.grade.score, db.contentarea.name) standard_ref_list = [] #Setup the Dictionary of standard averages standard_dict = {} standard_table = [] standard_averages = [[]] for row in standard_list: if row.standard.id in standard_dict.keys(): if ((row.grade.score != 0.0) | (row.student_grade.student_score != 0.0)): max_score = standard_dict[row.standard.id][0] + row.grade.score student_score = standard_dict[ row.standard.id][1] + row.student_grade.student_score standard_dict[row.standard.id] = [ max_score, student_score, row.standard.reference_number, row.standard.short_name ] else: standard_dict[row.standard.id] = [ row.grade.score, row.student_grade.student_score, row.standard.reference_number, row.standard.short_name ] i = 0 #set up the 2D list of Standard Averages for standard in sorted(standard_dict.keys()): standard_ref_list.append(standard_dict[standard][2]) standard_table.append([]) current_avg = (standard_dict[standard][1] / standard_dict[standard][0]) * 100 if minimum > current_avg: minimum = current_avg #int/round was here standard_table[i].append(standard_dict[standard][3] + ": " + format( (standard_dict[standard][1] / standard_dict[standard][0]) * 100, '.2f') + "%") #int/round was here standard_averages[0].append( (standard_dict[standard][1] / standard_dict[standard][0]) * 100) for grade in grade_standard_dict.keys(): for standardId in grade_standard_dict[grade][1]: if (standardId == standard): standard_table[i].append( grade_standard_dict[grade][0] + ":" + format((grade_student_dict[grade][1] / grade_student_dict[grade][0]) * 100, '.2f') + "%") i += 1 sorted(standard_table, key=lambda l: l[0]) '''---Graph---''' drawing = Drawing(600, 200) data = standard_averages bc = VerticalBarChart() #location in the document (x,y) bc.x = 10 bc.y = 30 #width and height of the graph bc.height = 225 bc.width = 400 bc.data = data bc.categoryAxis.drawGridLast = True bc.categoryAxis.gridStart = 0 bc.categoryAxis.gridStrokeLineCap = 2 bc.categoryAxis.gridEnd = 3 #bc.barLabels = #Update colors of the bars in the graph bc.bars.symbol = ShadedRect() bc.bars.symbol.fillColorStart = colors.lightblue bc.bars.symbol.fillColorEnd = colors.lightblue bc.bars.symbol.strokeWidth = 0 #this draws a line at the top of the graph to close it. bc.strokeColor = colors.black #Y-axis min, max, and steps. if minimum != 100: bc.valueAxis.valueMin = minimum - 10 else: bc.valueAxis.valueMin = 50 bc.valueAxis.valueMax = 100 bc.valueAxis.valueStep = 5 #where to anchor the origin of the graph bc.categoryAxis.labels.boxAnchor = 'ne' #Locations of labels for the X-axis bc.categoryAxis.labels.dx = 2 bc.categoryAxis.labels.dy = -2 bc.barLabels.nudge = -10 bc.barLabelFormat = '%.2f%%' bc.barLabels.dx = 0 bc.barLabels.dy = 0 #The angle of the lables for the X-axis bc.categoryAxis.labels.angle = 30 #List of the categories to place on the X-axis bc.categoryAxis.categoryNames = standard_ref_list drawing.add(bc) '''------''' '''--Graph Legend--''' #Graph Legend legend = Legend() legend.alignment = 'right' legend.x = 420 legend.y = 150 legend.deltax = 60 legend.dxTextSpace = 10 legend.columnMaximum = 4 legend.colorNamePairs = [(colors.lightblue, 'grade average')] drawing.add(legend, 'legend') drawing_title = "Bar Graph" Story.append(drawing) Story.append(Spacer(1, 15)) #LineGraph Title ptext = '<font size=15><b>Class Performance by Assignment</b></font>' Story.append(Paragraph(ptext, styles["title"])) Story.append(Spacer(1, 30)) ''' Line Plot Graph ------ ''' assignment_data_all = [[], []] for key in assignment_dict.keys(): assignment_data_all[0].append(assignment_dict[key][2]) assignment_data_all[1].append(assignment_dict[key][1]) drawing2 = Drawing(600, 200) data2 = assignment_data_all #lp = LinePlot() #data[0] = preprocessData(data[0]) lp = HorizontalLineChart() lp.x = -20 lp.y = 0 lp.height = 225 lp.width = 500 lp.data = data2 lp.joinedLines = 1 lp.lines.symbol = makeMarker('FilledCircle') lp.lines[0].strokeColor = colors.grey lp.lines[1].strokeColor = colors.lightblue lp.strokeColor = colors.black lp.categoryAxis.labels.fontSize = 7 lp.categoryAxis.categoryNames = assignment_names lp.categoryAxis.labels.boxAnchor = 'ne' lp.categoryAxis.labels.angle = 30 lp.categoryAxis.drawGridLast = True #lp.categoryAxis.gridStart=0 lp.categoryAxis.gridStrokeLineCap = 2 #lp.categoryAxis.gridEnd=3 #lp.categoryAxis.visibleGrid = 1 lp.valueAxis.visibleGrid = 1 lp.valueAxis.visible = 1 lp.valueAxis.drawGridLast = False #lp.valueAxis.gridStart = 0 #lp.valueAxis.gridEnd = 100 lp.valueAxis.gridStrokeColor = colors.black lp.valueAxis.valueMin = 0 lp.valueAxis.valueMax = 105 lp.valueAxis.valueStep = 10 lp.lineLabelFormat = '%2.0f' lp.strokeColor = colors.black lp.fillColor = colors.white drawing2.add(lp) legend = Legend() legend.alignment = 'right' legend.x = 482 legend.y = 150 legend.deltax = 60 legend.dxTextSpace = 2 legend.colorNamePairs = [(colors.lightblue, 'Student'), (colors.grey, 'Class')] drawing2.add(legend, 'legend') Story.append(drawing2) Story.append(Spacer(1, 30)) ptext = '<font size=15><b>Assignments by Standard</b></font>' Story.append(Paragraph(ptext, styles["title"])) Story.append(Spacer(1, 10)) t = Table(standard_table) t.setStyle( t.setStyle( TableStyle([ ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('BACKGROUND', (0, 0), (0, -1), colors.lightgrey), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ]))) Story.append(t) #build PDF document and return it doc.build(Story) pdf = buff.getvalue() buff.close() return pdf
def reporte_pdf(request, pk): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="Reporte del proyecto.pdf"' # Create the PDF object, using the response object as its "file." p = canvas.Canvas(response) p.drawString(210, 800, "1 - Cantidad de Trabajos en curso por equipo.") proyecto = Proyecto.objects.get(pk=pk) j=750 p.setFillColorRGB(0,0,0) p.setFont('Helvetica', 8) p.drawString(100, j, proyecto.nombre + ': ' + 'Estado ' + proyecto.estado) equipo = Miembro.objects.filter(proyecto=proyecto.pk) sprints = Sprint.objects.filter(proyecto = proyecto.pk).filter(estado=2) j = j-20 for sp in sprints: user_story = us.objects.filter(sprint = sp.pk) p.drawString(120, j, sp.nombre) j = j-20 for eq in equipo: p.drawString(140, j, '* ' + eq.usuario.username) j=j-20 for hu in user_story: if hu.responsable.usuario.username == eq.usuario.username: p.drawString(160, j, '- ' + hu.nombre) j=j-20 p.showPage() # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. miembros = Miembro.objects.filter(proyecto = proyecto.pk) #son los user stories que estan en el proyecto actual del cual se genera el reporte, de cada uno de los #sprint en uno de los tres estados (pendiente, en ejecucion o finalizado) p.drawString(200, 800, "2 - Cantidad de Trabajos por usuario, pendiente, en curso y finalizado.") j=750 for usuario_system in miembros : p.setFont('Helvetica', 8) p.drawString(100, j, usuario_system.usuario.username) user_story = us.objects.filter(responsable = usuario_system) j = j-20 for hu in user_story: sp = hu.sprint.pk p.drawString(120, j, '- ' + hu.nombre + ' Estado:' + hu.sprint.estado.estado) j=j-20 p.showPage() #son la actividades que se encuentran en cada flujo de un proyecto p.drawString(210, 800, "3 - Lista de Actividades para completar un proyecto.") j=750 fluj = Flujos.objects.filter(proyecto = proyecto.pk).order_by('nombre') j = j-20 for f in fluj: p.setFont('Helvetica', 8) p.drawString(120, j, f.nombre) acti = Actividad.objects.filter(flujo = f.pk).order_by('orden') j = j-20 for a in acti: p.drawString(140, j, str(a.orden) + ': ' + a.nombre) j = j-20 p.showPage() p.drawString(210, 800, "5 - Product BackLog del proyecto .") j=750 p.setFont('Helvetica', 8) user_story = us.objects.filter(proyecto = proyecto.pk).order_by('prioridad') j = j-20 p.drawString(120, j, 'Nombre del Us') p.drawString(200, j, ' Prioridad') j = j-20 for u in user_story: p.drawString(120, j, u.nombre + ' ' + str(u.prioridad)) j = j-20 p.showPage() p.drawString(210, 800, "6 - Sprint BackLog del proyecto .") j=750 p.setFont('Helvetica', 8) sprints = Sprint.objects.filter(proyecto = proyecto.pk).order_by('nombre') j = j-20 for s in sprints: p.drawString(120, j, s.nombre) user_story = us.objects.filter(sprint = s.pk) j = j-20 for hu in user_story: p.drawString(140, j, hu.nombre + ' RESPONSABLE: ' + hu.responsable.usuario.username) j = j-20 p.showPage() p.setFont('Helvetica', 8) #grafica del burndown chart del tiempo estimado y del tiempo real de todos los sprint del proyecto actual p.drawString(210, 800, "6 - Tiempo estimado y tiempo en curso, de cada sprint del proyecto, burndown chart") p.drawString(210, 800, "Burndown chart de los sprint del proyecto.") j=750 sprint = Sprint.objects.filter(proyecto=proyecto.pk) for s in sprint: p.setFont('Helvetica', 8) p.setFillColor(red) p.drawString(210, 760, "Tiempo Estimado.") p.setFillColor(green) p.drawString(280, 760,"Tiempo Real") p.setFillColor(black) sprint_dias = s.duracion_dias miembros = Miembro.objects.filter(proyecto=proyecto.pk) p.drawString(210,j,s.nombre + ': ' + s.estado.estado) j = j-20 horas_estimadas=0 for miembro in miembros: horas_estimadas+=miembro.horas_por_dia xdata =[i + 1 for i in range(sprint_dias)] ydataestimado= [horas_estimadas*(sprint_dias-i) for i in range(sprint_dias)] datose = [] dias = [] for ye in ydataestimado: datose.append(ye) if s.estado.pk == 2 or s.estado.pk == 3: try: ydata2real = generar_horas_trabajadas(s.pk, ydataestimado,horas_estimadas*s.duracion_dias) datosr = [] for yr in ydata2real: datosr.append(yr) data = [datose,datosr] except: data = [] else: data = [datose] drawing = Drawing(400, 200) for d in xdata: dias.append(str(d)) lc = HorizontalLineChart() lc.x = 50 lc.y = 50 lc.height = 200 lc.width = 400 lc.data = data lc.joinedLines = 1 lc.categoryAxis.categoryNames = dias lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = horas_estimadas*sprint_dias lc.valueAxis.valueStep = 10 lc.lines[0].strokeWidth = 1.5 lc.lines[1].strokeWidth = 1.5 drawing.add(lc) renderPDF.draw(drawing, p, 50, 500) p.showPage() p.showPage() p.save() return response
def tiempo_proyecto_grafica(request,id): proyecto=get_object_or_404(Proyecto,pk=id) timelines=TimeLine.objects.filter(userstory__proyecto=proyecto).order_by('fecha') listaDatos = omitirRepetidos(timelines) userstories = UserStory.objects.filter(proyecto=proyecto,estado_sprint="B") response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="informe.pdf"' p = canvas.Canvas(response) p.drawString(200, 800, proyecto.nombre) p.drawString(50, 780, "Tiempo estimado del proyecto: "+str(proyecto.total_horas())) p.drawString(350, 780, "Tiempo trabajo en el proyecto"+str(proyecto.total_horas()-proyecto.horas_faltantes())) p.drawString(50,760, "Grafico: horas restantes en funcion a dias") if listaDatos == []: p.showPage() p.save() return response '''GRAFICO 1''' drawing = Drawing(600, 300) datos = [] cat= [] for l in listaDatos: datos.append(l.horas_restantes_proyecto) cat.append(l.fecha.strftime('%m/%d/%Y')) data = [datos] lc = HorizontalLineChart() lc.x = 50 lc.y = 50 lc.height = 200 lc.width = 400 lc.data = data lc.joinedLines = 1 lc.categoryAxis.categoryNames = cat lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = proyecto.total_horas() lc.valueAxis.valueStep = 5 lc.lines[0].strokeWidth = 2 lc.lines[1].strokeWidth = 1.5 drawing.add(lc) renderPDF.draw(drawing, p, 50, 500) '''GRAFICO 2''' p.drawString(50,480, "Grafico: horas trabajadas en funcion a dias") drawing = Drawing(600, 300) datos = [] cat= [] for l in listaDatos: datos.append(l.horas) cat.append(l.fecha.strftime('%m/%d/%Y')) data = [datos] lc = HorizontalLineChart() lc.x = 50 lc.y = 50 lc.height = 200 lc.width = 400 lc.data = data lc.joinedLines = 1 lc.categoryAxis.categoryNames = cat lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = proyecto.total_horas()/2 lc.valueAxis.valueStep = 2 lc.lines[0].strokeWidth = 2 lc.lines[1].strokeWidth = 1.5 drawing.add(lc) renderPDF.draw(drawing, p, 50, 200) p.showPage() p.save() return response