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)
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)
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)
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)
def monthly_spending_bar(c, category, h, w): """ Creates a bar graph in a PDF """ my_data = [] for i in range(1, 12 + 1): my_data.append(data.category_data(category.lower(), i, year)) for i in range(month, 12): my_data[i] = 0 #d = Drawing(300, 250) d = Drawing(0, 0) bar = VerticalBarChart() bar.x = 150 bar.y = 150 bar.data = [my_data] bar.valueAxis.valueMin = 0 bar.categoryAxis.categoryNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] bar.categoryAxis.labels.fontName = serif_font bar.valueAxis.labels.fontName = serif_font bar.categoryAxis.labels.boxAnchor = 'n' bar.categoryAxis.labels.angle = 90 bar.categoryAxis.labels.dy = -15 bar.categoryAxis.labels.dx = -10 #below change monnth number based upon current month bar.bars[0].fillColor = PCMYKColor(150, 150, 150, 150, alpha=85) bar.bars[(0, month - 1)].fillColor = PCMYKColor(150, 0, 0, 0, alpha=85) d.add(bar, '') d.drawOn(c, 200, 480)
def category_predicted_spending(c, category, h, w): """ Creates a bar graph in a PDF """ my_data = [] for i in range(1, month + 1): my_data.append(round(data.category_data(category, i, year))) budget = data.category_budget(category) re_budget = (budget - sum(my_data)) / (12 - month) for x in range(month, 12): my_data.append(re_budget) d = Drawing(0, 0) bar = VerticalBarChart() bar.x = 150 bar.y = 150 bar.data = [my_data] bar.valueAxis.valueMin = 0 bar.categoryAxis.categoryNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] bar.categoryAxis.labels.fontName = serif_font bar.valueAxis.labels.fontName = serif_font bar.categoryAxis.labels.boxAnchor = 'n' bar.categoryAxis.labels.angle = 90 bar.categoryAxis.labels.dy = -15 bar.categoryAxis.labels.dx = -10 #below change monnth number based upon current month bar.bars[0].fillColor = PCMYKColor(150, 150, 150, 150, alpha=85) for i in range(month, 12): bar.bars[(0, i)].fillColor = PCMYKColor(0, 150, 150, 0, alpha=85) d.add(bar, '') d.drawOn(c, h, w)
def p_header(self, canvas, ldoc): """Set up the header for all portrait pages""" canvas.saveState() self.header_line.wrap(ldoc.width, ldoc.topMargin) self.header_line.drawOn(canvas, ldoc.leftMargin + 40, ldoc.height + ldoc.topMargin + 40) self.logo.drawHeight = 0.6 * cm self.logo.drawWidth = 1.9 * cm self.logo.drawOn(canvas, ldoc.leftMargin - 20, ldoc.height + ldoc.topMargin + 45) self.emblem1.drawHeight = 0.6 * cm self.emblem1.drawWidth = 0.6 * cm self.emblem1.drawOn(canvas, ldoc.width + 75, ldoc.height + ldoc.topMargin + 45) d = Drawing(ldoc.width, 1) d.add( Line(0, 0, ldoc.width + 40, 0, strokeWidth=0.1, strokeColor=ReportColors.get_my_blue())) d.drawOn(canvas, ldoc.leftMargin - 20, ldoc.height + ldoc.topMargin + 40) canvas.restoreState()
def drawOn(self, canvas): logo = self.logo x, y = logo.x, logo.y w, h = logo.width, logo.height D = Drawing(w, h) D.add(logo) D.drawOn(canvas, 0, 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)
def create_bar_syntgraph(self, width, height, synt): pfdc = synt["PFDC"].tolist() budget = synt["BUDGET"].tolist() dep = synt["DEP CUMULEES"].tolist() d = Drawing(width, height) d.add(QuickChart(), name="chart") d.chart.height = height d.chart.width = width d.chart.seriesNames = "PFDC", "Budget", "Dépenses cumulées" d.chart.seriesRelation = "sidebyside" d.chart.dataLabelsFontSize = 10 d.chart.legendFontSize = 10 d.chart.chartColors = [bleu, bleuciel, yellow] d.chart.data = [pfdc, budget, dep] d.chart.chartType = "column" d.chart.titleText = "" d.chart.xTitleText = "" d.chart.xAxisFontSize = 10 d.chart.xAxisLabelAngle = 30 d.chart.yAxisFontSize = 10 # d.chart.yAxisLabelAngle = 30 d.chart.categoryNames = synt.index.tolist() d.chart.dataLabelsAlignment = "bottom" # d.chart.pointerLabelMode = 'leftAndRight' d.chart.bgColor = None d.chart.plotColor = None d.chart.titleFontColor = black # d.rotate(90) d.drawOn(self.c, inch, inch * 0.1)
def overview_year_spend_by_month(c, w, h): my_data = data.monthly_total(year) total_budget = data.budget() left_budget = (total_budget - sum(my_data)) / (12 - month) for i in range(month, 12): my_data[i] = left_budget d = Drawing(0, 0) bar = VerticalBarChart() bar.x = 150 bar.y = 150 bar.data = [my_data] bar.valueAxis.valueMin = 0 bar.categoryAxis.categoryNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] bar.categoryAxis.labels.fontName = serif_font bar.valueAxis.labels.fontName = serif_font bar.categoryAxis.labels.boxAnchor = 'n' bar.categoryAxis.labels.angle = 90 bar.categoryAxis.labels.dy = -15 bar.categoryAxis.labels.dx = -10 bar.bars[0].fillColor = PCMYKColor(150, 150, 150, 150, alpha=85) bar.bars[(0, month - 1)].fillColor = PCMYKColor(150, 0, 0, 0, alpha=85) for i in range(month, 13): bar.bars[(0, i)].fillColor = PCMYKColor(0, 150, 150, 0, alpha=85) d.add(bar, '') d.drawOn(c, w, h)
def _draw_border(cv, x, y, width, height, color, stroke_width=1): d = Drawing(width, height) r = Rect(0, 0, width, height, strokeWidth=stroke_width, strokeColor=color, fillColor=Color(0, 0, 0, 0)) d.add(r) d.drawOn(cv, x, y)
class TweetsReport(): """ Ecrit sur un canvas """ def __init__(self,pdfPath): self.canvas = Canvas(pdfPath) def ecrireLegende(self, decalage, year, donnes): """ Ecrire la légenge """ self.canvas.setFont('Times-Bold', 18) self.canvas.drawString(70,610 - decalage ,"Année {0}".format(year)) self.canvas.setFont("Helvetica", 10) self.canvas.drawString(420,680 - decalage ,"Janvier : {0}".format(donnes[0]) ) self.canvas.drawString(420,668 - decalage ,"Février : {0}".format(donnes[1]) ) self.canvas.drawString(420,656 - decalage ,"Mars : {0}".format(donnes[2]) ) self.canvas.drawString(420,644 - decalage ,"Avril : {0}".format(donnes[3]) ) self.canvas.drawString(420,632 - decalage ,"Mai : {0}".format(donnes[4]) ) self.canvas.drawString(420,620 - decalage ,"Juin : {0}".format(donnes[5]) ) self.canvas.drawString(420,608 - decalage ,"Juillet : {0}".format(donnes[6]) ) self.canvas.drawString(420,596 - decalage ,"Août : {0}".format(donnes[7]) ) self.canvas.drawString(420,584 - decalage ,"Septembre : {0}".format(donnes[8]) ) self.canvas.drawString(420,572 - decalage ,"Octobre : {0}".format(donnes[9]) ) self.canvas.drawString(420,560 - decalage ,"Novembre : {0}".format(donnes[10]) ) self.canvas.drawString(420,548 - decalage ,"Décembre : {0}".format(donnes[11]) ) def ecrireTitre(self,user): """ Ecrire le titre """ self.canvas.setFont('Times-Bold', 18) self.canvas.drawString(50,790,"Cltwit") self.canvas.setFont("Helvetica", 14) self.canvas.drawString(50,750,"Nombre de tweets envoyés par année et par mois par {0}".format(user)) def addPie(self,decalage,donnes): self.d = Drawing(300, 200) self.pc = Pie() self.pc.data = donnes self.pc.checkLabelOverlap = 1 self.pc.labels = ['Jan.','Fev.','Mar.','Avr.','Mai.','Juin','Jui.','Aou.','Sept','Oct.','Nov.','Dec.'] self.pc.x = 20 self.pc.y = 90 self.pc.width = 140 self.pc.height = 140 n = len(self.pc.data) setItems(n,self.pc.slices,'fillColor',pdf_chart_colors) self.d.add(self.pc) self.d.drawOn(self.canvas, 200, 450 - decalage) def NextPage(self): """ Créer une nouvelle page """ self.canvas.showPage() def save(self): """ Enregistrer """ self.canvas.save()
def generate_barcode(self, value, left_margin, bottom_margin, out_dir, logo_path, description, page_size=( 200, 100, )): """ Generates a barcode from a value and save it on a PDF file. e.g >> from barcodelib import BarCode >> BarCode().generate_barcode('SBLS12-12', 2.8, 2, '.', logo_path=logo_dir, description="Stailess Style Standoff Diameter: 1/2, Standoff: 1/2 Satin Finish (For Inside Use Only)") :param left_margin: :param bottom_margin: :param out_dir: :return: """ width, height = page_size value = str(value) filename = 'barcode_%s.pdf' % value file_path = os.path.join(out_dir, filename) c = canvas.Canvas(file_path, pagesize=page_size) c.drawImage(logo_path, 5, height - 35, height=30, width=30) # stamp the bar code # drawOn puts the barcode on the canvas at the specified coordinates # stamp the bar code d = Drawing(50, 10) d.add( createBarcodeDrawing('Standard39', value=value, barHeight=10 * mm, humanReadable=True, checksum=0)) # drawOn puts the barcode on the canvas at the specified coordinates d.drawOn(c, left_margin * cm, bottom_margin * cm) styles = getSampleStyleSheet() p = Paragraph('<font size="10">{}</font>'.format(description), styles["Normal"]) p.wrapOn(c, width - 85, height) p.drawOn(c, 51, 10) # now create the actual PDF c.showPage() c.save() return file_path
def draw(self) -> None: w, h = 7 * cm, 0.7 * cm note = Drawing(w, h) note.add(Rect(0, 0, w, h, fillColor=HIPEAC_BLUE, strokeColor=None)) note.add( String(0.5 * cm, 7, self.text, fontName="Roboto-Regular", fontSize=8, fillColor="white")) note.drawOn(self.canv, self.doc.width - w - (0.4 * cm), self.doc.topMargin / 2)
def getPieChart(c, x, y, data, data_suff, labels, colors, fsize=8.5, radius=0.60, legdx=180, legdy=100): """ Function to draw a Pie Chart """ d = Drawing(200, 200) legend = Legend() legend.columnMaximum = 99 legend.alignment = 'right' legend.dx = 7 legend.dy = 7 legend.dxTextSpace = 5 legend.deltay = 10 legend.strokeWidth = 0 legend.strokeColor = HexColor("0xffffff") legend.subCols[0].minWidth = 75 legend.subCols[0].align = 'left' legend.boxAnchor = 'c' legend.y = legdy legend.x = legdx legend.fontName = "MavenPro" legend.fontSize = 8.5 legendList = [] for k, i in enumerate(colors): legendList.append((HexColor(i), labels[k])) legend.colorNamePairs = legendList pc3 = Pie() pc3.x = 10 pc3.y = 10 pc3.data = data pc3.labels = [str(r) + data_suff if r >= 15 else "" for r in data] pc3.slices.strokeColor = HexColor("0xffffff") pc3.slices.labelRadius = radius pc3.slices.fontName = "MavenPro" pc3.slices.fontSize = fsize pc3.slices.fontColor = HexColor("0xffffff") for k, i in enumerate(colors): pc3.slices[k].fillColor = HexColor(i) d.add(pc3, 'pie3') d.add(legend, 'legend') d.drawOn(c, x, y)
def test_draw(): sheet = Sheet('draw', margin=0, verbose=0) sheet.can.setFillColor('red') sheet.can.circle(0, 200, 100, stroke=1, fill=1) d = Drawing(200, 200) d.add(Rect(100, 0, 100, 120, fillColor=colors.yellow, strokeColor=None)) d.rotate(-45) d.add(Rect(100, 105, 120, 130, fillColor=colors.blue, strokeColor=None)) #d.rotate(45) d.add(String(150, 100, 'Hello World', fontSize=18, fillColor=colors.red)) #d.scale(0.5,0.5) d.wrapOn(sheet.can, 200, 200) d.drawOn(sheet.can, 0, 600) sheet.save()
def drawrelationshipcs(can, resultsbuffer): can.setFont("Helvetica", 24) sec_title = "System Heat Balance" can.drawString(25, 750, sec_title) desc_text = "The following figure shows the relationship between the chilled water" \ " system operating efficiency and the cooling load. As the figure shows, with " \ "the Cooling load ranges between 800 RT to 1100 RT, the efficiency hovers between " \ "0.75/RT to 0.91KW/RT." stylesheet = getSampleStyleSheet() paragraph = Paragraph(desc_text, stylesheet['Normal']) aW, aH = 500, 600 w, h = paragraph.wrap(aW, aH) if w <= aW and h <= aH: paragraph.drawOn(can, 25, 700) drawing = Drawing(600, 400) data = [((801, 0.7), (903, 0.8), (799, 0.84), (1002, 0.97), (1101, 0.89)), ((987, 0.98), (1007, 1.1), (1102, 0.98), (987, 0.95), (908, 0.89))] lp = LinePlot() lp.x = 50 lp.y = 50 lp.height = 250 lp.width = 400 lp.data = data lp.joinedLines = 0 lp.lines.symbol = makeMarker('FilledCircle') # lp.lines.symbol = makeMarker('Circle') # lp.lines[1].symbol = makeMarker('Circle') lp.lineLabelFormat = '%2.0f' lp.strokeColor = colors.black lp.xValueAxis.valueMin = 0 lp.xValueAxis.valueMax = 1200 lp.xValueAxis.valueSteps = [ 0.00, 200.00, 400.00, 600.00, 800.00, 1000.00, 1200.00 ] lp.xValueAxis.labelTextFormat = '%2.1f' lp.yValueAxis.valueMin = 0 lp.yValueAxis.valueMax = 1.2 lp.yValueAxis.valueSteps = [ 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2 ] drawing.add(lp) drawing.drawOn(can, 50, 350) can.showPage()
def generatePdf(description,upc,pages): tmpFile = NamedTemporaryFile(delete=False).name c=canvas.Canvas(tmpFile,pagesize=letter) count = 0 page = 1 products = list() for i in range(30*pages): products.append({"upc":upc, "description":description}) marginTop = 8.8 * mm marginLeft = 4 * mm labelHeight = 25.5 * mm labelWidth = 67 * mm # Assume 10dx5a labels for now. finish = False while not finish: for i in reversed(range(10)): for j in range(3): try: item = products[count] print item["description"] count = count + 1 x = marginLeft + (j*labelWidth) y = marginTop + (i*labelHeight) c.setFillColorCMYK(0,0,0,1) c.setFont("Helvetica",12) c.drawString(x + (10 * mm), y + (21 * mm), item["description"].upper()) drawing = Drawing() barcode = Ean13BarcodeWidget() barcode.value = str(int(item["upc"])).zfill(12) barcode.barHeight = 12 * mm barcode.barWidth = 0.95 barcode.fontSize = 6 drawing.add(barcode) drawing.drawOn(c,x + (10 * mm), y + (8 * mm)) except: finish = True c.showPage() c.save() response = make_response(open(tmpFile).read()) response.headers["Content-type"] = "application/pdf" return response
def _draw_barcode(self, value, barHeight, barWidth): """Draw a barcode""" barcode = Drawing() if barHeight is None: barcode.add(BarcodeCode128( value=value, barWidth=barWidth )) else: barcode.add(BarcodeCode128( value=value, barHeight=barHeight, barWidth=barWidth )) barcode.drawOn( self.canv, self.cursor.x * self.unit, self.cursor.y * self.unit, )
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)
def _draw_header(cv, page_size, content=None): start_x = int(page_size[0] / 10) width = page_size[0] height = int(page_size[1] / 20) d = Drawing(width, height, vAlign="TOP") header_line = Line(start_x, 0, width - start_x, 0) d.add(header_line) if content is not None: x = int(width / 2) y = 5 text = String(x, y, content) text.fontName = DefaultFontName text.textAnchor = "middle" d.add(text) d.wrapOn(cv, width, height) d.drawOn(cv, 0, page_size[1] - height)
def _draw_feet(cv, page_size, page_num=None): start_x = int(page_size[0] / 10) width = page_size[0] height = int(page_size[1] / 20) d = Drawing(width, height, vAlign="TOP") feet_line = Line(start_x, height, width - start_x, height) d.add(feet_line) if page_num is not None: x = int(width / 2) y = height - STATE_DEFAULTS['fontSize'] text = String(x, y, str(page_num)) text.fontName = DefaultFontName text.textAnchor = "middle" d.add(text) d.wrapOn(cv, width, height) d.drawOn(cv, 0, 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()
def pdf_drawBar(self, chart_data, categoryNames=[], bar_color=[], title="", title_size=70, title_font=FONTBLOD, x=300, y=1600, chart_width=2000, chart_height=655, lable_fontSize=50, background_color=HexColor(0x000000), lable_angle=0, lable_y=0): ''' @example: chart_data = [25,65,330] chart_lable=['Rank','Total Entries'] data = [] data.append(chart_data) self.pdf_drawBar(data,categoryNames = chart_lable) ''' y = self.pdf_config_object.pdf_height - y title_position = self.get_title_position(chart_width, title, title_size) self.pdf_page_object.setFillColor(HexColor(0x000000)) self.pdf_page_object.setFont(title_font, title_size) self.pdf_page_object.drawString(x + title_position - 150, y + chart_height + title_size * 3 - 80, title) max_list = [] for index in range(len(chart_data)): if chart_data[index]: max_list.append(max(chart_data[index])) else: max_list.append(0) barchart_max = max(max_list) + 100 drawing = Drawing(800, 2230) bc = VerticalBarChart() bc.x = 0 bc.y = 0 bc.height = chart_height bc.width = chart_width bc.data = chart_data bc.groupSpacing = 15 bc.barSpacing = 10 bc.strokeColor = HexColor(0xDFDFDF) bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = barchart_max + barchart_max / 20 bc.valueAxis.valueStep = (barchart_max + barchart_max / 20) / 5 bc.valueAxis.visible = 0 bc.valueAxis.gridStrokeColor = colors.gray bc.valueAxis.visibleGrid = 1 bc.categoryAxis.labels.dx = 8 bc.categoryAxis.labels.dy = lable_y bc.categoryAxis.labels.fontSize = lable_fontSize bc.categoryAxis.labels.angle = lable_angle bc.categoryAxis.categoryNames = categoryNames if len(bar_color) == 0: for i in range(len(chart_data)): bar_color.append(HexColor(self.randomcolor())) for i in range(len(chart_data)): setattr(bc.bars[i], 'fillColor', bar_color[i]) setattr(bc.bars[i], 'strokeColor', colors.white) bc.fillColor = HexColor(0xffffff) drawing.add(bc) drawing.drawOn(self.pdf_page_object, x, y) barchart_max = barchart_max + barchart_max / 20 try: colWidths = chart_width / (len(chart_data[0])) except ZeroDivisionError as e: raise e return yheight = chart_height yStart = y self.pdf_page_object.setFillColor(background_color) self.pdf_page_object.setFont(FONTBLOD, 50) for i in range(len(chart_data)): width = 0 if not chart_data[i] == 0: for j in range(len(chart_data[i])): width = x + j * colWidths try: if len(chart_data) == 1: self.pdf_page_object.drawCentredString( width + colWidths / 2, yStart + yheight * chart_data[i][j] / barchart_max + 20, format(int(chart_data[i][j]), ',')) else: self.pdf_page_object.drawCentredString( width + colWidths / (2 * len(chart_data) + 1) * ((i + 1) * 2) - colWidths / (2 * len(chart_data) + 1) / 2, yStart + yheight * chart_data[i][j] / barchart_max + 20, format(int(chart_data[i][j]), ',')) except Exception as e: raise e
def symbols(canv,data): ''' produces filled symbols arguments n number of points default 5 x,y initial symbol location dx delta x for each new symbol dy delta y for each symbol name symbol name (suitable for makeMarker) fillColor symbol fill colour strokeColor symbol stroke colour strokeWidth symbol stroke width angle symbol angle ''' args, kw = _evalArgs(data) if args: raise TypeError('Symbols takes no positional arguments') params = dict( n=5, x='72', y='72', dx='None', dy='0', name='StarFive', fillColor='yellow', strokeColor=None, strokeWidth='1', angle=0, ) params.update(kw) from reportlab.graphics.shapes import Drawing from reportlab.graphics.widgets.markers import makeMarker from rlextra.rml2pdf.rml2pdf import readLengthOrNone name = params['name'] n = int(params['n']) x0 = readLengthOrNone(params['x']) y0 = readLengthOrNone(params['y']) angle = float(params['angle']) size = readLengthOrNone(params['size']) strokeWidth = readLengthOrNone(params['strokeWidth']) dx = readLengthOrNone(params['dx']) if dx is None: dx = 2+1.5*size dy = readLengthOrNone(params['dy']) strokeColor = _toColor(params['strokeColor']) fillColor = _toColor(params['fillColor']) D = Drawing() for i in range(n): m = makeMarker(name) m.x = dx*i m.y = dy*i m.angle = angle m.size = size m.strokeWidth = strokeWidth m.strokeColor = strokeColor m.fillColor = fillColor D.add(m) D.drawOn(canv,x0,y0)
def run(): c = reportlab.pdfgen.canvas.Canvas('barcodetest.pdf', pagesize=pagesizes.A4) framePage(c, 'Hebi-No-Shisho Barcode Test Page' ) y = 700 yd = 50 xb = 40 xs = 240 y = y-yd mybarcode = code39.Standard39(barWidth=inch * 0.010, value="CD3910", checksum=0) mybarcode.drawOn(c, xb, y) c.drawString(xs, y, '%s - Standard39 10 mil' % mybarcode.encoded) y = y-yd mybarcode = code39.Standard39(barWidth=inch * 0.015, value="CD3915", checksum=0) mybarcode.drawOn(c, xb, y) c.drawString(xs, y, '%s - Standard39 15 mil' % mybarcode.encoded) y = y-yd mybarcode = code39.Standard39(barWidth=inch * 0.020, value="CD3930", checksum=0) mybarcode.drawOn(c, xb, y) c.drawString(xs, y, '%s - Standard39 20 mil' % mybarcode.encoded) y = y-yd mybarcode = code93.Standard93(barWidth=inch * 0.010, value="CD9310") mybarcode.drawOn(c, xb, y) c.drawString(xs, y, '%s - Standard93 10 mil' % mybarcode.encoded) y = y-yd mybarcode = code93.Standard93(barWidth=inch * 0.015, value="CD9315") mybarcode.drawOn(c, xb, y) c.drawString(xs, y, '%s - Standard93 15 mil' % mybarcode.encoded) y = y-yd mybarcode = code93.Standard93(barWidth=inch * 0.020, value="CD9320") mybarcode.drawOn(c, xb, y) c.drawString(xs, y, '%s - Standard93 20 mil' % mybarcode.encoded) y = y-yd mybarcode = code128.Code128(barWidth=inch * 0.010, value="C12810") mybarcode.drawOn(c, xb, y) c.drawString(xs, y, '%s - Standard128 10 mil' % mybarcode.value) y = y-yd mybarcode = code128.Code128(barWidth=inch * 0.015, value="C12815") mybarcode.drawOn(c, xb, y) c.drawString(xs, y, '%s - Standard128 15 mil' % mybarcode.value) y = y-yd mybarcode = code128.Code128(barWidth=inch * 0.020, value="C12820") mybarcode.drawOn(c, xb, y) c.drawString(xs, y, '%s - Standard128 20 mil' % mybarcode.value) y = y-yd-10 mydrawing = Drawing() mybarcode = eanbc.Ean13BarcodeWidget(barHeight=inch * 0.5, barWidth=inch * 0.015, value="123456789012") mydrawing.add(mybarcode) mydrawing.drawOn(c, xb, y) c.drawString(xs, y, 'EAN13') c.save()
def body(): # Body size_y = 0.62 data = [["Sold", "Cash", "Card", "Contingent", "Reserved", "Expected", "Unsold Reserv."]] for cat, value in report_result_dict.iteritems(): size_y = size_y + 1.86 """ if cat == 'all': report_cat_name = 'All' else: report_cat_name = self.report_cat_list[event_id][cat] """ if cat == "all": categorie_name = "All" else: categorie_name = cat_name[cat] p = Paragraph('<para alignment="center"><b>' + categorie_name + "</b></para>", styles["Normal"]) data.append([p, "", "", "", "", "", ""]) if cat == "all": data_for_pie = [ value["a_total_sold"], value["a_sold_cash"], value["a_sold_card"], value["a_sold_conti"], value["a_reserved"], value["a_not_visited"], ] data.append( [ value["a_total_sold"], value["a_sold_cash"], value["a_sold_card"], value["a_sold_conti"], value["a_reserved"], value["a_total_pre"], value["a_not_visited"], ] ) data.append( [ str(value["m_total_sold"]) + unichr(8364), str(value["m_sold_cash"]) + unichr(8364), str(value["m_sold_card"]) + unichr(8364), "-", str(value["m_reserved"]) + unichr(8364), str(value["m_total_pre"]) + unichr(8364), str(value["m_not_visited"]) + unichr(8364), ] ) tstyle = [ ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.grey), ("BOX", (0, 0), (-1, -1), 0.25, colors.black), ("ALIGN", (0, 1), (-1, -1), "RIGHT"), ( "COLBACKGROUNDS", (0, 0), (-1, -1), [ colors.lightpink, colors.lightpink, colors.lightpink, colors.lightpink, colors.lightyellow, colors.lightgrey, colors.lightyellow, ], ), ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.lightslategray, None, None]), ] t = Table(data) t.setStyle(TableStyle(tstyle)) t.wrapOn(c, 19 * cm, 0 * cm) pos_y = 26.5 - size_y t.drawOn(c, 1 * cm, pos_y * cm) # Price Details # size_y = 0.62 pdata = [] for cat, value in report_result_dict.iteritems(): size_y = size_y + 1.86 if cat == "all": pass else: categorie_name = cat_name[cat] p = Paragraph('<para alignment="center"><b>' + categorie_name + "</b></para>", styles["Normal"]) pdata.append([p]) data_price_titles = [] data_price_amount = [] data_price_total = [] for prow in p_result: if cat == "cat_" + str(prow["cat_id"]): data_price_titles.append(prow["name"]) try: data_price_amount.append(str(value["a_prices"][str(prow["id"])])) except KeyError: data_price_amount.append("0") try: data_price_total.append(str(value["m_prices"][str(prow["id"])]) + unichr(8364)) except KeyError: data_price_total.append("0" + unichr(8364)) print data_price_titles pdata.append(data_price_titles) pdata.append(data_price_amount) pdata.append(data_price_total) tstyle = [ ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.grey), ("BOX", (0, 0), (-1, -1), 0.25, colors.black), ("ALIGN", (0, 1), (-1, -1), "RIGHT"), ("COLBACKGROUNDS", (0, 0), (-1, -1), [colors.lightgrey, colors.whitesmoke]), ("ROWBACKGROUNDS", (0, 0), (-1, -1), [colors.lightslategray, None, None, None]), ] t = Table(pdata) t.setStyle(TableStyle(tstyle)) t.wrapOn(c, 19 * cm, 0 * cm) pos_y = 25 - size_y t.drawOn(c, 1 * cm, pos_y * cm) """ #Pie Chart d = Drawing(500, 500) pc = Pie() pc.x = 65 pc.y = 15 pc.width = 200 pc.height = 200 pc.data = data_for_pie pc.labels = ['Sold','Cash','Card','Contingent','Reserved','Unsold Reserv.'] pc.slices.strokeWidth=0.5 pc.slices[0].popout = 10 #pc.slices[0].strokeWidth = 2 #pc.slices[0].strokeDashArray = [2,2] pc.slices[0].labelRadius = 1.3 pc.slices[0].fontColor = colors.red pc.slices[0].fillColor = colors.lightpink pc.slices[1].fillColor = colors.lightpink pc.slices[2].fillColor = colors.lightpink pc.slices[3].fillColor = colors.lightpink pc.slices[4].fillColor = colors.lightyellow pc.slices[5].fillColor = colors.lightyellow d.add(pc) d.wrapOn(c, 5*cm, 5*cm) d.drawOn(c, 1*cm, 1*cm) """ if event_date == "all": data = [] sold = [] reserved = [] unsold_reserved = [] sold_contingent = [] for key, value in sorted(report_date_dict.iteritems(), key=lambda report_date_dict: report_date_dict[0]): date_day_dt = dt.datetime.strptime(key, "%Y-%m-%d") date_day = date_day_dt.strftime("%Y%m%d") sold.append((int(date_day), value["sold"])) reserved.append((int(date_day), value["reserved"])) unsold_reserved.append((int(date_day), value["unsold_reserved"])) sold_contingent.append((int(date_day), value["sold_contingent"])) data.append(sold) data.append(reserved) data.append(unsold_reserved) data.append(sold_contingent) print data # sample data _colors = ( Color(0.90, 0, 0), Color(0.801961, 0.801961, 0), Color(0.380392, 0.380392, 0), Color(0.580392, 0, 0), ) _catNames = "Sold", "Reserved", "Unsold Reserved", "Contingents" d = Drawing(400, 200) # adding the actual chart here. plot = GridLinePlot() plot.y = 50 plot.x = 15 plot.width = 525 plot.height = 125 plot.xValueAxis.xLabelFormat = "{ddd} {dd}. {mm}." plot.lineLabels.fontSize = 6 plot.lineLabels.boxStrokeWidth = 0.5 plot.lineLabels.visible = 1 plot.lineLabels.boxAnchor = "c" plot.lineLabels.angle = 0 plot.lineLabelNudge = 10 plot.joinedLines = 1 plot.lines.strokeWidth = 1.5 plot.lines[0].strokeColor = _colors[0] plot.lines[1].strokeColor = _colors[1] plot.lines[2].strokeColor = _colors[2] plot.lines[3].strokeColor = _colors[3] # sample data plot.data = data """ plot.data = [[(20010630, 1000), (20011231, 101), (20020630, 100.05), (20021231, 102), (20030630, 103), (20031230, 104), (20040630, 99.200000000000003), (20041231, 99.099999999999994)], [(20010630, 100.8), (20011231, 100.90000000000001), (20020630, 100.2), (20021231, 100.09999999999999), (20030630, 100), (20031230, 100.05), (20040630, 99.900000000000006), (20041231, 99.799999999999997)], [(20010630, 99.700000000000003), (20011231, 99.799999999999997), (20020630, 100), (20021231, 100.01000000000001), (20030630, 95), (20031230, 90), (20040630, 85), (20041231, 80)]] """ # y axis plot.yValueAxis.tickRight = 0 plot.yValueAxis.maximumTicks = 10 # plot.yValueAxis.leftAxisPercent = 0 plot.yValueAxis.tickLeft = 5 plot.yValueAxis.valueMax = None plot.yValueAxis.valueMin = None plot.yValueAxis.rangeRound = "both" plot.yValueAxis.requiredRange = 30 plot.yValueAxis.valueSteps = None plot.yValueAxis.valueStep = None plot.yValueAxis.forceZero = 0 plot.yValueAxis.labels.fontSize = 7 plot.yValueAxis.labels.dy = 0 plot.yValueAxis.avoidBoundFrac = 0.1 # x axis plot.xValueAxis.labels.fontName = "Helvetica" plot.xValueAxis.labels.fontSize = 7 plot.xValueAxis.valueSteps = None plot.xValueAxis.dailyFreq = 0 plot.xValueAxis.gridStrokeWidth = 0.25 plot.xValueAxis.labels.angle = 90 plot.xValueAxis.maximumTicks = 20 plot.xValueAxis.tickDown = 3 plot.xValueAxis.dailyFreq = 0 plot.xValueAxis.bottomAxisLabelSlack = 0 plot.xValueAxis.minimumTickSpacing = 10 plot.xValueAxis.visibleGrid = 0 plot.xValueAxis.gridEnd = 0 plot.xValueAxis.gridStart = 0 plot.xValueAxis.labels.angle = 45 plot.xValueAxis.labels.boxAnchor = "e" plot.xValueAxis.labels.dx = 0 plot.xValueAxis.labels.dy = -5 # adding legend legend = LineLegend() legend.boxAnchor = "sw" legend.x = 20 legend.y = -2 legend.columnMaximum = 1 legend.yGap = 0 legend.deltax = 50 legend.deltay = 0 legend.dx = 10 legend.dy = 1.5 legend.fontSize = 7 legend.alignment = "right" legend.dxTextSpace = 5 legend.colorNamePairs = [(_colors[i], _catNames[i]) for i in xrange(len(plot.data))] d.add(plot) d.add(legend) d.wrapOn(c, 18 * cm, 5 * cm) d.drawOn(c, 1 * cm, 1 * cm) c.showPage()
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()
def drawsystemdailyefficiency(can, resultsbuffer): can.setFont("Helvetica", 24) sec_title = "Chiller Plant System Daily Efficiency" can.drawString(25, 750, sec_title) desc_text = "The chiller plant system daily efficiency demonstrates the total efficiency including every" \ " parts of the system across a series of days. The range can be by default (say, 2 days) or" \ " specified by administrators." stylesheet = getSampleStyleSheet() paragraph = Paragraph(desc_text, stylesheet['Normal']) aW, aH = 500, 600 w, h = paragraph.wrap(aW, aH) if w <= aW and h <= aH: paragraph.drawOn(can, 25, 700) # Draw the chart drawing = Drawing(600, 400) # font fontName = 'Helvetica' fontSize = 7 # chart lp = LinePlot() lp.y = 16 lp.x = 32 lp.width = 400 lp.height = 200 # line styles lp.lines.strokeWidth = 0 lp.lines.symbol = makeMarker('FilledSquare') # x axis lp.xValueAxis = NormalDateXValueAxis() lp.xValueAxis.labels.fontName = fontName lp.xValueAxis.labels.fontSize = fontSize - 1 lp.xValueAxis.forceEndDate = 1 lp.xValueAxis.forceFirstDate = 1 lp.xValueAxis.labels.boxAnchor = 'autox' lp.xValueAxis.xLabelFormat = '{d}-{MMM}' lp.xValueAxis.maximumTicks = 5 lp.xValueAxis.minimumTickSpacing = 0.5 lp.xValueAxis.niceMonth = 0 lp.xValueAxis.strokeWidth = 1 lp.xValueAxis.loLLen = 5 lp.xValueAxis.hiLLen = 5 lp.xValueAxis.gridEnd = drawing.width lp.xValueAxis.gridStart = lp.x - 10 # y axis # self.chart.yValueAxis = AdjYValueAxis() lp.yValueAxis.visibleGrid = 1 lp.yValueAxis.visibleAxis = 0 lp.yValueAxis.labels.fontName = fontName lp.yValueAxis.labels.fontSize = fontSize - 1 lp.yValueAxis.labelTextFormat = '%0.2f%%' lp.yValueAxis.strokeWidth = 0.25 lp.yValueAxis.visible = 1 lp.yValueAxis.labels.rightPadding = 5 # self.chart.yValueAxis.maximumTicks = 6 lp.yValueAxis.rangeRound = 'both' lp.yValueAxis.tickLeft = 7.5 lp.yValueAxis.minimumTickSpacing = 0.5 lp.yValueAxis.maximumTicks = 8 lp.yValueAxis.forceZero = 0 lp.yValueAxis.avoidBoundFrac = 0.1 # legend ll = LineLegend() ll.fontName = fontName ll.fontSize = fontSize ll.alignment = 'right' ll.dx = 5 # sample data lp.data = [[(19010706, 3.3900000000000001), (19010806, 3.29), (19010906, 3.2999999999999998), (19011006, 3.29), (19011106, 3.3399999999999999), (19011206, 3.4100000000000001), (19020107, 3.3700000000000001), (19020207, 3.3700000000000001), (19020307, 3.3700000000000001), (19020407, 3.5), (19020507, 3.6200000000000001), (19020607, 3.46), (19020707, 3.3900000000000001)], [(19010706, 3.2000000000000002), (19010806, 3.1200000000000001), (19010906, 3.1400000000000001), (19011006, 3.1400000000000001), (19011106, 3.1699999999999999), (19011206, 3.23), (19020107, 3.1899999999999999), (19020207, 3.2000000000000002), (19020307, 3.1899999999999999), (19020407, 3.3100000000000001), (19020507, 3.4300000000000002), (19020607, 3.29), (19020707, 3.2200000000000002)]] lp.lines[0].strokeColor = PCMYKColor(0, 100, 100, 40, alpha=100) lp.lines[1].strokeColor = PCMYKColor(100, 0, 90, 50, alpha=100) lp.xValueAxis.strokeColor = PCMYKColor(100, 60, 0, 50, alpha=100) ll.colorNamePairs = [(PCMYKColor(0, 100, 100, 40, alpha=100), '01-Mar-2017'), (PCMYKColor(100, 0, 90, 50, alpha=100), '02-Mar-2017')] lp.lines.symbol.x = 0 lp.lines.symbol.strokeWidth = 0 lp.lines.symbol.arrowBarbDx = 5 lp.lines.symbol.strokeColor = PCMYKColor(0, 0, 0, 0, alpha=100) lp.lines.symbol.fillColor = None lp.lines.symbol.arrowHeight = 5 ll.dxTextSpace = 7 ll.boxAnchor = 'nw' ll.subCols.dx = 0 ll.subCols.dy = -2 ll.subCols.rpad = 0 ll.columnMaximum = 1 ll.deltax = 1 ll.deltay = 0 ll.dy = 5 ll.y = 240 ll.x = 300 lp.lines.symbol.kind = 'FilledCross' lp.lines.symbol.size = 5 lp.lines.symbol.angle = 45 drawing.add(lp) drawing.add(ll) # drawing.title.text = "Jurong Point System Efficiency" # drawing.title.fondSize = 16 drawing.drawOn(can, 100, 450) can.showPage()
def createBarGraph(c, x, y, data, labels, colors, barnames, minvalue, maxvalue, step, h=75, w=300, dy=0): """ Function to draw a Bar Graph """ drawing = Drawing(400, 200) legend = Legend() legend.columnMaximum = 99 legend.alignment = 'right' legend.dx = 7 legend.dy = 7 legend.dxTextSpace = 5 legend.deltay = 10 legend.strokeWidth = 0 legend.strokeColor = HexColor("0xffffff") legend.subCols[0].minWidth = 75 legend.subCols[0].align = 'left' legend.boxAnchor = 'c' legend.y = h + 25 legend.x = w + 110 legend.fontName = "MavenPro" legend.fontSize = 8.5 legendList = [] for k, i in enumerate(colors): legendList.append((HexColor(i), barnames[k])) legend.colorNamePairs = legendList bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = h # 75 bc.width = w # 300 bc.data = data bc.bars.strokeColor = HexColor("0xffffff") bc.valueAxis.labels.fontName = "MavenPro" bc.valueAxis.labels.fontSize = 8 bc.valueAxis.labels.dx = -10 bc.valueAxis.valueMin = minvalue bc.valueAxis.valueMax = maxvalue bc.valueAxis.valueStep = step bc.categoryAxis.labels.boxAnchor = 'n' bc.categoryAxis.labels.dx = 0 bc.categoryAxis.labels.dy = -10 - dy bc.categoryAxis.labels.angle = 0 bc.categoryAxis.labels.fontName = "MavenPro" bc.categoryAxis.labels.fontSize = 8 bc.categoryAxis.categoryNames = labels for k in xrange(len(colors)): bc.bars[k].fillColor = HexColor(colors[k]) #self.chart.bars[k].fillColor = HexColor(colors[k]) drawing.add(bc) drawing.add(legend, 'legend') drawing.drawOn(c, x, y)
def symbols(canv,data): ''' produces filled symbols arguments n number of points default 5 x,y initial symbol location dx delta x for each new symbol dy delta y for each symbol name symbol name (suitable for makeMarker) fillColor symbol fill colour strokeColor symbol stroke colour strokeWidth symbol stroke width angle symbol angle ''' args, kw = _evalArgs(data) if args: raise TypeError('Symbols takes no positional arguments') params = dict( n=5, x='72', y='72', dx='None', dy='0', name='StarFive', fillColor='yellow', strokeColor=None, strokeWidth='1', angle=0, ) params.update(kw) from reportlab.graphics.shapes import Drawing from reportlab.graphics.widgets.markers import makeMarker from reportPackages.rlextra.rml2pdf.rml2pdf import readLengthOrNone name = params['name'] n = int(params['n']) x0 = readLengthOrNone(params['x']) y0 = readLengthOrNone(params['y']) angle = float(params['angle']) size = readLengthOrNone(params['size']) strokeWidth = readLengthOrNone(params['strokeWidth']) dx = readLengthOrNone(params['dx']) if dx is None: dx = 2+1.5*size dy = readLengthOrNone(params['dy']) strokeColor = _toColor(params['strokeColor']) fillColor = _toColor(params['fillColor']) D = Drawing() for i in range(n): m = makeMarker(name) m.x = dx*i m.y = dy*i m.angle = angle m.size = size m.strokeWidth = strokeWidth m.strokeColor = strokeColor m.fillColor = fillColor D.add(m) D.drawOn(canv,x0,y0)
def generate_page1(c): #Image---------------------------------------------------------------------- im1 = Image.open("left.jpg") c.drawInlineImage(im1, 10, 15, width=546 / 2.3, height=1290 / 2.3) im2 = Image.open("shinken.jpg") c.drawInlineImage(im2, 259, height - 183, width=2434 / 4.4, height=725 / 4.4) im3 = Image.open("skor.jpg") c.drawInlineImage(im3, 259, height - 251, width=2335 / 4.2, height=271 / 4.2) im4 = Image.open("diagram.jpg") c.drawInlineImage(im4, 259, 15, width=2339 / 4.2, height=1367 / 4.2) #grafik1---------------------------------------------------------------------- from reportlab.graphics.shapes import Drawing from reportlab.graphics.charts.barcharts import HorizontalBarChart drawing = Drawing(500, 250) data = [(N1, N2, N3, N4, N5, N6, N7, N8, N9, N10, N11, N12, N13, N14, N15, N16, N17)] bc = HorizontalBarChart() bc.x = 100 bc.y = 100 bc.height = 250 bc.width = 300 bc.data = data bc.strokeColor = None bc.fillColor = None # bc.bars[0].fillColor = PCMYKColor(92,47,0,33,alpha=95) # bc.bars[0].strokeColor = PCMYKColor(92,47,0,33,alpha=95) # bc.bars[0].fillColor = PCMYKColor(92,32,0,33,alpha=95) # bc.bars[0].strokeColor = PCMYKColor(92,32,0,33,alpha=95) bc.bars[0].fillColor = PCMYKColor(92, 16, 0, 33, alpha=95) bc.bars[0].strokeColor = PCMYKColor(92, 16, 0, 33, alpha=95) # bc.bars[0].fillColor = PCMYKColor(92,7,0,33,alpha=95) # bc.bars[0].strokeColor = PCMYKColor(92,7,0,33,alpha=95) bc.barWidth = 15 bc.valueAxis.valueMin = 0 bc.valueAxis.valueMax = 100 bc.valueAxis.valueStep = 10 bc.valueAxis.visibleAxis = False bc.valueAxis.visibleGrid = False bc.valueAxis.visibleTicks = False bc.valueAxis.forceZero = True bc.valueAxis.visibleLabels = 0 bc.categoryAxis.visibleGrid = False bc.categoryAxis.visibleTicks = False # hidding the ticks remove the label bc.categoryAxis.tickLeft = 0 # a workaround is to set the tick length bc.categoryAxis.tickRight = 0 # to zero. bc.categoryAxis.strokeWidth = 0.25 bc.categoryAxis.labelAxisMode = 'low' bc.categoryAxis.labels.textAnchor = 'end' bc.categoryAxis.labels.angle = 0 bc.categoryAxis.labels.fontName = 'Designosaur-Regular' #bc.categoryAxis.labels.fontColor = PCMYKColor(0,65,100,0,alpha=90) bc.categoryAxis.labels.boxAnchor = 'e' bc.categoryAxis.labels.dx = -5 bc.categoryAxis.labels.dy = 0 bc.categoryAxis.labels.angle = 0 bc.categoryAxis.reverseDirection = 1 bc.categoryAxis.joinAxisMode = 'left' bc.categoryAxis.categoryNames = [ NN1, NN2, NN3, NN4, NN5, NN6, NN7, NN8, NN9, NN10, NN11, NN12, NN13, NN14, NN15, NN16, NN17 ] bc.barLabels.fontName = 'Designosaur-Regular' bc.barLabels.fontSize = 10 bc.barLabels.angle = 0 bc.barLabelFormat = "%.00f%%" bc.barLabels.boxAnchor = 'w' bc.barLabels.boxFillColor = None bc.barLabels.boxStrokeColor = None bc.barLabels.dx = 10 bc.barLabels.dy = 0 #bc.barLabels.dy = -1 bc.barLabels.boxTarget = 'hi' drawing.add(bc) drawing.wrapOn(c, width, height) drawing.drawOn(c, 350, height - 650) #Table--------------------------------------------------------------------- styleBH = styles["Normal"] styleBH.alignment = TA_CENTER styleBH.fontSize = 12 styleBH.fontName = 'Designosaur-Regular' #styleBH.textColor = PCMYKColor(92,7,0,33,alpha=100) isi1 = Paragraph(nama, styleBH) isitabel1 = [[isi1]] table1 = Table(isitabel1, colWidths=[150]) table1.wrapOn(c, width, height) table1.drawOn(c, 54, height - 352) isi2 = Paragraph(kelas, styleBH) isitabel2 = [[isi2]] table2 = Table(isitabel2, colWidths=[150]) table2.wrapOn(c, width, height) table2.drawOn(c, 54, height - 386) isi3 = Paragraph(sekolah, styleBH) isitabel3 = [[isi3]] table3 = Table(isitabel3, colWidths=[150]) table3.wrapOn(c, width, height) table3.drawOn(c, 54, height - 421) isi4 = Paragraph(outlet, styleBH) isitabel4 = [[isi4]] table4 = Table(isitabel4, colWidths=[150]) table4.wrapOn(c, width, height) table4.drawOn(c, 54, height - 455) #Text---------------------------------------------------------------------- #nilai total c.setFillColor(white) c.setStrokeColor(white) if (NTotal == '10.0'): c.setFont("Designosaur-Regular", 35) c.drawString(352, height - 230, NTotal + "/") c.setFont("Designosaur-Regular", 20) c.drawString(395, height - 235, "10") else: c.setFont("Designosaur-Regular", 35) c.drawString(338, height - 230, NTotal + "/") c.setFont("Designosaur-Regular", 20) c.drawString(415, height - 235, "10") #Yang paling tidak dikuasai siswa c.setFont("Designosaur-Regular", 9) c.drawString( 576, height - 205, "Topik yang paling tidak dikuasai peserta Try-Out II :" ) c.drawString(576, height - 216, "1. Mean, Median, dan Modus") c.drawString(576, height - 227, "2. Debit Air") c.drawString(576, height - 238, "3. Bangun Ruang")
def pdf_drawPolyline(self, table_data, table_lable=[], title="", title_size=70, title_font=FONTBLOD, x=350, y=1800, width=2000, height=1000, line_width=8, lable_color=HexColor(0x000000), lable_angle=45, lable_fontsize=30, legend_y=450): ''' @example: chart_data_1 = { 'name': 'Occupancy ', 'data': [1,2,3,5,6,8], 'color': HexColor(0x2ebf70) } chart_data = [] chart_data.append(chart_data_1) self.pdf_drawPolyline(chart_data) ''' y = self.pdf_config_object.pdf_height - y chart_values = [] size = len(table_data) if size == 0: return width_single = width / size / 4 / 3 step = width / size x_position_tmp = x + step / 3 y_position = y + 70 * 3 + height title_position = self.get_title_position(width, title, title_size) self.pdf_page_object.setFillColor(HexColor(0x000000)) self.pdf_page_object.setFont(title_font, title_size) self.pdf_page_object.drawString(x + title_position - 120, y + height + title_size * 5 - 200, title) self.pdf_page_object.setLineWidth(line_width) i = 0 for single in table_data: chart_values.append(single['data']) self.pdf_page_object.setStrokeColor(single['color']) x_position = x_position_tmp + (i) * step self.pdf_page_object.line(x_position, y_position - legend_y - height, x_position + width_single * 0.8, y_position - legend_y - height) self.pdf_page_object.setFont(FONTBLOD, 40) self.pdf_page_object.setFillColor(HexColor(0x000000)) self.pdf_page_object.drawString(x_position + width_single, y_position - legend_y - height, single['name']) i = i + 1 drawing = Drawing(x, y) lc = HorizontalLineChart() lc.valueAxis.visible = 0 lc.categoryAxis.gridStrokeColor = colors.gray lc.valueAxis.gridStrokeColor = colors.gray lc.valueAxis.visibleGrid = 1 lc.valueAxis.labels.visible = 0 lc.height = height lc.width = width lc.data = chart_values lc.categoryAxis.categoryNames = table_lable lc.categoryAxis.labels.fontName = FONTBLOD lc.strokeColor = HexColor(0xffffff) lc.categoryAxis.labels.angle = 0 lc.categoryAxis.labels.strokeColor = lable_color lc.categoryAxis.labels.angle = lable_angle lc.categoryAxis.labels.dy = -60 lc.categoryAxis.labels.fontSize = lable_fontsize lc.valueAxis.valueMin = 0 y_value_max = self.get_biggest_value(chart_values) + 20 lc.valueAxis.valueMax = (y_value_max / 10) * 13 lc.valueAxis.valueStep = (y_value_max / 10) * 13 / 5 lc.lines.strokeWidth = line_width for i in range(size): lc.lines[i].strokeColor = table_data[i]['color'] if len(chart_values[0]) == 0: return drawing.add(lc) drawing.drawOn(self.pdf_page_object, x, y) labelArr = [] step = (y_value_max / 10) * 13 / 5 valueMax = (y_value_max / 10) * 13 for i in range(5): labelArr.append(i * step) self.pdf_page_object.drawString(x - 100, y + height * i * step / valueMax, format(i * step, ',')) self.pdf_page_object.drawString(x - 100, y + height, format(5 * step, ',')) lenthOfLabelLine = 100 arrLabeled = [] for item in table_data: self.pdf_page_object.setStrokeColor(item['color'], 1) self.pdf_page_object.setLineWidth(3) self.pdf_page_object.setFillColor(item['color']) peakData = self.get_max_data(item['data']) for peakInLoop in peakData: peakDataOne = peakInLoop['value'] posInarry = peakInLoop['index'] posYOfPeak = y + height * peakDataOne / valueMax + 10 posXOfPeak = x + width / len(item['data']) * ( posInarry + 1) - width / len(item['data']) / 2 + 20 if posInarry in arrLabeled: lenthOfLabelLine = lenthOfLabelLine + 80 deltaX, deltaY = self.get_randomdelta(lenthOfLabelLine) self.pdf_page_object.line(posXOfPeak, posYOfPeak, posXOfPeak + deltaX, posYOfPeak + deltaY) self.pdf_page_object.drawCentredString( posXOfPeak + deltaX, posYOfPeak + deltaY + 10, format(peakDataOne, ',')) arrLabeled.append(posInarry) lenthOfLabelLine = 100