def sample1bar(data=[(13, 5, 20, 22, 37, 45, 19, 4)]): drawing = Drawing(400, 200) bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 60 bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 catNames = 'Jan Feb Mar Apr May Jun Jul Aug'.split( ' ') catNames = [n+'-99' for n in catNames] bc.categoryAxis.categoryNames = catNames drawing.add(bc) return drawing
def getBarChart(self, x_values, y_values): """Gets a bar chart with the given values Parameters: self: the class instance x_values: list - x values for the bar chart y_values: list - y values for the bar chart Returns: reportlab Vertical Bar Chart - bar chart with inputted values """ y_values = [tuple(y_values)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = y_values bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 250 bc.valueAxis.valueStep = 25 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 45 bc.categoryAxis.categoryNames = x_values return bc
def sample1bar(data=[(13, 5, 20, 22, 37, 45, 19, 4), (5, 20, 22, 37, 45, 19, 4, 13), (20, 22, 37, 45, 19, 4, 13, 5)]): # sanity check: for d in data: if len(d)!=8: raise ValueError("bar chart data must have 8 elements "+repr(data)) drawing = Drawing(400, 200) bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 60 bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 catNames = 'Jan Feb Mar Apr May Jun Jul Aug'.split() catNames = [n+'-99' for n in catNames] bc.categoryAxis.categoryNames = catNames drawing.add(bc) return drawing
def gen_bar_graphs(comparison_values, location, emission): bc = VerticalBarChart() labels = [] data = [] comparison_values.append([location, emission]) comparison_values.sort(key=lambda x: x[1]) for pair in comparison_values: labels.append(pair[0]) data.append(pair[1]) data = [data] location_index = labels.index(location) bc.x = -150 bc.y = -110 bc.height = 100 bc.width = 150 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = data[0][-1] + data[0][-1] * .1 #bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = labels for i in range(len(labels)): bc.bars[(0, i)].fillColor = colors.Color(166.0 / 255, 189.0 / 255, 219.0 / 255) bc.bars[(0, location_index)].fillColor = colors.Color(28.0 / 255, 144.0 / 255, 153.0 / 255) return bc
def show_figure(data, y_max, x_category, legend_category): drawing = Drawing(400, 200) bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 150 bc.width = 450 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = y_max # bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = len(data[0]) # bc.categoryAxis.labels.dy = -2 # bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = x_category drawing.add(bc) # add legend from here swatches = Legend() swatches.alignment = 'right' swatches.x = 80 swatches.y = 190 swatches.deltax = 30 swatches.dxTextSpace = 10 swatches.columnMaximum = 1 color_list = (colors.red, colors.green, colors.blue, colors.pink, colors.yellow) items = [] for index, item in enumerate(legend_category): items.append((color_list[index], item)) swatches.colorNamePairs = items drawing.add(swatches, 'legend') return drawing
def make_drawing(d, answerKey): drawing = Drawing(400, 200) maxData = 0 for count in d: if count > maxData: maxData = count data = [ tuple(d), ] names = answerKey bc = VerticalBarChart() bc.x = 20 bc.y = 50 bc.height = 180 bc.width = 400 bc.data = data bc.strokeColor = colors.white bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = maxData bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = -10 bc.categoryAxis.labels.fontName = 'Helvetica' bc.categoryAxis.categoryNames = names drawing.add(bc) return drawing
def myBarChart(data): drawing = Drawing(400, 200) bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.barWidth = .3 * inch bc.groupSpacing = .2 * inch bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 100 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 catNames = ('Trial1 Trial2 Trial3 Trial4 Trial5').split() bc.categoryAxis.categoryNames = catNames bc.bars[0].fillColor = colors.red bc.bars[1].fillColor = colors.lightblue drawing.add(bc) return drawing
def draw_bar_chart(pdf_text, page_height): '''Currently generates a dummy graph. Next, need to pass in data that shall be the reactors temp throughout the sequence. ''' pdf_text.showPage() drawing = Drawing(400, 200) data = [ (13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5) ] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = ['Jan-99','Feb-99','Mar-99','Apr-99','May-99','Jun-99','Jul-99','Aug-99'] drawing.add(bc) renderPDF.draw(drawing, pdf_text, inch, inch) return page_height
def ventas_totales(pos, periodos, ventas_totales): arreglo = [periodos, ventas_totales] table = Table(arreglo, colWidths=3 * cm) table.setStyle([('ALIGN', (0, 0), (-1, -1), 'LEFT')]) for index, row in enumerate(arreglo): bg_color = colors.red 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', ini, fin, bg_color)]) story.append(table) d = Drawing(400, 200) data = [(11541548, 15618561, 56416646)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 60000000 bc.valueAxis.valueStep = 10000000 #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 = ['2017', '2018', '2019'] bc.groupSpacing = 10 bc.barSpacing = 2 #bc.categoryAxis.style = 'stacked' # Una variación del gráfico d.add(bc) #pprint.pprint(bc.getProperties()) story.append(d)
def draw_bar_chart(pdf_text, page_height): '''Currently generates a dummy graph. Next, need to pass in data that shall be the reactors temp throughout the sequence. ''' pdf_text.showPage() drawing = Drawing(400, 200) data = [(13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = [ 'Jan-99', 'Feb-99', 'Mar-99', 'Apr-99', 'May-99', 'Jun-99', 'Jul-99', 'Aug-99' ] drawing.add(bc) renderPDF.draw(drawing, pdf_text, inch, inch) return page_height
def draw_bar(bar_data=[], ax=[], items=[]): drawing = Drawing(500, 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 = 'song' leg.alignment = 'right' leg.boxAnchor = 'ne' leg.x = 465 leg.y = 220 leg.dxTextSpace = 10 leg.columnMaximum = 3 leg.colorNamePairs = items drawing.add(leg) drawing.add(bc) return drawing
def persona(request,id): if 'pdf' in request.GET: response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="persona_%s.pdf"'%id p=canvas.Canvas(response) drawing = Drawing(400, 200) data = [(13, 5, 20, 22, 37, 45, 19, 4),(14, 6, 21, 23, 38, 46, 20, 5)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = ['Jan-99','Feb-99','Mar-99','Apr-99','May-99','Jun-99','Jul-99','Aug-99'] drawing.add(bc) renderPDF.draw(drawing,p,100,480) p.showPage() p.save() return response else: return HttpResponse("la informacion de la persona %s" %id)
def sample1bar(data=[(13, 5, 20, 22, 37, 45, 19, 4)]): drawing = Drawing(400, 200) bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 60 bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.labels.fontName = fontName bc.barLabels.fontName = fontName bc.barLabelFormat = u'\xc5%s' catNames = u'J\xe4n Feb M\xe4r \xc4pr M\xe4y J\xfcn J\xfcl \xc4\xfcg'.split( ' ') bc.barLabelArray = catNames catNames = [n + '-99' for n in catNames] bc.categoryAxis.categoryNames = catNames drawing.add(bc) return drawing
def getdrawing(): from reportlab.graphics.shapes import Drawing from reportlab.lib import colors from reportlab.graphics.charts.barcharts import VerticalBarChart drawing = Drawing(400, 200) data = [(13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = "ne" bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = [ "Jan-99", "Feb-99", "Mar-99", "Apr-99", "May-99", "Jun-99", "Jul-99", "Aug-99" ] drawing.add(bc) return drawing
def createpdf(self, datas): drawing = Drawing(400, 200) # data = [(13, 5, 20),(14, 6, 21)] data = datas bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = ['Jan-99', 'Feb-99', 'Mar-99'] # bc.categoryAxis.categoryNames = ytype drawing.add(bc) drawing.add(String(250, 150, "ss", fontSize=14, fillColor=colors.red)) # drawing.add(String(250,150,des, fontSize=14,fillColor=colors.red)) renderPDF.drawToFile(drawing, 'report1.pdf', 'API')
def gen_bar_graphs(comparison_values, location, emission): bc = VerticalBarChart() labels = [] data = [] comparison_values.append([location, emission]) comparison_values.sort(key = lambda x: x[1]) for pair in comparison_values: labels.append(pair[0]) data.append(pair[1]) data = [data] location_index = labels.index(location) bc.x = -150 bc.y = -110 bc.height = 100 bc.width = 150 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = data[0][-1] + data[0][-1] * .1 distance = abs(int(math.log10(abs(data[0][-1])))) + 1 # distance of 1 significant figure to decimal point bc.valueAxis.valueStep = float(format(data[0][-1], '.1g')) / 3 bc.valueAxis.labelTextFormat = '%0.' + str(distance) + 'g' bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = labels for i in range(len(labels)): bc.bars[(0, i)].fillColor = colors.Color(166.0/255, 189.0/255, 219.0/255) bc.bars[(0, location_index)].fillColor = colors.Color(28.0/255, 144.0/255, 153.0/255) return bc
def getVerticalBarChart(): data = [(3, 18, 20), (14, 12, 21)] chart = VerticalBarChart() chart.data = data chart.valueAxis.valueMin = 0 chart.valueAxis.valueMax = 25 chart.valueAxis.valueStep = 5 chart.x = 5 chart.y = 5 chart.width = 240 chart.height = 100 chart.strokeColor = colors.black chart.fillColor = colors.yellow chart.groupSpacing = 0 chart.categoryAxis.categoryNames = ['A', 'B', 'C'] title = String(50, 110, 'Vertical Bar Chart', fontSize=14) drawing = Drawing(240, 120) drawing.add(title) drawing.add(chart) return drawing
def sample1bar(data=[(13, 5, 20, 22, 37, 45, 19, 4)]): drawing = Drawing(400, 200) bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 60 bc.valueAxis.valueStep = 15 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 catNames = string.split('Jan Feb Mar Apr May Jun Jul Aug', ' ') catNames = map(lambda n:n+'-99', catNames) bc.categoryAxis.categoryNames = catNames drawing.add(bc) return drawing
def pie_chart(data_for_pie): d = Drawing(400, 400) pc = Pie() pc.x = 100 pc.y = 210 pc.width = 170 pc.height = 170 pc.sideLabels = True pc.sideLabelsOffset = 0.05 car_name_lst = [] car_sales_lst = [] car_price_lst = [] data_for_pie = data_for_pie[1:] data_for_pie = sorted(data_for_pie, key=itemgetter(3), reverse=True) # so i can show 10 most popular cars for i in data_for_pie: car_name = i[1] car_name_lst.append(car_name) car_sales = i[3] car_sales_lst.append(car_sales) car_price = float(i[2].strip( "$")) #by default all the prices are in '', for example '18731.76' car_price_lst.append(car_price) pc.data = car_sales_lst[:10] pc.labels = list(set( car_name_lst[:10])) # by using set i wont have similar items in list d.add(pc, '') """have to done this because in task i have to calculate revenue on Xaxis and car name on Yaxis""" revenue_calculation_1 = car_sales_lst[:10] revenue_calculation_2 = car_price_lst[:10] car_revenue_list = [] for i in range(len(car_price_lst[:10])): reven = revenue_calculation_1[i] * revenue_calculation_2[i] car_revenue_list.append( int(reven)) #using int because its many digits after "," """bar chart """ data = [tuple(car_revenue_list) ] #for some reason bar chart accepts only [[]] or [()] bc = VerticalBarChart() bc.x = 50 bc.y = 0 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 7000000 bc.valueAxis.valueMax = 23000000 bc.valueAxis.valueStep = 1000000 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = list(set(car_name_lst[:10])) d.add(bc) return d
def xerar_barChart_serv(self): """ Xera un gráfico de barras co número de empregados por departamento nos últimos 8 meses a partir da base de datos :return: """ from reportlab.graphics.charts.barcharts import VerticalBarChart styles = getSampleStyleSheet() ptext = Paragraph( 'Número de empregados por departamento nos últimos 8 meses:', styles['Heading1']) self.story.append(ptext) d = Drawing(400, 200) p = self.cursor.execute( """SELECT (SELECT SUM(nempregados) FROM servizos WHERE (departamento = 'produccion')) AS prod, (SELECT SUM(nempregados) FROM servizos WHERE (departamento = 'finanzas')) AS finanzas, (SELECT SUM(nempregados) FROM servizos WHERE (departamento = 'informatica')) AS informatica, (SELECT SUM(nempregados) FROM servizos WHERE (departamento = 'publicidade')) FROM servizos AS publicidade """).fetchone() self.conn.text_factory = str data = [(25, 34, 14, 18, 36, 22, 19, p[0]), (26, 31, 22, 24, 16, 10, 18, p[1]), (34, 40, 18, 9, 25, 7, 2, p[2]), (29, 20, 19, 16, 34, 40, 15, p[3])] bc = VerticalBarChart() bc.x = 50 bc.y = 55 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 # 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 = 30 bc.categoryAxis.categoryNames = [ 'Xan-19', 'Feb-19', 'Mar-19', 'Abr-19', 'Mai-19', 'Xuñ-19', 'Xul-19', 'Ago-19' ] bc.groupSpacing = 10 bc.barSpacing = 2 # bc.categoryAxis.style = 'stacked' # Una variación del gráfico d.add(bc) self.story.append(d)
def generateversionchart((versionpickle, picklehash, imagedir, pickledir)): datapickle = open(os.path.join(pickledir, versionpickle), 'rb') data = cPickle.load(datapickle) datapickle.close() ## calculate the possible widths and heights of chart, bars, labels and so on maxversionstring = max(map(lambda x: len(x[0]), data)) barwidth = 15 chartwidth = len(data) * barwidth + 10 * len(data) maxvalue = max(map(lambda x: x[1], data)) step = int(math.log(maxvalue,10)) valueStep = pow(10,step) ## calculate a possible good value for startx and starty so labels are not cut off startx = max(10 + step * 10, 30) ## TODO: fiddle with values to create nicer looking graphs starty = maxversionstring * 10 + 20 drawheight = 225 + starty drawwidth = chartwidth + startx + 10 ## create the drawing drawing = Drawing(drawwidth, drawheight) bc = VerticalBarChart() bc.x = startx bc.y = starty bc.height = 200 bc.width = chartwidth bc.data = [tuple(map(lambda x: x[1], data))] bc.strokeColor = colors.white bc.valueAxis.valueMin = 0 bc.valueAxis.labels.fontSize = 16 bc.valueAxis.valueMax = maxvalue bc.valueAxis.valueStep = valueStep bc.categoryAxis.labels.boxAnchor = 'w' bc.categoryAxis.labels.dx = 0 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = -90 bc.categoryAxis.labels.fontSize = 16 bc.categoryAxis.categoryNames = map(lambda x: x[0], data) bc.barWidth = barwidth drawing.add(bc) outname = os.path.join(imagedir, picklehash) renderPM.drawToFile(drawing, outname, fmt='PNG') return picklehash
def generateversionchart((versionpickle, picklehash, imagedir, pickledir)): datapickle = open(os.path.join(pickledir, versionpickle), 'rb') data = cPickle.load(datapickle) datapickle.close() ## calculate the possible widths and heights of chart, bars, labels and so on maxversionstring = max(map(lambda x: len(x[0]), data)) barwidth = 15 chartwidth = len(data) * barwidth + 10 * len(data) maxvalue = max(map(lambda x: x[1], data)) step = int(math.log(maxvalue, 10)) valueStep = pow(10, step) ## calculate a possible good value for startx and starty so labels are not cut off startx = max(10 + step * 10, 30) ## TODO: fiddle with values to create nicer looking graphs starty = maxversionstring * 10 + 20 drawheight = 225 + starty drawwidth = chartwidth + startx + 10 ## create the drawing drawing = Drawing(drawwidth, drawheight) bc = VerticalBarChart() bc.x = startx bc.y = starty bc.height = 200 bc.width = chartwidth bc.data = [tuple(map(lambda x: x[1], data))] bc.strokeColor = colors.white bc.valueAxis.valueMin = 0 bc.valueAxis.labels.fontSize = 16 bc.valueAxis.valueMax = maxvalue bc.valueAxis.valueStep = valueStep bc.categoryAxis.labels.boxAnchor = 'w' bc.categoryAxis.labels.dx = 0 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = -90 bc.categoryAxis.labels.fontSize = 16 bc.categoryAxis.categoryNames = map(lambda x: x[0], data) bc.barWidth = barwidth drawing.add(bc) outname = os.path.join(imagedir, picklehash) renderPM.drawToFile(drawing, outname, fmt='PNG') return picklehash
def grafica(request): print "Genero el PDF[grafica]" response = HttpResponse(content_type='application/pdf') pdf_name = "Grafica.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, ) courses = [] styles = getSampleStyleSheet() header = Paragraph("Total de Cursos", styles['Heading2']) courses.append(header) styles = getSampleStyleSheet() d = Drawing(600, 300) conteo = Course.objects.count() # for i in Course.objects.all(): # print conteo data = [(conteo, )] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 200 bc.width = 300 bc.data = data bc.strokeColor = colors.blue bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 10 bc.valueAxis.valueStep = 1 #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 = 30 bc.categoryAxis.categoryNames = ['Cursos'] bc.groupSpacing = 10 bc.barSpacing = 2 d.add(bc) pprint.pprint(bc.getProperties()) courses.append(d) doc.build(courses) response.write(buff.getvalue()) buff.close() return response
def test_21_barCharts(self): from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph from reportlab.pdfbase import pdfmetrics from reportlab.graphics.shapes import Drawing from reportlab.pdfbase.ttfonts import TTFont from reportlab.graphics.charts.barcharts import VerticalBarChart pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) stylesheet = getSampleStyleSheet() elements = [] doc = SimpleDocTemplate("demo.pdf") elements.append( Paragraph('<font name="chsFont">JY.zenist.song - 俊毅</font>', stylesheet['Title'])) elements.append(Spacer(1, 12)) d = Drawing(400, 200) data = [(13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.groupSpacing = 10 bc.barSpacing = 2.5 bc.valueAxis._valueMin = 0 bc.valueAxis._valueMax = 50 bc.valueAxis._valueStep = 10 bc.categoryAxis.categoryNames = [ '1', '2', '3', '4', '5', '6', '7', '8' ] # bc.categoryAxis.style = 'stacked' d.add(bc) elements.append(d) doc.build(elements)
def test_21_barCharts(self): from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph from reportlab.pdfbase import pdfmetrics from reportlab.graphics.shapes import Drawing from reportlab.pdfbase.ttfonts import TTFont from reportlab.graphics.charts.barcharts import VerticalBarChart pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) stylesheet = getSampleStyleSheet() elements = [] doc = SimpleDocTemplate("demo.pdf") elements.append(Paragraph('<font name="chsFont">JY.zenist.song - 俊毅</font>', stylesheet['Title'])) elements.append(Spacer(1,12)) d = Drawing(400,200) data = [ (13,5,20,22,37,45,19,4), (14,6,21,23,38,46,20,5) ] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.groupSpacing = 10 bc.barSpacing = 2.5 bc.valueAxis._valueMin = 0 bc.valueAxis._valueMax = 50 bc.valueAxis._valueStep = 10 bc.categoryAxis.categoryNames = ['1','2','3','4','5','6','7','8'] # bc.categoryAxis.style = 'stacked' d.add(bc) elements.append(d) doc.build(elements)
def getBarChart(self, x_values, y_values): """Gets a bar chart with the given values Parameters: self: the class instance x_values: list - x values for the bar chart y_values: list of tuples - y values for the bar chart Returns: reportlab Vertical Bar Chart - bar chart with inputted values """ # Setting up sizing, position and colourings bc = VerticalBarChart() bc.x = 50 bc.y = 100 bc.height = 150 bc.width = 350 bc.strokeColor = colors.black # Setting up axis bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 300 bc.valueAxis.valueStep = 25 # Setting up position and angle of labels bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 0 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 65 # Adding bar labels bc.barLabelFormat = '%s' bc.barLabels.nudge = 5 bc.barLabels.boxAnchor = 's' bc.barLabels.dy = -1 # Changing bar colours bc.bars[0].fillColor = colors.green # Adding x and y data to the chart bc.categoryAxis.categoryNames = x_values bc.data = y_values return bc
def create_barchart(barchart_data): color=[green,red,blue,yellow,black] data_length=len(barchart_data["data"]) bar_chart = Drawing(400, 200) bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = barchart_data["data"] bc.fillColor=lightblue bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = list(barchart_data["label"][0]) for i in xrange(data_length): bc.bars[i].fillColor = color[i] bar_chart.add(bc) ###legend#### bar_leg = LineLegend() bar_leg.boxAnchor = 'sw' bar_leg.x = 100 bar_leg.y = -1 bar_leg.columnMaximum = 1 bar_leg.yGap = 0 bar_leg.deltax = 50 bar_leg.deltay = 0 bar_leg.dx = 10 bar_leg.dy = 1.5 bar_leg.fontSize = 10 bar_leg.alignment = 'right' bar_leg.dxTextSpace = 5 bar_leg.colorNamePairs = [(color[i],barchart_data["legend"][0][i]) for i in xrange(data_length)] bar_chart.add(bar_leg) return bar_chart
def draw_chart_bar(self, bar_data): # sort the amounts by the largest drawing = Drawing(400, 400) data = [bar_data['amounts']] bc = VerticalBarChart() bc.x = 50 bc.y = 10 bc.height = 350 bc.width = 350 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = bar_data['clients'] bc.valueAxis.valueStep = 1000 drawing.add(bc) renderPDF.draw(drawing, self.pdf, 30 * mm, 100 * mm)
def getVerticalBarChart(): data = [(df2.iloc[i, 38:43])] chart = VerticalBarChart() chart.data = data chart.valueAxis.valueMax = 90 chart.valueAxis.valueMin = 0 chart.valueAxis.valueStep = 10 chart.x = 5 chart.y = 5 chart.height = 100 chart.width = 240 chart.strokeColor = colors.black chart.fillColor = colors.pink chart.categoryAxis.categoryNames = ['Q1', 'Q2', 'Q3', 'Q4', 'Q5'] title = String(50, 120, 'Time (sec)', fontSize=14) drawing = Drawing(240, 120) drawing.add(title) drawing.add(chart) return drawing
def verticalbargraph(data, elements): drawing = Drawing(0, 200) # for indices bc = VerticalBarChart() bc.x = 0 # x,y define the left bottom of graph bc.y = 0 bc.height = 150 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 6 # next 3 lines is for naming indices bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 60 bc.categoryAxis.categoryNames = ['Jan-99', 'Feb-99', 'Mar-99', 'Apr-99', 'May-99', 'Jun-99', 'Jul-99', 'Aug-99'] drawing.add(bc) elements.append(drawing) elements.append(Spacer(1, 0.5 * inch))
def vertical_bar_graph(data, elements): drawing = Drawing(0, 200) # for indices bc = VerticalBarChart() bc.x =15 # x,y define the left bottom of graph bc.y = -130 bc.height = 250 bc.width = 500 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 6 # next 3 lines is for naming indices bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 60 bc.categoryAxis.categoryNames = ['Ques1', 'Ques2', 'Ques3', 'Ques4', 'Ques5', 'Ques6', 'Ques7', 'Ques8'] drawing.add(bc) elements.append(drawing) elements.append(Spacer(1, 0.5 * inch))
def __drawPage2Group(self, c): # 第二页,下方柱状图,所有内容书写范围为Pleft:10mm Pright:200mm Pheader:187mm Pfooter:10mm Pleft = START_X + 10 * mm Pright = START_X + 200 * mm Pheader = START_Y + 187 * mm Pfooter = START_Y + 10 * mm c.setFillColorRGB(1, 1, 1) c.rect(Pleft, Pheader - 160 * mm, 190 * mm, 120 * mm, fill=1) c.setFont("song", 15) c.setFillColorRGB(1, 0, 1) c.drawString(Pleft + 3 * mm, Pheader - 50 * mm, "漏洞信息分组") a = [] familyids = [] for familyid in self.scanParams['statsFamily']: a.append(self.scanParams['statsFamily'][familyid]['total']) familyids.append(str(familyid)) print a, familyids d = Drawing(400, 300) data = [a] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 245 bc.width = 400 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 5 bc.valueAxis.valueStep = 1 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = familyids bc.categoryAxis.labels.fontName = 'song' bc.categoryAxis.labels.fontSize = 10 d.add(bc) renderPDF.draw(d, c, Pleft + 10 * mm, Pheader - 160 * mm)
def myBarChart(data): drawing = Drawing(400, 200) bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.barWidth = .3*inch bc.groupSpacing = .2 * inch bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 100 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 catNames = string.split('Trial1 Trial2 Trial3 Trial4 Trial5') bc.categoryAxis.categoryNames = catNames bc.bars[0].fillColor = colors.blue bc.bars[1].fillColor = colors.lightblue drawing.add(bc) return drawing
def getChart(self): d = Drawing(300, 200) chart = VerticalBarChart() chart.width = 560 chart.height = 460 chart.x = 50 chart.y = 50 chart.height = 125 chart.width = 300 chart.strokeColor = colors.black chart.valueAxis.valueMin = 0 chart.valueAxis.valueMax = 100 chart.valueAxis.valueStep = 10 chart.categoryAxis.labels.boxAnchor = 'ne' chart.categoryAxis.labels.dx = 8 chart.categoryAxis.labels.dy = -2 chart.categoryAxis.labels.angle = 0 chart.data = self.marks#self.averages chart.categoryAxis.categoryNames = self.chartXValues#self.studentNumbers d.add(chart) #d.save(fnRoot='test', formats=['png', 'pdf']) return d
def __drawPage2Owasp(self, c): # 第二页,右侧OWASP图,所有内容书写范围为Pleft:120mm Pright:200mm Pheader:247mm Pfooter:80mm Pleft = START_X + 100 * mm Pright = START_X + 200 * mm Pheader = START_Y + 247 * mm Pfooter = START_Y + 80 * mm c.setFillColorRGB(1, 1, 1) c.rect(Pleft, Pheader - 80 * mm, 100 * mm, 80 * mm, fill=1) c.setFont("song", 15) c.setFillColorRGB(1, 0, 1) c.drawString(Pleft + 2 * mm, Pheader - 10 * mm, "OWASP TOP10占比分布") d = Drawing(300, 200) data = [(13, 5, 20, 22, 37, 45, 19, 4, 5, 10)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 130 bc.width = 180 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = [ '1.SQL注入', '2.失效的身份认证和会话管理', '3.跨站脚本(XSS)', '4.不安全的直接引用对象', '5.安全配置错误', '6.敏感信息泄漏', '功能级访问控制缺失', '8.跨站请求伪造(CSRF)', '9.使用含有已知漏洞的组件', '10.未验证的重定向和转发' ] bc.categoryAxis.labels.fontName = 'song' bc.categoryAxis.labels.fontSize = 5 d.add(bc) renderPDF.draw(d, c, Pleft + 2 * mm, Pheader - 80 * mm)
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 __init__(self, width, height, labels, data): IRender.__init__(self, width, height, labels, data) #self.w = self.width #self.h = self.height #data = [[int(line[1])] for line in self.data] #labels = [line[0] for line in self.data] #plot = cairoplot.VerticalBarPlot('/tmp/tmp.png', data, self.w*2, self.h*2, x_labels=labels, grid=True, display_values=True) ##plot.font_size *= 2 #plot.render() #plot.commit() #with open('/tmp/tmp.png') as f: # self.image = Image(StringIO(f.read()), self.w, self.h) bc = VerticalBarChart() bc.x = 40 bc.y = 50 bc.height = self.height - 60 bc.width = self.width - 60 bc.data = [[int(line[1]) for line in self.data]] bc.strokeColor = colors.white bc.bars.strokeColor = RED bc.bars.fillColor = RED bc.bars[0].fillColor = RED bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = max([int(line[1]) for line in self.data]) bc.valueAxis.valueStep = bc.valueAxis.valueMax/10 if not bc.valueAxis.valueStep: bc.valueAxis.valueStep = 1 bc.valueAxis.valueMax = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = [line[0] for line in self.data] self.drawing = Drawing(self.width, self.height) self.drawing.add(bc)
from reportlab.graphics.charts.barcharts import VerticalBarChart draw = Drawing(640, 320) data = [ (13, 25, 35, 4, 30, 35), (15, 15, 20, 25, 33, 38) ] vbc = VerticalBarChart() vbc.x = 120 vbc.y = 50 vbc.height = 125 vbc.width = 300 vbc.data = data vbc.strokeColor = colors.black vbc.valueAxis.valueMin = 0 vbc.valueAxis.valueMax = 50 vbc.valueAxis.valueStep = 10 vbc.categoryAxis.labels.boxAnchor = 'ne' vbc.categoryAxis.labels.dx = 8 vbc.categoryAxis.labels.dy = -2 vbc.categoryAxis.labels.angle = 30 vbc.categoryAxis.categoryNames = ['Jan-99','Feb-99','Mar-99','Apr-99', 'May-99','Jun-99','Jul-99','Aug-99'] draw.add(vbc) renderPDF.drawToFile(draw, "pdfs/chart01.pdf", "Gráficos - Bar Chart")
def main(argv): parser = argparse.ArgumentParser() # the following options are provided on the commandline parser.add_argument("-f", "--file", action="store", dest="cleanupfile", help="path to cleanup result file", metavar="FILE") parser.add_argument("-o", "--output", action="store", dest="outputfile", help="path to output file", metavar="FILE") args = parser.parse_args() # path of the gzip compressed releases file if args.cleanupfile is None: parser.error("cleanup file missing") if args.outputfile is None: parser.error("output file missing") if os.path.isdir(args.outputfile): print("outputfile %s is a directory, cannot overwrite" % args.outputfile, file=sys.stderr) sys.exit(1) if not os.path.exists(args.cleanupfile): print("result file missing", file=sys.stderr) sys.exit(1) unique_releases = set() cleanupfile = open(args.cleanupfile, 'r') # store the number of the last release found with a small in the # dataset. This is to ensure that the right amount of columns will # be generated in the end through an ugly hack max_release_number = 0 # store the release number for releases with a smell for l in cleanupfile: if 'https://www.discogs.com/release/' in l and ' -- ' in l: #release_number = int(l.rsplit('/', 1)[1]) release_number = int(l.rsplit('/', 1)[1].split()[0]) max_release_number = max(max_release_number, release_number) unique_releases.add(release_number) else: print(l) cleanupfile.close() # count the number of releases, with a smell statistics = collections.Counter() statistics.update(map(lambda x: x//1000000, unique_releases)) last_index = max_release_number//1000000 bardata = (sorted(statistics.items())) barwidth = 20 # sometimes some dummy data need to be inserted to # ensure that empty bars are generated if needed if len(bardata) != last_index: for i in range(0, last_index): if bardata[i][0] != i: for d in range(0, bardata[i][0] - i): bardata.append((i, 0)) bardata.sort() print("Unique releases:", len(unique_releases)) print(bardata) maximumvalue = max(map(lambda x: x[1], bardata)) step = int(math.log(maximumvalue, 10)) valueStep = pow(10, step) # calculate a possible good value for startx so labels are not cut off startx = max(10 + step * 10, 30) # make sure that the chart is large enough chartwidth = len(bardata) * barwidth + 10 * len(bardata) drawheight = 225 drawwidth = chartwidth + startx + 20 # create the drawing that the barchart will be added to drawing = Drawing(drawwidth, drawheight) barchart = VerticalBarChart() barchart.x = startx barchart.y = 20 barchart.height = 200 barchart.width = chartwidth barchart.data = [tuple(map(lambda x: x[1], bardata))] barchart.strokeColor = colors.white barchart.valueAxis.valueMin = 0 barchart.valueAxis.labels.fontSize = 16 barchart.valueAxis.valueMax = maximumvalue barchart.valueAxis.valueStep = valueStep barchart.categoryAxis.labels.boxAnchor = 'w' barchart.categoryAxis.labels.dx = 0 barchart.categoryAxis.labels.dy = -10 #barchart.categoryAxis.labels.angle = -90 barchart.categoryAxis.labels.fontSize = 16 barchart.categoryAxis.categoryNames = list(map(lambda x: str(x[0]), bardata)) barchart.barWidth = barwidth drawing.add(barchart) renderPM.drawToFile(drawing, args.outputfile, fmt='PNG')
def reporte4_pdf(request, pk_proyecto): from reportlab.graphics.shapes import Drawing, Rect, String, Group, Line from reportlab.graphics.charts.barcharts import VerticalBarChart proy = Proyecto.objects.get(id=pk_proyecto) story = [] estilo = getSampleStyleSheet() import pprint estiloHoja = getSampleStyleSheet() cabecera = estiloHoja['Heading2'] cabecera.pageBreakBefore = 0 cabecera.keepWithNext = 0 cabecera.backColor = colors.white cabecera.spaceAfter = 0 cabecera.spaceBefore = 0 parrafo = Paragraph('', cabecera) story.append(parrafo) parrafo = Paragraph('CUARTO INFORME DEL' + '"' + proy.nombre_largo + '" : ', cabecera) story.append(parrafo) parrafo = Paragraph('_' * 66, cabecera) story.append(parrafo) cabecera2 = estiloHoja['Heading2'] cabecera2.pageBreakBefore = 0 cabecera2.keepWithNext = 0 cabecera2.backColor = colors.white parrafo = Paragraph( 'GRAFICO DE TIEMPO ESTIMADO Y EJECUTADO POR SPRINT DEL PROYECTO' + '"' + proy.nombre_largo + '"', cabecera2) story.append(parrafo) d = Drawing(400, 200) sprints = Sprint.objects.filter(proyecto=proy) print sprints listasprint = [] listaplan = [] listaejec = [] for sp in sprints: listasprint.append(sp.nombre) US = UserStory.objects.filter(sprint=sp) print US tarea = Tarea.objects.filter(user_story_id= US) totalus = 0 sumatarea = 0 for u in US: totalus += u.estimacion for t in tarea: sumatarea += t.horas_de_trabajo listaejec.append(totalus) listaplan.append(sumatarea) mayor = 0 for j in listaejec: if j > mayor: mayor = j for j in listaplan: if j > mayor: mayor = j data = [listaplan, listaejec] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = mayor + 10 bc.valueAxis.valueStep = 10 #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 = 30 bc.categoryAxis.categoryNames = listasprint bc.groupSpacing = 10 bc.barSpacing = 2 d.add(bc) pprint.pprint(bc.getProperties()) story.append(d) cabecera2 = estiloHoja['Heading2'] cabecera2.pageBreakBefore = 0 cabecera2.keepWithNext = 0 cabecera2.backColor = colors.white parrafo = Paragraph('ROJO = TIEMPO ESTIMADO', cabecera2) story.append(parrafo) cabecera2 = estiloHoja['Heading2'] cabecera2.pageBreakBefore = 0 cabecera2.keepWithNext = 0 cabecera2.backColor = colors.white parrafo = Paragraph('VERDE = TIEMPO EJECUTADO', cabecera2) story.append(parrafo) story.append(Spacer(0, 20)) parrafo = Paragraph('_' * 66, cabecera) story.append(parrafo) #parrafo = Paragraph('FIN DE CUARTO INFORME' + ' ' * 100 + '(' + str(datetime.date.today()) + ')', cabecera) parrafo = Paragraph('FIN DE CUARTO INFORME', cabecera) story.append(parrafo) buff = BytesIO() doc = SimpleDocTemplate(buff, pagesize=letter, rightMargin=40, leftMargin=40, topMargin=60, bottomMargin=18, ) doc.build(story) response = HttpResponse(content_type='application/pdf') pdf_name = "Reporte.pdf" response.write(buff.getvalue()) buff.close() return response
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 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 generate_certificate(elements): styles = ParagraphStyle( name='Normal', fontName='Helvetica-Bold', fontSize=15, alignment=1, ) elements.append(Spacer(1, 0.5 * inch)) i = Paragraph(str("candidate performance vs average performance"), styles) elements.append(i) elements.append(Spacer(1, 0.1 * inch)) drawing = Drawing(0, 200) # for indices data = [ (13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5) ] # data for drawing bar graphs bc = VerticalBarChart() bc.x = 0 # x,y define the left bottom of graph bc.y = 0 bc.height = 150 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 6 # next 3 lines is for naming indices bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 60 bc.categoryAxis.categoryNames = ['Jan-99', 'Feb-99', 'Mar-99', 'Apr-99', 'May-99', 'Jun-99', 'Jul-99', 'Aug-99'] drawing.add(bc) elements.append(drawing) elements.append(Spacer(1, 0.5 * inch)) drawing = Drawing(0, 175) # for indices lc = HorizontalLineChart() lc.x = 0 lc.y = 10 lc.height = 150 lc.width = 300 lc.data = data lc.joinedLines = 1 catnames = 'Jan Feb Mar Apr May Jun Jul Aug'.split(' ') lc.categoryAxis.categoryNames = catnames lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 15 lc.lines[0].strokeWidth = 2 lc.lines[1].strokeWidth = 1.5 drawing.add(lc) elements.append(drawing) drawing = Drawing(0, 400) # for indices data = [ ((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)), ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6)) ] elements.append(Spacer(1, 0.1 * inch)) i = Paragraph(str("candidate performance vs average performance"), styles) elements.append(i) elements.append(Spacer(1, 0.1 * inch)) lp = LinePlot() lp.x = 0 lp.y = 50 lp.height = 300 lp.width = 600 lp.data = data lp.joinedLines = 1 lp.lines[0].symbol = makeMarker('FilledCircle') lp.lines[1].symbol = makeMarker('Circle') lp.lineLabelFormat = '%2.0f' lp.strokeColor = colors.black lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 5 lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5] lp.xValueAxis.labelTextFormat = '%2.1f' lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 7 lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6] drawing.add(lp) elements.append(drawing) elements.append(Spacer(1, 0.1 * inch)) drawing = Drawing(100, 350) pc = Pie() pc.x = 65 pc.y = 15 pc.width = 300 pc.height = 300 pc.data = [10, 20, 30, 40, 50, 60] pc.labels = ['a', 'b', 'c', 'd', 'e', 'f'] pc.slices.strokeWidth = 0.5 pc.slices[3].popout = 10 pc.slices[3].strokeWidth = 2 pc.slices[3].strokeDashArray = [2, 2] pc.slices[3].labelRadius = 1.75 pc.slices[3].fontColor = colors.red drawing.add(pc) elements.append(drawing) elements.append(Spacer(1, 0.7 * inch)) styles = ParagraphStyle( name='Normal', fontName='Helvetica', fontSize=15, alignment=0, ) elements.append(Spacer(1, 0.5* inch)) i = Paragraph(str("Please click on black square to play the video."), styles) elements.append(i) elements.append(platypus.flowables.Macro('canvas.saveState()')) elements.append(platypus.flowables.Macro('canvas.linkURL("fun.mp4",(400,510,410,500),relative=0,thickness=10)')) elements.append(platypus.flowables.Macro('canvas.restoreState()')) return elements
def generar_pdf_libros_mes(request): # print "Genero el PDF" fecha_libro = b mes = 0 anio = 0 story = [] response = HttpResponse(content_type="application/pdf") pdf_name = "reporte_libro.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) reporte_libro = [] styles = getSampleStyleSheet() fichero_imagen = "biblioteca/media/images/Reports-banner.jpg" imagen_logo = Image(os.path.realpath(fichero_imagen), width=400, height=100) story.append(imagen_logo) reporte_libro.append(imagen_logo) fecha_reporte = Paragraph("Fecha del reporte: " + str(date.today()), styles["Heading1"]) reporte_libro.append(fecha_reporte) header = Paragraph( "Reporte de libros prestados en el mes " + str(fecha_libro.month) + " del " + str(fecha_libro.year), styles["Normal"], ) reporte_libro.append(header) headings = ("Nombre", "Fecha devolución", "Fecha préstamo") # fecha_libro = reportes.cleaned_data['fecha_consulta'] mes = b.month anio = b.year i = mes j = mes all_libros = [ (p.libro.nombre_libro, p.fecha_devolucion, p.fecha_prestamo) for p in Prestamo.objects.filter(fecha_prestamo__month=mes, fecha_prestamo__year=anio) ] # print all_libros t = Table([headings] + all_libros) 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 titulos = Paragraph( "Gráfica comparativa de libros prestados en el mes " + str(fecha_libro.month) + " y el mes anterior a éste. ", estilo["title"], ) drawing = Drawing(400, 200) data = [(x1, y1)] 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.red bc.strokeColor = colors.black bc.fillColor = colors.silver bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = y1 + 10 try: o = y1 / 2 if type(o) == "float": bc.valueAxis.valueStep = y1 + 0.5 if type(o) == "int": bc.valueAxis.valueStep = o except: "Nos se puede" bc.categoryAxis.labels.boxAnchor = "ne" bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 0 if mes == 1: i = mes + 11 else: j = mes - 1 bc.categoryAxis.categoryNames = [datetime.date(anio, j, 1).strftime("%B"), datetime.date(anio, i, 1).strftime("%B")] 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 reporte_libro.append(Spacer(0, inch * 0.1)) reporte_libro.append(Spacer(0, inch * 0.1)) reporte_libro.append(t) reporte_libro.append(Spacer(0, inch * 0.1)) reporte_libro.append(Spacer(0, inch * 0.1)) reporte_libro.append(titulos) reporte_libro.append(drawing) doc.build(reporte_libro) response.write(buff.getvalue()) buff.close() return response
def generar_pdf_usuarios_mes(request): #print "Genero el PDF" mes =0 anio =0 story =[] fecha_usuarios = x response = HttpResponse(content_type='application/pdf') pdf_name = "reporte_usuarios_mes.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) story.append(imagen_logo) reportes.append(imagen_logo) header = Paragraph("Fecha del reporte: "+str(date.today()), styles['Heading1']) header2 = Paragraph("Reporte de los usuarios que prestaron espacio en el mes "+str(fecha_usuarios.month)+" del "+str(fecha_usuarios.year), styles['Normal']) salto_linea = Paragraph("\n\n", styles["Normal"]) reportes.append(Spacer(1, 12)) reportes.append(header) #reportes.append(Spacer(1, 12)) reportes.append(header2) reportes.append(Spacer(1, 12)) headings = ('Fecha préstamo', 'Usuario', 'Nombre del espacio', 'Fecha devolución') mes = x.month anio = x.year n = mes f = mes allreportes = [(i.fecha_prestamo, i.usuario.nombre, i.espacio.nombre_espacio, i.fecha_devolucion) for i in Prestamo.objects.filter(fecha_prestamo__month =mes,fecha_prestamo__year = anio)] #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 titulo1 = Paragraph("Gráfica comparativa de usuarios que prestaron espacios en el mes "+str(fecha_usuarios.month)+" y el mes anterior a éste. ", estilo['title']) drawing = Drawing(400, 200) data = [(u1, u2)] 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.red bc.strokeColor = colors.black bc.fillColor = colors.silver bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = u2+10 try: o = u2 / 2 if type(o) == 'float': bc.valueAxis.valueStep = u2+0.5 if type(o) == 'int': bc.valueAxis.valueStep = o except: "No se puede" bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 0 if mes == 1: n = mes + 11 else: f = mes - 1 bc.categoryAxis.categoryNames = [ datetime.date(anio, f, 1).strftime('%B'), datetime.date(anio, n, 1).strftime('%B')] 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 reportes.append(t) reportes.append(Spacer(0, inch*.1)) reportes.append(Spacer(0, inch*.1)) reportes.append(titulo1) reportes.append(drawing) doc.build(reportes) response.write(buff.getvalue()) buff.close() return response
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 generate_certificate(elements): style = TableStyle([('TEXTALIGN', (0, 0), (-1, -1), 'CENTER'), ('TEXTCOLOR', (0, 0), (-1, -1), colors.red), ('VALIGN', (0, 0), (0, -1), 'TOP'), ('INNERGRID', (0, 0), (-1, -1), 0.50, colors.red), ('BOX', (0, 0), (-1, -1), 0.50, colors.green), ('BACKGROUND', (0, 0), (-1, -1), colors.blue), ]) s = getSampleStyleSheet() s = s["BodyText"] s.wordWrap = "RGB" styles = ParagraphStyle( name='Normal', fontName='Helvetica-Bold', fontSize=15, alignment=1, ) elements.append(Spacer(1, 0.5 * inch)) i = Paragraph(str("candidate performance vs average performance"), styles) elements.append(i) elements.append(Spacer(1, 0.1 * inch)) drawing = Drawing(0, 200) # for indices data = [ (13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5) ] # data for drawing bar graphs bc = VerticalBarChart() bc.x = 0 # x,y define the left bottom of graph bc.y = 0 bc.height = 150 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 6 # next 3 lines is for naming indices bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 60 bc.categoryAxis.categoryNames = ['Jan-99', 'Feb-99', 'Mar-99', 'Apr-99', 'May-99', 'Jun-99', 'Jul-99', 'Aug-99'] drawing.add(bc) elements.append(drawing) elements.append(Spacer(1, 0.5 * inch)) drawing = Drawing(0, 175) # for indices lc = HorizontalLineChart() lc.x = 0 lc.y = 10 lc.height = 150 lc.width = 300 lc.data = data lc.joinedLines = 1 catNames = 'Jan Feb Mar Apr May Jun Jul Aug'.split(' ') lc.categoryAxis.categoryNames = catNames lc.categoryAxis.labels.boxAnchor = 'n' lc.valueAxis.valueMin = 0 lc.valueAxis.valueMax = 60 lc.valueAxis.valueStep = 15 lc.lines[0].strokeWidth = 2 lc.lines[1].strokeWidth = 1.5 drawing.add(lc) elements.append(drawing) drawing = Drawing(0, 400) # for indices data = [ ((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)), ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6)) ] elements.append(Spacer(1, 0.1 * inch)) i = Paragraph(str("candidate performance vs average performance"), styles) elements.append(i) elements.append(Spacer(1, 0.1 * inch)) lp = LinePlot() lp.x = 0 lp.y = 50 lp.height = 300 lp.width = 600 lp.data = data lp.joinedLines = 1 lp.lines[0].symbol = makeMarker('FilledCircle') lp.lines[1].symbol = makeMarker('Circle') lp.lineLabelFormat = '%2.0f' lp.strokeColor = colors.black lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 5 lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5] lp.xValueAxis.labelTextFormat = '%2.1f' lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 7 lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6] drawing.add(lp) elements.append(drawing) elements.append(Spacer(1, 0.1 * inch)) drawing = Drawing(100, 350) pc = Pie() pc.x = 65 pc.y = 15 pc.width = 300 pc.height = 300 pc.data = [10, 20, 30, 40, 50, 60] pc.labels = ['a', 'b', 'c', 'd', 'e', 'f'] pc.slices.strokeWidth = 0.5 pc.slices[3].popout = 10 pc.slices[3].strokeWidth = 2 pc.slices[3].strokeDashArray = [2, 2] pc.slices[3].labelRadius = 1.75 pc.slices[3].fontColor = colors.red drawing.add(pc) elements.append(drawing) elements.append(Spacer(1, 0.5 * inch)) return elements
from reportlab.graphics.charts.barcharts import VerticalBarChart drawing = Drawing(400, 200) data = [ (13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5) ] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 50 bc.valueAxis.valueStep = 10 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = ['Jan-99','Feb-99','Mar-99', 'Apr-99','May-99','Jun-99','Jul-99','Aug-99'] drawing.add(bc) draw(drawing, 'Simple bar chart with two data series')
def generar_pdf_libros_mes(request): print "Genero el PDF" mes = 0 anio = 0 story=[] response = HttpResponse(content_type='application/pdf') pdf_name = "reporte_libro.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, ) reporte_libro = [] styles = getSampleStyleSheet() fichero_imagen="biblioteca/media/images/Reports-banner.jpg" imagen_logo = Image(os.path.realpath(fichero_imagen),width=400,height=100) story.append(imagen_logo) reporte_libro.append(imagen_logo) fecha_reporte = Paragraph("Fecha del reporte: "+str(date.today()), styles['Heading1']) reporte_libro.append(fecha_reporte) header = Paragraph("Listado de Libros que Fueron prestados en el mes", styles['Normal']) reporte_libro.append(header) headings = ('Nombre', 'Fecha devolución','Fecha Prestamo') #fecha_libro = reportes.cleaned_data['fecha_consulta'] mes = b.month anio = b.year i = mes j = mes all_libros = [(p.libro.nombre_libro, p.fecha_devolucion, p.fecha_prestamo) for p in Prestamo.objects.filter(fecha_prestamo__month = mes, fecha_prestamo__year = anio)] print all_libros t = Table([headings] + all_libros) 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 drawing = Drawing(400, 200) data = [(x1, y1)] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.bars[0].fillColor = colors.yellow bc.bars[1].fillColor = colors.red bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = y1+10 try: o = y1 / 2 if type(o) == 'float': bc.valueAxis.valueStep = y1+0.5 if type(o) == 'int': bc.valueAxis.valueStep = o except: "Nos se puede" bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 0 if mes == 1: i = mes + 11 else: j = mes - 1 bc.categoryAxis.categoryNames = [ datetime.date(anio, j, 1).strftime('%B'), datetime.date(anio, i, 1).strftime('%B')] 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 reporte_libro.append(drawing) reporte_libro.append(t) doc.build(reporte_libro) response.write(buff.getvalue()) buff.close() return response
def auto_chart(self, allcount, failcount, faillist, info, pathnow) : from reportlab.graphics.shapes import Drawing from reportlab.graphics import renderPDF from reportlab.graphics.charts.barcharts import VerticalBarChart from reportlab.lib import colors info = info.replace(',', ',') info = info.split(',') c = 0 infolist = ['project name:','version:','test type:','tester:','results:'] testtype = info[2] if failcount == 0 : info.append('pass') elif failcount != 0 : info.append('fail') drawing = Drawing(800,900) data = [(failcount,),((allcount - failcount),)] bc = VerticalBarChart() bc.x = 250 bc.y = 110 bc.height = 250 bc.width = 300 bc.groupSpacing = 25 bc.data = data bc.strokeColor = colors.black bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 16 bc.valueAxis.valueStep = 1 bc.categoryAxis.labels.boxAnchor = 'ne' bc.categoryAxis.labels.dx = 4 bc.categoryAxis.labels.dy = -2 bc.categoryAxis.labels.angle = 30 bc.categoryAxis.categoryNames = ['%s' %info[1],] bc.categoryAxis.style = 'stacked' drawing.add(bc) drawing.add(String(350,860,"Test Report!",fontSize=25, fillColor=colors.black)) for i in infolist : xt = '%s%s' %(i,info[0]) try: x_wid = self.get_width(xt, 14, 1) except Exception as e: print(e) x = 100 + x_wid/2 y = 800 - c c += 25 drawing.add(self.cn_process(i+info[0], x, y, pathnow)) info.remove(info[0]) xt2 = 100+(self.get_width("this %s has run %2d test case(s). pass: %2d, fail: %2d." %(testtype,allcount,(allcount-failcount),failcount),14,1)/2) drawing.add(self.cn_process("this %s has run %2d test case(s). pass: %2d, fail: %2d." %(testtype,allcount,(allcount-failcount),failcount), xt2, 650, pathnow)) if failcount != 0 : xt3 = 100 +(self.get_width("failed details: ",14,1)/2) drawing.add(self.cn_process("failed details: ", xt3, 625, pathnow)) drawing.add(self.cn_process("Dept.QA", 640, 80, pathnow)) y2 = 625 for m in faillist : y2 -= 25 xt3 = 130 + (self.get_width(m,14,1)/2) if xt3 > 500 : m = m[:65] + '...' xt3 = 130 + (self.get_width(m,14,1)/2) drawing.add(self.cn_process(m, xt3, y2, pathnow)) renderPDF.drawToFile(drawing, 'D:/WebZ/test report.pdf')
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 relatorio_final(request, id): analise = get_object_or_404(AnaliseSensorial, id=id) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="relatorio.pdf"' # Iniciando variáveis importantes buff = BytesIO() # Criando arquivos com as dimensões de margem arquivo = SimpleDocTemplate( buff, rightMargin=40, leftMargin=40, topMargin=40, bottomMargin=18) elements = [] styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='centered', alignment=TA_JUSTIFY)) styles.add(ParagraphStyle(name='body', alignment=TA_JUSTIFY, fontSize=10)) # Iniciando um dicionário de dados sobre o pdf dictionary = {'analise': analise, 'elements': elements, 'styles': styles} # Renderizando o título do documento dictionary['size'] = '20' dictionary['text'] = 'Relatório sobre a analise sensorial: ' + \ str(analise.nome) dictionary['style'] = 'title' dictionary['spacer'] = 20 dictionary['type'] = 'normal' put_string(dictionary) #------------------------------------------------------------------------- # Renderizando informações sobre a análise dictionary['size'] = '14' dictionary['spacer'] = 12 dictionary['style'] = 'BodyText' dictionary['type'] = 'normal' dictionary['text'] = 'Nome: ' + str(analise.nome) put_string(dictionary) dictionary['text'] = 'Descrição: ' + str(analise.descricao) put_string(dictionary) dictionary['text'] = 'Quantidade de provadores: ' + \ str(analise.quantidade_pessoas) put_string(dictionary) dictionary['text'] = 'Quantidade de amostras: ' + \ str(analise.quantidade_amostras) put_string(dictionary) dictionary['text'] = 'Fabricante: ' + str(analise.user.first_name) put_string(dictionary) #------------------------------------------------------------------------- # Recebendo perguntas perguntas = Pergunta.objects.filter(analise_id=analise.id) # Renderizar as perguntas dictionary['elements'].append(Spacer(1, 24)) dictionary['type'] = 'negrito' for pergunta in perguntas: dictionary['text'] = pergunta.pergunta dictionary['size'] = '18' dictionary['type'] = 'negrito' put_string(dictionary) for index in range(analise.quantidade_amostras): dictionary['text'] = 'Amostra %s' % transcricao_numero_letra(index) dictionary['type'] = 'Normal' dictionary['size'] = '14' put_string(dictionary) grafico = Drawing(400, 150) cartoon = VerticalBarChart() # Colocar tamanho do gráfico cartoon.height = 125 cartoon.width = 500 # Colocando os dados no gráfico cartoon.strokeColor = colors.black # Aplicando valores maximos e minimos para o gráfico cartoon.valueAxis.valueMin = 0 # Aqui ficará a 'quantidade_pessoas' cartoon.valueAxis.valueMax = analise.quantidade_pessoas cartoon.valueAxis.valueStep = (analise.quantidade_pessoas / 10) # Arrumando as labels do gráfico cartoon.categoryAxis.labels.boxAnchor = 'ne' cartoon.categoryAxis.labels.dx = 10 # Perguntas sim ou nção # Aqui ficará a divisão if pergunta.tipo == 'PSN': respostas = Boolean.objects.filter( analise_id=id, pergunta_id=pergunta.id, amostra__tipo=transcricao_numero_letra(index) ) contador_true = 0 contador_false = 0 for resposta in respostas: if resposta.resposta == True: contador_true += 1 else: contador_false += 1 # Caracterizando o grafico de acordo data = [(contador_true, contador_false), ] cartoon.data = data cartoon.categoryAxis.categoryNames = ['Sim', 'Não'] cartoon.bars[(0, 0)].fillColor = colors.green cartoon.bars[(0, 1)].fillColor = colors.red grafico.add(cartoon) elements.append(grafico) elements.append(Spacer(1, 20)) total = contador_true + contador_false porcentagem_sim = porcentagem(contador_true, total) porcentagem_nao = porcentagem(contador_false, total) dictionary['text'] = """Nessa questão {por_sim:.2f}{symbol} dos provadores responderam SIM - {n} pessoa(s) - e {por_nao:.2f}{symbol} responderam NÃO - {n2} pessoa(s).""" .format(symbol="%", por_sim=(porcentagem_sim), n=contador_true, por_nao=porcentagem_nao, n2=contador_false) dictionary['type'] = "Normal" dictionary['size'] = "12" put_string(dictionary) elements.append(Spacer(1, 20)) # Perguntas Hedônicas elif pergunta.tipo == 'PHD': respostas = Hedonica.objects.filter( analise_id=id, pergunta_id=pergunta.id, amostra__tipo=transcricao_numero_letra(index) ) # Variáveis h_01 = 0 h_02 = 0 h_03 = 0 h_04 = 0 h_05 = 0 h_06 = 0 h_07 = 0 h_08 = 0 h_09 = 0 for resposta in respostas: if resposta.resposta == 1: h_01 += 1 elif resposta.resposta == 2: h_02 += 1 elif resposta.resposta == 3: h_03 += 1 elif resposta.resposta == 4: h_04 += 1 elif resposta.resposta == 5: h_05 += 1 elif resposta.resposta == 6: h_06 += 1 elif resposta.resposta == 7: h_07 += 1 elif resposta.resposta == 8: h_08 += 1 else: h_09 += 1 data = [(h_01, h_02, h_03, h_04, h_05, h_06, h_07, h_08, h_09,)] cartoon.data = data cartoon.categoryAxis.categoryNames = [ 'Desgostei extremamente', 'Desgostei muito', 'Desgostei moderadamente', 'Desgostei ligeiramente', 'Nem gostei / Nem desgostei', 'Gostei ligeiramente', 'Gostei moderadamente', 'Gostei muito', 'Gostei muitíssimo' ] cartoon.bars[(0, 0)].fillColor = colors.green cartoon.bars[(0, 1)].fillColor = colors.red cartoon.bars[(0, 2)].fillColor = colors.yellow cartoon.bars[(0, 3)].fillColor = colors.blue cartoon.bars[(0, 4)].fillColor = colors.pink cartoon.bars[(0, 5)].fillColor = colors.gray cartoon.bars[(0, 6)].fillColor = colors.purple cartoon.bars[(0, 7)].fillColor = colors.black cartoon.bars[(0, 8)].fillColor = colors.orange cartoon.categoryAxis.labels.dx = 8 cartoon.categoryAxis.labels.dy = -2 cartoon.categoryAxis.labels.angle = 30 grafico.add(cartoon) elements.append(grafico) elements.append(Spacer(1, 60)) # Variável de menor nome q_p = h_01 + h_02 + h_03 + h_04 + h_05 + h_06 + h_07 + h_08 + h_09 dictionary['size'] = '12' dictionary['type'] = 'Normal' dictionary['text'] = "Resultados: " dictionary['spacer'] = 20 put_string(dictionary) dictionary['spacer'] = 10 if h_01 != 0: dictionary['text'] = """>{p_01:.2f}{symbol} - {n_01} pessoa(s) - responderam que <b>desgostaram extremamente</b> dessa amostra.""".format(symbol="%", p_01=porcentagem(h_01, q_p), n_01=h_01) put_string(dictionary) if h_02 != 0: dictionary['text'] = """>{p_02:.2f}{symbol} - {n_02} pessoa(s) - responderam que <b>desgostaram muito </b> dessa amostra.""".format(symbol="%", p_02=porcentagem(h_02, q_p), n_02=h_02) put_string(dictionary) if h_03 != 0: dictionary['text'] = """>{p_03:.2f}{symbol} - {n_03} pessoa(s) - responderam que <b>desgostaram moderadamente</b> dessa amostra.""".format(symbol="%", p_03=porcentagem(h_03, q_p), n_03=h_03) put_string(dictionary) if h_04 != 0: dictionary['text'] = """>{p_04:.2f}{symbol} - {n_04} pessoa(s) - responderam que <b>desgostaram ligeiramente</b> dessa amostra.""".format(symbol="%", p_04=porcentagem(h_04, q_p), n_04=h_04) put_string(dictionary) if h_05 != 0: dictionary['text'] = """>{p_05:.2f}{symbol} - {n_05} pessoa(s) - responderam que <b>nem gostaram, nem desgostaram</b> dessa amostra.""".format(symbol="%", p_05=porcentagem(h_05, q_p), n_05=h_05) put_string(dictionary) if h_06 != 0: dictionary['text'] = """>{p_06:.2f}{symbol} - {n_06} pessoa(s) - responderam que <b>gostaram ligeiramente</b> dessa amostra.""".format(symbol="%", p_06=porcentagem(h_06, q_p), n_06=h_06) put_string(dictionary) if h_07 != 0: dictionary['text'] = """>{p_07:.2f}{symbol} - {n_07} pessoa(s) - responderam que <b>gostaram moderadamente</b> dessa amostra.""".format(symbol="%", p_07=porcentagem(h_07, q_p), n_07=h_07) put_string(dictionary) if h_08 != 0: dictionary['text'] = """>{p_08:.2f}{symbol} - {n_08} pessoa(s) - responderam que <b>gostaram muito</b> dessa amostra.""".format(symbol="%", p_08=porcentagem(h_08, q_p), n_08=h_08) put_string(dictionary) if h_09 != 0: dictionary['text'] = """>{p_09:.2f}{symbol} - {n_09} pessoa(s) - responderam que <b>gostaram extremamente</b> dessa amostra.""".format(symbol="%", p_09=porcentagem(h_09, q_p), n_09=h_09) put_string(dictionary) elements.append(Spacer(1, 30)) # Perguntas dissertativas elif pergunta.tipo == 'PDT': respostas = Dissertativa.objects.filter( analise_id=id, pergunta_id=pergunta.id, amostra__tipo=transcricao_numero_letra(index) ) if respostas: for resposta in respostas: if resposta.resposta != "": dictionary['text'] = "> " + str(resposta.resposta) dictionary['type'] = 'Normal' dictionary['size'] = '12' dictionary['spacer'] = 10 put_string(dictionary) else: dictionary['text'] = "Nenhuma resposta cadastrada." dictionary['type'] = 'Normal' dictionary['size'] = '12' dictionary['spacer'] = 10 put_string(dictionary) # Perguntas de intenção de compra else: respostas = IntencaoCompra.objects.filter( analise_id=id, pergunta_id=pergunta.id, amostra__tipo=transcricao_numero_letra(index) ) ic_01 = 0 ic_02 = 0 ic_03 = 0 ic_04 = 0 ic_05 = 0 q_p = analise.quantidade_pessoas for resposta in respostas: if resposta.resposta == 1: ic_01 += 1 elif resposta.resposta == 2: ic_02 += 1 elif resposta.resposta == 3: ic_03 += 1 elif resposta.resposta == 4: ic_04 += 1 else: ic_05 += 1 data = [(ic_01, ic_02, ic_03, ic_04, ic_05), ] cartoon.data = data cartoon.categoryAxis.categoryNames = [ 'Certamente não compraria', 'Possivelmente não compraria', 'Talvez comprasse ou não comprasse', 'Possivelmente compraria', 'Certamente compraria' ] cartoon.bars[(0, 0)].fillColor = colors.green cartoon.bars[(0, 1)].fillColor = colors.red cartoon.bars[(0, 2)].fillColor = colors.yellow cartoon.bars[(0, 3)].fillColor = colors.blue cartoon.bars[(0, 4)].fillColor = colors.pink cartoon.categoryAxis.labels.dx = 8 cartoon.categoryAxis.labels.dy = -2 cartoon.categoryAxis.labels.angle = 30 grafico.add(cartoon) elements.append(grafico) elements.append(Spacer(1, 60)) dictionary['size'] = '12' dictionary['type'] = 'Normal' dictionary['text'] = "Resultados: " dictionary['spacer'] = 20 put_string(dictionary) q_p = ic_01 + ic_02 + ic_03 + ic_04 + ic_05 if ic_01 != 0: dictionary['spacer'] = 10 dictionary['text'] = """>{p_01:.2f}{symbol} - {n_01} pessoa(s) - responderam que <b>Certamente não compraria </b> dessa amostra.""".format(symbol="%", p_01=porcentagem(ic_01, q_p), n_01=ic_01) put_string(dictionary) if ic_02 != 0: dictionary['text'] = """>{p_02:.2f}{symbol} - {n_02} pessoa(s) - responderam que <b>possivelmente não compraria </b> dessa amostra.""".format(symbol="%", p_02=porcentagem(ic_02, q_p), n_02=ic_02) put_string(dictionary) if ic_03 != 0: dictionary['text'] = """>{p_03:.2f}{symbol} - {n_03} pessoa(s) - responderam que <b>talvez não comprasse ou talvez comprasse </b> dessa amostra.""".format(symbol="%", p_03=porcentagem(ic_03, q_p), n_03=ic_03) put_string(dictionary) if ic_04 != 0: dictionary['text'] = """>{p_04:.2f}{symbol} - {n_04} pessoa(s) - responderam que <b>possivelmente compraria</b> dessa amostra.""".format(symbol="%", p_04=porcentagem(ic_04, q_p), n_04=ic_04) put_string(dictionary) if ic_05 != 0: dictionary['text'] = """>{p_05:.2f}{symbol} - {n_05} pessoa(s) - responderam que <b>certamente compraria</b> dessa amostra.""".format(symbol="%", p_05=porcentagem(ic_05, q_p), n_05=ic_05) put_string(dictionary) elements.append(Spacer(1, 60)) elements.append(PageBreak()) #------------------------------------------------------------------------- arquivo.build(elements) response.write(buff.getvalue()) buff.close() return response