def imprimir_alertas(self,items): buffer = self.buffer doc = SimpleDocTemplate(buffer, rightMargin = 15*mm, leftMargin = 15*mm, topMargin = 15*mm, bottomMargin = 15*mm, pagesize = self.pagesize) elements = [] styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='logo',alignment=TA_LEFT,leftIndent=8*mm, fontSize=14)) logo = MEDIA_ROOT + "/logo.jpg" elements.append(ImageAndFlowables(Image(logo,width=75*mm,height=25*mm), [Paragraph("<b>Departamento de Mantenimiento</b>",styles['logo']), Paragraph("Alertas de falta de material en inventario",styles['Heading2'])], imageSide = 'left')) tablaItems = Table(items, colWidths=[doc.width/4.0]*4) tablaItems.setStyle(TableStyle([('BACKGROUND',(0,0),(-1,0),colors.HexColor(0xD8D8D8)), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black)])) elements.append(tablaItems) doc.build(elements, canvasmaker=CanvasNumerado) pdf = buffer.getvalue() buffer.close() return pdf
def striped_table(listA,listB): alt_join = stripe_lists(listA, listB) table_data = [] for row in alt_join: new_row = [] for item in row: content = Paragraph(item, table_cell_style) new_row.append(content) table_data.append(new_row) t=Table(table_data, colWidths=(PDF_WIDTH-2*margin)/num_cols) for each in range(len(alt_join)): if each % 2 == 0: bg_color = HEADER_COLOR txt_color = HEADER_TEXT_COLOR else: bg_color = BODY_COLOR txt_color = BODY_TEXT_COLOR t.setStyle(TableStyle([ ('BACKGROUND',(0,each),(num_cols,each),bg_color), ('TEXTCOLOR',(0,0),(num_cols,0),txt_color), ('ALIGN',(0,0),(-1,-1),'CENTER'), ('BOX',(0,0),(-1,-1),0.25, black), ('INNERGRID',(0,0),(-1,-1),0.25,black), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('LEFTPADDING',(0,0),(-1,-1),2), ('RIGHTPADDING',(0,0),(-1,-1),2), ('BOTTOMPADDING',(0,0),(-1,-1),2), ('TOPPADDING',(0,0),(-1,-1),2) ])) return t
def endFunctions(self, names): h1, h2, h3, bt, code = self.h1, self.h2, self.h3, self.bt, self.code styleSheet = getSampleStyleSheet() bt1 = styleSheet['BodyText'] story = self.story if not names: return tsa = tableStyleAttributes = [] # Make table with class and method rows # and add it to the story. p = Paragraph('<b>%s</b>' % self.classCompartment, bt) p.style.alignment = TA_CENTER rows = [(p,)] lenRows = len(rows) tsa.append(('BOX', (0,0), (-1,lenRows-1), 0.25, colors.black)) for name, doc, sig in self.methodCompartment: nameAndSig = Paragraph('<b>%s</b>%s' % (name, sig), bt1) rows.append((nameAndSig,)) # No doc strings, now... # docStr = Paragraph('<i>%s</i>' % reduceDocStringLength(doc), bt1) # rows.append((docStr,)) tsa.append(('BOX', (0,lenRows), (-1,-1), 0.25, colors.black)) t = Table(rows, (12*cm,)) tableStyle = TableStyle(tableStyleAttributes) t.setStyle(tableStyle) self.story.append(t) self.story.append(Spacer(1*cm, 1*cm))
def renderToc(self, tocpath, toc_entries, rtl): doc = SimpleDocTemplate(tocpath, pagesize=(pdfstyles.page_width, pdfstyles.page_height)) elements = [] elements.append( Paragraph(_("Contents"), pdfstyles.heading_style(mode="chapter", text_align="left" if not rtl else "right")) ) toc_table = [] styles = [] col_widths = self._getColWidths() for row_idx, (lvl, txt, page_num) in enumerate(toc_entries): if lvl == "article": page_num = str(page_num) elif lvl == "chapter": page_num = "<b>%d</b>" % page_num styles.append(("TOPPADDING", (0, row_idx), (-1, row_idx), 10)) elif lvl == "group": page_num = " " styles.append(("TOPPADDING", (0, row_idx), (-1, row_idx), 10)) toc_table.append( [ Paragraph(txt, pdfstyles.text_style(mode="toc_%s" % str(lvl), text_align="left")), Paragraph(page_num, pdfstyles.text_style(mode="toc_article", text_align="right")), ] ) t = Table(toc_table, colWidths=col_widths) t.setStyle(styles) elements.append(t) doc.build(elements)
def endClass(self, name, doc, bases): h1, h2, h3, bt, code = self.h1, self.h2, self.h3, self.bt, self.code styleSheet = getSampleStyleSheet() bt1 = styleSheet['BodyText'] story = self.story # Use only the first line of the class' doc string -- # no matter how long! (Do the same later for methods) classDoc = reduceDocStringLength(doc) tsa = tableStyleAttributes = [] # Make table with class and method rows # and add it to the story. p = Paragraph('<b>%s</b>' % self.classCompartment, bt) p.style.alignment = TA_CENTER rows = [(p,)] # No doc strings, now... # rows = rows + [(Paragraph('<i>%s</i>' % classDoc, bt1),)] lenRows = len(rows) tsa.append(('BOX', (0,0), (-1,lenRows-1), 0.25, colors.black)) for name, doc, sig in self.methodCompartment: nameAndSig = Paragraph('<b>%s</b>%s' % (name, sig), bt1) rows.append((nameAndSig,)) # No doc strings, now... # docStr = Paragraph('<i>%s</i>' % reduceDocStringLength(doc), bt1) # rows.append((docStr,)) tsa.append(('BOX', (0,lenRows), (-1,-1), 0.25, colors.black)) t = Table(rows, (12*cm,)) tableStyle = TableStyle(tableStyleAttributes) t.setStyle(tableStyle) self.story.append(t) self.story.append(Spacer(1*cm, 1*cm))
def pictures_table(diagram_img, machine_img): """ create a table containing the diagram image and the machine image. """ img_width = 7 * cm img_height = 6 * cm diagram_img = Image(diagram_img, width=img_width, height=img_height) machine_img = Image(machine_img, width=img_width, height=img_height) diagram = Paragraph('DIAGRAMA ESQUEMATICO', style=BLACK_BOLD_CENTER) machine = Paragraph('IMAGEN MAQUINA', style=BLACK_BOLD_CENTER) data = [[diagram, machine], [diagram_img, machine_img]] styles = [ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('GRID', (0, 0), (-1, -1), 0.25, black), ('BACKGROUND', (0, 0), (1, 0), TABLE_BLUE), ('FONTNAME', (0, 0), (0, 1), 'Arial-Bold'), ] table = Table(data, colWidths=[9 * cm, 9 * cm], rowHeights=[0.5 * cm, 6 * cm]) table.setStyle(TableStyle(styles)) return table
def build_ack_table(self): data = [('Name:', 'Date:'), ('Position:', 'Signature:')] table = Table(data, hAlign='LEFT', colWidths=[90 * mm, 90 * mm]) style = self.get_table_style() style.add('INNERGRID', (0, 0), (-1, -1), 0, colors.white) table.setStyle(style) return table
def through_table(data): styles = getSampleStyleSheet() table_cell_style = ParagraphStyle('yourtitle', alignment=1) table_data = [] for row in data: new_row = [] for item in row: content = Paragraph(item, table_cell_style) new_row.append(content) table_data.append(new_row) t=Table(table_data, colWidths=(PDF_WIDTH-2*margin)/5) t.setStyle(TableStyle([ ('BACKGROUND',(0,0),(0,-1),HEADER_COLOR), ('BACKGROUND',(0,0),(-1,0),HEADER_COLOR), ('TEXTCOLOR',(0,0),(2,0),black), ('ALIGN',(0,0),(-1,-1),'CENTER'), ('BOX',(0,0),(-1,-1),0.25, black), ('INNERGRID',(0,0),(-1,-1),0.25,black), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('LEFTPADDING',(0,0),(-1,-1),2), ('RIGHTPADDING',(0,0),(-1,-1),2), ('BOTTOMPADDING',(0,0),(-1,-1),2), ('TOPPADDING',(0,0),(-1,-1),2) ])) return t
def vert_table(listA, listB, cols): listC = [] for i in range(len(listA)): row = [] row.append(listA[i]) row.append(listB[i]) listC.append(row) table_data = [] for row in listC: new_row = [] for item in row: content = Paragraph(item, table_cell_style) new_row.append(content) table_data.append(new_row) t=Table(table_data, colWidths=(PDF_WIDTH-2*margin)/cols) t.setStyle(TableStyle([ ('BACKGROUND',(0,0),(0,4),HEADER_COLOR), ('TEXTCOLOR',(0,0),(2,0),black), ('ALIGN',(0,0),(-1,-1),'CENTER'), ('BOX',(0,0),(-1,-1),0.25, black), ('INNERGRID',(0,0),(-1,-1),0.25,black), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('LEFTPADDING',(0,0),(-1,-1),2), ('RIGHTPADDING',(0,0),(-1,-1),2), ('BOTTOMPADDING',(0,0),(-1,-1),2), ('TOPPADDING',(0,0),(-1,-1),2) ])) return t
def _create_header_table(self, report_date): """ create table to manage elements in custom header. """ logo = Image(LOGO, width=8.65 * cm, height=2.51 * cm) skf = Image(SKF, width=1.76 * cm, height=0.47 * cm) skf_text = Paragraph('Con tecnología', style=GREEN_SMALL) company = Paragraph(self.company.upper(), style=BLUE_HEADER) data = [[logo, skf_text, report_date], ['', skf, company]] styles = [ ('ALIGN', (0, 0), (0, -1), 'LEFT'), ('VALIGN', (0, 0), (0, -1), 'MIDDLE'), ('ALIGN', (1, 0), (1, -1), 'CENTER'), ('VALIGN', (1, 0), (1, 0), 'BOTTOM'), ('VALIGN', (1, -1), (1, -1), 'TOP'), ('VALIGN', (2, 0), (2, -1), 'MIDDLE'), ('ALIGN', (2, 0), (2, -1), 'LEFT'), ('SPAN', (0, 0), (0, -1)), ] table = Table(data, colWidths=[9 * cm, 2.5 * cm, 6.5 * cm], rowHeights=[1.26 * cm, 1.26 * cm]) table.setStyle(TableStyle(styles)) return table
def buildHowToPayTable(mem, dic_styles): ''' Return a Reportlab table with payment instructions ''' data= [[Paragraph('How to pay ?', dic_styles['MEDIUM'])], [Paragraph('1', dic_styles['SMALL']), Paragraph(PAYOPTIONBANKTRANSFER.format(acname=mem.organisation.bank_account_name, acnum=mem.organisation.bank_account_number, payref='15A-' + str(mem.id), adveml=mem.organisation.treasurer_email), dic_styles['SMALL'])], [Paragraph('2', dic_styles['SMALL']), Paragraph(PAYOPTIONBANKCHEQUE.format(acname=mem.organisation.bank_account_name, orgadd=mem.organisation.postal_address, payref='15A-' + str(mem.id)), dic_styles['SMALL'])]] t=Table(data,colWidths=(7.5*mm, None)) t.setStyle(TableStyle([ ('BOTTOMPADDING', (0, 0), (-1, 0), 9), ('TOPPADDING', (0, 1), (-1, 1), 0), ('BOTTOMPADDING', (0, 1), (-1, 1), 9), ('VALIGN', (0, 1), (-1, -1), 'TOP'), ('SPAN', (0, 0), (-1, 0)), ])) return t
def buildPriceTable(dic_styles): ''' Return a Reportlab table with pricing information ''' data= [[Paragraph("Annual Fee", dic_styles['MEDIUM']), "", Paragraph(ANNUALFEE, dic_styles['MEDIUM'])], [Paragraph("Options", dic_styles['MEDIUM'])], [Paragraph('1', dic_styles['SMALL']), Paragraph(ANNUALPAYINFULLTERMS, dic_styles['SMALL']), Paragraph(ANNUALPAYINFULLAMOUNT, dic_styles['SMALL'])], [Paragraph('2', dic_styles['SMALL']), Paragraph(ANNUALPAYAUTO, dic_styles['SMALL']), Paragraph(ANNUALPAYAUTOAMOUNT, dic_styles['SMALL'])], [Paragraph('3', dic_styles['SMALL']), Paragraph(ANNUALPAYONETERMTERMS, dic_styles['SMALL']), Paragraph(ANNUALPAYONETERMAMOUNT, dic_styles['SMALL'])]] t=Table(data,colWidths=(7.5*mm, None, 30*mm)) t.setStyle(TableStyle([ ('TOPPADDING', (0, 0), (-1, 0), 0), ('BOTTOMPADDING', (0, 0), (-1, 0), 9), ('TOPPADDING', (0, 1), (-1, 1), 0), ('BOTTOMPADDING', (0, 1), (-1, 1), 9), ('TOPPADDING', (0, 1), (-1, 1), 6), ('BOTTOMPADDING', (0, 1), (-1, 1), 6), ('SPAN', (0, 1), (-1, 1)), ('SPAN', (0, 0), ( 1, 0)), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) return t
def endClass(self, name, doc, bases): h1, h2, h3, bt, code = self.h1, self.h2, self.h3, self.bt, self.code styleSheet = getSampleStyleSheet() bt1 = styleSheet['BodyText'] story = self.story # Use only the first line of the class' doc string -- # no matter how long! (Do the same later for methods) classDoc = reduceDocStringLength(doc) tsa = tableStyleAttributes = [] # Make table with class and method rows # and add it to the story. p = Paragraph('<b>%s</b>' % self.classCompartment, bt) p.style.alignment = TA_CENTER rows = [(p, )] # No doc strings, now... # rows = rows + [(Paragraph('<i>%s</i>' % classDoc, bt1),)] lenRows = len(rows) tsa.append(('BOX', (0, 0), (-1, lenRows - 1), 0.25, colors.black)) for name, doc, sig in self.methodCompartment: nameAndSig = Paragraph('<b>%s</b>%s' % (name, sig), bt1) rows.append((nameAndSig, )) # No doc strings, now... # docStr = Paragraph('<i>%s</i>' % reduceDocStringLength(doc), bt1) # rows.append((docStr,)) tsa.append(('BOX', (0, lenRows), (-1, -1), 0.25, colors.black)) t = Table(rows, (12 * cm, )) tableStyle = TableStyle(tableStyleAttributes) t.setStyle(tableStyle) self.story.append(t) self.story.append(Spacer(1 * cm, 1 * cm))
def build_revisions_table(self): body_style = self.styles['BodyText'] self.styles.add( ParagraphStyle( name='BodyCentered', parent=body_style, alignment=TA_CENTER, )) centered = self.styles['BodyCentered'] header = ('Document Number', 'Title', 'Rev.', 'Status', 'RC') data = [header] for revision in self.revisions: data.append( (Paragraph(revision.document.document_number, body_style), Paragraph(revision.document.title, body_style), Paragraph(revision.name, centered), Paragraph(revision.status, centered), Paragraph(revision.get_final_return_code(), centered))) table = Table(data, hAlign='LEFT', colWidths=[70 * mm, 75 * mm, 10 * mm, 15 * mm, 10 * mm]) style = self.get_table_style() style.add('ALIGN', (0, 0), (-1, 0), 'CENTER') table.setStyle(style) return table
def endFunctions(self, names): h1, h2, h3, bt, code = self.h1, self.h2, self.h3, self.bt, self.code styleSheet = getSampleStyleSheet() bt1 = styleSheet['BodyText'] story = self.story if not names: return tsa = tableStyleAttributes = [] # Make table with class and method rows # and add it to the story. p = Paragraph('<b>%s</b>' % self.classCompartment, bt) p.style.alignment = TA_CENTER rows = [(p, )] lenRows = len(rows) tsa.append(('BOX', (0, 0), (-1, lenRows - 1), 0.25, colors.black)) for name, doc, sig in self.methodCompartment: nameAndSig = Paragraph('<b>%s</b>%s' % (name, sig), bt1) rows.append((nameAndSig, )) # No doc strings, now... # docStr = Paragraph('<i>%s</i>' % reduceDocStringLength(doc), bt1) # rows.append((docStr,)) tsa.append(('BOX', (0, lenRows), (-1, -1), 0.25, colors.black)) t = Table(rows, (12 * cm, )) tableStyle = TableStyle(tableStyleAttributes) t.setStyle(tableStyle) self.story.append(t) self.story.append(Spacer(1 * cm, 1 * cm))
def renderToc(self, tocpath, toc_entries): doc = SimpleDocTemplate(tocpath, pagesize=(pdfstyles.page_width, pdfstyles.page_height)) elements = [] elements.append(Paragraph(_('Contents'), pdfstyles.heading_style(mode='chapter', text_align='left'))) toc_table =[] styles = [] col_widths = self._getColWidths() for row_idx, (lvl, txt, page_num) in enumerate(toc_entries): if lvl == 'article': page_num = str(page_num) elif lvl == 'chapter': page_num = '<b>%d</b>' % page_num styles.append(('TOPPADDING', (0, row_idx), (-1, row_idx), 10)) elif lvl == 'group': page_num = ' ' styles.append(('TOPPADDING', (0, row_idx), (-1, row_idx), 10)) toc_table.append([ Paragraph(txt, pdfstyles.text_style(mode='toc_%s' % str(lvl), text_align='left')), Paragraph(page_num, pdfstyles.text_style(mode='toc_article', text_align='right')) ]) t = Table(toc_table, colWidths=col_widths) t.setStyle(styles) elements.append(t) doc.build(elements)
def SQL_to_table(fn): 'Convert a SQLITE db to a table object' data = SQL_to_2D_list(fn) # add blank column to the end for clean splitting between pages for i in range(len(data)): newrow = data[i] + [''] data[i] = newrow # Style Sheet style=[('VALIGN',(0,0),(-1,-1),'TOP'), ('ALIGN',(0,0),(0,-1),'CENTER'),#number col ('VALIGN',(0,0),(0,-1),'MIDDLE'),#number col ('ALIGN',(2,0),(-1,-1),'CENTER'),#answer col ('VALIGN',(2,0),(-1,-1),'MIDDLE'),#answer col ('RIGHTPADDING',(0,0),(-1,-1),5), ('LEFTPADDING',(0,0),(-1,-1),5), ('TOPPADDING',(0,0),(-1,-1),1), ('BOTTOMPADDING',(0,0),(-1,-1),1)] # special styles for i in range(0,len(data),3): style.append( ('SPAN',(-1,i),(-1,i+2)) ) # merge blank column rows style.append( ('SPAN',(1,i),(1,i+1)) ) # merge text rows style.append( ('GRID',(1,i),(-2,i+1),1,colors.black) ) # add grid lines style.append( ('BOX',(0,i),(0,i+1),1,colors.black) ) # grid around numbers style.append( ('BOX',(0,i+2),(-2,i+2),1,colors.black) ) # grid around separator style.append( ('TOPPADDING',(0,i+2),(-2,i+2),29) ) # Leave space for comments t = Table(data, colWidths=(25,355,26,26,26,26,26,1)) t.setStyle(TableStyle(style)) return t
def print_quote(self): """ Render the quote PDF """ buffer = self.buffer doc = SimpleDocTemplate(buffer, rightMargin=1 * inch, leftMargin=1 * inch, topMargin=2 * inch, bottomMargin=1 * inch, pagesize=self.pagesize, showBoundary=0) # Our container for 'Flowable' objects elements = [] # A large collection of style sheets pre-made for us stylesheet = getSampleStyleSheet() stylesheet.add(ParagraphStyle(name='centered', alignment=TA_CENTER)) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. project = get_object_or_404(Project, pk=self.pk) lineitems = project.line_item.all() # Parse lineitems and put into list [(name, description2),(name2, description2)] data = [('Name', 'Description', 'Unit Cost', 'Quantity', 'Total')] for lineitem in lineitems: if len(lineitem.description) > 63: lineitem.description = textwrap.fill(lineitem.description, 38) lineitem.description = "\n".join(lineitem.description.splitlines()) item = (Paragraph(lineitem.name, stylesheet['Normal']), lineitem.description, '$' + str(lineitem.price), lineitem.quantity, lineitem.tallys['total']) data.append(item) totalsData = [('','','','Sub-Total', project.sub_total),('','','','Discount', ((Decimal(project.discount) / 100) * project.sub_total)),('','','','Tax', project.tax), ('','','','Total', project.total)] table = Table(data, colWidths=(doc.width/5,2*doc.width/5,0.6667*doc.width/5,0.6667*doc.width/5,0.6667*doc.width/5)) table.setStyle(TableStyle([('INNERGRID', (0, 1), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.5, colors.black), ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'), ('BACKGROUND', (0, 0), (-1, 0), colors.gray)])) totalsTable = Table(totalsData, colWidths=(doc.width/5,2*doc.width/5,0.6667*doc.width/5,0.6667*doc.width/5,0.6667*doc.width/5)) totalsTable.setStyle(TableStyle([ ('LINEABOVE',(3,0),(4,0),1,colors.black), ('INNERGRID', (3, 0), (4, 3), 0.25, colors.black), ('BOX', (3, 0), (4, 3), 0.5, colors.black), ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'), ])) # Insert content tables and build doc elements.append(Spacer(1,.5*inch)) elements.append(table) elements.append(totalsTable) doc.build(elements, onFirstPage=self._header_footer, onLaterPages=self._header_footer) # Get the value of the BytesIO buffer and write it to the response. pdf = buffer.getvalue() buffer.close() return pdf
def __format_data(data): styles = getSampleStyleSheet() assets = data['assets'] liabilities = data['liabilities'] d = [['NR.\nCRT.', 'ELEMENTE DE ACTIV', 'VALORI\n(LEI)', 'ELEMENTE DE PASIV', 'VALORI\n(LEI)'], ['1.', Paragraph(u'Sold în casă', styles['Normal']), assets['cash'], Paragraph('Sold fond de rulment', styles['Normal']), liabilities['rulment']], ['2.', Paragraph(u'Sold conturi la bănci', styles['Normal']), assets['bank'], Paragraph(u'Sold fond de reparații', styles['Normal']), liabilities['repairs']], ['3.', Paragraph(u'Sume neachitate de proprietarii din asociație pentru lista de plată curentă', styles['Normal']), assets['apartment_pending'], Paragraph('Sold fond sume speciale', styles['Normal']), liabilities['special']], ['4.', Paragraph(u'Restanțe existente la data întocmirii acestei situații', styles['Normal']), assets['penalties_pending'], Paragraph('Soldul altor fonduri legal stabilite', styles['Normal']), '0'], ['5.', Paragraph(u'Debitori, alții decât mebrii asociației', styles['Normal']), '0', Paragraph('Furnizori pentru facturi neachitate', styles['Normal']), '0'], ['6.', Paragraph(u'Acte de plată pe luna în curs, nerepartizate proprietarilor', styles['Normal']), assets['outstanding_invoices'], Paragraph(u'Creditori diverși', styles['Normal']), liabilities['3rd party']], ['7.', Paragraph(u'Acte de plăți pentru cheltuielile aferente fondurilor de reparații, speciale, de penalizări care nu au fost încă scăzute din fondurile respective', styles['Normal']), '0', '', ''], ['', Paragraph(u'TOTAL PARTEA I', styles['Normal']), sum(assets.values()), Paragraph(u'TOTAL PARTEA II', styles['Normal']), sum(liabilities.values())] ] table = Table(d, colWidths=[1.3 * cm, 7 * cm, 4 * cm, 7 * cm, 4 * cm]) table.setStyle(TableStyle([ ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('ALIGN', (0, 0), (-1, 0), 'CENTER'), ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'), ('ALIGN', (0, 0), (0, -1), 'CENTER'), ('VALIGN', (0, 0), (0, -1), 'MIDDLE'), ('ALIGN', (2, 0), (2, -1), 'CENTER'), ('VALIGN', (2, 0), (2, -1), 'MIDDLE'), ('ALIGN', (4, 0), (4, -1), 'CENTER'), ('VALIGN', (4, 0), (4, -1), 'MIDDLE'), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black) ])) return table
def build_revisions_table(self): body_style = self.styles['BodyText'] self.styles.add(ParagraphStyle( name='BodyCentered', parent=body_style, alignment=TA_CENTER, )) centered = self.styles['BodyCentered'] header = ( 'Document Number', 'Title', 'Rev.', 'Status', 'RC') data = [header] for revision in self.revisions: data.append(( Paragraph(revision.document.document_number, body_style), Paragraph(revision.document.title, body_style), Paragraph(revision.name, centered), Paragraph(revision.status, centered), Paragraph(revision.get_final_return_code(), centered))) table = Table( data, hAlign='LEFT', colWidths=[70 * mm, 75 * mm, 10 * mm, 15 * mm, 10 * mm]) style = self.get_table_style() style.add('ALIGN', (0, 0), (-1, 0), 'CENTER') table.setStyle(style) return table
def create_table_graph(self, query_instance): """ create table graph for used in add_graphs method. Returns an image in bytes format. """ measurements = self.retrieve_measurements(query_instance) # TODO confirm title title = f'{query_instance.machine.machine_type} {query_instance.machine.name}'.upper( ) rows = self.format_table_data(measurements, title) styles = [ ('SPAN', (0, 0), (-1, 0)), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('BACKGROUND', (0, 0), (4, 1), TABLE_BLUE), ('GRID', (0, 0), (-1, -1), 0.25, black), ('FONTNAME', (0, 0), (0, -1), 'Arial-Bold'), ('FONTNAME', (0, 0), (4, 1), 'Arial-Bold'), ('FONTNAME', (1, 0), (-1, -1), 'Arial'), ] colors = self.create_row_colors(rows) styles += colors table = Table(rows, colWidths=[3 * cm]) table.setStyle(TableStyle(styles)) return table
def Naryad_Zakaz_PrintForm(ul,dom,date,date_str): day_task = GetListTaskDom(ul,dom,date) data = [['№пп','Наименование\nработ','Подъезд','Квартира','Примечание'], ] n = 1 elements = [] ### --- Имя файла для вывода --- FILE_NAME = os.getcwd()+'/tmp/'+str(time.time())+'.pdf' Font = ttfonts.TTFont('Arial','font/arial.ttf') Font2 = ttfonts.TTFont('ArialBD','font/arialbd.ttf') pdfmetrics.registerFont(Font) pdfmetrics.registerFont(Font2) style = getSampleStyleSheet() style.add(ParagraphStyle(name='Disp',wordWrap=True,fontName='ArialBD',fontSize=12,spaceAfter=5*mm,spaceBefore=5*mm,alignment=2)) style.add(ParagraphStyle(name='Naryad_Zakaz',wordWrap=True,fontName='ArialBD',fontSize=14,spaceAfter=5*mm,spaceBefore=5*mm,alignment=1)) style.add(ParagraphStyle(name='DateDom',wordWrap=True,fontName='ArialBD',fontSize=12,spaceAfter=5*mm,spaceBefore=5*mm,alignment=1)) style.add(ParagraphStyle(name='Table',wordWrap=True,fontName='Arial',fontSize=11,spaceAfter=1*mm,spaceBefore=1*mm,alignment=0)) doc = SimpleDocTemplate(FILE_NAME,topMargin=10*mm,bottomMargin=10*mm,leftMargin=10*mm,rightMargin=10*mm) for item in day_task: row = [n,Paragraph(item[9],style["Table"]),item[13],item[12],''] n = n + 1 data.append(row) t=Table(data) t.setStyle([('FONTNAME',(0,0),(-1,0),'ArialBD'), ('FONTSIZE',(0,0),(-1,0),11), ('ALIGN',(0,0),(-1,0),'CENTER'), ('VALIGN',(0,0),(-1,0),'MIDDLE'), ('GRID',(0,0),(-1,-1),0.25,colors.black), ('FONTNAME',(0,1),(-1,-1),'Arial'), ('FONTSIZE',(0,1),(-1,-1),11), ('ALIGN',(0,1),(0,-1),'CENTER'), ('ALIGN',(1,1),(-1,-1),'LEFT'), ('VALIGN',(0,1),(-1,-1),'TOP'), ]) elements.append(Paragraph('Наряд-Заказ',style["Naryad_Zakaz"])) elements.append(Paragraph('на выполнение работ по адресу: '+ul+' дом '+dom+' на '+date_str,style["DateDom"])) elements.append(t) elements.append(Paragraph('Диспетчер ООО "Артэкс"',style["Disp"])) doc.build(elements) os.system(PDFVIEW+" "+FILE_NAME+" &")
def signatures(font_size=None): d = [[u'PREȘEDINTE\n(numele și semnătura)', u'CENZOR\n(numele și semnătura)', u'ADMINISTRATOR\n(numele și semnătura)']] table = Table(d, colWidths=[7 * cm, 7 * cm, 7 * cm]) style = [('ALIGN', (0, 0), (-1, 0), 'CENTER'), ] if font_size: style.append(('FONTSIZE', (0, 0), (-1, -1), font_size)) table.setStyle(TableStyle(style)) return table
def showtable(self, ident, widths=None): if self.table_ident == ident: self._spacer() tbl = Table(self.table_data, colWidths=widths, repeatRows=1) tbl.setStyle(self.table_style) self.contents.append(tbl) self.table_ident = None self._spacer()
def _header_footer(self, canvas, doc): """ Renders a header and footer which will be inserted regardless of pdf method""" # Save the state of our canvas so we can draw on it canvas.saveState() stylesheet = getSampleStyleSheet() # Header logo = Image("http://www.fabco.la/fabco-seal-1.png", width=1.5*inch, height=1.5*inch) logo.hAlign = 'CENTER' stylesheet['BodyText'].fontSize = 10 stylesheet['BodyText'].leading = 14 stylesheet['BodyText'].leftIndent = 5 stylesheet['BodyText'].textColor = 'gray' FabcoAddress = "Fabco Art Services\n166 West Avenue 34\nLos Angeles CA 90031" project = get_object_or_404(Project, pk=self.pk) rightHeader = "Job #%s\nCompletion Date %s" % (project.project_id, project.due_date) # Build and format Left Header Table: leftHeaderData = [[FabcoAddress], [project.client.first_name + ' ' + project.client.last_name+'\n'+project.client.address.street+'\n'+project.client.address.city + ' ' + project.client.address.zip_code], ] leftHeaderTable = Table(leftHeaderData) leftHeaderTable.setStyle(TableStyle([ ('LEFTPADDING',(0,0),(0, 1),0), ('TOPPADDING',(0,1),(0, 1), 30), ('BOTTOMPADDING',(0,1),(0, 1), 0), ])) # Build and format Header Table: headerData = [([leftHeaderTable, logo, rightHeader])] headerTable = Table(headerData, colWidths=doc.width/3) headerTable.setStyle(TableStyle([ ('VALIGN', (0, 0), (-3, 0), 'MIDDLE'), ('VALIGN', (0, 0), (0, 0), 'TOP'), ('ALIGN',(1,0),(1,0),'CENTER'), ('ALIGN',(2,0),(2,0),'RIGHT'), ('LEFTPADDING',(0,0),(0,0),-1), ('RIGHTPADDING',(2,0),(2,0),-1), ])) # find required space | I don't really understand this.. w, h = headerTable.wrap(doc.width, doc.height) # render to canvas | I also don't really understand this.. headerTable.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin - doc.bottomMargin) # Footer footer = Paragraph('Client Signature: _________________________', stylesheet['Normal']) w, h = footer.wrap(doc.width, doc.bottomMargin) footer.drawOn(canvas, doc.leftMargin, doc.bottomMargin) # Release the canvas canvas.restoreState()
def post(self, request: WSGIRequest, *args, **kwargs): try: word_data = EngTestGenerator.generate_by_google_sheet_url( request.POST["url"], int(request.POST["startIdx"]), int(request.POST["endIdx"]), ) value_list = list(word_data.values()) random.shuffle(value_list) questionCount = int(request.POST["questionCount"]) response = HttpResponse(content_type="application/pdf") response[ "Content-Disposition"] = "attachment; filename=somefilename.pdf" elements = [] # kor = Korean: 'HYSMyeongJoStd-Medium', 'HYGothic-Medium' doc = SimpleDocTemplate( response, rightMargin=1 * cm, leftMargin=1 * cm, topMargin=1 * cm, bottomMargin=1 * cm, ) # 테이블 스타일 지정 2,3 번째 튜플 데이터는 해당 스타일의 적용 범위를 의미함 (cell 주소) # 모든 cell 에 스타일을 적용하려면 (0, 0), (-1, -1) 사용하면 됨 table_style = TableStyle([ ("FONT", (0, 0), (-1, -1), "HYSMyeongJoStd-Medium"), ("FONTSIZE", (0, 0), (-1, -1), 20), ("BOTTOMPADDING", (0, 0), (-1, -1), 15), ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black), # 테이블 내부 구분선 ("BOX", (0, 0), (-1, -1), 0.25, colors.black), # 테이블 외곽선 ]) # table = Table(value_list[:questionCount], colWidths=270, rowHeights=79) value_list = [ [1, "hello", "안녕하세요", 2, "dead", "죽었다"], [1, "hello", "안녕하세요", 2, "dead", "죽었다"], ] table = Table( data=value_list, colWidths=[50, 100, 150, 50, 100, 150], rowHeights=35, hAlign="CENTER", ) table.setStyle(table_style) elements.append(table) doc.build(elements) return response except Exception as e: return HttpResponseServerError(traceback.format_exc())
def print_statistics(self): buffer = self.buffer doc = SimpleDocTemplate(buffer, rightMargin=inch / 4, leftMargin=inch / 4, topMargin=inch / 2, bottomMargin=inch / 4, pagesize=self.pageSize) # Our container for 'Flowable' objects elements = [] # A large collection of style sheets pre-made for us styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='centered', alignment=TA_CENTER)) # Draw things on the PDF. Here's where the PDF generation happens. elements.append( Paragraph(self.statistics["field_text"], styles['Heading1'])) if self.statistics["field_type"] == 'NumberField': pieChart = PieChart(self.statistics["quintilesY"], self.statistics["quintilesX"]) else: pieChart = PieChart(self.statistics["total_per_option"], self.statistics["options"]) elements.append(pieChart) # Draw table rows = [["Field type", self.statistics["field_type"]], ["Answered fields", self.statistics["total_filled"]], ["Empty fields", self.statistics["total_not_filled"]], ["Required", self.statistics["required"]]] if self.statistics["field_type"] == 'NumberField': rows.append(["Mean", self.statistics["mean"]]) rows.append(["Total Mean", self.statistics["total_mean"]]) rows.append( ["Standard Deviation", self.statistics["standard_deviation"]]) rows.append([ "Total Standard Deviation", self.statistics["total_standard_deviation"] ]) table = Table(rows) table.setStyle( TableStyle([('GRID', (0, 0), (-1, -1), 0.25, colors.black)])) elements.append(table) doc.build(elements, onFirstPage=self._header_footer, onLaterPages=self._header_footer) # Get the value of the BytesIO buffer and write it to the response. pdf = buffer.getvalue() buffer.close() return pdf
def draw_contract_nb_table(self, canvas): data = [ ('Contract NB', self.transmittal.contract_number), ('Phase', ''), ] table = Table(data, hAlign='LEFT', colWidths=[25 * mm, 25 * mm]) table.setStyle(self.get_table_style()) table.wrapOn(canvas, 50 * mm, 50 * mm) table.drawOn(canvas, *self.coord(145, 55))
def draw_contract_nb_table(self, canvas): data = [ ('Contract NB', self.transmittal.contract_number), ('Phase', ''), ] table = Table(data, hAlign='LEFT', colWidths=[25 * mm, 25 * mm]) table.setStyle(self.get_table_style()) table.wrapOn(canvas, 50 * mm, 50 * mm) table.drawOn(canvas, *self.coord(145, 55))
def build_trs_meta(self): date = dateformat.format(self.revision.created_on, 'd/m/Y') data = [ ('Transmittal Number', self.document.document_number), ('Issue Date', date), ] table = Table(data, hAlign='LEFT', colWidths=[70 * mm, 60 * mm]) table.setStyle(self.get_table_style()) return table
def EgresoPDF(request): response = HttpResponse(content_type='application/pdf') buffer = BytesIO() pdf = canvas.Canvas(buffer) doc = SimpleDocTemplate( buffer, pagesizes=letter, rightMargin=30, leftMargin=30, topMargin=176.9, bottomMargin=50, paginate_by=0, ) ta_r = ParagraphStyle( 'parrafos', alignment=TA_RIGHT, fontSize=13, fontName="Helvetica-Bold", ) persona = [] styles = getSampleStyleSheet() # TABLA NUMERO 1 count = 0 data = [] filtro = Egreso.objects.all().order_by('-fecha', '-id') if (request.GET['tipo']): tipo = request.GET['tipo'] c = filtro.filter(concepto=tipo) else: c = filtro if c: for i in c: count = count + 1 data.append([ count, i.fecha, str(i.monto) + ' bs.', i.descripcion, i.concepto ]) else: return redirect('diezmo:egresos') x = Table(data, colWidths=[35, 85, 80, 200, 80]) x.setStyle( TableStyle([ ('GRID', (0, 0), (12, -1), 1, colors.black), ('ALIGN', (0, 0), (3, -1), 'CENTER'), ('FONTSIZE', (0, 0), (4, -1), 8), ])) persona.append(x) doc.build(persona, onFirstPage=HeaderFooterEgreso, onLaterPages=HeaderFooterEgreso, canvasmaker=NumberedCanvas) response.write(buffer.getvalue()) buffer.close() return response
def reporteContable(request): #suma = Pago.objects.all().aggregate(s = Sum('montoPago')) #valor = suma['s'] cursor = connection.cursor() cursor.execute( " select SUM(p.\"montoPago\") as suma from conntabilidad_pago as p where TO_DATE(to_char(p.\"fechaPago\",'YYYY-MM-DD'),'YYYY-MM-DD') = current_date " ) lista = cursor.fetchall() l = lista[0] valor = l[0] response = HttpResponse(content_type='application/pdf') buffer = BytesIO() pdf = SimpleDocTemplate( buffer, pagesize=letter, title="Reporte de Ingresos", ) style = getSampleStyleSheet() versuma = Paragraph('Total de Ingresos: ' + str(valor), style['Heading3']) elementos = [] img1 = Image(0, 0, 200, 60, "CEM/imagenes/logo.PNG") dibujo = Drawing(30, 30) dibujo.add(img1) titulo = Paragraph('Reporte de Ingresos', style['Heading1']) #table encabezados = (' Doctor', '', 'Monto') #info_tabla = [(pago.idDoctor, pago.montoPago) for pago in Pago.objects.all()] #2da alternativa cursor2 = connection.cursor() cursor2.execute( " select d.\"primerNombreDoctor\",d.\"primerApellidoDoctor\",SUM(p.\"montoPago\") as total from \"CEM_doctor\" as d inner join conntabilidad_pago as p on d.id = p.\"idDoctor_id\" where TO_DATE(to_char(p.\"fechaPago\",'YYYY-MM-DD'),'YYYY-MM-DD') = current_date group by d.\"primerApellidoDoctor\",d.\"primerNombreDoctor\" " ) info_tabla = cursor2.fetchall() tabla = Table([encabezados] + info_tabla, colWidths=[100, 100, 150]) tabla.setStyle( TableStyle([('GRID', (0, 0), (3, -1), 0.5, colors.dodgerblue), ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue), ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue)])) """p=0 for i in Pago.objects.all(): p = p + i.montoPago versuma = Paragraph(str(p),style['BodyText'])""" elementos.append(dibujo) elementos.append(titulo) elementos.append(Spacer(0, 15)) elementos.append(tabla) elementos.append(Spacer(0, 15)) elementos.append(versuma) pdf.build(elementos) response.write(buffer.getvalue()) buffer.close() return response
def _make(self, rows): ta = Table(rows) ta.hAlign = 'LEFT' self._set_column_widths(ta) self._set_row_heights(ta, rows) s = self._get_style(rows) ta.setStyle(s) return ta
def print_invoice_data(self): elements = [] invoice_data = [] if self.purchase_order: invoice_data.append(('', '', self.purchase_order)) else: invoice_data.append(('', '', '')) issue_date = self.date.strftime('%B %d, %Y') invoice_data.append(('', self.get_client_name, issue_date)) start_date = self.start_date.strftime('%m/%d/%Y') end_date = self.end_date.strftime('%m/%d/%Y') dates = start_date + ' - ' + end_date invoice_data.append(('', self.address, dates)) invoice_data.append(('', self.business_style, '')) invoice_data.append(('', self.client_contact, '')) invoice_table = Table(invoice_data, colWidths=[1.8 * cm, 12.8 * cm, 4.4 * cm], rowHeights=17) fontsize = ('FONTSIZE', (0, 0), (2, len(invoice_data) - 1), 11) fontstyle = ('FONT', (0, 0), (2, len(invoice_data) - 1), 'Times-Bold') po_padding = ('BOTTOMPADDING', (0, 0), (2, 0), 17) styles = [fontsize, fontstyle, po_padding] if len(self.address) > 70: styles.append(('FONTSIZE', (0, 2), (1, 2), 9.5)) invoice_table.setStyle(TableStyle(styles)) item_data = [] row = 0 for i in self.invoiceitem_set.filter(is_active=True).order_by('pk'): amount = '{:,}'.format(i.amount) if i.amount else None if i.type == 'text': item_data.append(('', i.description, '', '', '', amount)) else: rate = '{:,}'.format(i.rate) if i.rate else None shift = i.equivalent_guard_shift \ if i.equivalent_guard_shift else None hours = '{:,} hrs'.format(i.hours) if i.hours else None item_data.append( ('', i.description, shift, hours, rate, amount)) row += 1 item_table = Table(item_data, colWidths=[ 1.8 * cm, 7.25 * cm, 2.3 * cm, 2.45 * cm, 2.35 * cm, 2.3 * cm ], rowHeights=18) fontsize_items = ('FONTSIZE', (0, 0), (5, len(item_data) - 1), 11) fontstyle_items = ('FONT', (0, 0), (5, len(item_data) - 1), 'Times-Roman') align_amount = ('ALIGN', (5, 0), (5, len(item_data) - 1), "RIGHT") styles = [fontsize_items, fontstyle_items, align_amount] item_table.setStyle(TableStyle(styles)) elements.append(invoice_table) elements.append(Spacer(0, 7.6 * cm)) elements.append(item_table) return elements
def build_ack_table(self): data = [ ('Name:', 'Date:'), ('Position:', 'Signature:') ] table = Table(data, hAlign='LEFT', colWidths=[90 * mm, 90 * mm]) style = self.get_table_style() style.add('INNERGRID', (0, 0), (-1, -1), 0, colors.white) table.setStyle(style) return table
def generateTable(data): table = Table(data, colWidths=90, rowHeights=30) table.setStyle(([ ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'), ('BLACK', (1, 1), (-2, -2), colors.black), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ])) return table
def cabecera(self, request, fecha, pdf): usuario = request.user.get_full_name() #Utilizamos el archivo logo_django.png que está guardado en la carpeta media/imagenes archivo_imagen = settings.MEDIA_ROOT + 'Logo.png' #Definimos el tamaño de la imagen a cargar y las coordenadas correspondientes pdf.drawImage(archivo_imagen, 30, 700, 120, 90, preserveAspectRatio=True ) pdf.setFont("Helvetica", 9) # pdf.drawString(550, 770, u"%s" %time.strftime("%x")) pdf.drawString(500, 760, u"Fecha: %s/%s/%s" %(fecha.day, fecha.month, fecha.year) ) pdf.drawString(500, 750, u"Hora: %s:%s" %(fecha.hour, fecha.minute) ) #Creamos una tupla de encabezados para neustra tabla encabezados = ['Estado de Cuenta'.upper()] #Creamos una lista de tuplas que van a contener a las personas detalles = [ ('%s, Edificio %s, Apartamento %s' %(usuario, p.edificio, p.no_apartamento)) for p in Residente.objects.filter(id=request.user.id) ] #Establecemos el tamaño de cada una de las columnas de la tabla detalle_orden = Table([encabezados] + [detalles], rowHeights=50, colWidths=[575] ) #Aplicamos estilos a las celdas de la tabla detalle_orden.setStyle( TableStyle( [ #La primera fila(encabezados) va a estar centrada ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (0, -1), 'CENTER'), ('FONTSIZE', (0, 0), (-1, -1), 12), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (0, 0), 'CENTER'), ('FONTSIZE', (0, 0), (-1, 0), 16), ('TEXTCOLOR', (0, 1), (-1, -1), colors.black), ] ) ) #Establecemos el tamaño de la hoja que ocupará la tabla detalle_orden.wrapOn(pdf, 1000, 800) #Definimos la coordenada donde se dibujará la tabla detalle_orden.drawOn(pdf, 15, 660)
def pdf_testPlatypus(self, fpath, txt, pkg=None, tbl=None, **kwargs): self.app.setThermo('build_pdf', 0, 'Preparo elaborazione', 10, command='init') PAGE_HEIGHT = A4[1]; PAGE_WIDTH = A4[0] styles = getSampleStyleSheet() def myLaterPages(canvas, doc): canvas.saveState() canvas.setFont('Times-Roman', 9) canvas.drawString(cm, 2 * cm, "Page %d" % (doc.page)) canvas.restoreState() doc = SimpleDocTemplate(fpath) Story = [Spacer(1, 4 * cm)] style = styles["Normal"] colWidths = (3 * cm, 1 * cm, 1 * cm, 4 * cm, 5 * cm) tstyle = TableStyle([('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey), ('GRID', (0, 0), (-1, -1), 0.25, colors.black), #('FONTSIZE', (0,0), (-1,-1), 7) ]) packages = [o for p, o in self.db.packages.items() if not pkg or p == pkg] self.app.setThermo('build_pdf', maximum_1=len(packages) + 1) for i, pobj in enumerate(packages): tables = [o for t, o in pobj.tables.items() if not tbl or t == tbl] self.app.setThermo('build_pdf', i, pobj.name, progress_2=0, message_2='', maximum_2=len(tables)) for k, tobj in enumerate(tables): if self.app.setThermo('build_pdf', progress_2=k, message_2=tobj.fullname) == 'stop': self.app.setThermo('build_pdf', command='stopped') return p = Paragraph(tobj.fullname, style) Story.append(p) Story.append(Spacer(1, 1 * cm)) data = [['Name', 'Type', 'Size', 'Name Long', 'Relations']] for cobj in tobj.columns.values(): rel = '' if cobj.relatedColumn(): rel = cobj.relatedColumn().fullname elif cobj.name == tobj.pkey and tobj.relatingColumns: rel = Paragraph('<br/>'.join(tobj.relatingColumns), style) data.append([cobj.name, cobj.attributes.get('dtype', ''), cobj.attributes.get('size', ''), self._(cobj.attributes.get('name_long', '')), rel]) t = Table(data, colWidths=colWidths) t.setStyle(tstyle) Story.append(t) Story.append(Spacer(1, 1 * cm)) self.app.setThermo('build_pdf', i + 1, "Impaginazione PDF", progress_2=0, message_2='', maximum_2=0) doc.build(Story, onFirstPage=myLaterPages, onLaterPages=myLaterPages) self.app.setThermo('build_pdf', command='end')
def tabla(self, datos, c): encabezados = [["Nombre", "Primer Apellido", "Sergundo Apellido", "Correo", "Nombre Mascota", "Tipo", "Peso"]] width, height = A4 tabla = Table(encabezados+datos, colWidths=30*mm) tabla.setStyle([("VALIGN", (0,0), (-1,-1), "MIDDLE"), ("ALIGN", (0,0), (-1,-1), "CENTER"), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('FONT', (0,0), (-1,0), 'Times-Bold'), ('FONTSIZE', (0,0),(-1,-1), 10)]) tabla.wrapOn(c, width, height) tabla.drawOn(c, 0, 520)
def set_common_per_page(self, canvas, doc): PAGE_WIDTH, PAGE_HEIGHT = pagesizes.A4 PDF_HEADER_FONT_SIZE = 8 canvas.saveState() # header string = self.set_header_string() canvas.setFont(self.FONT_MEIRYO, PDF_HEADER_FONT_SIZE) canvas.drawCentredString((PAGE_WIDTH / 2.0), (PAGE_HEIGHT - 20), string) # footer string = self.set_footer_string() canvas.setFont(self.FONT_MEIRYO, PDF_HEADER_FONT_SIZE) canvas.drawCentredString((PAGE_WIDTH / 2.0), 20, string) # 左上: アイコン image_path = django_settings.PDF_IMAGE_DIR + 'apple-icon-180x180.png' canvas.drawImage(image_path, 10*mm, 285*mm, width=10*mm, height=10*mm, preserveAspectRatio=True, mask=[0, 0, 0, 0, 0, 0]) # 右上: TLP表記 string = 'TLP: %s' % (self.feed.tlp.upper()) # Tableにて実装 data = [[string], ] table = Table(data) if self.feed.tlp.upper() == 'RED': color = '#FF0033' elif self.feed.tlp.upper() == 'AMBER': color = '#FFC000' elif self.feed.tlp.upper() == 'GREEN': color = '#33FF00' else: color = '#FFFFFF' table.setStyle(TableStyle([ # 背景色は黒 ('BACKGROUND', (0, 0), (-1, -1), colors.black), # テキスト色はTLPによって異なる ('TEXTCOLOR', (0, 0), (-1, -1), color), # 表で使うフォントとそのサイズを設定 ('FONT', (0, 0), (-1, -1), self.FONT_MEIRYO, 9), # ('FONT', (0, 0), (-1, -1), 'CJK', 9), # 四角に罫線を引いて、0.5の太さで、色は黒 ('BOX', (0, 0), (-1, -1), 1, colors.black), # 四角の内側に格子状の罫線を引いて、0.25の太さで、色は赤 ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), # セルの縦文字位置を、TOPにする ('VALIGN', (0, 0), (-1, -1), 'TOP'), ])) # 配置位置 table.wrapOn(canvas, 180*mm, 287*mm) table.drawOn(canvas, 180*mm, 287*mm) canvas.restoreState()
def build_trs_meta(self): date = dateformat.format( self.revision.created_on, 'd/m/Y') data = [ ('Transmittal Number', self.document.document_number), ('Issue Date', date), ] table = Table(data, hAlign='LEFT', colWidths=[70 * mm, 60 * mm]) table.setStyle(self.get_table_style()) return table
def _create_especifications_table(data): """ return basic table populated by the data it is passed. """ styles = [('VALIGN', (0, 0), (1, 3), 'MIDDLE'), ('ALIGN', (0, 0), (1, 3), 'CENTER'), ('ALIGN', (2, 0), (2, 3), 'LEFT')] table = Table(data, colWidths=[2 * cm, 2 * cm, 10 * cm]) table.setStyle(TableStyle(styles)) return table
def Stamp(buff,d_id,person): ### --- Список согласователей --- per = FIO_Job_Person(person) Font1 = ttfonts.TTFont('PT','kis/fonts/PTC55F.ttf') Font2 = ttfonts.TTFont('PTB','kis/fonts/PTC75F.ttf') Font3 = ttfonts.TTFont('PTI','kis/fonts/PTS56F.ttf') pdfmetrics.registerFont(Font1) pdfmetrics.registerFont(Font2) pdfmetrics.registerFont(Font3) style = getSampleStyleSheet() style.add(ParagraphStyle(name='Head',wordWrap=True,fontName='PTB',fontSize=14,spaceAfter=5*mm,spaceBefore=5*mm,alignment=1)) style.add(ParagraphStyle(name='DepName',wordWrap=True,fontName='PTB',fontSize=10,spaceAfter=5*mm,spaceBefore=5*mm,alignment=1)) style.add(ParagraphStyle(name='Data',wordWrap=True,fontName='PT',fontSize=8,spaceAfter=1*mm,spaceBefore=1*mm,alignment=0)) doc = SimpleDocTemplate(buff,topMargin=10*mm,bottomMargin=10*mm,leftMargin=20*mm,rightMargin=10*mm) elements = [] elements.append(Paragraph('КИС Договоры заявки',style["Head"])) elements.append(Paragraph('Номер заявки '+str(d_id),style["Head"])) Tdata = [['Участники договорной\nработы','ФИО лица,\nзавизировавшего договор'],] author = per[0] Tdata.append([Paragraph(u'Ответственный исполнитель, '+author[0],style["Data"]),Paragraph(author[1],style["Data"])],) for item in per[1:]: Tdata.append([Paragraph(item[0],style["Data"]),Paragraph(item[1],style["Data"])],) TableHead=Table(Tdata) TableHead.setStyle([('FONTNAME',(0,0),(-1,-1),'PTB'), ('FONTSIZE',(0,0),(-1,-1),10), ('ALIGN',(0,0),(-1,0),'CENTER'), ('ALIGN',(0,1),(-1,-1),'LEFT'), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('GRID',(0,0),(-1,-1),0.25,colors.black), ]) elements.append(TableHead) doc.build(elements) return buff
def draw_totals(self, y_pos): """ Draws the boxes containing the totals and the tax id. """ totals_data = [[(_('Total')), self.total_cost], [(_('Payment Received')), self.payment_received], [(_('Balance')), self.balance]] if self.is_invoice: # only print TaxID if we are generating an Invoice totals_data.append([ '', '{tax_label}: {tax_id}'.format(tax_label=self.tax_label, tax_id=self.tax_id) ]) heights = 8 * mm totals_table = Table(totals_data, 40 * mm, heights) styles = [ # Styling for the totals table. ('ALIGN', (0, 0), (-1, -1), 'RIGHT'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), # Styling for the Amounts cells # NOTE: since we are not printing the TaxID for Credit Card # based receipts, we need to change the cell range for # these formatting rules ('RIGHTPADDING', (-1, 0), (-1, -2 if self.is_invoice else -1), 7 * mm), ('GRID', (-1, 0), (-1, -2 if self.is_invoice else -1), 3.0, colors.white), ('BACKGROUND', (-1, 0), (-1, -2 if self.is_invoice else -1), '#EEEEEE'), ] totals_table.setStyle(TableStyle(styles)) __, rendered_height = totals_table.wrap(0, 0) left_padding = 97 * mm if y_pos - (self.margin + self.min_clearance) <= rendered_height: # if space left on page is smaller than the rendered height, render the table on the next page. self.prepare_new_page() totals_table.drawOn(self.pdf, self.margin + left_padding, self.second_page_start_y_pos - rendered_height) return self.second_page_start_y_pos - rendered_height - self.min_clearance else: totals_table.drawOn(self.pdf, self.margin + left_padding, y_pos - rendered_height) return y_pos - rendered_height - self.min_clearance
def _build_recap(_recap_date, _recap_ref, recaps): """ """ elements = [] _intro = Table([[ u"Veuillez trouver ci-joint le récapitulatif des factures ainsi que le montant total à payer"]], [10 * cm, 5 * cm], 1 * [0.5 * cm], hAlign='LEFT') elements.append(_intro) elements.append(Spacer(1, 18)) data = [] i = 0 data.append(("N d'ordre", u"Note no°", u"Nom et prénom", "Montant" )) total = 0.0 _invoice_nrs = ""; for recap in recaps: i+=1 data.append((i, recap[0], recap[1], recap[2])) total = decimal.Decimal(total) + decimal.Decimal(recap[2]) _invoice_nrs += "-" + recap[0] data.append(("", "", u"à reporter", round(total, 2), "")) table = Table(data, [2*cm, 3*cm , 7*cm, 3*cm], (i+2)*[0.75*cm] ) table.setStyle(TableStyle([('ALIGN',(1,1),(-2,-2),'LEFT'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('FONTSIZE', (0,0), (-1,-1), 9), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ])) elements.append(table) elements.append(Spacer(1, 18)) elements.append(Spacer(1, 18)) _infos_iban = Table([["Lors du virement, veuillez indiquer la r" + u"é" + "f" + u"é" + "rence: %s " % _recap_ref]], [10 * cm], 1 * [0.5 * cm], hAlign='LEFT') _date_infos = Table([["Date facture : %s " % _recap_date]], [10 * cm], 1 * [0.5 * cm], hAlign='LEFT') elements.append(_date_infos) elements.append(Spacer(1, 18)) elements.append(_infos_iban) elements.append(Spacer(1, 18)) _total_a_payer = Table([["Total "+ u"à"+ " payer:", "%10.2f Euros" % total]], [10*cm, 5*cm], 1*[0.5*cm], hAlign='LEFT') elements.append(_total_a_payer) elements.append(Spacer(1, 18)) _infos_iban = Table([[u"Numéro IBAN: %s" % config.MAIN_BANK_ACCOUNT]], [10*cm], 1*[0.5*cm], hAlign='LEFT') elements.append( _infos_iban ) return elements
def front_page(self, pagetitle): # Front page logo = self._logo("CVE") now = datetime.now() date_time = now.strftime("%d %B %Y at %H:%M:%S") front_page = [ [logo], [Paragraph(pagetitle, self.h1)], [Paragraph("Report generated on " + date_time, self.h3)], ] tbl = Table(front_page, colWidths=10 * cm) tbl.setStyle(self.frontPageStyle) self.contents.append(tbl) self.pagebreak()
def _create_footer_table(): """ create table to manage elements in footer. """ data = [[LINE_ONE], [LINE_TWO], [LINE_THREE]] styles = [('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (-1, -1), 'CENTER')] table = Table(data, colWidths=[18 * cm], rowHeights=[0.5 * cm, 0.4 * cm, 0.4 * cm]) table.setStyle(TableStyle(styles)) return table
def get_report_story(self, **kwargs): story = [] data = [[Paragraph(dummy_text, self.styles["line_data_large"])]] t = Table(data, colWidths=(9 * cm)) t.setStyle( TableStyle([ ("INNERGRID", (0, 0), (0, 1), 0.25, colors.black), ("INNERGRID", (0, 2), (0, 3), 0.25, colors.black), ])) t.hAlign = "RIGHT" story.append(t) return story
def _build_recap(_recap_date, _recap_ref, recaps): """ """ elements = [] _intro = Table([["Veuillez trouver ci-joint le r"+ u"é"+ "capitulatif des factures ainsi que le montant total " + u"à" +" payer"]], [10*cm, 5*cm], 1*[0.5*cm], hAlign='LEFT') elements.append(_intro) elements.append(Spacer(1, 18)) data = [] i = 0 data.append(("N d'ordre", u"Note no°", u"Nom et prénom", "Montant" )) total = 0.0 _invoice_nrs = ""; for recap in recaps: i+=1 data.append((i, recap[0], recap[1], recap[2])) total = decimal.Decimal(total) + decimal.Decimal(recap[2]) _invoice_nrs += "-" + recap[0] data.append(("", "", u"à reporter", round(total, 2), "")) table = Table(data, [2*cm, 3*cm , 7*cm, 3*cm], (i+2)*[0.75*cm] ) table.setStyle(TableStyle([('ALIGN',(1,1),(-2,-2),'LEFT'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('FONTSIZE', (0,0), (-1,-1), 9), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ])) elements.append(table) elements.append(Spacer(1, 18)) elements.append(Spacer(1, 18)) _infos_iban = Table([["Lors du virement, veuillez indiquer la r" + u"é" + "f" + u"é" + "rence: %s " % _recap_ref]], [10 * cm], 1 * [0.5 * cm], hAlign='LEFT') _date_infos = Table([["Date facture : %s " % _recap_date]], [10 * cm], 1 * [0.5 * cm], hAlign='LEFT') elements.append(_date_infos) elements.append(Spacer(1, 18)) elements.append(_infos_iban) elements.append(Spacer(1, 18)) _total_a_payer = Table([["Total "+ u"à"+ " payer:", "%10.2f Euros" % total]], [10*cm, 5*cm], 1*[0.5*cm], hAlign='LEFT') elements.append(_total_a_payer) elements.append(Spacer(1, 18)) _infos_iban = Table([["Num" + u"é" + "ro IBAN: LU55 0019 4555 2516 1000 BCEELULL"]], [10*cm], 1*[0.5*cm], hAlign='LEFT') elements.append( _infos_iban ) return elements
def razas(self, pdf): #Se crea una lista de tuplas que van a contener los datos de todos los animales encabezados = ('Codigo', 'Nombre') parametros = [(p.id, p.nombre) for p in Raza.objects.all()] t = Table([encabezados] + parametros) 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.green)])) #Establecemos el tamaño de la hoja que ocupará la tabla t.wrapOn(pdf, 640, 480) #Definimos la coordenada donde se dibujará la tabla t.drawOn(pdf, 200, 200)
def build_way_of_transmission(self): data = [ ('Way of transmission', ''), ('EDMS', 'X'), ('Email', ''), ('USB Key', ''), ('Post', ''), ('Other', ''), ] table = Table(data, hAlign='LEFT', colWidths=[70 * mm, 20 * mm]) style = self.get_table_style() style.add('SPAN', (0, 0), (1, 0)) style.add('ALIGN', (0, 0), (0, 0), 'CENTER') style.add('ALIGN', (1, 0), (1, -1), 'CENTER') table.setStyle(style) return table
def draw_totals(self, y_pos): """ Draws the boxes containing the totals and the tax id. """ totals_data = [ [(_('Total')), self.total_cost], [(_('Payment Received')), self.payment_received], [(_('Balance')), self.balance] ] if self.is_invoice: # only print TaxID if we are generating an Invoice totals_data.append( ['', u'{tax_label}: {tax_id}'.format(tax_label=self.tax_label, tax_id=self.tax_id)] ) heights = 8 * mm totals_table = Table(totals_data, 40 * mm, heights) styles = [ # Styling for the totals table. ('ALIGN', (0, 0), (-1, -1), 'RIGHT'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), # Styling for the Amounts cells # NOTE: since we are not printing the TaxID for Credit Card # based receipts, we need to change the cell range for # these formatting rules ('RIGHTPADDING', (-1, 0), (-1, 2), 7 * mm), ('GRID', (-1, 0), (-1, 2), 3.0, colors.white), ('BACKGROUND', (-1, 0), (-1, 2), '#EEEEEE'), ] totals_table.setStyle(TableStyle(styles)) __, rendered_height = totals_table.wrap(0, 0) left_padding = 97 * mm if y_pos - (self.margin + self.min_clearance) <= rendered_height: # if space left on page is smaller than the rendered height, render the table on the next page. self.prepare_new_page() totals_table.drawOn(self.pdf, self.margin + left_padding, self.second_page_start_y_pos - rendered_height) return self.second_page_start_y_pos - rendered_height - self.min_clearance else: totals_table.drawOn(self.pdf, self.margin + left_padding, y_pos - rendered_height) return y_pos - rendered_height - self.min_clearance
def legend(): 'Description of answer abreviations' data = [[p('Strongly Agree'),'SA'], [p('Agree'),'A'], [p('Disagree'),'D'], [p('Strongly Disagree'),'SD'], [p('Do Not Know / Neutral'), 'DNK']] style = [('BACKGROUND',(0,0),(1,0),'rgb(215,255,200)'), ('BACKGROUND',(0,1),(1,1),'rgb(200,215,255)'), ('BACKGROUND',(0,2),(1,2),'rgb(255,250,180)'), ('BACKGROUND',(0,3),(1,3),'rgb(255,200,200)'), ('BACKGROUND',(0,4),(1,4),'rgb(235,240,250)'), ('GRID',(0,0),(-1,-1),1,colors.black), ('BOX',(0,0),(-1,-1),2,colors.black)] t = Table(data,colWidths=(130,50)) t.setStyle(style) return t
def render(self, rowsets): """Return the data as a binary string holding a PDF""" # Start by creating the table headers rowtables = [] if self.headers: for headerrow in self.headers: widths = [headercolumn.style.width for headercolumn in headerrow] # Let ReportLab calculate the width of the last column # so that it occupies the total remaining open space widths[-1] = None headertable = Table([[Paragraph(headercolumn.title, self.headercellstyle) for headercolumn in headerrow]], style=self.tablebasestyle, colWidths=widths) headertable.setStyle(self.tablerowstyle) headertable.setStyle(self.tableheaderstyle) rowtables.append([headertable]) # Then create a table to hold the contents of each line for rowset in rowsets: subrowtables = [] if isinstance(rowset, TableRow): rowset = [rowset] for subrow in rowset: subrowtable = Table([[self._rendercell(cell) for cell in subrow]], style=self.tablebasestyle, colWidths=[cell.style.width for cell in subrow]) subrowtable.setStyle(self.tablerowstyle) subrowtables.append([subrowtable]) rowtable = Table(subrowtables, style=self.tablebasestyle) rowtables.append([rowtable]) # Wrap all of those rows into an outer table parenttable = Table(rowtables, style=self.tablebasestyle, repeatRows=1) parenttable.setStyle(self.tableparentstyle) # Finally, build the list of elements that the table will # comprise components = [] if self.title: components.append(Paragraph(self.title, self.titlestyle)) if self.explanation: components.extend([Spacer(1, .2 * inch), Paragraph(self.explanation, self.explanationstyle)]) components.extend([Spacer(1, .3 * inch), parenttable]) # Compile the whole thing and return the results stringbuf = StringIO.StringIO() doc = SimpleDocTemplate(stringbuf, bottomMargin=.5 * inch, topMargin=.5 * inch, rightMargin=.5 * inch, leftMargin=.5 * inch) doc.build(components) return stringbuf.getvalue()
def getfile(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="raport.pdf"' elements = [] doc = SimpleDocTemplate(response, rightMargin=0, leftMargin=1, topMargin=2 * cm, bottomMargin=0) data=[] table_tyle = [] index = 0 for o in Order.objects.raw("""SELECT o.`id`, p.`Name`, o.`Number`, o.`Date`, s.`Name` as n , s.`City` , s.`Surname`, s.`Address`, s.`Country` FROM `shop_order` o INNER JOIN `shop_product` p ON ( o.`Product_id` = p.`id`) INNER JOIN `shop_bought` b ON ( o.`Container_id` = b.`basket_ptr_id`) INNER JOIN `shop_shippinginformation` s ON ( b.`ShippingInformation_id` = s.`id`) WHERE o.`Container_id` IN (SELECT U0.`basket_ptr_id` FROM `shop_bought` U0 INNER JOIN `shop_shoppinglist` U1 ON (U0.`ShoppingList_id` = U1.`id`) INNER JOIN `shop_useraccount` U2 ON (U1.`id` = U2.`ShoppingList_id`) WHERE NOT (U2.`id` IS NULL))"""): table_tyle.append(('TEXTCOLOR',(0,index),(2,index),colors.green)) table_tyle.append(('BACKGROUND',(0,index),(2,index),colors.beige)) data.append(('Product','Number','Date')) index = index+ 1 table_tyle.append(('BACKGROUND',(0,index),(2,index),colors.azure)) data.append((o.Name[:15], o.Number,o.Date.strftime("%d/%m/%Y %H:%M:%S"))) index = index+ 1 table_tyle.append(('TEXTCOLOR',(0,index),(0,index),colors.green)) table_tyle.append(('BACKGROUND',(0,index),(0,index),colors.azure)) index = index+ 1 table_tyle.append(('BACKGROUND',(0,index),(4,index),colors.azure)) data.append(('Address:',)) data.append((o.n,o.Surname, o.City, o.Address, o.Country)) index = index+ 1 table = Table(data, colWidths=100, rowHeights=20) table.setStyle(TableStyle(table_tyle)) elements.append(table) doc.build(elements) return response
def add_image(self, src, width, height, align=CENTER, caption=None): if src.split(".")[-1] in ["png", "PNG"]: try: f = open(src, 'rb') data = StringIO(f.read()) except: return else: img = Image(data, width, height) f.close() else: img = Image(src, width, height) img.hAlign = align if caption: caption_p = Paragraph(caption, self.theme.paragraph_centered) image_table = Table([[img], [caption_p]], width) image_table.setStyle(TableStyle([('ALIGN',(-1,-1),(-1,-1), 'CENTER')])) self.add(image_table) else: self.add(img)
def _build_recap(recaps): """ """ elements = [] data = [] i = 0 data.append(("No d'ordre", u"Note no°", u"Nom et prénom", "Montant", u"réservé à la caisse")) total = 0.0 #import pydevd; pydevd.settrace() for recap in recaps: i+=1 data.append((i, recap[0], recap[1], recap[2], "")) total = decimal.Decimal(total) + decimal.Decimal(recap[2]) data.append(("", "", u"à reporter", round(total, 2), "")) table = Table(data, [2*cm, 2*cm , 8*cm, 3*cm, 3*cm], (i+2)*[0.75*cm] ) table.setStyle(TableStyle([('ALIGN',(1,1),(-2,-2),'LEFT'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('FONTSIZE', (0,0), (-1,-1), 9), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ])) elements.append(table) return elements
def draw_totals(self, y_pos): """ Draws the boxes containing the totals and the tax id. """ totals_data = [ [(_('Total')), self.total_cost], [(_('Payment Received')), self.payment_received], [(_('Balance')), self.balance], ['', '{tax_label}: {tax_id}'.format(tax_label=self.tax_label, tax_id=self.tax_id)] ] heights = 8 * mm totals_table = Table(totals_data, 40 * mm, heights) totals_table.setStyle(TableStyle([ # Styling for the totals table. ('ALIGN', (0, 0), (-1, -1), 'RIGHT'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), # Styling for the Amounts cells ('RIGHTPADDING', (-1, 0), (-1, -2), 7 * mm), ('GRID', (-1, 0), (-1, -2), 3.0, colors.white), ('BACKGROUND', (-1, 0), (-1, -2), '#EEEEEE'), ])) __, rendered_height = totals_table.wrap(0, 0) left_padding = 97 * mm if y_pos - (self.margin + self.min_clearance) <= rendered_height: # if space left on page is smaller than the rendered height, render the table on the next page. self.prepare_new_page() totals_table.drawOn(self.pdf, self.margin + left_padding, self.second_page_start_y_pos - rendered_height) return self.second_page_start_y_pos - rendered_height - self.min_clearance else: totals_table.drawOn(self.pdf, self.margin + left_padding, y_pos - rendered_height) return y_pos - rendered_height - self.min_clearance
def body_1(start, end,event_time): #Body data= [['No.', 'Name', 'Cat II', 'Cat III']] for i in range(start,end): #Generate Transaction Id transaction_id = str(event_id)+event_date+event_time+str(i) transaction_id = filter(str.isalnum, str(transaction_id)) luhn = generate(transaction_id) transaction_id = str(transaction_id)+luhn data.append([str(i)+','+luhn,'','','']) ##### tstyle = [('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black),] t = Table(data, colWidths=(3*cm, 4*cm, 6*cm, 6*cm)) t.setStyle(TableStyle(tstyle)) t.wrapOn(c, 1*cm, 0*cm) t.drawOn(c, 1*cm, 1*cm) c.showPage()