我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用reportlab.platypus.Paragraph()。
def add_header(self): # # aiddata logo # logo = self.assets_dir + '/templates/aid_data.png' # im = Image(logo, 2.188*inch, 0.5*inch) # im.hAlign = 'LEFT' # self.Story.append(im) # self.Story.append(Spacer(1, 0.25*inch)) # title ptext = '<font size=20>AidData GeoQuery Request Documentation</font>' self.Story.append(Paragraph(ptext, self.styles['Center'])) # report generation info
def draw_paragraph(self, text, max_width, max_height, style): if not text: text = '' if not isinstance(text, str): text = str(text) text = text.strip(string.whitespace) text = text.replace('\n', "<br/>") p = Paragraph(text, style) used_width, used_height = p.wrap(max_width, max_height) line_widths = p.getActualLineWidths0() number_of_lines = len(line_widths) if number_of_lines > 1: actual_width = used_width elif number_of_lines == 1: actual_width = min(line_widths) used_width, used_height = p.wrap(actual_width + 0.1, max_height) else: return 0, 0 p.drawOn(self.canvas, self.cursor.x, self.cursor.y - used_height) return used_width, used_height
def tabla_otros(self): orden = self.orden_compra p = ParagraphStyle('parrafos', alignment = TA_CENTER, fontSize = 8, fontName="Times-Roman") sub_total = Paragraph(u"SUBTOTAL: ",p) igv = Paragraph(u"IGV: ",p) total = Paragraph(u"TOTAL: ",p) datos_otros = [[ Paragraph(u"LUGAR DE ENTREGA",p), Paragraph(u"PLAZO DE ENTREGA",p), Paragraph(u"FORMA DE PAGO",p),sub_total,orden.subtotal], [Paragraph(EMPRESA.direccion(),p),Paragraph(u"INMEDIATA",p),Paragraph(orden.forma_pago.descripcion,p),igv,str(orden.igv)], ['','','',total,str(orden.total)], ] tabla_otros = Table(datos_otros,colWidths=[5.5 * cm, 5 * cm, 5 * cm, 2 * cm, 2.5 * cm]) tabla_otros.setStyle(TableStyle( [ ('GRID', (0, 0), (2, 2), 1, colors.black), ('SPAN',(0,1),(0,2)), ('SPAN',(1,1),(1,2)), ('SPAN',(2,1),(2,2)), ('GRID', (4, 0), (4, 2), 1, colors.black), ('VALIGN',(0,1),(2,1),'MIDDLE'), ] )) return tabla_otros
def tabla_observaciones(self): orden = self.orden_compra p = ParagraphStyle('parrafos', alignment = TA_JUSTIFY, fontSize = 8, fontName="Times-Roman") obs=Paragraph("OBSERVACIONES: "+orden.observaciones,p) observaciones = [[obs]] tabla_observaciones = Table(observaciones,colWidths=[20 * cm], rowHeights=1.8 * cm) tabla_observaciones.setStyle(TableStyle( [ ('GRID', (0, 0), (0, 2), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 8), ('ALIGN',(0,0),(-1,-1),'LEFT'), ('VALIGN',(0,0),(-1,-1),'TOP'), ] )) return tabla_observaciones
def cuadro_observaciones(self,pdf,y,orden): p = ParagraphStyle('parrafos') p.alignment = TA_JUSTIFY p.fontSize = 10 p.fontName="Times-Roman" obs=Paragraph("Observaciones: "+orden.observaciones,p) observaciones = [[obs]] tabla_observaciones = Table(observaciones,colWidths=[18.50 * cm], rowHeights=1.8 * cm) tabla_observaciones.setStyle(TableStyle( [ ('GRID', (0, 0), (0, 2), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 8), ('ALIGN',(0,0),(-1,-1),'LEFT'), ('VALIGN',(0,0),(-1,-1),'TOP'), ] )) tabla_observaciones.wrapOn(pdf, 800, 600) tabla_observaciones.drawOn(pdf, 40,y-58)
def tabla_encabezado(self,valorizado): sp = ParagraphStyle('parrafos', alignment=TA_CENTER, fontSize=14, fontName="Times-Roman") try: archivo_imagen = os.path.join(settings.MEDIA_ROOT, str(EMPRESA.logo)) imagen = Image(archivo_imagen, width=90, height=50, hAlign='LEFT') except: imagen = Paragraph(u"LOGO", sp) if valorizado: titulo = Paragraph(u"REGISTRO DEL INVENTARIO PERMANENTE VALORIZADO", sp) else: titulo = Paragraph(u"REGISTRO DEL INVENTARIO PERMANENTE EN UNIDADES FÍSICAS", sp) encabezado = [[imagen,titulo]] tabla_encabezado = Table(encabezado, colWidths=[2 * cm, 23 * cm]) return tabla_encabezado
def rightBottom(self, e): story = [] if e is None: return story parts = [] if 'solution' in e: story.append( reportlab.platypus.Preformatted( wrapParagraph( e['solution'], 50), self.style_pre)) if 'keywords' in e: parts.append('<i>' + ', '.join(e['keywords']) + '</i>') if 'comments' in e: parts.append('<br/>'.join(e['comments'])) story.append(reportlab.platypus.Paragraph( '<font face="%s" size=%d>%s</font>' % ( FONT_FAMILY, FONT_SIZE['rightpane'], '<br/><br/>'.join(parts) ), self.style )) return story
def test_11_drawing(self): from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph from reportlab.pdfbase import pdfmetrics from reportlab.graphics.shapes import Drawing, Rect from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) stylesheet = getSampleStyleSheet() elements = [] doc = SimpleDocTemplate("demo.pdf") elements.append(Paragraph('<font name="chsFont">JY.zenist.song - ??</font>', stylesheet['Title'])) elements.append(Spacer(1,12)) d = Drawing(400,200) d.add(Rect(50,50,300,100, fillColor=colors.yellow)) elements.append(d) doc.build(elements)
def generate_pdf_report(self, report_id, recipient): # PREPARE PDF report_buffer = BytesIO() doc = SimpleDocTemplate( report_buffer, pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=72, ) # COVER PAGE self.pdf_elements.extend( api.NotificationApi.get_cover_page( report_id=report_id, recipient=recipient, ), ) # METADATA PAGE self.pdf_elements.extend(self.get_metadata_page(recipient)) # REPORT self.pdf_elements.extend( [Paragraph("Report Questions", self.section_title_style)], ) for item in self.report_data: question, answers = item.popitem() self.render_question(question, answers) doc.build( self.pdf_elements, onFirstPage=self.get_header_footer(recipient), onLaterPages=self.get_header_footer(recipient), canvasmaker=NumberedCanvas, ) result = report_buffer.getvalue() report_buffer.close() return result
def afterFlowable(self, flowable): if flowable.__class__.__name__ == 'Paragraph': text = flowable.getPlainText() style = flowable.style.name if style == 'Heading1': key = 'h1-%s' % self.seq.nextf('heading1') self.canv.bookmarkPage(key) self.notify('TOCEntry', (0, text, self.page, key)) if style == 'Heading2': key = 'h2-%s' % self.seq.nextf('heading2') self.canv.bookmarkPage(key) self.notify('TOCEntry', (1, text, self.page, key)) if style == 'Heading3': key = 'h3-%s' % self.seq.nextf('heading3') self.canv.bookmarkPage(key) self.notify('TOCEntry', (2, text, self.page, key))
def parse_repeat(self, r_object): styNormal = styleSheet['Normal'] styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.white) gnr_question = r_object['name'] for gnr_answer in self.main_answer[gnr_question]: for first_children in r_object['children']: question = first_children['name'] group_answer = self.main_answer[gnr_question] question_label = first_children['label'] if gnr_question+"/"+question in gnr_answer: if first_children['type'] == 'note': answer= '' elif first_children['type'] == 'photo': #photo = '/media/user/attachments/'+ gnr_answer[gnr_question+"/"+question] photo = 'http://'+self.base_url+'/media/'+ self.media_folder +'/attachments/'+ gnr_answer[gnr_question+"/"+question] answer = self.create_logo(photo) # answer ='' else: answer = gnr_answer[gnr_question+"/"+question] else: answer = '' if 'label' in first_children: question = first_children['label'] row=[Paragraph(question, styBackground), answer] self.data.append(row)
def parse_group(self, g_object): styNormal = styleSheet['Normal'] styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.white) gnr_question = g_object['name'] for first_children in g_object['children']: question = first_children['name'] if gnr_question+"/"+question in self.main_answer: if first_children['type'] == 'note': answer= '' elif first_children['type'] == 'photo': photo = 'http://'+self.base_url+'/media/'+ self.media_folder +'/attachments/'+self.main_answer[gnr_question+"/"+question] answer = self.create_logo(photo) else: answer = self.main_answer[gnr_question+"/"+question] else: answer = '' if 'label' in first_children: question = first_children['label'] row=[Paragraph(question, styBackground), answer] self.data.append(row)
def parse_individual_questions(self, parent_object): styNormal = styleSheet['Normal'] styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.white) answer=self.main_answer for first_children in parent_object: if first_children['type'] == "repeat": self.parse_repeat(first_children) elif first_children['type'] == 'group': self.parse_group(first_children) else: question = first_children['name'] if first_children['type'] == 'note' or question not in self.main_answer: answer= Paragraph('', styBackground) elif first_children['type'] == 'photo': photo = 'http://'+self.base_url+'/media/'+ self.media_folder +'/attachments/'+self.main_answer[question] answer = self.create_logo(photo) else: answer = Paragraph(self.main_answer[question], styBackground) if 'label' in first_children: question = first_children['label'] row=(Paragraph(question, styBackground), answer) self.data.append(row)
def cuadro_observaciones(self,pdf,y,cotizacion): p = ParagraphStyle('parrafos') p.alignment = TA_JUSTIFY p.fontSize = 8 p.fontName="Times-Roman" obs=Paragraph("OBSERVACIONES: "+cotizacion.observaciones,p) observaciones = [[obs]] tabla_observaciones = Table(observaciones,colWidths=[18 * cm], rowHeights=1.8 * cm) tabla_observaciones.setStyle(TableStyle( [ ('GRID', (0, 0), (0, 2), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 8), ('ALIGN',(0,0),(-1,-1),'LEFT'), ('VALIGN',(0,0),(-1,-1),'TOP'), ] )) tabla_observaciones.wrapOn(pdf, 800, 600) tabla_observaciones.drawOn(pdf, 40,y+20)
def tabla_encabezado(self, styles): sp = ParagraphStyle('parrafos', alignment=TA_CENTER, fontSize=14, fontName="Times-Roman") requerimiento = self.requerimiento try: archivo_imagen = os.path.join(settings.MEDIA_ROOT, str(EMPRESA.logo)) imagen = Image(archivo_imagen, width=90, height=50, hAlign='LEFT') except: print u"Ingresa acá " imagen = Paragraph(u"LOGO", sp) nro = Paragraph(u"REQUERIMIENTO DE BIENES Y SERVICIOS<br/>N°" + requerimiento.codigo, sp) encabezado = [[imagen, nro, '']] tabla_encabezado = Table(encabezado, colWidths=[4 * cm, 11 * cm, 4 * cm]) tabla_encabezado.setStyle(TableStyle( [ ('ALIGN', (0, 0), (1, 0), 'CENTER'), ('VALIGN', (0, 0), (1, 0), 'CENTER'), ] )) return tabla_encabezado
def tabla_datos(self, styles): requerimiento = self.requerimiento izquierda = ParagraphStyle('parrafos', alignment=TA_LEFT, fontSize=10, fontName="Times-Roman") solicitado = Paragraph(u"SOLICITADO POR: " + requerimiento.solicitante.nombre_completo(), izquierda) oficina = Paragraph(u"OFICINA: " + requerimiento.oficina.nombre, izquierda) motivo = Paragraph(u"MOTIVO: " + requerimiento.motivo, izquierda) fecha = Paragraph(u"FECHA DE REQUERIMIENTO: " + requerimiento.fecha.strftime('%d/%m/%Y'), izquierda) mes = Paragraph(u"MES EN QUE SE NECESITA: " + requerimiento.get_mes_display(), izquierda) para_stock = Paragraph(u"AÑO EN QUE SE NECESITA: " + str(requerimiento.annio), izquierda) if requerimiento.entrega_directa_solicitante: entrega = Paragraph(u"ENTREGA DIRECTAMENTE AL SOLICITANTE: SI", izquierda) else: entrega = Paragraph(u"ENTREGA DIRECTAMENTE AL SOLICITANTE: NO", izquierda) datos = [[solicitado, oficina], [motivo], [fecha, mes], [para_stock, entrega]] tabla_datos = Table(datos, colWidths=[11 * cm, 9 * cm]) style = TableStyle( [ ('SPAN', (0, 1), (1, 1)), ] ) tabla_datos.setStyle(style) return tabla_datos
def tabla_observaciones(self): requerimiento = self.requerimiento p = ParagraphStyle('parrafos') p.alignment = TA_JUSTIFY p.fontSize = 8 p.fontName = "Times-Roman" obs = Paragraph("OBSERVACIONES: " + requerimiento.observaciones, p) observaciones = [[obs]] tabla_observaciones = Table(observaciones, colWidths=[20 * cm], rowHeights=1.8 * cm) tabla_observaciones.setStyle(TableStyle( [ ('GRID', (0, 0), (0, 2), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 8), ('ALIGN', (0, 0), (-1, -1), 'LEFT'), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ] )) return tabla_observaciones
def tabla_total(self): movimiento = self.movimiento izquierda = ParagraphStyle('parrafos', alignment = TA_LEFT, fontSize = 10, fontName="Times-Roman") texto_total = Paragraph("Total: ",izquierda) total = Paragraph(str(round(movimiento.total,2)),izquierda) total = [['',texto_total, total]] tabla_total = Table(total,colWidths=[15.5 * cm,2 * cm,2.5 * cm]) tabla_total.setStyle(TableStyle( [ ('GRID', (2, 0), (2, 0), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 8), ('ALIGN',(0,0),(-1,-1),'RIGHT'), ] )) return tabla_total
def tabla_observaciones(self): movimiento = self.movimiento p = ParagraphStyle('parrafos', alignment = TA_JUSTIFY, fontSize = 8, fontName="Times-Roman") obs=Paragraph("OBSERVACIONES: "+movimiento.observaciones,p) observaciones = [[obs]] tabla_observaciones = Table(observaciones,colWidths=[20 * cm], rowHeights=1.8 * cm) tabla_observaciones.setStyle(TableStyle( [ ('GRID', (0, 0), (0, 2), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 8), ('ALIGN',(0,0),(-1,-1),'LEFT'), ('VALIGN',(0,0),(-1,-1),'TOP'), ] )) return tabla_observaciones
def tabla_encabezado_consolidado(self, grupos): sp = ParagraphStyle('parrafos', alignment=TA_CENTER, fontSize=14, fontName="Times-Roman") try: archivo_imagen = os.path.join(settings.MEDIA_ROOT, str(EMPRESA.logo)) imagen = Image(archivo_imagen, width=90, height=50, hAlign='LEFT') except: imagen = Paragraph(u"LOGO", sp) if grupos: titulo = Paragraph(u"RESUMEN MENSUAL DE ALMACÉN POR GRUPOS Y CUENTAS", sp) else: titulo = Paragraph(u"RESUMEN MENSUAL DE ALMACÉN POR PRODUCTOS", sp) encabezado = [[imagen,titulo]] tabla_encabezado = Table(encabezado, colWidths=[2 * cm, 23 * cm]) style = TableStyle( [ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ] ) tabla_encabezado.setStyle(style) return tabla_encabezado
def convertSourceFiles(filenames): "Helper function - makes minimal PDF document" from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, XPreformatted from reportlab.lib.styles import getSampleStyleSheet styT=getSampleStyleSheet()["Title"] styC=getSampleStyleSheet()["Code"] doc = SimpleDocTemplate("pygments2xpre.pdf") S = [].append for filename in filenames: S(Paragraph(filename,style=styT)) src = open(filename, 'r').read() fmt = pygments2xpre(src) S(XPreformatted(fmt, style=styC)) doc.build(S.__self__) print('saved pygments2xpre.pdf')
def test_09_docTemplate(self): from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) stylesheet = getSampleStyleSheet() elements = [] doc = SimpleDocTemplate("demo.pdf") elements.append(Paragraph('<font name="chsFont">AUT OOM????</font>', stylesheet['Title'])) elements.append(Spacer(1,12)) doc.build(elements)
def add_str_content(self, content, size=9, Bold=False, indent=(0.05*inch, 0.05*inch), style=None): ''' ?????? :param content: ?????? :param size: ????,??9 :param Bold: ????,??False :param indent: ??????,(???,???) :param style: ???? ''' if style == None: style = styles["Normal"] __content = "<font name='chsFont' size=%s>%s</font>" % (size, content) if Bold: __content = "<b>%s</b>" % __content p = Paragraph(__content, style) self.__content.append(Spacer(PAGE_WIDTH, indent[0])) self.__content.append(p) self.__content.append(Spacer(PAGE_WIDTH, indent[1]))
def _add_notes(self, canvas): """ This is designed to be the last element on the page. Don't move it or stuff will break """ start_posn = self.start_posn start_posn = self.start_posn canvas.setFillColor(colors.blue) canvas.setFont('Helvetica', 10) canvas.drawString(0.5*inch, start_posn, 'Section E - Registration Notes') canvas.setFillColor(colors.black) canvas.rect(0.5*inch, 0.75*inch, PAGE_WIDTH-inch, start_posn-0.85*inch) style_sheet = getSampleStyleSheet() style = style_sheet['BodyText'] para = Paragraph(self.details['registration_notes'], style) h=para.wrap(7.1 * inch, start_posn-0.65*inch)[1] para.drawOn(canvas, 0.7 * inch, start_posn-h-0.2*inch)
def render_footer(url, date=None): ''' Renders the footer used in the different PDFs :return: a Paragraph object ''' if not date: date = datetime.date.today().strftime("%d.%m.%Y") p = Paragraph('''<para> {date} - <a href="{url}">{url}</a> - wger Workout Manager {version} </para>'''.format(date=date, url=url, version=get_version()), styleSheet["Normal"]) return p # register new truetype fonts for reportlab
def gen_team_pdf(team_tuples: list): global _reged if not _reged: pdfmetrics.registerFont(TTFont('my_font', options.options.ttf_font_name)) _reged = True buf = io.BytesIO() canv = canvas.Canvas(buf, pagesize=A4_TRANSVERSE) style = ParagraphStyle(name='default', fontName='my_font', fontSize=options.options.pdf_font_size, alignment=1, leading=options.options.pdf_font_size * 1.2) for index, team in team_tuples: paragraph = Paragraph('Team {0}<br />{1}'.format(index, team['team_name']), style) w, h = paragraph.wrap(A4_TRANSVERSE[0] - 50, A4_TRANSVERSE[1] - 50) paragraph.drawOn(canv, (A4_TRANSVERSE[0] - w) / 2, (A4_TRANSVERSE[1] - h) / 2) canv.showPage() canv.save() return buf.getvalue()
def add_timeline(self): ptext = '<b><font size=14>Processing Timeline</font></b>' self.Story.append(Paragraph(ptext, self.styles['Normal'])) self.Story.append(Spacer(1, 0.1*inch)) data = [ [self.request['stage'][0]['name'], self.time_str(self.request['stage'][0]['time'])], [self.request['stage'][1]['name'], self.time_str(self.request['stage'][1]['time'])], [self.request['stage'][2]['name'], self.time_str(self.request['stage'][2]['time'])], [self.request['stage'][3]['name'], self.time_str(int(time.time()))] # ['complete', self.time_str(self.request['stage'][3]['time'])] ] data = [[i[0], pg(i[1], 1)] for i in data] t = Table(data) t.setStyle(TableStyle([ ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black) ])) self.Story.append(t)
def gather_elements(self, client, node, style): if isinstance(node.parent, docutils.nodes.sidebar): elements = [Paragraph(client.gen_pdftext(node), client.styles['sidebar-subtitle'])] elif isinstance(node.parent, docutils.nodes.document): #elements = [Paragraph(client.gen_pdftext(node), #client.styles['subtitle'])] # The visible output is now done by the cover template elements = [] # FIXME: looks like subtitles don't have a rawsource like # titles do. # That means that literals and italics etc in subtitles won't # work. client.doc_subtitle = getattr(node,'rawtext',node.astext()).strip() else: elements = node.elements # FIXME Can we get here??? return elements
def gather_elements(self, client, node, style): if isinstance(node.parent, docutils.nodes.authors): # Is only one of multiple authors. Return a paragraph node.elements = [Paragraph(client.gather_pdftext(node), style=style)] if client.doc_author: client.doc_author += client.author_separator(style=style) \ + node.astext().strip() else: client.doc_author = node.astext().strip() else: # A single author: works like a field fb = client.gather_pdftext(node) t_style=TableStyle(client.styles['field-list'].commands) colWidths=map(client.styles.adjustUnits, client.styles['field-list'].colWidths) node.elements = [Table( [[Paragraph(client.text_for_label("author", style)+":", style=client.styles['fieldname']), Paragraph(fb, style)]], style=t_style, colWidths=colWidths)] client.doc_author = node.astext().strip() return node.elements
def gather_elements(self, client, node, style): # Based on the graphviz extension global graphviz_warn try: # Is vectorpdf enabled? if hasattr(VectorPdf,'load_xobj'): # Yes, we have vectorpdf fname, outfn = sphinx.ext.graphviz.render_dot(node['builder'], node['code'], node['options'], 'pdf') else: # Use bitmap if not graphviz_warn: log.warning('Using graphviz with PNG output. You get much better results if you enable the vectorpdf extension.') graphviz_warn = True fname, outfn = sphinx.ext.graphviz.render_dot(node['builder'], node['code'], node['options'], 'png') if outfn: client.to_unlink.append(outfn) client.to_unlink.append(outfn+'.map') else: # Something went very wrong with graphviz, and # sphinx should have given an error already return [] except sphinx.ext.graphviz.GraphvizError, exc: log.error('dot code %r: ' % node['code'] + str(exc)) return [Paragraph(node['code'],client.styles['code'])] return [MyImage(filename=outfn, client=client)]
def create_title(self, title_text, element_type=None): if element_type == "document": title_text_style = self.text_styleT elif element_type == "section": title_text_style = self.text_styleH else: title_text_style = self.text_styleN title = Paragraph('''<para align=center spaceb=3><b>''' + title_text + '''</b></para>''', title_text_style) title_table = Table([[title]], colWidths=[5 * inch] * 1) title_table.setStyle(self.title_style) return title_table
def add_question(self, question): self.pdf_elements.append( Paragraph(question, self.body_style), ) self.pdf_elements.append(Spacer(1, 4))
def add_answer_list(self, answers): for answer in answers: self.pdf_elements.append( Paragraph(answer, self.notes_style), ) self.pdf_elements.append(Spacer(1, 1))
def hello(c, link): c.translate(ORIGIN_X, ORIGIN_Y) # Draw paragraph stylesheet = getSampleStyleSheet() style = stylesheet['BodyText'] style.fontName = 'LeagueGothic' style.fontSize = 42 style.leading = 44 p = Paragraph('<b>print</b><br/>your<br/><b>badge</b><br/>here', style) qr_left = 30*mm p_w, p_h = p.wrap(qr_left, HEIGHT) p.drawOn(c, 0, 0) # Add QR Code qr_code = qr.QrCodeWidget(link) qr_bounds = qr_code.getBounds() qr_width = qr_bounds[2] - qr_bounds[0] qr_height = qr_bounds[3] - qr_bounds[1] d = Drawing(HEIGHT, HEIGHT, transform=[HEIGHT/qr_width,0,0,HEIGHT/qr_height,0,0]) d.add(qr_code) renderPDF.draw(d, c, qr_left, 0) # Draw thin line between text and QR code c.line(qr_left, 0, qr_left, HEIGHT) c.line(qr_left + HEIGHT, 0, qr_left+HEIGHT, HEIGHT) img_left = qr_left + HEIGHT # Draw images c.drawImage('images/ipv6.jpg', img_left, 0, 20*mm, 1/3 * HEIGHT, mask=None, preserveAspectRatio=True, anchor='c') c.drawImage('images/ffrhein_logo_claim_line_rot.png', img_left, 1/3*HEIGHT, 20*mm, 2/3 * HEIGHT, mask=None, preserveAspectRatio=True, anchor='c')
def render(self): style = getSampleStyleSheet()['Normal'] style.alignment = self.text_align style.fontName = self.font_name if self._layout.debug_fields: style.backColor = "rgba(255, 0, 0, 0.5)" if self.fit_text: original_size = self.font_size text_width = stringWidth(self.data, self.font_name, self.font_size) while text_width > self.width: self.font_size -= 1 text_width = stringWidth(self.data, self.font_name, self.font_size) # Size has been adjusted. Lower text accordingly if original_size > self.font_size: self._offset_top = (original_size - self.font_size) / 2.0 if self.height == 0: self.height = self.font_size style.fontSize = self.font_size style.leading = self.font_size p = Paragraph('<font color="%s">%s</font>' % (self.color, self.data), style) p.wrap(self.width, self.height) top = self._layout.height - self.top - self.height - self._offset_top p.drawOn(self._canvas, self.left, top)
def resize_images(self, story): # replace images with resized ones fitting into the available width W, H = ( self.width - self.lm - self.rm), self.height - self.tm - self.bm for i, el in enumerate(story): if el.__class__ == Image: img = PIL.Image.open(el.filename) h = W / img.size[0] * img.size[1] img = Image(el.filename, width=w, height=h, kind='direct', mask="auto", lazy=1) story[i] = img elif type(el) == str: story[i] = Paragraph(el, bt) # Spacer(0, 0)
def markdown_to_platypus(path): "Convert a specific MarkDown file into ReportLab Platypus items." cover, qa = extract_markdown(path) title, paras = cover cover = [Paragraph(title, h1)] + [Paragraph(p, bt) for p in paras] items = [{"q": Paragraph(q, bt), "a": XPreformatted(pygments2xpre(a), code)} for q, a in qa] return cover, items
def make_cards_platypus(cardSize, cover, items, verbose=False): "Generate q/a sides of quiz cards from a list of quiz items." # cover and items are Platypus flowables! cw, ch = cardSize kwDict = { "lm": 4 * mm, "rm": 4 * mm, "text": "", "width": cw, "height": ch, "verbose": verbose } q_side = QuizCard(**kwDict) a_side = QuizCard(**kwDict) # first cover card questions = cover answers = [] # rest of the normal cards for i, item in enumerate(items): q, a = item["q"], item["a"] q_side.text = questions a_side.text = answers yield q_side, a_side questions = [Paragraph("Question:", fine)] + [q] answers = [Paragraph("Answer %d:<br/><br/>" % (i + 1), fine)] + [a] q_side = QuizCard(**kwDict) a_side = QuizCard(**kwDict) q_side.text = questions a_side.text = answers yield q_side, a_side
def _header_footer(self, canvas, doc): # Save the state of our canvas so we can draw on it canvas.saveState() styles = getSampleStyleSheet() style_right = ParagraphStyle(name='right', parent=styles['Normal'], fontName='Helvetica', fontSize=10, alignment=TA_RIGHT) # Header fieldsight_logo = Image('http://' + self.base_url +'/static/images/fs1.jpg') fieldsight_logo._restrictSize(1.5 * inch, 1.5 * inch) # headerleft = Paragraph("FieldSight", styles['Normal']) headerright = Paragraph(self.project_name, style_right) # w1, h1 = headerleft.wrap(doc.width, doc.topMargin) w2, h2 = headerright.wrap(doc.width, doc.topMargin) textWidth = stringWidth(self.project_name, fontName='Helvetica', fontSize=10) fieldsight_logo.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin + 12) headerright.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin + 20) project_logo = Image('http://' + self.base_url + self.project_logo) project_logo._restrictSize(0.4 * inch, 0.4 * inch) project_logo.drawOn(canvas, headerright.width + doc.leftMargin -0.5 * inch - textWidth, doc.height + doc.topMargin + 10) # header.drawOn(canvas, doc.leftMargin + doc.width, doc.height + doc.topMargin +20) # Footer footer = Paragraph('Page no. '+str(canvas._pageNumber), style_right) w, h = footer.wrap(doc.width, doc.bottomMargin) footer.drawOn(canvas, doc.leftMargin, h + 40) # Release the canvas canvas.restoreState()
def tabla_encabezado(self, styles): orden_compra = self.orden_compra sp = ParagraphStyle('parrafos', alignment = TA_CENTER, fontSize = 14, fontName="Times-Roman") try: archivo_imagen = os.path.join(settings.MEDIA_ROOT,str(EMPRESA.logo)) imagen = Image(archivo_imagen, width=90, height=50,hAlign='LEFT') except: imagen = Paragraph(u"LOGO", sp) nro = Paragraph(u"ORDEN DE COMPRA", sp) ruc = Paragraph("R.U.C."+EMPRESA.ruc, sp) encabezado = [[imagen,nro,ruc],['',u"N°"+orden_compra.codigo,EMPRESA.distrito + " " + orden_compra.fecha.strftime('%d de %b de %Y')]] tabla_encabezado = Table(encabezado,colWidths=[4 * cm, 9 * cm, 6 * cm]) tabla_encabezado.setStyle(TableStyle( [ ('ALIGN',(0,0),(2,1),'CENTER'), ('VALIGN',(0,0),(2,0),'CENTER'), ('VALIGN',(1,1),(2,1),'TOP'), ('SPAN',(0,0),(0,1)), ] )) return tabla_encabezado
def tabla_datos(self, styles): orden = self.orden_compra izquierda = ParagraphStyle('parrafos', alignment = TA_LEFT, fontSize = 10, fontName="Times-Roman") cotizacion = orden.cotizacion if cotizacion is None: proveedor = orden.proveedor else: proveedor = orden.cotizacion.proveedor razon_social_proveedor = Paragraph(u"SEÑOR(ES): "+proveedor.razon_social, izquierda) ruc_proveedor = Paragraph(u"R.U.C.: "+proveedor.ruc, izquierda) direccion = Paragraph(u"DIRECCIÓN: "+proveedor.direccion, izquierda) try: telefono = Paragraph(u"TELÉFONO: "+proveedor.telefono, izquierda) except: telefono = Paragraph(u"TELÉFONO: -", izquierda) try: referencia = Paragraph(u"REFERENCIA: "+orden.cotizacion.requerimiento.codigo+" - "+orden.cotizacion.requerimiento.oficina.nombre, izquierda) except: referencia = Paragraph(u"REFERENCIA: ",izquierda) proceso = Paragraph(u"PROCESO: "+orden.proceso, izquierda) nota = Paragraph(u"Sírvase remitirnos según especificaciones que detallamos lo siguiente: ", izquierda) datos = [[razon_social_proveedor,ruc_proveedor],[direccion,telefono],[referencia,''],[proceso,''],[nota,'']] tabla_detalle = Table(datos,colWidths=[11* cm, 9 * cm]) tabla_detalle.setStyle(TableStyle( [ ('SPAN',(0,2),(1,2)), ] )) return tabla_detalle
def tabla_detalle(self): orden = self.orden_compra encabezados = ['Item', 'Cantidad', 'Unidad', u'Descripción','Precio','Total'] detalles = DetalleOrdenCompra.objects.filter(orden=orden).order_by('pk') sp = ParagraphStyle('parrafos') sp.alignment = TA_JUSTIFY sp.fontSize = 8 sp.fontName="Times-Roman" lista_detalles = [] for detalle in detalles: try: tupla_producto = [Paragraph(str(detalle.nro_detalle),sp), Paragraph(str(detalle.cantidad), sp), Paragraph(detalle.detalle_cotizacion.detalle_requerimiento.producto.unidad_medida.descripcion,sp), Paragraph(detalle.detalle_cotizacion.detalle_requerimiento.producto.descripcion, sp), Paragraph(str(detalle.precio),sp), Paragraph(str(detalle.valor),sp)] except: tupla_producto = [Paragraph(str(detalle.nro_detalle),sp), Paragraph(str(detalle.cantidad), sp), Paragraph(detalle.producto.unidad_medida.descripcion,sp), Paragraph(detalle.producto.descripcion, sp), Paragraph(str(detalle.precio),sp), Paragraph(str(detalle.valor),sp)] lista_detalles.append(tupla_producto) adicionales = [('','','','','')] * (15-len(lista_detalles)) tabla_detalle = Table([encabezados] + lista_detalles + adicionales,colWidths=[0.8 * cm, 2 * cm, 2.5 * cm,10.2* cm, 2 * cm, 2.5 * cm]) style = TableStyle( [ ('ALIGN',(0,0),(4,0),'CENTER'), ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('ALIGN',(4,1),(-1,-1),'LEFT'), ('VALIGN',(0,0),(-1,-1),'TOP'), ] ) tabla_detalle.setStyle(style) return tabla_detalle
def tabla_detalle(self): requerimiento = self.requerimiento encabezados = ['Nro', 'Cantidad', 'Unidad', u'Descripción', 'Uso'] detalles = DetalleRequerimiento.objects.filter(requerimiento=requerimiento) sp = ParagraphStyle('parrafos') sp.alignment = TA_JUSTIFY sp.fontSize = 8 sp.fontName = "Times-Roman" lista_detalles = [] for detalle in detalles: tupla_producto = [Paragraph(str(detalle.nro_detalle), sp), Paragraph(str(detalle.cantidad), sp), Paragraph(detalle.producto.unidad_medida.descripcion, sp), Paragraph(detalle.producto.descripcion, sp), Paragraph(detalle.uso, sp)] lista_detalles.append(tupla_producto) adicionales = [('', '', '', '', '')] * (15 - len(detalles)) tabla_detalle = Table([encabezados] + lista_detalles, colWidths=[0.8 * cm, 2 * cm, 2.5 * cm, 7 * cm, 7.7 * cm]) style = TableStyle( [ ('ALIGN', (0, 0), (4, 0), 'CENTER'), ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('ALIGN', (4, 1), (-1, -1), 'LEFT'), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ] ) tabla_detalle.setStyle(style) return tabla_detalle
def tabla_encabezado(self, styles): movimiento = self.movimiento sp = ParagraphStyle('parrafos', alignment = TA_CENTER, fontSize = 14, fontName="Times-Roman") try: archivo_imagen = os.path.join(settings.MEDIA_ROOT,str(EMPRESA.logo)) imagen = Image(archivo_imagen, width=90, height=50,hAlign='LEFT') except: imagen = Paragraph(u"LOGO", sp) if movimiento.tipo_movimiento.incrementa: nota = Paragraph(u"NOTA DE INGRESO N°", sp) else: nota = Paragraph(u"NOTA DE SALIDA N°", sp) id_movimiento = Paragraph(movimiento.id_movimiento, sp) fecha = Paragraph("FECHA: "+movimiento.fecha_operacion.strftime('%d/%m/%y'), sp) encabezado = [[imagen,nota,fecha], ['',id_movimiento,''] ] tabla_encabezado = Table(encabezado,colWidths=[4 * cm, 9 * cm, 6 * cm]) tabla_encabezado.setStyle(TableStyle( [ ('VALIGN',(0,0),(2,0),'CENTER'), ('VALIGN',(1,1),(2,1),'TOP'), ('SPAN',(0,0),(0,1)), ] )) return tabla_encabezado
def tabla_datos(self, styles): movimiento = self.movimiento izquierda = ParagraphStyle('parrafos', alignment = TA_LEFT, fontSize = 10, fontName="Times-Roman") try: if movimiento.referencia.cotizacion is not None: proveedor = Paragraph(u"PROVEEDOR: "+movimiento.referencia.cotizacion.proveedor.razon_social,izquierda) else: proveedor = Paragraph(u"PROVEEDOR: "+movimiento.referencia.proveedor.razon_social,izquierda) except: proveedor = Paragraph(u"PROVEEDOR:",izquierda) operacion = Paragraph(u"OPERACIÓN: "+movimiento.tipo_movimiento.descripcion,izquierda) almacen = Paragraph(u"ALMACÉN: "+movimiento.almacen.codigo+"-"+movimiento.almacen.descripcion,izquierda) try: orden_compra = Paragraph(u"ORDEN DE COMPRA: "+movimiento.referencia.codigo,izquierda) except: orden_compra = Paragraph(u"REFERENCIA: -",izquierda) try: documento = Paragraph(u"DOCUMENTO: "+movimiento.tipo_documento.descripcion + " SERIE:" + movimiento.serie + u" NÚMERO:" + movimiento.numero, izquierda) except: documento = "" try: pedido = Paragraph(u"PEDIDO: "+movimiento.pedido.codigo, izquierda) except: pedido = "" encabezado = [[operacion,''], [almacen,''], [proveedor,''], [orden_compra,''], [documento,''], [pedido,'']] tabla_datos = Table(encabezado,colWidths=[11 * cm, 9 * cm]) tabla_datos.setStyle(TableStyle( [ ] )) return tabla_datos
def _header(self, canvas, doc): canvas.saveState() sp = ParagraphStyle('parrafos', alignment=TA_CENTER, fontSize=14, fontName="Times-Roman") try: archivo_imagen = os.path.join(settings.MEDIA_ROOT, str(EMPRESA.logo)) imagen = Image(archivo_imagen, width=90, height=50, hAlign='LEFT') except: imagen = Paragraph(u"LOGO", sp) ruc_empresa = "RUC: " + EMPRESA.ruc if self.valorizado: titulo = Paragraph(u"REGISTRO DEL INVENTARIO PERMANENTE VALORIZADO", sp) else: titulo = Paragraph(u"REGISTRO DEL INVENTARIO PERMANENTE EN UNIDADES FÍSICAS",sp) pagina = u"Página " + str(doc.page) + " de " + str(self.total_paginas) encabezado = [[imagen, titulo, pagina], [ruc_empresa, "", ""]] tabla_encabezado = Table(encabezado, colWidths=[3 * cm, 20 * cm, 3 * cm]) style = TableStyle( [ ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ] ) tabla_encabezado.setStyle(style) tabla_encabezado.wrapOn(canvas, 50, 510) tabla_encabezado.drawOn(canvas, 50, 510) 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("Listado de Clientes", styles['Heading1']) clientes.append(header) headings = ('Nombre', 'Email', 'Edad', 'Direccion') allclientes = [(p.codigo, p.descripcion, p.precio_mercado, p.grupo_suministros) for p in Producto.objects.all()] t = Table([headings] + allclientes) t.setStyle(TableStyle( [ ('GRID', (0, 0), (3, -1), 1, colors.dodgerblue), ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue), ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue) ] )) clientes.append(t) doc.build(clientes) response.write(buff.getvalue()) buff.close() return response
def leftTop(self, e): if e is None: return '' return reportlab.platypus.Paragraph( '<font face="%s" size=%d>%s</font><br/>' % (FONT_FAMILY, FONT_SIZE['header'], ExportDocument.header( e, self.Lang)), self.style)
def leftBottom(self, e): story = [] if e is None: return story b = model.Board() if 'algebraic' in e: b.fromAlgebraic(e['algebraic']) x = unicode(self.board2Html(b).decode("ISO-8859-1")) story.append( BorderedParagraph( '<para autoLeading="max">' + x + '</para>', self.style)) s_left = '' if 'stipulation' in e: s_left = e['stipulation'] story.append(self.subscript(s_left, b.getPiecesCount())) story.append( reportlab.platypus.Paragraph( '<font face="%s" size=%d>%s</font>' % (FONT_FAMILY, FONT_SIZE['footer'], ExportDocument.solver( e, self.Lang) + '<br/>' + ExportDocument.legend(b)), self.style)) return story