Beispiel #1
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
Beispiel #2
0
def ventas_totales(pos, periodos, ventas_totales):
    arreglo = [periodos, ventas_totales]
    table = Table(arreglo, colWidths=3 * cm)
    table.setStyle([('ALIGN', (0, 0), (-1, -1), 'LEFT')])
    for index, row in enumerate(arreglo):
        bg_color = colors.red
        ini, fin = (0, index), (len(row) - 1, index)
        table.setStyle([("BOX", ini, fin, 0.25, colors.black),
                        ('INNERGRID', ini, fin, 0.25, colors.black),
                        ('BACKGROUND', ini, fin, bg_color)])
    story.append(table)
    d = Drawing(400, 200)
    data = [(11541548, 15618561, 56416646)]
    bc = VerticalBarChart()
    bc.x = 50
    bc.y = 50
    bc.height = 125
    bc.width = 300
    bc.data = data
    bc.strokeColor = colors.black
    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = 60000000
    bc.valueAxis.valueStep = 10000000  #paso de distancia entre punto y punto
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 8
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 0
    bc.categoryAxis.categoryNames = ['2017', '2018', '2019']
    bc.groupSpacing = 10
    bc.barSpacing = 2
    #bc.categoryAxis.style = 'stacked'  # Una variación del gráfico
    d.add(bc)
    #pprint.pprint(bc.getProperties())
    story.append(d)
    def 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 simple_bar_chart_angled_labels():
    d = Drawing(280, 250)
    bar = VerticalBarChart()
    bar.x = 50
    bar.y = 85
    data = [
        [1, 2, 3, None, None, None, 5],
        [10, 5, 2, 6, 8, 3, 5],
        [5, 7, 2, 8, 8, 2, 5],
        [2, 10, 2, 1, 8, 9, 5],
    ]
    bar.data = data
    bar.categoryAxis.categoryNames = [
        'Year1', 'Year2', 'Year3', 'Year4', 'Year5', 'Year6', 'Year7'
    ]

    bar.bars[0].fillColor = colors.green
    bar.bars[1].fillColor = colors.blue
    bar.bars[2].fillColor = colors.red
    bar.bars[3].fillColor = colors.purple
    bar.categoryAxis.labels.angle = 45
    bar.categoryAxis.labels.dy = -15
    bar.groupSpacing = 12
    bar.barSpacing = 2

    d.add(bar, '')

    doc = SimpleDocTemplate('simple_bar_chart_angled_labels.pdf')
    story = []
    story.append(d)
    doc.build(story)
Beispiel #5
0
def genBarDrawing(data, data_note, width=letter[0]*0.8, height=letter[1]*0.25):
    """
    函数功能:生成Drawing之用
    :return:
    """
    data_value = list(map(lambda x:x[1],data))

    data_finale = [tuple(data_value)]

    drawing = Drawing(width=width, height=height)


    bc = VerticalBarChart()

    # bc.x = 50
    # bc.y = 50
    # bc.height = 125
    bc.width = width
    bc.data = data_finale
    # bc.valueAxis.valueMin = 0
    bc.barSpacing = 0

    # bc.valueAxis.valueMax = 50
    # bc.valueAxis.valueStep = 10
    # bc.categoryAxis.style = 'stacked'
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 8
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 30

    barFillColors = [
        colors.red, colors.green, colors.white, colors.blue, colors.yellow,
        colors.pink, colors.purple, colors.lightgreen, colors.darkblue, colors.lightyellow,
        colors.fidred, colors.greenyellow, colors.gray, colors.blueviolet, colors.lightgoldenrodyellow]

    for i in range(len(data_finale)):
        bc.bars[i].name = data_note[i]

        # 最多只支持15种颜色,多出的设置为红色
        if i < 15:
            bc.bars[i].fillColor = barFillColors[i]
        else:
            bc.bars[i].fillColor = colors.red

    # x_min = data[0][0]
    # x_max = data[-1][0]

    # bc.xValueAxis.valueMin = x_min
    # lp.xValueAxis.valueMax = x_max

    # step = int(((x_max - x_min) / (60 * 60 * 24)) / 15) + 1

    # bc.categoryAxis.categoryNames = [str(Sec2Datetime(x))[0:10] for x in range(int(x_min), int(x_max), 60 * 60 * 24 * step)]

    drawing.add(bc)

    # 增加legend
    # add_legend(drawing, bc, pos_x=10, pos_y=-10)

    return drawing
Beispiel #6
0
    def xerar_barChart_serv(self):
        """
        Xera un gráfico de barras co número de empregados por departamento nos últimos 8 meses a partir da base de datos

        :return:
        """
        from reportlab.graphics.charts.barcharts import VerticalBarChart

        styles = getSampleStyleSheet()

        ptext = Paragraph(
            'Número de empregados por departamento nos últimos 8 meses:',
            styles['Heading1'])

        self.story.append(ptext)

        d = Drawing(400, 200)

        p = self.cursor.execute(
            """SELECT (SELECT SUM(nempregados) FROM servizos WHERE (departamento = 'produccion')) AS prod, 
        (SELECT SUM(nempregados) FROM servizos WHERE (departamento = 'finanzas')) AS finanzas,
        (SELECT SUM(nempregados) FROM servizos WHERE (departamento = 'informatica')) AS informatica,
         (SELECT SUM(nempregados) FROM servizos WHERE (departamento = 'publicidade')) FROM servizos AS publicidade
        """).fetchone()

        self.conn.text_factory = str

        data = [(25, 34, 14, 18, 36, 22, 19, p[0]),
                (26, 31, 22, 24, 16, 10, 18, p[1]),
                (34, 40, 18, 9, 25, 7, 2, p[2]),
                (29, 20, 19, 16, 34, 40, 15, p[3])]

        bc = VerticalBarChart()
        bc.x = 50
        bc.y = 55
        bc.height = 125
        bc.width = 300
        bc.data = data
        bc.strokeColor = colors.black
        bc.valueAxis.valueMin = 0
        bc.valueAxis.valueMax = 50
        bc.valueAxis.valueStep = 10  # paso de distancia entre punto y punto
        bc.categoryAxis.labels.boxAnchor = 'ne'
        bc.categoryAxis.labels.dx = 8
        bc.categoryAxis.labels.dy = -2
        bc.categoryAxis.labels.angle = 30
        bc.categoryAxis.categoryNames = [
            'Xan-19', 'Feb-19', 'Mar-19', 'Abr-19', 'Mai-19', 'Xuñ-19',
            'Xul-19', 'Ago-19'
        ]
        bc.groupSpacing = 10
        bc.barSpacing = 2
        # bc.categoryAxis.style = 'stacked'  # Una variación del gráfico
        d.add(bc)
        self.story.append(d)
def grafica(request):
    print "Genero el PDF[grafica]"
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "Grafica.pdf"  # llamado clientes
    # la linea 26 es por si deseas descargar el pdf a tu computadora
    response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
    buff = BytesIO()
    doc = SimpleDocTemplate(
        buff,
        pagesize=letter,
        rightMargin=40,
        leftMargin=40,
        topMargin=60,
        bottomMargin=18,
    )
    courses = []
    styles = getSampleStyleSheet()
    header = Paragraph("Total de Cursos", styles['Heading2'])
    courses.append(header)
    styles = getSampleStyleSheet()
    d = Drawing(600, 300)
    conteo = Course.objects.count()
    # for i in Course.objects.all():
    # print conteo
    data = [(conteo, )]
    bc = VerticalBarChart()
    bc.x = 50
    bc.y = 50
    bc.height = 200
    bc.width = 300
    bc.data = data
    bc.strokeColor = colors.blue
    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = 10
    bc.valueAxis.valueStep = 1  #paso de distancia entre punto y punto
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 8
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 30
    bc.categoryAxis.categoryNames = ['Cursos']
    bc.groupSpacing = 10
    bc.barSpacing = 2
    d.add(bc)
    pprint.pprint(bc.getProperties())
    courses.append(d)
    doc.build(courses)
    response.write(buff.getvalue())
    buff.close()
    return response
Beispiel #8
0
    def test_21_barCharts(self):
        from reportlab.lib.styles import getSampleStyleSheet
        from reportlab.lib import colors
        from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph
        from reportlab.pdfbase import pdfmetrics
        from reportlab.graphics.shapes import Drawing
        from reportlab.pdfbase.ttfonts import TTFont
        from reportlab.graphics.charts.barcharts import VerticalBarChart

        pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc'))
        stylesheet = getSampleStyleSheet()

        elements = []
        doc = SimpleDocTemplate("demo.pdf")

        elements.append(
            Paragraph('<font name="chsFont">JY.zenist.song - 俊毅</font>',
                      stylesheet['Title']))
        elements.append(Spacer(1, 12))

        d = Drawing(400, 200)
        data = [(13, 5, 20, 22, 37, 45, 19, 4), (14, 6, 21, 23, 38, 46, 20, 5)]
        bc = VerticalBarChart()
        bc.x = 50
        bc.y = 50
        bc.height = 125
        bc.width = 300
        bc.data = data
        bc.strokeColor = colors.black
        bc.groupSpacing = 10
        bc.barSpacing = 2.5

        bc.valueAxis._valueMin = 0
        bc.valueAxis._valueMax = 50
        bc.valueAxis._valueStep = 10

        bc.categoryAxis.categoryNames = [
            '1', '2', '3', '4', '5', '6', '7', '8'
        ]
        # bc.categoryAxis.style = 'stacked'
        d.add(bc)

        elements.append(d)

        doc.build(elements)
def genBcDrawing(data, data_name, width, height):

    note_list = data_name

    drawing = Drawing(width=width, height=height)
    bc = VerticalBarChart()
    # bc.x = 50
    # bc.y = 50
    # bc.height = 125
    bc.width = width
    bc.data = data
    bc.valueAxis.valueMin = 0
    bc.barSpacing = 10

    # bc.valueAxis.valueMax = 50
    # bc.valueAxis.valueStep = 10
    bc.categoryAxis.style = 'stacked'
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 8
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 30

    barFillColors = [
        colors.red, colors.green, colors.white, colors.blue, colors.yellow,
        colors.pink, colors.purple, colors.lightgreen, colors.darkblue,
        colors.lightyellow, colors.fidred, colors.greenyellow, colors.gray,
        colors.blueviolet, colors.lightgoldenrodyellow
    ]

    for i in range(len(data)):
        bc.bars[i].name = note_list[i]

        # 最多只支持15种颜色,多出的设置为红色
        if i < 15:
            bc.bars[i].fillColor = barFillColors[i]
        else:
            bc.bars[i].fillColor = colors.red

    bc.categoryAxis.categoryNames = [str(i) for i in range(1, 25, 1)]
    drawing.add(bc)

    # 增加legend
    add_legend(drawing, bc, pos_x=10, pos_y=-10)

    return drawing
Beispiel #10
0
    def test_21_barCharts(self):
        from reportlab.lib.styles import getSampleStyleSheet
        from reportlab.lib import colors
        from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph
        from reportlab.pdfbase import pdfmetrics
        from reportlab.graphics.shapes import Drawing
        from reportlab.pdfbase.ttfonts import TTFont
        from reportlab.graphics.charts.barcharts import VerticalBarChart

        pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc'))
        stylesheet = getSampleStyleSheet()

        elements = []
        doc = SimpleDocTemplate("demo.pdf")

        elements.append(Paragraph('<font name="chsFont">JY.zenist.song - 俊毅</font>', stylesheet['Title']))
        elements.append(Spacer(1,12))

        d = Drawing(400,200)
        data = [
            (13,5,20,22,37,45,19,4),
            (14,6,21,23,38,46,20,5)
        ]
        bc = VerticalBarChart()
        bc.x = 50
        bc.y = 50
        bc.height = 125
        bc.width = 300
        bc.data = data
        bc.strokeColor = colors.black
        bc.groupSpacing = 10
        bc.barSpacing = 2.5

        bc.valueAxis._valueMin = 0
        bc.valueAxis._valueMax = 50
        bc.valueAxis._valueStep = 10

        bc.categoryAxis.categoryNames = ['1','2','3','4','5','6','7','8']
        # bc.categoryAxis.style = 'stacked'
        d.add(bc)

        elements.append(d)

        doc.build(elements)
Beispiel #11
0
def sample1barline(
    data=[(100, 110, 120, 130), (70, 25, 85, 30), (63, 75, 51, 92),
          (51, 21, 66, 71), (10, 11, 90, 30)],
    seriesOrder=[[0, 3, 1], [4], [2]],
    lines=[3, 4],
    cAStyle='mixed',
):
    d = Drawing(400, 250)
    chart = VerticalBarChart()
    d.add(chart, name='chart')
    leg = Legend()
    d.add(leg, name='leg')
    chart.bars.strokeColor = None
    chart.bars[2].fillColor = colors.blue
    chart.bars[3].fillColor = colors.orange
    chart.bars[4].fillColor = colors.black  #yellow
    chart.bars[4].strokeWidth = 3
    chart.bars[4].symbol = makeMarker('FilledDiamond',
                                      size=10,
                                      fillColor=colors.red)
    chart.barSpacing = 1
    chart.categoryAxis.style = cAStyle
    chart.data = data
    chart.x = 20
    chart.y = 70
    chart.height = d.height - chart.y - 10
    chart.valueAxis.forceZero = True
    chart.width = d.width - chart.x - 10
    for i in lines:
        chart.bars[i].isLine = 1
    for i in lines:
        chart.bars[i].strokeWidth = 2
    leg.colorNamePairs = Auto(chart=chart)
    leg.x = d.width / 2
    leg.y = 5
    leg.boxAnchor = 's'
    leg.columnMaximum = 1
    leg.alignment = 'right'
    return d
Beispiel #12
0
def barras(datos):
    alto = datos["alto"]
    ancho = datos["ancho"]
    data = datos["data"]
    labels = datos["labels"]
    colores = datos["colores"]

    grafico = VerticalBarChart()
    grafico.x = 30
    grafico.y = 0
    grafico.height = alto
    grafico.width = ancho
    grafico.data = data
    grafico.barSpacing = 1.25
    for i in range(len(colores)):
        color = colors.HexColor(colores[i])
        grafico.bars[i].strokeColor = color
        grafico.bars[i].fillColor = color
    grafico.valueAxis.labels.fontName = "Helvetica"
    grafico.valueAxis.labels.fontSize = FONTSIZE
    grafico.valueAxis.valueMin = 0
    grafico.valueAxis.valueMax = 100
    grafico.valueAxis.valueStep = 10
    grafico.categoryAxis.categoryNames = labels
    grafico.categoryAxis.labels.fontName = "Helvetica"
    grafico.categoryAxis.labels.fontSize = FONTSIZE
    grafico.categoryAxis.labels.dy = -FONTSIZE
    grafico.categoryAxis.labels.boxAnchor = 'c'
    grafico.categoryAxis.labels.angle = 0
    retorno = crearDrawing(grafico)
    etiqueta = Label()
    etiqueta.setOrigin(0, alto)
    etiqueta.fontSize = FONTSIZE
    etiqueta.fontName = "Helvetica"
    etiqueta.setText("(%)")
    retorno.add(etiqueta)
    return retorno
    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 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)
Beispiel #15
0
gBarra.data = datos
gBarra.valueAxis.valueMin = 0
gBarra.valueAxis.valueMax = 50
gBarra.valueAxis.valueStep = 10
# podemos ponerle un estilo, sino pondrá el predeterrminado
gBarra.categoryAxis.style = 'stacked'
gBarra.categoryAxis.labels.boxAnchor = 'ne'  # noroeste
gBarra.categoryAxis.labels.dx = 8
gBarra.categoryAxis.labels.dy = -2
gBarra.categoryAxis.labels.angle = 30
gBarra.categoryAxis.categoryNames = [
    'Xan-17', 'Feb-17', 'Mar-17', 'Abr-17', 'Mai-17', 'Xun-17', 'Xul-17',
    'Ago-17'
]
gBarra.groupSpacing = 10
gBarra.barSpacing = 2

d.add(gBarra)
# añadimos un nuevo dibujo
d2 = Drawing(300, 200)

tarta = Pie()
tarta.x = 65
tarta.y = 15
tarta.height = 170
tarta.width = 170
tarta.data = [10.456, 20.234, 30.567, 40, 50]
tarta.labels = ['Azucre', 'Borrajas', 'Carne', 'Datiles', 'Espinacas']
# porciones
tarta.slices.strokeWidth = 0.5
tarta.slices[3].popout = 50
data = [
        (13, 5, 20, 22, 37, 45, 19, 4),
        (14, 6, 21, 23, 38, 46, 20, 5)
        ]

bc = VerticalBarChart()
bc.x = 50
bc.y = 50
bc.height = 125
bc.width = 300
bc.data = data
bc.strokeColor = colors.black

bc.groupSpacing = 10
bc.barSpacing = 2.5

bc.valueAxis.valueMin = 0
bc.valueAxis.valueMax = 50
bc.valueAxis.valueStep = 10

bc.categoryAxis.labels.boxAnchor = 'ne'
bc.categoryAxis.labels.dx = 8
bc.categoryAxis.labels.dy = -2
bc.categoryAxis.labels.angle = 30
bc.categoryAxis.categoryNames = ['Jan-99','Feb-99','Mar-99',
       'Apr-99','May-99','Jun-99','Jul-99','Aug-99']

drawing.add(bc)

draw(drawing, 'Like before, but with modified spacing')
Beispiel #17
0
                ('TEXTCOLOR', (0, 0), (0, 3), colors.blue)])
tabla.setStyle([('BACKGROUND', (1, 1), (-1, -1), colors.aliceblue)])
tabla.setStyle([('INNERGRID', (1, 1), (-1, -1), 0.25, colors.darkgray)])

doc = [tabla]

d = Drawing(400, 400)
gb = VerticalBarChart()
gb.x = 50
gb.y = 50
gb.height = 125
gb.width = 300
gb.data = listaDatosEdade
gb.strokeColor = colors.black
gb.valueAxis.valueMin = 0
gb.valueAxis.valueMax = 100
gb.valueAxis.valueStep = 10
gb.categoryAxis.labels.boxAnchor = 'ne'
gb.categoryAxis.labels.dx = 8
gb.categoryAxis.labels.dy = -2
gb.categoryAxis.labels.angle = 30
gb.categoryAxis.categoryNames = listaDatosNome
gb.groupSpacing = 10
gb.barSpacing = 2

d.add(gb)

doc.append(d)

documento = SimpleDocTemplate("informeTabla.pdf", pagesize=A4, showBoundary=0)
documento.build(doc)
Beispiel #18
0
    def pdf_drawBar(self,
                    chart_data,
                    categoryNames=[],
                    bar_color=[],
                    title="",
                    title_size=70,
                    title_font=FONTBLOD,
                    x=300,
                    y=1600,
                    chart_width=2000,
                    chart_height=655,
                    lable_fontSize=50,
                    background_color=HexColor(0x000000),
                    lable_angle=0,
                    lable_y=0):
        '''
            @example:
            
                    chart_data = [25,65,330]
                    chart_lable=['Rank','Total Entries']
                    data = []
                    data.append(chart_data)
                    self.pdf_drawBar(data,categoryNames = chart_lable)
        '''

        y = self.pdf_config_object.pdf_height - y
        title_position = self.get_title_position(chart_width, title,
                                                 title_size)
        self.pdf_page_object.setFillColor(HexColor(0x000000))
        self.pdf_page_object.setFont(title_font, title_size)
        self.pdf_page_object.drawString(x + title_position - 150,
                                        y + chart_height + title_size * 3 - 80,
                                        title)
        max_list = []
        for index in range(len(chart_data)):
            if chart_data[index]:
                max_list.append(max(chart_data[index]))
            else:
                max_list.append(0)
        barchart_max = max(max_list) + 100
        drawing = Drawing(800, 2230)
        bc = VerticalBarChart()
        bc.x = 0
        bc.y = 0
        bc.height = chart_height
        bc.width = chart_width
        bc.data = chart_data
        bc.groupSpacing = 15
        bc.barSpacing = 10
        bc.strokeColor = HexColor(0xDFDFDF)
        bc.valueAxis.valueMin = 0
        bc.valueAxis.valueMax = barchart_max + barchart_max / 20
        bc.valueAxis.valueStep = (barchart_max + barchart_max / 20) / 5
        bc.valueAxis.visible = 0
        bc.valueAxis.gridStrokeColor = colors.gray
        bc.valueAxis.visibleGrid = 1
        bc.categoryAxis.labels.dx = 8
        bc.categoryAxis.labels.dy = lable_y
        bc.categoryAxis.labels.fontSize = lable_fontSize
        bc.categoryAxis.labels.angle = lable_angle
        bc.categoryAxis.categoryNames = categoryNames
        if len(bar_color) == 0:
            for i in range(len(chart_data)):
                bar_color.append(HexColor(self.randomcolor()))
        for i in range(len(chart_data)):
            setattr(bc.bars[i], 'fillColor', bar_color[i])
            setattr(bc.bars[i], 'strokeColor', colors.white)
        bc.fillColor = HexColor(0xffffff)
        drawing.add(bc)
        drawing.drawOn(self.pdf_page_object, x, y)
        barchart_max = barchart_max + barchart_max / 20

        try:
            colWidths = chart_width / (len(chart_data[0]))
        except ZeroDivisionError as e:
            raise e
            return
        yheight = chart_height
        yStart = y
        self.pdf_page_object.setFillColor(background_color)
        self.pdf_page_object.setFont(FONTBLOD, 50)
        for i in range(len(chart_data)):
            width = 0
            if not chart_data[i] == 0:
                for j in range(len(chart_data[i])):
                    width = x + j * colWidths
                    try:
                        if len(chart_data) == 1:
                            self.pdf_page_object.drawCentredString(
                                width + colWidths / 2, yStart +
                                yheight * chart_data[i][j] / barchart_max + 20,
                                format(int(chart_data[i][j]), ','))
                        else:
                            self.pdf_page_object.drawCentredString(
                                width + colWidths / (2 * len(chart_data) + 1) *
                                ((i + 1) * 2) - colWidths /
                                (2 * len(chart_data) + 1) / 2, yStart +
                                yheight * chart_data[i][j] / barchart_max + 20,
                                format(int(chart_data[i][j]), ','))
                    except Exception as e:
                        raise e
Beispiel #19
0
def bar_chart(data, labels, **kw):
    """
    :param data:    contains a two dimentional array of values, e.g. [[d11, d21, x1], [d12, d22, x2]]
    :type data:     list[list[numbers],...]
    :param labels:  can contain, but must not ["xlabel", "ylabel", ["data label0", ...]]
                    third item can also be an interger stating the iteration start as label
    :type lables:   ???
    :param ylim:    limit the y axis to these values, e.g. (0, 100)
    :type ylim:     ???
    :param bars:    list of colors we should use for the bars, refer to PDF_CHART_COLORS as an example
    :type bars:     ???
    :param size:    size in pixels, e.g. (8 * cm, 4 * cm) or pixels, e.g. (400, 200)
    :type size:     ???
    :param title:   title of bar chart
    :type title:    string
    :param stacked: weather to do a stacked bar plot or std column plot
    :type stacked:  ???
    """
    title = kw.pop('title', None)
    stacked = kw.pop('stacked', False)
    bars = kw.pop('bars', PDF_CHART_COLORS)
    size = kw.pop('plotSize', (18 * cm, 9 * cm))
    ylim = kw.pop('ylim', None)

    # Create the drawing
    drawing = Drawing(size[0], size[1])

    # Create the Chart
    chart = VerticalBarChart()

    for key, val in list(kw.items()):
        setattr(chart, key, val)

    if title is not None:
        drawing.add(String(20, size[1] - 20, title), name='title')
        chart.y -= 10

    chart.width = drawing.width - 20
    chart.height = drawing.height - 40

    chart.data = data
    max_y = 0
    min_y = maxsize
    for i in range(len(data)):
        chart.bars[i].fillColor = HexColor(bars[i % len(bars)])
        max_y = max(data[i] + [max_y])
        min_y = min(data[i] + [min_y])
    chart.valueAxis.valueMax = max_y * 1.1
    chart.valueAxis.valueMin = min_y * 0.9

    if ylim is not None:
        chart.valueAxis.valueMin = ylim[0]
        chart.valueAxis.valueMax = ylim[1]

    if len(data) > 1:
        chart.barSpacing = 2

    if labels is not None:
        if len(labels) > 0:
            xlabel = Label()
            xlabel._text = labels[0]  # pylint: disable=W0212
            xlabel.textAnchor = 'middle'
            xlabel.x = drawing.width / 2
            xlabel.y = 0
            chart.y += 15
            drawing.add(xlabel, name="xlabel")

        if len(labels) > 1:
            ylabel = Label()
            ylabel._text = labels[1]  # pylint: disable=W0212
            xlabel.textAnchor = 'middle'
            ylabel.angle = 90
            ylabel.x = 0
            ylabel.y = drawing.height / 2
            chart.x += 10
            drawing.add(ylabel, name="ylabel")

        if len(labels) > 2:
            if len(labels[2]) == max([len(x) for x in data]):
                chart.categoryAxis.categoryNames = labels[2]
                chart.categoryAxis.labels.angle = 30
            elif type(labels[2]) == int:
                chart.categoryAxis.categoryNames = range(labels[2], max([len(x) for x in data]) + labels[2])

    if stacked:
        chart.categoryAxis.style = 'stacked'

    drawing.add(chart, name='chart')

    return drawing
Beispiel #20
0
def reporte4_pdf(request, pk_proyecto):
    from reportlab.graphics.shapes import Drawing, Rect, String, Group, Line
    from reportlab.graphics.charts.barcharts import VerticalBarChart

    proy = Proyecto.objects.get(id=pk_proyecto)
    story = []
    estilo = getSampleStyleSheet()
    import pprint

    estiloHoja = getSampleStyleSheet()
    cabecera = estiloHoja['Heading2']
    cabecera.pageBreakBefore = 0
    cabecera.keepWithNext = 0
    cabecera.backColor = colors.white
    cabecera.spaceAfter = 0
    cabecera.spaceBefore = 0
    parrafo = Paragraph('', cabecera)
    story.append(parrafo)
    parrafo = Paragraph('CUARTO INFORME DEL' + '"' + proy.nombre_largo + '" : ', cabecera)
    story.append(parrafo)
    parrafo = Paragraph('_' * 66, cabecera)
    story.append(parrafo)
    cabecera2 = estiloHoja['Heading2']
    cabecera2.pageBreakBefore = 0
    cabecera2.keepWithNext = 0
    cabecera2.backColor = colors.white
    parrafo = Paragraph(
        'GRAFICO DE TIEMPO ESTIMADO Y EJECUTADO POR SPRINT DEL PROYECTO' + '"' + proy.nombre_largo + '"', cabecera2)
    story.append(parrafo)
    d = Drawing(400, 200)

    sprints = Sprint.objects.filter(proyecto=proy)
    print sprints
    listasprint = []
    listaplan = []
    listaejec = []

    for sp in sprints:
        listasprint.append(sp.nombre)
        US = UserStory.objects.filter(sprint=sp)
        print US
        tarea = Tarea.objects.filter(user_story_id= US)

        totalus = 0
        sumatarea = 0
        for u in US:
            totalus += u.estimacion

            for t in tarea:
                sumatarea += t.horas_de_trabajo

        listaejec.append(totalus)
        listaplan.append(sumatarea)

    mayor = 0
    for j in listaejec:
        if j > mayor:
            mayor = j
    for j in listaplan:
        if j > mayor:
            mayor = j

    data = [listaplan, listaejec]
    bc = VerticalBarChart()
    bc.x = 50
    bc.y = 50
    bc.height = 125
    bc.width = 300
    bc.data = data
    bc.strokeColor = colors.black
    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = mayor + 10
    bc.valueAxis.valueStep = 10  #paso de distancia entre punto y punto
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 8
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 30
    bc.categoryAxis.categoryNames = listasprint
    bc.groupSpacing = 10
    bc.barSpacing = 2

    d.add(bc)
    pprint.pprint(bc.getProperties())
    story.append(d)
    cabecera2 = estiloHoja['Heading2']
    cabecera2.pageBreakBefore = 0
    cabecera2.keepWithNext = 0
    cabecera2.backColor = colors.white
    parrafo = Paragraph('ROJO = TIEMPO ESTIMADO', cabecera2)
    story.append(parrafo)
    cabecera2 = estiloHoja['Heading2']
    cabecera2.pageBreakBefore = 0
    cabecera2.keepWithNext = 0
    cabecera2.backColor = colors.white
    parrafo = Paragraph('VERDE = TIEMPO EJECUTADO', cabecera2)
    story.append(parrafo)
    story.append(Spacer(0, 20))
    parrafo = Paragraph('_' * 66, cabecera)
    story.append(parrafo)
    #parrafo = Paragraph('FIN DE CUARTO INFORME' + ' ' * 100 + '(' + str(datetime.date.today()) + ')', cabecera)
    parrafo = Paragraph('FIN DE CUARTO INFORME', cabecera)
    story.append(parrafo)
    buff = BytesIO()
    doc = SimpleDocTemplate(buff,
                            pagesize=letter,
                            rightMargin=40,
                            leftMargin=40,
                            topMargin=60,
                            bottomMargin=18,
    )
    doc.build(story)
    response = HttpResponse(content_type='application/pdf')
    pdf_name = "Reporte.pdf"
    response.write(buff.getvalue())
    buff.close()
    return response
Beispiel #21
0
def MakeHistogram(filename):  #, data):
    '''
	c = canvas.Canvas(filename, pagesize=A2)   # A2 = C size = 17x22 inches
	width, height = A2
	c.rect(36, 36, width-72, height-72, stroke=1, fill=0)   # x, y, width, height, stroke, fill
	'''
    '''
	#framePage(c, 'Color Demo - RGB Space - page %d' % c.getPageNumber())
	miny = 10000000
	maxy = 0
	
	for bin in bins:
		print bin
		if bin > maxy:
			maxy = bin
		if bin < min:
			miny = bin
	#

	minx = 0
	maxx = len(data)
	'''
    '''
	x = 10
	for bin in data:
		c.setFillColor(colors.red)
		c.rect(x, 100, 10, bin, stroke=1, fill=1)   # x, y, width, height, stroke, fill
		x += 20
		
		#all_colors = reportlab.lib.colors.getAllNamedColors().items()
		#all_colors.sort() # alpha order by name
		#c.setFont('Times-Roman', 12)
		#c.drawString(72,730, 'This shows all the named colors in the HTML standard.')
		#y = 700
		#for (name, color) in all_colors:
			#c.setFillColor(colors.black)
			#c.drawString(100, y, name)
			#c.setFillColor(color)
			#c.rect(200, y-10, 300, 30, fill=1)
			#y = y - 40
			#if y < 100:
				#c.showPage()
				#framePage(c, 'Color Demo - RGB Space - page %d' % c.getPageNumber())
				#y = 700
	#
	c.showPage()
	c.save()
	'''

    #------------------------------
    from reportlab.graphics.shapes import Drawing
    from reportlab.graphics.charts.barcharts import VerticalBarChart
    drawing = Drawing(1600, 1200)
    data = \
    [
     (99, 99, 97, 95, 87, 93),
     (56, 48, 59, 50, 56, 52),
     (50, 50, 50, 50, 50, 50)
    ]
    bc = VerticalBarChart()
    bc.x = 250  # Position
    bc.y = 250
    bc.height = 700  # Size
    bc.width = 1000
    #bc.data = [data]    # Expects a list of tuples; one tuple for each series
    bc.data = data  # Expects a list of tuples; one tuple for each series
    bc.strokeColor = colors.black
    bc.valueAxis.valueMin = 0
    #top = (maxy + 100) / 100
    #top = top * 100
    #bc.valueAxis.valueMax = top
    #bc.valueAxis.valueStep = 100
    bc.groupSpacing = 100
    bc.barSpacing = 0
    bc.barWidth = 50
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 8
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 0
    bc.categoryAxis.labels._value.fontSize = 20
    bc.categoryAxis.categoryNames = [
        'Composite', 'Vocabulary', 'Reading', 'Language', 'Mathematics',
        'Sources'
    ]
    drawing.add(bc)

    from reportlab.graphics import renderPDF
    renderPDF.drawToFile(drawing, filename, 'Test')
    '''
Beispiel #22
0
def get_pdf():
    tmpfilename = os.path.join(request.folder, 'private', str(uuid4()))
    doc = SimpleDocTemplate(tmpfilename,
                            rightMargin=1 * inch,
                            leftMargin=1 * inch,
                            topMargin=1 * cm,
                            bottomMargin=1 * inch)
    elements = []
    trabajadores = []

    data = [['Universidad Simon Bolivar'], ['Vicerrectorado Administrativo'],
            ['Direccion de Planta Fisica'],
            ['Unidad de Atención e Inspección'],
            ['', 'Solicitudes atentidas y pendientes'], [''],
            [
                'AREA', 'SOLICITADAS', 'SOLUCIONADAS', 'PENDIENTES',
                'ANULADAS', 'EFECTIVIDAD(%)'
            ]]

    vrs = request.args
    if len(request.args) == 0:
        y = None
        m = None
    else:
        y = str(vrs[0])
        m = str(vrs[1])

    table_data = getData(m, y)

    format_data = []
    total_solicitadas = 0
    total_realizadas = 0
    total_pendientes = 0
    total_anuladas = 0

    for key in table_data:
        area = []

        styles = getSampleStyleSheet()
        text = Paragraph(str(key), styles['Normal'])
        area.append(text)
        area.append(str(table_data[key]['totales']))
        area.append(str(table_data[key]['realizadas']))
        area.append(str(table_data[key]['pendientes']))
        area.append(str(table_data[key]['anuladas']))
        area.append(str(table_data[key]['efectividad']))

        total_solicitadas += table_data[key]['totales']
        total_realizadas += table_data[key]['realizadas']
        total_pendientes += table_data[key]['pendientes']
        total_anuladas += table_data[key]['anuladas']

        format_data.append(area)

    total_efectividad = (float(total_realizadas) / total_solicitadas) * 100

    totales = [[
        'TOTALES',
        str(total_solicitadas),
        str(total_realizadas),
        str(total_pendientes),
        str(total_anuladas),
        str(total_efectividad)
    ]]

    data += format_data
    data += totales
    data += [['Observaciones', '']]

    t = Table(data,
              colWidths=3 * cm,
              rowHeights=1 * cm,
              splitByRow=1,
              repeatRows=0,
              repeatCols=0)

    t.setStyle(
        TableStyle([('FONTSIZE', (0, 0), (4, 3), 10),
                    ('FONTSIZE', (1, 4), (1, 4), 20),
                    ('FONTSIZE', (1, 4), (1, 4), 20),
                    ('SPAN', (1, -1), (-1, -1)),
                    ('GRID', (0, 6), (-1, -1), 0.25, colors.black),
                    ('ALIGN', (0, 6), (-1, -1), 'CENTER'),
                    ('VALIGN', (0, 6), (-1, -1), 'MIDDLE')]))

    t._rowHeights[4] = 2.5 * cm
    t._rowHeights[0] = 0.5 * cm
    t._rowHeights[1] = 0.5 * cm
    t._rowHeights[2] = 0.5 * cm
    t._rowHeights[3] = 0.5 * cm
    t._rowHeights[-1] = 4 * cm

    drawing = Drawing(400, 200)

    categories = []
    data = [[], [], [], []]
    categories = []
    max_x = 0
    steps = 0.5
    for key in table_data.keys():
        categories.append(key)
        max_x = max(max_x, table_data[key]['totales'])
        data[0].append(table_data[key]['totales'])
        data[1].append(table_data[key]['realizadas'])
        data[2].append(table_data[key]['pendientes'])
        data[3].append(table_data[key]['anuladas'])
        pass

    steps = max_x / 10.0

    bc = VerticalBarChart()
    bc.x = -35
    bc.y = 20
    bc.height = 150
    bc.width = 510
    bc.data = data
    bc.barSpacing = 1
    bc.strokeColor = colors.black
    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = max_x * 1.1
    bc.valueAxis.valueStep = steps
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 8
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 15
    bc.categoryAxis.categoryNames = categories

    for i in range(len(data)):
        bc.bars[(0, i)].fillColor = colors.blue
        bc.bars[(1, i)].fillColor = colors.green
        bc.bars[(2, i)].fillColor = colors.red
        bc.bars[(3, i)].fillColor = colors.grey

    drawing.add(bc)

    elements.append(t)
    elements.append(drawing)
    doc.build(elements)

    data = open(tmpfilename, "rb").read()
    os.unlink(tmpfilename)
    response.headers['Content-Type'] = 'application/pdf'
    return data
Beispiel #23
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
Beispiel #24
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)
    def print_sensor_data(self, report_instance):
        buffer = self.buffer
        doc = SimpleDocTemplate(buffer,
                                rightMargin=50,
                                leftMargin=50,
                                topMargin=20,
                                bottomMargin=50,
                                pagesize=self.pagesize)

        # A large collection of style sheets pre-made for us
        styles = getSampleStyleSheet()
        styles.add(ParagraphStyle(name='centered', alignment=TA_CENTER))

        style_Normal = styles["Normal"]
        style_Normal.textColor = colors.black

        style_Alerta = styles["Normal"]
        style_Alerta.textColor = colors.black

        style_Title = styles["Heading1"]
        style_Title.alignment = TA_LEFT

        style_Title_Center = styles["Heading1"]
        style_Title_Center.alignment = TA_CENTER

        # Our container for 'Flowable' objects
        elements = []

        # Saltos de linea
        saltosDeLineax1 = Paragraph("<br/>", style_Title)
        saltosDeLineax2 = Paragraph("<br/><br/>", style_Title)
        saltosDeLineax3 = Paragraph("<br/><br/><br/>", style_Title)

        # ps = ParagraphStyle('title', fontSize=20, leading=24)
        #  p1 = "here is some paragraph to see in large font"
        # Paragraph(p1, ps),

        # Tabla con reporte de incidencias y LOGOS.
        titulo_data = []
        titulo_table = []
        logo_cliente = Paragraph(
            '' + report_instance.sensor.arduino.project.enterprise.name,
            style_Normal)
        titulo_ciente = Paragraph(
            'Reporte de incidencias<br/>Sensor ' +
            report_instance.sensor.description, style_Title_Center)

        img_sensait = Image("arduino/static/sensait/logos/Sensait_logo.png")
        img_sensait.drawHeight = 8 * mm
        img_sensait.drawWidth = 20 * mm

        titulo_data.append((logo_cliente, titulo_ciente, img_sensait))

        titulo_table = Table(titulo_data,
                             colWidths=(50 * mm, 100 * mm, 50 * mm))
        titulo_table.setStyle(
            TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.white),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.white)]))
        elements.append(titulo_table)

        elements.append(saltosDeLineax2)

        resumen_data = []
        resumen_table = []

        resumen_laboratorio = Paragraph(
            '<b>Laboratorio:</b><br/>' +
            report_instance.sensor.arduino.project.name, style_Normal)
        resumen_equipo = Paragraph(
            '<b>Equipo:</b><br/>' + report_instance.sensor.arduino.name,
            style_Normal)
        resumen_serie = Paragraph(
            '<b>Modelo:</b><br/>' +
            report_instance.sensor.arduino.modelo_transmisor, style_Normal)

        resumen_data.append(
            (resumen_laboratorio, resumen_equipo, resumen_serie))

        resumen_periodo = Paragraph(
            '<b>Periodo:</b><br/>' + datetime.fromtimestamp(
                report_instance.fecha_inicial).strftime('%d/%m/%Y %H:%M:%S') +
            " al <br/>" + datetime.fromtimestamp(
                report_instance.fecha_final).strftime('%d/%m/%Y %H:%M:%S'),
            style_Normal)

        # Cantidad de Dias del reporte seleccionado.
        difEpochDias = (report_instance.fecha_final -
                        report_instance.fecha_inicial) / 86400
        periodoReporte = "Dia"

        if difEpochDias == 30:
            periodoReporte = "Mensual"
        elif difEpochDias == 15 or difEpochDias == 14:
            periodoReporte = "Quincenal"
        elif difEpochDias == 7 or difEpochDias == 6:
            periodoReporte = "Semanal"
        elif difEpochDias != 1:
            periodoReporte = str(difEpochDias) + " dias"
        else:
            periodoReporte = str(difEpochDias) + " Dia"

        resumen_rangodias = Paragraph(
            '<b>Periodo Generado:</b><br/>' + str(periodoReporte),
            style_Normal)
        resumen_void = Paragraph(" ", style_Normal)

        resumen_data.append((resumen_periodo, resumen_rangodias, resumen_void))

        # resumen_proyecto = Paragraph('<b>Proyecto:</b><br/>' + report_instance.sensor.arduino.project.name, style_Normal)
        # resumen_transmisor = Paragraph('<b>Transmisor:</b><br/>' + report_instance.sensor.arduino.name, style_Normal)
        # resumen_void = Paragraph(" ", style_Normal)

        # resumen_data.append((resumen_proyecto, resumen_transmisor, resumen_void))

        resumen_sensor = Paragraph(
            '<b>Sensor:</b><br/>' + report_instance.sensor.description,
            style_Normal)
        resumen_valmin = Paragraph(
            '<b>Valor Minimo:</b><br/>' +
            "%.2f" % report_instance.sensor.min_value, style_Normal)
        resumen_valmax = Paragraph(
            '<b>Valor Maximo:</b><br/>' +
            "%.2f" % report_instance.sensor.max_value, style_Normal)

        resumen_data.append((resumen_sensor, resumen_valmin, resumen_valmax))

        # VALORES MINIMOS Y MAXIMOS CALCULO.
        min_value = report_instance.sensor.min_value
        max_value = report_instance.sensor.max_value

        totalAlertas = 0
        promedioRegistros = 0.0
        totalRegistros = 0

        valmax = 0
        valmin = 0

        # Tabla de ejemplo
        main_table = []
        dataTable_L = []
        dataTable_R = []
        table_data = []

        all_alerts = []
        alert_list = []

        dataTable_L.append(
            ("Fecha y Hora", "Lectura", "Estado", "Numero incidencia"))
        sensorStatus = "Correcto"

        for num, data in enumerate(report_instance.sensor_data(), start=0):
            if str(data.data) != str("-127.00"):
                totalRegistros = num
                promedioRegistros += float(data.data)
                if num == 0:
                    valmin = float(data.data)
                if float(data.data) > float(max_value) or float(
                        min_value) > float(data.data):
                    sensorStatus = "Fuera de Rango"
                    alert_list.append(data)
                    totalAlertas += 1
                else:
                    sensorStatus = "Correcto"
                    if len(alert_list) > 0:
                        # print "New List " + str(len(all_alerts))
                        all_alerts.append(list(alert_list))
                        alert_list = []

                if float(data.data) > float(valmax):
                    valmax = float(data.data)
                if float(valmin) > float(data.data):
                    valmin = float(data.data)

                if len(alert_list) > 0:
                    alerta_code = "Alerta # " + str(len(all_alerts))
                else:
                    alerta_code = " "

                dataTable_L.append((datetime.fromtimestamp(
                    data.epoch).strftime('%d/%m/%Y %H:%M:%S'), data.data,
                                    sensorStatus, alerta_code))

        table_L = Table(dataTable_L, colWidths=[(doc.width) / 4.0] * 4)
        table_L.setStyle(
            TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]))

        print promedioRegistros
        print totalRegistros
        if float(promedioRegistros) == 0 and float(promedioRegistros) == 0:
            val_promedio = 0
        else:
            val_promedio = float(promedioRegistros) / float(totalRegistros)

        resumen_promedio = Paragraph(
            '<b>Temperatura Promedio:</b><br/>' + "%.2f" % val_promedio,
            style_Normal)
        resumen_minima = Paragraph(
            '<b>Temperatura Minimo Registrada:</b><br/>' + "%.2f" % valmin,
            style_Normal)
        resumen_maxima = Paragraph(
            '<b>Temperatura Maxima Registrada:</b><br/>' + "%.2f" % valmax,
            style_Normal)

        resumen_data.append((resumen_promedio, resumen_minima, resumen_maxima))

        resumen_totalregistros = Paragraph(
            '<b>Total de Registros:</b><br/>' + "%.2f" % totalRegistros,
            style_Normal)
        resumen_totalfuera = Paragraph(
            '<b>Resumen Registros:</b><br/>' + "X %.2f" % totalAlertas +
            "<br/> + %.2f" % (totalRegistros - totalAlertas), style_Normal)
        resumen_alertasregistradas = Paragraph(
            '<b>Total alertas registradas:</b><br/>' + str(len(all_alerts)),
            style_Normal)
        resumen_void = Paragraph(" ", style_Normal)

        resumen_data.append((resumen_totalregistros, resumen_totalfuera,
                             resumen_alertasregistradas))

        resumen_table = Table(resumen_data,
                              colWidths=[(doc.width) / 3.0] * 3,
                              rowHeights=(16 * mm))
        resumen_table.setStyle(
            TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.white),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.white),
                        ('VALIGN', (0, 0), (-1, -1), 'TOP')]))
        elements.append(resumen_table)

        # Informacion del reporte digamos LEGAL.
        # elements.append(Paragraph('La informacion que se despliega a continuacion son propiedad de la empresa que contrata el servicio de SENSAIT. La informacion que se despliega a continuacion son propiedad de la empresa que contrata el servicio de SENSAIT. ', styles['Normal']))

        elements.append(saltosDeLineax3)

        valores_Correctos = int(totalRegistros - totalAlertas)
        drawing = Drawing(400, 200)
        data = [(valores_Correctos, int(totalAlertas))]
        bc = VerticalBarChart()
        bc.x = 50
        bc.y = 50
        bc.height = 200
        bc.width = 400
        bc.data = data
        bc.barSpacing = 2.5
        bc.barWidth = 5
        bc.strokeColor = colors.black
        bc.valueAxis.valueMin = 0
        bc.valueAxis.valueMax = int(totalRegistros)
        bc.valueAxis.valueStep = 50
        bc.categoryAxis.labels.boxAnchor = 'ne'
        bc.categoryAxis.labels.dx = 8
        bc.categoryAxis.labels.dy = -2
        # bc.categoryAxis.labels.angle = 30
        bc.categoryAxis.categoryNames = [
            'Correctos = ' + str(valores_Correctos),
            'Fuera de Rango = ' + str(totalAlertas)
        ]
        bc.bars[(0, 0)].fillColor = colors.green
        bc.bars[(0, 1)].fillColor = colors.red
        drawing.add(bc)
        elements.append(drawing)

        elements.append(
            Paragraph(
                'Responsable ' +
                report_instance.sensor.arduino.project.nombre_encargado,
                style_Title))

        elements.append(PageBreak())

        # table_R = Table(dataTable_R, colWidths=[(doc.width) / 3.0] * 3)
        # table_R.setStyle(TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]))

        # dataTable_Main = [table_L]  table_R
        # table_Main = Table(table_L, colWidths=[doc.width])
        # table_Main.setStyle(TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.red), ('BOX', (0, 0), (-1, -1), 0.25, colors.red)]))

        # Tabla con todos los registros...
        elements.append(
            Paragraph(
                str(len(all_alerts)) + ' ALERTAS REGISTRADAS',
                style_Title_Center))

        # Tablas POR ALERTA...
        alert_data_tables = []
        alerts_tables = []
        alert_content = []

        alerts_onedata_data = []
        alerts_onedata_table = []
        # print "all_alerts.len()"
        # print len(all_alerts)

        alerts_onedata_data.append(
            ("Fecha Alerta", "# Registros en alerta ", "Valor"))
        alert_max_value = float(report_instance.sensor.max_value)
        alert_min_value = float(report_instance.sensor.min_value)

        for num, alertlist in enumerate(all_alerts, start=0):
            print str(len(alertlist))
            # Esto genera la tabla para un rango de registros NO LO QUITARE jeje
            if len(alertlist) > 200:
                one_fecha = str(
                    datetime.fromtimestamp(
                        alertlist[len(alertlist) -
                                  1].epoch).strftime('%d/%m/%Y %H:%M:%S'))
                one_registros = len(alertlist)
                one_value = str(alertlist[len(alertlist) - 1].data)
                alerts_onedata_data.append(
                    (one_fecha, one_registros, one_value))
                # alerts_onedata_data.append( alertlist[num] , drawing))
            else:
                titulo = Paragraph('<b>Alerta # ' + str(num) + ' </b>',
                                   style_Normal)

                alert_data_tables = []
                alert_content = []
                alert_graph = []
                alert_limit = []
                alert_graph_dates = []

                alerta_primer_registro = Paragraph(
                    '<b>Fecha inicio alerta:</b><br/>' + str(
                        datetime.fromtimestamp(alertlist[0].epoch).strftime(
                            '%d/%m/%Y %H:%M:%S') + "<br/><br/>"), style_Normal)
                alerta_ultima_registro = Paragraph(
                    '<b>Fecha final alerta:</b><br/>' + str(
                        datetime.fromtimestamp(alertlist[len(alertlist) -
                                                         1].epoch).
                        strftime('%d/%m/%Y %H:%M:%S') + "<br/><br/>"),
                    style_Normal)
                tiempoAlerta = alertlist[0].epoch - alertlist[len(alertlist) -
                                                              1].epoch

                print "difEpoch: " + str(alertlist[len(alertlist) - 1].epoch)
                print "difEpochR: " + str(tiempoAlerta)
                print "difEpoch: " + str(alertlist[0].epoch)

                alerta_duracion = Paragraph(
                    '<b>Duracion alerta:</b><br/>' + str(
                        datetime.fromtimestamp(tiempoAlerta).strftime('%M:%S')
                        + "<br/><br/>"), style_Normal)
                alerta_total_registros = Paragraph(
                    '<b>Registros fuera de rango:</b><br/>' +
                    str(len(alertlist)) + "<br/><br/>", style_Normal)
                rango_maximo = Paragraph(
                    '<b>Valor Maximo:</b><br/>' +
                    "%.2f" % report_instance.sensor.max_value + "<br/><br/>",
                    style_Normal)
                rango_minimo = Paragraph(
                    '<b>Valor Maximo:</b><br/>' +
                    "%.2f" % report_instance.sensor.min_value + "<br/><br/>",
                    style_Normal)
                alerta_comentarios = Paragraph(
                    "<b>Comentarios:</b><br/>__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________<br/>",
                    style_Normal)
                alerta_accioncorrectiva = Paragraph(
                    "<b>Accion correctiva:</b><br/>__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________<br/>",
                    style_Normal)

                alerta_data = []
                alerta_table = []

                alerta_data.append((titulo, " "))
                alerta_data.append(
                    (alerta_primer_registro, alerta_ultima_registro))
                alerta_data.append((alerta_duracion, alerta_total_registros))
                alerta_data.append((rango_maximo, rango_minimo))
                alerta_data.append((" ", saltosDeLineax2))
                # alerta_data.append((alerta_comentarios))

                alerta_table = Table(alerta_data, colWidths=(50 * mm, 50 * mm))
                alerta_table.setStyle(
                    TableStyle([
                        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.white),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.white)
                    ]))

                # alert_content.append(alerta_primer_registro)
                # alert_content.append(alerta_ultima_registro)
                # alert_content.append(alerta_duracion)
                # alert_content.append(alerta_total_registros)
                # alert_content.append(rango_maximo)
                # alert_content.append(rango_minimo)
                # alert_content.append(alerta_comentarios)
                # alert_content.append(saltosDeLineax2)
                valMax = 0
                valMin = 0
                valTmp = 0

                for ids, alert in enumerate(alertlist, start=0):
                    # print alert.data
                    # datos = Paragraph(str(alert.data), style_Normal)
                    valTmp = float(alert.data)
                    # print "tmp: " + str(valTmp)
                    # print "max: " + str(valMax)
                    # print "min: " + str(valMin)
                    if float(valTmp >= 0):
                        if float(valTmp) > float(valMax):
                            valMax = valTmp
                            if valMin == 0:
                                valMin = float(valTmp)

                        if float(valMin) > float(valTmp):
                            valMin = float(valTmp)

                    else:
                        if float(valTmp) < float(valMax):
                            valMax = valTmp
                            if valMin == 0:
                                valMin = float(valTmp)

                        if float(valTmp) > float(valMin):
                            valMin = float(valTmp)

                    valueData = float(alert.data)

                    alert_graph.append(valueData)
                    alert_limit.append(alert_max_value)
                    alert_graph_dates.append(
                        str(
                            datetime.fromtimestamp(
                                alert.epoch).strftime('%H:%M:%S')))
                # END FOR
                print "tmp: " + str(valTmp)
                print "max: " + str(valMax)
                print "min: " + str(valMin)

                # CALCULAR BIEN LOS LIMITES DE LA GRAFICA
                if float(valMin) >= 0:
                    lim_min = float(valMin - 1)

                elif float(valMax) >= 0:
                    lim_max = float(valMax + 2)

                elif float(valMax) < 0:
                    lim_max = float(valMax - 2)

                elif float(valMin) < 0:
                    lim_min = float(valMin - 1)
                # END CALCULAR LIMITES

                lim_min = valMin
                lim_max = valMax

                print "lim_min: " + str(lim_min)
                print "lim_max: " + str(lim_max)

                drawing = Drawing(200, 220)
                data = [alert_graph, alert_limit]
                lc = HorizontalLineChart()
                lc.x = 10
                lc.y = 30
                lc.height = 150
                lc.width = 220
                lc.data = data
                # lc.strokeColor = colors.black
                catNames = alert_graph_dates
                lc.categoryAxis.categoryNames = catNames
                lc.categoryAxis.labels.dx = 0
                lc.categoryAxis.labels.dy = -15
                lc.categoryAxis.labels.angle = 75
                lc.categoryAxis.labels.boxAnchor = 'n'
                lc.joinedLines = 1
                lc.lines[0].symbol = makeMarker('FilledCircle')
                # lc.lineLabelFormat = '%2.0f'
                # lc.strokeColor = colors.black
                lc.valueAxis.valueMin = lim_min
                lc.valueAxis.valueMax = lim_max
                lc.valueAxis.valueStep = 1
                lc.lines[0].strokeWidth = 2
                # lc.lines[1].strokeWidth = 1.5
                drawing.add(lc)

                # print "endFor"

                alert_data_tables.append((drawing, alerta_table))
                alert_data_tables.append(
                    (alerta_comentarios, alerta_accioncorrectiva))

                alerts_tables = Table(alert_data_tables,
                                      colWidths=[(doc.width) / 2.0] * 2)
                alerts_tables.setStyle(
                    TableStyle([
                        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.white),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.white)
                    ]))
                elements.append(alerts_tables)

                # elements.append(PageBreak())

        if len(alerts_onedata_data) > 1:

            elements.append(
                Paragraph('ALERTAS CON 5 REGISTROS O MENOS',
                          style_Title_Center))
            elements.append(saltosDeLineax1)
            alerts_onedata_table = Table(alerts_onedata_data,
                                         colWidths=[(doc.width) / 3.0] * 3)
            alerts_onedata_table.setStyle(
                TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25,
                             colors.black),
                            ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]))
            elements.append(alerts_onedata_table)
            # elements.append(PageBreak())

        elements.append(PageBreak())
        elements.append(Paragraph('DETALLE DE REGISTROS', style_Title_Center))
        elements.append(table_L)
        # elements.append(table_R)

        # Se agrega el llamado del header y footer
        doc.build(elements,
                  onFirstPage=self._header_footer,
                  onLaterPages=self._header_footer,
                  canvasmaker=NumberedCanvas)