def blank_plot(maxx, maxy, minx=0.0, miny=0.0): if maxx == 0.0: maxx = 1.0 if maxy < 1E-8 and miny == 0.0: maxy = 1.0 lpt = AddedPlot() lpt.strokeColor = HexColor("#454545") lpt.joinedLines = 1 lpt.xValueAxis.labels.fontName = 'Arial' lpt.xValueAxis.tickDown = 0 lpt.xValueAxis.tickUp = 5 lpt.yValueAxis.tickLeft = 0 lpt.yValueAxis.tickRight = 5 lpt.yValueAxis.labels.fontName = 'Arial' lpt.xValueAxis.valueMin = minx lpt.xValueAxis.valueMax = maxx lpt.yValueAxis.valueMin = miny lpt.yValueAxis.valueMax = maxy lpt.data = [[(0, 0), (0, 0)], [(0, 0), (0, 0)]] rto = 7 if maxx - minx > 10 or isinstance(minx, int): lpt.xValueAxis.labelTextFormat = '%.0f' elif maxx - minx > 1: lpt.xValueAxis.labelTextFormat = '%.1f' elif maxx - minx > 0.1: lpt.xValueAxis.labelTextFormat = '%.2f' else: lpt.xValueAxis.labelTextFormat = '%.3f' if maxy - miny > 10: lpt.yValueAxis.labelTextFormat = '%.0f' elif maxy - miny > 1: lpt.yValueAxis.labelTextFormat = '%.1f' elif maxy - miny > 0.1: lpt.yValueAxis.labelTextFormat = '%.2f' else: lpt.yValueAxis.labelTextFormat = '%.3f' xsp = float(lpt.xValueAxis.labelTextFormat % ((maxx - minx) / rto)) ysp = float(lpt.yValueAxis.labelTextFormat % ((maxy - miny) / rto)) if xsp > 10: xsp = int(xsp) / 10 * 10 if ysp > 10: ysp = int(ysp) / 10 * 10 if xsp == 0.0: xsp = 1.0 if ysp == 0.0: ysp = 1.0 if np.abs(miny - maxy) < 1E-10: maxy = miny + 1.0 ysp = 1.0 lpt.xValueAxis.valueSteps = list(np.arange(minx, maxx + xsp / 2, xsp)) lpt.yValueAxis.valueSteps = list(np.arange(miny, maxy + ysp / 2, ysp)) if lpt.xValueAxis.valueSteps[-1] > maxx: lpt.xValueAxis.valueMax = lpt.xValueAxis.valueSteps[-1] if lpt.yValueAxis.valueSteps[-1] > maxy: lpt.yValueAxis.valueMax = lpt.yValueAxis.valueSteps[-1] return lpt
def table_model(): """ 添加表格 :return: """ template_path = current_app.config.get("REPORT_TEMPLATES") image_path = os.path.join(template_path, 'test.jpg') new_img = Image(image_path, width=300, height=300) base = [ [new_img, ""], ["大类", "小类"], ["WebFramework", "django"], ["", "flask"], ["", "web.py"], ["", "tornado"], ["Office", "xlsxwriter"], ["", "openpyxl"], ["", "xlrd"], ["", "xlwt"], ["", "python-docx"], ["", "docxtpl"], ] style = [ # 设置字体 ('FONTNAME', (0, 0), (-1, -1), 'SimSun'), # 合并单元格 (列,行) ('SPAN', (0, 0), (1, 0)), ('SPAN', (0, 2), (0, 5)), ('SPAN', (0, 6), (0, 11)), # 单元格背景 ('BACKGROUND', (0, 1), (1, 1), HexColor('#548DD4')), # 字体颜色 ('TEXTCOLOR', (0, 1), (1, 1), colors.white), # 对齐设置 ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), # 单元格框线 ('GRID', (0, 0), (-1, -1), 0.5, colors.grey), ('BOX', (0, 0), (-1, -1), 0.5, colors.black), ] component_table = Table(base, style=style) return component_table
def draw_bar_chart(min, max, x_list, data=[()], x_label_angle=0, bar_color=HexColor("#7BB8E7"), height=125, width=280): ''' :param min: 设置y轴的最小值 :param max: 设置y轴的最大值 :param x_list: x轴上的标签 :param data: y轴对应标签的值 :param x_label_angle: x轴上标签的倾斜角度 :param bar_color: 柱的颜色 可以是含有多种颜色的列表 :param height: 柱状图的高度 :param width: 柱状图的宽度 :return: ''' bc = VerticalBarChart() bc.x = 50 # x和y是柱状图在框中的坐标 bc.y = 50 bc.height = height # 柱状图的高度 bc.width = width # 柱状图的宽度 bc.data = data for j in xrange(len(x_list)): setattr(bc.bars[j], 'fillColor', bar_color) # bar_color若含有多种颜色在这里分配bar_color[j] # 调整step minv = min * 0.5 maxv = max * 1.5 maxAxis = int(height/10) # 向上取整 minStep = int((maxv-minv+maxAxis-1)/maxAxis) bc.valueAxis.valueMin = min * 0.5 #设置y轴的最小值 bc.valueAxis.valueMax = max * 1.5 #设置y轴的最大值 bc.valueAxis.valueStep = (max-min)/4 #设置y轴的最小度量单位 if bc.valueAxis.valueStep < minStep: bc.valueAxis.valueStep = minStep if bc.valueAxis.valueStep == 0: bc.valueAxis.valueStep = 1 bc.categoryAxis.labels.boxAnchor = 'ne' # x轴下方标签坐标的开口方向 bc.categoryAxis.labels.dx = -5 # x和y是x轴下方的标签距离x轴远近的坐标 bc.categoryAxis.labels.dy = -5 bc.categoryAxis.labels.angle = x_label_angle # x轴上描述文字的倾斜角度 # bc.categoryAxis.labels.fontName = 'song' x_real_list = [] if len(x_list) > 10: for i in range(len(x_list)): tmp = '' if i%5 != 0 else x_list[i] x_real_list.append(tmp) else: x_real_list = x_list bc.categoryAxis.categoryNames = x_real_list return bc
def draw_line(_certificateGen, attributes, canvas, _context): stroke = 0 stroke_color = attributes.get('stroke_color') stroke_width = attributes.get('stroke_width') if stroke_color or stroke_width: stroke_color = stroke_color or '#000000' stroke_width = stroke_width or 1 canvas.setLineWidth(stroke_width) canvas.setStrokeColor(HexColor(stroke_color)) canvas.line( attributes['x_start'], attributes['y_start'], attributes['x_end'], attributes['y_end'], )
def __init__(self, report_type, report_method, **kwargs): # self.db = Db() # 连接数据库 self.grade_color = HexColor(0xe20c1e) # 等级颜色 self.id = None # 报告id self.name = None # 任务名称 self.high = 5 # 病毒木马数量 self.medium = 6 # 程序告警数量 + 设备告警数量 self.low = 7 # 操作告警数量 self.alm = 0 # 程序告警数量 self.dev = 0 # 设备告警数量 self.total = 0 # 总数 self.report_type = report_type self.report_method = report_method # self.start_time = kwargs["start_time"] # 开始时间 # self.end_time = kwargs["end_time"] # 结束时间 self.data_dict = kwargs
def line_plot(data, colors, widths, maxx, maxy, minx=0.0, miny=0.0, marker=False, intpol=False): ym, yn = maxy, miny if not intpol: lpt = PGPlot.blank_plot(maxx, maxy, minx=minx, miny=miny) if len(data) != 0 and len(data[0]) != 0: lpt.data = data mm = makeMarker('FilledCircle', size=2) for ii, i in enumerate(zip(colors, widths)): lpt.lines[ii].strokeColor = i[0] lpt.lines[ii].strokeWidth = i[1] if marker: lpt.lines[ii].symbol = mm else: from scipy.interpolate import CubicSpline ldata = [] for d in data: dd = np.array(d) ipx = CubicSpline(dd[:, 0], dd[:, 1], bc_type='clamped') datax = np.arange(minx, max(dd[:, 0]), (maxx - minx) / 500.0 - 1E-6) datay = ipx(datax) ldata += [zip(datax, datay), d] ym = max(max(datay), ym) yn = min(min(datay), yn) lpt = PGPlot.blank_plot(maxx, ym, minx=minx, miny=yn) lpt.data = ldata mm = makeMarker('FilledCircle', size=3, fillColor=HexColor("#FFFFFF"), strokeColor=colors[0], strokeWidth=widths[0]) for ii, i in enumerate(zip(colors, widths)): lpt.lines[ii * 2].strokeColor = i[0] lpt.lines[ii * 2].strokeWidth = i[1] lpt.lines[ii * 2 + 1].strokeColor = None lpt.lines[ii * 2 + 1].strokeWidth = 0.0 if marker: lpt.lines[ii * 2 + 1].symbol = mm return lpt, ym, yn
def make_overlay_pdf(watermark, position, font, fontsize, mediabox): lowerLeft = (mediabox.lowerLeft[0].as_numeric(), mediabox.lowerLeft[1].as_numeric()) lowerRight = (mediabox.lowerRight[0].as_numeric(), mediabox.lowerRight[1].as_numeric()) upperLeft = (mediabox.upperLeft[0].as_numeric(), mediabox.upperLeft[1].as_numeric()) upperRight = (mediabox.upperRight[0].as_numeric(), mediabox.upperRight[1].as_numeric()) width_page = lowerRight[0] - lowerLeft[0] height_page = upperLeft[1] - lowerLeft[1] margin = { 'top': 0.5 * cm, 'right': 1 * cm, 'bottom': 1 * cm, 'left': 1 * cm } # 上、右、下、左的边距为厘米 packet = io.BytesIO() canva = canvas.Canvas(packet, pagesize=(width_page, height_page)) canva.setFont(font, fontsize) watermark_width = canva.stringWidth(watermark, font, fontsize) canva.setFillColor(HexColor(FONT_COLOR)) if position == 'top-left': x = upperLeft[0] + margin['left'] y = upperLeft[1] - margin['top'] - fontsize elif position == 'top-right': x = upperRight[0] - (margin['right'] + watermark_width) y = upperRight[1] - margin['top'] - fontsize elif position == 'bottom-left': x = lowerLeft[0] + margin['left'] y = lowerLeft[1] + margin['bottom'] elif position == 'bottom-right': x = lowerRight[0] - (margin['right'] + watermark_width) y = lowerRight[1] + margin['bottom'] elif position == 'top-middle': x = upperLeft[0] + (upperRight[0] - upperLeft[0]) / 2.0 - watermark_width / 2.0 y = upperRight[1] - margin['top'] - fontsize elif position == 'bottom-middle': x = lowerLeft[0] + (lowerRight[0] - lowerLeft[0]) / 2.0 - watermark_width / 2.0 y = lowerLeft[1] + margin['bottom'] canva.drawString(x, y, watermark) canva.save() packet.seek(0) return PyPDF2.PdfFileReader(packet)
def pdf_drawString(self, content, x, y, font=FONTBLOD, font_size=100, font_color=HexColor(0x000000)): ''' @function: draw string. @args: 1. content : draw content. 2. x: set x-height 3. y: set y-height ''' self.pdf_page_object.setFillColor(font_color) self.pdf_page_object.setFont(font, font_size) if content != None: self.pdf_page_object.drawString(x, y, content)
def addOutline(self): print("add outline to [%s]" % (self._outPdfName)) coutline = canvas.Canvas(self._outlinePdfName, pagesize=A4) coutline.drawString((100) * mm, (275) * mm, "Outline") posi = 0 for pi in range(len(self._texts)): text = self._texts[pi] level = self._levels[pi] if level == 2 or text == "Introduction": pos = self._pos[posi] + 1 posi += 1 lineStr = " " * 8 * (level - 1) + text + " " * 4 + str(pos) else: lineStr = " " * 8 * (level - 1) + text height = (250 - 10 * (pi + 1)) % 250 + 20 coutline.drawString((30) * mm, (height) * mm, lineStr) if height == 20: coutline.showPage() #增加网址和邮箱信息 if pi == len(self._texts) - 1: coutline.setFont('Helvetica', 9) coutline.setFillColor(HexColor(0xff8100)) pi += 1 height = (250 - 10 * (pi + 1)) % 250 + 20 lineStr = "Printed v" + self._version + " from [ " + self._urls[ 0] + " ] at " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + "." coutline.drawString((30) * mm, (height) * mm, lineStr) height -= 5 lineStr = "Visit [ https://download.csdn.net/user/ldengjie/uploads ] to get the latest version pdf" coutline.drawString((30) * mm, (height) * mm, lineStr) height -= 5 lineStr = "or mail to [email protected] to ask for printing and updating the latest version pdf." coutline.drawString((30) * mm, (height) * mm, lineStr) coutline.showPage() coutline.save() outlinePdf = PdfFileReader(open(self._outlinePdfName, 'rb'), strict=False) self._outlinePageNum = outlinePdf.getNumPages() for ci in range(self._outlinePageNum): self._outPdf.addPage(outlinePdf.getPage(ci)) os.remove(self._outlinePdfName)
def title_bar(self, title): # Build a title bar for top of page w, t, c = '100%', 2, HexColor('#404040') title = '<b>{0}</b>'.format(title) return [ HRFlowable(width=w, thickness=t, color=c, spaceAfter=2, vAlign='MIDDLE', lineCap='square'), self.pdf.new_paragraph(title, 'TitleBar'), HRFlowable(width=w, thickness=t, color=c, spaceBefore=2, vAlign='MIDDLE', lineCap='square') ]
def generate_pdf(opts, notes): outfile = os.path.join(opts.outdir, 'out.pdf') tallest_note = -1 for n in notes: lines = simpleSplit(n, opts.font, opts.font_size, opts.note_width) tallest_note = max(tallest_note, len(lines)) note_height = ((tallest_note + 1) * opts.leading) + (opts.notepadding * 2) s = ParagraphStyle('note') s.fontName = opts.font s.textColor = 'black' s.alignment = TA_LEFT s.fontSize = opts.font_size s.leading = opts.leading img_w, img_h = opts.pagesize pagesize = (img_w, img_h + note_height) c = canvas.Canvas(outfile, pagesize=pagesize) c.setStrokeColorRGB(0, 0, 0) for slide, note in slides_and_notes(opts, notes): c.setFillColor(HexColor('#ffffff')) c.rect(0, 0, img_w, img_h + note_height, fill=1) c.drawImage(slide, 0, note_height, img_w, img_h, preserveAspectRatio=True) c.line(0, note_height, img_w, note_height) if note: p = Paragraph(note.replace('\n', '<br/>'), s) p.wrapOn(c, opts.note_width, note_height) p.breakLines(opts.note_width) p.drawOn(c, opts.notepadding, note_height - opts.notepadding) c.showPage() c.save()
def __init__(self, name, color): self.name = name self.color = color if isinstance(color, str): if color == '': self.color = None elif color.startswith('#'): try: self.color = HexColor(color) except ValueError: raise Exception("Not a valid hex color: " + color) else: if color in PackProfile.colors: self.color = PackProfile.colors[color] else: raise Exception("Not a color: " + color) elif not isinstance(color, Color): raise TypeError("Invalid color parameter: ", type(color))
def draw_border(self, background_width, background_height): top = float(self.border.top) right = float(self.border.right) bottom = float(self.border.bottom) left = float(self.border.left) self.canv.setStrokeColor(self.border_color or HexColor(0x000000)) if top: self.canv.setLineWidth(top) self.canv.line(0, background_height - top / 2, background_width, background_height - top / 2) if right: self.canv.setLineWidth(right) self.canv.line(background_width - right / 2, background_height, background_width - right / 2, 0) if bottom: self.canv.setLineWidth(bottom) self.canv.line(background_width, bottom / 2, 0, bottom / 2) if left: self.canv.setLineWidth(left) self.canv.line(left / 2, 0, left / 2, background_height)
def pie_pagina(self, pdf): pdf.setFont("Helvetica", 10) now = datetime.now() pdf.drawString( 10, 50, 'CEC ESPOL, Campus Gustavo Galindo Velasco | Teléf:042269763 | 0960507588 ' ) pdf.drawString( 10, 35, u"Fecha impresión:" + str(now.day) + '/' + str(now.month) + '/' + str(now.year)) page_num = pdf.getPageNumber() text = "Pág. %s|1" % page_num pdf.drawString(500, 30, text) pdf.drawString(200, 30, u'Usuario: ') pdf.drawString(240, 30, u'Luis Eduardo Ardila Macias') pdf.setFillColor(HexColor('#3c5634')) pdf.drawString( 10, 65, "///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////" )
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 pdf_drawLine(self, x1, y1, x2, y2, line_color=HexColor(0X000000), line_width=5): ''' @function: draw line. @args: 1. line_width: the line of width 2. line_color: line color 3. x1: the left piont x coordinate 4. y1: the left piont y coordinate 5 x2: the right piont x coordinate 6. y2: the right piont y coordinate ''' self.pdf_page_object.setStrokeColor(line_color, 1) self.pdf_page_object.setLineWidth(line_width) self.pdf_page_object.line(x1, y1, x2, y2)
def draw_text(certificateGen, attributes, canvas, context): string = unicode(attributes['string']) if context: string = string.format(**context) fontSize = attributes.get('font_size', 12) leading = attributes.get('leading', 12) textColor = attributes.get('text_color', '#000000') height = attributes['height'] width = attributes['width'] x_position = attributes['x'] y_position = attributes['y'] alignment = attributes.get('alignment', 'left') alignment = _translate_reportlab_alignment(alignment) auto_scale = attributes.get('auto_scale') style_for_text = ParagraphStyle( name='text', fontSize=fontSize, leading=leading, textColor=HexColor(textColor), alignment=getattr(reportlab_enums, alignment), ) (fonttag, fontfile, text_style) = font_for_string( apply_style_to_font_list(certificateGen.fontlist, style_for_text), string ) max_height = height if auto_scale: paragraph = autoscale_text(canvas, string, fontSize, leading, height, width, text_style) y_position = y_position + ((height - paragraph.height) / 2) + (text_style.fontSize / 5) else: paragraph = Paragraph(string, text_style) width, height = paragraph.wrapOn(canvas, width, height) y_position = y_position + (max_height - paragraph.height) paragraph.drawOn(canvas, x_position, y_position)
def histogram(data, colors, alpha=0.6, bins=40): hist = [] maxx, maxy = None, None for d in data: dx = np.array(d) dmax = dx.max() if dx.shape[0] != 0 else 0.0 if maxx is None or dmax > maxx: maxx = dmax for d in data: dx = np.array(d) cnts = np.zeros(bins) for x in dx: if maxx == 0.0: idx = 0 else: idx = int(np.floor(bins * x / maxx)) if idx == bins: idx = bins - 1 cnts[idx] += 1 cnts = cnts / float(cnts.sum()) hist.append(cnts) if maxy is None or cnts.max() > maxy: maxy = cnts.max() if maxx is None: maxx, maxy = 1.0, 1.0 lpt = PGPlot.blank_plot(maxx, maxy) wid = maxx / bins stkc = HexColor("#111111") stkc.alpha = alpha for h, c in zip(hist, colors): c.alpha = alpha for ii, i in enumerate(h): if i > 0: rc = Rect(ii * wid, 0, wid, i, strokeColor=stkc, strokeWidth=1.0, fillColor=c) lpt.g.add(rc) return lpt
def add_aws_findings_by_severity_chart(): drawing = Drawing(doc.width / 2 - 18, doc.height / 2 - 45) aws, azure = get_all_violations_by_severity() rules = [aws] maxVal = max(rules[0]) if (maxVal > 1000): multiplier = 1000 step = 4 * multiplier else: multiplier = 100 step = 4 * multiplier value_step = int(ceil(maxVal / step)) * multiplier if (value_step < 10): value_step = 1 bar = VerticalBarChart() bar.x = 10 bar.y = 70 bar.height = doc.height / 4 bar.width = doc.width / 2 - 40 bar.barWidth = 2 bar.barSpacing = 0.5 bar.data = rules bar.valueAxis.valueMin = 0 bar.valueAxis.valueMax = int( maxVal * 1.5) ## graph displa twice as much as max violation bar.valueAxis.valueStep = value_step ## Convert to neartest 10 bar.categoryAxis.categoryNames = ["high", "medium", "low"] bar.barLabelFormat = '%d' bar.barLabels.nudge = 15 bar.bars[0].fillColor = HexColor("#434476") bar.bars[0].strokeColor = None bar.categoryAxis.labels.boxAnchor = 'n' drawing.add(bar) fields.append(drawing)
def create_name_file(width, height, font, size, color, first_name, last_name, text_height=''): ''' Requires: » width, height, size: integers » font, first_name, last_name: strings Returns name_watermark_pdf with chosen string over transparent canvas ''' packet = io.BytesIO() # Page size chooser if not text_height: print( f'\n{Fore.YELLOW}Please write y-axis value for first name (middle: {height/2}):', end=' ') text_height = input(' ') text_height = int(float(text_height)) # Create a new PDF with Reportlab name_watermark = canvas.Canvas(packet) name_watermark.setPageSize((width, height)) name_watermark.setFont(font, size) name_watermark.setFillColor(HexColor(color)) name_watermark.drawCentredString(width / 2, text_height, first_name) name_watermark.drawCentredString(width / 2, text_height - size, last_name) name_watermark.showPage() name_watermark.save() # Move to the beginning of the StringIO buffer packet.seek(0) name_watermark_pdf = PyPDF2.PdfFileReader(packet) return (name_watermark_pdf, text_height)
def add_top_10_objects_by_risk(): columns = [ "Risk\nScore", "Finding\nCount", "Object Name", "Object ID", "Provider", "Cloud Account" ] data = get_top_10_objects_by_risk() # Use escape to add escape characters for d in data: d[2] = Paragraph(escape(d[2]), style=styles["BodyText"]) d[3] = Paragraph(escape(d[3]), style=styles["BodyText"]) d[5] = Paragraph(escape(d[5]), style=styles["BodyText"]) data.insert(0, columns) rs_table = Table(data, [60, 45, 90, 170, 60, 80], 80, repeatRows=1) rs_table.hAlign = "CENTER" rs_table.vAlign = "MIDDLE" rs_table.setStyle( TableStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'), ('VALIGN', (0, 1), (-1, -1), 'TOP'), ('FONT', (0, 0), (-1, -1), 'Helvetica')])) data_len = len(data) for each in range(data_len): if each % 2 == 0: bg_color = colors.whitesmoke #HexColor("#DCDCDC") else: bg_color = colors.white rs_table.setStyle( TableStyle([('BACKGROUND', (0, each), (-1, each), bg_color)])) rs_table.setStyle( TableStyle([('BACKGROUND', (0, 0), (-1, 0), HexColor("#3a7c91"))])) rs_table.setStyle( TableStyle([('TEXTCOLOR', (0, 0), (-1, 0), colors.white)])) fields.append(rs_table)
def on_first_page(canvas, doc): canvas.saveState() canvas.drawImage("images/vss.jpeg", 20 * mm, HEIGHT - 200, width=6.5 * inch, height=1.06 * inch) canvas.setFont('Times-Bold', 20) canvas.drawCentredString(WIDTH / 2.0, HEIGHT - 350, "Security Overview Report") canvas.setFont('Times-Roman', 14) company = get_org_name() canvas.drawCentredString(WIDTH / 2.0, HEIGHT / 2.0 - (100), "For: " + company) canvas.setFillColor(HexColor("#696969")) canvas.setFont('Times-Roman', 12) today = datetime.date.today() time_formatted = datetime.datetime.utcnow().replace( microsecond=0).strftime("%b-%d-%Y %H:%M:%S UTC") today_formatted = today.strftime("%b-%d-%Y") canvas.drawCentredString(WIDTH / 2.0, HEIGHT / 2.0 - (120), "Generated On: " + time_formatted) canvas.restoreState()
def title_bar(self, title): # Build a title bar for top of page w, t, c = "100%", 2, HexColor("#404040") title = "<b>{0}</b>".format(title) return [ HRFlowable( width=w, thickness=t, color=c, spaceAfter=2, vAlign="MIDDLE", lineCap="square", ), self.pdf.new_paragraph(title, "TitleBar"), HRFlowable( width=w, thickness=t, color=c, spaceBefore=2, vAlign="MIDDLE", lineCap="square", ), ]
def convert_image_pdf(input_file, output_file, header_text): pdf = SimpleDocTemplate(output_file) sample_style_sheet = getSampleStyleSheet() parastyle = ParagraphStyle('header', fontSize=13, textColor=HexColor(0x3b3b3b) # fontName="Roboto" ) flowables = [ Paragraph( f'Question: {header_text}', parastyle, ), Spacer(2, height=2 * cm), Image(input_file, width=6 * inch, height=6 * inch, kind='proportional'), ] pdf.build(flowables=flowables)
def heatkey(canvas, hkX, hkY, idpt): """Draw color key for the heat map.""" canvas.setLineWidth(1) canvas.setLineCap(0) canvas.setFillColor(black) canvas.setFont(bFont, LfSize) canvas.drawString(hkX, hkY, "Nt id. %") # draw heatmap color scale canvas.setFont(rFont, NfSize) hk_list = sorted(idpt.iterkeys(), reverse=True) hk_list.insert(0, 100) hk_i = 0 hkY -= hk_boxX*1.5 canvas.drawCentredString(hkX+hk_boxX+incrN*3, hkY, str(100)) while hk_i < len(hk_list)-1: hk_boxY = (hk_list[hk_i]-hk_list[hk_i+1])*hk_u hkY -= hk_boxY canvas.setFillColor(HexColor(idpt[hk_list[hk_i+1]])) canvas.rect(hkX, hkY, hk_boxX, hk_boxY, fill=1) canvas.setFillColor(black) canvas.drawCentredString(hkX+hk_boxX+incrN*3, hkY, str(hk_list[hk_i+1])) hk_i += 1
def _create_letter_header_footer(canvas, doc): # header current_y = PAGE_HEIGHT - LETTER_HEADER_MARGIN dpaw_header_logo = ImageReader(COLOUR_DPAW_HEADER_LOGO) canvas.drawImage(dpaw_header_logo, LETTER_HEADER_MARGIN, current_y - LETTER_IMAGE_HEIGHT, width=LETTER_IMAGE_WIDTH, height=LETTER_IMAGE_HEIGHT) # footer current_x = PAGE_WIDTH - LETTER_HEADER_MARGIN current_y = LETTER_HEADER_MARGIN canvas.setFont(DEFAULT_FONTNAME, SMALL_FONTSIZE) canvas.setFillColor(HexColor(LETTER_BLUE_FONT)) canvas.drawRightString(current_x, current_y, DPAW_URL) canvas.drawRightString(current_x, current_y + SMALL_FONTSIZE, 'Phone: {} Fax: {} Email: {}'.format(DPAW_PHONE, DPAW_FAX, DPAW_EMAIL)) canvas.drawRightString(current_x, current_y + SMALL_FONTSIZE * 2, DPAW_PO_BOX) canvas.setFont(BOLD_ITALIC_FONTNAME, SMALL_FONTSIZE) canvas.drawRightString(current_x, current_y + SMALL_FONTSIZE * 3, 'Wildlife Licensing Section')
def escribirElPersonalEnLaTabla(self): for i in range(0, self.tamanioFilas): if (i + 1 != self.tamanioFilas): tamanioFuente = 12 tamanioDelTexto = self.pdf.stringWidth( self.personal[self.contPersonal].upper(), "Helvetica-Bold", tamanioFuente) # BUCLE REDEFINE EL TAMAÑO DEL TEXTO HORIZONTALMENTE while (self.redefinirTamanioHorizontalTexto( self.filasListaNombres[0], self.filasListaNombres[1], tamanioDelTexto)): tamanioFuente -= 1 tamanioDelTexto = self.pdf.stringWidth( self.personal[self.contPersonal].upper(), "Helvetica-Bold", tamanioFuente) xlista = self.hubicarHorizontalLetras( self.filasListaNombres[0], self.filasListaNombres[1], tamanioDelTexto) ylista = self.hubicarVerticalLetras( self.columnasListaNombres[i], self.columnasListaNombres[i + 1], tamanioFuente) texto = self.pdf.beginText(xlista, ylista) texto.setFillColor(HexColor(0xcc0000)) texto.setFont("Helvetica-Bold", tamanioFuente) texto.textLine(str(self.personal[self.contPersonal].upper())) self.pdf.drawText(texto) else: break if (self.contPersonal == len(self.personal) - 1): self.contPersonal = 0 else: self.contPersonal += 1
def __init__(self, labels: list, data: list, coordenadas: list, alto_ancho: list, drawing_cord=[400, 320]): self._coordenadas: List[x, y] = coordenadas self._alto_ancho: Lista[alto, ancho] = alto_ancho self._data: Lista[(value_bar_1, value_bar_2)] = data self._labels: Lista['name_bar_1', 'name_bar_2'] = labels self.chart_colors = [ HexColor("#0000e5"), HexColor("#246de3"), HexColor("#9898fa"), HexColor("#fa7f7f"), HexColor("#f54545"), HexColor("#f20f0f"), ] #Colores para las barras self._drawing = Drawing( drawing_cord[0], drawing_cord[1]) # Coordenadas para empezar a dibujar el grafico self._bc = VerticalBarChart()
from reportlab.lib import colors from reportlab.lib.colors import HexColor from reportlab.graphics.charts.piecharts import Pie from reportlab.graphics.shapes import Drawing, Rect from reportlab.lib.styles import getSampleStyleSheet from reportlab.graphics.charts.linecharts import HorizontalLineChart from reportlab.graphics.charts.barcharts import VerticalBarChart from reportlab.platypus import Spacer, Table, TableStyle, Paragraph from reportlab.platypus import PageBreak, Image from webhelpers.number import format_byte_size from baruwa.lib.outputformats import BaruwaPDFTemplate PIE_COLORS = ['#FF0000', '#ffa07a', '#deb887', '#d2691e', '#008b8b', '#006400', '#ff8c00', '#ffd700', '#f0e68c', '#000000'] PIE_CHART_COLORS = [HexColor(pie_color) for pie_color in PIE_COLORS] TABLE_STYLE = TableStyle([ ('FONT', (0, 0), (-1, -1), 'Helvetica'), ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('FONTSIZE', (0, 0), (-1, -1), 8), ('GRID', (0, 0), (-1, -1), 0.15, colors.black), ('ALIGN', (0, 0), (-1, 0), 'CENTER'), ('ALIGN', (4, 1), (-1, -1), 'CENTER'), ('ALIGN', (0, 0), (0, -1), 'CENTER'), ('VALIGN', (4, 1), (-1, -1), 'MIDDLE'), ('SPAN', (4, 1), (-1, -1)), ]) PIE_TABLE = TableStyle([ ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
c.drawImage("files/cloud.png", 500, -60, width=1.52 * 300, height=.87 * 300, mask=None) c.drawImage("files/cloud.png", -225, 100, width=1.52 * 300, height=.87 * 300, mask=None) # header 1 c.setFont('Bold', 32) c.setFillColor(HexColor(0x3f3d56)) c.drawCentredString(415, 500, "Certificate of Completion") # header 2 c.setFont('Light', 24) c.setFillColor(HexColor(0x3f3d56)) c.drawCentredString(415, 450, "This is awarded to") #Name c.setFont('Extra', 40) c.setFillColor(HexColor(0x6c63ff)) c.drawCentredString(400, 380, fullName) # lower part of certicate c.setFont('Light', 18)