Пример #1
0
def conversion_chart(data, labels):
    """Create chart that can be drawn as a gif with given data/labels"""

    drawing = Drawing(500, 400)
    bc = VerticalBarChart()

    bc.x = 80
    bc.y = 80

    bc.height = 290
    bc.width = 390

    bc.data = data

    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = 100
    bc.valueAxis.valueStep = 10
    bc.valueAxis.labelTextFormat = '%2.2f'
    bc.barLabels.fontSize = 15
    bc.barLabelFormat = '%2.2f'
    bc.barLabels.boxAnchor = 's'

    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 8
    bc.categoryAxis.labels.dy = 2
    bc.categoryAxis.labels.angle = 30
    bc.categoryAxis.categoryNames = labels

    drawing.add(bc)

    return drawing
    def vertical_bar_chart_draw(self, values, days, llabels):
        d = Drawing(0, 170)
        #  chart
        bc = VerticalBarChart()
        # set width and height
        bc.height = 125
        bc.width = 470
        # set data
        bc.data = values
        # set distance between bars elements
        bc.barSpacing = 0.5

        # set labels position under the x axe
        bc.categoryAxis.labels.dx = 8
        bc.categoryAxis.labels.dy = -2
        # set name displayed for x axe
        bc.categoryAxis.categoryNames = days

        # set label format for each bar
        bc.barLabelFormat = '%d'
        # set distance between top of bar and it's label
        bc.barLabels.nudge = 7

        # set some charactestics for the Y axe
        bc.valueAxis.labelTextFormat = '%d km/h'
        bc.valueAxis.valueMin = 0

        d.add(self.title_draw(250, 190, _('Wind speed statistics')))
        d.add(bc)
        d.add(self.legend_draw(llabels, bc, x=480, y=165, boxAnchor='ne',
                               columnMaximum=1, type='bar'))
        # d.add(bcl)
        return d
    def create_chart(self, data, y_label, d_format, cols):
        """Generates and returns a bar chart object"""
        chart = VerticalBarChart()  # Create a bar chart
        chart.width = self.W - (self.MARGIN * 2)  # Set chart width
        chart.height = self.H / 2  # Set chart height
        chart.x = self.MARGIN  # Shift right to centre
        chart.y = (self.H / 2) - self.MARGIN  # Shift up to near top
        chart.valueAxis.valueMin = 0  # Baseline of axes (set to 0)

        # Set bar colors
        for i in range(len(data)):
            chart.bars[i].fillColor = cols[i]

        # Add data to chart
        formatted_data = []
        for data_item in data:
            formatted_data.append([data_item])
        chart.data = formatted_data

        # Add labels to chart
        chart.categoryAxis.categoryNames = [y_label]
        chart.barLabelFormat = d_format  # Format of text to display on labels
        chart.barLabels.nudge = 8  # Nudge labels upwards by 8px

        return chart
Пример #4
0
    def vertical_bar_chart_draw(self, values, days, llabels):
        d = Drawing(0, 170)
        bc = VerticalBarChart()
        bc.height = 125
        bc.width = 470
        bc.data = values
        bc.barSpacing = 0.5

        bc.categoryAxis.labels.dx = 8
        bc.categoryAxis.labels.dy = -2
        bc.categoryAxis.categoryNames = days

        bc.barLabelFormat = '%d'
        bc.barLabels.nudge = 7

        bc.valueAxis.labelTextFormat = '%d km/h'
        bc.valueAxis.valueMin = 0

        d.add(self.title_draw(250, 190, _('Wind speed statistics')))
        d.add(bc)
        d.add(
            self.legend_draw(llabels,
                             bc,
                             x=480,
                             y=165,
                             boxAnchor='ne',
                             columnMaximum=1,
                             type='bar'))
        return d
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
Пример #6
0
    def makeBarChart(self, context, width, height, data, xvalues, barColors, strokeWidth, displayBarLabels, labelAngles, yAxisMin, yAxisMax):
        content = []

        drawing = Drawing(width, height)

        chart = VerticalBarChart()
        chart.x = 0
        chart.y = 0
        chart.height = height
        chart.width = width
        chart.data = data

        if displayBarLabels:
            chart.barLabelFormat = '%2.0f'
            chart.barLabels.dy = 6
        else:
            chart.barLabelFormat = None

        if xvalues:
            chart.categoryAxis.categoryNames = xvalues

        if yAxisMin is not None:
            chart.valueAxis.valueMin = yAxisMin

        if yAxisMax is not None:
            chart.valueAxis.valueMax = yAxisMax

        if strokeWidth:
            self.handleSingleOrList(chart.bars, strokeWidth, 'strokeWidth', len(data))

        if barColors:
            self.handleSingleOrList(chart.bars, barColors, 'fillColor', len(data), colors.HexColor)

        if labelAngles is not None:
            self.handleSingleOrList(chart.categoryAxis.labels, labelAngles, 'angle', len(data[0]))

        drawing.add(chart)

        content.append( drawing )

        return content
def run(self, include_sub_survey=False, dimensions=[]):

    # Build data set
    averages = []
    category_names = []
    
    for dimension in self.getDimensions():
        averages.append(self.get_average_score_for_dimension(
            include_sub_survey=include_sub_survey,
            dimension=dimension))
        category_names.append(dimension)
        
    drawing = Drawing(600, 300)
    
    bc = VerticalBarChart()         
    bc.x = 20
    bc.y = 20  
    bc.height = 260
    bc.width = 580
    bc.data = [averages]
    bc.categoryAxis.categoryNames = category_names
    bc.categoryAxis.labels.fontName = 'Helvetica'
    bc.categoryAxis.labels.fontSize = 10
    bc.categoryAxis.labels.textAnchor = 'middle'
    bc.categoryAxis.visibleTicks = 0
    bc.valueAxis.valueMax = 100.0
    bc.valueAxis.valueMin = min(averages, 0)
    bc.valueAxis.labels.fontName = 'Helvetica'
    bc.valueAxis.labels.fontSize = 10
    bc.valueAxis.labels.textAnchor = 'middle'
    bc.barLabelFormat = '%.0f'
    bc.barLabels.dy = 8
    bc.barLabels.fontName = 'Helvetica'
    bc.barLabels.fontSize = 10
    bc.barWidth = len(averages)
    bc.fillColor = None

    drawing.add(bc)
    
    # Write out
    data = drawing.asString('png')
    request = self.REQUEST
    response = request.RESPONSE
    response.setHeader('Content-Type', 'image/png')
    response.setHeader('Content-Disposition','inline; filename=%s.png' % self.getId())
    response.setHeader('Content-Length', len(data))           
    response.setHeader('Cache-Control', 's-maxage=0')
    
    return data
Пример #8
0
    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
Пример #9
0
 def GraficoCustoFixoImplemento(self):
     grafico = Drawing(200, 200)
     dados = [
         (self.DepreciacaoImplemento, self.JuroImplemento,
          self.GaragemImplemento, self.SeguroImplemento),
     ]
     barras = VerticalBarChart()
     barras.x = 0
     barras.y = 0
     barras.height = 150
     barras.width = 150
     barras.data = dados
     barras.barLabelFormat = DecimalFormatter(2)
     barras.barLabels.nudge = 6
     barras.categoryAxis.categoryNames = [
         'Depreciação', 'Juros', 'Garagem', 'Seguro'
     ]
     barras.categoryAxis.labels.angle = 45
     barras.categoryAxis.labels.boxAnchor = 'ne'
     grafico.add(barras)
     return grafico
Пример #10
0
 def GraficoCustoVariavel(self):
     grafico = Drawing(200, 200)
     dados = [
         (self.CustoCombHora, self.CustoOleoHora,
          self.CustoManutencaoHoraTrator, self.PrecoTratorista),
     ]
     barras = VerticalBarChart()
     barras.x = 0
     barras.y = 0
     barras.height = 150
     barras.width = 150
     barras.data = dados
     barras.barLabelFormat = DecimalFormatter(2)
     barras.barLabels.nudge = 6
     barras.categoryAxis.categoryNames = [
         'Combustível', 'Óleo', 'Manutenção', 'Operador'
     ]
     barras.categoryAxis.labels.angle = 45
     barras.categoryAxis.labels.boxAnchor = 'ne'
     grafico.add(barras)
     return grafico
Пример #11
0
def getVetricalBarChart(taxes_int):
    values = []
    years = []
    font = 'Arial'
    for year in taxes_int:
        years.append(year)
        values.append(taxes_int[year])

    data = [values]
    chart = VerticalBarChart()
    chart.height = 180
    chart.width = 450
    chart.data = data

    chart.valueAxis.valueMin = 0
    chart.barWidth = 20
    chart.groupSpacing = 5
    chart.barLabels.fontName = font
    chart.barLabels.fontSize = 8
    chart.bars[0].fillColor = colors.cornflowerblue
    chart.barLabelFormat = '%d тг'
    chart.barLabels.nudge = 7

    chart.categoryAxis.labels.fontName = font
    chart.categoryAxis.labels.fontSize = 8
    chart.categoryAxis.categoryNames = years

    chart.valueAxis.labels.fontName = font
    chart.valueAxis.labels.fontSize = 8
    # chart.valueAxis.gridStrokeDashArray = strokeDashArray
    # chart.valueAxis.gridStrokeWidth = strokeWidth
    # chart.valueAxis.strokeDashArray = strokeDashArray
    # chart.valueAxis.strokeWidth = strokeWidth


    drawing = Drawing(300)
    drawing.add(chart)
    return drawing
Пример #12
0
        def vertical_bar_chart(self):
            """
            Draws a vertical bar chart
            :return: vertical bar chart
            """

            drawing = Drawing(200, 280)
            graph = VerticalBarChart()
            graph.x = self.graph_x
            graph.y = self.graph_y

            graph.width = self.width
            graph.height = self.height

            graph.valueAxis.forceZero = 1
            graph.valueAxis.valueMin = self.value_min
            graph.valueAxis.valueMax = self.value_max
            graph.valueAxis.valueStep = self.value_step

            graph.data = self.data
            graph.categoryAxis.categoryNames = self.categories

            graph.barLabels.nudge = 15
            graph.barLabelFormat = '%dº'
            graph.barLabels.dx = 0
            graph.barLabels.dy = 0
            graph.barLabels.boxAnchor = 'n'
            graph.barLabels.fontName = 'Vera'
            graph.barLabels.fontSize = 10

            graph.bars[0].fillColor = PCMYKColor(45, 45, 0, 0, alpha=85)
            graph.bars[1].fillColor = PCMYKColor(70, 75, 0, 0, alpha=100)
            graph.bars.fillColor = PCMYKColor(64, 62, 0, 18, alpha=85)
            drawing.add(graph, '')

            return [drawing]
        def _rawDraw(self, x, y):
            from reportlab.lib import colors 
            from reportlab.graphics.shapes import Drawing, Line, String, STATE_DEFAULTS
            from reportlab.graphics.charts.axes import XCategoryAxis,YValueAxis
            from reportlab.graphics.charts.textlabels import Label
            from reportlab.graphics.charts.barcharts  import VerticalBarChart
            
            self.originX = x
            self.originY = y
            self._setScale([self.dataBar])
            (x1, y1, Width, Height) = self._getGraphRegion(x, y)

            #Build the graph
            self.drawing = Drawing(self.width, self.height)

            #Size of the Axis
            SizeXaxis = 14
            countSteps = int(self.valueMax / self.valueStep)
            SizeYaxis = 0.0
            for n in range(countSteps + 1):
                eachValue = self.valueMin + n * self.valueStep
                textString = self._customSecondsLabelFormat( eachValue )
                SizeYaxis = max(SizeYaxis, self._stringWidth(textString, STATE_DEFAULTS['fontName'], STATE_DEFAULTS['fontSize']) )

            bc = VerticalBarChart()
            SizeYaxis += bc.valueAxis.tickLeft
            bc.x = x1 - x + SizeYaxis
            bc.y = y1 - y + SizeXaxis
            bc.height = Height - SizeXaxis
            bc.width  = Width  - SizeYaxis
            self.graphCenterX = bc.x + bc.width/2
            self.graphCenterY = bc.y + bc.height/2
            if self.validData:
                # add valid data to chart
                bc.data = self.dataBar
                bc.categoryAxis.categoryNames = self.dataNames
                # axis values
                bc.valueAxis.valueMin  = self.valueMin
                bc.valueAxis.valueMax  = self.valueMax
                bc.valueAxis.valueStep = self.valueStep
                # add value labels above bars
                bc.barLabelFormat = self._customSecondsLabelFormat
                bc.barLabels.dy = 0.08*inch
                bc.barLabels.fontSize = 6
            else:
                # no valid data
                bc.data = [ (0, ), ]
                bc.categoryAxis.categoryNames = [ '' ]
                bc.valueAxis.valueMin  = 0
                bc.valueAxis.valueMax  = 1
                bc.valueAxis.valueStep = 1
                Nodata = Label()
                Nodata.fontSize = 12
                Nodata.angle = 0
                Nodata.boxAnchor = 'c'
                Nodata.dx = self.graphCenterX
                Nodata.dy = self.graphCenterY
                Nodata.setText("NO VALID DATA")
                self.drawing.add(Nodata)
            
            # chart formatting
            (R,G,B) = VeriwaveYellow
            bc.bars[0].fillColor   = colors.Color(R,G,B)
            bc.valueAxis.labelTextFormat = self._customSecondsLabelFormat
            # axis labels
            bc.categoryAxis.labels.boxAnchor = 'c'
            bc.categoryAxis.labels.dx    = 0
            bc.categoryAxis.labels.dy    = -10
            bc.categoryAxis.labels.angle = 0
            bc.categoryAxis.labels.fontSize = 8

            # add chart
            self.drawing.add(bc)

            #Adjust the labels to be the center of the graph
            self._drawLabels(self.title, "", "")

            # Add Legend in upper right corner
            legendHeight  = 9 
            legendX = bc.x + 5
            legendY = bc.y + bc.height - 12
            self.drawing.add(Line(legendX, legendY + 3 , legendX + 20, legendY + 3, strokeColor=bc.bars[0].fillColor, strokeWidth=3 ))
            self.drawing.add(String(legendX + 22, legendY, 'MIN', fontName='Helvetica', fontSize=8))
            legendY -= legendHeight
            self.drawing.add(Line(legendX, legendY + 3 , legendX + 20, legendY + 3, strokeColor=bc.bars[1].fillColor, strokeWidth=3 ))
            self.drawing.add(String(legendX + 22, legendY, 'MAX', fontName='Helvetica', fontSize=8))
            legendY -= legendHeight
            self.drawing.add(Line(legendX, legendY + 3 , legendX + 20, legendY + 3, strokeColor=bc.bars[2].fillColor, strokeWidth=3 ))
            self.drawing.add(String(legendX + 22, legendY, 'AVG', fontName='Helvetica', fontSize=8))
            legendY -= legendHeight
Пример #14
0
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
Пример #15
0
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
Пример #16
0
def genChart(width, height):

    chart = VerticalBarChart()
    chart.data = [(12, 11, 9, 6, 2, 22, 7)]

    # Vertical axis - Y axis
    chart.valueAxis.valueMin = 0
    chart.valueAxis.valueMax = 25
    chart.valueAxis.visible = 0  # hide

    # Horizontal axis - X axis
    chart.categoryAxis.categoryNames = [
        'Asia', 'Africa', 'North America', 'South America', 'Antarctica',
        'Europe', 'Australia'
    ]
    # We could hide X axis like we did with Y axis:
    #   example: chart.categoryAxis.visible = 0
    # Hidding the X axis will hide all the elements of X axis
    # and we want to see the labels!
    #   example: chart.categoryAxis.labels.visible = 1 # by default they are visible
    # So we just hide what we don't want to see!
    chart.categoryAxis.visibleAxis = 0  # hide line
    chart.categoryAxis.visibleTicks = 0  # hide line ticks
    chart.categoryAxis.labels.angle = 90  # rotate labels
    chart.categoryAxis.labels.dx = -30  # adjust labels position at x
    chart.categoryAxis.labels.dy = 30  # adjust labels position at y

    # Numbers above each bar
    chart.barLabelFormat = '%s'  # contains the provived string
    chart.barLabels.nudge = 15  # space between the bar and the text
    chart.barLabels.angle = -20  # rotate the text
    chart.barLabels.fontName = 'barText'  # registered font at report.py line 91
    chart.barLabels.fontSize = 20
    chart.barLabels.fillColor = colors.red

    chart.barWidth = 5
    chart.barSpacing = 8  # space between each bar
    # NOTE: bar list doesn't work like we could expect,
    # the first element apparently sets the configuration for all!
    chart.bars[0].fillColor = colors.toColor('hsl(240, 100%, 20%)')
    chart.bars[0].strokeColor = colors.white

    chart.x = width * 5 / 100  # starts at 5% of width space
    chart.y = height * 5 / 100  # starts at 5% of height space
    chart.width = width * 90 / 100  # uses 90% of width
    chart.height = height * 80 / 100  # uses 80% of height

    titleShadow = String(
        19,
        height * 60 / 100 - 1,  # x and y start point
        'Average JC attacks by continent',
        fontSize=20,
        fontName='chartTitle',  # registered font at report.py line 94
        fillColor=colors.red)

    title = String(
        20,
        height * 60 / 100,  # x and y start point
        'Average JC attacks by continent',
        fontSize=20,
        fontName='chartTitle',  # registered font at report.py line 94
        fillColor=colors.orange)

    bounds = title.getBounds()  # returns a tuple with (x1,y1,x2,y2)

    rectangle = Rect(
        bounds[0] - 3,
        bounds[1],  # x1 and y1
        bounds[2] - bounds[0] + 3,
        20  # x2 and y2
    )
    rectangle.fillColor = colors.black

    drawing = Drawing()
    drawing.add(rectangle)
    drawing.add(titleShadow)
    drawing.add(title)
    drawing.add(chart)

    # Bars bottom 'labels'
    # For a better understand of this coordinates please
    # see code guide
    charWidth = utils.getStringWidth('A')
    dataLen = len(chart.data[0])  # 7 elements

    startPoint = chart.getBounds()[0]
    barAndLabelWidth = chart.width / dataLen  # total width / 7 elements
    center = barAndLabelWidth / 2 - charWidth / 2

    yPos = chart.y - 10

    # Example:
    # drawing.add(String(startPoint + barAndLabelWidth * 0 + center, chart.y - 10, 'A'))
    # drawing.add(String(startPoint + barAndLabelWidth * 1 + center, chart.y - 10, 'B'))
    # ...
    # drawing.add(String(startPoint + barAndLabelWidth * 6 + center, chart.y - 10, 'G'))
    for index, char in enumerate('ABCDEFG', start=0):
        xPos = startPoint + barAndLabelWidth * index + center

        drawing.add(String(xPos, yPos, char))

    return drawing
Пример #17
0
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 create_bar(self,
                   data_list,
                   label_x_axis,
                   contain,
                   y_label=None,
                   x_label=None,
                   bar_width=520,
                   bar_height=100,
                   draw_width=520,
                   draw_height=200,
                   user_color=None,
                   fontName="Times-Roman",
                   fontSize=6,
                   x_angle=0,
                   bar_space=0):

        d = Drawing(width=draw_width, height=draw_height)
        bar = VerticalBarChart()
        bar.width = bar_width
        bar.height = bar_height
        bar.y = bar.height - (bar_height / 4)
        bar.strokeColor = colors.black
        bar.barLabelFormat = '%s'
        bar.barLabels.nudge = 7
        bar.barLabels.fontSize = fontSize

        ################# X AXIS PROPERTIES #################
        bar.categoryAxis.labels.dx = 0
        bar.categoryAxis.labels.angle = x_angle
        bar.categoryAxis.labels.boxAnchor = 'autox'
        bar.categoryAxis.labels.fontSize = fontSize
        bar.categoryAxis.labels.fontName = self.master_font
        bar.categoryAxis.strokeWidth = 0.25
        bar.categoryAxis.tickDown = -(bar.height)
        bar.categoryAxis.categoryNames = label_x_axis

        labX = Label()
        labX.boxAnchor = 'ne'
        labX.dx = bar.width * 2.15
        labX.dy = bar.height
        labX.fontName = fontName
        labX.fontSize = fontSize
        labX.setText(x_label)
        d.add(labX)
        #####################################################

        ################# Y AXIS PROPERTIES #################
        bar.valueAxis.forceZero = 1
        bar.valueAxis.labels.fontSize = fontSize
        bar.valueAxis.labels.fontName = fontName
        bar.valueAxis.rangeRound = 'both'
        bar.valueAxis.valueMin = 0
        bar.valueAxis.visibleGrid = 1
        bar.valueAxis.visibleAxis = 1
        bar.valueAxis.labels.dx = -10

        labY = Label()
        labY.boxAnchor = 'autox'
        labY.dy = bar.y + (bar.height / 1.5)
        labY.dx = bar.x - 30
        labY.angle = 90
        labY.fontName = fontName
        labY.fontSize = fontSize
        labY.setText(y_label)
        d.add(labY)
        #####################################################

        bar.barSpacing = bar_space
        # bar.groupSpacing = 3

        bar.data = data_list

        # print len(data_list)
        # print len(contain)

        if user_color != None:
            usage_color = user_color
        else:
            random_range = [randint(0, 100) for i in range(len(contain))]
            usage_color = map(
                lambda item: PCMYKColor(randint(0, item), randint(0, item),
                                        randint(0, item), randint(0, item)),
                random_range)

        for i in range(len(data_list)):
            bar.bars[i].name = contain[i].upper()
            bar.bars[i].fillColor = usage_color[i]

        legend = Legend()
        # legend.autoXPadding = 10
        legend.alignment = 'right'
        legend.boxAnchor = 'sw'
        legend.dxTextSpace = 10
        legend.fontSize = fontSize
        legend.fontName = fontName
        legend.subCols.minWidth = 55
        legend.variColumn = 1
        legend.deltay = 15
        legend.x = bar.x
        legend.colorNamePairs = Auto(obj=bar)

        d.add(bar)
        d.add(legend)
        self.flowables.append(d)
    def results_chart(self, control_mean, match_mean, treated_mean, att):
        """
        Specify layout of the results chart and generate
        flowable object that can be added to the pdf
        """
        drawing = Drawing()
        vbc = VerticalBarChart()

        # Offset chart from border and text
        vbc.x = self.chart_offset_x
        vbc.y = self.chart_offset_y

        # Set figure size
        vbc.height = self.chart_height
        vbc.width = self.chart_width

        # Specify chart -- list of lists -- list of series with enteries
        vbc.data = [[control_mean, match_mean, treated_mean, att]]

        #Set Y-Axis ranges
        #axis_range = self._calculate_y_axis(vbc.data)
        #vbc.valueAxis.valueMin = axis_range['min']
        #vbc.valueAxis.valueMax = axis_range['max']
        #vbc.valueAxis.valueStep = axis_range['step']

        #Grid formatting
        vbc.valueAxis.visibleGrid = 1
        vbc.valueAxis.gridStrokeColor = colors.lightgrey

        # Set bar characteristics
        vbc.bars[(0, 0)].fillColor = colors.blue
        vbc.bars[(0, 1)].fillColor = colors.yellow
        vbc.bars[(0, 2)].fillColor = colors.red
        vbc.bars[(0, 3)].fillColor = colors.green
        vbc.bars.strokeColor = None
        vbc.barSpacing = 2

        # Create callout labels
        #vbc.barLabels.fontName = "Helvetica"
        vbc.barLabels.fontSize = 8
        vbc.barLabels.fillColor = colors.black
        vbc.barLabelFormat = '%.2f'
        vbc.barLabels.nudge = 5

        # X-axis labels
        #vbc.categoryAxis.labels.dy = -60
        #vbc.valueAxis.labels.fontName = 'Helvetica'
        vbc.categoryAxis.categoryNames = [
            'Control Mean', 'Matched Control Mean', 'Treatment mean', 'ATT'
        ]

        lab = Label()
        lab.setOrigin(10, 155)
        lab.boxAnchor = 'ne'
        lab.angle = 90
        lab.dx = 0
        lab.dy = -15

        #lab.boxStrokeColor = colors.green
        lab.setText('Result Values')
        drawing.add(lab)

        drawing.add(vbc)
        self.elements.append(drawing)
    def balance_statistics_chart(self, control_vars, match_vars, var_names):
        """
        Specify layout of the balance statistics chart and generate
        flowable object that can be added to the pdf
        """
        drawing = Drawing()
        vbc = VerticalBarChart()

        # Chart position in document
        vbc.x = self.chart_offset_x
        vbc.y = self.chart_offset_y
        vbc.height = self.chart_height
        vbc.width = self.chart_width

        # Specify data
        # [[control_var1, control_var2], [match_var1, match_var2]]
        vbc.data = [control_vars, match_vars]

        #Set Y-Axis ranges
        #axis_range = self._calculate_y_axis(vbc.data)
        #vbc.valueAxis.valueMin = axis_range['min']
        #vbc.valueAxis.valueMax = axis_range['max']
        #vbc.valueAxis.valueStep = axis_range['step']

        #Grid formatting
        vbc.valueAxis.visibleGrid = 1
        vbc.valueAxis.gridStrokeColor = colors.lightgrey

        #Bar formatting
        vbc.bars[0].fillColor = colors.blue
        vbc.bars[1].fillColor = colors.yellow
        vbc.bars.strokeColor = None
        vbc.groupSpacing = 1
        vbc.barWidth = 5

        # Callout label formatting (numbers above bar)
        #vbc.barLabels.fontName = "Arial"
        vbc.barLabels.fontSize = 8
        vbc.barLabels.fillColor = colors.black
        vbc.barLabelFormat = '%.2f'
        vbc.barLabels.nudge = 5

        # Central axis
        vbc.categoryAxis.visibleTicks = 1

        # X-axis labels
        #vbc.categoryAxis.labels.dy = -60
        vbc.valueAxis.labels.fontName = 'Helvetica'
        vbc.categoryAxis.categoryNames = var_names

        lab = Label()
        lab.setOrigin(10, 155)
        lab.boxAnchor = 'ne'
        lab.angle = 90
        lab.dx = 0
        lab.dy = -15

        #lab.boxStrokeColor = colors.green
        lab.setText('Percent Bias')
        drawing.add(lab)
        drawing.add(vbc)
        self.elements.append(drawing)
Пример #21
0
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
Пример #22
0
chart.width = 500  # Set the width of the chart itself
chart.height = 200  # Set the height of the chart itself
chart.x = 50  # Shift chart right by 50px to centre it
chart.y = 150  # Shift chart up by 150px so legend can sit underneath
chart.valueAxis.valueMin = 0  # Baseline of axes (set to 0)

# Set bar colors
for i in range(len(colors)):
    chart.bars[i].fillColor = colors[i]

# Add data to chart
chart.data = prices
chart.categoryAxis.categoryNames = categories

# Add labels to chart
chart.barLabelFormat = '$%.2f'  # Text to display on label - 2 decimal float
chart.barLabels.nudge = 8  # Nudge labels upwards by 8px

# ------- Create legend -------
legend = Legend()  # Create the legend
legend.boxAnchor = 'sw'  # Set anchor to bottom-left
legend.x = 50  # Shift legend right to bring in line with chart
legend.y = 50  # Shift legend up by 50px
legend.alignment = 'right'  # Put labels to the right of color icons

# Set legend colors
legend.colorNamePairs = [(colors[i], '{}  '.format(labels[i]))
                         for i in range(len(colors))]

# Add chart and legend to drawing
d.add(chart)
Пример #23
0
chart.width = 500               # Set the width of the chart itself
chart.height = 200              # Set the height of the chart itself
chart.x = 50                    # Shift chart right by 50px to centre it
chart.y = 150                   # Shift chart up by 150px so legend can sit underneath
chart.valueAxis.valueMin = 0    # Baseline of axes (set to 0)

# Set bar colors
for i in range(len(colors)):
    chart.bars[i].fillColor = colors[i]

# Add data to chart
chart.data = prices
chart.categoryAxis.categoryNames = categories

# Add labels to chart
chart.barLabelFormat = '$%.2f'  # Text to display on label - 2 decimal float
chart.barLabels.nudge = 8       # Nudge labels upwards by 8px


# ------- Create legend -------
legend = Legend()               # Create the legend
legend.boxAnchor = 'sw'         # Set anchor to bottom-left
legend.x = 50                   # Shift legend right to bring in line with chart
legend.y = 50                   # Shift legend up by 50px
legend.alignment = 'right'      # Put labels to the right of color icons

# Set legend colors
legend.colorNamePairs = [(colors[i], '{}  '.format(labels[i])) for i in range(len(colors))]


# Add chart and legend to drawing
Пример #24
0
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
Пример #25
0
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 _rawDraw(self, x, y):
            from reportlab.lib import colors 
            from reportlab.graphics.shapes import Drawing, Line, String, STATE_DEFAULTS
            from reportlab.graphics.charts.linecharts import HorizontalLineChart, Label
            from reportlab.graphics.charts.barcharts  import VerticalBarChart
            from reportlab.graphics.widgets.markers import makeMarker
            self._setScale([self.dataLine, self.dataBar])
            (x1, y1, Width, Height) = self._getGraphRegion(x, y)

            #Build the graph
            self.drawing = Drawing(self.width, self.height)

            #Size of the Axis
            SizeXaxis = 14
            SizeYaxis = 0.0
            for n in range(int(self.valueMax / self.valueStep) + 1):
                eachValue = self.valueMin + n * self.valueStep
                SizeYaxis = max(SizeYaxis, self._stringWidth(str("%.1f Mbps" % eachValue), STATE_DEFAULTS['fontName'], STATE_DEFAULTS['fontSize']) )
                
            # Bar chart of measured data
            bc = VerticalBarChart()
            SizeYaxis += bc.valueAxis.tickLeft
            bc.x = x1 - x + SizeYaxis
            bc.y = y1 - y + SizeXaxis
            bc.height = Height - SizeXaxis
            bc.width  = Width  - SizeYaxis
            self.graphCenterX = bc.x + bc.width/2
            self.graphCenterY = bc.y + bc.height/2
            if self.validData:
                # add valid data to chart
                bc.data = self.dataBar
                bc.categoryAxis.categoryNames = self.dataNames
                # add value labels above bars
                bc.barLabelFormat = "%.2f"
                bc.barLabels.dy = 0.08*inch
                bc.barLabels.fontSize = 6
            else:
                # add message informing user there is no valid data
                bc.data = [ (0, ), ]
                bc.categoryAxis.categoryNames = [ '' ]
                Nodata = Label()
                Nodata.fontSize = 12
                Nodata.angle = 0
                Nodata.boxAnchor = 'c'
                Nodata.dx = self.graphCenterX
                Nodata.dy = self.graphCenterY
                Nodata.setText("NO VALID DATA")
                self.drawing.add(Nodata)
            
            # veriwave colors
            (R,G,B) = VeriwaveYellow
            bc.bars[0].fillColor   = colors.Color(R,G,B)
            # set axis ranges
            bc.valueAxis.valueMin  = self.valueMin
            bc.valueAxis.valueMax  = self.valueMax
            bc.valueAxis.valueStep = self.valueStep
            bc.valueAxis.labelTextFormat = "%.1f Mbps"
            # set axis labels
            bc.categoryAxis.labels.boxAnchor = 'ne'
            bc.categoryAxis.labels.dx = 8
            bc.categoryAxis.labels.dy = -2
            bc.categoryAxis.labels.angle = 0
            # add bar chart
            self.drawing.add(bc)

            #Put the labels on the center of the graph
            self._drawLabels(self.title, "Frame Size", "")

            # Add Legend in upper left corner
            legendHeight  = 9 
            legendX = bc.x + 5
            legendY = bc.y + bc.height - 12
            self.drawing.add(Line(legendX, legendY + 3 , legendX + 20, legendY + 3, strokeColor=bc.bars[0].fillColor, strokeWidth=3 ))
            self.drawing.add(String(legendX + 22, legendY, 'Offered Load', fontName='Helvetica', fontSize=8))
            legendY -= legendHeight
            self.drawing.add(Line(legendX, legendY + 3 , legendX + 20, legendY + 3, strokeColor=bc.bars[1].fillColor, strokeWidth=3 ))
            self.drawing.add(String(legendX + 22, legendY, 'Forwarding Rate', fontName='Helvetica', fontSize=8))
            legendY -= legendHeight

            # theoretical line chart
            if self.validData and len(self.dataLine[0]) > 0:
                # if one datapoint, draw horizontal line across chart
                DashArray = [2,2]
                if len(self.dataLine[0]) == 1:
                    yPos = bc.height * (self.dataLine[0][0] - bc.valueAxis.valueMin) / (bc.valueAxis.valueMax - bc.valueAxis.valueMin)
                    self.drawing.add(Line(bc.x, bc.y + yPos, bc.x + bc.width, bc.y + yPos, strokeColor=colors.red, strokeWidth=1, strokeDashArray = DashArray))
                # theoretical line
                lc = HorizontalLineChart()    
                lc.x = bc.x
                lc.y = bc.y
                lc.height = bc.height
                lc.width  = bc.width
                # line axis values
                lc.valueAxis.valueMin  = self.valueMin
                lc.valueAxis.valueMax  = self.valueMax
                lc.valueAxis.valueStep = self.valueStep
                lc.valueAxis.visible   = False
                lc.data = self.dataLine
                # line formatting
                lc.lines[0].strokeColor = colors.red
                lc.lines[0].strokeDashArray = DashArray
                lc.lines[0].symbol = makeMarker('FilledDiamond')
                lc.joinedLines = 1
                self.drawing.add(lc)
                # add legend
                self.drawing.add(Line(legendX, legendY + 3, legendX + 20 , legendY + 3, strokeColor=colors.red, strokeWidth=1, strokeDashArray=DashArray))
                self.drawing.add(String(legendX + 22, legendY, 'Theory', fontName='Helvetica', fontSize=8))
                legendY -= legendHeight
Пример #27
0
    def alpdf(mensaje):
        locale.getlocale()
        aux = mensaje.split('#')
        periodos = aux[0][2:-4].split(",")
        descriptores = aux [1][4:-2].split(",")
        #valor = int(descriptores[0])
        #print("valor:",valor)
        #año = int(años_final[0][1:-1])
        #print("descriptores: ",descriptores)
        #print("periodos ",periodos)
        doc = SimpleDocTemplate("SURALUM.pdf", pagesize=letter)
        story = []
        imagen = Image(logotipo, 7 * cm, 3 * cm)
        story.append(imagen)
        story.append(Spacer(10, 20))
        styles = getSampleStyleSheet()
        styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
    
        if (int(descriptores[0])):#VENTAS TOTALES
            print("ventas_totales")
            story.append(Paragraph('Ventas Totales por Año', styles['title']))
            totales = []
            connection_ddbb = cx_Oracle.connect(usr, passw, "localhost")
            cursor = connection_ddbb.cursor()   
            for i in periodos:
                print()
                cursor = connection_ddbb.cursor()
                cursor.execute("SELECT id_venta, total, fecha FROM ventas WHERE EXTRACT(YEAR FROM fecha) = " + i)
                total = 0
                for fname in cursor:
                    total = total+ fname[1]
                    #print ("Values:", fname[1])
                totales.append(total)
            arreglo = [periodos,totales]

            table = Table(arreglo, colWidths=4* cm)
            table.setStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER')])
            for index, row in enumerate(arreglo):
                ini, fin = (0, index), (len(row)-1, index)
                table.setStyle([
                    ("BOX", ini, fin, 0.25, colors.black),
                    ('INNERGRID', ini, fin, 0.25, colors.black),
                    ('BACKGROUND', (0, 0), (-1, 0), colors.gray)
                ])
            story.append(table)
            d = Drawing(300, 200)
            data = [totales]
            bc = VerticalBarChart()
            bc.x = 50
            bc.y = 50
            bc.height = 125
            bc.width = 400
            bc.data = data
            bc.strokeColor = colors.black
            bc.valueAxis.valueMin = 0
            bc.valueAxis.valueMax = 1000000000
            bc.valueAxis.valueStep = 100000000  #paso de distancia entre punto y punto
            bc.categoryAxis.labels.boxAnchor = 'ne'
            bc.categoryAxis.labels.dx = 8
            bc.categoryAxis.labels.dy = -2
            bc.categoryAxis.labels.angle = 0
            bc.categoryAxis.categoryNames = periodos
            bc.groupSpacing = 10
            bc.barSpacing = 4
            bc.barLabelFormat = '$%d'
            bc.valueAxis.labelTextFormat = ' $%d '
            bc.barLabels.nudge = 7
            d.add(bc)
            #pprint.pprint(bc.getProperties())
            story.append(d)
            #print(story)
   #############################################################################################################################################################
        if (int(descriptores[2][1:])):
            print("ventas por familia")
            story.append(Paragraph('Ventas por Familia', styles['title']))
            connection_ddbb = cx_Oracle.connect(usr, passw, "localhost")
            cursor = connection_ddbb.cursor()
            totales  = [('Periodo','Suralum','Huracan','Industrial')]
            valores_g = []
            for i in periodos:
                cursor.execute("""SELECT
                productos.id_familia,
                SUM(venta_productos.cantidad * venta_productos.precio) as c     
                FROM
                    venta_productos INNER JOIN productos ON venta_productos.id_producto = productos.id_producto JOIN ventas ON venta_productos.id_venta=ventas.id_venta
                WHERE EXTRACT(YEAR FROM ventas.fecha) = """+i+"""AND(productos.id_familia=1 OR productos.id_familia=2 OR productos.id_familia=3)
                GROUP BY
                    productos.id_familia
                ORDER BY
                    productos.id_familia DESC
                """)
                vt=[(i)]
                vg =[]
                for valor in cursor:
                    #print ("Values:", valor)
                    vt.append(valor[1])
                    vg.append(valor[1])
                    #print(vt)
                totales.append(vt)
                valores_g.append(vg)

            table = Table(totales, colWidths=4*cm)
            table.setStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER')])
            for index, row in enumerate(totales):
                ini, fin = (0, index), (len(row)-1, index)
                table.setStyle([
                    ("BOX", ini, fin, 0.25, colors.black),
                    ('INNERGRID', ini, fin, 0.25, colors.black),
                    ('BACKGROUND', (0, 0), (-1, 0), colors.gray),
                    ('BACKGROUND', (0, 0), (0,-1), colors.gray)
                ])
            story.append(table)
            d = Drawing(600, 200)
            data = valores_g
            bc = VerticalBarChart()
            bc.x = 50
            bc.y = 50
            bc.height = 125
            bc.width = 400
            bc.data = data
            bc.strokeColor = colors.black
            bc.valueAxis.valueMin = 0
            bc.valueAxis.valueMax = 500000000
            bc.valueAxis.valueStep = 100000000 #paso de distancia entre punto y punto
            bc.categoryAxis.labels.boxAnchor = 'ne'
            bc.categoryAxis.labels.dx = 8
            bc.categoryAxis.labels.dy = -2
            bc.categoryAxis.labels.angle = 0
            bc.categoryAxis.categoryNames = ('Suralum','Huracan','Industrial')
            bc.valueAxis.labelTextFormat = ' $%d '
            bc.groupSpacing = 10
            bc.barSpacing = 4
            bc.barLabelFormat = '$%d'
            bc.barLabels.nudge = 7

            legend=Legend()
            legend.x                       = 20
            legend.y                       = 0
            legend.boxAnchor               = 'se'
            legend.subCols[1].align        = 'right'
            legend.alignment               = 'right'
            legend.columnMaximum           = 9
            legend.fontSize                = 13
            # these data can be read from external sources

            legend.colorNamePairs=Auto(obj=bc)
            d.add(bc)
            d.add(legend)
            #pprint.pprint(bc.getProperties())
            story.append(d)
            #print(totales)

        

        if (int(descriptores[3][1:])):
            print("Suralum")
            story.append(Paragraph('Ventas Suralum', styles['title']))
            connection_ddbb = cx_Oracle.connect(usr, passw, "localhost")
            cursor = connection_ddbb.cursor()
            
            for i in periodos:
                #print("para el periodo:",i)
                cursor.execute("""SELECT
                    productos.descripcion,
                    SUM(venta_productos.cantidad) as v,
                    SUM(venta_productos.cantidad * venta_productos.precio) as c
                FROM
                    venta_productos JOIN productos ON venta_productos.id_producto = productos.id_producto JOIN ventas ON venta_productos.id_venta=ventas.id_venta
                WHERE EXTRACT(YEAR FROM ventas.fecha) = """+i+"""AND productos.id_familia=1
                GROUP BY
                    productos.descripcion
                ORDER BY
                    v DESC""")
                #AGREGAR TITULO DEL PERIODO AL STORY PARA SEPARAR LAS TABLAS
                story.append(Paragraph('Año:'+i, styles['Center']))
                k= 0
                totales = []
                totales.append(head)
                for valor in cursor:
                    producto = []
                    if (k < 12):
                        producto.append(valor[0])#nombre
                        producto.append(valor[1])#totales_ccantidad
                        producto.append(valor[2])#totales_ventas
                        totales.append(producto)
                    k = k+1
                table = Table(totales, colWidths=4*cm)
                table.setStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER')])
                for index, row in enumerate(totales):
                    bg_color = colors.green
                    ini, fin = (0, index), (len(row)-1, index)
                    table.setStyle([
                        ("BOX", ini, fin, 0.25, colors.black),
                        ('INNERGRID', ini, fin, 0.25, colors.black),
                        ('BACKGROUND', (0, 0), (-1, 0), colors.gray)
                    ])
                story.append(Spacer(10, 20))
                story.append(table)
                story.append(Spacer(10, 20))

        
############################################################################################################################
        if (int(descriptores[4][1:])):
            print("Huracan")

            story.append(Paragraph('Ventas Huracan', styles['title']))
            connection_ddbb = cx_Oracle.connect(usr, passw, "localhost")
            cursor = connection_ddbb.cursor()
            
            for i in periodos:
                #print("para el periodo:",i)
                cursor.execute("""SELECT
                    productos.descripcion,
                    SUM(venta_productos.cantidad) as v,
                    SUM(venta_productos.cantidad * venta_productos.precio) as c
                FROM
                    venta_productos JOIN productos ON venta_productos.id_producto = productos.id_producto JOIN ventas ON venta_productos.id_venta=ventas.id_venta
                WHERE EXTRACT(YEAR FROM ventas.fecha) = """+i+"""AND productos.id_familia=2
                GROUP BY
                    productos.descripcion
                ORDER BY
                    v DESC""")
                #AGREGAR TITULO DEL PERIODO AL STORY PARA SEPARAR LAS TABLAS
                story.append(Paragraph('Año:'+i, styles['Center']))
                k= 0
                totales = []
                totales.append(head)
                for valor in cursor:
                    producto = []
                    if (k < 12):
                        producto.append(valor[0])#nombre
                        producto.append(valor[1])#totales_ccantidad
                        producto.append(valor[2])#totales_ventas
                        totales.append(producto)
                        k = k+1


                table = Table(totales, colWidths=4*cm)
                table.setStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER')])
                for index, row in enumerate(totales):
                    bg_color = colors.violet
                    ini, fin = (0, index), (len(row)-1, index)
                    table.setStyle([
                        ("BOX", ini, fin, 0.25, colors.black),
                        ('INNERGRID', ini, fin, 0.25, colors.black),
                        ('BACKGROUND', (0, 0), (-1, 0), colors.gray)
                    ])
                story.append(Spacer(10, 20))
                story.append(table)
                story.append(Spacer(10, 20))
               


#######################################################################################################################################

        if (int(descriptores[5][1:])):
            print("Industrial")

            story.append(Paragraph('Ventas Industrial', styles['title']))
            connection_ddbb = cx_Oracle.connect(usr, passw, "localhost")
            cursor = connection_ddbb.cursor()
            
            for i in periodos:
                #print("para el periodo:",i)
                cursor.execute("""SELECT
                    productos.descripcion,
                    SUM(venta_productos.cantidad) as v,
                    SUM(venta_productos.cantidad * venta_productos.precio) as c
                FROM
                    venta_productos JOIN productos ON venta_productos.id_producto = productos.id_producto JOIN ventas ON venta_productos.id_venta=ventas.id_venta
                WHERE EXTRACT(YEAR FROM ventas.fecha) = """+i+"""AND productos.id_familia=3
                GROUP BY
                    productos.descripcion
                ORDER BY
                    v DESC""")
                #AGREGAR TITULO DEL PERIODO AL STORY PARA SEPARAR LAS TABLAS
                story.append(Paragraph('Año:'+i, styles['Center']))
                k= 0
                totales = []
                totales.append(head)
                for valor in cursor:
                    producto = []
                    if (k < 12):
                        producto.append(valor[0])#nombre
                        producto.append(valor[1])#totales_ccantidad
                        producto.append(valor[2])#totales_ventas
                        totales.append(producto)
                    k = k+1
                table = Table(totales, colWidths=4*cm)
                table.setStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER')])
                for index, row in enumerate(totales):
                    bg_color = colors.aqua
                    ini, fin = (0, index), (len(row)-1, index)
                    table.setStyle([
                        ("BOX", ini, fin, 0.25, colors.black),
                        ('INNERGRID', ini, fin, 0.25, colors.black),
                        ('BACKGROUND', (0, 0), (-1, 0), colors.gray)
                    ])
                story.append(Spacer(10, 20))
                story.append(table)
                story.append(Spacer(10, 20))
        
        
        if (int(descriptores[6][1:])):
            print("mas vendido")
            story.append(Paragraph('PRODUCTOS MÁS VENDIDOS', styles['title']))
            connection_ddbb = cx_Oracle.connect(usr, passw, "localhost")
            cursor = connection_ddbb.cursor()
            for i in periodos:
                cursor.execute("""SELECT
                    productos.descripcion,
                    SUM(venta_productos.cantidad) as v,
                    SUM(venta_productos.cantidad * venta_productos.precio) as c
                FROM
                    venta_productos JOIN productos ON venta_productos.id_producto = productos.id_producto JOIN ventas ON venta_productos.id_venta=ventas.id_venta
                WHERE EXTRACT(YEAR FROM ventas.fecha) = """+i+"""
                GROUP BY
                    productos.descripcion
                ORDER BY
                    v DESC"""
                )
                story.append(Paragraph('Año:'+i, styles['Center']))
                k= 0
                totales = []
                totales.append(head)
                for valor in cursor:
                    producto = []
                    if (k < 20):
                        producto.append(valor[0])#nombre
                        producto.append(valor[1])#totales_ccantidad
                        producto.append(valor[2])#totales_ventas
                        #producto.append(valor[3])#familia
                        totales.append(producto)
                    k = k+1
                table = Table(totales, colWidths=4*cm)
                table.setStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER')])
                for index, row in enumerate(totales):
                    bg_color = colors.aqua
                    ini, fin = (0, index), (len(row)-1, index)
                    table.setStyle([
                        ("BOX", ini, fin, 0.25, colors.black),
                        ('INNERGRID', ini, fin, 0.25, colors.black),
                        ('BACKGROUND', (0, 0), (-1, 0), colors.gray)
                    ])
                story.append(Spacer(10, 20))
                story.append(table)
                story.append(Spacer(10, 20))  
        doc.build(story)
Пример #28
0
def create_single_grade_pdf(student_id, class_id, assignment_count, grade_standard_dict, grade_student_dict, assignment_line_all, assignment_names, assignment_dict):
    '''--Variables--'''
    Story=[]
    Elements=[]
    buff = StringIO()
    formatted_time = time.ctime()
    minimum = 100
    standard_averages=[[]]
    standard_table=[]

    #content_areas = []

    '''------'''
    styles = getSampleStyleSheet()
    HeaderStyle = styles["Heading1"]

    #get the student Name

    #Create the name for the PDf being returned
    pdfName = get_student_name(student_id).first_name+"_"+get_student_name(student_id).last_name+"_SR"+".pdf"

    #set up the response headers so the browser knows to return a PDF document
    response.headers['Content-Type'] = 'application/pdf'
    response.headers['Content-Disposition'] ='attachment;filename=%s;'%pdfName
    doc = SimpleDocTemplate(buff,pagesize=letter,rightMargin=72,leftMargin=72,topMargin=72,bottomMargin=18)
    doc.title=pdfName

    #Set up some styles
    styles=getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
    styles.add(ParagraphStyle(name='Indent', rightIndent=3))
    styles.add(ParagraphStyle(name = 'Title2',
                                  parent = styles['Normal'],
                                  fontName = 'DejaVuSansCondensed',
                                  fontSize = 18,
                                  leading = 22,
                                  #alignment = TA_LEFT,
                                  spaceAfter = 6),
                                  alias = 'title2')


    #Time-Stamp
    ptext = '<font size=12>%s</font>' % formatted_time
    Story.append(Paragraph(ptext, styles["Normal"]))
    Story.append(Spacer(1, 12))
    Elements.extend(ptext)

    #Administrator
    ptext='<font size=12><b>%s %s</b></font>'%(get_student_name(student_id).first_name, get_student_name(student_id).last_name)
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 12))
    Elements.extend(ptext)

    #Grade Number and Content Area
    ptext = '<font size=12><b>%s Student Report</b></font>'%(get_class_name(class_id).name)
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 7))
    Elements.extend(ptext)
    
    
    #Total Assignments
    ptext = '<font size=12>Total Assignments: %s</font>'%(assignment_count)
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 7))
    Elements.extend(ptext)
    
    
    
    
    
    Story.append(Spacer(1,20))
    #Graph Title
    ptext = '<font size=15><b>Current Performance by Standard</b></font>'
    Story.append(Paragraph(ptext, styles["title"]))
    Story.append(Spacer(1,50))

    
    #get all the standards for a specific grade and content area
    standard_query = ((db.classes.id == class_id)&
                       (student_id == db.student.id)&
                      (db.classes.id == db.student_classes.class_id)&
                      (db.student.id == db.student_classes.student_id)&
                      (db.student.id == db.student_grade.student_id)&
                      (db.grade.id == db.student_grade.grade_id)&
                      (db.grade.id == db.grade_standard.grade_id)&
                      (db.standard.id == db.grade_standard.standard_id)&
                      (db.classes.id == db.class_grade.class_id)&
                      (db.grade.id == db.class_grade.grade_id)&
                      (db.standard.content_area == db.contentarea.id))

    standard_list = db(standard_query).select(db.standard.id, db.standard.short_name, db.standard.reference_number,db.student_grade.student_score, db.grade.score, db.contentarea.name)
    standard_ref_list=[]
    #Setup the Dictionary of standard averages
    standard_dict = {}
    standard_table = []
    standard_averages=[[]]
    for row in standard_list:
        if row.standard.id in standard_dict.keys():
            if((row.grade.score != 0.0) | (row.student_grade.student_score != 0.0)):
                max_score = standard_dict[row.standard.id][0] + row.grade.score
                student_score = standard_dict[row.standard.id][1] + row.student_grade.student_score
                standard_dict[row.standard.id] = [max_score, student_score, row.standard.reference_number, row.standard.short_name]
        else:
            standard_dict[row.standard.id] = [row.grade.score, row.student_grade.student_score, row.standard.reference_number, row.standard.short_name]

    
    
        
    i = 0
    #set up the 2D list of Standard Averages
    for standard in sorted(standard_dict.keys()):
        standard_ref_list.append(standard_dict[standard][2])
        standard_table.append([])
        current_avg = (standard_dict[standard][1]/standard_dict[standard][0])*100
        if minimum > current_avg:
            minimum = current_avg
        #int/round was here
        standard_table[i].append(standard_dict[standard][3]+": "+format((standard_dict[standard][1]/standard_dict[standard][0])*100,'.2f')+"%")
        #int/round was here 
        standard_averages[0].append((standard_dict[standard][1]/standard_dict[standard][0])*100)


        for grade in grade_standard_dict.keys():
            for standardId in grade_standard_dict[grade][1]:
                if(standardId == standard):
                    standard_table[i].append(grade_standard_dict[grade][0]+":"+format((grade_student_dict[grade][1]/grade_student_dict[grade][0])*100, '.2f')+"%")
        i+=1
    sorted(standard_table,key=lambda l:l[0])

    
    '''---Graph---'''
    drawing = Drawing(600, 200)
    data = standard_averages
    bc = VerticalBarChart()

    #location in the document (x,y)
    bc.x = 10
    bc.y = 30

    #width and height of the graph
    bc.height = 225
    bc.width = 400
    bc.data = data
    bc.categoryAxis.drawGridLast=True
    bc.categoryAxis.gridStart=0
    bc.categoryAxis.gridStrokeLineCap = 2
    bc.categoryAxis.gridEnd=3
    #bc.barLabels = 

    #Update colors of the bars in the graph
    bc.bars.symbol = ShadedRect()
    bc.bars.symbol.fillColorStart = colors.lightblue
    bc.bars.symbol.fillColorEnd = colors.lightblue
    bc.bars.symbol.strokeWidth = 0


    #this draws a line at the top of the graph to close it. 
    bc.strokeColor = colors.black

    #Y-axis min, max, and steps.
    if minimum != 100:
        bc.valueAxis.valueMin = minimum -10
    else:
        bc.valueAxis.valueMin = 50
    bc.valueAxis.valueMax = 100
    bc.valueAxis.valueStep = 5

    #where to anchor the origin of the graph
    bc.categoryAxis.labels.boxAnchor = 'ne'

    #Locations of labels for the X-axis
    bc.categoryAxis.labels.dx = 2
    bc.categoryAxis.labels.dy = -2

    bc.barLabels.nudge = -10
    bc.barLabelFormat = '%.2f%%'
    bc.barLabels.dx = 0
    bc.barLabels.dy = 0
    #The angle of the lables for the X-axis
    bc.categoryAxis.labels.angle = 30
    #List of the categories to place on the X-axis
    bc.categoryAxis.categoryNames = standard_ref_list
    drawing.add(bc)
    '''------'''
    '''--Graph Legend--'''
    #Graph Legend
    legend = Legend()
    legend.alignment = 'right'
    legend.x = 420
    legend.y = 150
    legend.deltax = 60
    legend.dxTextSpace = 10
    legend.columnMaximum = 4

    legend.colorNamePairs = [(colors.lightblue, 'grade average')]
    drawing.add(legend, 'legend')
    drawing_title = "Bar Graph"
    
    Story.append(drawing)
    Story.append(Spacer(1,15))
    #LineGraph Title
    ptext = '<font size=15><b>Class Performance by Assignment</b></font>'
    Story.append(Paragraph(ptext, styles["title"]))
    Story.append(Spacer(1,30))
    
    '''
    Line Plot Graph ------
    '''
    assignment_data_all =[[],[]]
    for key in assignment_dict.keys():
        assignment_data_all[0].append(assignment_dict[key][2])
        assignment_data_all[1].append(assignment_dict[key][1])
    drawing2 = Drawing(600, 200)
    data2 = assignment_data_all
    #lp = LinePlot()
    
    #data[0] = preprocessData(data[0])
    lp = HorizontalLineChart()
    lp.x = -20
    lp.y = 0
    lp.height = 225
    lp.width = 500
    lp.data = data2
    lp.joinedLines = 1
    lp.lines.symbol = makeMarker('FilledCircle')
    lp.lines[0].strokeColor = colors.grey
    lp.lines[1].strokeColor = colors.lightblue
    lp.strokeColor = colors.black
    lp.categoryAxis.labels.fontSize = 7
    lp.categoryAxis.categoryNames = assignment_names
    lp.categoryAxis.labels.boxAnchor = 'ne'
    lp.categoryAxis.labels.angle = 30
    lp.categoryAxis.drawGridLast=True
    #lp.categoryAxis.gridStart=0
    lp.categoryAxis.gridStrokeLineCap = 2
    #lp.categoryAxis.gridEnd=3
    #lp.categoryAxis.visibleGrid           = 1
    lp.valueAxis.visibleGrid           = 1
    lp.valueAxis.visible               = 1
    lp.valueAxis.drawGridLast=False
    #lp.valueAxis.gridStart = 0
    #lp.valueAxis.gridEnd = 100
    lp.valueAxis.gridStrokeColor = colors.black
    lp.valueAxis.valueMin = 0
    lp.valueAxis.valueMax = 105
    lp.valueAxis.valueStep = 10
    lp.lineLabelFormat = '%2.0f'
    lp.strokeColor = colors.black
    lp.fillColor = colors.white
    drawing2.add(lp)
    
    legend = Legend()
    legend.alignment = 'right'
    legend.x = 482
    legend.y = 150
    legend.deltax = 60
    legend.dxTextSpace = 2
    legend.colorNamePairs = [(colors.lightblue, 'Student'),(colors.grey, 'Class')]
    drawing2.add(legend, 'legend')
    
    Story.append(drawing2)
    Story.append(Spacer(1,30))
    ptext = '<font size=15><b>Assignments by Standard</b></font>'
    Story.append(Paragraph(ptext, styles["title"]))
    Story.append(Spacer(1,10))
    t=Table(standard_table)
    t.setStyle(t.setStyle(TableStyle([('BOX', (0,0), (-1,-1), 0.25, colors.black),
                                      ('FONTSIZE', (0,0), (-1,-1), 7),
                                      ('BACKGROUND',(0,0),(0,-1),colors.lightgrey),
                                      ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),])))
    Story.append(t)
    #build PDF document and return it
    doc.build(Story)
    pdf = buff.getvalue()
    buff.close()
    return pdf
        def _rawDraw(self, x, y):
            from reportlab.lib import colors 
            from reportlab.graphics.shapes import Drawing, Line, String, STATE_DEFAULTS
            from reportlab.graphics.charts.linecharts import HorizontalLineChart, Label
            from reportlab.graphics.charts.barcharts  import VerticalBarChart 

            self._setScale([self.dataLine, self.dataBar])
            (x1, y1, Width, Height) = self._getGraphRegion(x, y)
            self.drawing = Drawing(self.width, self.height)

            #Size of the Axis
            SizeXaxis = 14
            SizeYaxis = 0.0
            for n in range(int(self.valueMax / self.valueStep) + 1):
                eachValue = self.valueMin + n * self.valueStep
                SizeYaxis = max(SizeYaxis, self._stringWidth("%.3f%%" % (eachValue), STATE_DEFAULTS['fontName'], STATE_DEFAULTS['fontSize']) )

            bc = VerticalBarChart()
            SizeYaxis += bc.valueAxis.tickLeft
            bc.x = x1 - x + SizeYaxis
            bc.y = y1 - y + SizeXaxis
            bc.height = Height - SizeXaxis
            bc.width  = Width  - SizeYaxis
            self.graphCenterX = bc.x + bc.width/2
            self.graphCenterY = bc.y + bc.height/2
            if self.validData:
                # add valid data to chart
                bc.data = self.dataBar
                bc.categoryAxis.categoryNames = self.dataNames
                # add value labels above bars
                bc.barLabelFormat = "%.2f"
                bc.barLabels.dy = 0.08*inch
                bc.barLabels.fontSize = 6
            else:
                # no valid data
                bc.data = [ (0,), ]
                bc.categoryAxis.categoryNames = [ '' ]
                Nodata = Label()
                Nodata.fontSize = 12
                Nodata.angle = 0
                Nodata.boxAnchor = 'c'
                Nodata.dx = self.graphCenterX
                Nodata.dy = self.graphCenterY
                Nodata.setText("NO VALID DATA")
                self.drawing.add(Nodata)
                
            # format chart
            (R,G,B) = VeriwaveYellow
            bc.bars[0].fillColor   = colors.Color(R,G,B)
            # axis values
            bc.valueAxis.valueMin  = self.valueMin
            bc.valueAxis.valueMax  = self.valueMax
            bc.valueAxis.valueStep = self.valueStep
            # axis formatting
            if self.valueStep >= 10.0:
                bc.valueAxis.labelTextFormat = "%.0f%%"
            elif self.valueStep >= 1.0:
                bc.valueAxis.labelTextFormat = "%.1f%%"
            elif self.valueStep >= 0.1:
                bc.valueAxis.labelTextFormat = "%.2f%%"
            else:
                bc.valueAxis.labelTextFormat = "%.3f%%"
            bc.categoryAxis.labels.boxAnchor = 'ne'
            bc.categoryAxis.labels.dx = 8
            bc.categoryAxis.labels.dy = -2
            bc.categoryAxis.labels.angle = 0

            self._drawLabels(self.title, "Frame Size", "Percent Loss")

            # What if all loss is Zero
            if self.valueMin == 0.0 and self.valueMax == self.valueStep and self.validData:
                bc.valueAxis.labelTextFormat = "%.3f%%"
                Label_Zero = Label()
                Label_Zero.fontSize = 12
                Label_Zero.angle = 0
                Label_Zero.dx = self.graphCenterX
                Label_Zero.dy = self.graphCenterY
                Label_Zero.boxAnchor = 'c'
                Label_Zero.setText("ALL DATA IS ZERO")
                self.drawing.add(Label_Zero)
            self.drawing.add(bc)
            # Add Legend in upper right corner
            legendHeight  = 9 
            legendX = bc.x + 5
            legendY = bc.y + bc.height - 12

            if len(self.dataLine) > 0 and self.validData:
                # if one datapoint, draw horizontal line across chart
                DashArray = [2,2]
                if len(self.dataLine[0]) == 1:
                    yPos = bc.height * (self.dataLine[0][0] - bc.valueAxis.valueMin) / (bc.valueAxis.valueMax - bc.valueAxis.valueMin)
                    self.drawing.add(Line(bc.x, bc.y + yPos, bc.x + bc.width, bc.y + yPos, strokeColor=colors.red, strokeWidth=1, strokeDashArray = DashArray))
                # theoretical line                           
                lc = HorizontalLineChart()    
                lc.x = bc.x
                lc.y = bc.y
                lc.height = bc.height
                lc.width  = bc.width
                # axis values
                lc.valueAxis.valueMin  = self.valueMin
                lc.valueAxis.valueMax  = self.valueMax
                lc.valueAxis.valueStep = self.valueStep
                lc.valueAxis.visible   = False
                lc.data = self.dataLine
                # dashed line with diamond markers
                lc.lines[0].strokeDashArray = [2,2]
                lc.lines[0].symbol = makeMarker('FilledDiamond')
                lc.joinedLines = 1
                self.drawing.add(lc)
                self.drawing.add(Line(legendX, legendY + 3, legendX + 20 , legendY + 3, strokeColor=lc.lines[0].strokeColor, strokeWidth=1, strokeDashArray = lc.lines[0].strokeDashArray))
                self.drawing.add(String(legendX + 22, legendY, 'Theory', fontName='Helvetica', fontSize=8))
                legendY -= legendHeight
        def _rawDraw(self, x, y):
            from reportlab.lib import colors 
            from reportlab.graphics.shapes import Drawing, Line, String, STATE_DEFAULTS
            from reportlab.graphics.charts.linecharts import HorizontalLineChart, Label
            from reportlab.graphics.charts.barcharts  import VerticalBarChart
            from reportlab.graphics.widgets.markers import makeMarker
            self._setScale([self.dataBar])
            (x1, y1, Width, Height) = self._getGraphRegion(x, y)
            #self._drawBox(x1, y1, Width, Height)

            #Build the graph
            self.drawing = Drawing(self.width, self.height)

            #Size of the Axis
            SizeXaxis = 14
            SizeYaxis = 0.0
            countSteps = int(self.valueMax / self.valueStep)
            for n in range(countSteps + 1):
                eachValue = self.valueMin + n * self.valueStep
                SizeYaxis = max(SizeYaxis, self._stringWidth(self._customSecondsLabelFormat(eachValue), STATE_DEFAULTS['fontName'], STATE_DEFAULTS['fontSize']) )
            
            bc = VerticalBarChart()
            SizeYaxis += bc.valueAxis.tickLeft   
            bc.x = x1 - x + SizeYaxis
            bc.y = y1 - y + SizeXaxis
            bc.height = Height - SizeXaxis
            bc.width  = Width  - SizeYaxis
            self.graphCenterX = bc.x + bc.width/2
            self.graphCenterY = bc.y + bc.height/2
            if self.validData:
                bc.data = self.dataBar
                bc.categoryAxis.categoryNames = self.dataNames
                if len(self.dataNames) < 16:
                    bc.barLabelFormat = self._customSecondsLabelFormat
                    bc.barLabels.dy = 0.08*inch
                    bc.barLabels.fontSize = 9
            else:
                bc.data = [ (0, ), ]
                bc.categoryAxis.categoryNames = [ '' ]
                Nodata = Label()
                Nodata.fontSize = 12
                Nodata.angle = 0
                Nodata.boxAnchor = 'c'
                Nodata.dx = self.graphCenterX
                Nodata.dy = self.graphCenterY
                Nodata.setText("NO VALID DATA")
                self.drawing.add(Nodata)
                
            (R,G,B) = VeriwaveYellow
            bc.bars[0].fillColor   = colors.Color(R,G,B)
            bc.valueAxis.valueMin  = self.valueMin
            bc.valueAxis.valueMax  = self.valueMax
            bc.valueAxis.valueStep = self.valueStep
            bc.valueAxis.labelTextFormat = self._customSecondsLabelFormat
            bc.categoryAxis.labels.boxAnchor = 'ne'
            bc.categoryAxis.labels.dx = 8
            bc.categoryAxis.labels.dy = -2
            bc.categoryAxis.labels.angle = 0
            self.drawing.add(bc)

            #Put the labels on the center of the graph
            self._drawLabels(self.title, "Trial", "Clients")
Пример #31
0
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