Example #1
0
    def test_24_PieCharts(self):
        from reportlab.lib.styles import getSampleStyleSheet
        from reportlab.lib import colors
        from reportlab.lib.units import inch
        from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph
        from reportlab.pdfbase import pdfmetrics
        from reportlab.graphics.shapes import Drawing
        from reportlab.pdfbase.ttfonts import TTFont
        from reportlab.graphics.charts.piecharts import Pie

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

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

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

        d = Drawing(400,200)
        data = [13,5,20,22,37,45]
        pc = Pie()
        pc.x = 65
        pc.y = 15
        pc.width = 150
        pc.height = 150
        pc.data = data
        pc.labels = ['a','b','c','d','e','f']
        d.add(pc)

        elements.append(d)

        doc.build(elements)
Example #2
0
def get_pie_image(width, height, x, y, datas, lables, _colors):
    """
        ��ɱ�״ͼ
    @param width: ͼƬ���
    @param height: ͼƬ�Ŀ��
    @param x: ͼƬ��x���
    @param y: ͼƬ��y���
    @param datas: ���ͼƬ�����
    @param lables: ��״ͼ���������
    """

    from reportlab.graphics.charts.piecharts import Pie
    drawing = Drawing(width, height)
    pc = Pie()
    pc.width = 80
    pc.height = 80
    pc.x = x
    pc.y = y
    pc.data = datas
    pc.labels = lables
    pc.slices.strokeWidth = 0.5
    pc.startAngle = 90
    pc.checkLabelOverlap = True
    pc.sideLabels = True
    pc.sideLabelsOffset = 0.1
    pc.direction = 'clockwise'
    for i in range(len(lables)):
        pc.slices[i].fontName = "msyh"
        pc.slices[i].fontSize = 3
        pc.slices[i].labelRadius = 3
        pc.slices[i].popout = 5
        pc.slices[i].fillColor = _colors[i]
    drawing.add(pc)
    return drawing
Example #3
0
    def test_24_PieCharts(self):
        from reportlab.lib.styles import getSampleStyleSheet
        from reportlab.lib import colors
        from reportlab.lib.units import inch
        from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph
        from reportlab.pdfbase import pdfmetrics
        from reportlab.graphics.shapes import Drawing
        from reportlab.pdfbase.ttfonts import TTFont
        from reportlab.graphics.charts.piecharts import Pie

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

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

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

        d = Drawing(400, 200)
        data = [13, 5, 20, 22, 37, 45]
        pc = Pie()
        pc.x = 65
        pc.y = 15
        pc.width = 150
        pc.height = 150
        pc.data = data
        pc.labels = ['a', 'b', 'c', 'd', 'e', 'f']
        d.add(pc)

        elements.append(d)

        doc.build(elements)
Example #4
0
    def __add_graph(self):
        drawing = Drawing(200, 100)
        data = list()
        labels = list()

        self.c.drawString(370, 730, 
            'Distribucion en pesos'.encode('utf-8'))

        for acc in self.accounts:
            balance = acc.balance
            if acc.currency == 'USD':
                balance = balance * self.dolar

            data.append(balance)
            labels.append(acc.name)

        pie = Pie()
        pie.x = 280
        pie.y = 630
        pie.height = 100
        pie.width = 100
        pie.data = data
        pie.labels = labels
        pie.simpleLabels = 1
        pie.slices.strokeWidth = 1
        pie.slices.strokeColor = black
        pie.slices.label_visible = 0

        legend = Legend()
        legend.x = 400
        legend.y = 680
        legend.dx              = 8
        legend.dy              = 8
        legend.fontName        = 'Helvetica'
        legend.fontSize        = 7
        legend.boxAnchor       = 'w'
        legend.columnMaximum   = 10
        legend.strokeWidth     = 1
        legend.strokeColor     = black
        legend.deltax          = 75
        legend.deltay          = 10
        legend.autoXPadding    = 5
        legend.yGap            = 0
        legend.dxTextSpace     = 5
        legend.alignment       = 'right'
        legend.dividerLines    = 1|2|4
        legend.dividerOffsY    = 4.5
        legend.subCols.rpad    = 30
        n = len(pie.data)
        self.__setItems(n,pie.slices,
            'fillColor',self.pdf_chart_colors)

        legend.colorNamePairs = [(pie.slices[i].fillColor, 
            (pie.labels[i][0:20],'$%0.2f' % pie.data[i])) for i in xrange(n)]


        drawing.add(pie)
        drawing.add(legend)
        x, y = 0, 0
        renderPDF.draw(drawing, self.c, x, y, showBoundary=False)
Example #5
0
    def __init__(self,
                 drawing=None,
                 data=None,
                 x=70,
                 y=25,
                 width=115,
                 height=115):

        pie = Pie()
        pie.strokeColor = white
        pie.slices.strokeColor = white
        pie.slices.popout = 1
        pie.width = width
        pie.height = height
        pie.y = y
        pie.x = x
        pie.sideLabels = 1
        pie.slices.fontName = 'Lato'
        pie.slices.fontSize = 9

        colors = get_n_random_colors(len(data))
        for i in range(0, len(data)):
            pie.slices[i].fillColor = toColor(colors[i])

        pie.data = [value for (_, value) in data]
        pie.labels = [key for (key, _) in data]

        drawing.add(pie)
def draw_time_repartition(mandate):
    drawing = Drawing(width=180*mm, height=120*mm)
    pdf_chart_colors = [HexColor("#fa9d00"), HexColor("#006884"), HexColor("#00909e"), HexColor("#ffd08d"), ]
    pie = Pie()
    pie.x = 60*mm
    pie.y = 35*mm
    pie.width = 60*mm
    pie.height = 60*mm
    pie.slices.strokeWidth = 0.5
    pie.slices.fontName = 'Helvetica'
    pie.slices.fontSize = 8
    pie.data = []
    pie.labels = []
    titles = []
    add_data_and_titles_to_pie(pie, titles, mandate.research_percent, 'research_percent')
    add_data_and_titles_to_pie(pie, titles, mandate.tutoring_percent, 'tutoring_percent')
    add_data_and_titles_to_pie(pie, titles, mandate.service_activities_percent, 'service_activities_percent')
    add_data_and_titles_to_pie(pie, titles, mandate.formation_activities_percent, 'formation_activities_percent')
    if len(pie.data) > 0:
        drawing.add(pie)
        add_legend_to_pie(drawing)
        n = len(pie.data)
        set_items(n, pie.slices, 'fillColor', pdf_chart_colors)
        drawing.legend.colorNamePairs = \
            [(pie.slices[i].fillColor, (titles[i], '%0.f' % pie.data[i] + '%')) for i in range(n)]
    return drawing
Example #7
0
def overview_month_spending_breakdown_pie(c, h, w):
    categories = [
        'Clothing', 'Transport', 'Insurance', 'Food', 'Medical and Dental',
        'Housing', 'Utilities', 'Education', 'Gifts', 'Entertainment'
    ]
    d = Drawing()
    pie = Pie()
    pie.sideLabels = 1
    pie._seriesCount = 10
    my_data = []
    for x in categories:
        my_data.append(data.category_data(x.lower(), month, 2019))
    pie.x = 0
    pie.y = 0
    pie.width = 100

    pie.height = pie.width
    pie.data = my_data
    pie.slices.fontName = serif_font
    pie.slices.fontSize = 11
    pie.labels = tuple(categories)
    pie.slices.strokeWidth = 0.5
    #pie.slices[3].popout = 20
    d.add(pie)
    d.drawOn(c, h, w)
Example #8
0
def create_pie_chart(data, labels, legend=False):
    from reportlab.graphics.charts.piecharts import Pie
    from reportlab.graphics.shapes import Drawing

    d = Drawing(250, 275)
    pie = Pie()
    # required by Auto
    pie._seriesCount = len(data)

    pie.x = 175
    pie.y = 100
    pie.width = 150
    pie.height = 150
    pie.data = data
    pie.labels = labels
    pie.simpleLabels = 0
    pie.sideLabels = True
    pie.slices.strokeWidth = 0.5

    for i in range(0, len(colores)):
        pie.slices[i].fillColor = colores[i]

    if legend:
        add_legend(d, pie, data)

    d.add(pie)

    #d.save(formats=['pdf'], outDir='.', fnRoot='test-pie')
    return d
Example #9
0
def monthly_spending_breakdown_pie(c, category, h, w, v=False):
    d = Drawing()
    pie = Pie()
    pie.sideLabels = 1
    pie._seriesCount = 10
    output = []
    my_data = []
    output = data.cat_ind_data(category, month, year)

    my_data = output[1]
    labels = output[0]
    if sum(my_data) == 0:
        return
    pie.x = 0
    pie.y = 0
    pie.width = 100
    pie.height = pie.width
    pie.data = my_data
    pie.slices.fontName = serif_font
    pie.slices.fontSize = 11
    pie.labels = labels
    pie.slices.strokeWidth = 0.5
    #pie.slices[3].popout = 20
    d.add(pie)
    d.drawOn(c, h, w)
Example #10
0
def category_budget_left_pie(c, category, h, w):
    my_data = []
    for x in range(1, month + 1):
        my_data.append(data.category_data(category, x, year))
    labels = month_name[1:month + 1]
    labels.append('Budget')
    my_data.append(data.category_budget(category) - sum(my_data))
    d = Drawing()
    pie = Pie()
    pie.sideLabels = 1
    pie._seriesCount = 10
    #if legend:
    #    add_legend(d, pie, data)
    pie.x = 0
    pie.y = 0
    pie.width = 100
    pie.height = pie.width
    pie.data = my_data
    pie.slices.fontName = serif_font
    pie.slices.fontSize = 11
    pie.labels = labels
    pie.slices.strokeWidth = 0.5
    #pie.slices[3].popout = 20
    d.add(pie)
    d.drawOn(c, h, w)
Example #11
0
def monthly_spending_cat_pie(c, category, h, w, v=False):
    d = Drawing()
    pie = Pie()
    pie.sideLabels = 1
    pie._seriesCount = 10
    spent = 0
    my_data = []
    for i in range(1, month + 1):
        spent += int(data.month_code(category, i, year))
    print(spent, category)
    my_data.append(spent)
    my_data.append(data.code_budget(category) - spent)
    labels = [f'{category} spending', 'budget left']
    if sum(my_data) == 0:
        return
    pie.x = 0
    pie.y = 0
    pie.width = 50
    pie.height = pie.width
    pie.data = my_data
    pie.slices.fontName = serif_font
    pie.slices.fontSize = 11
    pie.labels = labels
    pie.slices.strokeWidth = 0.5
    #pie.slices[3].popout = 20
    d.add(pie)
    d.drawOn(c, h, w)
Example #12
0
def draw_pie(data=[], labels=[], use_colors=[], width=360, Height=150):
    '''更多属性请查询reportlab.graphics.charts.piecharts.WedgeProperties'''

    pie = Pie()
    pie.x = 60  # x,y饼图在框中的坐标
    pie.y = 20
    pie.slices.label_boxStrokeColor = colors.white  #标签边框的颜色

    pie.data = data  # 饼图上的数据
    pie.labels = labels  # 数据的标签
    pie.simpleLabels = 0  # 0 标签在标注线的右侧;1 在线上边
    pie.sameRadii = 1  # 0 饼图是椭圆;1 饼图是圆形

    pie.slices.strokeColor = colors.red  # 圆饼的边界颜色
    pie.strokeWidth = 1  # 圆饼周围空白区域的宽度
    pie.strokeColor = colors.white  # 整体饼图边界的颜色
    pie.slices.label_pointer_piePad = 10  # 圆饼和标签的距离
    pie.slices.label_pointer_edgePad = 25  # 标签和外边框的距离
    pie.width = width
    pie.height = Height
    pie.direction = 'clockwise'
    pie.pointerLabelMode = 'LeftRight'
    # for i in range(len(labels)):
    #     pie.slices[i].fontName = 'song' #设置中文
    for i, col in enumerate(use_colors):
        pie.slices[i].fillColor = col
    return pie
Example #13
0
    def __init__(self, width, height, labels, data):
        IRender.__init__(self, width, height, labels, data)

        #self.w = self.width
        #self.h = self.height
        #data = {}
        #for value in self.data:
        #    data[value[0]] = int(value[1])

        #plot = cairoplot.PiePlot('/tmp/tmp.png', data, self.w*2, self.h*2, gradient=True)
        ##plot.font_size *= 2
        #plot.render()
        #plot.commit()
        #with open('/tmp/tmp.png') as f:
        #    self.image = Image(StringIO(f.read()), self.w, self.h)
        pc = Pie()
        pc.width = min(self.height,self.width - 150)
        pc.height = min(self.height - 50,self.width)
        pc.width = pc.height = min(pc.height, pc.width)
        pc.x = self.width / 2 - pc.width / 2
        pc.y = self.height / 2 - pc.height / 2
        pc.data = [int(line[1]) for line in self.data]
        pc.labels = [line[0] for line in self.data]

        for i in xrange(len(self.data)):
            pc.slices[i].fillColor = COLORS[i % len(COLORS)]
            pc.slices[i].strokeColor = COLORS[i % len(COLORS)]
        self.drawing = Drawing(self.width, self.height)
        self.drawing.add(pc)
Example #14
0
def build_pdf():
    fruit = {"elderberries": 1,"figs": 1,"apples": 2,"durians": 3,"bananas": 5,"cherries": 8,"grapes": 13}
    report = SimpleDocTemplate("/home/scottdavis/eclipse-workspace/module1/report.pdf")
    styles = getSampleStyleSheet()
    report_title = Paragraph("A Complete Inventory of My Fruit", styles["h1"])
    table_data = []
    for k, v in fruit.items():
        table_data.append([k, v])
    
    table_style = [('GRID', (0,0), (-1,-1), 1, colors.black)]
    report_table = Table(data=table_data, style=table_style, hAlign="LEFT")
    
    
    report_pie = Pie()
    #width=3*inch, height=3*inch
    report_pie.width = 180
    report_pie.height = 180
    report_pie.data = []
    report_pie.labels = []
    
    for fruit_name in sorted(fruit):
        report_pie.data.append(fruit[fruit_name])
        report_pie.labels.append(fruit_name)
    
    report_chart = Drawing()
    report_chart.add(report_pie)
    
    report.build([report_title, report_table, report_chart])
Example #15
0
def overview_budget_spent(c, w, h):
    my_data = data.monthly_total(year)
    my_data = my_data[0:month]
    budget = data.budget() - sum(my_data)
    my_data.append(budget)
    my_label = []
    label = [
        'January', 'Febuary', 'March', 'April', 'May', 'June', 'July',
        'August', 'September', 'October', 'November', 'December'
    ]
    for j in range(0, month):
        my_label.append(label[j])
    my_label.append('Budget remaining')
    d = Drawing()
    pie = Pie()
    pie.sideLabels = 1
    pie._seriesCount = 10
    pie.x = 0
    pie.y = 0
    pie.width = 100
    pie.height = pie.width
    pie.data = my_data
    pie.slices.fontName = serif_font
    pie.slices.fontSize = 11
    pie.labels = my_label
    pie.slices.strokeWidth = 0.5
    pie.slices[-1].popout = 20
    d.add(pie)
    d.drawOn(c, w, h)
Example #16
0
    def on_btnInforme_clicked(self, boton):
        """
        Función que controla el comportamiento del botón "btnInforme".
        Genera un informe general sobre cuantos clientes hay registrados en cada servicio usando ReportLab.

        :param boton:
        :return:
        """
        # 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 = ['Seguro Coche', 'Seguro Moto', 'Sin Seguro']
        # porciones
        # tarta.slices.strokeWidth = 0.5
        # tarta.slices[3].popout = 50
        # tarta.slices[3].strokeWidth = 5
        # tarta.slices[3].strokeDashArray = [5, 2]  # pixels de la linea (tamaño)
        # tarta.slices[3].labelRadius = 1.75
        # tarta.slices[3].fontColor = colors.red
        tarta.sideLabels = 0
        cores = [colors.blue, colors.red, colors.green]

        # coge cada elemento y le asigna un numero
        for i, color in enumerate(cores):
            tarta.slices[i].fillColor = color

        d2.add(tarta)

        lenda = Legend()
        lenda.x = 270
        lenda.y = 0
        lenda.dx = 8
        lenda.dy = 8  # espacio entre lineas (?)
        lenda.fontName = "Helvetica"
        lenda.fontSize = 8
        lenda.boxAnchor = 'n'
        lenda.columnMaximum = 3
        lenda.strokeColor = colors.black
        lenda.deltax = 75
        lenda.deltay = 10
        lenda.autoXPadding = 5
        lenda.yGap = 0
        lenda.dxTextSpace = 5
        lenda.alignment = 'right'
        lenda.dividerLines = 1 | 2 | 4  #
        lenda.dividerOffsY = 4.5
        lenda.subCols.rpad = 30

        d2.add(lenda)

        doc = SimpleDocTemplate("informeGrafica.pdf", pagesize=A4)
        doc.build([d2])
Example #17
0
def readings_and_mix_table(reading_data, mix_data, breakdown, state_emission, location, Elements):
    '''
    Creates 2 tables that are then embedded as the columns of 1 bigger table
    '''
    no_rows = 1  # not used
    no_cols = 1
    col_size = 4.5

    readings_table = Table(reading_data, no_cols*[col_size/2*inch], 5*[0.25*inch] + [0.3*inch], hAlign="LEFT")
    readings_table.setStyle(TableStyle([('FONT', (0,0), (-1,-1), "Times-Roman"),
                                         ('FONT', (0,0), (-1,0), "Times-Bold"),
                                         ('FONTSIZE', (0,0), (-1,-1), 12),
                                         ('FONTSIZE', (0,0), (-1,0), 13),
                                         ('ALIGN', (0,0), (0,-1), "RIGHT"),
                                         ('VALIGN', (-1,-1), (-1,-1), "TOP")]))


    d = Drawing(100, 100)
    pc = Pie()

    data = []
    if state_emission:
        data = ["Coal", "Oil", "Natural Gas", "Low Carbon"]
    else:
        data = ["Coal", "Petroleum", "Natural Gas", "Low Carbon"]

    for i in range(4):
        data[i] += ": " + str(round(breakdown[i], 1)) + "%"

    pc.x = 45
    pc.y = 0
    pc.width = 55
    pc.height = 55
    pc.data = breakdown[:4]
    pc.slices[0].fillColor = colors.Color(202.0/255, 0.0/255, 32.0/255)
    pc.slices[1].fillColor = colors.Color(244.0/255, 165.0/255, 130.0/255)
    pc.slices[2].fillColor = colors.Color(5.0/255, 113.0/255, 176.0/255)
    pc.slices[3].fillColor = colors.Color(146.0/255, 197.0/255, 222.0/255)
    pc.labels = data
    pc.slices.strokeWidth=0.5
    pc.sideLabels = True
    d.add(pc)

    mix_data = [['Energy Mix Data'], [d], ['Location: ' + location]]
    mix_table = Table(mix_data, no_cols*[col_size/2*inch], [.25*inch, 1*inch, .3*inch], hAlign="RIGHT")
    mix_table.setStyle(TableStyle([('FONT', (0,0), (-1,-1), "Times-Roman"),
                                   ('FONT', (0,0), (0,0), "Times-Bold"),
                                   ('FONTSIZE', (0,0), (0,0), 13),
                                   ('FONTSIZE', (-1,-1), (-1,-1), 12),
                                   ('ALIGN', (0,0), (0,0), "LEFT")]))


    table_data = [(readings_table, mix_table)]
    t = Table(table_data, [4.25*inch, 3*inch], hAlign='CENTER')
    t.setStyle(TableStyle([('VALIGN', (-1,-1), (-1,-1), "TOP")]))
    Elements.append(t)
Example #18
0
def pie_chart(data_for_pie):
    d = Drawing(400, 400)
    pc = Pie()
    pc.x = 100
    pc.y = 210
    pc.width = 170
    pc.height = 170
    pc.sideLabels = True
    pc.sideLabelsOffset = 0.05
    car_name_lst = []
    car_sales_lst = []
    car_price_lst = []
    data_for_pie = data_for_pie[1:]
    data_for_pie = sorted(data_for_pie, key=itemgetter(3),
                          reverse=True)  # so i can show 10 most popular cars
    for i in data_for_pie:
        car_name = i[1]
        car_name_lst.append(car_name)
        car_sales = i[3]
        car_sales_lst.append(car_sales)
        car_price = float(i[2].strip(
            "$"))  #by default all the prices are in '', for example '18731.76'
        car_price_lst.append(car_price)
    pc.data = car_sales_lst[:10]
    pc.labels = list(set(
        car_name_lst[:10]))  # by using set i wont have similar items in list
    d.add(pc, '')
    """have to done this because in task i have to calculate revenue on Xaxis and car name on Yaxis"""
    revenue_calculation_1 = car_sales_lst[:10]
    revenue_calculation_2 = car_price_lst[:10]
    car_revenue_list = []
    for i in range(len(car_price_lst[:10])):
        reven = revenue_calculation_1[i] * revenue_calculation_2[i]
        car_revenue_list.append(
            int(reven))  #using int because its many digits after ","
    """bar chart """
    data = [tuple(car_revenue_list)
            ]  #for some reason bar chart accepts only [[]] or [()]
    bc = VerticalBarChart()
    bc.x = 50
    bc.y = 0
    bc.height = 125
    bc.width = 300
    bc.data = data
    bc.strokeColor = colors.black
    bc.valueAxis.valueMin = 7000000
    bc.valueAxis.valueMax = 23000000
    bc.valueAxis.valueStep = 1000000
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 8
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 30
    bc.categoryAxis.categoryNames = list(set(car_name_lst[:10]))
    d.add(bc)

    return d
Example #19
0
def draw_Pie(story, ProjectID):
    d = Drawing(140, 180)
    pie = Pie()
    pie.sideLabels = 1
    pie.labels = get_story_name_list(ProjectID)
    pie.data = get_story_count_list(ProjectID)
    pie.width = 140
    pie.height = 140
    pie.y = 0
    pie.x = 150
    d.add(pie)
    story.append(d)
Example #20
0
    def __init__(self, drawing=None, data=None):
        #Drawing.__init__(self, width=100, height=175)

        pie = Pie()
        pie.strokeColor = white
        pie.slices.strokeColor = white
        pie.slices.popout = 1
        pie.width = 100
        pie.height = 100
        pie.y = 50
        pie.x = 80

        legend = Legend()
        legend.columnMaximum = 99
        legend.alignment = 'right'
        legend.boxAnchor = 'c'
        legend.dx = 6
        legend.dy = 6
        legend.dxTextSpace = 5
        legend.deltay = 10
        legend.strokeWidth = 0
        legend.strokeColor = white
        legend.subCols[0].minWidth = 75
        legend.subCols[0].align = 'left'
        legend.subCols[1].minWidth = 25
        legend.subCols[1].align = 'right'
        legend.y = 20
        legend.x = 128
        legend.fontName = 'Lato'
        legend.fontSize = 9

        pie.data = data
        pie.slices[0].fillColor = lightgrey
        pie.slices[1].fillColor = limegreen
        pie.slices[1].popout = 6
        pie.slices[2].fillColor = red
        #pie.slices[2].popout = 1

        neutral_pct = positive_pct = negative_pct = 0
        total = sum(data)
        if total > 0:
            neutral_pct = (data[0] / total) * 100.0
            positive_pct = (data[1] / total) * 100.0
            negative_pct = (data[2] / total) * 100.0

        legend.colorNamePairs = [
            (limegreen, ('Positive', '%.1f%%' % positive_pct)),
            (lightgrey, ('Neutral', '%.1f%%' % neutral_pct)),
            (red, ('Negative', '%.1f%%' % negative_pct))
        ]

        drawing.add(pie)
        drawing.add(legend)
Example #21
0
    def __drawPage2LeftPie(self, c):
        totalHigh = len(self.scanParams['results']['HIGH'])
        totalMed = len(self.scanParams['results']['MED'])
        totalLow = len(self.scanParams['results']['LOW'])
        total = totalHigh + totalMed + totalLow

        # 第二页,左侧饼图,所有内容书写范围为Pleft:10mm Pright:100mm Pheader:247mm Pfooter:80mm
        Pleft = START_X + 10 * mm
        Pright = START_X + 100 * mm
        Pheader = START_Y + 247 * mm
        Pfooter = START_Y + 80 * mm

        #矩形框
        c.rect(Pleft, Pheader - 80 * mm, 80 * mm, 80 * mm, fill=0)
        c.setFont("song", 15)
        c.drawString(Pleft + 2 * mm, Pheader - 10 * mm, "漏洞等级分布")

        #饼图
        d = Drawing(400, 200)
        pc = Pie()
        pc.x = 65
        pc.y = 15
        pc.width = 70
        pc.height = 70
        pc.data = [totalHigh, totalMed, totalLow]
        pc.labels = ['高危', '中危', '低危']
        pc.sideLabels = 1
        pc.slices.strokeWidth = 0.5
        for i in range(3):
            pc.slices[i].fontName = 'song'
        #pc.slices[1].fontColor = colors.red
        pc.slices[1].fillColor = colors.red
        d.add(pc)
        #添加饼图到画布
        renderPDF.draw(d, c, Pleft + 6 * mm, Pheader - 55 * mm)

        #底部标注
        c.rect(Pleft + 5 * mm, Pheader - 75 * mm, 70 * mm, 8 * mm, fill=0)
        c.setFont("song", 7)
        c.circle(Pleft + 8 * mm, Pheader - 71 * mm, 2 * mm, fill=1)
        c.drawString(
            Pleft + 11 * mm, Pheader - 72 * mm,
            "高危(" + str(round((totalHigh / float(total)) * 100, 1)) + "%)")

        c.circle(Pleft + 28 * mm, Pheader - 71 * mm, 2 * mm, fill=1)
        c.drawString(
            Pleft + 31 * mm, Pheader - 72 * mm,
            "中危(" + str(round((totalMed / float(total)) * 100, 1)) + "%)")

        c.circle(Pleft + 48 * mm, Pheader - 71 * mm, 2 * mm, fill=1)
        c.drawString(
            Pleft + 51 * mm, Pheader - 72 * mm,
            "低危(" + str(round((totalLow / float(total)) * 100, 1)) + "%)")
Example #22
0
def draw_Pie(story, ProjectID):
    d = Drawing(140, 180)
    pie = Pie()
    pie.sideLabels = 1
    pie.labels= get_story_name_list(ProjectID)
    pie.data = get_story_count_list(ProjectID)
    pie.width = 140
    pie.height = 140
    pie.y = 0
    pie.x = 150
    d.add(pie)
    story.append(d)
Example #23
0
def makePie(pdf, SeBAz_contents, total):
    pdf.saveState()
    d = Drawing(A4[0] * 6 / 12, A4[1] * 5 / 17)
    pc = Pie()
    pc.x = A4[0] * 4 / 12
    pc.y = A4[1] * 5 / 17
    pc.width = A4[0] * 4 / 12
    pc.height = A4[0] * 4 / 12
    passd = len([s for s in SeBAz_contents if len(s) > 3 and s[2] == 'PASS'])
    faild = len([s for s in SeBAz_contents if len(s) > 3 and s[2] == 'FAIL'])
    check = len([s for s in SeBAz_contents if len(s) > 3 and s[2] == 'CHEK'])
    excluded = total - (passd + faild + check)
    pc.data = [passd, faild, excluded, check]
    pc.simpleLabels = 0
    pc.slices.strokeWidth = 0.5
    pc.slices.fontName = 'SF-Pro-Rounded-Heavy'
    pc.slices.fontSize = 8
    pc.slices.labelRadius = 1.1
    pc.slices[0].popout = 10
    pc.slices[0].fillColor = Color(colorPass[0] / 256, colorPass[1] / 256,
                                   colorPass[2] / 256, 1)
    pc.slices[0].fontColor = Color(colorPass[0] / 256, colorPass[1] / 256,
                                   colorPass[2] / 256, 1)
    pc.slices[
        0].label_text = 'which is {:.3f}% of all tests\n{} of {} tests ({:.3f}%) Passed,'.format(
            (passd / total) * 100, passd, (passd + faild + check),
            (passd / (passd + faild + check)) * 100)
    pc.slices[1].fillColor = Color(colorFail[0] / 256, colorFail[1] / 256,
                                   colorFail[2] / 256, 1)
    pc.slices[1].fontColor = Color(colorFail[0] / 256, colorFail[1] / 256,
                                   colorFail[2] / 256, 1)
    pc.slices[
        1].label_text = 'which is {:.3f}% of all tests\n{} of {} tests ({:.3f}%) Failed,'.format(
            (faild / total) * 100, faild, (passd + faild + check),
            (faild / (passd + faild + check)) * 100)
    pc.slices[2].fillColor = darkgray
    pc.slices[2].fontColor = darkgray
    pc.slices[2].label_text = '{} of {} tests ({:.0f}%) Excluded'.format(
        excluded, total, (excluded / total) * 100)
    pc.slices[3].fillColor = Color(colorWarn[0] / 256, colorWarn[1] / 256,
                                   colorWarn[2] / 256, 1)
    pc.slices[3].fontColor = Color(colorWarn[0] / 256, colorWarn[1] / 256,
                                   colorWarn[2] / 256, 1)
    pc.slices[
        3].label_text = 'which is {:.3f}% of all tests\n{} of {} tests ({:.3f}%) are to be Checked,'.format(
            (check / total) * 100, check, (passd + faild + check),
            (check / (passd + faild + check)) * 100)
    d.add(pc)
    renderPDF.draw(d, pdf, -A4[0] / 52, -A4[1] / 6)
    pdf.restoreState()
def graphout(prod_catnames, data):
    drawing = Drawing(500, 200)
    pie = Pie()

    pie.sideLabels       = 1
    pie.labels           = prod_catnames
    pie.data             =  data[0]
    pie.width            = 140
    pie.height           = 140
    pie.y                = 35
    pie.x                = 125
    pie.slices.popout = 5 
    
    drawing.add(pie)
        
    return drawing
Example #25
0
def pie_chart(car_data):
    report_pie = Pie()
    report_pie.width = 380
    report_pie.height = 380
    report_pie.x = 42
    report_pie.y = -230
    report_pie.data = []
    report_pie.labels = []
    car_make = {}
    for item in car_data:
        car_info = format_car(item["car"])
        report_pie.data.append(item["total_sales"])
        report_pie.labels.append(car_info)
    report_chart = Drawing()
    report_chart.add(report_pie)
    return (report_chart)
def graphout(prod_catnames, data):
    drawing = Drawing(500, 200)
    pie = Pie()

    pie.sideLabels = 1
    pie.labels = prod_catnames
    pie.data = data[0]
    pie.width = 140
    pie.height = 140
    pie.y = 35
    pie.x = 125
    pie.slices.popout = 5

    drawing.add(pie)

    return drawing
    def __init__(self, data, labels):
        super(PieChart, self).__init__(400,200)

        colors = [  
            HexColor("#0000e5"),  
            HexColor("#ff0011"),
            HexColor("#800000"),
            HexColor("#e05897"),   
            HexColor("#a08ff7"),  
            HexColor("#8f8ff5"),  
            HexColor("#c7c7fa"),  
            HexColor("#800000"),  
            HexColor("#eb8585"),   
            HexColor("#d60a0a"),  
            HexColor("#ffff00"),
            HexColor("#1f1feb"),   
        ]  

        # Create pie chart 
        pieChart = Pie()
        pieChart.x = 40
        pieChart.y = 30
        pieChart.width = 120
        pieChart.height = 120
        pieChart.slices.strokeWidth=0.5
        data = json.loads(data)
        pieChart.data = data
        pieChart.labels = []
        labels = json.loads(labels.replace("'",'"'))
        for d in data:
            pieChart.labels.append(str(d))

        # Create legend
        legend = Legend()
        legend.x = 380
        legend.y = 60  
        legend.boxAnchor           = 'se'  
        legend.subCols[1].align    = 'right'
        legend.colorNamePairs = []

        len_data = len(data) 
        for i in range(0,len_data):
            pieChart.slices[i].fillColor = colors[i]
            legend.colorNamePairs.append((colors[i],labels[i]))

        self.add(pieChart, "pie chart")       
        self.add(legend, "legend")
Example #28
0
    def __init__(self, data, labels):
        super(PieChart, self).__init__(400, 200)

        colors = [
            HexColor("#0000e5"),
            HexColor("#ff0011"),
            HexColor("#800000"),
            HexColor("#e05897"),
            HexColor("#a08ff7"),
            HexColor("#8f8ff5"),
            HexColor("#c7c7fa"),
            HexColor("#800000"),
            HexColor("#eb8585"),
            HexColor("#d60a0a"),
            HexColor("#ffff00"),
            HexColor("#1f1feb"),
        ]

        # Create pie chart
        pieChart = Pie()
        pieChart.x = 40
        pieChart.y = 30
        pieChart.width = 120
        pieChart.height = 120
        pieChart.slices.strokeWidth = 0.5
        data = json.loads(data)
        pieChart.data = data
        pieChart.labels = []
        labels = json.loads(labels.replace("'", '"'))
        for d in data:
            pieChart.labels.append(str(d))

        # Create legend
        legend = Legend()
        legend.x = 380
        legend.y = 60
        legend.boxAnchor = 'se'
        legend.subCols[1].align = 'right'
        legend.colorNamePairs = []

        len_data = len(data)
        for i in range(0, len_data):
            pieChart.slices[i].fillColor = colors[i]
            legend.colorNamePairs.append((colors[i], labels[i]))

        self.add(pieChart, "pie chart")
        self.add(legend, "legend")
Example #29
0
def create_pie(pie_data):
    pie_chart = Drawing(400, 200)
    pc = Pie()
    pc.x = 65
    pc.y = 15
    pc.width = 100
    pc.height = 100
    pc.data = pie_data["data"]     	     
    pc.labels = list(pie_data["label"][0]) 
    pc.slices.strokeWidth=0.5
    pc.slices[3].popout = 10
    pc.slices[3].strokeWidth = 2
    pc.slices[3].strokeDashArray = [2,2]
    pc.slices[3].labelRadius = 1.75
    pc.slices[3].fontColor = colors.red
    pie_chart.add(pc)
    return pie_chart
def generate(filename, title, additional_info, table_data):

    styles = getSampleStyleSheet()
    report = SimpleDocTemplate(filename)
    report_title = Paragraph(title, styles["h1"])
    report_info = Paragraph(additional_info, styles["BodyText"])
    table_style = [('GRID', (0, 0), (-1, -1), 1, colors.black),
                   ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
                   ('ALIGN', (0, 0), (-1, -1), 'CENTER')]
    report_table = Table(data=table_data, style=table_style, hAlign="LEFT")
    empty_line = Spacer(1, 20)

    sale_per_model = {}
    #print(table_data)
    for data in table_data[1:]:
        #print(data)
        if data[1].split()[0] not in sale_per_model:
            sale_per_model[data[1].split()[0]] = data[3]
        else:
            sale_per_model[data[1].split()[0]] += int(data[3])
    #print(sale_per_model)
    sorted_sales = sorted(sale_per_model.items(),
                          key=lambda kv: (kv[1], kv[0]))
    report_pie = Pie()
    report_pie.sideLabels = 1
    report_pie.checkLabelOverlap = 0
    report_pie.width = 300
    report_pie.height = 200
    report_pie.x = 120
    report_pie.y = 100

    report_pie.data = []
    report_pie.labels = []
    #print('sorted_sale '*20)
    #print(sorted_sales)
    for item in sorted_sales:
        report_pie.data.append(item[1])
        report_pie.labels.append(item[0])

    print(len(set(report_pie.labels)))
    report_chart = Drawing(500, 500)
    report_chart.add(report_pie)
    report.build([
        report_title, empty_line, report_info, empty_line, report_table,
        report_chart
    ])
Example #31
0
    def add_pie_chart(self, width, height, labels, data, side_labels=False):
        pad = 15

        pc = Pie()
        pc.x = pad * mm
        pc.y = pad * mm
        pc.width = (width - 2 * pad) * mm
        pc.height = (height - 2 * pad) * mm

        pc.labels = labels
        pc.data = data
        pc.sideLabels = side_labels

        drawing = Drawing(width * mm, height * mm)
        drawing.hAlign = "CENTER"
        drawing.add(pc)
        self.story.append(drawing)
Example #32
0
def graphout_pie(data, labels, sizeOfDrawing): # data and labels are both lists of same size
	drawing = Drawing(sizeOfDrawing*inch, sizeOfDrawing*inch)
	pc = Pie()
	pc.x = .125*inch
	pc.y = .125*inch
	pc.width = (sizeOfDrawing-0.25)*inch
	pc.height = (sizeOfDrawing-0.25)*inch
	pc.data = data
	pc.labels = None
	pc.slices.strokeWidth = 0.5
	
	# ensure pie chart and legend coloring matches
	for i in range(len(labels)):
		pc.slices[i].fillColor = colorList[i]

	drawing.add(pc)
	return drawing
def pie_graph(data, elements):
    drawing = Drawing(100, 350)
    pc = Pie()
    pc.x = 65
    pc.y = 15
    pc.width = 300
    pc.height = 300
    pc.data = data
    pc.labels = ['a', 'b', 'c', 'd', 'e', 'f']
    pc.slices.strokeWidth = 0.5
    pc.slices[3].popout = 10
    pc.slices[3].strokeWidth = 2
    pc.slices[3].strokeDashArray = [2, 2]
    pc.slices[3].labelRadius = 1.75
    pc.slices[3].fontColor = colors.red
    drawing.add(pc)
    elements.append(drawing)
def piegraph(elements):
    drawing = Drawing(100, 350)
    pc = Pie()
    pc.x = 65
    pc.y = 15
    pc.width = 300
    pc.height = 300
    pc.data = [10, 20, 30, 40, 50, 60]
    pc.labels = ['a', 'b', 'c', 'd', 'e', 'f']
    pc.slices.strokeWidth = 0.5
    pc.slices[3].popout = 10
    pc.slices[3].strokeWidth = 2
    pc.slices[3].strokeDashArray = [2, 2]
    pc.slices[3].labelRadius = 1.75
    pc.slices[3].fontColor = colors.red
    drawing.add(pc)
    elements.append(drawing)
    elements.append(Spacer(1, 0.7 * inch))
Example #35
0
def pie_chart_with_legend(doc, FI, Equity):
    data = ['Bond (' + str(FI[-1]) + '%)', 'Equity (' + str(Equity[-1]) + '%)']
    drawing = Drawing(width=doc.width / 2, height=250)
    my_title = String(140, -70, 'Asset-wise Allocation', fontSize=14)
    pie = Pie()
    pie.sideLabels = False
    pie.slices.label_visible = False
    pie.x = 100
    pie.y = -40
    pie.width = 200
    pie.height = 200
    pie.data = [FI[-1], Equity[-1]]
    pie.labels = data
    pie.slices.strokeWidth = 0.5
    drawing.add(my_title)
    drawing.add(pie)
    add_legend(drawing, pie, data, doc)
    return drawing
Example #36
0
    def _graphout(doc, category_names, data):
        drawing = Drawing(doc.width, 150)
        graph = Pie()
        graph.x = doc.width / 2 - 50
        graph.y = 0
        graph.height = 100
        graph.width = 100
        graph.labels = category_names
        graph.data = data
        graph.slices[0].fillColor = colors.darkcyan
        graph.slices[1].fillColor = colors.blueviolet
        graph.slices[2].fillColor = colors.blue
        graph.slices[3].fillColor = colors.cyan
        graph.slices[4].fillColor = colors.aquamarine
        graph.slices[5].fillColor = colors.cadetblue
        graph.slices[6].fillColor = colors.lightcoral

        drawing.add(graph)
        return drawing
Example #37
0
    def makePieChart(self, context, width, height, data, backColors):
        content=[]
        drawing = Drawing(width, height)
        pie=Pie()
        pie.data = data
        pie.x = 0
        pie.y = 0
        pie.width = width
        pie.height = height

        if len(data) == len(backColors):
            for i in range(len(data)) :
                pie.slices[i].fillColor = colors.HexColor(backColors[i])

        drawing.add(pie)

        content.append( drawing )

        return content
Example #38
0
def draw_pass_fail_piechart(passed_data: List[int]) -> Drawing:
    passed_data_labels = ['Passed', 'Failed', 'Not run']
    d = Drawing(width=200, height=200)
    pc = Pie()
    pc.x = 50
    pc.y = 50
    pc.width = 80
    pc.height = 80
    pc.slices[0].fillColor = COLOR_GREEN
    pc.slices[1].fillColor = COLOR_RED
    pc.slices[2].fillColor = COLOR_GRAY
    pc.direction = 'anticlockwise'
    pc.data = passed_data
    pc.labels = passed_data_labels
    pc.sideLabels = True
    pc.slices.fontName = MAIN_FONT_NAME
    pc.slices.fontSize = AXIS_FONT_SIZE
    d.add(pc)
    return d
 def _add_pie_chart(
     self,
     expense_stats: Dict[str, Tuple],
     size: int,
     padding: int,
 ):
     if expense_stats:
         figure = Drawing(self.width, min(size + 2 * padding, self.height))
         pie_chart = Pie()
         pie_chart.x = (self.width - size) / 2
         pie_chart.y = padding
         pie_chart.width = size
         pie_chart.height = size
         pie_chart.data = [i[0] for i in expense_stats.values()]
         pie_chart.labels = list(expense_stats.keys())
         pie_chart.slices.strokeWidth = 0.5
         pie_chart.sideLabels = True
         figure.add(pie_chart)
         self.report_elements.append(figure)
Example #40
0
    def pdf_drawPie(self,
                    pie_data,
                    pie_lable=[],
                    colors=[],
                    x=805,
                    y=1650,
                    width=900,
                    height=900,
                    innerRadiusFraction=0.5):
        '''
            @example:
                    chart_data = [1212,66,585,225,36]
                    lable = ['dfd','sdd','trtr','rrrr','ytytyt']
                    self.pdf_drawPie(chart_data,lable)
        '''

        if len(pie_data) == 0 or sum(pie_data) == 0:
            return
        d = Drawing(200, 100)
        pc = Pie()
        pc.x = 65
        pc.y = 65
        pc.width = width
        pc.height = height
        pc.data = pie_data
        pc.labels = pie_lable
        pc.startAngle = 0
        pc.sideLabels = 1
        pc.simpleLabels = 0
        if len(colors) != len(pie_data):
            colors = []
            for i in range(len(pie_data)):
                colors.append(HexColor(self.randomcolor()))
        for i in range(0, len(pie_data)):
            pc.slices[i].fontSize = 40
            pc.slices[i].fontName = FONT
            pc.slices[i].fillColor = colors[i]
            pc.slices[i].strokeColor = colors[i]
            pc.innerRadiusFraction = innerRadiusFraction
        d.add(pc)
        d.drawOn(self.pdf_page_object, x, y)
Example #41
0
    def generate_pie_charts(self):

        self.elements.append(
            Paragraph(
                "<u><font color=green>CHARTS</font></u><br/><br/>",
                ReportPDF.styleH)
            )

        # pie chart for categories
        pc_cat = Pie()
        pc_cat.x = 0
        pc_cat.width = ReportPDF.pie_charts_w
        pc_cat.height = ReportPDF.pie_charts_h
        pc_cat.data = []
        pc_cat.labels = []
        pc_cat.sideLabels = 1

        # pie chart for subcategories
        pc_subcat = Pie()
        pc_subcat.x = 250
        pc_subcat.width = ReportPDF.pie_charts_w
        pc_subcat.height = ReportPDF.pie_charts_h
        pc_subcat.data = []
        pc_subcat.labels = []
        pc_subcat.sideLabels = 1

        # get data for charts
        for stat, value in self.payments_stat_data.items():
            stat_vars = stat.split('_')
            if stat_vars[1] == 'category':
                pc_cat.data.append(float(value))
                pc_cat.labels.append(
                    get_object_or_404(Category, id=stat_vars[2])
                )
            elif stat_vars[1] == 'subcategory':
                pc_subcat.data.append(float(value))
                pc_subcat.labels.append(
                    get_object_or_404(Subcategory, id=stat_vars[2])
                )
            elif stat_vars[1] == 'time':
                self.lc_data.append(float(value))
                self.cat_names.append(stat_vars[2])

        # PIE CHARTS IN DRAWING
        if len(pc_cat.labels) > 1:
            self.elements.append(
                Paragraph(
                    "<u><b><font color=green>"
                    "Pie charts for categories and subcategories."
                    "</font></b></u>",
                    ReportPDF.styleN)
                )
            d_pie = Drawing(350, 240)
            d_pie.add(pc_cat)
            d_pie.add(pc_subcat)
            # add charts to PDF
            self.elements.append(d_pie)

        float_left = True
        counter = 0
        for category in pc_cat.labels:
            counter += 1
            pc_category = Pie()

            if float_left:
                pc_category.x = 0
                float_left = False
            else:
                pc_category.x = 250
                float_left = True

            pc_category.width = ReportPDF.pie_charts_w
            pc_category.height = ReportPDF.pie_charts_h
            pc_category.data = []
            pc_category.labels = []
            pc_category.sideLabels = 1

            subcategories = Subcategory.objects.filter(category=category)

            for sc_id in list(map(lambda sc: sc.id, subcategories)):
                # stats for subcategories
                subcategory_key = 'all_subcategory_{}'.format(sc_id)

                if self.payments_stat_data.get(subcategory_key, 0):
                    # self.payments_stat_data[subcategory_key] += p_value
                    pc_category.data.append(float(value))
                    pc_category.labels.append(
                        get_object_or_404(Subcategory, id=sc_id)
                    )

            if counter % 2 == 0:
                d_pie_categories.add(pc_category)

                if len(pc_cat.labels) % 2 == 0:
                    self.elements.append(
                        Paragraph(
                            "<br/><br/><br/><u><b><font color=green>"
                            "Pie chart for {} and {}."
                            "</font></b></u>".format(
                                last_category,
                                category
                            ),
                            ReportPDF.styleN)
                        )
                    self.elements.append(d_pie_categories)
            else:
                last_category = category
                d_pie_categories = Drawing(350, 240)
                d_pie_categories.add(pc_category)

                if len(pc_cat.labels) % 2 != 0:
                    self.elements.append(
                        Paragraph(
                            "<br/><br/><br/><u><b><font color=green>"
                            "Pie chart for {}."
                            "</font></b></u>".format(category),
                            ReportPDF.styleN)
                        )
                    self.elements.append(d_pie_categories)
Example #42
0
    def __per_account_statistic(self):

        for acc in self.accounts:
            p = PageBreak()
            p.drawOn(self.c, 0, 1000)
            self.c.showPage()
            self.l = 760

            self.c.setFont('Courier', 14)
            self.c.drawString(30, 800, 'Cuenta: %s' % \
                acc.name)

            header = ['Fecha', 'Tipo', 'Monto', 'Description']
            data   = [header]
            g_data = list()
            g_labe = list()
            total  = 0

            for tra in self.transactions:
                if tra.account == acc.name:
                    if tra.t_type in ['expense', 'transfer']:
                        tipo = self.__translate_type(tra.t_type)
                        data.append([tra.date, tipo.upper(),
                            '$%2.f' % tra.amount, tra.description])
                        total += tra.amount

                        g_data.append(tra.amount)
                        g_labe.append(tra.description.encode('utf-8'))

            data.append(['TOTAL', '', '$%.2f' % total, ''])

            if len(g_data) == 0 or len(g_labe) == 0:
                self.c.setFont('Courier', 12)
                self.c.drawString(30, 770, 'Sin movimientos negativos')
                continue
 
            from_title = 35
            if len(data) != 2:
                self.l -= ((len(data) * len(data)) + len(data)) + from_title

            t = Table(data)
            t.setStyle(TableStyle([('INNERGRID', (0,0), (-1,-1), 0.25, black),
                ('BOX', (0,0), (-1,-1), 0.25, black),
                ('FONTNAME', (0,0), (-1,0), 'Courier-Bold'),
                ('BACKGROUND', (0,0), (-1,0), HexColor('#efeded')),
                ('BACKGROUND', (0,0), (0,-1), HexColor('#efeded')),
                ('FONTSIZE', (0,0), (-1,0), 12),
                ('FONTSIZE', (0,1), (-1,-1), 8),
                ('FONTNAME', (0,1), (-1,-1), 'Courier'),
                ('BACKGROUND', (0,-1), (-1,-1), red),
                ('TEXTCOLOR', (0,-1), (-1,-1), white)]))

            t.wrapOn(self.c, 30, self.l)
            t.drawOn(self.c, 30, self.l)

            drawing = Drawing(200, 100)

            pie = Pie()
            pie.x = 30
            pie.y = self.l - 300
            pie.height = 200
            pie.width = 200
            pie.data = g_data
            pie.labels = g_labe
            pie.simpleLabels = 1
            pie.slices.strokeWidth = 1
            pie.slices.strokeColor = black
            pie.slices.label_visible = 0
            pie.slices.popout        = 1
            #pie.labels   = map(str, pie.data)

            
            legend = Legend()
            legend.x = 250
            legend.y = self.l - 250
            legend.dx              = 8
            legend.dy              = 8
            legend.fontName        = 'Helvetica'
            legend.fontSize        = 7
            legend.boxAnchor       = 'w'
            legend.columnMaximum   = 10
            legend.strokeWidth     = 1
            legend.strokeColor     = black
            legend.deltax          = 75
            legend.deltay          = 10
            legend.autoXPadding    = 5
            legend.yGap            = 0
            legend.dxTextSpace     = 5
            legend.alignment       = 'right'
            legend.dividerLines    = 1|2|4
            legend.dividerOffsY    = 4.5
            legend.subCols.rpad    = 30
            n = len(pie.data)
            self.__setItems(n,pie.slices,
                'fillColor',self.pdf_chart_colors)

            legend.colorNamePairs = [(pie.slices[i].fillColor, 
                (pie.labels[i][0:20],'$%0.2f' % pie.data[i])) for i in xrange(n)]
            

            drawing.add(pie)
            drawing.add(legend)
            x, y = 0, 10

            renderPDF.draw(drawing, self.c, x, y, showBoundary=False)
def generate_certificate(elements):
    style = TableStyle([('TEXTALIGN', (0, 0), (-1, -1), 'CENTER'),
                        ('TEXTCOLOR', (0, 0), (-1, -1), colors.red),
                        ('VALIGN', (0, 0), (0, -1), 'TOP'),
                        ('INNERGRID', (0, 0), (-1, -1), 0.50, colors.red),
                        ('BOX', (0, 0), (-1, -1), 0.50, colors.green),
                        ('BACKGROUND', (0, 0), (-1, -1), colors.blue),
                        ])
    s = getSampleStyleSheet()
    s = s["BodyText"]
    s.wordWrap = "RGB"
    styles = ParagraphStyle(
        name='Normal',
        fontName='Helvetica-Bold',
        fontSize=15,
        alignment=1,
    )
    elements.append(Spacer(1, 0.5 * inch))
    i = Paragraph(str("candidate performance vs average performance"), styles)
    elements.append(i)
    elements.append(Spacer(1, 0.1 * inch))
    drawing = Drawing(0, 200)  # for indices
    data = [
        (13, 5, 20, 22, 37, 45, 19, 4),
        (14, 6, 21, 23, 38, 46, 20, 5)
    ]  # data for drawing bar graphs
    bc = VerticalBarChart()
    bc.x = 0  # x,y define the left bottom of graph
    bc.y = 0
    bc.height = 150
    bc.width = 300
    bc.data = data
    bc.strokeColor = colors.black
    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = 50
    bc.valueAxis.valueStep = 10
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 6  # next 3 lines is for naming indices
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 60
    bc.categoryAxis.categoryNames = ['Jan-99', 'Feb-99', 'Mar-99',
                                     'Apr-99', 'May-99', 'Jun-99', 'Jul-99', 'Aug-99']
    drawing.add(bc)
    elements.append(drawing)
    elements.append(Spacer(1, 0.5 * inch))
    drawing = Drawing(0, 175)  # for indices
    lc = HorizontalLineChart()
    lc.x = 0
    lc.y = 10
    lc.height = 150
    lc.width = 300
    lc.data = data
    lc.joinedLines = 1
    catNames = 'Jan Feb Mar Apr May Jun Jul Aug'.split(' ')
    lc.categoryAxis.categoryNames = catNames
    lc.categoryAxis.labels.boxAnchor = 'n'
    lc.valueAxis.valueMin = 0
    lc.valueAxis.valueMax = 60
    lc.valueAxis.valueStep = 15
    lc.lines[0].strokeWidth = 2
    lc.lines[1].strokeWidth = 1.5
    drawing.add(lc)
    elements.append(drawing)
    drawing = Drawing(0, 400)  # for indices
    data = [
        ((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)),
        ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6))
    ]
    elements.append(Spacer(1, 0.1 * inch))
    i = Paragraph(str("candidate performance vs average performance"), styles)
    elements.append(i)
    elements.append(Spacer(1, 0.1 * inch))
    lp = LinePlot()
    lp.x = 0
    lp.y = 50
    lp.height = 300
    lp.width = 600
    lp.data = data
    lp.joinedLines = 1
    lp.lines[0].symbol = makeMarker('FilledCircle')
    lp.lines[1].symbol = makeMarker('Circle')
    lp.lineLabelFormat = '%2.0f'
    lp.strokeColor = colors.black
    lp.xValueAxis.valueMin = 0
    lp.xValueAxis.valueMax = 5
    lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5]
    lp.xValueAxis.labelTextFormat = '%2.1f'
    lp.yValueAxis.valueMin = 0
    lp.yValueAxis.valueMax = 7
    lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6]
    drawing.add(lp)
    elements.append(drawing)
    elements.append(Spacer(1, 0.1 * inch))
    drawing = Drawing(100, 350)
    pc = Pie()
    pc.x = 65
    pc.y = 15
    pc.width = 300
    pc.height = 300
    pc.data = [10, 20, 30, 40, 50, 60]
    pc.labels = ['a', 'b', 'c', 'd', 'e', 'f']
    pc.slices.strokeWidth = 0.5
    pc.slices[3].popout = 10
    pc.slices[3].strokeWidth = 2
    pc.slices[3].strokeDashArray = [2, 2]
    pc.slices[3].labelRadius = 1.75
    pc.slices[3].fontColor = colors.red
    drawing.add(pc)
    elements.append(drawing)
    elements.append(Spacer(1, 0.5 * inch))
    return elements
pc.slices[3].strokeDashArray = [2,2]
pc.slices[3].labelRadius = 1.75
pc.slices[3].fontColor = colors.red

d.add(pc)
""")

from reportlab.graphics.charts.piecharts import Pie

d = Drawing(200, 100)

pc = Pie()
pc.x = 65
pc.y = 15
pc.width = 70
pc.height = 70
pc.data = [10,20,30,40,50,60]
pc.labels = ['a','b','c','d','e','f']

pc.slices.strokeWidth=0.5
pc.slices[3].popout = 10
pc.slices[3].strokeWidth = 2
pc.slices[3].strokeDashArray = [2,2]
pc.slices[3].labelRadius = 1.75
pc.slices[3].fontColor = colors.red

d.add(pc)

draw(d, 'A bare bones pie chart')

disc("""
Example #45
0
def ListadoUsos(request):
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=num_aprobados_reprobados.pdf; pagesize=A4;'

    #Esta lista contendra todos los elementos que se dibujaran en el pdf
    elementos = []
    doc = SimpleDocTemplate(response)
    styleSheet = getSampleStyleSheet()
    #---> Estilo Titulo
    el_titulo = styleSheet['Heading1']
    el_titulo.alignment = TA_CENTER
    el_titulo.spaceBefore = 15
    el_titulo.fontSize = 12
    el_titulo.fontName = 'Helvetica'


    txtInfo = u'<br />A.C.C.E.M.A:'
    # Estilo txtInfo
    info = styleSheet['Normal']
    info.fontSize = 12
    info.alignment = TA_LEFT
    info.fontName = 'Helvetica'
    infoV = Paragraph(txtInfo, info)

    #-->Estilo tabla
    x = [
    ('ALIGN', (0,0), (-1,-1), 'CENTER'),
    ('TOPPADDING', (0,0), (-1,-1), 1),
    ('BOTTOMPADDING', (0,0), (-1,-1), 2),
    ('GRID', (0,0), (-1,-1), 0.80, colors.black),
    ('FONT', (0,0), (-1,-1), "Helvetica", 10),
    ('FONT', (0,0), (1,0), "Helvetica-Bold", 12),
    ]
    tabla = []

    #--> Titulo de la constancia
    elementos.append(Spacer(1,5))
    Titulo = Paragraph('<b>Estadisticas de usos</b>', el_titulo)
    elementos.append(Titulo)
    elementos.append(Spacer(1,5))

    #--> Añadiendo la Informción antes del cuadro
    elementos.append(infoV)
    elementos.append(Spacer(1,10))

    usuarios = User.objects.all()
    usos = UsosDisp.objects.all()


    tabla.append([' CANTIDAD DE USUARIOS', u'NÚMERO DE USOS'])
    tabla.append(['%s'%(usuarios.__len__()), u'%s'%(usos.__len__())])

    t1 = Table(tabla, colWidths=('', ''))
    t1.setStyle(TableStyle(x))
    elementos.append(t1)

    #--> Calculando los porcentajes
    total = usos.__len__()
    
    #--> Frame del gráfico
    frame = Drawing(350,200)
    torta = Pie()
    torta.x = 125
    torta.y = 35
    torta.width = 120
    torta.height = 120

    torta.labels = []
    contador = 0 
    for i in usuarios:
        #import ipdb;ipdb.set_trace()
        uso_actual = usos.filter(Usuario=i).count()
        porcen_usuario = (float(uso_actual) * 100) / total

        torta.labels.append('%3.2f%% %s'%(porcen_usuario, i.username))
        torta.data.append(porcen_usuario)

    #--> Estilos del gráfico
    torta.slices.labelRadius = 1
    torta.sideLabels = 1
    torta.slices.fontSize = 8
    torta.slices.fontName = 'Helvetica-Bold'
    torta.slices.strokeWidth = 2
    torta.slices.popout = 10

    frame.add(torta)
    elementos.append(frame)
    doc.build(elementos, canvasmaker=NumeroDePagina )
    return response
Example #46
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
    chart.lines[1].strokeColor = PCMYKColor(0,100,100,40,alpha=100)
    chart.xValueAxis.xLabelFormat            = '{mm}/{YY}'
    chart.data = [[('20120101', 100), ('20120102', 100), ('20120103', 101), ('20120104', 101), ('20120105', 102), ('20120106', 101), ('20120107', 101), ('20120108', 101), ('20120109', 102), ('20120110', 103), ('20120111', 103), ('20120112', 104), ('20120113', 103), ('20120114', 103), ('20120115', 103), ('20120116', 103), ('20120117', 103), ('20120118', 105), ('20120119', 106), ('20120120', 106), ('20120121', 106), ('20120122', 106), ('20120123', 106), ('20120124', 107), ('20120125', 108), ('20120126', 107), ('20120127', 107), ('20120128', 107), ('20120129', 107), ('20120130', 107), ('20120131', 107), ('20120201', 109), ('20120202', 109), ('20120203', 111), ('20120204', 111), ('20120205', 111), ('20120206', 111), ('20120207', 111), ('20120208', 111), ('20120209', 110), ('20120210', 109), ('20120211', 109), ('20120212', 109), ('20120213', 110), ('20120214', 110), ('20120215', 109), ('20120216', 111), ('20120217', 111), ('20120218', 111), ('20120219', 111), ('20120220', 111), ('20120221', 111), ('20120222', 111), ('20120223', 112), ('20120224', 111), ('20120225', 111), ('20120226', 111), ('20120227', 111), ('20120228', 111), ('20120229', 110), ('20120301', 111), ('20120302', 109), ('20120303', 109), ('20120304', 109), ('20120305', 109), ('20120306', 106), ('20120307', 108), ('20120308', 109), ('20120309', 111), ('20120310', 111), ('20120311', 111), ('20120312', 110), ('20120313', 113), ('20120314', 112), ('20120315', 113), ('20120316', 112), ('20120317', 112), ('20120318', 112), ('20120319', 113), ('20120320', 112), ('20120321', 112), ('20120322', 110), ('20120323', 111), ('20120324', 111), ('20120325', 111), ('20120326', 113), ('20120327', 113), ('20120328', 112), ('20120329', 112), ('20120330', 112), ('20120331', 112), ('20120401', 112), ('20120402', 113), ('20120403', 112), ('20120404', 110), ('20120405', 110), ('20120406', 110), ('20120407', 110), ('20120408', 110), ('20120409', 108), ('20120410', 106), ('20120411', 107), ('20120412', 109), ('20120413', 107), ('20120414', 107), ('20120415', 107), ('20120416', 107), ('20120417', 109), ('20120418', 108), ('20120419', 108), ('20120420', 108), ('20120421', 108), ('20120422', 108), ('20120423', 106), ('20120424', 107), ('20120425', 109), ('20120426', 110), ('20120427', 111), ('20120428', 111), ('20120429', 111), ('20120430', 110), ('20120501', 110), ('20120502', 110), ('20120503', 108), ('20120504', 106), ('20120505', 106), ('20120506', 106), ('20120507', 106), ('20120508', 106), ('20120509', 105), ('20120510', 106), ('20120511', 105), ('20120512', 105), ('20120513', 105), ('20120514', 104), ('20120515', 103), ('20120516', 103), ('20120517', 101), ('20120518', 100), ('20120519', 100), ('20120520', 100), ('20120521', 102), ('20120522', 102), ('20120523', 102), ('20120524', 102), ('20120525', 102), ('20120526', 102), ('20120527', 102), ('20120528', 102), ('20120529', 104), ('20120530', 102), ('20120531', 101), ('20120601', 98), ('20120602', 98), ('20120603', 98), ('20120604', 98), ('20120605', 99), ('20120606', 102), ('20120607', 101), ('20120608', 102), ('20120609', 102), ('20120610', 102), ('20120611', 100), ('20120612', 101), ('20120613', 99), ('20120614', 100), ('20120615', 101), ('20120616', 101), ('20120617', 101), ('20120618', 102), ('20120619', 103), ('20120620', 103), ('20120621', 100), ('20120622', 101), ('20120623', 101), ('20120624', 101), ('20120625', 99), ('20120626', 99), ('20120627', 100), ('20120628', 100), ('20120629', 103), ('20120630', 103), ('20120701', 103), ('20120702', 104), ('20120703', 106), ('20120704', 106), ('20120705', 106), ('20120706', 104), ('20120707', 104), ('20120708', 104), ('20120709', 104), ('20120710', 102), ('20120711', 102), ('20120712', 102), ('20120713', 103), ('20120714', 103), ('20120715', 103), ('20120716', 102), ('20120717', 103), ('20120718', 104), ('20120719', 104), ('20120720', 102), ('20120721', 102), ('20120722', 102), ('20120723', 101), ('20120724', 99), ('20120725', 100), ('20120726', 101), ('20120727', 104), ('20120728', 104), ('20120729', 104), ('20120730', 103), ('20120731', 103), ('20120801', 101), ('20120802', 101), ('20120803', 103), ('20120804', 103), ('20120805', 103), ('20120806', 104), ('20120807', 105), ('20120808', 105), ('20120809', 106), ('20120810', 106), ('20120811', 106), ('20120812', 106), ('20120813', 105), ('20120814', 105), ('20120815', 106), ('20120816', 107), ('20120817', 108), ('20120818', 108), ('20120819', 108), ('20120820', 107), ('20120821', 107), ('20120822', 107), ('20120823', 106), ('20120824', 106), ('20120825', 106), ('20120826', 106), ('20120827', 106), ('20120828', 107), ('20120829', 107), ('20120830', 106), ('20120831', 106), ('20120901', 106), ('20120902', 106), ('20120903', 106), ('20120904', 107), ('20120905', 107), ('20120906', 110), ('20120907', 110), ('20120908', 110), ('20120909', 110), ('20120910', 110), ('20120911', 110), ('20120912', 111), ('20120913', 112), ('20120914', 114), ('20120915', 114), ('20120916', 114), ('20120917', 113), ('20120918', 112), ('20120919', 112), ('20120920', 111), ('20120921', 111), ('20120922', 111), ('20120923', 111), ('20120924', 111), ('20120925', 109), ('20120926', 108), ('20120927', 110), ('20120928', 109), ('20120929', 109), ('20120930', 109), ('20121001', 109), ('20121002', 109), ('20121003', 109), ('20121004', 110), ('20121005', 110), ('20121006', 110), ('20121007', 110), ('20121008', 109), ('20121009', 108), ('20121010', 108), ('20121011', 108), ('20121012', 107), ('20121013', 107), ('20121014', 107), ('20121015', 108), ('20121016', 109), ('20121017', 110), ('20121018', 110), ('20121019', 108), ('20121020', 108), ('20121021', 108), ('20121022', 108), ('20121023', 107), ('20121024', 107), ('20121025', 107), ('20121026', 107), ('20121027', 107), ('20121028', 107), ('20121029', 107), ('20121030', 107), ('20121031', 109), ('20121101', 111), ('20121102', 109), ('20121103', 109), ('20121104', 109), ('20121105', 110), ('20121106', 111), ('20121107', 108), ('20121108', 107), ('20121109', 107), ('20121110', 107), ('20121111', 107), ('20121112', 107), ('20121113', 106), ('20121114', 104), ('20121115', 104), ('20121116', 105), ('20121117', 105), ('20121118', 105), ('20121119', 107), ('20121120', 107), ('20121121', 108), ('20121122', 108), ('20121123', 109), ('20121124', 109), ('20121125', 109), ('20121126', 109), ('20121127', 109), ('20121128', 109), ('20121129', 110), ('20121130', 110), ('20121201', 110), ('20121202', 110), ('20121203', 110), ('20121204', 110), ('20121205', 110), ('20121206', 110), ('20121207', 110), ('20121208', 110), ('20121209', 110), ('20121210', 111), ('20121211', 112), ('20121212', 112), ('20121213', 111), ('20121214', 111), ('20121215', 111), ('20121216', 111), ('20121217', 112), ('20121218', 114), ('20121219', 114), ('20121220', 114), ('20121221', 113), ('20121222', 113), ('20121223', 113), ('20121224', 113), ('20121225', 113), ('20121226', 112), ('20121227', 112), ('20121228', 112), ('20121229', 112), ('20121230', 112), ('20121231', 114)], [('20120101', 100), ('20120102', 100), ('20120103', 101), ('20120104', 100), ('20120105', 101), ('20120106', 101), ('20120107', 101), ('20120108', 101), ('20120109', 101), ('20120110', 103), ('20120111', 103), ('20120112', 104), ('20120113', 103), ('20120114', 103), ('20120115', 103), ('20120116', 103), ('20120117', 103), ('20120118', 105), ('20120119', 105), ('20120120', 105), ('20120121', 105), ('20120122', 105), ('20120123', 105), ('20120124', 106), ('20120125', 107), ('20120126', 107), ('20120127', 107), ('20120128', 107), ('20120129', 107), ('20120130', 107), ('20120131', 107), ('20120201', 109), ('20120202', 109), ('20120203', 112), ('20120204', 112), ('20120205', 112), ('20120206', 111), ('20120207', 111), ('20120208', 111), ('20120209', 111), ('20120210', 109), ('20120211', 109), ('20120212', 109), ('20120213', 111), ('20120214', 110), ('20120215', 109), ('20120216', 112), ('20120217', 111), ('20120218', 111), ('20120219', 111), ('20120220', 111), ('20120221', 111), ('20120222', 110), ('20120223', 112), ('20120224', 111), ('20120225', 111), ('20120226', 111), ('20120227', 111), ('20120228', 111), ('20120229', 109), ('20120301', 110), ('20120302', 108), ('20120303', 108), ('20120304', 108), ('20120305', 108), ('20120306', 106), ('20120307', 107), ('20120308', 109), ('20120309', 110), ('20120310', 110), ('20120311', 110), ('20120312', 110), ('20120313', 112), ('20120314', 111), ('20120315', 112), ('20120316', 112), ('20120317', 112), ('20120318', 112), ('20120319', 113), ('20120320', 112), ('20120321', 112), ('20120322', 111), ('20120323', 112), ('20120324', 112), ('20120325', 112), ('20120326', 114), ('20120327', 113), ('20120328', 112), ('20120329', 112), ('20120330', 112), ('20120331', 112), ('20120401', 112), ('20120402', 113), ('20120403', 113), ('20120404', 111), ('20120405', 110), ('20120406', 110), ('20120407', 110), ('20120408', 110), ('20120409', 108), ('20120410', 106), ('20120411', 107), ('20120412', 109), ('20120413', 107), ('20120414', 107), ('20120415', 107), ('20120416', 108), ('20120417', 109), ('20120418', 108), ('20120419', 108), ('20120420', 108), ('20120421', 108), ('20120422', 108), ('20120423', 107), ('20120424', 108), ('20120425', 110), ('20120426', 110), ('20120427', 111), ('20120428', 111), ('20120429', 111), ('20120430', 110), ('20120501', 110), ('20120502', 110), ('20120503', 109), ('20120504', 107), ('20120505', 107), ('20120506', 107), ('20120507', 107), ('20120508', 107), ('20120509', 106), ('20120510', 107), ('20120511', 107), ('20120512', 107), ('20120513', 107), ('20120514', 105), ('20120515', 105), ('20120516', 104), ('20120517', 102), ('20120518', 101), ('20120519', 101), ('20120520', 101), ('20120521', 103), ('20120522', 103), ('20120523', 103), ('20120524', 103), ('20120525', 103), ('20120526', 103), ('20120527', 103), ('20120528', 103), ('20120529', 105), ('20120530', 103), ('20120531', 103), ('20120601', 100), ('20120602', 100), ('20120603', 100), ('20120604', 100), ('20120605', 101), ('20120606', 103), ('20120607', 103), ('20120608', 104), ('20120609', 104), ('20120610', 104), ('20120611', 101), ('20120612', 103), ('20120613', 102), ('20120614', 103), ('20120615', 104), ('20120616', 104), ('20120617', 104), ('20120618', 104), ('20120619', 106), ('20120620', 106), ('20120621', 103), ('20120622', 105), ('20120623', 105), ('20120624', 105), ('20120625', 103), ('20120626', 103), ('20120627', 105), ('20120628', 105), ('20120629', 108), ('20120630', 108), ('20120701', 108), ('20120702', 109), ('20120703', 111), ('20120704', 111), ('20120705', 111), ('20120706', 109), ('20120707', 109), ('20120708', 109), ('20120709', 109), ('20120710', 108), ('20120711', 107), ('20120712', 107), ('20120713', 108), ('20120714', 108), ('20120715', 108), ('20120716', 108), ('20120717', 108), ('20120718', 109), ('20120719', 109), ('20120720', 107), ('20120721', 107), ('20120722', 107), ('20120723', 105), ('20120724', 104), ('20120725', 104), ('20120726', 105), ('20120727', 108), ('20120728', 108), ('20120729', 108), ('20120730', 107), ('20120731', 107), ('20120801', 104), ('20120802', 104), ('20120803', 107), ('20120804', 107), ('20120805', 107), ('20120806', 108), ('20120807', 109), ('20120808', 108), ('20120809', 109), ('20120810', 109), ('20120811', 109), ('20120812', 109), ('20120813', 108), ('20120814', 108), ('20120815', 109), ('20120816', 110), ('20120817', 111), ('20120818', 111), ('20120819', 111), ('20120820', 111), ('20120821', 110), ('20120822', 110), ('20120823', 109), ('20120824', 110), ('20120825', 110), ('20120826', 110), ('20120827', 110), ('20120828', 110), ('20120829', 111), ('20120830', 110), ('20120831', 110), ('20120901', 110), ('20120902', 110), ('20120903', 110), ('20120904', 111), ('20120905', 111), ('20120906', 114), ('20120907', 114), ('20120908', 114), ('20120909', 114), ('20120910', 114), ('20120911', 114), ('20120912', 115), ('20120913', 116), ('20120914', 117), ('20120915', 117), ('20120916', 117), ('20120917', 117), ('20120918', 116), ('20120919', 116), ('20120920', 116), ('20120921', 116), ('20120922', 116), ('20120923', 116), ('20120924', 116), ('20120925', 114), ('20120926', 113), ('20120927', 115), ('20120928', 114), ('20120929', 114), ('20120930', 114), ('20121001', 114), ('20121002', 114), ('20121003', 114), ('20121004', 115), ('20121005', 114), ('20121006', 114), ('20121007', 114), ('20121008', 114), ('20121009', 112), ('20121010', 112), ('20121011', 113), ('20121012', 112), ('20121013', 112), ('20121014', 112), ('20121015', 113), ('20121016', 113), ('20121017', 114), ('20121018', 114), ('20121019', 112), ('20121020', 112), ('20121021', 112), ('20121022', 111), ('20121023', 111), ('20121024', 111), ('20121025', 111), ('20121026', 110), ('20121027', 110), ('20121028', 110), ('20121029', 110), ('20121030', 110), ('20121031', 111), ('20121101', 113), ('20121102', 111), ('20121103', 111), ('20121104', 111), ('20121105', 111), ('20121106', 112), ('20121107', 109), ('20121108', 108), ('20121109', 108), ('20121110', 108), ('20121111', 108), ('20121112', 108), ('20121113', 107), ('20121114', 105), ('20121115', 105), ('20121116', 106), ('20121117', 106), ('20121118', 106), ('20121119', 108), ('20121120', 108), ('20121121', 109), ('20121122', 109), ('20121123', 110), ('20121124', 110), ('20121125', 110), ('20121126', 110), ('20121127', 110), ('20121128', 111), ('20121129', 112), ('20121130', 112), ('20121201', 112), ('20121202', 112), ('20121203', 112), ('20121204', 112), ('20121205', 112), ('20121206', 112), ('20121207', 112), ('20121208', 112), ('20121209', 112), ('20121210', 112), ('20121211', 114), ('20121212', 113), ('20121213', 112), ('20121214', 112), ('20121215', 112), ('20121216', 112), ('20121217', 114), ('20121218', 115), ('20121219', 116), ('20121220', 116), ('20121221', 116), ('20121222', 116), ('20121223', 116), ('20121224', 115), ('20121225', 115), ('20121226', 114), ('20121227', 114), ('20121228', 113), ('20121229', 113), ('20121230', 113), ('20121231', 116)]]
    chartCanvas.add(chart)
    renderPDF.draw(chartCanvas, c, 50, 400)

    pieChartCanvas = Drawing()
    pieChart = Pie()
    pieChart.data = [30.0, 21.0, 21.0, 14.0, 14.0]
    pieChart.slices[0].fillColor             = PCMYKColor(100,0,90,50,alpha=85)
    pieChart.slices[1].fillColor             = PCMYKColor(0,100,100,40,alpha=85)
    pieChart.slices[2].fillColor             = PCMYKColor(100,60,0,50,alpha=85)
    pieChart.slices[3].fillColor             = PCMYKColor(23,51,0,4,alpha=85)
    pieChart.slices[4].fillColor             = PCMYKColor(66,13,0,22,alpha=85)
    pieChart.width = 100
    pieChart.height = 100
    pieChart.slices.popout = 5
    pieChart.slices.strokeColor      = PCMYKColor(0,0,0,0)
    pieChart.slices.strokeWidth      = 0.5
    pieChartCanvas.add(pieChart)
    renderPDF.draw(pieChartCanvas, c, 100, 100)

    pieChartLegendCanvas = Drawing()
    pieChartLegend = Legend()
    pieChartLegend.x = 100
    pieChartLegend.y = 100
    pieChartLegend.alignment = "right"
    pieChartLegend.columnMaximum = 5
    pieChartLegend.colorNamePairs = [(PCMYKColor(100,0,90,50,alpha=100), ('BP', '30%')), (PCMYKColor(0,100,100,40,alpha=100), ('Shell Transport & Trading', '21%')), (PCMYKColor(100,60,0,50,alpha=100), ('Liberty International', '21%')), (PCMYKColor(23,51,0,4,alpha=100), ('Persimmon', '14%')), (PCMYKColor(66,13,0,22,alpha=100), ('Royal Bank of Scotland', '14%'))]
    pieChartLegendCanvas.add(pieChartLegend)
    renderPDF.draw(pieChartLegendCanvas, c, 100, 100)
Example #48
0
    def __get_tags_statistics(self):
        monto_categorias = dict()
        for tra in self.transactions:
            if len(tra.tags) > 0:
                for tag in tra.tags:
                    if tag in monto_categorias.keys():
                        monto_categorias[tag] += tra.amount
                    else:
                        monto_categorias[tag] = tra.amount

        labels = [lab.encode('utf-8') for lab in monto_categorias.keys()]
        data = monto_categorias.values()

        p = PageBreak()
        p.drawOn(self.c, 0, 1000)
        self.c.showPage()
        self.l = 600

        self.c.setFont('Courier', 14)
        self.c.drawString(30, 800, 'Categorias')

        drawing = Drawing(200, 200)

        pie = Pie()
        pie.x = 30
        pie.y = self.l - 130
        pie.height = 300
        pie.width = 300
        pie.data = data
        pie.labels = labels
        pie.simpleLabels = 1
        pie.slices.strokeWidth = 1
        pie.slices.strokeColor = black
        pie.slices.label_visible = 0

        legend = Legend()
        legend.x = 400
        legend.y = self.l
        legend.dx              = 8
        legend.dy              = 8
        legend.fontName        = 'Helvetica'
        legend.fontSize        = 7
        legend.boxAnchor       = 'w'
        legend.columnMaximum   = 10
        legend.strokeWidth     = 1
        legend.strokeColor     = black
        legend.deltax          = 75
        legend.deltay          = 10
        legend.autoXPadding    = 5
        legend.yGap            = 0
        legend.dxTextSpace     = 5
        legend.alignment       = 'right'
        legend.dividerLines    = 1|2|4
        legend.dividerOffsY    = 4.5
        legend.subCols.rpad    = 30
        n = len(pie.data)
        self.__setItems(n,pie.slices,
            'fillColor',self.pdf_chart_colors)

        legend.colorNamePairs = [(pie.slices[i].fillColor, 
            (pie.labels[i][0:20],'$%0.2f' % pie.data[i])) for i in xrange(n)]

        drawing.add(pie)
        drawing.add(legend)
        x, y = 0, 10

        renderPDF.draw(drawing, self.c, x, y, showBoundary=False)
Example #49
0
def generate_certificate(elements):
    styles = ParagraphStyle(
        name='Normal',
        fontName='Helvetica-Bold',
        fontSize=15,
        alignment=1,
    )
    elements.append(Spacer(1, 0.5 * inch))
    i = Paragraph(str("candidate performance vs average performance"), styles)
    elements.append(i)
    elements.append(Spacer(1, 0.1 * inch))
    drawing = Drawing(0, 200)  # for indices
    data = [
        (13, 5, 20, 22, 37, 45, 19, 4),
        (14, 6, 21, 23, 38, 46, 20, 5)
    ]  # data for drawing bar graphs
    bc = VerticalBarChart()
    bc.x = 0  # x,y define the left bottom of graph
    bc.y = 0
    bc.height = 150
    bc.width = 300
    bc.data = data
    bc.strokeColor = colors.black
    bc.valueAxis.valueMin = 0
    bc.valueAxis.valueMax = 50
    bc.valueAxis.valueStep = 10
    bc.categoryAxis.labels.boxAnchor = 'ne'
    bc.categoryAxis.labels.dx = 6  # next 3 lines is for naming indices
    bc.categoryAxis.labels.dy = -2
    bc.categoryAxis.labels.angle = 60
    bc.categoryAxis.categoryNames = ['Jan-99', 'Feb-99', 'Mar-99',
                                     'Apr-99', 'May-99', 'Jun-99', 'Jul-99', 'Aug-99']
    drawing.add(bc)
    elements.append(drawing)
    elements.append(Spacer(1, 0.5 * inch))
    drawing = Drawing(0, 175)  # for indices
    lc = HorizontalLineChart()
    lc.x = 0
    lc.y = 10
    lc.height = 150
    lc.width = 300
    lc.data = data
    lc.joinedLines = 1
    catnames = 'Jan Feb Mar Apr May Jun Jul Aug'.split(' ')
    lc.categoryAxis.categoryNames = catnames
    lc.categoryAxis.labels.boxAnchor = 'n'
    lc.valueAxis.valueMin = 0
    lc.valueAxis.valueMax = 60
    lc.valueAxis.valueStep = 15
    lc.lines[0].strokeWidth = 2
    lc.lines[1].strokeWidth = 1.5
    drawing.add(lc)
    elements.append(drawing)
    drawing = Drawing(0, 400)  # for indices
    data = [
        ((1, 1), (2, 2), (2.5, 1), (3, 3), (4, 5)),
        ((1, 2), (2, 3), (2.5, 2), (3.5, 5), (4, 6))
    ]
    elements.append(Spacer(1, 0.1 * inch))
    i = Paragraph(str("candidate performance vs average performance"), styles)
    elements.append(i)
    elements.append(Spacer(1, 0.1 * inch))
    lp = LinePlot()
    lp.x = 0
    lp.y = 50
    lp.height = 300
    lp.width = 600
    lp.data = data
    lp.joinedLines = 1
    lp.lines[0].symbol = makeMarker('FilledCircle')
    lp.lines[1].symbol = makeMarker('Circle')
    lp.lineLabelFormat = '%2.0f'
    lp.strokeColor = colors.black
    lp.xValueAxis.valueMin = 0
    lp.xValueAxis.valueMax = 5
    lp.xValueAxis.valueSteps = [1, 2, 2.5, 3, 4, 5]
    lp.xValueAxis.labelTextFormat = '%2.1f'
    lp.yValueAxis.valueMin = 0
    lp.yValueAxis.valueMax = 7
    lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6]
    drawing.add(lp)
    elements.append(drawing)
    elements.append(Spacer(1, 0.1 * inch))
    drawing = Drawing(100, 350)
    pc = Pie()
    pc.x = 65
    pc.y = 15
    pc.width = 300
    pc.height = 300
    pc.data = [10, 20, 30, 40, 50, 60]
    pc.labels = ['a', 'b', 'c', 'd', 'e', 'f']
    pc.slices.strokeWidth = 0.5
    pc.slices[3].popout = 10
    pc.slices[3].strokeWidth = 2
    pc.slices[3].strokeDashArray = [2, 2]
    pc.slices[3].labelRadius = 1.75
    pc.slices[3].fontColor = colors.red
    drawing.add(pc)
    elements.append(drawing)
    elements.append(Spacer(1, 0.7 * inch))
    styles = ParagraphStyle(
        name='Normal',
        fontName='Helvetica',
        fontSize=15,
        alignment=0,
    )
    elements.append(Spacer(1, 0.5* inch))
    i = Paragraph(str("Please click on black square to play the video."), styles)
    elements.append(i)
    
    elements.append(platypus.flowables.Macro('canvas.saveState()'))
    elements.append(platypus.flowables.Macro('canvas.linkURL("fun.mp4",(400,510,410,500),relative=0,thickness=10)'))
    elements.append(platypus.flowables.Macro('canvas.restoreState()'))
    return elements