def tabla(self, pdf, fech1, fech2): encabezados = ('Expediente', 'Nombre', 'Grado', 'Genero', 'Fecha de Consulta') data = [] #query2 = Alumno.objects.values('expediente','nombres','grado','genero') f1 = datetime.datetime.strptime(fech1, '%d-%m-%Y').strftime('%Y-%m-%d') f2 = datetime.datetime.strptime(fech2, '%d-%m-%Y').strftime('%Y-%m-%d') query1 = Consulta.objects.filter( fecha_consulta__range=[f1, f2]).order_by('fecha_consulta') cantidad = len(query1) #print cantidad for alum in query1: expediente = Expediente.objects.get( cod_expediente=alum.cod_expediente) #print expediente Alumnos = Alumno.objects.get(id=expediente.alumno_id) grado = str(Alumnos.grado) + "° Grado" if Alumnos.genero == 1: sexo = "Masculino" else: sexo = "Femenino" if Alumnos.grado == 10: grado = "1° Bachillerato" elif Alumnos.grado == 11: grado = "2° Bachillerato" elif Alumnos.grado == 12: grado = "3° Bachillerato" data.append([ (expediente.cod_expediente), (Alumnos.nombres), (grado), (sexo), (alum.fecha_consulta.strftime('%d-%m-%Y')), ]) total = [("", "", "", "Total", cantidad)] # pxatendidos = [cantidad] detalle_orden = Table( [encabezados] + data + total, colWidths=[3 * cm, 7 * cm, 3 * cm, 3 * cm, 4 * cm]) detalle_orden.setStyle( TableStyle([ ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 11), ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor("#1899B2")), ('ROWBACKGROUNDS', (0, 1), (-1, cantidad), [colors.white, colors.lightblue]), ])) detalle_orden.wrapOn(pdf, 800, 560) detalle_orden.drawOn(pdf, 23, 425)
def __add_genes(self): """ Adds gene elements to the drawing of the map """ for gene in self.pathway.genes: for g in gene.graphics: fillcolour = colors.HexColor(g.bgcolor) self.drawing.setStrokeColor(g.fgcolor) self.drawing.setFillColor(fillcolour) self.__add_graphics(g) if self.label_compounds: self.drawing.setFillColor(hexdarken(g.fgcolor)) self.__add_labels(g)
def test_parseColor(self): self.assertTrue(parseColor('none') == None) self.assertTrue(parseColor('currentColor') == 'currentColor') self.assertTrue( parseColor('transparent') == colors.Color(0., 0., 0., 0.)) self.assertTrue(parseColor('dimgrey') == colors.dimgrey) self.assertRaises(SVGError, parseColor, 'unknown') self.assertTrue(parseColor('#fab') == colors.HexColor('#ffaabb')) self.assertRaises(SVGError, parseColor, '#fa') self.assertTrue(parseColor('#1a01FF') == colors.HexColor('#1a01FF')) self.assertRaises(SVGError, parseColor, '#1a01F') self.assertTrue( parseColor('rgb(128,9,255)') == colors.Color( 128 / 255., 9 / 255., 255 / 255.)) self.assertTrue( parseColor('rgb(128, 9, 255)') == colors.Color( 128 / 255., 9 / 255., 255 / 255.)) self.assertTrue( parseColor('Rgb(128,9,255)') == colors.Color( 128 / 255., 9 / 255., 255 / 255.)) self.assertRaises(SVGError, parseColor, 'rgb(128,9,256)') self.assertTrue( parseColor('rgb(40%,90%,8%)') == colors.Color( 40 / 100., 90 / 100., 8 / 100.)) self.assertTrue( parseColor('rgb(40%, 90%, 8%)') == colors.Color( 40 / 100., 90 / 100., 8 / 100.)) self.assertTrue( parseColor('rgB(40%,90%,8%)') == colors.Color( 40 / 100., 90 / 100., 8 / 100.)) self.assertRaises(SVGError, parseColor, 'rgb(40%,101%,8%)') self.assertRaises(SVGError, parseColor, '') self.assertRaises(SVGError, parseColor, '1a01FF') self.assertRaises(SVGError, parseColor, 'rgb(40%,90%,8%')
def add_footer(self, qr_image, uuID, instructions): # output QR-code: self.qr_size = Units.pixel_to_point(qr_image.size[0]) x = self.origin_x + self.inner_width - self.qr_size #align right self.canvas.drawInlineImage(qr_image, x, self.origin_y, self.qr_size, self.qr_size) # output Print ID: items = [] style = ParagraphStyle(name='Helvetica', fontName='Helvetica', fontSize=10) items.append(Paragraph('Print ID: ' + uuID, style)) frame = Frame(x, self.origin_y-self.qr_size, self.inner_width-self.qr_size, self.qr_size, showBoundary=0, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0) frame.addFromList(items, self.canvas) # output default instructions: link_text = "When you're done drawing on the map, scan or photograph it and \ submit it to our website: http://localground.org/upload, or \ email it to [email protected]." items = [] style = ParagraphStyle( name='Helvetica', fontName='Helvetica', fontSize=8, backColor=colors.HexColor(0xEEEEEE), borderColor=colors.HexColor(0xEEEEEE), leftIndent=0, rightIndent=0, spaceBefore=5, spaceAfter=5, borderWidth=5) items.append(Paragraph(link_text, style)) padding_x, padding_y = -4, 12 width, height = self.inner_width - self.qr_size, self.qr_size frame = Frame(self.origin_x+padding_x, self.origin_y+3, width, height, showBoundary=0) frame.addFromList(items, self.canvas) # output custom instructions: items = [] style = ParagraphStyle(name='Helvetica', fontName='Helvetica', fontSize=10) items.append(Paragraph(instructions, style)) frame = Frame(self.origin_x+padding_x-2, self.origin_y-padding_y, width, height-15, showBoundary=0) frame.addFromList(items, self.canvas)
def tstyle(self, e): area = e.get('area', '0:-1') topleft, bottomright = (list(int(q) for q in p.split(',')) for p in area.split(':')) top = topleft[0] left = topleft[-1] bottom = bottomright[0] right = bottomright[-1] cells = [(top, left), (bottom, right)] tstyle_dict = dict(e.attrib) if 'area' in tstyle_dict: del tstyle_dict['area'] if 'border' in tstyle_dict: border = tstyle_dict['border'] tstyle_dict.update({ 'border-left': border, 'border-right': border, 'border-top': border, 'border-bottom': border }) del tstyle_dict['border'] if 'padding' in tstyle_dict: padding = tstyle_dict['padding'] tstyle_dict.update({ 'padding-left': padding, 'padding-right': padding, 'padding-top': padding, 'padding-bottom': padding }) del tstyle_dict['padding'] for key in tstyle_dict.keys(): value = tstyle_dict[key] desc = CSS_DICT.get(key, key.upper()) params = value.split(',') for i in xrange(len(params)): param = params[i].strip() if param[0] == '#': params[i] = colors.HexColor(eval('0x' + param[1:])) else: try: floatval = toLength(param) params[i] = floatval except ValueError: params[i] = param.upper() yield [desc] + cells + params
def make_pham_genome(self, pham_genes, seq_length): """ Creates PDF Graph of the phage genome with the pham number and color labeling each gene. {Phage}PhamsGraph.pdf """ pham_colors = get_pham_colors(self.db) gd_diagram = GenomeDiagram.Diagram(self.name) gd_track = gd_diagram.new_track(1, name=self.name, greytrack=1) gd_pham_set = gd_track.new_set() print "making genome page" for gene_num in pham_genes: pham = pham_genes[gene_num][1] gene = pham_genes[gene_num][0] print pham, gene.id if pham == None: pham_no = "None" pham_color = 'Black' else: pham_no = pham pham_color = colors.HexColor(pham_colors[pham_no]) if gene.annotations['orientation'] == 'F': gene_location = FeatureLocation(gene.annotations['start'], gene.annotations['stop']) strand = 1 else: strand = -1 gene_location = FeatureLocation(gene.annotations['stop'], gene.annotations['start']) gene_feature = SeqFeature(gene_location, strand=strand) gene_number = get_gene_number(gene.id) # label the gene with the gene number gd_pham_set.add_feature(gene_feature, name=str(gene_number), label=True, label_size=6, label_angle=75) # label gene with pham color and name gd_pham_set.add_feature(gene_feature, color=pham_color, name=pham_no, label=True, label_position='middle') gd_diagram.draw(format='linear', orientation='portrait', pagesize=letter, fragments=8, start=0, end=seq_length) gd_diagram.write( '%sPhamsGraph.pdf' % (self.intermediate_dir + self.name), "PDF")
def __init__(self): self.s = MySheet() self._s = self.s.getSampleStyleSheet() self.doc = { "leftMargin": None, "rightMargin": None, "topMargin": None, "bottomMargin": None, } self.headers = { H1: self._s["Heading1"], H2: self._s["Heading2"], H3: self._s["Heading3"], H4: self._s["Heading4"], H5: self._s["Heading5"], H6: self._s["Heading6"], T1: self._s["Title"], T2: self._s["Title2"], T3: self._s["Title3"], T4: self._s["Title4"], } self.paragraph = self._s["Normal"] self.spacer_height = 0.25 * inch self.table_style = [ ("ALIGN", (0, 0), (-1, -1), "LEFT"), ("VALIGN", (0, 0), (-1, -1), "TOP"), ("FONT", (0, 0), (-1, 0), "Helvetica-Bold"), ("LINEBELOW", (0, 0), (-1, 0), 1, colors.black), ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#C0C0C0")), ( "ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#E0E0E0")], ), ]
def get_default_style(cls): return TableStyle([ ('FONTNAME', (0, 0), (-1, -1), 'msyh'), # 字体 ('TEXTCOLOR', (0, 0), (-1, 0), colors.HexColor("#0449A6")), #标题文本颜色(报表名称) ('FONTSIZE', (0, 0), (-1, 1), 7), # 标题文本字体大小 (报表名称) ('TEXTCOLOR', (0, 1), (-1, 1), colors.black), #标题文本颜色(报表名称) ('SPAN', (0, 0), (-1, 0)), #合并第一行所有列 ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#E6F3FF')), #标题背景颜色 ('FONTSIZE', (0, 1), (-1, -1), 5), # 列表头字体大小 ('BACKGROUND', (0, 1), (-1, 1), colors.HexColor("#F6F6F6")), #列表头背景颜色 ('ALIGN', (0, 1), (-1, 1), 'LEFT'), # 列表头对齐方式 ("LEFTPADDING", (0, 0), (-1, -1), 1), #表格左边内部边距为1 ("RIGHTPADDING", (0, 0), (-1, -1), 1), #表格右边内部边距为1 ("BOTTOMPADDING", (0, 0), (-1, -1), 1), ('ALIGN', (0, 2), (-1, -1), 'LEFT'), # 对齐 ('TEXTCOLOR', (0, 2), (-1, -1), colors.black), # 设置表格内文字颜色 ('GRID', (0, 0), (-1, -1), 0.8, colors.HexColor("#C9C9C9")), # 设置表格框线为灰色,线宽为0.5 ])
def _populate_report(self): from itertools import izip row_no = 0 report_contents = [] extra_styles = [] empty_column = " " for sect1, sect2 in self.data: report_contents.append([sect1.display_title(), empty_column, empty_column]) row_no += 1 extra_styles.append(('BACKGROUND', (0, row_no), (2, row_no), colors.HexColor('#ffeb94'))) extra_styles.append(('LINEBELOW', (0, row_no), (2, row_no), 1, colors.HexColor('#1f8dd6'))) extra_styles.append(('FONT', (0, row_no), (1, row_no), 'Helvetica-Bold')) for comm1_row, comm2_row in izip(sect1.data, sect2.data): row_no += 1 if row_no % 2 != 0: extra_styles.append(('BACKGROUND', (0, row_no), (-1, row_no), colors.HexColor('#e1f2fa'))) value1 = Paragraph(comm1_row.display_value(), self.p_style['value']) value2 = Paragraph(comm2_row.display_value(), self.p_style['value']) row_data = [comm1_row.label, value1, value2] report_contents.append(row_data) return (report_contents, extra_styles)
class DefaultTheme(object): _s = getSampleStyleSheet() filename = 'Invoice' doc = { 'leftMargin': None, 'rightMargin': None, 'topMargin': None, 'bottomMargin': None } headers = { H1: _s['Heading1'], H2: _s['Heading2'], H3: _s['Heading3'] } paragraph = _s['Normal'] spacer_height = 0.25 * inch table_style = [ ('ALIGN', (0,0), (-1,-1), 'LEFT'), ('VALIGN', (0,0), (-1,-1), 'TOP'), ('FONT', (0,0), (-1,0), 'Helvetica-Bold'), ('LINEBELOW', (0,0), (-1,0), 1, colors.black), ('BACKGROUND', (0,0), (-1,0), colors.HexColor('#C0C0C0')), ('ROWBACKGROUNDS', (0,1), (-1, -1), [colors.white, colors.HexColor('#E0E0E0')]) ] @classmethod def doc_template_args(cls): return dict([(k, v) for k, v in cls.doc.items() if v is not None]) @classmethod def header_for_level(cls, level): return cls.headers[level] def __new__(cls, *args, **kwargs): raise TypeError("Theme classes may not be instantiated.")
def draw_rectangle(report, attributes, line_style, line_width, fore_color, background_color, fill): """ Draw a rectangle on report_info. :param attributes: :param line_style: :param line_width: :param fore_color: :param background_color: :param fill: """ # global report_info report['canvas'].saveState() report['canvas'].setDash(line_style_dict.get(line_style, (1))) report['canvas'].setLineWidth(line_width) if fore_color is not None: report['canvas'].setStrokeColor(colors.HexColor(fore_color)) if background_color is not None: report['canvas'].setFillColor(colors.HexColor(background_color)) if attributes.get('radius') is None: report['canvas'].rect(attributes['x'], report['cur_y'] - attributes['y'] - attributes['height'], attributes['width'], attributes['height'], fill=fill) else: report['canvas'].roundRect(attributes['x'], report['cur_y'] - attributes['y'] - attributes['height'], attributes['width'], attributes['height'], radius=attributes.get('radius'), fill=fill) report['canvas'].restoreState()
def get(self, request, *args, **kwargs): response = HttpResponse(content_type='application/pdf') pdf_name = "clientes.pdf" # llamado clientes # la linea 26 es por si deseas descargar el pdf a tu computadora # response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name buff = BytesIO() doc = SimpleDocTemplate(buff, pagesize=letter, rightMargin=40, leftMargin=40, topMargin=60, bottomMargin=18, ) clientes = [] styles = getSampleStyleSheet() header = Paragraph("Inventario", styles['Heading2']) clientes.append(header) encabezados = ('Cant.', 'Producto', 'Marca') #Creamos una lista de tuplas que van a contener a las personas query =DetallePedido.objects.all().exclude(cantidad=0) existencias = [(detalle.cantidad, detalle.producto.nombre, detalle.producto.marca.nombre) for detalle in query] t = Table([encabezados] + existencias, colWidths=[60, 160, 160]) t.setStyle(TableStyle( [ ('GRID', (0, 0), (3, -1), 1, colors.black ), ('LINEBELOW', (0, 0), (-1, 0), 2, colors.HexColor('#7E7E7E') ), ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#CADF89') ) ] )) clientes.append(t) doc.build(clientes) response.write(buff.getvalue()) buff.close() return response
def convertColor(self, svgAttr): "Convert string to a RL color object." # fix it: most likely all "web colors" are allowed predefined = "aqua black blue fuchsia gray green lime maroon navy " predefined = predefined + "olive orange purple red silver teal white yellow " predefined = predefined + "lawngreen indianred aquamarine lightgreen brown" # This needs also to lookup values like "url(#SomeName)"... text = svgAttr if not text or text == "none": return None if text in predefined.split(): return self.color_converter(getattr(colors, text)) elif text == "currentColor": return "currentColor" elif len(text) == 7 and text[0] == '#': return self.color_converter(colors.HexColor(text)) elif len(text) == 4 and text[0] == '#': return self.color_converter( colors.HexColor('#' + 2 * text[1] + 2 * text[2] + 2 * text[3])) elif text.startswith('rgb') and '%' not in text: t = text[3:].strip('()') tup = [h[2:] for h in [hex(int(num)) for num in t.split(',')]] tup = [(2 - len(h)) * '0' + h for h in tup] col = "#%s%s%s" % tuple(tup) return self.color_converter(colors.HexColor(col)) elif text.startswith('rgb') and '%' in text: t = text[3:].replace('%', '').strip('()') tup = (float(val) / 100.0 for val in t.split(',')) return self.color_converter(colors.Color(*tup)) logger.warn("Can't handle color: %s" % text) return None
def get_styles(): #Create all different font styles styles = getSampleStyleSheet() styles.add( ParagraphStyle(name='header_style', fontName='DejaVuSans', fontSize=11, textColor=colors.HexColor('#FFFFFF'))) styles['header_style'].alignment = TA_CENTER styles.add( ParagraphStyle(name='category_style', fontName='DejaVuSans', fontSize=20, leftIndent=13, textColor=colors.HexColor('#FFFFFF'))) styles.add( ParagraphStyle( name='Breadpointlist_style', fontName='DejaVuSans', fontSize=7, leading=12, wordWrap='LTR', )) styles.add( ParagraphStyle(name='title_style', fontName='DejaVuSans', fontSize=30, textColor=colors.HexColor("#1ca4bc"))) styles.add( ParagraphStyle(name='subtitle1_style', fontName='DejaVuSans', fontSize=12)) styles.add( ParagraphStyle(name='subtitle2_style', fontName='DejaVuSans', fontSize=11)) return styles
def drawFirstPage(self, canvas, doc): canvas.saveState() self.drawBackgroundAndFooter(canvas, doc) titleStyle = self._styles["Title"] titleStyle.textColor = colors.HexColor(0x820031) titreTxt = self._pdfdata.titre titre = Paragraph('<b><i>%s</i></b>' % titreTxt, titleStyle) w, h = titre.wrapOn(canvas, 145 * mm, 25 * mm) titre.drawOn(canvas, (600 / 2 - w / 2), 280 * mm) if self._pdftype == 'experience': self.drawExperienceRightColumn(canvas, doc) else: self.drawInstitutionRightColumn(canvas, doc) # 210 × 297 canvas.restoreState()
def make_pham_genome(phage_genes, phage_name, length, file_path): file_name = os.path.join(file_path, '%sPhamsGraph.pdf' % phage_name) if check_file(file_name): return pham_colors = phams.get_pham_colors() gd_diagram = GenomeDiagram.Diagram(phage_name) gd_track = gd_diagram.new_track(1, name=phage_name, greytrack=1) gd_pham_set = gd_track.new_set() print "making genome page" for gene_id in sorted(phage_genes.iterkeys()): phage_gene = phage_genes[gene_id] pham_no = phage_gene["pham_no"] gene = phage_gene["gene"] print pham_no, gene.gene_id if pham_no is None: pham_no = "None" pham_color = 'Black' else: pham_color = colors.HexColor(pham_colors[str(pham_no)]) if gene.orientation == 'F': gene_location = FeatureLocation(gene.start, gene.stop) strand = 1 else: strand = -1 gene_location = FeatureLocation(gene.stop, gene.start) gene_feature = SeqFeature(gene_location, strand=strand) gene_number = phamgene.get_gene_number(gene.gene_id) # label the gene with the gene number gd_pham_set.add_feature(gene_feature, name=str(gene_number), label=True, label_size=6, label_angle=75) # label gene with pham color and name gd_pham_set.add_feature(gene_feature, color=pham_color, name=str(pham_no), label=True, label_position='middle') print type(length), length gd_diagram.draw(format='linear', orientation='portrait', pagesize=reportlab.lib.pagesizes.letter, fragments=8, start=0, end=length) gd_diagram.write(file_name, "PDF")
def __init__(self, archivo="etiquetas_cr.pdf"): # self.cliente = encabezado[0] # self.proyecto = encabezado[1] self.archivo = archivo self.verde_inmetar = colors.HexColor("#23C32D") self.colorqr = "green" ancho_letter, largo_letter = letter self.tamaño = ancho_letter, largo_letter / 6 self.doc = SimpleDocTemplate(self.archivo, pagesize=self.tamaño, rightMargin=3, leftMargin=3, topMargin=13, bottomMargin=10) self.elem = []
def graph(self, nodeid=None): "Generate graphical system status" totals = DailyTotals(Session, c.user) if nodeid: server = self._get_server(nodeid) if not server: abort(404) baruwa_totals = totals.get(hostname=server.hostname) else: baruwa_totals = totals.get() if not baruwa_totals.total: abort(404) piedata = [] labels = [] for attr in ['clean', 'highspam', 'lowspam', 'virii', 'infected']: value = getattr(baruwa_totals, attr) or 0 piedata.append(value) if baruwa_totals.total > 0: labels.append( ("%.1f%% %s" % ((1.0 * value / baruwa_totals.total) * 100, attr))) else: labels.append('0%') pie = PieChart(350, 264) pie.chart.labels = labels pie.chart.data = piedata pie.chart.width = 180 pie.chart.height = 180 pie.chart.x = 90 pie.chart.y = 30 pie.chart.slices.strokeWidth = 1 pie.chart.slices.strokeColor = colors.black pie.chart.slices[0].fillColor = PIE_CHART_COLORS[5] pie.chart.slices[1].fillColor = PIE_CHART_COLORS[0] pie.chart.slices[2].fillColor = PIE_CHART_COLORS[1] pie.chart.slices[3].fillColor = PIE_CHART_COLORS[9] pie.chart.slices[4].fillColor = PIE_CHART_COLORS[3] self.imgfile = StringIO() renderPM.drawToFile(pie, self.imgfile, 'PNG', bg=colors.HexColor('#ffffff')) response.content_type = 'image/png' response.headers['Cache-Control'] = 'max-age=0' return self.imgfile.getvalue()
def dump_reg_list_info(self): t=Table(table_data_reg_list, colWidths=[120,120,200], splitByRow=1, repeatRows=1, style=[ ('GRID',(0,0),(-1,-1),0.5,doc_color), ('LINEABOVE',(0,1),(-1,1),1,colors.black), ('BACKGROUND',(0,0),(-1,0),colors.HexColor(0xD9D9D9)) ]) elements.append(t) #elements.append(Spacer(1, 1*inch)) # Page break elements.append(PageBreak())
def test_0(self): "Test color attribute conversion." mapping = ( ("red", colors.red), ("#ff0000", colors.red), ("#f00", colors.red), ("rgb(100%,0.5%,0.5%)", colors.Color(1, 0.005, 0.005, 1)), ("rgb(255, 0, 0)", colors.red), ("fuchsia", colors.Color(1, 0, 1, 1)), ("slategrey", colors.HexColor(0x708090)), ("transparent", colors.Color(0, 0, 0, 0)), ("whatever", None), ) ac = svglib.Svg2RlgAttributeConverter() failed = _testit(ac.convertColor, mapping) assert len(failed) == 0
def draw_label(label, width, height, obj): # Pick a background colour. colour = random.choice(colours) # And a style. style = random.choice(('solid', 'stripes', 'hatch')) # Draw a solid background. if style == 'solid': r = shapes.Rect(0, 0, width, height) r.fillColor = colour r.strokeColor = None label.add(r) # Both stripes and hatches need vertical stripes. if style in ('stripes', 'hatch'): g = Grid() g.width = width g.height = height g.delta = width / 14.0 # The width of the stripes. g.delta0 = random.random() * (width / 14.0 ) # Offset of the start of the stripe. g.fillColor = None g.strokeColor = None g.orientation = 'vertical' g.stripeColors = (colors.HexColor(0xFFFFFF), colour) label.add(g) # Draw the horizontal stripes of any hatching. # Note the empty parts need to be 'coloured' transparent to avoid # hiding the vertical stripes. if style == 'hatch': g2 = Grid() g2.width = width g2.height = height g2.delta = height / 4.0 g2.delta0 = random.random() * (height / 4.0) g2.fillColor = None g2.strokeColor = None g2.orientation = 'horizontal' g2.stripeColors = (colors.transparent, colour) label.add(g2) # Print the label value as a string. label.add(shapes.String(2, 2, str(obj), fontName="Helvetica", fontSize=40))
def pdf_response(self): """ returns pdf HttpResponse. """ response = HttpResponse(mimetype="application/pdf") response['Content-Disposition'] = 'filename=' + self.filename + '.pdf' doc = SimpleDocTemplate(response, topMargin=inch / 2, bottomMargin=inch / 2, leftMargin=inch / 2, rightMargin=inch / 2) elements = [] data = [] for i in range(self.table.no_of_rows()): q = [] for j in range(self.table.no_of_columns()): q.append(self.table.cell(i, j)) data.append(q) header = [] if self.date: header.append(['Date : ' + self.date]) for heading in self.headings: header.append([heading]) header.append(['']) er = len(header) width, height = defaultPageSize width = width - inch t = pdfTable(header + data, [ int(width * self.table.col_width_percent(i) / 100.) for i in range(self.table.no_of_columns()) ]) style_list = [] for i in range(len(header)): style_list.append(('SPAN', (0, i), (-1, i))) style_list += [ ('ALIGN', (0, 1 if self.date else 0), (-1, er - 1), 'CENTER'), ('FONT', (0, 0), (-1, er), 'Helvetica-Bold'), ('INNERGRID', (0, er), (-1, -1), 1, colors.black), ('BOX', (0, er), (-1, -1), 1, colors.black), ('BACKGROUND', (0, er), (-1, -1), colors.HexColor('#efefef')) ] t.setStyle(TableStyle(style_list)) elements.append(t) doc.build(elements) return response
def __init__(self, experimentID): self.width, self.height = letter self.experimentid = experimentID ProteinID = "entrezGeneID_Human_1_24_2015.mat" path = BASE_DIR + "/data/" + ProteinID proteinid = loadmat(path, squeeze_me=False, mat_dtype=True) self._proteinid = proteinid['proteinid'] self.gfpid = GFP.objects.filter(experiment_id=experimentID) self.map = {} mapper = "Mapper_Symbol_Entrez.pkl" path = BASE_DIR + "/data/Mappers/" + mapper handle = open(path, 'r') symbolsentrez = pickle.load(handle) handle.close() self.style = ParagraphStyle('Body', fontName="Helvetica", fontSize=9, spaceBefore=24) self.tablestyle = TableStyle([ ('BACKGROUND', (0, 0), (-1, -1), colors.HexColor('#EDEDED')), ('FONTSIZE', (0, 0), (-1, -1), 7), ]) i = 0 for m in symbolsentrez.keys(): self.map[int(symbolsentrez[m])] = m self.types = {} self.types["Co"] = "co-expression" self.types["PPI"] = "protein-protein interaction" self.types["SM"] = "semantic similarity" self.algorithms = {} self.algorithms["NV"] = "neighbor voting" self.algorithms["LR"] = "logistic regression" self.algorithms["RWR"] = "random walk with restart" self.algorithms["SGD"] = "support vector machines" self.algorithms["PA"] = "passive aggressive" self.algorithms["RP"] = "rankprop"
def cartesiano(datos): alto = datos["alto"] ancho = datos["ancho"] data = datos["data"] colores = datos["colores"] labels = datos["labels"] menor = datos["rango"][0] mayor = datos["rango"][1] grafico = ScatterPlot() grafico.x = 20 grafico.y = 40 grafico.width = ancho grafico.height = alto grafico.data = data grafico.joinedLines = 1 grafico.lineLabelFormat = None grafico.outerBorderOn = 0 grafico.outerBorderColor = None grafico.background = None for i in range(len(colores)): color = colors.HexColor(colores[i]) grafico.lines[i].strokeColor = color grafico.lines[i].symbol.strokeColor = color grafico.lines[i].symbol.fillColor = color grafico.lines[i].symbol.strokeWidth = 0 grafico.xLabel=labels["x"] grafico.xValueAxis.labels.fontSize = FONTSIZE grafico.xValueAxis.labelTextFormat = lambda x: " Hace\n%d días" % abs(x) grafico.xValueAxis.valueStep = 10 grafico.xValueAxis.labels.dy = -5 grafico.xValueAxis.strokeColor = colors.black grafico.xValueAxis.strokeWidth = 1 grafico.xValueAxis.tickDown = 5 grafico.yLabel=labels["y"] grafico.yValueAxis.labels.fontSize = FONTSIZE grafico.yValueAxis.labelTextFormat = "%d" grafico.yValueAxis.labels.dx = -5 grafico.yValueAxis.strokeColor = colors.black grafico.yValueAxis.strokeWidth = 1 grafico.yValueAxis.tickLeft = 5 grafico.yValueAxis.valueStep = 1 grafico.yValueAxis.valueMin = menor grafico.yValueAxis.valueMax = mayor return crearDrawing(grafico)
def parse_paragraph_style(self, raw_style): if '=' in raw_style: # define name, definition = (i.strip() for i in raw_style.split('=', 1)) if '+' in definition: source_name, definition = (i.strip() for i in definition.split('+', 1)) else: source_name = None def_dict = eval(definition) new_dict = {} for k in def_dict.keys(): v = def_dict[k] nk = CSS_DICT.get(k, k) # translate v v = CSS_DICT.get(v, v) if nk == 'fontSize' or nk == 'leading': v = toLength(v) elif nk == 'color': v = colors.HexColor(eval('0x' + v[1:])) new_dict[nk] = v if 'leading' not in new_dict and 'fontSize' in new_dict: new_dict['leading'] = new_dict['fontSize'] * 1.5 # + 2.0 if source_name is not None: source_dict = self.styles[source_name].__dict__.copy() source_dict.update(new_dict) new_dict = source_dict new_dict.update({'name': name}) if name in self.styles: self.styles[name].__dict__.update(new_dict) else: self.styles.add(ParagraphStyle(**new_dict)) else: name = raw_style.strip() if name == 'end' or name == '': self.style_stack.pop() elif name in self.styles: style = self.styles[name] self.style_stack.append(style)
def __init__(self, encabezado, archivo="etiquetas_es.pdf"): # self.lista = lista self.cliente = encabezado[0] self.proyecto = encabezado[1] self.archivo = archivo self.verde_inmetar = colors.HexColor("#23C32D") # self.verde_inmetar = colors.black self.colorqr = "green" ancho_letter, largo_letter = letter self.tamaño = ancho_letter, largo_letter / 4 self.doc = SimpleDocTemplate(self.archivo, pagesize=self.tamaño, rightMargin=5, leftMargin=5, topMargin=2, bottomMargin=2) self.elem = []
def panel_drawing(name, hdim, vdim, scale=DEFAULT_PANEL_SCALE, padding=6, material=None, thickness=None): """Create an individual panel Drawing of the named panel.""" # Calculate the width and height of the panel rectangle in points. hdim_scaled = hdim * inch * scale vdim_scaled = vdim * inch * scale # We might need 36 pts of space on left of rectangle to be safe, # for a long vdim_str, like 23 13/16-". result = Drawing(hdim_scaled + 2 * padding + 36, vdim_scaled + 2 * padding + 14 + 4 + 10) # Coordinates of the lower left corner of the rectangle rx = padding + 36 ry = padding + 14 # For the background color, use a little less red variation of # linen (0xfaf0e6). background_clr = colors.HexColor(0xf8f0e6) result.add( Rect(rx, ry, hdim_scaled, vdim_scaled, fillColor=background_clr, strokeWidth=0.75)) # Add the panel name to the top of the drawing. result.add( String(rx + hdim_scaled / 2, ry + vdim_scaled + 4, name, textAnchor='middle')) boundsln_len = 10 result.add(hdimarrow_str(hdim, scale, rx, ry - 9, 0.67, boundsln_len)) result.add(vdimarrow_str(vdim, scale, rx - 9, ry, 0.67, boundsln_len)) if material is not None and thickness is not None: thick_str, matl_str = matl_thick_strs(material, thickness, rx, ry, hdim_scaled, vdim_scaled) result.add(thick_str) result.add(matl_str) return result
def dump_field_list_info(self): t=Table(table_data_field_list, colWidths=[45,80,50,83,192], splitByRow=1, repeatRows=1, style=[ ('GRID',(0,0),(-1,-1),0.5,doc_color), ('LINEABOVE',(0,1),(-1,1),1,colors.black), ('BACKGROUND',(0,0),(-1,0),colors.HexColor(0xD9D9D9)), ('ALIGN',(0,0),(-1,-1),'LEFT'), ('VALIGN',(0,1),(-1,-1),'MIDDLE'), ]) elements.append(t) #elements.append(Spacer(1, 1*inch)) # Page break elements.append(PageBreak())
def makePieChart(self, context, width, height, data, backColors): content=[] drawing = Drawing(width, height) pie=Pie() pie.data = data pie.x = 0 pie.y = 0 pie.width = width pie.height = height if len(data) == len(backColors): for i in range(len(data)) : pie.slices[i].fillColor = colors.HexColor(backColors[i]) drawing.add(pie) content.append( drawing ) return content
def __add_compounds(self): """Adds compound elements to the drawing of the map (PRIVATE).""" for compound in self.pathway.compounds: for g in compound.graphics: # Modify transparency of compounds that don't participate # in reactions fillcolor = colors.HexColor(g.bgcolor) if not compound.is_reactant: fillcolor.alpha *= self.non_reactant_transparency self.drawing.setStrokeColor(g.fgcolor) self.drawing.setFillColor(fillcolor) self.__add_graphics(g) if self.label_compounds: if not compound.is_reactant: t = 0.3 else: t = 1 self.drawing.setFillColor(colors.Color(0.2, 0.2, 0.2, t)) self.__add_labels(g)