def legend_draw(self, labels, chart, **kwargs): legend = Legend() chart_type = kwargs['type'] legend.fontName = 'FreeSans' legend.fontSize = 13 legend.strokeColor = None if 'x' in kwargs: legend.x = kwargs['x'] if 'y' in kwargs: legend.y = kwargs['y'] legend.alignment = 'right' if 'boxAnchor' in kwargs: legend.boxAnchor = kwargs['boxAnchor'] if 'columnMaximum' in kwargs: legend.columnMaximum = kwargs['columnMaximum'] # x-distance between neighbouring swatche\s legend.deltax = 0 lcolors = legendcolors if chart_type == 'line': lcolors = [colors.red, colors.blue] legend.colorNamePairs = zip(lcolors, labels) for i, color in enumerate(lcolors): if chart_type == 'line': chart.lines[i].fillColor = color elif chart_type == 'pie': chart.slices[i].fillColor = color elif chart_type == 'bar': chart.bars[i].fillColor = color return legend
def make_legend(self, drawing, chart): if not self.legend_labels: return # Get legend labels labels = self.get_legend_labels() # Legend object legend = Legend() legend.colorNamePairs = zip(self.colors[:len(labels)], labels) legend.columnMaximum = len(legend.colorNamePairs) legend.deltay = 5 legend.alignment = 'right' legend.x = drawing.width + 40 legend.y = drawing.height - (self.title and self.title.get('height', DEFAULT_TITLE_HEIGHT) or 0) # Sets legend extra attributes if legend_labels is a dictionary if isinstance(self.legend_labels, dict): for k,v in self.legend_labels.items(): if k != 'labels' and v: setattr(legend, k, v) drawing.add(legend) return legend
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 createReadsHistogram(self): ''' Routine to create histogram of numbers of 'reads' for given years ''' # The vertical bar chart will get added to the 'drawing' object drawing = Drawing(400, 200) # Now we can start constructing the vertical bar chart lc = VerticalBarChart() lc.x = 30 lc.y = 50 lc.height = 125 lc.width = 350 # Record the years, because these values will be used as x axis labels years = sorted(map(lambda b: int(b), filter(lambda a: a.isdigit(), self.data['reads histogram'].keys()))) # This list will hold the data points for the histogram lc.data = [] # Record the counts of both reads of refereed and non-refereed papers refereed = [] non_refereed = [] # The maximum number of reads will be used to scale the y axis max_reads = 0 # Take only the first two values of each value string in the histogram data # The first is for 'all' papers, the second for the 'refereed' papers for year in years: values = map(lambda a: int(a),self.data['reads histogram'][str(year)].split(':')[:2]) max_reads = max(max_reads,max(values)) refereed.append(values[1]) non_refereed.append(values[0]-values[1]) lc.data.append(refereed) lc.data.append(non_refereed) # Proper label placement for years: shift by (-6, -6) in x and y to have labels positioned properly lc.categoryAxis.labels.dx = -6 lc.categoryAxis.labels.dy = -6 # and rotate the labels by 90 degrees lc.categoryAxis.labels.angle = 90 # Define the value step and maximum for the y axis lc.valueAxis.valueMax = int(math.ceil(float(max_reads)/10.0))*10 lc.valueAxis.valueStep = max(int(math.floor(float(max_reads)/10.0)),1) lc.valueAxis.valueMin = 0 # The label names are the access years lc.categoryAxis.categoryNames = map(lambda a: str(a), years) # Now add the histogram to the 'drawing' object drawing.add(lc) # Add a legend to the histogram so that we now which color means what legend = Legend() legend.alignment = 'right' legend.x = 380 legend.y = 160 legend.deltax = 60 legend.dxTextSpace = 10 items = [(colors.red, 'refereed'), (colors.green, 'non-refereed')] legend.colorNamePairs = items drawing.add(legend, 'legend') # Finally add a title to the histogram drawing.add(String(200,190,"reads histogram", textAnchor="middle", fillColor='blue')) # Append the result to the 'story' self.story.append(drawing)
def myBarLegend(drawing, name1, name2): "Add sample swatches to a diagram." d = drawing or Drawing(400, 200) swatches = Legend() swatches.alignment = 'right' swatches.x = 80 swatches.y = 160 swatches.deltax = 60 swatches.dxTextSpace = 10 swatches.columnMaximum = 4 items = [(colors.blue, name1), (colors.lightblue, name2)] swatches.colorNamePairs = items d.add(swatches, 'legend') return d
def setLegend(self): legend = Legend() legend.colorNamePairs = [] legend.fontName = 'Helvetica-Bold' legend.fontSize = 12 legend.x = 100 legend.y = 110 legend.dxTextSpace = 5 legend.dy = 20 legend.dx = 20 legend.deltay = 5 legend.deltax = 7 legend.columnMaximum = 1 legend.alignment ='right' self.add(legend, name='Legend')
def sample1c(): "Make sample legend." d = Drawing(200, 100) legend = Legend() legend.alignment = 'right' legend.x = 0 legend.y = 100 legend.dxTextSpace = 5 items = 'red green blue yellow pink black white'.split() items = [(getattr(colors, i), i) for i in items] legend.colorNamePairs = items d.add(legend, 'legend') return d
def sample3(drawing=None): "Add sample swatches to a diagram." d = drawing or Drawing(400, 200) swatches = Legend() swatches.alignment = 'right' swatches.x = 80 swatches.y = 160 swatches.deltax = 60 swatches.dxTextSpace = 10 swatches.columnMaximum = 4 items = [(colors.red, 'before'), (colors.green, 'after')] swatches.colorNamePairs = items d.add(swatches, 'legend') return d
def create_pie_chart(self, data_list, label_list, user_color=None): label_list = map(lambda item: item.upper(), label_list) data = [(item / (sum(data_list) * 1.0)) * 100 for item in data_list] if user_color != None: usage_color = user_color else: random_range = [randint(0, 100) for i in range(len(data_list))] usage_color = map( lambda item: PCMYKColor(randint(0, item), randint(0, item), randint(0, item), randint(0, item)), random_range) print user_color d = Drawing() pie = Pie() pie.x = 200 pie.y = 85 pie.data = data pie.labels = label_list for i, color in enumerate(usage_color): pie.slices[i].fillColor = color pie.slices.strokeWidth = 0.5 pie.slices.popout = 1.5 pie._seriesCount = 3 pie.sideLabels = 1 legend = Legend() legend.alignment = 'right' legend.x = 0 legend.y = 75 legend.colorNamePairs = [ (z, (x, ' {val:.2f}%'.format(val=y))) for x, y, z in zip(pie.labels, data, usage_color) ] d.add(legend) d.add(pie) self.flowables.append(d)
def sample2c(): "Make sample legend." d = Drawing(200, 100) legend = Legend() legend.alignment = 'right' legend.x = 20 legend.y = 90 legend.deltax = 60 legend.dxTextSpace = 10 legend.columnMaximum = 4 items = 'red green blue yellow pink black white'.split() items = [(getattr(colors, i), i) for i in items] legend.colorNamePairs = items d.add(legend, 'legend') return d
def autoLegender(chart, title='', width=448, height=230, order='off', categories=[], use_colors=[]): d = Drawing(width, height) d.add(chart) lab = Label() lab.x = width / 2 #x和y是title文字的位置坐标 lab.y = 21 / 23 * height lab.fontName = 'song' #增加对中文字体的支持 lab.fontSize = 20 lab.setText(title) d.add(lab) #颜色图例说明等 if categories != [] and use_colors != []: leg = Legend() leg.x = 500 # 说明的x轴坐标 leg.y = 0 # 说明的y轴坐标 leg.boxAnchor = 'se' # leg.strokeWidth = 4 leg.strokeColor = None leg.subCols[1].align = 'right' leg.columnMaximum = 10 # 图例说明一列最多显示的个数 leg.fontName = 'song' leg.alignment = 'right' leg.colorNamePairs = list(zip(use_colors, tuple(categories))) d.add(leg) if order == 'on': d.background = Rect(0, 0, width, height, strokeWidth=1, strokeColor="#868686", fillColor=None) #边框颜色 return d
def sample1barline( data=[(100, 110, 120, 130), (70, 25, 85, 30), (63, 75, 51, 92), (51, 21, 66, 71), (10, 11, 90, 30)], seriesOrder=[[0, 3, 1], [4], [2]], lines=[3, 4], cAStyle='mixed', ): d = Drawing(400, 250) chart = VerticalBarChart() d.add(chart, name='chart') leg = Legend() d.add(leg, name='leg') chart.bars.strokeColor = None chart.bars[2].fillColor = colors.blue chart.bars[3].fillColor = colors.orange chart.bars[4].fillColor = colors.black #yellow chart.bars[4].strokeWidth = 3 chart.bars[4].symbol = makeMarker('FilledDiamond', size=10, fillColor=colors.red) chart.barSpacing = 1 chart.categoryAxis.style = cAStyle chart.data = data chart.x = 20 chart.y = 70 chart.height = d.height - chart.y - 10 chart.valueAxis.forceZero = True chart.width = d.width - chart.x - 10 for i in lines: chart.bars[i].isLine = 1 for i in lines: chart.bars[i].strokeWidth = 2 leg.colorNamePairs = Auto(chart=chart) leg.x = d.width / 2 leg.y = 5 leg.boxAnchor = 's' leg.columnMaximum = 1 leg.alignment = 'right' return d
def setLegend(self): legend = Legend() legend.colorNamePairs = [] legend.fontName = 'Helvetica-Bold' legend.fontSize = 12 legend.x = 100 legend.y = 110 legend.dxTextSpace = 5 legend.dy = 20 legend.dx = 20 legend.deltay = 5 legend.deltax = 7 legend.columnMaximum = 1 legend.alignment ='right' legend.x = 60 legend.y = 50 legend.columnMaximum = 2 legend.colorNamePairs = [] legend.colorNamePairs.append((colors.green, self._data_dict['max_score_legend'])) legend.colorNamePairs.append((colors.red, self._data_dict['score_legend'])) self.add(legend, name='Legend')
def draw_legend(self, name_pairs): legend = Legend() legend.colorNamePairs = name_pairs fontName = 'Helvetica' fontSize = 7 legend.fontName = fontName legend.fontSize = fontSize legend.alignment = 'right' legend.dxTextSpace = 7 legend.boxAnchor = 'nw' legend.subCols.dx = 0 legend.subCols.dy = -2 legend.subCols.rpad = 0 legend.columnMaximum = len(name_pairs) legend.deltax = 1 legend.deltay = 0 legend.dy = 5 legend.dx = 5 radius = self.track_radii[self.current_track_level][1] legend.x = self.xcenter - radius / 4 legend.y = self.ycenter + radius / 4 * 3 self.drawing.add(legend)
def draw_bar(bar_data=[], ax=[], items=[], limit_step=(100, 10), draw_weight=500, draw_height=250): drawing = Drawing(draw_weight, draw_height) bc = VerticalBarChart() bc.x = 35 bc.y = 100 bc.height = 120 bc.width = 350 bc.data = bar_data bc.strokeColor = Config_Charts.chose_colors[15] bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = limit_step[0] bc.valueAxis.valueStep = limit_step[1] bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -10 bc.categoryAxis.labels.angle = 20 bc.categoryAxis.categoryNames = ax bc.bars.strokeColor = Config_Charts.chose_colors[148] for index, item in enumerate(items): bc.bars[index].fillColor = item[0] # 图示 leg = Legend() leg.fontName = Config_Charts.typeface leg.alignment = 'right' leg.boxAnchor = 'ne' leg.x = 465 leg.y = 220 leg.dxTextSpace = 0 leg.columnMaximum = 10 leg.colorNamePairs = items drawing.add(leg) drawing.add(bc) return drawing
def draw_bar(bar_data=[], ax=[], items=[]): drawing = Drawing(600, 250) bc = VerticalBarChart() bc.x = 35 bc.y = 100 bc.height = 120 bc.width = 350 bc.data = bar_data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 100 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -10 bc.categoryAxis.labels.angle = 20 bc.categoryAxis.categoryNames = ax # 图示 leg = Legend() leg.fontName = 'SimSun' leg.alignment = 'right' leg.boxAnchor = 'ne' leg.x = 505 leg.y = 220 leg.dxTextSpace = 10 leg.columnMaximum = 4 leg.colorNamePairs = items drawing.add(leg) drawing.add(bc) return drawing
def draw_line(line_data=[], ax=[], items=[], limit_step=(100, 10), draw_weight=500, draw_height=150): drawing = Drawing(draw_weight, draw_height) lc = SampleHorizontalLineChart() lc.x = 35 lc.y = 100 lc.height = 120 lc.width = 350 lc.data = line_data lc.strokeColor = Config_Charts.chose_colors[15] lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = limit_step[0] lc.valueAxis.valueStep = limit_step[1] lc.categoryAxis.labels.dx = 8 lc.categoryAxis.labels.dy = -10 lc.categoryAxis.labels.angle = 20 lc.categoryAxis.categoryNames = ax for index, item in enumerate(items): lc.lines[index].strokeColor = item[0] # 图示 leg = Legend() leg.fontName = Config_Charts.typeface leg.alignment = 'right' leg.boxAnchor = 'ne' leg.x = 465 leg.y = 200 leg.dxTextSpace = 0 leg.columnMaximum = 10 leg.colorNamePairs = items drawing.add(leg) drawing.add(lc) return drawing
for i in range(len(names)): lp.lines[i].strokeColor = self.Color[i] legend = Legend() legend.x = 0 legend.y = h - 30 legend.boxAnchor = 'sw' legend.colorNamePairs = [(self.Color[i], names[i]) for i in range(len(names))] legend.fontName = 'Helvetica' legend.fontSize = 8 legend.dxTextSpace = 5 legend.dy = 5 legend.dx = 5 legend.deltay = 5 legend.alignment ='right' drawing.add(lp) drawing.add(legend) if title != None: label = Label() label.x = w label.y = h - 25 label.boxAnchor = 'se' label.fontName = 'Helvetica' label.fontSize = 10 label.setText(title) drawing.add(label) return drawing
def xerar_pieChart_serv(self): """ Xera unha gráfica circular co número de empregados por servizo, obtidos da base de datos :return: """ from reportlab.graphics.charts.piecharts import Pie from reportlab.graphics.charts.legends import Legend styles = getSampleStyleSheet() ptext = Paragraph('Número de empregados por tipo de servizo:', styles['Heading1']) self.story.append(ptext) d = Drawing(300, 200) pc = Pie() pc.x = 65 pc.y = 12 pc.width = 170 pc.height = 170 pc.labels = [ 'Mantemento', 'Administración', 'Investigación de mercados', 'Contabilidade', 'Programación', 'Vendas', 'Soporte técnico', 'Desarrollo', 'Distribución', 'Dirección de empresas', 'Recursos humanos' ] pc.data = [ row for row in self.cursor.execute( """SELECT (SELECT nempregados FROM servizos WHERE (nom_serv = 'mantemento')) AS man, (SELECT nempregados FROM servizos WHERE (nom_serv = 'administracion')) AS adm, (SELECT nempregados FROM servizos WHERE (nom_serv = 'investigacion de mercados')) AS inv, (SELECT nempregados FROM servizos WHERE (nom_serv = 'contabilidade')) AS cont, (SELECT nempregados FROM servizos WHERE (nom_serv = 'programacion')) AS prog, (SELECT nempregados FROM servizos WHERE (nom_serv = 'vendas')) AS vendas, (SELECT nempregados FROM servizos WHERE (nom_serv = 'soporte tecnico')) AS sop, (SELECT nempregados FROM servizos WHERE (nom_serv = 'desarrollo')) AS des, (SELECT nempregados FROM servizos WHERE (nom_serv = 'distribucion')) AS dist, (SELECT nempregados FROM servizos WHERE (nom_serv = 'direccion de empresas')) AS dir, (SELECT nempregados FROM servizos WHERE (nom_serv = 'recursos humanos')) FROM servizos AS rh """).fetchone() ] pc.slices.strokeWidth = 0.5 pc.slices[2].popout = 10 pc.slices[2].strokeWidth = 2 pc.slices[2].strokeDashArray = [2, 2] pc.slices[2].labelRadius = 1.75 pc.slices[2].fontColor = colors.purple pc.sideLabels = 1 # Con 0 no se muestran líneas hacia las etiquetas # Insertamos la leyenda legend = Legend() legend.x = 370 legend.y = 0 legend.dx = 8 legend.dy = 8 legend.fontName = 'Helvetica' legend.fontSize = 7 legend.boxAnchor = 'n' legend.columnMaximum = 10 legend.strokeWidth = 1 legend.strokeColor = colors.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 # Insertemos nuestros propios colores colores = [ colors.darkblue, colors.cyan, colors.purple, colors.magenta, colors.pink, colors.lightgreen, colors.coral, colors.crimson, colors.darkgreen, colors.darkorange, colors.lavender ] for i, color in enumerate(colores): pc.slices[i].fillColor = color legend.colorNamePairs = [(pc.slices[i].fillColor, (pc.labels[i][0:20], '%0.2f' % pc.data[i])) for i in range(len(pc.data))] d.add(pc) d.add(legend) self.story.append(d) self.story.append(Spacer(0, 110))
# Add data to chart chart.data = prices chart.categoryAxis.categoryNames = categories # Add labels to chart chart.barLabelFormat = '$%.2f' # Text to display on label - 2 decimal float chart.barLabels.nudge = 8 # Nudge labels upwards by 8px # ------- Create legend ------- legend = Legend() # Create the legend legend.boxAnchor = 'sw' # Set anchor to bottom-left legend.x = 50 # Shift legend right to bring in line with chart legend.y = 50 # Shift legend up by 50px legend.alignment = 'right' # Put labels to the right of color icons # Set legend colors legend.colorNamePairs = [(colors[i], '{} '.format(labels[i])) for i in range(len(colors))] # Add chart and legend to drawing d.add(chart) d.add(legend) # Export as test_img.png d.save(fnRoot='test_img', formats=['png']) #--------------------------------# # Opening an image from disk #
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 create_single_grade_pdf(grade,content_area_id): '''--Variables--''' school_level = [] Story=[] Elements=[] contentarea_name = "" buff = StringIO() formatted_time = time.ctime() minimum = 100 standard_averages=[[]] standard_table=[] content_areas = [] '''------''' styles = getSampleStyleSheet() HeaderStyle = styles["Heading1"] #get the Content Area Name query = ((content_area_id == db.contentarea.id)) results = db(query).select(db.contentarea.name) for row in results: contentarea_name = row.name #Create the name for the PDf being returned pdfName = "Grade_"+str(grade)+"_"+contentarea_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, 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>Administrator</b></font>' Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) #Grade Number and Content Area ptext = '<font size=12><b>Grade %s %s Standards Report</b></font>'%(grade, contentarea_name) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 7)) Elements.extend(ptext) Story.append(Spacer(1,40)) #Graph Title ptext = '<font size=15><b>Standards Progress</b></font>' Story.append(Paragraph(ptext, styles["title"])) i = 0 #get all the standards for a specific grade and content area standard_query = standard_query = ((db.classes.grade_level == grade)& (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)& (db.contentarea.id == content_area_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 = {} 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] standard_table = [] standard_averages=[[]] #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 standard_table[i].append(standard_dict[standard][3]+": "+format((standard_dict[standard][1]/standard_dict[standard][0])*100,'.2f')+"%") standard_averages[0].append(int(round((standard_dict[standard][1]/standard_dict[standard][0])*100))) 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 = '%0.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) #build PDF document and return it doc.build(Story) pdf = buff.getvalue() buff.close() return pdf
def run(self): def weight_sort(a, b): return cmp(a.getWeight(), b.getWeight()) drawing = Drawing(600, 300) lc = LinePlot() # Determine axis dimensions and create data set maxval = 0 minval = 0 dimension_one_values = [] dimension_two_values = [] dimension_one_answeroptions_as_objects = [] dimension_two_answeroptions_as_objects = [] counter = 0 for question in self.getQuestions(): weights = [int(weight) for weight in question.getAnswerOptionsWeights()] answeroptions = list(question.getAnswerOptions()) # This is used by the legend. Sort on weight. if counter == 0: dimension_one_answeroptions_as_objects = question.getAnswerOptionsAsObjects() dimension_one_answeroptions_as_objects.sort(weight_sort) else: dimension_two_answeroptions_as_objects = question.getAnswerOptionsAsObjects() dimension_two_answeroptions_as_objects.sort(weight_sort) # Minmax lmin = min(weights) lmax = max(weights) if lmin < minval: minval = lmin if lmax > maxval: maxval = lmax # Data for user, answer in question.answers.items(): value = answer.get('value', None) weight = None if value is not None: # Lookup the integer weight of this answer if value in answeroptions: index = answeroptions.index(value) weight = weights[index] # Always add to the list. ReportLab deals with None. if counter == 0: dimension_one_values.append(weight) else: dimension_two_values.append(weight) counter += 1 # Set minmax absmax = max(abs(minval), abs(maxval)) * 1.1 lc.xValueAxis.valueMin = -absmax lc.xValueAxis.valueMax = absmax lc.yValueAxis.valueMin = -absmax lc.yValueAxis.valueMax = absmax # Zip to create data data = [zip(dimension_one_values, dimension_two_values)] if not len(data[0]): return lc.x = 0 lc.y = 0 # Misc setup lc.height = 300 lc.width = 300 lc.data = data lc.joinedLines = 0 lc.fillColor = None lc.lines[0].strokeColor = colors.red lc.lines[0].symbol = makeMarker('FilledCircle') # Add a grid grid = DoubleGrid() lc.background = grid setupGrid(lc) lc.background = None # Finetune the grid grid.grid0.strokeWidth = 0.2 grid.grid1.strokeWidth = 0.2 # Add to drawing else it overwrites the center Y axis drawing.add(grid) # Add a Y axis to pass through the origin yaxis = YValueAxis() yaxis.setPosition(lc.width/2, 0, lc.height) yaxis.configure([(0,-absmax),(0,absmax)]) yaxis.strokeColor = colors.blue drawing.add(yaxis) # Color X-Axis lc.xValueAxis.strokeColor = colors.green drawing.add(lc) # Legend for Dimension One drawing.add(String(lc.width+20, lc.height-12, 'Dimension One (X-Axis):', fontName='Helvetica', fontSize=12, fillColor=colors.green)) legend = Legend() legend.alignment = 'right' legend.x = lc.width + 20 legend.y = lc.height - 20 legend.fontName = 'Helvetica' legend.fontSize = 12 legend.columnMaximum = 7 items = [] for ob in dimension_one_answeroptions_as_objects: items.append( ( StringWidget(ob.getWeight()), ob() ) ) legend.colorNamePairs = items drawing.add(legend, 'legend1') # Legend for Dimension Two drawing.add(String(lc.width+20, lc.height/2-12, 'Dimension Two (Y-Axis):', fontName='Helvetica', fontSize=12, fillColor=colors.blue)) legend = Legend() legend.alignment = 'right' legend.x = lc.width + 20 legend.y = lc.height/2 - 20 legend.fontName = 'Helvetica' legend.fontSize = 12 legend.columnMaximum = 7 items = [] for ob in dimension_two_answeroptions_as_objects: items.append( ( StringWidget(ob.getWeight()), ob() ) ) legend.colorNamePairs = items drawing.add(legend, 'legend2') # Write out data = drawing.asString('png') request = self.REQUEST response = request.RESPONSE response.setHeader('Content-Type', 'image/png') response.setHeader('Content-Disposition','inline; filename=%s.png' % self.getId()) response.setHeader('Content-Length', len(data)) response.setHeader('Cache-Control', 's-maxage=0') return data
def createCitationHistogram(self): ''' Routine to create a histogram of citations: 1. refereed papers to refereed papers 2. refereed papers to non-refereed papers 3. non-refereed papers to refereed papers 4. non-refereed papers to non-refereed papers (where 'to X' means 'to the papers of type X in the publication set, used to generate the metrics) ''' # The vertical bar chart will get added to the 'drawing' object drawing = Drawing(400, 200) # Now we can start constructing the vertical bar chart lc = VerticalBarChart() lc.x = 30 lc.y = 50 lc.height = 125 lc.width = 350 # Record the publication years, because these values will be used as x axis labels years = sorted(map(lambda b: int(b), filter(lambda a: a.isdigit(), self.data['citation histogram'].keys()))) # This list will hold the data points for the histogram lc.data = [] # Record the counts for the 4 different types of citations ref_ref = [] ref_non = [] non_ref = [] non_non = [] # The maximum number of citations will be used to scale the y axis max_citations = 0 # Take only the first four values of each value string in the histogram data for year in years: values = map(lambda a: int(a),self.data['citation histogram'][str(year)].split(':')[:4]) all2all = values[0] all2ref = values[2] ref2ref = values[3] ref2all = values[1] all2non = all2all - all2ref ref2non = ref2all - ref2ref non2all = all2all - ref2all non2ref = all2ref - ref2ref non2non = non2all - non2ref ref_ref.append(ref2ref) ref_non.append(ref2non) non_ref.append(non2ref) non_non.append(non2non) max_citations = max(max_citations,ref2ref,ref2non,non2ref,non2non) lc.data.append(ref_ref) lc.data.append(ref_non) lc.data.append(non_ref) lc.data.append(non_non) # If there are no citations, just omit this histogram: if max_citations == 0: return # Proper label placement for years: shift by (-6, -6) in x and y to have labels positioned properly lc.categoryAxis.labels.dx = -6 lc.categoryAxis.labels.dy = -6 # and rotate the labels by 90 degrees lc.categoryAxis.labels.angle = 90 # The label names are the publication years lc.categoryAxis.categoryNames = map(lambda a: str(a), years) # Define the colors for the various bars lc.bars[0].fillColor = colors.red lc.bars[1].fillColor = colors.green lc.bars[2].fillColor = colors.blue lc.bars[3].fillColor = colors.orange # Define the value step and maximum for the y axis lc.valueAxis.valueMax = int(math.ceil(float(max_citations)/10.0))*10 lc.valueAxis.valueStep = max(int(math.floor(float(max_citations)/10.0)),1) # Now add the histogram to the 'drawing' object drawing.add(lc) # Add a legend to the histogram so that we now which color means what legend = Legend() legend.alignment = 'right' legend.x = 380 legend.y = 160 legend.deltax = 60 legend.dxTextSpace = 10 legend.columnMaximum = 6 items = [(colors.red, 'refereed to refereed'), (colors.green, 'refereed to non-refereed'),(colors.blue, 'non-refereed to refereed'),(colors.orange, 'non-refereed to non-refereed')] legend.colorNamePairs = items drawing.add(legend, 'legend') # Finally add a title to the histogram drawing.add(String(200,190,"citation histogram", textAnchor="middle", fillColor='blue')) # Append the result to the 'story' self.story.append(drawing)
for i in range(len(names)): lp.lines[i].strokeColor = self.Color[i] legend = Legend() legend.x = 0 legend.y = h - 30 legend.boxAnchor = 'sw' legend.colorNamePairs = [(self.Color[i], names[i]) for i in range(len(names))] legend.fontName = 'Helvetica' legend.fontSize = 8 legend.dxTextSpace = 5 legend.dy = 5 legend.dx = 5 legend.deltay = 5 legend.alignment = 'right' drawing.add(lp) drawing.add(legend) if title != None: label = Label() label.x = w label.y = h - 25 label.boxAnchor = 'se' label.fontName = 'Helvetica' label.fontSize = 10 label.setText(title) drawing.add(label) return drawing
def alpdf(mensaje): locale.getlocale() aux = mensaje.split('#') periodos = aux[0][2:-4].split(",") descriptores = aux [1][4:-2].split(",") #valor = int(descriptores[0]) #print("valor:",valor) #año = int(años_final[0][1:-1]) #print("descriptores: ",descriptores) #print("periodos ",periodos) doc = SimpleDocTemplate("SURALUM.pdf", pagesize=letter) story = [] imagen = Image(logotipo, 7 * cm, 3 * cm) story.append(imagen) story.append(Spacer(10, 20)) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) if (int(descriptores[0])):#VENTAS TOTALES print("ventas_totales") story.append(Paragraph('Ventas Totales por Año', styles['title'])) totales = [] connection_ddbb = cx_Oracle.connect(usr, passw, "localhost") cursor = connection_ddbb.cursor() for i in periodos: print() cursor = connection_ddbb.cursor() cursor.execute("SELECT id_venta, total, fecha FROM ventas WHERE EXTRACT(YEAR FROM fecha) = " + i) total = 0 for fname in cursor: total = total+ fname[1] #print ("Values:", fname[1]) totales.append(total) arreglo = [periodos,totales] table = Table(arreglo, colWidths=4* cm) table.setStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER')]) for index, row in enumerate(arreglo): ini, fin = (0, index), (len(row)-1, index) table.setStyle([ ("BOX", ini, fin, 0.25, colors.black), ('INNERGRID', ini, fin, 0.25, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.gray) ]) story.append(table) d = Drawing(300, 200) data = [totales] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 400 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 1000000000 bc.valueAxis.valueStep = 100000000 #paso de distancia entre punto y punto bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 0 bc.categoryAxis.categoryNames = periodos bc.groupSpacing = 10 bc.barSpacing = 4 bc.barLabelFormat = '$%d' bc.valueAxis.labelTextFormat = ' $%d ' bc.barLabels.nudge = 7 d.add(bc) #pprint.pprint(bc.getProperties()) story.append(d) #print(story) ############################################################################################################################################################# if (int(descriptores[2][1:])): print("ventas por familia") story.append(Paragraph('Ventas por Familia', styles['title'])) connection_ddbb = cx_Oracle.connect(usr, passw, "localhost") cursor = connection_ddbb.cursor() totales = [('Periodo','Suralum','Huracan','Industrial')] valores_g = [] for i in periodos: cursor.execute("""SELECT productos.id_familia, SUM(venta_productos.cantidad * venta_productos.precio) as c FROM venta_productos INNER JOIN productos ON venta_productos.id_producto = productos.id_producto JOIN ventas ON venta_productos.id_venta=ventas.id_venta WHERE EXTRACT(YEAR FROM ventas.fecha) = """+i+"""AND(productos.id_familia=1 OR productos.id_familia=2 OR productos.id_familia=3) GROUP BY productos.id_familia ORDER BY productos.id_familia DESC """) vt=[(i)] vg =[] for valor in cursor: #print ("Values:", valor) vt.append(valor[1]) vg.append(valor[1]) #print(vt) totales.append(vt) valores_g.append(vg) table = Table(totales, colWidths=4*cm) table.setStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER')]) for index, row in enumerate(totales): ini, fin = (0, index), (len(row)-1, index) table.setStyle([ ("BOX", ini, fin, 0.25, colors.black), ('INNERGRID', ini, fin, 0.25, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.gray), ('BACKGROUND', (0, 0), (0,-1), colors.gray) ]) story.append(table) d = Drawing(600, 200) data = valores_g bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 400 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 500000000 bc.valueAxis.valueStep = 100000000 #paso de distancia entre punto y punto bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 0 bc.categoryAxis.categoryNames = ('Suralum','Huracan','Industrial') bc.valueAxis.labelTextFormat = ' $%d ' bc.groupSpacing = 10 bc.barSpacing = 4 bc.barLabelFormat = '$%d' bc.barLabels.nudge = 7 legend=Legend() legend.x = 20 legend.y = 0 legend.boxAnchor = 'se' legend.subCols[1].align = 'right' legend.alignment = 'right' legend.columnMaximum = 9 legend.fontSize = 13 # these data can be read from external sources legend.colorNamePairs=Auto(obj=bc) d.add(bc) d.add(legend) #pprint.pprint(bc.getProperties()) story.append(d) #print(totales) if (int(descriptores[3][1:])): print("Suralum") story.append(Paragraph('Ventas Suralum', styles['title'])) connection_ddbb = cx_Oracle.connect(usr, passw, "localhost") cursor = connection_ddbb.cursor() for i in periodos: #print("para el periodo:",i) cursor.execute("""SELECT productos.descripcion, SUM(venta_productos.cantidad) as v, SUM(venta_productos.cantidad * venta_productos.precio) as c FROM venta_productos JOIN productos ON venta_productos.id_producto = productos.id_producto JOIN ventas ON venta_productos.id_venta=ventas.id_venta WHERE EXTRACT(YEAR FROM ventas.fecha) = """+i+"""AND productos.id_familia=1 GROUP BY productos.descripcion ORDER BY v DESC""") #AGREGAR TITULO DEL PERIODO AL STORY PARA SEPARAR LAS TABLAS story.append(Paragraph('Año:'+i, styles['Center'])) k= 0 totales = [] totales.append(head) for valor in cursor: producto = [] if (k < 12): producto.append(valor[0])#nombre producto.append(valor[1])#totales_ccantidad producto.append(valor[2])#totales_ventas totales.append(producto) k = k+1 table = Table(totales, colWidths=4*cm) table.setStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER')]) for index, row in enumerate(totales): bg_color = colors.green ini, fin = (0, index), (len(row)-1, index) table.setStyle([ ("BOX", ini, fin, 0.25, colors.black), ('INNERGRID', ini, fin, 0.25, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.gray) ]) story.append(Spacer(10, 20)) story.append(table) story.append(Spacer(10, 20)) ############################################################################################################################ if (int(descriptores[4][1:])): print("Huracan") story.append(Paragraph('Ventas Huracan', styles['title'])) connection_ddbb = cx_Oracle.connect(usr, passw, "localhost") cursor = connection_ddbb.cursor() for i in periodos: #print("para el periodo:",i) cursor.execute("""SELECT productos.descripcion, SUM(venta_productos.cantidad) as v, SUM(venta_productos.cantidad * venta_productos.precio) as c FROM venta_productos JOIN productos ON venta_productos.id_producto = productos.id_producto JOIN ventas ON venta_productos.id_venta=ventas.id_venta WHERE EXTRACT(YEAR FROM ventas.fecha) = """+i+"""AND productos.id_familia=2 GROUP BY productos.descripcion ORDER BY v DESC""") #AGREGAR TITULO DEL PERIODO AL STORY PARA SEPARAR LAS TABLAS story.append(Paragraph('Año:'+i, styles['Center'])) k= 0 totales = [] totales.append(head) for valor in cursor: producto = [] if (k < 12): producto.append(valor[0])#nombre producto.append(valor[1])#totales_ccantidad producto.append(valor[2])#totales_ventas totales.append(producto) k = k+1 table = Table(totales, colWidths=4*cm) table.setStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER')]) for index, row in enumerate(totales): bg_color = colors.violet ini, fin = (0, index), (len(row)-1, index) table.setStyle([ ("BOX", ini, fin, 0.25, colors.black), ('INNERGRID', ini, fin, 0.25, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.gray) ]) story.append(Spacer(10, 20)) story.append(table) story.append(Spacer(10, 20)) ####################################################################################################################################### if (int(descriptores[5][1:])): print("Industrial") story.append(Paragraph('Ventas Industrial', styles['title'])) connection_ddbb = cx_Oracle.connect(usr, passw, "localhost") cursor = connection_ddbb.cursor() for i in periodos: #print("para el periodo:",i) cursor.execute("""SELECT productos.descripcion, SUM(venta_productos.cantidad) as v, SUM(venta_productos.cantidad * venta_productos.precio) as c FROM venta_productos JOIN productos ON venta_productos.id_producto = productos.id_producto JOIN ventas ON venta_productos.id_venta=ventas.id_venta WHERE EXTRACT(YEAR FROM ventas.fecha) = """+i+"""AND productos.id_familia=3 GROUP BY productos.descripcion ORDER BY v DESC""") #AGREGAR TITULO DEL PERIODO AL STORY PARA SEPARAR LAS TABLAS story.append(Paragraph('Año:'+i, styles['Center'])) k= 0 totales = [] totales.append(head) for valor in cursor: producto = [] if (k < 12): producto.append(valor[0])#nombre producto.append(valor[1])#totales_ccantidad producto.append(valor[2])#totales_ventas totales.append(producto) k = k+1 table = Table(totales, colWidths=4*cm) table.setStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER')]) for index, row in enumerate(totales): bg_color = colors.aqua ini, fin = (0, index), (len(row)-1, index) table.setStyle([ ("BOX", ini, fin, 0.25, colors.black), ('INNERGRID', ini, fin, 0.25, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.gray) ]) story.append(Spacer(10, 20)) story.append(table) story.append(Spacer(10, 20)) if (int(descriptores[6][1:])): print("mas vendido") story.append(Paragraph('PRODUCTOS MÁS VENDIDOS', styles['title'])) connection_ddbb = cx_Oracle.connect(usr, passw, "localhost") cursor = connection_ddbb.cursor() for i in periodos: cursor.execute("""SELECT productos.descripcion, SUM(venta_productos.cantidad) as v, SUM(venta_productos.cantidad * venta_productos.precio) as c FROM venta_productos JOIN productos ON venta_productos.id_producto = productos.id_producto JOIN ventas ON venta_productos.id_venta=ventas.id_venta WHERE EXTRACT(YEAR FROM ventas.fecha) = """+i+""" GROUP BY productos.descripcion ORDER BY v DESC""" ) story.append(Paragraph('Año:'+i, styles['Center'])) k= 0 totales = [] totales.append(head) for valor in cursor: producto = [] if (k < 20): producto.append(valor[0])#nombre producto.append(valor[1])#totales_ccantidad producto.append(valor[2])#totales_ventas #producto.append(valor[3])#familia totales.append(producto) k = k+1 table = Table(totales, colWidths=4*cm) table.setStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER')]) for index, row in enumerate(totales): bg_color = colors.aqua ini, fin = (0, index), (len(row)-1, index) table.setStyle([ ("BOX", ini, fin, 0.25, colors.black), ('INNERGRID', ini, fin, 0.25, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.gray) ]) story.append(Spacer(10, 20)) story.append(table) story.append(Spacer(10, 20)) doc.build(story)
def createBarGraph(c, x, y, data, labels, colors, barnames, minvalue, maxvalue, step, h=75, w=300, dy=0): """ Function to draw a Bar Graph """ drawing = Drawing(400, 200) legend = Legend() legend.columnMaximum = 99 legend.alignment = 'right' legend.dx = 7 legend.dy = 7 legend.dxTextSpace = 5 legend.deltay = 10 legend.strokeWidth = 0 legend.strokeColor = HexColor("0xffffff") legend.subCols[0].minWidth = 75 legend.subCols[0].align = 'left' legend.boxAnchor = 'c' legend.y = h + 25 legend.x = w + 110 legend.fontName = "MavenPro" legend.fontSize = 8.5 legendList = [] for k, i in enumerate(colors): legendList.append((HexColor(i), barnames[k])) legend.colorNamePairs = legendList bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = h # 75 bc.width = w # 300 bc.data = data bc.bars.strokeColor = HexColor("0xffffff") bc.valueAxis.labels.fontName = "MavenPro" bc.valueAxis.labels.fontSize = 8 bc.valueAxis.labels.dx = -10 bc.valueAxis.valueMin = minvalue bc.valueAxis.valueMax = maxvalue bc.valueAxis.valueStep = step bc.categoryAxis.labels.boxAnchor = 'n' bc.categoryAxis.labels.dx = 0 bc.categoryAxis.labels.dy = -10 - dy bc.categoryAxis.labels.angle = 0 bc.categoryAxis.labels.fontName = "MavenPro" bc.categoryAxis.labels.fontSize = 8 bc.categoryAxis.categoryNames = labels for k in xrange(len(colors)): bc.bars[k].fillColor = HexColor(colors[k]) #self.chart.bars[k].fillColor = HexColor(colors[k]) drawing.add(bc) drawing.add(legend, 'legend') drawing.drawOn(c, x, y)
renderPDF.draw(chartCanvas, c, 50, 400) pieChartCanvas = Drawing() pieChart = Pie() pieChart.data = [30.0, 21.0, 21.0, 14.0, 14.0] pieChart.slices[0].fillColor = PCMYKColor(100,0,90,50,alpha=85) pieChart.slices[1].fillColor = PCMYKColor(0,100,100,40,alpha=85) pieChart.slices[2].fillColor = PCMYKColor(100,60,0,50,alpha=85) pieChart.slices[3].fillColor = PCMYKColor(23,51,0,4,alpha=85) pieChart.slices[4].fillColor = PCMYKColor(66,13,0,22,alpha=85) pieChart.width = 100 pieChart.height = 100 pieChart.slices.popout = 5 pieChart.slices.strokeColor = PCMYKColor(0,0,0,0) pieChart.slices.strokeWidth = 0.5 pieChartCanvas.add(pieChart) renderPDF.draw(pieChartCanvas, c, 100, 100) pieChartLegendCanvas = Drawing() pieChartLegend = Legend() pieChartLegend.x = 100 pieChartLegend.y = 100 pieChartLegend.alignment = "right" pieChartLegend.columnMaximum = 5 pieChartLegend.colorNamePairs = [(PCMYKColor(100,0,90,50,alpha=100), ('BP', '30%')), (PCMYKColor(0,100,100,40,alpha=100), ('Shell Transport & Trading', '21%')), (PCMYKColor(100,60,0,50,alpha=100), ('Liberty International', '21%')), (PCMYKColor(23,51,0,4,alpha=100), ('Persimmon', '14%')), (PCMYKColor(66,13,0,22,alpha=100), ('Royal Bank of Scotland', '14%'))] pieChartLegendCanvas.add(pieChartLegend) renderPDF.draw(pieChartLegendCanvas, c, 100, 100) c.showPage() c.save()
def create_single_grade_pdf(grade, content_area_id): '''--Variables--''' school_level = [] Story = [] Elements = [] contentarea_name = "" buff = StringIO() formatted_time = time.ctime() minimum = 100 standard_averages = [[]] standard_table = [] content_areas = [] '''------''' styles = getSampleStyleSheet() HeaderStyle = styles["Heading1"] #get the Content Area Name query = ((content_area_id == db.contentarea.id)) results = db(query).select(db.contentarea.name) for row in results: contentarea_name = row.name #Create the name for the PDf being returned pdfName = "Grade_" + str(grade) + "_" + contentarea_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, 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>Administrator</b></font>' Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) #Grade Number and Content Area ptext = '<font size=12><b>Grade %s %s Standards Report</b></font>' % ( grade, contentarea_name) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 7)) Elements.extend(ptext) Story.append(Spacer(1, 40)) #Graph Title ptext = '<font size=15><b>Standards Progress</b></font>' Story.append(Paragraph(ptext, styles["title"])) i = 0 #get all the standards for a specific grade and content area standard_query = standard_query = ( (db.classes.grade_level == grade) & (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) & (db.contentarea.id == content_area_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 = {} 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 ] standard_table = [] standard_averages = [[]] #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 standard_table[i].append(standard_dict[standard][3] + ": " + format( (standard_dict[standard][1] / standard_dict[standard][0]) * 100, '.2f') + "%") standard_averages[0].append( int( round( (standard_dict[standard][1] / standard_dict[standard][0]) * 100))) 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 = '%0.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) #build PDF document and return it doc.build(Story) pdf = buff.getvalue() buff.close() return pdf
def line_chart(data, labels, **kw): """ :param data: contains a three dimensional array of values (list of lists of points) or just a list of datapoint lists (it will be auto-transposed to start at 0) :type data: list :param labels: can contain, but must not ["xlabel", "ylabel", ["data label0", ...]] third item can also be an interger stating the iteration start as label when of same size as data, then a legend is added instead :type lables: ??? :param xlim: limit the x axis to these values, e.g. (0, 100) :type xlim: Tuple(Number, Number) :param ylim: limit the y axis to these values, e.g. (0, 50) :type ylim: Tuple(Number, Number) :param size: size in pixels, e.g. (18*cm, 9*cm) :type size: Tuple(Number, Number) :param title: title of bar chart :type title: string :param lines: list of colors we should use to paint lines :type lines: list[???] :param markers: list of markers we should use to draw markers :type markers: list[`PDF_LINE_MARKERS`,...] :param scatter: weather to do a scatter plot or line chart :type scatter: boolean """ # Get all arguments from the keywordargs title = kw.pop('title', None) scatter = kw.pop('scatter', False) size = kw.pop('plotSize', (18 * cm, 9 * cm)) lines = kw.pop('lines', PDF_CHART_COLORS) markers = kw.pop('markers', PDF_LINE_MARKERS) xlim = kw.pop('xlim', None) ylim = kw.pop('ylim', None) drawing = Drawing(size[0], size[1]) chart = None if(scatter): chart = ScatterPlot() else: chart = LinePlot() for key, val in list(kw.items()): setattr(chart, key, val) if title is not None: drawing.add(String(20, size[1] - 10, title), name='title') chart.y -= 10 chart.width = drawing.width - 20 chart.height = drawing.height - 40 chart.x = 10 chart.y = 10 chart.data = data if type(data[0][0]) in (tuple, list) else [list(zip(list(range(len(i))), i)) for i in data] max_y = 0 min_y = maxsize for i in range(len(data)): chart.lines[i].strokeColor = HexColor(lines[i % len(lines)]) if markers is not None: chart.lines[i].symbol = makeMarker(markers[i % len(markers)]) chart.lines[i].symbol.size = 3 max_y = max([k[1] for k in chart.data[i]] + [max_y]) min_y = min([k[1] for k in chart.data[i]] + [min_y]) chart.yValueAxis.valueMax = max_y * 1.1 chart.yValueAxis.valueMin = min_y * 0.9 chart.xValueAxis.visibleGrid = True chart.yValueAxis.visibleGrid = True if xlim is not None: chart.xValueAxis.valueMin = xlim[0] chart.xValueAxis.valueMax = xlim[1] if ylim is not None: chart.yValueAxis.valueMin = ylim[0] chart.yValueAxis.valueMax = ylim[1] if scatter: chart.xLabel = '' chart.yLabel = '' chart.y -= 10 chart.lineLabelFormat = None if labels is not None: if len(labels) > 0: xlabel = Label() xlabel._text = labels[0] # pylint: disable=W0212 xlabel.textAnchor = 'middle' xlabel.x = drawing.width / 2 xlabel.y = 5 chart.y += 15 drawing.add(xlabel, name="xlabel") if len(labels) > 1: ylabel = Label() ylabel._text = labels[1] # pylint: disable=W0212 xlabel.textAnchor = 'middle' ylabel.angle = 90 ylabel.x = 0 ylabel.y = drawing.height / 2 chart.x += 12 drawing.add(ylabel, name="ylabel") if len(labels) > 2: # when labels are of same size as max nr of data point, use as x axis labels if len(labels[2]) == max([len(x) for x in data]): chart.categoryAxis.categoryNames = labels[2] # pylint: disable=E1101 chart.xValueAxis.labels.angle = 30 # pylint: disable=E1101 # otherwise when integer use the counter elif type(labels[2]) == int: temp = range(labels[2], max([len(x) for x in data]) + labels[2]) chart.categoryAxis.categoryNames = temp # pylint: disable=E1101 # or we could add a legend when of same size as data elif len(labels[2]) == len(data): legend = Legend() chart.height -= 8 chart.y += 8 xlabel.y += 8 legend.boxAnchor = 'sw' legend.x = chart.x + 8 legend.y = -2 legend.columnMaximum = 1 legend.deltax = 50 legend.deltay = 0 legend.dx = 10 legend.dy = 1.5 legend.fontSize = 7 legend.alignment = 'right' legend.dxTextSpace = 5 legend.colorNamePairs = [(HexColor(lines[i]), labels[2][i]) for i in range(len(chart.data))] legend.strokeWidth = 0 drawing.add(legend, name='legend') drawing.add(chart, name='chart') return drawing
def generar_pdf_busquedas_view(request): print "Genero el PDF" fecha_m = "" resultados=[] fecha_a = "" b=[] t=[] fecha_inicio = x fecha_final = y c=0 r=[] #story =[] response = HttpResponse(content_type='application/pdf') pdf_name = "reporte_busqueda.pdf" # llamado clientes # la linea 26 es por si deseas descargar el pdf a tu computadora response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name buff = BytesIO() doc = SimpleDocTemplate(buff, pagesize=letter, rightMargin=40, leftMargin=40, topMargin=60, bottomMargin=18, ) reportes = [] styles = getSampleStyleSheet() fichero_imagen="biblioteca/media/images/Reports-banner.jpg" imagen_logo=Image(os.path.realpath(fichero_imagen),width=400,height=100) reportes.append(imagen_logo) header = Paragraph("Fecha del reporte: "+str(date.today()), styles['Heading1']) header2 = Paragraph("Reporte de las busquedas realizadas entre la fecha "+str(fecha_inicio)+" hasta la fecha "+str(fecha_final) + "\n", styles['Normal']) salto_linea = Paragraph("\n\n", styles["Normal"]) reportes.append(header) reportes.append(header2) reportes.append(Spacer(1, 12)) headings = ('Busqueda', 'Resultado',)# 'Cantidad_Veces_Buscadas') lista=[] t = Busqueda.objects.all() b = Busqueda.objects.filter(fecha__range=(fecha_inicio, fecha_final)).values('busqueda', 'resultados').distinct() listar=[] for r in b: print "llllllllllllllllll",r,"\n" if r['resultados'] == False: r['resultados']="No se encontró" listar.append(r) else: r['resultados']="Se encontró" listar.append(r) print "lisygyujgyjgjhbjh", listar #GRAFICAS BARRA total_busquedas=Busqueda.objects.all().count() #TOTAL BUSQUEDAS si=Busqueda.objects.filter(resultados=True).count() #BUSUEDAS ENCONTRADAS (SI) no=total_busquedas-si #BUSQUEDAS NO ENCONTRADAS (NO) #GRAFICAS PASTEL for i in b: print "________________",i.get("busqueda") for j in t: print "===============",j.busqueda if j.busqueda == i.get("busqueda") and j.fecha >= fecha_inicio and j.fecha <= fecha_final: c = c + 1 print c lista.append(c) c=0 print lista , len(lista) li = zip(b,lista) ''' for i in b: print "________________",i.get("busqueda") for j in t: print "===============",j.busqueda if j.busqueda == i.get("busqueda"): c = c + 1 print c lista.append(c) c=0 li = zip(b,lista) ''' #allreportes = [ (i.busqueda, i.resultados) for i in Busqueda.objects.filter(fecha__range=(fecha_inicio, fecha_final)).values('busqueda', 'resultados').distinct()] # allreportes = [ i.values() for i in Busqueda.objects.filter(fecha__range=(fecha_inicio, fecha_final)).values('busqueda', 'resultados').distinct()] b=listar allreportes = [ i.values() for i in b] print allreportes t = Table([headings] + allreportes) t.setStyle(TableStyle( [ ('GRID', (0, 0), (3, -1), 1, colors.dodgerblue), ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue), ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue) ] )) #GRAFICA DE BARRAS titulo = Paragraph("Busquedas encontradas y no encontradas en el sistema", estilo['title']) drawing = Drawing(400, 200) data = [(si, no)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.bars[0].fillColor = colors.blue bc.bars[1].fillColor = colors.black bc.strokeColor = colors.black bc.fillColor = colors.silver bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = total_busquedas+30 try: r = total_busquedas/2 if type(r) == 'float': bc.valueAxis.valueStep = total_busquedas+0.5 if type(r) == 'int': bc.valueAxis.valueStep = r except: "Nos se puede" bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 0 bc.categoryAxis.categoryNames = ['Encontradas', 'No Encontradas'] drawing.add(bc) bc.barLabels.nudge = 20 bc.barLabelFormat = '%0.0f' bc.barLabels.dx = 0 bc.barLabels.dy = 0 bc.barLabels.boxAnchor = 'n' # irrelevant (becomes 'c') bc.barLabels.fontName = 'Helvetica' bc.barLabels.fontSize = 14 #GRAFICAS DE PASTEL titulo2 = Paragraph("Busquedas y número de veces realizadas", estilo['title']) d = Drawing(400, 200) pc = Pie() pc.x = 125 pc.y = 25 pc.data = lista print lista #pc.data = [7, 1, 1, 1, 1, 2] #pc.labels = [ str(i.values()) for i in Busqueda.objects.filter(fecha__range=(fecha_inicio, fecha_final)).values('busqueda').distinct()] lista_labels = [ str(i.values()) for i in Busqueda.objects.filter(fecha__range=(fecha_inicio, fecha_final)).values('busqueda').distinct()] #pc.labels = ['example1', 'example2', 'example3', 'example4', 'example5', 'example6'] pc.sideLabels = 1 pc.width = 150 pc.height = 150 pc.slices.strokeWidth=1#0.5 pc.slices[0].fillColor = colors.yellow 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 d.add(pc) legend = Legend() legend.x = 370 legend.y = 0 legend.dx = 10 legend.dy = 10 legend.fontName = 'Helvetica' legend.fontSize = 10 legend.boxAnchor = 'n' legend.columnMaximum = 10 legend.strokeWidth = 1 legend.strokeColor = colors.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 #Insertemos nuestros propios colores colores = [colors.blue, colors.red, colors.green, colors.yellow, colors.black, colors.white, colors.silver, colors.pink, colors.brown, colors.orange, colors.purple] for i, color in enumerate(colores): pc.slices[i].fillColor = color legend.colorNamePairs = [( pc.slices[i].fillColor, (lista_labels[i][0:200], '%0.0f' % pc.data[i]) ) for i in xrange(len(pc.data))] d.add(pc) reportes.append(t) reportes.append(Spacer(0, inch*.1)) reportes.append(Spacer(0, inch*.1)) reportes.append(Spacer(0, inch*.1)) reportes.append(titulo) reportes.append(drawing) reportes.append(Spacer(0, inch*.1)) reportes.append(Spacer(0, inch*.1)) reportes.append(titulo2) d.add(legend) reportes.append(d) doc.build(reportes) response.write(buff.getvalue()) buff.close() return response
def get_pdf_results(task_id): # Flask response response = Response() response.status_code = 200 task = data.get_task_result(task_id) #Saving file to a in-memory file output_file = StringIO.StringIO() def header_footer(canvas, doc): canvas.saveState() background = 'static/img/pdf_bg.png' canvas.drawImage(background, 1 * inch, 5.75 * inch, width=8 * inch, height=6 * inch, mask='auto') # Header logo = Image('static/img/logo/logo.png') logo.drawHeight = 0.5 * inch logo.drawWidth = 1.75 * inch date = datetime.now().strftime("%y-%m-%d %H:%M") headerData = [[logo, '', date]] headerTable = Table(headerData, colWidths=[2 * inch, 3.58 * inch, 1.2 * inch], style=[('LINEBELOW', (0, 0), (2, 0), 1, colors.HexColor(0xcccccc)), ('TEXTCOLOR', (0, 0), (2, 0), colors.HexColor(0x807F83)), ('VALIGN', (1, 0), (1, 0), 'MIDDLE'), ('VALIGN', (2, 0), (2, 0), 'MIDDLE')]) headerTable.wrapOn(canvas, doc.width, doc.topMargin) headerTable.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin) pageNum = "Page %d" % doc.page footerData = [[ 'KAPSARC Building Energy Assessment Tool (BEAT)', pageNum ]] footerTable = Table(footerData, colWidths=[5.76 * inch, 1 * inch], style=[('LINEABOVE', (0, 0), (1, 0), 2, colors.HexColor(0xcccccc)), ('TEXTCOLOR', (0, 0), (1, 0), colors.HexColor(0x807F83)), ('ALIGN', (1, 0), (1, 0), 'RIGHT')]) footerTable.wrapOn(canvas, doc.width, doc.bottomMargin) footerTable.drawOn(canvas, doc.leftMargin, 0.5 * inch) canvas.restoreState() pdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf')) pdfmetrics.registerFont(TTFont('VeraBd', 'VeraBd.ttf')) pdfmetrics.registerFont(TTFont('VeraIt', 'VeraIt.ttf')) pdfmetrics.registerFont(TTFont('VeraBI', 'VeraBI.ttf')) styles = getSampleStyleSheet() # Title styles.add( ParagraphStyle(name='styleTitle', alignment=TA_CENTER, fontSize=16, fontName='Vera', textColor=colors.HexColor(0x61a659), leading=30, spaceBefore=35, spaceAfter=10)) # Headings styles.add( ParagraphStyle(name='styleHeading', parent=styles['Heading2'], fontSize=14, textColor=colors.HexColor(0x807F83), leading=20, spaceBefore=10, underlineProportion=1.1, spaceAfter=10)) styles.add( ParagraphStyle(name='styleHeading2', parent=styles['Heading2'], fontSize=14, textColor=colors.HexColor(0x61a659), leading=20, spaceBefore=20, underlineProportion=1.1, spaceAfter=20)) styles.add( ParagraphStyle( name='styleHeading3', #alignment= TA_CENTER, fontSize=12, fontName='Vera', textColor=colors.HexColor(0x61a659), leading=20, spaceBefore=10, spaceAfter=5)) # Body text styles.add( ParagraphStyle(name='styleBodyText', parent=styles['Normal'], fontSize=9, textColor=colors.HexColor(0x666666), spaceBefore=5, spaceAfter=15)) styleTitle = styles['styleTitle'] styleHeading = styles['styleHeading'] styleHeading2 = styles['styleHeading2'] styleHeading3 = styles['styleHeading3'] styleBodyText = styles['styleBodyText'] pdf_chart_colors = [ "#3D6531", "#61a24f", "#89B97B", "#B0D1A7", "#cde5c7", "#7e7f82", "#9E9FA1", "#BFBFC1", "#DFDFE0", "#ffd200", "#FFE360", "#FFEE9F", ] Elements = [] doc = BaseDocTemplate(output_file, showBoundary=0, pagesize=A4, title='KASPSARC BEAT Report', author="KAPSARC", leftMargin=0.75 * inch, rightMargin=0.75 * inch, topMargin=inch, bottomMargin=inch) frame = Frame(doc.leftMargin, doc.topMargin, doc.width, doc.height, topPadding=0.3 * inch, showBoundary=0) template = PageTemplate(id='template', frames=[frame], onPage=header_footer) doc.addPageTemplates([template]) ## PAGE 1 #add some flowables Elements.append( Paragraph("KAPSARC Building Energy Assessment Tool (BEAT)", styleTitle)) Elements.append(Paragraph("Your Building Description", styleHeading)) rowHeights = 0.3 * inch calibrationData = task['calibrationData'] Elements.append(Paragraph("General Information:", styleHeading3)) infoTableData = [ [ Paragraph('<b>- Name: </b>' + calibrationData['txtBldgName'], styleBodyText), Paragraph('<b>- Address: </b>' + calibrationData['txtBldgAddress'], styleBodyText), Paragraph('<b>- Type: </b>' + calibrationData['cmbBldgType'], styleBodyText) ], [ Paragraph( '<b>- Location: </b>' + calibrationData['cmbBldgLocation'], styleBodyText), Paragraph('<b>- Shape: </b>' + calibrationData['cmbBldgShape'], styleBodyText), Paragraph( '<b>- Floor Area (m' + u"\u00b2" + '): </b>' + str(calibrationData['txtFloorArea']), styleBodyText) ] ] infoTable = Table(infoTableData, colWidths=[160, 165, 150], rowHeights=rowHeights) Elements.append(infoTable) Elements.append(Paragraph('<br />', styleBodyText)) Elements.append(Paragraph("Envelope Construction Details:", styleHeading3)) envTableData = [ [ Paragraph( '<b>- South Wall: </b>' + calibrationData['cmbSouthWall'], styleBodyText), Paragraph('<b>- West Wall: </b>' + calibrationData['cmbWestWall'], styleBodyText) ], [ Paragraph( '<b>- North Wall: </b>' + calibrationData['cmbNorthWall'], styleBodyText), Paragraph('<b>- East Wall: </b>' + calibrationData['cmbEastWall'], styleBodyText) ], [ Paragraph('<b>- Roof: </b>' + calibrationData['cmbRoof'], styleBodyText), Paragraph( '<b>- Floor: </b>' + calibrationData['cmbFirstFloorContact'], styleBodyText) ], [ Paragraph('<b>- Windows Type: </b>' + calibrationData['glasstype'], styleBodyText), Paragraph( '<b>- Overhang Depth (m): </b>' + str(calibrationData['txtWinSouthOverhang']), styleBodyText) ] ] envTable = Table(envTableData, colWidths=[240, 235], rowHeights=rowHeights) Elements.append(envTable) Elements.append(Paragraph('<br />', styleBodyText)) Elements.append(Paragraph("Air Conditioning Systems", styleHeading3)) hvacTableData = [[ Paragraph( '<b>- HVAC System Type: </b>' + calibrationData['cmbBldgSystem'], styleBodyText), Paragraph( '<b>- Cooling Temperature Setting (' + u"\u00b0" + 'C): </b>' + str(calibrationData['txtCoolSetTemp']), styleBodyText) ], [ Paragraph( '<b>- Energy Efficiency Ratio (EER): </b>' + str(calibrationData['eir']), styleBodyText), Paragraph( '<b>- Heating Temperature Setting (' + u"\u00b0" + 'C): </b>' + str(calibrationData['txtHeatSetTemp']), styleBodyText) ]] hvacTable = Table(hvacTableData, colWidths=[240, 235], rowHeights=rowHeights) Elements.append(hvacTable) Elements.append(Paragraph('<br />', styleBodyText)) Elements.append(Paragraph("Overall Assessment", styleHeading)) Elements.append( Paragraph( "Based on your description and current SASO requirements, the tool provides the following assessments:", styleBodyText)) if task['compliant']: compliant = "<strong><font color=green>meets</font></strong>" else: compliant = "<strong><font color=red>does not meet</font></strong>" if (task['ngEnergyDiff'] < 0): energyDiff = "<strong><font color=green>" + str( task['energyDiff']) + " kWh/year, less</font></strong>" else: energyDiff = "<strong><font color=red>" + str( task['energyDiff']) + " kWh/year, more</font></strong>" Elements.append( Paragraph( "- Your building " + compliant + " SASO requirements for all building envelope", styleBodyText)) Elements.append( Paragraph( "- Your building consumed " + energyDiff + " than the SASO Baseline", styleBodyText)) if task['compliant']: Elements.append( Paragraph( "- You may reduce even more your energy consumption in your building by using LED lamps and high efficient appliances and air conditioning system", styleBodyText)) else: Elements.append( Paragraph( " - You need to add more insulation to the walls and/or roof, or use more efficient window glazing to comply with SASO requirements", styleBodyText)) if not task['compliant'] and (task['ngEnergyDiff'] >= 0): Elements.append( Paragraph( " - You may also consider using LED lamps and energy efficient appliances and air conditioning system", styleBodyText)) Elements.append(PageBreak()) Elements.append( Paragraph("How electricity is used in your building?", styleHeading3)) Elements.append( Paragraph( "Your building needs electricity to operate several types of equipment including: air-conditioning, lighting, appliances and domestic hot water.", styleBodyText)) #add image Elements.append( Image('static/img/results-intro.png', width=4 * inch, height=1.2 * inch)) #add text Elements.append( Paragraph( "Based on the description you provided as well as typical lighting and appliances used in households, here how your building consumes electricity on annual basis:", styleBodyText)) bepuPieData = task['bepuPieData'] bepuTableData = [[0 for i in xrange(len(bepuPieData[0]))] for i in xrange(len(bepuPieData) + 1)] bepuChartLabel = [0 for i in xrange(len(bepuPieData))] bepuChartData = [0 for i in xrange(len(bepuPieData))] bepuTableData[0][0] = 'End-Use' bepuTableData[0][1] = 'Annual Electricity Use' for i, result in enumerate(bepuPieData): # write body cells bepuTableData[i + 1][0] = str(result['label']) bepuTableData[i + 1][1] = int(result['value']) bepuChartLabel[i] = str(result['label']) bepuChartData[i] = result['value'] #add chart bepuChart = Drawing(400, 200) pc = Pie() pc.data = bepuChartData labelc = [0 for i in xrange(len(bepuChartData))] for i, r in enumerate(bepuChartData): labelc[i] = str(round(r / sum(bepuChartData) * 100, 1)) + "%" pc.labels = labelc pc._seriesCount = len(bepuChartLabel) pc.slices.strokeColor = colors.HexColor(0xffffff) pc.slices.strokeWidth = 0.5 bepu_chart_colors = ['#FFC43E', '#A4A4A4', '#F67A40', '#5894D0', '#98cd99'] for i, r in enumerate(bepuChartLabel): pc.slices[i].fillColor = colors.HexColor(bepu_chart_colors[i]) pc.width = pc.height = 120 pc.x = 40 pc.y = 30 # add_legend(d, pc) legend = Legend() legend.alignment = 'right' legend.x = pc.width + pc.x + 80 legend.y = pc.height - 10 legend.dx = 8 legend.dy = 8 legend.fontName = 'Helvetica' legend.fillColor = colors.HexColor(0x807F83) legend.fontSize = 10 legend.boxAnchor = 'nw' legend.columnMaximum = 8 legend.strokeWidth = 0.5 legend.strokeColor = colors.HexColor(0xffffff) legend.deltax = 75 legend.deltay = 10 legend.autoXPadding = 10 legend.yGap = 0 legend.dxTextSpace = 5 legend.dividerLines = 1 | 2 | 4 legend.dividerOffsY = 6 legend.subCols.rpad = 70 legend.dividerColor = colors.HexColor(0xdedede) legend.colorNamePairs = [(pc.slices[i].fillColor, (bepuChartLabel[i][0:20], ' %s ' % "{:,}".format(int(pc.data[i])))) for i in xrange(len(pc.data))] legendHeader = Legend() legendHeader.colorNamePairs = [ ('', ('End-Use', 'Annual Electricity Use\n(kWh/year)')) ] legendHeader.alignment = 'right' legendHeader.x = legend.x - 20 legendHeader.y = legend.y + 30 legendHeader.fontName = 'Helvetica' legendHeader.fillColor = colors.HexColor(0x807F83) legendHeader.fontSize = 10 legendHeader.boxAnchor = 'nw' legendHeader.subCols.rpad = 80 legendFooter = Legend() legendFooter.colorNamePairs = [ ('', ('Total', str("{:,}".format(int(sum(bepuChartData)))) + '')) ] legendFooter.alignment = 'right' legendFooter.x = legendHeader.x + 5 legendFooter.y = legend.y - (len(bepuChartLabel) + 1) * 10 legendFooter.fontName = 'Helvetica-Bold' legendFooter.fillColor = colors.HexColor(0x807F83) legendFooter.fontSize = 10 legendFooter.boxAnchor = 'nw' legendFooter.subCols.rpad = 145 bepuChart.add(legend) bepuChart.add(legendHeader) bepuChart.add(legendFooter) pc.slices.fontColor = colors.HexColor(0x807F83) n = len(pc.data) bepuChart.add(pc, '') Elements.append(bepuChart) ## PAGE 2 Elements.append( Paragraph("When electricity is consumed in your building?", styleHeading3)) Elements.append( Paragraph( "Based on the weather of your location as well as typical lighting and appliances used in households, your building consumes electricity as noted in the following monthly profile:", styleBodyText)) #add chart pseBarData = task['pseBarData'] pseTableData = [[0 for i in xrange(len(pseBarData[0]['values']) + 1)] for i in xrange(len(pseBarData) + 1)] pseChartData = [[0 for i in xrange(len(pseBarData[0]['values']))] for i in xrange(len(pseBarData))] pseChartLegend = [0 for i in xrange(len(pseBarData))] pseTableData[0][0] = 'Key' month = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] for i, m in enumerate(month): pseTableData[0][i + 1] = str(month[i]) for i, result in enumerate(pseBarData): # write body cells pseTableData[i + 1][0] = str(result['key']) pseChartLegend[i] = str(result['key']) for j, value in enumerate(result['values']): pseTableData[i + 1][j + 1] = int(result['values'][j]['y']) pseChartData[i][j] = int(result['values'][j]['y']) pseChart = Drawing(400, 200) bc = VerticalBarChart() bc.x = 70 bc.y = 0 bc.height = 200 bc.width = 300 bc.data = pseChartData bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.strokeWidth = 0 bc.valueAxis.valueMin = 0 bc.categoryAxis.style = 'stacked' bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 10 bc.categoryAxis.labels.dy = -2 bc.valueAxis.labels.fontName = 'Helvetica' bc.valueAxis.labels.fontSize = 10 bc.valueAxis.strokeWidth = 0.5 bc.valueAxis.strokeColor = colors.HexColor(0x807F83) bc.categoryAxis.strokeWidth = 0.5 bc.categoryAxis.strokeColor = colors.HexColor(0x807F83) bc.valueAxis.labels.fillColor = colors.HexColor(0x807F83) bc.categoryAxis.labels.fontName = 'Helvetica' bc.categoryAxis.labels.fontSize = 10 bc.categoryAxis.labels.fillColor = colors.HexColor(0x807F83) bc.categoryAxis.categoryNames = month # create a list and add the elements of our document (image, paragraphs, table, chart) to it #add our barchart and legend bc.barWidth = .3 * inch bc.groupSpacing = .2 * inch bc.bars.strokeColor = colors.HexColor(0xffffff) bc.bars.strokeWidth = 0. pse_chart_colors = ['#FFC43E', '#A4A4A4', '#F67A40', '#5894D0'] for i, r in enumerate(pseChartLegend): bc.bars[i].fillColor = colors.HexColor(pse_chart_colors[i]) # = colors.blue legend = Legend() legend.alignment = 'right' legend.x = bc.width + bc.x + 5 legend.y = bc.height + bc.y legend.deltax = 40 legend.dxTextSpace = 5 legend.dx = 8 legend.dy = 8 legend.fontName = 'Helvetica' legend.fillColor = colors.HexColor(0x807F83) legend.fontSize = 10 legend.boxAnchor = 'nw' legend.columnMaximum = (len(bc.data) + 1) / 2 legend.strokeWidth = 0.5 legend.strokeColor = colors.HexColor(0xffffff) legend.deltax = 75 legend.deltay = 12 legend.dividerColor = colors.HexColor(0xdedede) legend.columnMaximum = len(pseChartLegend) legend.colorNamePairs = [(bc.bars[i].fillColor, pseChartLegend[i]) for i in xrange(len(bc.data))] #pseChart.hAlign = 'RIGHT' label = Label() label.setOrigin(10, bc.height / 2) #label.boxAnchor = 'sw' label.angle = 90 label.fillColor = colors.HexColor(0x807F83) label.setText('Electricity Consumption (kWh)') label.fontName = 'Helvetica' pseChart.add(legend, 'legend') pseChart.add(bc) pseChart.add(label) Elements.append(pseChart) Elements.append(PageBreak()) ## PAGE 3 Elements.append( Paragraph( "Does your building meet SASO Thermal Performance Requirements?", styleHeading3)) Elements.append( Paragraph( "Based on your description, the thermal transmittance properties of the walls, roof and glazing are calculated, and compared with SASO thermal building performance requirements:", styleBodyText)) #add chart lvdData = task['lvdData'] lvdChartData = [[0 for i in xrange(len(lvdData[0]['values']))] for i in xrange(len(lvdData))] lvdChartCategoryNames = [0 for i in xrange(len(lvdData[0]['values']))] lvdComparedObjKey = [0 for i in xrange(len(lvdData))] for i, result in enumerate(lvdData): # write body cells lvdComparedObjKey[i] = str(lvdData[i]['key']) for j, value in enumerate(result['values']): lvdChartCategoryNames[j] = value['label'] lvdChartData[i][j] = value['value'] lvdChart = Drawing(400, 200) bc = VerticalBarChart() bc.x = 70 bc.y = 0 bc.height = 200 bc.width = 300 bc.data = lvdChartData bc.strokeColor = colors.black # bc.fillColor=colors.blue bc.valueAxis.valueMin = 0 bc.strokeWidth = 0 bc.valueAxis.valueMin = 0 bc.categoryAxis.labels.boxAnchor = 'n' bc.categoryAxis.labels.dx = 0 bc.categoryAxis.labels.dy = -2 # bc.categoryAxis.labels.angle = 20 bc.valueAxis.labels.fontName = 'Helvetica' bc.valueAxis.labels.fontSize = 10 bc.valueAxis.strokeWidth = 0.5 bc.valueAxis.strokeColor = colors.HexColor(0x807F83) bc.categoryAxis.strokeWidth = 0.5 bc.categoryAxis.strokeColor = colors.HexColor(0x807F83) bc.valueAxis.labels.fillColor = colors.HexColor(0x807F83) bc.categoryAxis.labels.fontName = 'Helvetica' bc.categoryAxis.labels.fontSize = 8 bc.categoryAxis.labels.fillColor = colors.HexColor(0x807F83) bc.categoryAxis.categoryNames = lvdChartCategoryNames bc.categoryAxis.labels.angle = 0 # create a list and add the elements of our document (image, paragraphs, table, chart) to it #add our barchart and legend bc.barWidth = .3 * inch bc.groupSpacing = .2 * inch bc.bars.strokeColor = colors.HexColor(0xffffff) bc.bars.strokeWidth = 0.5 lvd_chart_colors = ['#5894D0', '#F67A40'] for i, r in enumerate(lvdComparedObjKey): bc.bars[i].fillColor = colors.HexColor(lvd_chart_colors[i]) # = colors.blue legend = Legend() legend.alignment = 'right' legend.x = bc.width + bc.x + 5 legend.y = bc.height + bc.y legend.deltax = 40 legend.dxTextSpace = 5 legend.dx = 8 legend.dy = 8 legend.fontName = 'Helvetica' legend.fillColor = colors.HexColor(0x807F83) legend.fontSize = 10 legend.boxAnchor = 'nw' legend.columnMaximum = (len(bc.data) + 1) / 2 legend.strokeWidth = 0.5 legend.strokeColor = colors.HexColor(0xffffff) legend.deltax = 75 legend.deltay = 12 legend.dividerColor = colors.HexColor(0xdedede) legend.columnMaximum = len(lvdComparedObjKey) legend.colorNamePairs = [(bc.bars[i].fillColor, lvdComparedObjKey[i]) for i in xrange(len(bc.data))] #pseChart.hAlign = 'RIGHT' label = Label() label.setOrigin(10, bc.height / 2) #label.boxAnchor = 'sw' label.angle = 90 label.fillColor = colors.HexColor(0x807F83) label.setText('Envelope U-value (W/m' + u'\u00b2' + '.k)') label.fontName = 'Helvetica' lvdChart.add(label) lvdChart.add(legend, 'legend') lvdChart.add(bc) Elements.append(lvdChart) #Elements.append(PageBreak()) Elements.append(Paragraph('<br /><br />', styleBodyText)) ## PAGE 4 Elements.append( Paragraph("How energy efficient is your building?", styleHeading3)) Elements.append( Paragraph( "Using your input specifications, the annual electricity consumption is calculated and compared with a similar building that meets SASO requirements:", styleBodyText)) #add chart bepuComparisonData = task['bepuComparisonData'] bepuComparisonChartData = [[ 0 for i in xrange(len(bepuComparisonData[0]['values'])) ] for i in xrange(len(bepuComparisonData))] bepuChartCategoryNames = [ 0 for i in xrange(len(bepuComparisonData[0]['values'])) ] bepuComparedObjKey = [0 for i in xrange(len(bepuComparisonData))] for i, result in enumerate(bepuComparisonData): # write body cells bepuComparedObjKey[i] = str(bepuComparisonData[i]['key']) for j, value in enumerate(result['values']): bepuChartCategoryNames[j] = value['label'] bepuComparisonChartData[i][j] = value['value'] bepuComparisonChart = Drawing(400, 200) bc = VerticalBarChart() bc.x = 70 bc.y = 0 bc.height = 200 bc.width = 300 bc.data = bepuComparisonChartData bc.strokeColor = colors.black # bc.fillColor=colors.blue bc.valueAxis.valueMin = 0 bc.strokeWidth = 0 bc.valueAxis.valueMin = 0 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 10 bc.categoryAxis.labels.dy = -2 # bc.categoryAxis.labels.angle = 20 bc.valueAxis.labels.fontName = 'Helvetica' bc.valueAxis.labels.fontSize = 10 bc.valueAxis.strokeWidth = 0.5 bc.valueAxis.strokeColor = colors.HexColor(0x807F83) bc.categoryAxis.strokeWidth = 0.5 bc.categoryAxis.strokeColor = colors.HexColor(0x807F83) bc.valueAxis.labels.fillColor = colors.HexColor(0x807F83) bc.categoryAxis.labels.fontName = 'Helvetica' bc.categoryAxis.labels.fontSize = 10 bc.categoryAxis.labels.fillColor = colors.HexColor(0x807F83) bc.categoryAxis.categoryNames = bepuChartCategoryNames bc.categoryAxis.labels.angle = 30 # create a list and add the elements of our document (image, paragraphs, table, chart) to it #add our barchart and legend bc.barWidth = .3 * inch bc.groupSpacing = .2 * inch bc.bars.strokeColor = colors.HexColor(0xffffff) bc.bars.strokeWidth = 0.5 bepu_chart_colors = ['#5894D0', '#F67A40'] for i, r in enumerate(bepuComparedObjKey): bc.bars[i].fillColor = colors.HexColor(bepu_chart_colors[i]) # = colors.blue # bc.bars[1].fillColor = colors.lightblue legend = Legend() legend.alignment = 'right' legend.x = bc.width + bc.x + 5 legend.y = bc.height + bc.y legend.deltax = 40 legend.dxTextSpace = 5 legend.dx = 8 legend.dy = 8 legend.fontName = 'Helvetica' legend.fillColor = colors.HexColor(0x807F83) legend.fontSize = 10 legend.boxAnchor = 'nw' legend.columnMaximum = (len(bc.data) + 1) / 2 legend.strokeWidth = 0.5 legend.strokeColor = colors.HexColor(0xffffff) legend.deltax = 75 legend.deltay = 12 legend.dividerColor = colors.HexColor(0xdedede) legend.columnMaximum = len(bepuComparedObjKey) legend.colorNamePairs = [(bc.bars[i].fillColor, bepuComparedObjKey[i]) for i in xrange(len(bc.data))] #pseChart.hAlign = 'RIGHT' label = Label() label.setOrigin(10, bc.height / 2) #label.boxAnchor = 'sw' label.angle = 90 label.fillColor = colors.HexColor(0x807F83) label.setText('Annual Energy Use (kWh/year)') label.fontName = 'Helvetica' bepuComparisonChart.add(label) bepuComparisonChart.add(legend, 'legend') bepuComparisonChart.add(bc) Elements.append(bepuComparisonChart) Elements.append(PageBreak()) doc.build(Elements) output_file.seek(0) # Set filname and mimetype file_name = 'K-BEAT_export_{}.pdf'.format( datetime.now().strftime("%Y-%m-%d %H:%M:%S")) #Returning the file from memory return send_file(output_file, attachment_filename=file_name, as_attachment=True)
chart.bars[i].fillColor = colors[i] # Add data to chart chart.data = prices chart.categoryAxis.categoryNames = categories # Add labels to chart chart.barLabelFormat = '$%.2f' # Text to display on label - 2 decimal float chart.barLabels.nudge = 8 # Nudge labels upwards by 8px # ------- Create legend ------- legend = Legend() # Create the legend legend.boxAnchor = 'sw' # Set anchor to bottom-left legend.x = 50 # Shift legend right to bring in line with chart legend.y = 50 # Shift legend up by 50px legend.alignment = 'right' # Put labels to the right of color icons # Set legend colors legend.colorNamePairs = [(colors[i], '{} '.format(labels[i])) for i in range(len(colors))] # Add chart and legend to drawing d.add(chart) d.add(legend) # Export as test_img.png d.save(fnRoot='test_img', formats=['png']) #--------------------------------# # Opening an image from disk # #--------------------------------#
def generarGraficoProveedores(self): nombres = [] cantidades = [] self.iniciar_conexion() cursor = self.__conexion.cursor() sql = "select nombre_empresa,count(prod.id_proveedor) as cantidad from productos prod,proveedores prov where prod.id_proveedor=prov.id_proveedor group by nombre_empresa" cursor.execute(sql) rows = cursor.fetchall() for row in rows: nombre_empresa = row[0] cantidad = row[1] nombres.append(nombre_empresa) cantidades.append(cantidad) #print(nombre_empresa+"-"+str(cantidad)+"-") self.cerrar_conexion() reporte = SimpleDocTemplate("graficoProveedores.pdf") partes = [] font_text = ParagraphStyle("test") font_text.textColor = "black" font_text.alignment = TA_CENTER font_text.fontSize = 20 text = Paragraph("Reporte grafico de proveedores", font_text) partes.append(text) draw = Drawing() pie = Pie() pie.width = 300 pie.height = 200 pie.x = 50 pie.y = -100 pie.data = cantidades pie.labels = nombres pie.slices.strokeWidth = 0.5 legend = Legend() legend.x = 250 legend.y = -200 legend.dx = 8 legend.dy = 8 legend.fontName = "Helvetica" legend.fontSize = 7 legend.boxAnchor = "n" legend.columnMaximum = 10 legend.strokeWidth = 1 legend.strokeColor = colors.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 legend.colorNamePairs = [(pie.slices[i].fillColor, (pie.labels[i][0:20], "%0.0f prod" % pie.data[i])) for i in xrange(len(pie.data))] draw.add(legend) draw.add(pie) partes.append(draw) reporte.build(partes) if (os.path.isfile("graficoProveedores.pdf")): return True else: return False
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 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, drawing=None, title=None, data=None, bench_data=None): pie = Pie() pie.strokeColor = white pie.slices.strokeColor = white pie.slices.popout = 1 pie.width = 85 pie.height = 85 pie.y = 50 pie.x = 35 bench_pie = Pie() bench_pie.strokeColor = white bench_pie.slices.strokeColor = white bench_pie.slices.popout = 1 bench_pie.width = 85 bench_pie.height = 85 bench_pie.y = 50 bench_pie.x = 150 legend = Legend() legend.columnMaximum = 99 legend.alignment = 'right' legend.boxAnchor = 'c' legend.dx = 6 legend.dy = 6 legend.dxTextSpace = 5 legend.deltay = 10 legend.strokeWidth = 0 legend.strokeColor = white legend.subCols[0].minWidth = 75 legend.subCols[0].align = 'left' legend.subCols[1].minWidth = 25 legend.subCols[1].align = 'right' legend.y = 20 legend.x = 153 legend.fontName = 'Lato' legend.fontSize = 9 pie.data = data pie.slices[0].fillColor = lightgrey pie.slices[1].fillColor = limegreen #pie.slices[1].popout = 6 pie.slices[2].fillColor = red bench_pie.data = bench_data bench_pie.slices[0].fillColor = lightgrey bench_pie.slices[1].fillColor = limegreen #bench_pie.slices[1].popout = 6 bench_pie.slices[2].fillColor = red legend.colorNamePairs = [(limegreen, 'Positive'), (lightgrey, 'Neutral'), (red, 'Negative')] drawing.add( String(x=75, y=145, text=title, fontSize=10, fontName='Lato', textAnchor='middle')) drawing.add( String(x=165, y=145, text='Benchmark', fontSize=10, fontName='Lato')) drawing.add(pie) drawing.add(bench_pie) drawing.add(legend)
def grafica_pastel(request): response = HttpResponse(content_type='application/pdf') pdf_name = "Gráfica.pdf" # llamado clientes # la linea 26 es por si deseas descargar el pdf a tu computadora response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name buff = BytesIO() doc = SimpleDocTemplate( buff, pagesize=letter, rightMargin=40, leftMargin=40, topMargin=200, bottomMargin=18, ) story = [] estilo = getSampleStyleSheet() d = Drawing(300, 200) pc = Pie() pc.x = 65 pc.y = 15 pc.width = 170 pc.height = 170 # pc.data = [11,20,30,40,50] # pc.labels = ['IE','Kopete','Chrome','Firefox','Opera'] datos = [] etiquetas = [] for key in Venta.objects.values('producto').annotate( suma=Sum('cantidad_vendida')): producto = get_object_or_404(Producto, pk=key['producto']) etiquetas.append(producto.nombre) datos.append(key['suma']) pc.data = datos pc.labels = etiquetas 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.sideLabels = 1 # Con 0 no se muestran lÌneas hacia las etiquetas #~ pc.slices.labelRadius = 0.65 # Para mostrar el texto dentro de las tajadas #Insertamos la legenda legend = Legend() legend.x = 370 legend.y = 0 legend.dx = 8 legend.dy = 8 legend.fontName = 'Helvetica' legend.fontSize = 7 legend.boxAnchor = 'n' legend.columnMaximum = 10 legend.strokeWidth = 1 legend.strokeColor = colors.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 #Insertemos nuestros propios colores colores = [ colors.blue, colors.red, colors.green, colors.yellow, colors.pink ] for i, color in enumerate(colores): pc.slices[i].fillColor = color legend.colorNamePairs = [(pc.slices[i].fillColor, (pc.labels[i][0:20], '%0.2f' % pc.data[i])) for i in xrange(len(pc.data))] d.add(pc) d.add(legend) story.append(d) doc.build(story) response.write(buff.getvalue()) buff.close() return response
def create_bar(self, data_list, label_x_axis, contain, y_label=None, x_label=None, bar_width=520, bar_height=100, draw_width=520, draw_height=200, user_color=None, fontName="Times-Roman", fontSize=6, x_angle=0, bar_space=0): d = Drawing(width=draw_width, height=draw_height) bar = VerticalBarChart() bar.width = bar_width bar.height = bar_height bar.y = bar.height - (bar_height / 4) bar.strokeColor = colors.black bar.barLabelFormat = '%s' bar.barLabels.nudge = 7 bar.barLabels.fontSize = fontSize ################# X AXIS PROPERTIES ################# bar.categoryAxis.labels.dx = 0 bar.categoryAxis.labels.angle = x_angle bar.categoryAxis.labels.boxAnchor = 'autox' bar.categoryAxis.labels.fontSize = fontSize bar.categoryAxis.labels.fontName = self.master_font bar.categoryAxis.strokeWidth = 0.25 bar.categoryAxis.tickDown = -(bar.height) bar.categoryAxis.categoryNames = label_x_axis labX = Label() labX.boxAnchor = 'ne' labX.dx = bar.width * 2.15 labX.dy = bar.height labX.fontName = fontName labX.fontSize = fontSize labX.setText(x_label) d.add(labX) ##################################################### ################# Y AXIS PROPERTIES ################# bar.valueAxis.forceZero = 1 bar.valueAxis.labels.fontSize = fontSize bar.valueAxis.labels.fontName = fontName bar.valueAxis.rangeRound = 'both' bar.valueAxis.valueMin = 0 bar.valueAxis.visibleGrid = 1 bar.valueAxis.visibleAxis = 1 bar.valueAxis.labels.dx = -10 labY = Label() labY.boxAnchor = 'autox' labY.dy = bar.y + (bar.height / 1.5) labY.dx = bar.x - 30 labY.angle = 90 labY.fontName = fontName labY.fontSize = fontSize labY.setText(y_label) d.add(labY) ##################################################### bar.barSpacing = bar_space # bar.groupSpacing = 3 bar.data = data_list # print len(data_list) # print len(contain) if user_color != None: usage_color = user_color else: random_range = [randint(0, 100) for i in range(len(contain))] usage_color = map( lambda item: PCMYKColor(randint(0, item), randint(0, item), randint(0, item), randint(0, item)), random_range) for i in range(len(data_list)): bar.bars[i].name = contain[i].upper() bar.bars[i].fillColor = usage_color[i] legend = Legend() # legend.autoXPadding = 10 legend.alignment = 'right' legend.boxAnchor = 'sw' legend.dxTextSpace = 10 legend.fontSize = fontSize legend.fontName = fontName legend.subCols.minWidth = 55 legend.variColumn = 1 legend.deltay = 15 legend.x = bar.x legend.colorNamePairs = Auto(obj=bar) d.add(bar) d.add(legend) self.flowables.append(d)
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 generarGraficoProductos(self): nombres = [] precios = [] self.iniciar_conexion() cursor = self.__conexion.cursor() sql = "SELECT prod.nombre,SUM(prod.precio) AS precio_final FROM productos prod,proveedores prov WHERE prod.id_proveedor=prov.id GROUP BY prod.nombre" cursor.execute(sql) rows = cursor.fetchall() for row in rows: nombre_producto = row[0] precio = row[1] nombres.append(nombre_producto) precios.append(precio) self.cerrar_conexion() reporte = SimpleDocTemplate("graficoProductos.pdf") partes = [] font_text = ParagraphStyle("test") font_text.textColor = "black" font_text.alignment = TA_CENTER font_text.fontSize = 20 text = Paragraph("Reporte gráfico de productos y sus precios", font_text) partes.append(text) draw = Drawing() pie = Pie() pie.width = 300 pie.height = 200 pie.x = 50 pie.y = -100 pie.data = precios pie.labels = nombres pie.slices.strokeWidth = 0.5 legend = Legend() legend.x = 250 legend.y = -200 legend.dx = 8 legend.dy = 8 legend.fontName = "Helvetica" legend.fontSize = 7 legend.boxAnchor = "n" legend.columnMaximum = 10 legend.strokeWidth = 1 legend.strokeColor = colors.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 legend.colorNamePairs = [(pie.slices[i].fillColor, (pie.labels[i][0:20], "$" + "%0.2f" % pie.data[i])) for i in xrange(len(pie.data))] draw.add(legend) draw.add(pie) partes.append(draw) reporte.build(partes) if (os.path.isfile("graficoProductos.pdf")): return True else: return False
def add_findings_by_account_chart(): drawing = Drawing(500, 500) open_findings, _, accounts = get_top_10_accounts_by_findings() length_accounts = len(accounts) for account in accounts: if (length_accounts > 0): idx = accounts.index(account) long_account_string = account if (len(long_account_string) > 15): accounts.remove(account) account = textwrap.fill(account, 15) accounts.insert(idx, account) length_accounts = length_accounts - 1 maxVal = max( open_findings[0] ) ## Find maximum number of findings open or resolved and use it as basis for plotting the graph if (maxVal > 1000): multiplier = 1000 step = 4 * multiplier else: multiplier = 100 step = 4 * multiplier value_step = int(ceil(maxVal / step)) * multiplier if (value_step < 10): value_step = 1 bar = HorizontalBarChart() bar.x = 25 bar.y = -25 bar.height = 500 bar.width = 450 bar.data = open_findings #bar.strokeColor = colors.white bar.valueAxis.valueMin = 0 bar.valueAxis.valueMax = maxVal * 2 ## graph display 2 times as much as max violation bar.valueAxis.valueStep = value_step ## Convert to neartest 100 bar.categoryAxis.labels.boxAnchor = 'ne' bar.categoryAxis.labels.dx = -10 bar.categoryAxis.labels.dy = 0 bar.categoryAxis.labels.fontName = 'Helvetica' bar.categoryAxis.categoryNames = accounts bar.bars[0].fillColor = HexColor("#E57300") bar.barWidth = 2.5 bar.categoryAxis.strokeWidth = 0 bar.barLabelFormat = '%d' bar.barLabels.nudge = 15 bar.barLabels.fillColor = colors.black bar.bars[0].strokeColor = None legend = Legend() legend.alignment = 'right' legend.colorNamePairs = [[HexColor("#E57300"), "Open Findings"]] legend.columnMaximum = 2 legend.x = 400 legend.y = 470 drawing.add(legend) drawing.add(bar) fields.append(drawing) newPage()
def create_single_class_pdf(teacher_name, class_id, class_name, class_average, total_students, total_grades, standards_list, grade_standard_dict, grade_student_dict, standard_total_dict): pdfName = class_name + "_CLR" + ".pdf" response.headers['Content-Type'] = 'application/pdf' response.headers[ 'Content-Disposition'] = 'attachment;filename=%s;' % pdfName styles = getSampleStyleSheet() HeaderStyle = styles["Heading1"] buff = StringIO() doc = SimpleDocTemplate(buff, pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) doc.title = pdfName Story = [] Elements = [] formatted_time = time.ctime() 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') ptext = '<font size=12>%s</font>' % formatted_time Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) #Teacher Name ptext = '<font size=12><b>%s %s</b></font>' % (teacher_name.first_name, teacher_name.last_name) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) #Class Name ptext = '<font size=12>%s: </font>' % (class_name) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 7)) Elements.extend(ptext) #Class Average ptext = '<font size=12>Class Average:%s%%</font>' % (class_average) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) #Total Students ptext = '<font size=12>Total Students:%s</font>' % (total_students) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) #Total Assignments ptext = '<font size=12>Total Assignments:%s</font>' % (total_grades) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) Story.append(Spacer(1, 40)) ptext = '<font size=15><b>Standards Progress</b></font>' Story.append(Paragraph(ptext, styles["title"])) test_values = [[10, 20, 50, 90, 80]] standard_table = [] i = 0 minimum = 100 standard_averages = [[]] #Go through the standard_total_dict keys and add all the necessary values to the standard_averages 2d list. for standard in sorted(standard_total_dict.keys()): standard_table.append([]) current_avg = (standard_total_dict[standard][1] / standard_total_dict[standard][0]) * 100 if minimum > current_avg: minimum = current_avg standard_table[i].append(standard_total_dict[standard][3] + ": " + format((standard_total_dict[standard][1] / standard_total_dict[standard][0]) * 100, '.2f') + "%") standard_averages[0].append( int( round((standard_total_dict[standard][1] / standard_total_dict[standard][0]) * 100))) #add assignments to correct buckets 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 = [10, 20, 30, 40, 50] #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 #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 = standards_list drawing.add(bc) #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) 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) doc.build(Story) pdf = buff.getvalue() buff.close() return pdf
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 create_single_class_pdf( teacher_name, class_id, class_name, class_average, total_students, total_grades, standards_list, grade_standard_dict, grade_student_dict, standard_total_dict, ): pdfName = class_name + "_CLR" + ".pdf" response.headers["Content-Type"] = "application/pdf" response.headers["Content-Disposition"] = "attachment;filename=%s;" % pdfName styles = getSampleStyleSheet() HeaderStyle = styles["Heading1"] buff = StringIO() doc = SimpleDocTemplate(buff, pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) doc.title = pdfName Story = [] Elements = [] formatted_time = time.ctime() 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", ) ptext = "<font size=12>%s</font>" % formatted_time Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) # Teacher Name ptext = "<font size=12><b>%s %s</b></font>" % (teacher_name.first_name, teacher_name.last_name) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) # Class Name ptext = "<font size=12>%s: </font>" % (class_name) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 7)) Elements.extend(ptext) # Class Average ptext = "<font size=12>Class Average:%s%%</font>" % (class_average) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) # Total Students ptext = "<font size=12>Total Students:%s</font>" % (total_students) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) Elements.extend(ptext) # Total Assignments ptext = "<font size=12>Total Assignments:%s</font>" % (total_grades) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) Story.append(Spacer(1, 40)) ptext = "<font size=15><b>Standards Progress</b></font>" Story.append(Paragraph(ptext, styles["title"])) test_values = [[10, 20, 50, 90, 80]] standard_table = [] i = 0 minimum = 100 standard_averages = [[]] # Go through the standard_total_dict keys and add all the necessary values to the standard_averages 2d list. for standard in sorted(standard_total_dict.keys()): standard_table.append([]) current_avg = (standard_total_dict[standard][1] / standard_total_dict[standard][0]) * 100 if minimum > current_avg: minimum = current_avg standard_table[i].append( standard_total_dict[standard][3] + ": " + format((standard_total_dict[standard][1] / standard_total_dict[standard][0]) * 100, ".2f") + "%" ) standard_averages[0].append( int(round((standard_total_dict[standard][1] / standard_total_dict[standard][0]) * 100)) ) # add assignments to correct buckets 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 = [10, 20, 30, 40, 50] # 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 # 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 = standards_list drawing.add(bc) # 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) 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) doc.build(Story) pdf = buff.getvalue() buff.close() return pdf
def __get_tags_statistics(self): monto_categorias = dict() for tra in self.transactions: if len(tra.tags) > 0: for tag in tra.tags: if tag in monto_categorias.keys(): monto_categorias[tag] += tra.amount else: monto_categorias[tag] = tra.amount labels = [lab.encode('utf-8') for lab in monto_categorias.keys()] data = monto_categorias.values() p = PageBreak() p.drawOn(self.c, 0, 1000) self.c.showPage() self.l = 600 self.c.setFont('Courier', 14) self.c.drawString(30, 800, 'Categorias') drawing = Drawing(200, 200) pie = Pie() pie.x = 30 pie.y = self.l - 130 pie.height = 300 pie.width = 300 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 = self.l 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, 10 renderPDF.draw(drawing, self.c, x, y, showBoundary=False)
def pie_chart(data, **kw): """ Function to Create a reportlab Drawing with a Pie Chart included. :param data: 1d array of data, e.g. [5, 10, 20, ...] :type data: list[numbers] :kwarg kw: list of optional keyword parameters :kwparam lables: 1d array of labels :type labels: string :kwparam lblFrmt: how to format the data, e.g. 5% :type lblFrmt: format string :kwparam plotSize: size in pixels, e.g. (400, 200) :type plotSize: Tuple :kwparam title: title of pie chart :type title: string :param legend: true/false, when true, labels are displayed here, when false added to the pie :type legend: bool """ title = kw.pop('title', None) labels = kw.pop('labels', '%.1f%%') lbl_frmt = kw.pop('lblFrmt', '%.1f%%') legend = kw.pop('legend', False) size = kw.pop('plotSize', (18 * cm, 9 * cm)) # Create the drawing drawing = Drawing(size[0], size[1]) # Create the Pie Chart chart = pie() for key, val in list(kw.items()): setattr(chart, key, val) chart.x = 10 chart.y = (drawing.height - chart.height) / 2 chart.slices.strokeWidth = 1 # self.chart.slices.popout = 1 chart.direction = 'clockwise' chart.width = chart.height chart.startAngle = 90 # self.chart.slices[0].popout = 10 for i in range(len(data)): chart.slices[i].fillColor = HexColor(PDF_CHART_COLORS[i % len(PDF_CHART_COLORS)]) chart.data = data chart.labels = [(lbl_frmt % i) for i in chart.data] chart.checkLabelOverlap = True if title is not None: drawing.add(String(20, size[1] - 20, title), name='title') chart.y -= 10 if legend: legend = Legend() legend.boxAnchor = 'w' legend.x = chart.width + 40 legend.y = drawing.height / 2 legend.subCols[1].align = 'right' legend.alignment = 'right' legend.columnMaximum = 7 if labels is not None: legend.colorNamePairs = [(chart.slices[i].fillColor, labels[i]) for i in range(len(labels))] drawing.add(legend, name='legend') elif labels is not None: for i in range(min([len(labels), len(data)])): chart.labels[i] = labels[i] drawing.add(chart, name='chart') return drawing
leyenda.dx = 8 leyenda.dy = 8 leyenda.fontName = 'Helvetica' leyenda.fontSize = 7 leyenda.boxAnchor = 'n' leyenda.columnMaximum = 10 leyenda.strokeWidth = 1 leyenda.strokeColor = colors.darkgray leyenda.deltax = 75 leyenda.deltay = 10 leyenda.autoXPadding = 5 leyenda.autoYPadding = 0 leyenda.yGap = 0 leyenda.dxTextSpace = 5 leyenda.alignment = 'right' leyenda.dividerLines = 1 | 2 | 4 leyenda.dividerOffsY = 4.5 leyenda.subCols.rpad = 30 colores = [colors.blue, colors.red, colors.green, colors.yellow, colors.pink] for i, color in enumerate(colores): tarta.slices[i].fillColor = color leyenda.colorNamePairs = [(tarta.slices[i].fillColor, (tarta.labels[i][0:20], '%0.2f' % tarta.data[i])) for i in range(len(tarta.data))] d.add(tarta) d.add(leyenda) guion.append(d)
def __per_account_statistic(self): for acc in self.accounts: p = PageBreak() p.drawOn(self.c, 0, 1000) self.c.showPage() self.l = 760 self.c.setFont('Courier', 14) self.c.drawString(30, 800, 'Cuenta: %s' % \ acc.name) header = ['Fecha', 'Tipo', 'Monto', 'Description'] data = [header] g_data = list() g_labe = list() total = 0 for tra in self.transactions: if tra.account == acc.name: if tra.t_type in ['expense', 'transfer']: tipo = self.__translate_type(tra.t_type) data.append([tra.date, tipo.upper(), '$%2.f' % tra.amount, tra.description]) total += tra.amount g_data.append(tra.amount) g_labe.append(tra.description.encode('utf-8')) data.append(['TOTAL', '', '$%.2f' % total, '']) if len(g_data) == 0 or len(g_labe) == 0: self.c.setFont('Courier', 12) self.c.drawString(30, 770, 'Sin movimientos negativos') continue from_title = 35 if len(data) != 2: self.l -= ((len(data) * len(data)) + len(data)) + from_title t = Table(data) t.setStyle(TableStyle([('INNERGRID', (0,0), (-1,-1), 0.25, black), ('BOX', (0,0), (-1,-1), 0.25, black), ('FONTNAME', (0,0), (-1,0), 'Courier-Bold'), ('BACKGROUND', (0,0), (-1,0), HexColor('#efeded')), ('BACKGROUND', (0,0), (0,-1), HexColor('#efeded')), ('FONTSIZE', (0,0), (-1,0), 12), ('FONTSIZE', (0,1), (-1,-1), 8), ('FONTNAME', (0,1), (-1,-1), 'Courier'), ('BACKGROUND', (0,-1), (-1,-1), red), ('TEXTCOLOR', (0,-1), (-1,-1), white)])) t.wrapOn(self.c, 30, self.l) t.drawOn(self.c, 30, self.l) drawing = Drawing(200, 100) pie = Pie() pie.x = 30 pie.y = self.l - 300 pie.height = 200 pie.width = 200 pie.data = g_data pie.labels = g_labe pie.simpleLabels = 1 pie.slices.strokeWidth = 1 pie.slices.strokeColor = black pie.slices.label_visible = 0 pie.slices.popout = 1 #pie.labels = map(str, pie.data) legend = Legend() legend.x = 250 legend.y = self.l - 250 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, 10 renderPDF.draw(drawing, self.c, x, y, showBoundary=False)