示例#1
0
文件: pdf.py 项目: mfkiwl/drivers
 def categoryVvalueChart(self,
                         chapter,
                         ordinateValues,
                         abscissaCategories,
                         chartType='HorizontalBarChart',
                         markerType=None,
                         gridlinesX=False,
                         gridlinesY=True,
                         ordinateTics=10,
                         bIncludeZero=True,
                         ordinateFmtType='%0.3f',
                         chartIdx=0,
                         pageHfraction=1.0,
                         chartX=None,
                         chartY=None,
                         chartH=None,
                         chartW=None,
                         title="",
                         captionLabel="",
                         caption="",
                         fontname='',
                         fontsize='',
                         fontcolor=''):
     abscissaCategories, title, captionLabel, caption = GetUnicode(
         [abscissaCategories, title, captionLabel, caption])
     ##testing
     #from numpy import randn,histogram
     #mu,sigma = 100,15
     #x = list(mu + sigma*randn(10000))
     #ordinateTics=10
     #ordinateValues,abscissaCategories = histogram(x,100,normed=True)
     #ordinateValues,abscissaCategories = [list(ordinateValues)],list(abscissaCategories)
     #for idx in xrange(len(abscissaCategories)):
     #    if idx%5: abscissaCategories[idx]=''
     #    else: abscissaCategories[idx]='%.2f'%abscissaCategories[idx]
     ##print abscissaCategories[:10],abscissaCategories[-10:]
     ##testing
     # if no X/Y & H/W scaling specified, set to fill up page within margins
     if chartType in ("HorizontalBarChart", "HorizontalLineChart",
                      "VerticalBarChart"):  # note: no "VerticalLineChart"
         pageWidth, pageHeight = self.pagesize  # in points
         nLeft, nBottom, nRight, nTop = [
             val * inch
             for val in self.nLeft, self.nBottom, self.nRight, self.nTop
         ]  # inches to points
         availH, availW = pageHfraction * (
             pageHeight - (nTop + nBottom)), pageWidth - (nLeft + nRight)
         pgMinDim, pgMaxDim = min(pageWidth / inch, pageHeight / inch), max(
             pageWidth / inch, pageHeight / inch)  # inches
         nGutter = min(
             pgMinDim / 17., pgMaxDim / 22.
         ) * inch  # 0.5" nominal gutter based on 8.5" x 11" paper size
         # todo: QC size (e.g., >0)
         if chartX == None or chartY == None or chartH == None or chartW == None:
             chartX, chartY, chartH, chartW, drawH, drawW = nGutter, nGutter, availH - 3 * nGutter, availW - 1.25 * nGutter, availH - 1.5 * nGutter, availW - 0.5 * nGutter
         else:
             chartX, chartY, chartH, chartW = [
                 val * inch for val in chartX, chartY, chartH, chartW
             ]
             drawH, drawW = chartH + 1.5 * nGutter, chartW + 0.75 * nGutter
         bIsHorizontal, bIsBarChart = chartType.find(
             'Horizontal') == 0, chartType.find('BarChart') > 0
         if bIsHorizontal:
             if bIsBarChart:
                 bXisValueYisCategory, bXisCategoryYisValue = True, False
                 gridlinesX, gridlinesY = gridlinesY, gridlinesX
                 chartObj = HorizontalBarChart()
                 for dataSeries in ordinateValues:
                     dataSeries.reverse()
                 ordinateValues.reverse()
                 abscissaCategories.reverse()
             else:  # note: HorizontalLineChart has same aspect as VerticalBarChart
                 bXisValueYisCategory, bXisCategoryYisValue = False, True
                 chartObj = HorizontalLineChart()
         else:  # note: only vertical chart possible is barchart
             bXisValueYisCategory, bXisCategoryYisValue = False, True
             chartObj = VerticalBarChart()
         if bXisValueYisCategory:
             labelsAngle, labelsAnchor, labelsDX, labelsDY = 0, 'e', -max(
                 [len(val) for val in abscissaCategories]), 0
             if gridlinesX:
                 chartObj.valueAxis.tickUp = chartH
             if gridlinesY:
                 chartObj.categoryAxis.tickRight = chartW
         else:  # bXisCategoryYisValue
             labelsAngle, labelsAnchor, labelsDX, labelsDY = 30, 'ne', 0, 0
             if gridlinesX:
                 chartObj.categoryAxis.tickUp = chartH
             if gridlinesY:
                 chartObj.valueAxis.tickRight = chartW
         colorPalette = [
             colors.lightcoral, colors.cornflower, colors.darkseagreen,
             colors.tan, colors.aquamarine, colors.lightsteelblue,
             colors.cadetblue, colors.thistle, colors.steelblue
         ]
         if bIsBarChart:
             chartObj.bars[0].fillColor = colorPalette[chartIdx % len(
                 colorPalette
             )]  # todo: bars[0],[1],... if ordinateValues a list of lists (stacked bars)
         else:
             chartObj.joinedLines = 1
             chartObj.lines[
                 0].strokeWidth = 2  # todo: lines[0],[1],... if ordinateValues a list of lists (multiple lines)
             chartObj.lines[0].strokeColor = colorPalette[
                 chartIdx % len(colorPalette)]  # ibid.
             #todo: chartObj.lines[0].symbol = makeMarker('FilledCircle') # or 'Circle', others?
             if markerType:
                 chartObj.lines[0].symbol = makeMarker(markerType)
         chartObj.data = ordinateValues
         chartObj.x, chartObj.y = chartX, chartY
         chartObj.height, chartObj.width = chartH, chartW
         ordinateMin = min([
             min(ordinateValuesSet) for ordinateValuesSet in ordinateValues
         ])
         ordinateMax = max([
             max(ordinateValuesSet) for ordinateValuesSet in ordinateValues
         ])
         if bIncludeZero:
             ordinateMin = min(0, ordinateMin)
             ordinateMax = max(0, ordinateMax)
         # evaluate ordinate range in graph string-label space and adjust ordinate[Min,Max,Step] accordingly
         ordinateMinGstr, ordinateMaxGstr = [
             ordinateGstr.replace('%', '').split()[0]
             for ordinateGstr in (ordinateFmtType % ordinateMin,
                                  ordinateFmtType % ordinateMax)
         ]
         ordinateMinG, ordinateMaxG = float(ordinateMaxGstr), float(
             ordinateMinGstr)
         bAdjustMinMax = True
         if ordinateMinG == ordinateMaxG:
             # if constant y-value graph, set range to span from zero (regardless of bIncludeZero)
             bAdjustMinMax = False
             if ordinateMinG != 0.:  # y-values!=0
                 if ordinateMax > 0: ordinateMin = 0
                 else: ordinateMax = 0
             else:  # y-values==0, set range to [0,1]
                 ordinateMin, ordinateMax = 0, 1.
             ordinateMinG, ordinateMaxG = ordinateMin, ordinateMax
             ordinateTics = 2
         #  determine smallest significant ordinateStep, per desired ordinateTicSize--using stepwise reduction down to 1
         for ordinateTicSize in range(ordinateTics, 1, -1):
             ordinateStep = abs(
                 (ordinateMaxG - ordinateMinG) / ordinateTicSize)
             ordinateStepGstr = ordinateFmtType % ordinateStep
             ordinateStepGstr = ordinateStepGstr.replace('%', '').split()[0]
             ordinateStepG = float(ordinateStepGstr)
             if ordinateStepG != 0:
                 ordinateStep = ordinateStepG
                 break
         if bAdjustMinMax:
             if ordinateMin != 0:  # extend y-axis on low side...
                 ordinateMin -= ordinateStep
             if ordinateMax != 0:  # then extend y-axis on high side, but don't exceed 100%...
                 try:
                     if (ordinateMax + ordinateStep
                         ) >= 100 and ordinateFmtType[-1] == '%':
                         ordinateMax = 100.
                     else:
                         ordinateMax += ordinateStep
                 except:  # ostensibly b/c invalid ordinateFmtType
                     ordinateMax += ordinateStep
         chartObj.valueAxis.valueMin, chartObj.valueAxis.valueMax, chartObj.valueAxis.valueStep = ordinateMin, ordinateMax, ordinateStep
         chartObj.valueAxis.labelTextFormat = ordinateFmtType
         chartObj.categoryAxis.labels.boxAnchor = labelsAnchor
         chartObj.categoryAxis.labels.dx, chartObj.categoryAxis.labels.dy = labelsDX, labelsDY
         chartObj.categoryAxis.labels.angle = labelsAngle
         chartObj.categoryAxis.categoryNames = abscissaCategories
         chartObjDrawing = Drawing(drawW, drawH)
         chartObjDrawing.add(chartObj)
         if title:
             self.CPage(
                 chapter, 0.5 + drawH / inch
             )  # todo: had to hack this b/c [start,end]Keep not working
             self.clabel2(chapter, title, fontname, fontsize, fontcolor)
         self.report[chapter].append(chartObjDrawing)
         if captionLabel or caption:
             self.report[chapter].append(
                 self.aTextFlowable('<b>%s</b> %s' %
                                    (captionLabel, caption),
                                    fontname=fontname,
                                    fontsize=fontsize,
                                    fontcolor=fontcolor))
示例#2
0
def addAcTemp(canvas_param, opc_df_today, pos_x, pos_y, width, height):

    total_df = opc_df_today

    total_df_OAT = total_df[total_df.browse_name == 'OA-T']

    total_df_CSSWT = total_df[total_df.browse_name == 'CS-SWT']
    total_df_CSRWT = total_df[total_df.browse_name == 'CS-RWT']

    total_df_FSSWT = total_df[total_df.browse_name == 'FS-SWT']
    total_df_FSRWT = total_df[total_df.browse_name == 'FS-RWT']

    # 生成5个变量相应的点阵
    data_OAT = ExtractPointFromDf_DateX(
        df_origin=total_df_OAT,
        date_col='present_value_source_timestamp',
        y_col='present_value_value')

    data_CSSWT = ExtractPointFromDf_DateX(
        df_origin=total_df_CSSWT,
        date_col='present_value_source_timestamp',
        y_col='present_value_value')
    data_CSRWT = ExtractPointFromDf_DateX(
        df_origin=total_df_CSRWT,
        date_col='present_value_source_timestamp',
        y_col='present_value_value')

    data_FSSWT = ExtractPointFromDf_DateX(
        df_origin=total_df_FSSWT,
        date_col='present_value_source_timestamp',
        y_col='present_value_value')
    data_FSRWT = ExtractPointFromDf_DateX(
        df_origin=total_df_FSRWT,
        date_col='present_value_source_timestamp',
        y_col='present_value_value')

    data_origin = [
        tuple(data_OAT),
        tuple(data_CSSWT),
        tuple(data_CSRWT),
        tuple(data_FSSWT),
        tuple(data_FSRWT)
    ]

    # 定义各曲线标签
    data_name_origin = ['室外温度', '冷却侧供水温度', '冷却侧回水温度', '冷冻侧供水温度', '冷冻侧回水温度']

    # 处理某条线没有数据的情况,若不处理“没有数据”的情况,画线的时候会报错!
    data = []
    data_name = []

    for i in range(0, len(data_origin)):
        if len(data_origin[i]) != 0:
            data.append(data_origin[i])
            data_name.append(data_name_origin[i])

    if len(data) == 0:
        print('函数 addAcTemp:原始df解析后没有想要的温度数据!')
        return canvas_param

    c = canvas_param
    # c.setFont("song", 10)

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

    lp = LinePlot()
    # lp.x = 50
    # lp.y = 50
    lp.height = height
    lp.width = width
    lp.data = data
    lp.joinedLines = 1

    # 定义各曲线颜色
    lp.lines[0].strokeColor = colors.blue
    lp.lines[1].strokeColor = colors.red
    lp.lines[2].strokeColor = colors.lightgreen
    lp.lines[3].strokeColor = colors.orange
    lp.lines[4].strokeColor = colors.darkgreen

    for i in range(0, len(data)):
        lp.lines[i].name = data_name[i]
        lp.lines[i].symbol = makeMarker('FilledCircle', size=0.5)
        lp.lines[i].strokeWidth = 0.2

    # lp.lineLabelFormat = '%2.0f'
    # lp.strokeColor = colors.black

    lp.xValueAxis.valueMin = 0
    lp.xValueAxis.valueMax = 60 * 60 * 24
    lp.xValueAxis.valueSteps = [n for n in range(0, 60 * 60 * 24, 60 * 60)]
    lp.xValueAxis.labelTextFormat = lambda x: str(s2t(x))[0:2]
    lp.yValueAxis.valueMin = 0
    # lp.yValueAxis.valueMax = 50
    # lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6]
    drawing.add(lp)
    add_legend(draw_obj=drawing, chart=lp, pos_x=10, pos_y=-10)

    renderPDF.draw(drawing=drawing, canvas=c, x=pos_x, y=pos_y)
示例#3
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
示例#4
0
def run():
    styles = getSampleStyleSheet()
    styleN = styles['Normal']
    styleH = styles['Heading1']
    story = []
    storyAdd = story.append

    #for codeNames in code
    storyAdd(Paragraph('I2of5', styleN))
    storyAdd(I2of5(1234, barWidth = inch*0.02, checksum=0))

    storyAdd(Paragraph('MSI', styleN))
    storyAdd(MSI(1234))

    storyAdd(Paragraph('Codabar', styleN))
    storyAdd(Codabar("A012345B", barWidth = inch*0.02))

    storyAdd(Paragraph('Code 11', styleN))
    storyAdd(Code11("01234545634563"))

    storyAdd(Paragraph('Code 39', styleN))
    storyAdd(Standard39("A012345B%R"))

    storyAdd(Paragraph('Extended Code 39', styleN))
    storyAdd(Extended39("A012345B}"))

    storyAdd(Paragraph('Code93', styleN))
    storyAdd(Standard93("CODE 93"))

    storyAdd(Paragraph('Extended Code93', styleN))
    storyAdd(Extended93("L@@K! Code 93 :-)")) #, barWidth=0.005 * inch))

    storyAdd(Paragraph('Code 128', styleN))
    storyAdd(Code128("AB-12345678"))

    storyAdd(Paragraph('Code 128 Auto', styleN))
    storyAdd(Code128Auto("AB-12345678"))

    storyAdd(Paragraph('USPS FIM', styleN))
    storyAdd(FIM("A"))

    storyAdd(Paragraph('USPS POSTNET', styleN))
    storyAdd(POSTNET('78247-1043'))

    storyAdd(Paragraph('USPS 4 State', styleN))
    storyAdd(USPS_4State('01234567094987654321','01234567891'))

    from reportlab.graphics.barcode import createBarcodeDrawing

    storyAdd(Paragraph('EAN13', styleN))
    storyAdd(createBarcodeDrawing('EAN13', value='123456789012'))

    storyAdd(Paragraph('EAN13 quiet=False', styleN))
    storyAdd(createBarcodeDrawing('EAN13', value='123456789012', quiet=False))

    storyAdd(Paragraph('EAN8', styleN))
    storyAdd(createBarcodeDrawing('EAN8', value='1234567'))

    storyAdd(PageBreak())

    storyAdd(Paragraph('EAN5 price=True', styleN))
    storyAdd(createBarcodeDrawing('EAN5', value='11299', price=True))

    storyAdd(Paragraph('EAN5 price=True quiet=False', styleN))
    storyAdd(createBarcodeDrawing('EAN5', value='11299', price=True, quiet=False))

    storyAdd(Paragraph('EAN5 price=False', styleN))
    storyAdd(createBarcodeDrawing('EAN5', value='11299', price=False))

    storyAdd(Paragraph('ISBN alone', styleN))
    storyAdd(createBarcodeDrawing('ISBN', value='9781565924796'))

    storyAdd(Paragraph('ISBN  with ean5 price', styleN))
    storyAdd(createBarcodeDrawing('ISBN', value='9781565924796',price='01299'))

    storyAdd(Paragraph('ISBN  with ean5 price, quiet=False', styleN))
    storyAdd(createBarcodeDrawing('ISBN', value='9781565924796',price='01299',quiet=False))

    storyAdd(Paragraph('UPCA', styleN))
    storyAdd(createBarcodeDrawing('UPCA', value='03600029145'))

    storyAdd(Paragraph('USPS_4State', styleN))
    storyAdd(createBarcodeDrawing('USPS_4State', value='01234567094987654321',routing='01234567891'))

    storyAdd(Paragraph('QR', styleN))
    storyAdd(createBarcodeDrawing('QR', value='01234567094987654321'))

    storyAdd(Paragraph('QR', styleN))
    storyAdd(createBarcodeDrawing('QR', value='01234567094987654321',x=30,y=50))

    def addCross(d,x,y,w=5,h=5, strokeColor='black', strokeWidth=0.5):
        w *= 0.5
        h *= 0.5
        d.add(Line(x-w,y,x+w,y,strokeWidth=0.5,strokeColor=colors.blue))
        d.add(Line(x, y-h, x, y+h,strokeWidth=0.5,strokeColor=colors.blue))
    storyAdd(Paragraph('QR in drawing at (0,0)', styleN))
    d = Drawing(100,100)
    d.add(Rect(0,0,100,100,strokeWidth=1,strokeColor=colors.red,fillColor=None))
    d.add(QrCodeWidget(value='01234567094987654321'))
    storyAdd(d)

    storyAdd(Paragraph('QR in drawing at (10,10)', styleN))
    d = Drawing(100,100)
    d.add(Rect(0,0,100,100,strokeWidth=1,strokeColor=colors.red,fillColor=None))
    addCross(d,10,10)
    d.add(QrCodeWidget(value='01234567094987654321',x=10,y=10))
    storyAdd(d)

    storyAdd(Paragraph('Label Size', styleN))
    storyAdd(XBox((2.0 + 5.0/8.0)*inch, 1 * inch, '1x2-5/8"'))

    storyAdd(Paragraph('Label Size', styleN))
    storyAdd(XBox((1.75)*inch, .5 * inch, '1/2x1-3/4"'))

    if pylibdmtx:
        storyAdd(PageBreak())
        storyAdd(Paragraph('DataMatrix in drawing at (10,10)', styleN))
        d = Drawing(100,100)
        d.add(Rect(0,0,100,100,strokeWidth=1,strokeColor=colors.red,fillColor=None))
        addCross(d,10,10)
        d.add(DataMatrixWidget(value='1234567890',x=10,y=10))
        storyAdd(d)
        storyAdd(Paragraph('DataMatrix in drawing at (10,10)', styleN))
        d = Drawing(100,100)
        d.add(Rect(0,0,100,100,strokeWidth=1,strokeColor=colors.red,fillColor=None))
        addCross(d,10,10)
        d.add(DataMatrixWidget(value='1234567890',x=10,y=10,color='black',bgColor='lime'))
        storyAdd(d)

        storyAdd(Paragraph('DataMatrix in drawing at (90,90) anchor=ne', styleN))
        d = Drawing(100,100)
        d.add(Rect(0,0,100,100,strokeWidth=1,strokeColor=colors.red,fillColor=None))
        addCross(d,90,90)
        d.add(DataMatrixWidget(value='1234567890',x=90,y=90,color='darkblue',bgColor='yellow', anchor='ne'))
        storyAdd(d)
    

    SimpleDocTemplate('out.pdf').build(story)
    print('saved out.pdf')
示例#5
0
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 30 18:21:27 2018

@author: DELL
"""

from reportlab.graphics.shapes import Drawing, String
from reportlab.graphics import renderPDF

d = Drawing(100, 100)  #设置画布大小
s = String(50, 50, 'hello,world!', textAnchor='middle')  #设置内容,格式

d.add(s)  #画布上添加内容

renderPDF.drawToFile(d, 'hello.pdf', 'A simple PDF file')  #生成文件
示例#6
0
# coding=utf-8
from reportlab.graphics.shapes import Drawing, String
from reportlab.graphics import renderPDF

d = Drawing(100,100)    #创建100*100大小的图纸
s = String(50,50,"hello world", textAnchor = "middle")   #在整个图纸的什么位置,如何显示文本
d.add(s)                                             #把文本放置在图纸上
renderPDF.drawToFile(d, 'hello.pdf', 'a simple pdf file')         #在本地目录下输出一个pdf文件
示例#7
0
    def get3PieChart():
        legend = Legend()
        a = df2.iloc[i, 13]
        b = df2.iloc[i, 14]
        c = df2.iloc[i, 15]
        d = df2.iloc[i, 16]
        e = df2.iloc[i, 17]
        da = [a, b, c, d, e]

        x = 0
        y = 0
        for i6 in da:
            if i6 == "Attempted":
                x = x + 1
        a = df2.iloc[i, 28]
        b = df2.iloc[i, 29]
        c = df2.iloc[i, 30]
        d = df2.iloc[i, 31]
        e = df2.iloc[i, 32]
        da = [a, b, c, d, e]
        for i7 in da:
            if i7 == "Correct":
                y = y + 1

        data = [y, x - y]
        u = round(y * 100 / x)
        v = round((x - y) * 100 / x)
        h = [u, v]
        d = []
        l = ["%.2f" % i7 for i7 in h]
        for i7 in l:
            k = i7.split(".")
            d.append(k[0])
        e = []
        j = 0
        for i7 in d:
            w = i7 + "%"
            j = j + 1
            w = i7 + "%"
            if j == 1:
                w = w + " (Correct)"
            if j == 2:
                w = w + " (Incorrect)"
            e.append(w)
        drawing = Drawing(width=400, height=200)
        my_title = String(80,
                          -20,
                          'Accuracy from attemptes questions',
                          fontSize=14)
        pie = Pie()
        pie.sideLabels = True
        pie.slices.popout = 3
        pie.x = 150
        pie.y = 10
        pie.data = data
        pie.labels = [letter for letter in e]
        pie.slices.strokeWidth = 0.5
        drawing.add(my_title)
        n = len(pie.data)
        setItems(n, pie.slices, 'fillColor', pdf_chart_colors)
        legend.colorNamePairs = [(pie.slices[i7].fillColor,
                                  (pie.labels[i7][0:20],
                                   '%0.2f' % pie.data[i7])) for i7 in range(n)]
        drawing.add(pie)
        add_legend(drawing, pie, data)
        return drawing
示例#8
0
    def demo(self):
        D = Drawing(100, 100)
        g = ShadedRect()
        D.add(g)

        return D
    from fontTools.ttLib import TTFont
    from reportlab.lib import colors

    path = sys.argv[1]
    glyphName = sys.argv[2]
    if (len(sys.argv) > 3):
        imageFile = sys.argv[3]
    else:
        imageFile = "%s.png" % glyphName

    font = TTFont(
        path)  # it would work just as well with fontTools.t1Lib.T1Font
    gs = font.getGlyphSet()
    pen = ReportLabPen(gs, Path(fillColor=colors.red, strokeWidth=5))
    g = gs[glyphName]
    g.draw(pen)

    w, h = g.width, 1000
    from reportlab.graphics import renderPM
    from reportlab.graphics.shapes import Group, Drawing, scale

    # Everything is wrapped in a group to allow transformations.
    g = Group(pen.path)
    g.translate(0, 200)
    g.scale(0.3, 0.3)

    d = Drawing(w, h)
    d.add(g)

    renderPM.drawToFile(d, imageFile, fmt="PNG")
示例#10
0
                          strokeColor=None)
        path.isClipPath = 1
        g = Group()
        g.add(path)
        rect = ShadedRect(strokeWidth=0, strokeColor=None)
        for k in 'fillColorStart', 'fillColorEnd', 'numShades', 'cylinderMode':
            setattr(rect, k, getattr(self, k))
        g.add(rotatedEnclosingRect(P, self.angle, rect))
        g.add(EmptyClipPath)
        path = path.copy()
        path.isClipPath = 0
        path.strokeColor = self.strokeColor
        path.strokeWidth = self.strokeWidth
        g.add(path)
        return g


if __name__ == '__main__':  #noruntests
    from reportlab.lib.colors import blue
    from reportlab.graphics.shapes import Drawing
    angle = 45
    D = Drawing(120, 120)
    D.add(
        ShadedPolygon(points=(10, 10, 60, 60, 110, 10),
                      strokeColor=None,
                      strokeWidth=1,
                      angle=90,
                      numShades=50,
                      cylinderMode=0))
    D.save(formats=['gif'], fnRoot='shobj', outDir='/tmp')
示例#11
0
 def demo(self):
     D = Drawing(100, 100)
     g = DoubleGrid()
     D.add(g)
     return D
示例#12
0
countries = []
for row in result.fetchall():
    if c != unicode(row[0]):
        c = unicode(row[0])
        countries.append(c)
        data_row += 1
        data_col = 0
        data_values.append([])
        linelabels.append([])
    data_values[data_row].append(float(str(row[4])))
    if data_col == 0:
        linelabels[data_row].append(c)
    else:
        linelabels[data_row].append(None)
    data_col += 1

d = Drawing(800, 600)
chart = HorizontalLineChart()
chart.width = 740
chart.height = 560
chart.x = 50
chart.y = 20
chart.lineLabelArray = linelabels
chart.lineLabelFormat = 'values'
chart.data = data_values
chart.categoryAxis.categoryNames = h_labels
chart.valueAxis.valueMin = 0

d.add(chart)
d.save(fnRoot='ghg-totals', formats=['png'])
示例#13
0
    def testUtf8Canvas(self):
        """Verify canvas declared as utf8 autoconverts.

        This assumes utf8 input. It converts to the encoding of the
        underlying font, so both text lines APPEAR the same."""

        c = Canvas(outputfile('test_pdfbase_encodings_utf8.pdf'))

        c.drawString(100, 700, testUTF8)

        # Set a font with UTF8 encoding
        c.setFont('Vera', 12)

        # This should pass the UTF8 through unchanged
        c.drawString(100, 600, testUTF8)
        # and this should convert from Unicode to UTF8
        c.drawString(100, 500, testUni)

        # now add a paragraph in Latin-1 in the latin-1 style
        p = Paragraph(testUTF8, style=self.styNormal, encoding="utf-8")
        w, h = p.wrap(150, 100)
        p.drawOn(c, 100, 400)  #3
        c.rect(100, 300, w, h)

        # now add a paragraph in UTF-8 in the UTF-8 style
        p2 = Paragraph(testUTF8, style=self.styTrueType, encoding="utf-8")
        w, h = p2.wrap(150, 100)
        p2.drawOn(c, 300, 400)  #4
        c.rect(100, 300, w, h)

        # now add a paragraph in Unicode in the latin-1 style
        p3 = Paragraph(testUni, style=self.styNormal)
        w, h = p3.wrap(150, 100)
        p3.drawOn(c, 100, 300)
        c.rect(100, 300, w, h)

        # now add a paragraph in Unicode in the UTF-8 style
        p4 = Paragraph(testUni, style=self.styTrueType)
        p4.wrap(150, 100)
        p4.drawOn(c, 300, 300)
        c.rect(300, 300, w, h)

        # now a graphic
        d1 = Drawing(400, 50)
        d1.add(Ellipse(200, 25, 200, 12.5, fillColor=None))
        d1.add(String(200, 25, testUTF8, textAnchor='middle',
                      encoding='utf-8'))
        d1.drawOn(c, 100, 150)

        # now a graphic in utf8
        d2 = Drawing(400, 50)
        d2.add(Ellipse(200, 25, 200, 12.5, fillColor=None))
        d2.add(
            String(200,
                   25,
                   testUTF8,
                   fontName='Vera',
                   textAnchor='middle',
                   encoding='utf-8'))
        d2.drawOn(c, 100, 100)

        # now a graphic in Unicode with T1 font
        d3 = Drawing(400, 50)
        d3.add(Ellipse(200, 25, 200, 12.5, fillColor=None))
        d3.add(String(200, 25, testUni, textAnchor='middle'))
        d3.drawOn(c, 100, 50)

        # now a graphic in Unicode with TT font
        d4 = Drawing(400, 50)
        d4.add(Ellipse(200, 25, 200, 12.5, fillColor=None))
        d4.add(String(200, 25, testUni, fontName='Vera', textAnchor='middle'))
        d4.drawOn(c, 100, 0)

        extracted = extractText(c.getCurrentPageContent())
        self.assertEquals(extracted[0], expectedCp1252)
        self.assertEquals(extracted[1], extracted[2])
        #self.assertEquals(subsetToUnicode(self.vera, extracted[1]), testUni)
        c.save()
示例#14
0
    def generate(self, order):
        from reportlab.graphics.shapes import Drawing
        from reportlab.pdfgen import canvas
        from reportlab.lib import pagesizes, units
        from reportlab.graphics.barcode.qr import QrCodeWidget
        from reportlab.graphics import renderPDF
        from PyPDF2 import PdfFileWriter, PdfFileReader

        pagesize = self.settings.get('pagesize', default='A4')
        if hasattr(pagesizes, pagesize):
            pagesize = getattr(pagesizes, pagesize)
        else:
            pagesize = pagesizes.A4
        orientation = self.settings.get('orientation', default='portrait')
        if hasattr(pagesizes, orientation):
            pagesize = getattr(pagesizes, orientation)(pagesize)

        buffer = BytesIO()
        p = canvas.Canvas(buffer, pagesize=pagesize)

        for op in order.positions.all().select_related('item', 'variation'):
            event_s = self.settings.get('event_s', default=22, as_type=float)
            if event_s:
                p.setFont("Helvetica", event_s)
                event_x = self.settings.get('event_x',
                                            default=15,
                                            as_type=float)
                event_y = self.settings.get('event_y',
                                            default=235,
                                            as_type=float)
                p.drawString(event_x * units.mm, event_y * units.mm,
                             str(self.event.name))

            name_s = self.settings.get('name_s', default=17, as_type=float)
            if name_s:
                p.setFont("Helvetica", name_s)
                name_x = self.settings.get('name_x', default=15, as_type=float)
                name_y = self.settings.get('name_y',
                                           default=220,
                                           as_type=float)
                item = str(op.item.name)
                if op.variation:
                    item += " – " + str(op.variation)
                p.drawString(name_x * units.mm, name_y * units.mm, item)

            price_s = self.settings.get('price_s', default=17, as_type=float)
            if price_s:
                p.setFont("Helvetica", price_s)
                price_x = self.settings.get('price_x',
                                            default=15,
                                            as_type=float)
                price_y = self.settings.get('price_y',
                                            default=210,
                                            as_type=float)
                p.drawString(price_x * units.mm, price_y * units.mm,
                             "%s %s" % (str(op.price), self.event.currency))

            qr_s = self.settings.get('qr_s', default=80, as_type=float)
            if qr_s:
                reqs = qr_s * units.mm
                qrw = QrCodeWidget(op.id, barLevel='H')
                b = qrw.getBounds()
                w = b[2] - b[0]
                h = b[3] - b[1]
                d = Drawing(reqs,
                            reqs,
                            transform=[reqs / w, 0, 0, reqs / h, 0, 0])
                d.add(qrw)
                qr_x = self.settings.get('qr_x', default=10, as_type=float)
                qr_y = self.settings.get('qr_y', default=130, as_type=float)
                renderPDF.draw(d, p, qr_x * units.mm, qr_y * units.mm)

            code_s = self.settings.get('code_s', default=11, as_type=float)
            if code_s:
                p.setFont("Helvetica", code_s)
                code_x = self.settings.get('code_x', default=15, as_type=float)
                code_y = self.settings.get('code_y',
                                           default=130,
                                           as_type=float)
                p.drawString(code_x * units.mm, code_y * units.mm, op.id)

            p.showPage()

        p.save()

        buffer.seek(0)
        new_pdf = PdfFileReader(buffer)
        output = PdfFileWriter()
        bg_file = self.settings.get('background', as_type=File)
        if isinstance(bg_file, File):
            bgf = default_storage.open(bg_file.name, "rb")
        else:
            bgf = open(finders.find('pretixpresale/pdf/ticket_default_a4.pdf'),
                       "rb")
        bg_pdf = PdfFileReader(bgf)
        for page in new_pdf.pages:
            bg_page = copy.copy(bg_pdf.getPage(0))
            bg_page.mergePage(page)
            output.addPage(bg_page)

        outbuffer = BytesIO()
        output.write(outbuffer)
        outbuffer.seek(0)
        return 'order%s%s.pdf' % (
            self.event.slug, order.code), 'application/pdf', outbuffer.read()
示例#15
0
    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)
示例#16
0
from reportlab.platypus import KeepTogether
from reportlab.platypus import LongTable

from client.pdfs import CustomPdf, format_number_thousand_decimal_points, right_align_bold_paragraph_style
from client.pdfs import get_logo_and_qr_code_from_client, create_right_align_header, size_nine_helvetica_leading_10, \
    add_new_line_to_string_at_index, get_reciver_address_list_from_object, size_nine_helvetica_bold, two_new_lines, \
    get_delivery_address_html_string_from_object, size_nine_helvetica, Table, TableStyle, size_twelve_helvetica_bold, \
    horizontal_line, size_ten_helvetica, underline
from reportlab.platypus import Paragraph
from reportlab.lib.enums import TA_RIGHT, TA_LEFT, TA_CENTER
from reportlab.lib.styles import ParagraphStyle
from order.models import Order
from client.models import Client
from reportlab.graphics.shapes import Drawing, Line, colors

order_horizontal_line = Drawing(100, 1)
order_horizontal_line.add(Line(0, 0, 423, 0))


class OrderPdfView(View):
    @property
    def order(self):
        return Order.objects.get(pk=self.kwargs.get("pk"))

    @property
    def client(self):
        client = Client.objects.get(pk=self.request.session.get("client"))
        return client

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
示例#17
0
eg("""
>>> from reportlab.lib import colors
>>> from reportlab.graphics import shapes
>>> from reportlab.graphics import widgetbase
>>> from reportlab.graphics import renderPDF
>>> d = shapes.Drawing(200, 100)
>>> f = widgetbase.Face()
>>> f.skinColor = colors.yellow
>>> f.mood = "sad"
>>> d.add(f)
>>> renderPDF.drawToFile(d, 'face.pdf', 'A Face')
""")

from reportlab.graphics import widgetbase
d = Drawing(200, 120)
f = widgetbase.Face()
f.x = 50
f.y = 10
f.skinColor = colors.yellow
f.mood = "sad"
d.add(f)
draw(d, 'A sample widget')

disc("""
Let's see what properties it has available, using the $setProperties()$
method we have seen earlier:
""")

eg("""
>>> f.dumpProperties()
示例#18
0
    def build_table(self):
        colwidths = [30, 68, 152, 60, 65, 65]

        right_align_paragraph_style = ParagraphStyle("adsadsa",
                                                     alignment=TA_RIGHT,
                                                     fontName="Helvetica",
                                                     fontSize=9,
                                                     rightIndent=17)
        header = [
            Paragraph("<b>Pos</b>", style=size_nine_helvetica),
            Paragraph("<b>EAN / SKU</b>", style=size_nine_helvetica),
            Paragraph("<b>Bezeichnung</b>", style=size_nine_helvetica),
            Paragraph("<b>Menge</b>", style=right_align_paragraph_style),
            Paragraph("<b>Einzelpreis</b>", style=right_align_paragraph_style),
            Paragraph("<b>Betrag</b>", style=right_align_paragraph_style),
        ]

        data = []
        data.append(header)
        pos = 1

        for productorder in self.order.productorder_set.all():

            data.append([
                Paragraph(str(pos), style=size_nine_helvetica),
                Paragraph(productorder.get_ean_or_sku(),
                          style=size_nine_helvetica),
                Paragraph(productorder.product.title,
                          style=size_nine_helvetica),
                Paragraph(str(productorder.amount),
                          style=right_align_paragraph_style),
                Paragraph(format_number_thousand_decimal_points(
                    productorder.netto_price),
                          style=right_align_paragraph_style),
                Paragraph(format_number_thousand_decimal_points(
                    (productorder.netto_price * productorder.amount)),
                          style=right_align_paragraph_style),
            ], )

            pos += 1
        table = LongTable(data,
                          splitByRow=True,
                          colWidths=colwidths,
                          repeatRows=1)
        table.setStyle(
            TableStyle([
                ('LEFTPADDING', (0, 0), (-1, -1), 0),
                ('RIGHTPADDING', (0, 0), (-1, -1), 0),
                ('VALIGN', (0, 0), (-1, -1), "TOP"),
            ]))

        total_netto = 0

        for productorder in self.order.productorder_set.all():
            total_netto += productorder.amount * productorder.netto_price

        horizontal_line_betrag = Drawing(20, 1)
        horizontal_line_betrag.add(Line(425, 0, 200, 0))

        betrag_data = [
            [
                Paragraph(f"Nettobetrag", style=right_align_paragraph_style),
                Paragraph(
                    f"{format_number_thousand_decimal_points(total_netto)} €",
                    style=right_align_paragraph_style),
            ],
            [
                Paragraph(f"+ Umsatzsteuer (19,00%)",
                          style=right_align_paragraph_style),
                Paragraph(
                    f"{format_number_thousand_decimal_points(total_netto*0.19)} €",
                    style=right_align_paragraph_style),
            ], [
                horizontal_line_betrag,
            ],
            [
                Paragraph(f"GESAMT", style=right_align_bold_paragraph_style),
                Paragraph(
                    f"{format_number_thousand_decimal_points(total_netto+(total_netto*0.19))} €",
                    style=right_align_bold_paragraph_style),
            ]
        ]
        betrag_table = Table(betrag_data, colWidths=[None, 70, 75])
        betrag_table.setStyle(
            TableStyle([
                ('LEFTPADDING', (0, 0), (-1, -1), 0),
                ('RIGHTPADDING', (0, 0), (-1, -1), 0),
                ('VALIGN', (0, 0), (-1, -1), "TOP"),
            ]))

        self.story.extend(
            [table, order_horizontal_line,
             KeepTogether(betrag_table)])
示例#19
0
    def getPieChart():

        legend = Legend()
        a = df2.iloc[i, 38]
        b = df2.iloc[i, 39]
        c = df2.iloc[i, 40]
        d = df2.iloc[i, 41]
        e = df2.iloc[i, 42]
        data = [a, b, c, d, e]

        drawing = Drawing(width=400, height=200)
        my_title = String(81,
                          37,
                          'Time Spend as the Function of Total Time',
                          fontSize=14)
        pie = Pie()
        pie.sideLabels = True
        pie.slices.popout = 2
        pie.x = 135
        pie.y = 55
        pie.data = data
        s = a + b + c + d + e
        t = round(a * 100 / s)
        u = round(b * 100 / s)
        v = round(c * 100 / s)
        x = round(d * 100 / s)
        z = round(e * 100 / s)
        h = [t, u, v, x, z]
        d = []
        l = ["%.2f" % i4 for i4 in h]
        for i4 in l:
            k = i4.split(".")
            d.append(k[0])
        e = []
        j = 0
        for i4 in d:
            w = i4 + "%"
            j = j + 1
            if j == 1:
                w = w + " (Q1)"
            if j == 2:
                w = w + " (Q2)"
            if j == 3:
                w = w + " (Q3)"
            if j == 4:
                w = w + " (Q4)"
            if j == 5:
                w = w + " (Q5)"
            e.append(w)
        pie.labels = [letter for letter in e]
        pie.slices.strokeWidth = 0.5
        drawing.add(my_title)
        drawing.add(pie)
        n = len(pie.data)
        setItems(n, pie.slices, 'fillColor', pdf_chart_colors)
        legend.colorNamePairs = [(pie.slices[i4].fillColor,
                                  (pie.labels[i4][0:20],
                                   '%0.2f' % pie.data[i4])) for i4 in range(n)]
        add_legend(drawing, pie, data)

        return drawing
示例#20
0
 def demo(self, drawing=None):
     if not drawing:
         tx, ty = self._getDrawingDimensions()
         drawing = Drawing(tx, ty)
     drawing.add(self.draw())
     return drawing
示例#21
0
    def get4PieChart():

        legend = Legend()
        a = df2.iloc[i, 13]
        b = df2.iloc[i, 14]
        c = df2.iloc[i, 15]
        d = df2.iloc[i, 16]
        e = df2.iloc[i, 17]
        da = [a, b, c, d, e]

        x = 0
        y = 0
        for i9 in da:
            if i9 == "Attempted":
                x = x + 1
        a = df2.iloc[i, 28]
        b = df2.iloc[i, 29]
        c = df2.iloc[i, 30]
        d = df2.iloc[i, 31]
        e = df2.iloc[i, 32]
        da = [a, b, c, d, e]
        for i9 in da:
            if i9 == "Correct":
                y = y + 1
        z = 5 - x
        o = x - y
        data = [z, y, o]
        s = z + y + o
        u = round(z * 100 / s)
        v = round(y * 100 / s)
        r = round(o * 100 / s)
        h = [u, v, r]
        d = []
        l = ["%.2f" % i9 for i9 in h]
        for i9 in l:
            k = i9.split(".")
            d.append(k[0])
        e = []
        j = 0
        for i9 in d:
            w = i9 + "%"
            j = j + 1
            w = i9 + "%"
            if j == 1:
                w = w + " (Unattempted)"
            if j == 2:
                w = w + " (Correct)"
            if j == 3:
                w = w + " (Incorrect)"
            e.append(w)
        drawing = Drawing(width=400, height=200)
        my_title = String(80,
                          -20,
                          'Overall Performance against the test',
                          fontSize=14)
        pie = Pie()
        pie.sideLabels = True
        pie.slices.popout = 3
        pie.x = 150
        pie.y = 10
        pie.data = data
        pie.labels = [letter for letter in e]
        pie.slices.strokeWidth = 0.5
        drawing.add(my_title)
        drawing.add(pie)
        n = len(pie.data)
        setItems(n, pie.slices, 'fillColor', pdf_chart_colors)
        legend.colorNamePairs = [(pie.slices[i9].fillColor,
                                  (pie.labels[i9][0:20],
                                   '%0.2f' % pie.data[i9])) for i9 in range(n)]
        add_legend(drawing, pie, data)

        return drawing
示例#22
0
lab.setOrigin(100,90)
lab.boxAnchor = 'ne'
lab.angle = 45
lab.dx = 0
lab.dy = -20
lab.boxStrokeColor = colors.green
lab.setText('Some\nMulti-Line\nLabel')

d.add(lab)
""")


from reportlab.graphics import shapes
from reportlab.graphics.charts.textlabels import Label

d = Drawing(200, 100)

# mark the origin of the label
d.add(Circle(100,90, 5, fillColor=colors.green))

lab = Label()
lab.setOrigin(100,90)
lab.boxAnchor = 'ne'
lab.angle = 45
lab.dx = 0
lab.dy = -20
lab.boxStrokeColor = colors.green
lab.setText('Some\nMulti-Line\nLabel')

d.add(lab)
示例#23
0
    def make_graphs(self, canvas=None, left_margin=None):  #text=None):
        from reportlab.graphics import renderPDF
        from reportlab.lib.pagesizes import letter
        from reportlab.graphics.shapes import Drawing, String
        from reportlab.graphics.charts.legends import Legend
        from reportlab.graphics.charts.lineplots import LinePlot
        from reportlab.graphics.widgets.markers import makeMarker
        from reportlab.lib import colors
        from reportlab.lib.units import inch
        #help(colors)

        self.framework = {
            4: dict(status=SpotClass.SPINDLE, color=colors.black),
            5: dict(status=SpotClass.OVERLAP, color=colors.limegreen),
            6: dict(status=SpotClass.OUTLIER, color=colors.greenyellow),
            7: dict(status=SpotClass.ICE, color=colors.skyblue),
        }

        # set size and position
        width, height = letter
        #letter_landscape = (width,height)
        plot_dim = 3.0 * inch

        # construct scatter plot
        plot_dxdy_pos = (left_margin * inch, height - plot_dim - 0.5 * inch)
        plot_dxdy = LinePlot()
        plot_dxdy.data = self.plot_dxdy_data

        std_colors = {0: colors.darkred, 1: colors.red, 2: colors.salmon}
        for key in std_colors.keys():
            plot_dxdy.lines[key].strokeColor = None
            plot_dxdy.lines[key].symbol = makeMarker('Circle')
            plot_dxdy.lines[key].symbol.strokeColor = None
            plot_dxdy.lines[key].symbol.fillColor = std_colors[key]
            plot_dxdy.lines[key].symbol.size = 1.2

        for key in self.framework.keys():
            plot_dxdy.lines[key].strokeColor = None
            plot_dxdy.lines[key].symbol = makeMarker('Circle')
            plot_dxdy.lines[key].symbol.strokeColor = None
            plot_dxdy.lines[key].symbol.fillColor = self.framework[key][
                "color"]
            plot_dxdy.lines[key].symbol.size = 1.2

        plot_dxdy.lines[3].strokeColor = None
        plot_dxdy.lines[3].symbol = makeMarker('Circle')
        plot_dxdy.lines[3].symbol.strokeColor = colors.blue
        plot_dxdy.lines[3].symbol.fillColor = None
        plot_dxdy.lines[3].symbol.strokeWidth = 0.6
        plot_dxdy.lines[3].symbol.size = plot_dim * (self.sqrtr2)
        #print plot_dxdy.lines[3].symbol.getProperties()
        plot_dxdy.width = plot_dim
        plot_dxdy.height = plot_dim
        plot_dxdy.xValueAxis.valueMax = 1.0
        plot_dxdy.xValueAxis.valueMin = -1.0
        plot_dxdy.xValueAxis.joinAxis = plot_dxdy.yValueAxis
        plot_dxdy.xValueAxis.joinAxisMode = 'value'
        plot_dxdy.xValueAxis.joinAxisPos = -1.0
        plot_dxdy.yValueAxis.valueMax = 1.0
        plot_dxdy.yValueAxis.valueMin = -1.0
        d_dxdy = Drawing(plot_dim, plot_dim)
        d_dxdy.add(plot_dxdy)

        # construct cdf plot
        plot_cdf_pos = (left_margin * inch,
                        height - 2.0 * (plot_dim + 0.5 * inch))
        plot_cdf = LinePlot()
        plot_cdf.data = self.plot_cdf_data
        plot_cdf.lines[0].strokeColor = colors.blue

        for key in std_colors.keys():
            plot_cdf.lines[key + 1].strokeColor = None
            plot_cdf.lines[key + 1].symbol = makeMarker('Circle')
            plot_cdf.lines[key + 1].symbol.strokeColor = None
            plot_cdf.lines[key + 1].symbol.fillColor = std_colors[key]
            plot_cdf.lines[key + 1].symbol.size = 1.2

        if (len(self.plot_cdf_data) == 5):
            plot_cdf.lines[4].strokeColor = colors.green
        plot_cdf.width = plot_dim
        plot_cdf.height = plot_dim
        plot_cdf.xValueAxis.valueMax = 1.0
        plot_cdf.xValueAxis.valueMin = 0.0
        plot_cdf.yValueAxis.valueMax = 1.0
        plot_cdf.yValueAxis.valueMin = 0.0
        d_cdf = Drawing(plot_dim, plot_dim)
        d_cdf.add(plot_cdf)

        # construct pdf plot
        plot_pdf_pos = (left_margin * inch,
                        height - 3.0 * (plot_dim + 0.5 * inch))
        plot_pdf = LinePlot()
        plot_pdf.data = self.plot_pdf_data
        plot_pdf.lines[1].strokeColor = colors.blue
        plot_pdf.lines[0].strokeColor = None
        plot_pdf.lines[0].symbol = makeMarker('Circle')
        plot_pdf.lines[0].symbol.strokeColor = colors.red
        plot_pdf.lines[0].symbol.size = 1
        plot_pdf.width = plot_dim
        plot_pdf.height = plot_dim
        plot_pdf.xValueAxis.valueMax = 1.0
        plot_pdf.xValueAxis.valueMin = 0.0
        d_pdf = Drawing(2 * plot_dim, plot_dim)
        d_pdf.add(plot_pdf)

        # add legend
        legend = Legend()
        legend.alignment = 'right'
        legend.colorNamePairs = [
            (std_colors[0],
             'Inliers (%d' % int(self.fraction * 100.0) + '% used for fit)'),
            (std_colors[1], 'Other inliers'),
            (std_colors[2], 'Outliers, reject next round'),
        ]
        for key in self.framework.keys():
            legend.colorNamePairs.append(
                (self.framework[key]["color"],
                 "%s" % self.framework[key]["status"]))

        legend.x = plot_dim - 1.0 * inch
        legend.y = plot_dim
        legend.columnMaximum = 8
        d_pdf.add(legend)

        # add titles
        title_pos = (plot_dim / 2.0, plot_dim + 0.25 * inch)
        title_dxdy = String(title_pos[0], title_pos[1], 'dx vs. dy (all)')
        title_dxdy.fontSize = 15
        title_dxdy.textAnchor = 'middle'
        d_dxdy.add(title_dxdy)
        title_cdf = String(title_pos[0], title_pos[1], 'cdf (good)')
        title_cdf.fontSize = 15
        title_cdf.textAnchor = 'middle'
        d_cdf.add(title_cdf)
        title_pdf = String(title_pos[0], title_pos[1], 'pdf (good)')
        title_pdf.fontSize = 15
        title_pdf.textAnchor = 'middle'
        d_pdf.add(title_pdf)

        # draw everything
        renderPDF.draw(d_dxdy, canvas, plot_dxdy_pos[0], plot_dxdy_pos[1])
        renderPDF.draw(d_cdf, canvas, plot_cdf_pos[0], plot_cdf_pos[1])
        renderPDF.draw(d_pdf, canvas, plot_pdf_pos[0], plot_pdf_pos[1])
    def balance_statistics_chart(self, control_vars, match_vars, var_names):
        """
        Specify layout of the balance statistics chart and generate
        flowable object that can be added to the pdf
        """
        drawing = Drawing()
        vbc = VerticalBarChart()

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

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

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

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

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

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

        # Central axis
        vbc.categoryAxis.visibleTicks = 1

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

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

        #lab.boxStrokeColor = colors.green
        lab.setText('Percent Bias')
        drawing.add(lab)
        drawing.add(vbc)
        self.elements.append(drawing)
示例#25
0
        symbol = None
    return symbol


class _isSymbol(Validator):
    def test(self, x):
        return hasattr(x, '__call__') or isinstance(x, Marker) or isinstance(
            x, Flag) or (isinstance(x, type) and issubclass(x, Widget))


isSymbol = _isSymbol()


def makeMarker(name, **kw):
    if Marker._attrMap['kind'].validate(name):
        m = Marker(**kw)
        m.kind = name
    elif name[-5:] == '_Flag' and Flag._attrMap['kind'].validate(name[:-5]):
        m = Flag(**kw)
        m.kind = name[:-5]
        m.size = 10
    else:
        raise ValueError("Invalid marker name %s" % name)
    return m


if __name__ == '__main__':
    D = Drawing()
    D.add(Marker())
    D.save(fnRoot='Marker', formats=['pdf'], outDir='/tmp')
    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)
示例#27
0
def genLPDrawing(data,
                 data_note,
                 width=letter[0] * 0.8,
                 height=letter[1] * 0.25,
                 time_axis='day',
                 y_min_zero=False,
                 line_width=1.5,
                 marker_size=5):
    """
    函数功能:生成Drawing之用
    :return:
    """

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

    lp = LinePlot()

    lp.height = height
    lp.width = width
    lp.data = data
    lp.joinedLines = 1

    # 定义颜色集
    barFillColors = [
        colors.red, colors.green, colors.blue, colors.darkgoldenrod,
        colors.pink, colors.purple, colors.lightgreen, colors.darkblue,
        colors.lightyellow, colors.fidred, colors.greenyellow, colors.gray,
        colors.white, colors.blueviolet, colors.lightgoldenrodyellow
    ]

    for i in range(0, len(data)):
        lp.lines[i].name = data_note[i]
        lp.lines[i].symbol = makeMarker('FilledCircle', size=marker_size)
        lp.lines[i].strokeWidth = line_width
        lp.lines[i].strokeColor = barFillColors[i]

    # lp.lineLabelFormat = '%2.0f'
    # lp.strokeColor = colors.black

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

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

    if time_axis == 'day':
        step = int(((x_max - x_min) / (60 * 60 * 24)) / 30) + 1

        lp.xValueAxis.valueSteps = [
            n for n in range(int(x_min), int(x_max), 60 * 60 * 24 * step)
        ]
        lp.xValueAxis.labelTextFormat = lambda x: str(Sec2Datetime(x)[0:10])
        lp.xValueAxis.labels.angle = 90
        lp.xValueAxis.labels.fontSize = 6
        lp.xValueAxis.labels.dy = -18
        if y_min_zero:
            lp.yValueAxis.valueMin = 0

        # lp.yValueAxis.valueMax = 50
        # lp.yValueAxis.valueSteps = [1, 2, 3, 5, 6]

    elif time_axis == 'quarter':

        step = int(((x_max - x_min) / 0.25) / 30) + 1

        lp.xValueAxis.valueSteps = [
            n
            for n in range(int(x_min), int(x_max), int(math.ceil(0.25 * step)))
        ]
        lp.xValueAxis.labelTextFormat = lambda x: convertValue2Quarter(x)
        lp.xValueAxis.labels.angle = 90
        lp.xValueAxis.labels.fontSize = 6
        lp.xValueAxis.labels.dy = -18

        if y_min_zero:
            lp.yValueAxis.valueMin = 0

    elif time_axis == 'year':

        lp.xValueAxis.valueSteps = [
            n for n in range(int(x_min), int(x_max), 1)
        ]
        lp.xValueAxis.labelTextFormat = lambda x: str(x)
        lp.xValueAxis.labels.angle = 90
        lp.xValueAxis.labels.fontSize = 6
        lp.xValueAxis.labels.dy = -18

        if y_min_zero:
            lp.yValueAxis.valueMin = 0

    elif time_axis == 'month':

        lp.xValueAxis.valueSteps = list(map(lambda x: x[0], data[0]))
        lp.xValueAxis.labelTextFormat = lambda x: str(Sec2Datetime(x))[0:7]
        lp.xValueAxis.labels.angle = 90
        lp.xValueAxis.labels.fontSize = 6
        lp.xValueAxis.labels.dy = -18

        if y_min_zero:
            lp.yValueAxis.valueMin = 0

    drawing.add(lp)
    add_legend(draw_obj=drawing, chart=lp, pos_x=10, pos_y=-20)

    return drawing
 def draw_line(self, x1, y1, x2, y2, line_color=colors.black):
     drawable_line = Drawing(x1, y1)
     drawable_line.add(Line(0, 0, x2, y2, fillColor=line_color))
     return drawable_line
示例#29
0
文件: corp.py 项目: OYZQ/odoo_qingjia
 def demo(self):
     D = Drawing(self.width, self.height)
     D.add(self)
     return D
示例#30
0
    def _draw_bar_chart(format_json):
        width = format_json['rect'][2]
        height = format_json['rect'][3]

        d = Drawing(width, height, vAlign="TOP")

        if format_json['data'] is None or type(format_json['data']) is str:
            PDFTemplate._draw_chart_rect(d, 20, 20, width - 40, height - 50,
                                         format_json)
        elif type(format_json['data']) is list:
            cat_names = format_json['category_names']
            data = format_json['data']
            bar_style = format_json['bar_style']

            style = "parallel"
            if "style" in format_json and isString(
                    format_json['style']) is True:
                style = format_json['style']
            label_format = None
            if "label_format" in format_json and isString(
                    format_json['label_format']) is True:
                label_format = format_json['label_format']
            step_count = 4
            if "step_count" in format_json and isNumber(
                    format_json['step_count']) is True:
                step_count = format_json['step_count']
            legend_names = None
            if "legend_names" in format_json and isListOfStrings(
                    format_json['legend_names']) is True:
                legend_names = format_json['legend_names']
            legend_position = "top-right"
            if "legend_position" in format_json and isString(
                    format_json['legend_position']) is True:
                legend_position = format_json['legend_position']
            legend_adjust_x = 0
            if "legend_adjust_x" in format_json and isNumber(
                    format_json['legend_adjust_x']) is True:
                legend_adjust_x = format_json['legend_adjust_x']
            legend_adjust_y = 0
            if "legend_adjust_y" in format_json and isNumber(
                    format_json['legend_adjust_y']) is True:
                legend_adjust_y = format_json['legend_adjust_y']
            main_title = ""
            if "main_title" in format_json and isString(
                    format_json['main_title']) is True:
                main_title = format_json['main_title']
            main_title_font_name = None
            if "main_title_font_name" in format_json and isString(
                    format_json['main_title_font_name']) is True:
                main_title_font_name = format_json['main_title_font_name']
            main_title_font_size = None
            if "main_title_font_size" in format_json and isNumber(
                    format_json['main_title_font_size']) is True:
                main_title_font_size = format_json['main_title_font_size']
            main_title_font_color = None
            if "main_title_font_color" in format_json:
                main_title_font_color = format_json['main_title_font_color']
            x_desc = None
            if "x_desc" in format_json and isString(
                    format_json['x_desc']) is True:
                x_desc = format_json['x_desc']
            y_desc = None
            if "y_desc" in format_json and isString(
                    format_json['y_desc']) is True:
                y_desc = format_json['y_desc']
            cat_label_all = False
            if "cat_label_all" in format_json:
                cat_label_all = format_json['cat_label_all']
            cat_label_angle = 30
            if "cat_label_angle" in format_json and isNumber(
                    format_json['cat_label_angle']) is True:
                cat_label_angle = format_json['cat_label_angle']

            bar_chart = None
            if bar_style == "horizontal":
                bar_chart = ReportLabHorizontalBarChart(
                    0,
                    0,
                    width,
                    height,
                    cat_names,
                    data,
                    style=style,
                    label_format=label_format,
                    step_count=step_count,
                    legend_names=legend_names,
                    legend_position=legend_position,
                    legend_adjust_x=legend_adjust_x,
                    legend_adjust_y=legend_adjust_y,
                    main_title=main_title,
                    main_title_font_name=main_title_font_name,
                    main_title_font_size=main_title_font_size,
                    main_title_font_color=main_title_font_color,
                    x_desc=x_desc,
                    y_desc=y_desc,
                    cat_label_angle=cat_label_angle,
                    cat_label_all=cat_label_all)
            elif bar_style == "vertical":
                bar_chart = ReportLabVerticalBarChart(
                    0,
                    0,
                    width,
                    height,
                    cat_names,
                    data,
                    style=style,
                    label_format=label_format,
                    step_count=step_count,
                    legend_names=legend_names,
                    legend_position=legend_position,
                    legend_adjust_x=legend_adjust_x,
                    legend_adjust_y=legend_adjust_y,
                    main_title=main_title,
                    main_title_font_name=main_title_font_name,
                    main_title_font_size=main_title_font_size,
                    main_title_font_color=main_title_font_color,
                    x_desc=x_desc,
                    y_desc=y_desc,
                    cat_label_angle=cat_label_angle,
                    cat_label_all=cat_label_all)
            if bar_chart is not None:
                d.add(bar_chart)

        return d