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 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 _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 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 draw_demographics(self, story, **kwargs): try: assignment = fill(self.assignment, width=80) except NotAllowed: assignment = "*****************" rows = [ ["Subject:", self.subject_identifier], [ "Gender/Age:", f"{self.registered_subject.get_gender_display()} {self.age}", ], ["Weight:", f"{self.weight_at_timepoint} kg"], [ "Study site:", f"{self.registered_subject.site.id}: " f"{self.registered_subject.site.name.title()}", ], [ "Randomization date:", self.registered_subject.randomization_datetime.strftime( "%Y-%m-%d %H:%M"), ], ["Assignment:", assignment], ] t = Table(rows, (4 * cm, 14 * cm)) self.set_table_style(t, bg_cmd=self.bg_cmd) t.hAlign = "LEFT" story.append(t)
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 _draw_section_one_header(self, story): t = Table([["Section 1: Death Report"]], (18 * cm)) self.set_table_style(t, bg_cmd=self.bg_cmd) story.append(t) t = Table([[f"Prepared by {self.get_user(self.death_report)}."]], (18 * cm)) self.set_table_style(t) story.append(t)
def _draw_opinion(self, story): t = Table([["Section 2: Opinion of Local Study Doctor"]], (18 * cm)) self.set_table_style(t, bg_cmd=self.bg_cmd) story.append(t) rows = [] row = ["Main cause of death:"] if self.death_report.cause_of_death.short_name == OTHER: row.append( fill( f"{self.death_report.cause_of_death.name}: " f"{self.death_report.cause_of_death_other}", width=80, )) else: row.append(fill(self.death_report.cause_of_death.name)) rows.append(row) if self.death_report.cause_of_death == TUBERCULOSIS: rows.append([ "If cause of death is TB, site of TB disease:", self.death_report.get_tb_site_display(), ]) t = Table(rows, (4 * cm, 14 * cm)) self.set_table_style(t, bg_cmd=self.bg_cmd) t.hAlign = "LEFT" story.append(t) self.draw_narrative(story, title="Narrative:", text=self.death_report.narrative)
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 _draw_audit_trail(self, story): s = self.styles["line_data_small"] t = Table( [[ Paragraph("Document", s), Paragraph("Changed by", s), Paragraph("Date", s), Paragraph("Action", s), ]], (3 * cm, 3 * cm, 3 * cm, 9 * cm), ) self.set_table_style(t, bg_cmd=("BACKGROUND", (0, 0), (3, -1), colors.lightgrey)) story.append(t) qs = DeathReportModel.history.filter( id=self.death_report.id).order_by("-history_date") for obj in qs: username = (obj.user_created if obj.history_type == "+" else obj.user_modified) t = Table( [[ Paragraph(DeathReportModel._meta.verbose_name, s), Paragraph(username, s), Paragraph(obj.modified.strftime("%Y-%m-%d %H:%M"), s), Paragraph(fill(self.history_change_message(obj), width=60), s), ]], (3 * cm, 3 * cm, 3 * cm, 9 * cm), ) self.set_table_style(t) story.append(t)
def __init__(self, data, width, height, cust_data_function=None, colWidths=None, rowHeights=None, style=None, repeatRows=0, repeatCols=0, splitByRow=1, emptyTableAction=None, ident=None, hAlign=None, vAlign=None, normalizedData=0, cellStyles=None, rowSplitRange=None, spaceBefore=None, spaceAfter=None): self.cust_data_function = cust_data_function Table.__init__(self, data, colWidths, rowHeights, style, repeatRows, repeatCols, splitByRow, emptyTableAction, ident, hAlign, vAlign, normalizedData, cellStyles, rowSplitRange, spaceBefore, spaceAfter) self.wrap(width, height)
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 _draw_opinion(self, story): t = Table([["Section 2: Opinion of Local Study Doctor"]], (18 * cm)) self.set_table_style(t, bg_cmd=self.bg_cmd) story.append(t) rows = [] row = ["Main cause of death:"] if not self.death_report.cause_of_death: row.append(self.not_reported_text) else: if self.death_report.cause_of_death.name == OTHER: row.append( fill( f"{self.death_report.cause_of_death.name}: " f"{self.death_report.cause_of_death_other}", width=80, )) else: row.append(fill(self.death_report.cause_of_death.name)) rows.append(row) t = Table(rows, (4 * cm, 14 * cm)) self.set_table_style(t, bg_cmd=self.bg_cmd) t.hAlign = "LEFT" story.append(t) self.draw_narrative(story, title="Narrative:", text=self.death_report.narrative)
def tabela(self, largura, altura, dados, colWidths=None, rowHeights=None, style=None, repeatRows=0, repeatCols=0, splitByRow=1, emptyTableAction=None, ident=None, hAlign=None, vAlign=None): # Escape dados str ou unicode dados = [[escape(d) if isinstance(d, (str, unicode)) else d for d in l] for l in dados] # Renderizar 1 linha tabela = Table(dados[:1], colWidths, rowHeights, style, repeatRows, repeatCols, splitByRow, emptyTableAction, ident, hAlign, vAlign) l, a = tabela.wrapOn(self.canvas, largura, altura) # Quantas linhas dessa altura cabem linhas = int(altura/a) # Renderizar linhas tabela = Table(dados[:linhas], colWidths, rowHeights, style, repeatRows, repeatCols, splitByRow, emptyTableAction, ident, hAlign, vAlign) l, a = tabela.wrapOn(self.canvas, largura, altura) # Se não couber, vou tirando de 1 em 1 if a > altura: for i in range(linhas, 0, -1): tabela = Table(dados[:i], colWidths, rowHeights, style, repeatRows, repeatCols, splitByRow, emptyTableAction, ident, hAlign, vAlign) l, a = tabela.wrapOn(self.canvas, largura, altura) if a <= altura: break return (tabela, i, a) # Se couber, vou colocando de 1 em 1 i = linhas for i in range(linhas, len(dados)): tabela = Table(dados[:i], colWidths, rowHeights, style, repeatRows, repeatCols, splitByRow, emptyTableAction, ident, hAlign, vAlign) l, a = tabela.wrapOn(self.canvas, largura, altura) if a > altura: break i -= 1 tabela = Table(dados[:i], colWidths, rowHeights, style, repeatRows, repeatCols, splitByRow, emptyTableAction, ident, hAlign, vAlign) l, a = tabela.wrapOn(self.canvas, largura, altura) return (tabela, i, a)
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 create_detail(self): self.layout.append(Spacer(0, 20)) detail = Table([(key, ': {value}'.format(value=value)) for key, value in self.detail.items()], hAlign='LEFT') print(detail.wrap(0, 0)) self.layout.append(detail)
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 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 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 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 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 wrap(self, w, h): # Create the table, with the widths from colWidths reinterpreted # if needed as percentages of frame/cell/whatever width w is. # _tw = w/sum(self.colWidths) def adjust(*args, **kwargs): kwargs['total'] = w return styles.adjustUnits(*args, **kwargs) # adjust=functools.partial(styles.adjustUnits, total=w) self.colWidths = [adjust(x) for x in self._colWidths] # colWidths = [_w * _tw for _w in self.colWidths] self.t = Table( self.data, colWidths=self.colWidths, style=self.style, repeatRows=self.repeatrows, splitByRow=True, ) self._set_max_page_height_on_cell_flowables(h) # splitByRow=self.splitByRow) self.t.hAlign = self.hAlign return self.t.wrap(w, h)
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_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 wrap(self, availWidth, availHeight): "All table properties should be known by now." # makes an internal table which does all the work. # we draw the LAST RUN's entries! If there are # none, we make some dummy data to keep the table # from complaining if len(self._lastEntries) == 0: _tempEntries = [(0, 'Placeholder for table of contents', 0, None)] else: _tempEntries = self._lastEntries def drawTOCEntryEnd(canvas, kind, label): '''Callback to draw dots and page numbers after each entry.''' label = label.split(',') page, level, key = int(label[0]), int(label[1]), literal_eval( label[2]) if level == 2: return style = self.getLevelStyle(level) if level <= 1: dot = ' . ' else: dot = '' if self.formatter: page = self.formatter(page) drawPageNumbers(canvas, style, [(page, key)], availWidth, availHeight, dot) self.canv.drawTOCEntryEnd = drawTOCEntryEnd tableData = [] for (level, text, pageNum, key) in _tempEntries: style = self.getLevelStyle(level) if key: text = '<a href="#%s">%s</a>' % (key, text) keyVal = repr(key).replace(',', '\\x2c').replace('"', '\\x2c') else: keyVal = None para = TocParagraph( '%s<onDraw name="drawTOCEntryEnd" label="%d,%d,%s"/>' % (text, pageNum, level, keyVal), style, level=level) # import ipdb; ipdb.set_trace() if style.spaceBefore: tableData.append([ Spacer(1, style.spaceBefore), ]) tableData.append([ para, ]) self._table = Table(tableData, colWidths=(availWidth, ), style=self.tableStyle) self.width, self.height = self._table.wrapOn(self.canv, availWidth, availHeight) return (self.width, self.height)
def _draw_death_overview(self, story): # basics rows = [ ["Reference:", self.death_report.identifier], [ "Report date:", self.death_report.report_datetime.strftime("%Y-%m-%d %H:%M"), ], [ "Death date:", getattr(self.death_report, self.death_report.death_date_field).strftime( "%Y-%m-%d %H:%M"), ], [ "Study day:", self.death_report.study_day or self.not_reported_text ], [ "Death as inpatient:", self.death_report.death_as_inpatient or self.not_reported_text, ], ] t = Table(rows, (4 * cm, 14 * cm)) self.set_table_style(t, bg_cmd=self.bg_cmd) t.hAlign = "LEFT" story.append(t)
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 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 wrap(self, availWidth, availHeight): "All table properties should be known by now." widths = (availWidth - self.rightColumnWidth, self.rightColumnWidth) # makes an internal table which does all the work. # we draw the LAST RUN's entries! If there are # none, we make some dummy data to keep the table # from complaining if len(self._lastEntries) == 0: _tempEntries = [(0, 'Placeholder for table of contents', 0)] else: _tempEntries = self._lastEntries tableData = [] for (level, text, pageNum) in _tempEntries: leftColStyle = self.levelStyles[level] #right col style is right aligned rightColStyle = ParagraphStyle(name='leftColLevel%d' % level, parent=leftColStyle, leftIndent=0, alignment=enums.TA_RIGHT) leftPara = Paragraph(text, leftColStyle) rightPara = Paragraph(str(pageNum), rightColStyle) tableData.append([leftPara, rightPara]) self._table = Table(tableData, colWidths=widths, style=self.tableStyle) self.width, self.height = self._table.wrapOn(self.canv, availWidth, availHeight) return (self.width, self.height)
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 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 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 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 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 _build(self, availWidth, availHeight): _tempEntries = self._getlastEntries() _tempEntries.sort(lambda a, b: cmp([x.upper() for x in a[0]], [x.upper() for x in b[0]])) leveloffset = self.headers and 1 or 0 def drawIndexEntryEnd(canvas, kind, label): '''Callback to draw dots and page numbers after each entry.''' style = self.getLevelStyle(leveloffset) pages = loads(decodestring(label)) drawPageNumbers(canvas, style, pages, availWidth, availHeight, self.dot) self.canv.drawIndexEntryEnd = drawIndexEntryEnd alpha = '' tableData = [] lastTexts = [] for texts, pageNumbers in _tempEntries: texts = list(texts) if self.headers: alphaStyle = self.getLevelStyle(0) nalpha = texts[0][0].upper() if alpha != nalpha: alpha = nalpha tableData.append([ Spacer(1, alphaStyle.spaceBefore), ]) tableData.append([ Paragraph(alpha, alphaStyle), ]) tableData.append([ Spacer(1, alphaStyle.spaceAfter), ]) i, diff = listdiff(lastTexts, texts) if diff: lastTexts = texts texts = texts[i:] label = encodestring(dumps(list(pageNumbers))).strip() texts[-1] = '%s<onDraw name="drawIndexEntryEnd" label="%s"/>' % ( texts[-1], label) for text in texts: style = self.getLevelStyle(i + leveloffset) para = Paragraph(text, style) if style.spaceBefore: tableData.append([ Spacer(1, style.spaceBefore), ]) tableData.append([ para, ]) i += 1 self._flowable = Table(tableData, colWidths=[availWidth], style=self.tableStyle)
def _build(self,availWidth,availHeight): _tempEntries = self._getlastEntries() def getkey(seq): return [x.upper() for x in seq[0]] _tempEntries.sort(key=getkey) #was: _tempEntries.sort(lambda a,b: cmp([x.upper() for x in a[0]], [x.upper() for x in b[0]])) leveloffset = self.headers and 1 or 0 def drawIndexEntryEnd(canvas, kind, label): '''Callback to draw dots and page numbers after each entry.''' style = self.getLevelStyle(leveloffset) pages = loads(decodestring(label)) drawPageNumbers(canvas, style, pages, availWidth, availHeight, self.dot) self.canv.drawIndexEntryEnd = drawIndexEntryEnd alpha = '' tableData = [] lastTexts = [] alphaStyle = self.getLevelStyle(0) for texts, pageNumbers in _tempEntries: texts = list(texts) #track when the first character changes; either output some extra #space, or the first letter on a row of its own. We cannot do #widow/orphan control, sadly. nalpha = texts[0][0].upper() if alpha != nalpha: alpha = nalpha if self.headers: header = alpha else: header = ' ' tableData.append([Spacer(1, alphaStyle.spaceBefore),]) tableData.append([Paragraph(header, alphaStyle),]) tableData.append([Spacer(1, alphaStyle.spaceAfter),]) i, diff = listdiff(lastTexts, texts) if diff: lastTexts = texts texts = texts[i:] label = encodestring(dumps(list(pageNumbers))).strip() texts[-1] = '%s<onDraw name="drawIndexEntryEnd" label="%s"/>' % (texts[-1], label) for text in texts: #Platypus and RML differ on how parsed XML attributes are escaped. #e.g. <index item="M&S"/>. The only place this seems to bite us is in #the index entries so work around it here. text = escapeOnce(text) style = self.getLevelStyle(i+leveloffset) para = Paragraph(text, style) if style.spaceBefore: tableData.append([Spacer(1, style.spaceBefore),]) tableData.append([para,]) i += 1 self._flowable = Table(tableData, colWidths=[availWidth], style=self.tableStyle)
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 print_work_order(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', 'Quantity')] for lineitem in lineitems: lineitem.description = "\n".join(lineitem.description.splitlines()) if "\n" not in lineitem.description: if len(lineitem.description) > 63: lineitem.description = textwrap.fill(lineitem.description, 64) item = (Paragraph(lineitem.name, stylesheet['Normal']), lineitem.description, lineitem.quantity) data.append(item) table = Table(data, colWidths=(doc.width/5, None,0.75*inch)) 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)])) # Insert content tables and build doc elements.append(Spacer(1,.5*inch)) 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 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 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 _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 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 _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 _build(self, availWidth, availHeight): _tempEntries = self._getlastEntries() def getkey(seq): return [x.upper() for x in seq[0]] _tempEntries.sort(key=getkey) # was: _tempEntries.sort(lambda a,b: cmp([x.upper() for x in a[0]], [x.upper() for x in b[0]])) leveloffset = self.headers and 1 or 0 def drawIndexEntryEnd(canvas, kind, label): """Callback to draw dots and page numbers after each entry.""" if not isStrType(label): label = label.decoce("utf-8") style = self.getLevelStyle(leveloffset) pages = decode_label(label) drawPageNumbers(canvas, style, pages, availWidth, availHeight, self.dot) self.canv.drawIndexEntryEnd = drawIndexEntryEnd alpha = "" tableData = [] lastTexts = [] alphaStyle = self.getLevelStyle(0) for texts, pageNumbers in _tempEntries: texts = list(texts) # track when the first character changes; either output some extra # space, or the first letter on a row of its own. We cannot do # widow/orphan control, sadly. nalpha = texts[0][0].upper() if alpha != nalpha: alpha = nalpha if self.headers: header = alpha else: header = " " tableData.append([Spacer(1, alphaStyle.spaceBefore)]) tableData.append([Paragraph(header, alphaStyle)]) tableData.append([Spacer(1, alphaStyle.spaceAfter)]) i, diff = listdiff(lastTexts, texts) if diff: lastTexts = texts texts = texts[i:] label = encode_label(list(pageNumbers)) texts[-1] = '%s<onDraw name="drawIndexEntryEnd" label="%s"/>' % (texts[-1], label) for text in texts: # Platypus and RML differ on how parsed XML attributes are escaped. # e.g. <index item="M&S"/>. The only place this seems to bite us is in # the index entries so work around it here. text = escapeOnce(text) style = self.getLevelStyle(i + leveloffset) para = Paragraph(text, style) if style.spaceBefore: tableData.append([Spacer(1, style.spaceBefore)]) tableData.append([para]) i += 1 self._flowable = Table(tableData, colWidths=[availWidth], style=self.tableStyle)
def wrap(self, availWidth, availHeight): self.setMaxHeight(availHeight) # Strange bug, sometime the totalWidth is not set !? try: self.totalWidth except: self.totalWidth = availWidth # Prepare values totalWidth = self._normWidth(self.totalWidth, availWidth) remainingWidth = totalWidth remainingCols = 0 newColWidths = self._colWidths #print #print "TABLE", newColWidths # Calculate widths that are fix # IMPORTANT!!! We can not substitute the private value # self._colWidths therefore we have to modify list in place for i, colWidth in enumerate(newColWidths): if (colWidth is not None) or (colWidth == '*'): colWidth = self._normWidth(colWidth, totalWidth) remainingWidth -= colWidth else: remainingCols += 1 colWidth = None newColWidths[i] = colWidth # Distribute remaining space minCellWidth = totalWidth * 0.01 if remainingCols > 0: for i, colWidth in enumerate(newColWidths): if colWidth is None: # print "*** ", i, newColWidths[i], remainingWidth, remainingCols newColWidths[i] = max(minCellWidth, remainingWidth / remainingCols) # - 0.1 # Bigger than totalWidth? Lets reduce the fix entries propotionally # print "New values:", totalWidth, newColWidths, sum(newColWidths) # Call original method "wrap()" # self._colWidths = newColWidths if sum(newColWidths) > totalWidth: quotient = totalWidth / sum(newColWidths) # print quotient for i in range(len(newColWidths)): newColWidths[i] = newColWidths[i] * quotient # To avoid rounding errors adjust one col with the difference diff = sum(newColWidths) - totalWidth if diff > 0: newColWidths[0] -= diff # print "New values:", totalWidth, newColWidths, sum(newColWidths) return Table.wrap(self, availWidth, availHeight)
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 wrap(self, availWidth, availHeight): "All table properties should be known by now." widths = (availWidth - self.rightColumnWidth, self.rightColumnWidth) # makes an internal table which does all the work. # we draw the LAST RUN's entries! If there are # none, we make some dummy data to keep the table # from complaining if len(self._lastEntries) == 0: _tempEntries = [(0,'Placeholder for table of contents',0)] else: _tempEntries = self._lastEntries tableData = [] for (level, text, pageNum) in _tempEntries: leftColStyle = self.levelStyles[level] #right col style is right aligned rightColStyle = ParagraphStyle(name='leftColLevel%d' % level, parent=leftColStyle, leftIndent=0, alignment=enums.TA_RIGHT) leftPara = Paragraph(text, leftColStyle) rightPara = Paragraph(str(pageNum), rightColStyle) tableData.append([leftPara, rightPara]) self._table = Table(tableData, colWidths=widths, style=self.tableStyle) self.width, self.height = self._table.wrapOn(self.canv,availWidth, availHeight) return (self.width, self.height)
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 _build(self,availWidth,availHeight): _tempEntries = [(tuple(asUnicode(t) for t in texts),pageNumbers) for texts, pageNumbers in self._getlastEntries()] def getkey(seq): return [''.join((c for c in unicodedata.normalize('NFD', x.upper()) if unicodedata.category(c) != 'Mn')) for x in seq[0]] _tempEntries.sort(key=getkey) leveloffset = self.headers and 1 or 0 def drawIndexEntryEnd(canvas, kind, label): '''Callback to draw dots and page numbers after each entry.''' style = self.getLevelStyle(leveloffset) pages = [(p[1],k) for p,k in sorted(decode_label(label))] drawPageNumbers(canvas, style, pages, availWidth, availHeight, self.dot) self.canv.drawIndexEntryEnd = drawIndexEntryEnd alpha = '' tableData = [] lastTexts = [] alphaStyle = self.getLevelStyle(0) for texts, pageNumbers in _tempEntries: texts = list(texts) #track when the first character changes; either output some extra #space, or the first letter on a row of its own. We cannot do #widow/orphan control, sadly. nalpha = ''.join((c for c in unicodedata.normalize('NFD', texts[0][0].upper()) if unicodedata.category(c) != 'Mn')) if alpha != nalpha: alpha = nalpha if self.headers: header = alpha else: header = ' ' tableData.append([Spacer(1, alphaStyle.spaceBefore),]) tableData.append([Paragraph(header, alphaStyle),]) tableData.append([Spacer(1, alphaStyle.spaceAfter),]) i, diff = listdiff(lastTexts, texts) if diff: lastTexts = texts texts = texts[i:] label = encode_label(list(pageNumbers)) texts[-1] = '%s<onDraw name="drawIndexEntryEnd" label="%s"/>' % (texts[-1], label) for text in texts: #Platypus and RML differ on how parsed XML attributes are escaped. #e.g. <index item="M&S"/>. The only place this seems to bite us is in #the index entries so work around it here. text = escapeOnce(text) style = self.getLevelStyle(i+leveloffset) para = Paragraph(text, style) if style.spaceBefore: tableData.append([Spacer(1, style.spaceBefore),]) tableData.append([para,]) i += 1 self._flowable = Table(tableData, colWidths=[availWidth], style=self.tableStyle)
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))
class PmlTableOfContents(TableOfContents): def wrap(self, availWidth, availHeight): "All table properties should be known by now." widths = (availWidth - self.rightColumnWidth, self.rightColumnWidth) # makes an internal table which does all the work. # we draw the LAST RUN's entries! If there are # none, we make some dummy data to keep the table # from complaining if len(self._lastEntries) == 0: _tempEntries = [(0, 'Placeholder for table of contents', 0)] else: _tempEntries = self._lastEntries i = 0 lastMargin = 0 tableData = [] tableStyle = [ ('VALIGN', (0, 0), (- 1, - 1), 'TOP'), ('LEFTPADDING', (0, 0), (- 1, - 1), 0), ('RIGHTPADDING', (0, 0), (- 1, - 1), 0), ('TOPPADDING', (0, 0), (- 1, - 1), 0), ('BOTTOMPADDING', (0, 0), (- 1, - 1), 0), ] for entry in _tempEntries: level, text, pageNum = entry[:3] leftColStyle = self.levelStyles[level] if i: # Not for first element tableStyle.append(( 'TOPPADDING', (0, i), (- 1, i), max(lastMargin, leftColStyle.spaceBefore))) # print leftColStyle.leftIndent lastMargin = leftColStyle.spaceAfter #right col style is right aligned rightColStyle = ParagraphStyle(name='leftColLevel%d' % level, parent=leftColStyle, leftIndent=0, alignment=TA_RIGHT) leftPara = Paragraph(text, leftColStyle) rightPara = Paragraph(str(pageNum), rightColStyle) tableData.append([leftPara, rightPara]) i += 1 self._table = Table( tableData, colWidths=widths, style=TableStyle(tableStyle)) self.width, self.height = self._table.wrapOn(self.canv, availWidth, availHeight) return (self.width, self.height)
class TableRender(IRender): def __init__(self, width, height, labels, data): IRender.__init__(self, width, height, labels, data) self.table = Table([self.labels] + self.data, style=[#('GRID',(0,0),(-1,-1),0.5,colors.grey), #('BOX',(0,0),(-1,-1),2,colors.black), ('LINEABOVE',(0,1),(-1,1),2,colors.black), #('ALIGN',(0,0),(-1,0),'CENTER'), ('TOPPADDING', (0,1), (-1,-1), 2), ('BOTTOMPADDING', (0,1), (-1,-1), 1), ]) self.table._calc(width, height) for n, w in enumerate(self.table._colWidths): print w self.table._argW[n] = w + (width - self.table._width) / self.table._ncols self.table._calc(width, height) self.height = self.table._rowpositions[0] def render(self): return self.table