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 _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 _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 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 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 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 createBeritaAcaraPage(contain, styles, tahunAkademik, hariSekarang, tglSekarang, namaDosen, prodi, kelas, jumlahMhs, jumlahHadir, jumlahTdkHadir, listMasukan, namaDeputi, namaKaprodi, qrDeputi, qrKaprodi, qrDosen): text = '<font size="14"><b>BERITA ACARA PERWALIAN</b></font>' contain.append(Paragraph(text, styles["Center"])) contain.append(Spacer(1, .5*cm)) text = f'<font size="14"><b>TAHUN AKADEMIK {tahunAkademik}</b></font>' contain.append(Paragraph(text, styles["Center"])) contain.append(Spacer(1, 1.5*cm)) text = f'<font size="12">Pada hari ini {hariSekarang} tanggal {tglSekarang}, telah dilaksanakan Perwalian Tahun Akademik {tahunAkademik} dengan data sebagai berikut:</font>' contain.append(Paragraph(text, styles["Justify"])) contain.append(Spacer(1, .5*cm)) data = [['Nama Dosen Wali', ':', namaDosen], ['Jurusan / Kelas', ':', f'{prodi} / {kelas}'], ['Jumlah Mahasiswa', ':', jumlahMhs], ['Jumlah yang hadir', ':', jumlahHadir], ['Jumlah yang tidak hadir', ':', jumlahTdkHadir], ] table = Table(data, [5*cm, .5*cm, 10.5*cm], len(data)*[.6*cm]) table.setStyle(TableStyle([ ('FONT',(0,0),(-1,-1),'Times-Roman', 12), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ])) contain.append(table) contain.append(Spacer(1, .7*cm)) text = '<font size="12">Catatan masukan dari mahasiswa :</font>' contain.append(Paragraph(text, styles["Justify"])) contain.append(Spacer(1, .1*cm)) table = Table(listMasukan, [.8*cm, 15.2*cm], len(listMasukan)*[.6*cm]) table.setStyle(TableStyle([ ('FONT',(0,0),(-1,-1),'Times-Roman', 12), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ])) contain.append(table) contain.append(Spacer(1, .7*cm)) data = [ [Paragraph('<font size="12"><b>Dosen Wali,</b></font>', styles["Center"]), Paragraph('<font size="12"><b>Ketua Prodi,</b></font>', styles["Center"]), Paragraph('<font size="12"><b>Deputi Akademik,</b></font>', styles["Center"])], [Image(qrDeputi, 4*cm, 4*cm), Image(qrKaprodi, 4*cm, 4*cm), Image(qrDosen, 4*cm, 4*cm)], [Paragraph(f'<font size="12"><u>{namaDosen}</u></font>', styles["Center"]), Paragraph(f'<font size="12"><u>{namaKaprodi}</u></font>', styles["Center"]), Paragraph(f'<font size="12"><u>{namaDeputi}</u></font>', styles["Center"])], ] table = Table(data, [6.8*cm, 6.8*cm, 6.8*cm], [.6*cm, 4.5*cm, 1*cm]) table.setStyle(TableStyle([ ('FONT',(0,0),(-1,-1),'Times-Roman', 12), ('ALIGN',(0,1),(-1,-1),'CENTER'), ])) contain.append(table) contain.append(PageBreak())
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 _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 convert_pdf(self, request, queryset): from reportlab.platypus import SimpleDocTemplate from reportlab.platypus.tables import Table from django.http import HttpResponse cm = 2.54 response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename=hasil_nilai.pdf' elements = [] doc = SimpleDocTemplate(response, rightMargin=0, leftMargin=6.5 * cm, topMargin=0.3 * cm, bottomMargin=0) data = [ ["Nama Siswa", "Mata Pelajaran", "Score", "Lulus"], ] for s in queryset: data.append([s.user, s.mata_pelajaran, s.score, s.lulus]) table = Table(data) elements.append(table) doc.build(elements) return response
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 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 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 getAttributeTable(self): """ """ ik_tbl_style = TableStyle([\ ('LEFTPADDING', (0,0), (-1,-1), 0), ('RIGHTPADDING', (0,0), (-1,-1), 0), ('BOTTOMPADDING', (0,0), (-1,-1), 0), ('TOPPADDING', (0,0), (-1,-1), 0), ('ALIGN', (0,0), (-1,-1), 'LEFT'), ]) colWidths = [50 * mm, 85 * mm] data = [] fields = self.getReportFields() for f_name, f_obj in fields.items(): f_val = getattr(self.context, f_name) if f_val is not None: rptPara = RptPara(unicode(f_val), doc=self.document) data.append([f_obj.field.title, rptPara]) if len(data) > 0: t0 = Table(data, hAlign = 'RIGHT', style=ik_tbl_style, colWidths=colWidths) else: t0 = None return t0
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 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 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 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 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 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 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 _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 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 getAttributeTable(self): """ """ rowColor = getTabBackgroundColor() rowColorLight = getTabBackgroundColorLight() ik_tbl_style = TableStyle([\ ('LEFTPADDING', (0,0), (-1,-1), 0), ('RIGHTPADDING', (0,0), (-1,-1), 0), ('BOTTOMPADDING', (0,0), (-1,-1), 0), ('TOPPADDING', (0,0), (-1,-1), 3), ('ALIGN', (0,0), (-1,-1), 'LEFT'), ('VALIGN',(0,0),(-1,-1),'TOP'), ('ROWBACKGROUNDS',(0,0),(-1,-1),[rowColorLight, rowColor]), ]) colWidths = [50 * mm, 85 * mm] data = [] data.extend(self.prependAttributeTable()) data.extend(self.makeAttributeTable()) data.extend(self.appendAttributeTable()) if len(data) > 0: t0 = Table(data, hAlign='RIGHT', style=ik_tbl_style, colWidths=colWidths) else: t0 = None return t0
def add_table(self, rows, width=None, col_widths=None, align=CENTER, extra_style=[]): style = self.theme.table_style + extra_style if width and col_widths is None: # one cannot spec table width in rLab only col widths col_widths = calc_table_col_widths(rows, width) # this helper calcs it for us table = Table(rows, col_widths, style=style, hAlign=align) self.add(table)
def run_sample(request): global samples output = io.BytesIO() today = date.today() val1 = int(request.GET['num1']) val2 = int(request.GET['num2']) try: samples = random.sample(range(1, val1), k=val2) except ValueError: pass # response = HttpResponse(output,content_type='application/ms-excel') # response['Content-Disposition'] = 'attachment; filename="Samples.xlsx' df = pd.DataFrame(samples) df.columns = ['Sample Item'] df.sort_values(by=['Sample Item'], inplace=True, ignore_index=True) df.index.name = 'Sample Number' df.index = df.index + 1 df['Sample Number'] = df.index col_name = 'Sample Number' first_col = df.pop(col_name) df.insert(0, col_name, first_col) lista = [df.columns[:, ].values.astype(str).tolist()] + df.values.tolist() response = HttpResponse(output) response['Content-Disposition'] = 'attachment; filename=SamplesReport.pdf' elements = [] header = Paragraph("Auditor Sample Selection") population = Paragraph("Population Size: " + str(val1)) sample = Paragraph("Sample Size: " + str(val2)) description = Paragraph( "This sample was generated using AuditSampling.com. Samples" " generated using this software are generated procedurally using a computer" " aided sampling technique. Samples generated using this method are handled " "by the third-party web service and are free of auditor bias.") space = Paragraph(".") date_generated = Paragraph("Report Generated on: " + str(today)) doc = SimpleDocTemplate(response) table = Table(lista, colWidths=80, rowHeights=15) elements.append(header) elements.append(population) elements.append(sample) elements.append(date_generated) elements.append(space) elements.append(description) elements.append(space) elements.append(table) doc.build(elements) return response
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()