def layoutTable(self, hTableAlignment=None, colWidths=None): """ Returns a table flowable with automatically estimated column width. :param styledTable: a styled table :type styledTable: StyledTable :param hTableAlignment: the table alignment on the frame :type hTableAlignment: int :param colWidths: the columns width in cm :type colWidths: list :param spaceBefore: the space above the table in cm :type spaceBefore: float :param spaceAfter: the space below the table in cm :type spaceAfter: float :returns: a table flowable element """ self.addTableStyleCommand(('LEFTPADDING', (0, 0), (-1, -1), 0.1 * cm)) self.addTableStyleCommand(('VALIGN', (0, 0), (-1, -1), 'BOTTOM')) if colWidths: colWidths = [x * cm for x in colWidths] table = Table(self.tableData, colWidths=colWidths, spaceBefore=0, spaceAfter=0) table.setStyle(self.handleStyleCommands()) if hTableAlignment is not None: table.hAlign = hTableAlignment else: table.hAlign = self.hTableAlignment return table
def makeImage(self, context, path, caption='', width=None, align='CENTER', padding=10): content = [] if width is None: width = 16 * cm if len(caption) > 0: caption = str(context.currentImage) + ". " + caption context.currentImage = context.currentImage + 1 image = cmn_utils_rp.getImage(path, width, dummy=True) context.dummies.append(image) imgData = [[image], [ context.paragraph(caption, context.styleSheet["ImageCaption"]) ]] imgTable = Table(imgData) imgTable.setStyle( TableStyle([('ALIGN', (0, 0), (-1, -1), align), ('VALIGN', (0, 0), (-1, -1), align), ('LEFTPADDING', (0, 0), (-1, -1), padding), ('RIGHTPADDING', (0, 0), (-1, -1), padding), ('TOPPADDING', (0, 0), (-1, -1), padding), ('BOTTOMPADDING', (0, 0), (-1, -1), padding)])) imgTable.hAlign = align content.append(imgTable) return content
def build_index_Casse(self, records, sito): styleSheet = getSampleStyleSheet() styNormal = styleSheet['Normal'] styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.pink) styH3 = styleSheet['Heading3'] data = self.datestrfdate() lst = [] lst.append(Paragraph("<b>ELENCO CASSE</b><br/><b>Sito: %s <br/>Data: %s <br/>Ditta esecutrice: adArte snc, Rimini</b>" % (sito, data), styH3)) table_data = [] for i in range(len(records)): exp_index = CASSE_index_pdf_sheet(records[i]) table_data.append(exp_index.getTable()) styles = exp_index.makeStyles() colWidths=[60,150,100, 120] table_data_formatted = Table(table_data, colWidths, style=styles) table_data_formatted.hAlign = "LEFT" #table_data_formatted.setStyle(styles) lst.append(table_data_formatted) lst.append(Spacer(0,0)) filename = ('%s%s%s') % (self.PDF_path, os.sep, 'elenco_casse.pdf') f = open(filename, "wb") doc = SimpleDocTemplate(f, pagesize=(21*cm, 29*cm), showBoundary=1) doc.build(lst, canvasmaker=NumberedCanvas_Campioniindex) f.close()
def make_story(elements, data, swarr, spanArr, b): ps = ParagraphStyle('title') t0 = Table(data, colWidths=swarr) t0.hAlign = "CENTER" t0.setStyle( TableStyle([ ('GRID', (0, 0), (-1, -1), 1, black), ('LEFTPADDING', (0, 0), (-1, -1), 2), ('RIGHTPADDING', (0, 0), (-1, -1), 2), ('TOPPADDING', (0, 0), (-1, -1), -1), ('BOTTOMPADDING', (0, 0), (-1, -1), 2), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), # ('BACKGROUND',(0,0),(-1,-1),red), ])) tabStyles = [] for i in range(len(spanArr)): for j in range(len(spanArr[i])): span = spanArr[i][j] if span > 1: tabStyles.append(('SPAN', (j, i), (j + span - 1, i))) bcolor = b[i][j] if bcolor != 0: c0 = bcolor[0] c1 = bcolor[1] c2 = bcolor[2] tabStyles.append(('BACKGROUND', (j, i), (j + span - 1, i), Color(c0, c1, c2))) t0.setStyle(TableStyle(tabStyles)) elements.append(t0)
def build_document(experiments_by_week, semester, level, filename): buf = io.BytesIO() output_doc = SimpleDocTemplate( buf, rightMargin=15 * mm, leftmargin=15 * mm, topMargin=15 * mm, bottomMargin=30 * mm, pagesize=A4, ) styles = get_styles() Story = get_header(semester, styles, level) table_content, table_style = build_table(experiments_by_week, semester, styles) table = Table(table_content) table.setStyle(table_style) table.hAlign = 'CENTER' Story.append(table) output_doc.build(Story) with open(filename, 'wb') as f: f.write(buf.getvalue())
def crea_pdf(self): titolo = "Dettagli lotto numero " + self.tree.parent(self.item) + " " + self.tree.item(self.item, 'text') styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) data = [('Taglio', 'Lotto Ingresso', 'Fornitore', 'Documento', 'Data Acquisto')] self.c.execute("SELECT DISTINCT prod_origine, lotto_acq,fornitore,documento,data_acq " "FROM lotti_vendita JOIN ingresso_merce " "WHERE progressivo_ven = %s " "AND lotti_vendita.lotto_acq = ingresso_merce.progressivo_acq", (self.tree.parent(self.item),)) for lista in self.c: data.append(lista) doc = SimpleDocTemplate("./traccia.pdf", pagesize=A4) parts = [] table_with_style = Table(data, [1 * inch, 1.7 * inch, inch]) table_with_style.hAlign = "LEFT" table_with_style.setStyle(TableStyle([ ('FONT', (0, 0), (-1, -1), 'Helvetica'), ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('FONTSIZE', (0, 0), (-1, -1), 8), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, 0), 0.25, colors.green), ('ALIGN', (0, 0), (-1, 0), 'CENTER'), ])) parts.append(Paragraph(titolo, styles["Center"])) parts.append(Spacer(1, 0.5 * inch)) parts.append(table_with_style) doc.build(parts) if messagebox.askyesno('STAMPA', 'Vuoi stampare il pdf?'): win32api.ShellExecute(None, "print", "traccia.pdf", None, ".", 0)
def assemble_document(datafile, outfile, do_metric): # create the document doc = create_document(output_filename) # "Flowable" objects container elements = [] # header content add_header_content(elements) # retrieve data and set up column spacing contents = get_content(datafile) cols = [90, 35, 35, 35, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50] # Assemble data for each column using simple loop to append it into data list data = [] data.append([ i.split('~')[0] if '~' in i else i for i in contents.columns.tolist() ]) # add spanning elements spanners = [ '', '', '{}'.format('m/min' if do_metric else 'ft/min'), '{}'.format('m' if do_metric else 'ft'), '|--------------- {} ---------------|' .format('kw/m2' if do_metric else 'BTU/ft2/min'), '', '', '', '', '|------------- Fuel Model 13 -------------|', '', '', '|------------- Fuel Model 40 -------------|', '', '' ] data.append(spanners) # add the actual data for i in contents.index: data.append(list(contents.irow(i).values)) # add the table style -- this applies formatting to the table table_that_splits_over_pages = Table(data, colWidths=cols, repeatRows=2) table_that_splits_over_pages.hAlign = 'LEFT' tbl_style = TableStyle([('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('ALIGN', (0, 0), (-1, 1), 'CENTER'), ('ALIGN', (0, 2), (-1, -1), 'RIGHT'), ('LEADING', (0, 0), (-1, 0), 0), ('BOTTOMPADDING', (0, 0), (-1, 0), 0), ('TOPPADDING', (0, 1), (-1, 1), 0), ('FONTSIZE', (0, 1), (-1, -1), 8), ('INNERGRID', (0, 2), (-1, -1), 0.5, colors.black), ('SPAN', (4, 1), (8, 1)), ('SPAN', (9, 1), (11, 1)), ('SPAN', (12, 1), (-1, 1)), ('BOX', (0, 0), (-1, 1), 1, colors.black), ('BOX', (0, 2), (-1, -1), 1, colors.black)]) tbl_style.add('BACKGROUND', (0, 0), (-1, 1), colors.lightblue) tbl_style.add('BACKGROUND', (0, 2), (-1, -1), colors.white) table_that_splits_over_pages.setStyle(tbl_style) elements.append(table_that_splits_over_pages) # - put it all together doc.build(elements, canvasmaker=num_canvas.NumberedCanvas)
def draw_demographics(self, story, **kwargs): model_obj = getattr(self, self.model_attr) weight = get_weight_for_timepoint( subject_identifier=self.subject_identifier, reference_dt=model_obj.report_datetime, ) assignment = "*****************" if self.request.user.groups.filter(name=RANDO).exists(): assignment = fill(self.drug_assignment, width=80) rows = [ ["Subject:", self.subject_identifier], [ "Gender/Age:", f"{self.registered_subject.get_gender_display()} {self.age}", ], ["Weight:", f"{weight} 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 report(self, pdfdownload, title): # set some characteristics for pdf documents doc = SimpleDocTemplate(self.buffer, rightMargin=72, leftMargin=72, topmargin=30, bottomMargin=72, pagesize=self.pageSize) # a collection of styles offered by the library styles = getSampleStyleSheet() # add custom paragraph style styles.add( ParagraphStyle(name="TableHeader", fontSize=11, alignment=TA_CENTER)) styles.add( ParagraphStyle(name="ParagraphTitle", fontSize=11, alignment=TA_JUSTIFY)) styles.add(ParagraphStyle(name="Justify", alignment=TA_JUSTIFY)) # list used for elements addded into document data = [] data.append(Paragraph(title, styles['Title'])) # insert a blank space data.append(Spacer(1, 12)) table_data = [] # table header table_data.append([ Paragraph('Contribution Date', styles['TableHeader']), Paragraph('Name', styles['TableHeader']), Paragraph('Amount', styles['TableHeader']) ]), for pd in pdfdownload: # data.append(Spacer(1, 24)) # add a row to table table_data.append([ pd.Contribution_date, Paragraph(pd.member.username, styles['Justify']), u"Ksh.{0}".format(pd.amount) ]) # create table pd_table = Table(table_data, colWidths=[doc.width / 3.0] * 7) pd_table.hAlign = 'LEFT' pd_table.setStyle( TableStyle([('INNERGRID', (0, 0), (-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)])) data.append(pd_table) data.append(Spacer(1, 48)) # create document doc.build(data, onFirstPage=self.pageNumber, onLaterPages=self.pageNumber) pdf = self.buffer.getvalue() self.buffer.close() return pdf
def crea_pdf(self): data = [('settimana', 'codice', 'prodotto', 'cod_ean')] self.c.execute("SELECT settimana,prodotto,SUM(quantita),cod_ean " "FROM ingredienti " "WHERE settimana = %s " "GROUP BY prodotto", (self.settimana.get(),)) for i in self.c: data.append(i) doc = SimpleDocTemplate("./table.pdf", pagesize=A4) parts = [] table_with_style = Table(data, [1 * inch, 1.7 * inch, inch]) table_with_style.hAlign = "LEFT" table_with_style.setStyle(TableStyle([ ('FONT', (0, 0), (-1, -1), 'Helvetica'), ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('FONTSIZE', (0, 0), (-1, -1), 8), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, 0), 0.25, colors.green), ('ALIGN', (0, 0), (-1, 0), 'CENTER'), ])) parts.append(Spacer(1, 0.5 * inch)) parts.append(table_with_style) doc.build(parts) if messagebox.askyesno('STAMPA', 'Vuoi stampare il pdf?'): win32api.ShellExecute(None, "print", "table.pdf", None, ".", 0)
def buildTable(data): doc = SimpleDocTemplate("MOOSE_requirements_tracability.pdf", pagesize=A4, rightMargin=30,leftMargin=30, topMargin=30,bottomMargin=18) doc.pagesize = landscape(A4) elements = [] #Configure style and word wrap s = getSampleStyleSheet() s = s["BodyText"] s.wordWrap = 'CJK' pdf_data = [["Requirement", "Description", "Test Case(s)"]] #TODO: Need a numerical sort here keys = sorted(data.keys()) for key in keys: data[key][2] = '\n'.join(data[key][2]) pdf_data.append([Paragraph(cell, s) for cell in data[key]]) # Build the Table and Style Information tableThatSplitsOverPages = Table(pdf_data, repeatRows=1) tableThatSplitsOverPages.hAlign = 'LEFT' tblStyle = TableStyle([('TEXTCOLOR',(0,0),(-1,-1),colors.black), ('VALIGN',(0,0),(-1,-1),'TOP'), ('LINEBELOW',(0,0),(-1,-1),1,colors.black), ('INNERGRID', (0,0), (-1,-1),1,colors.black), ('BOX',(0,0),(-1,-1),1,colors.black), ('BOX',(0,0),(0,-1),1,colors.black)]) tblStyle.add('BACKGROUND',(0,0),(-1,-1),colors.lightblue) tblStyle.add('BACKGROUND',(0,1),(-1,-1),colors.white) tableThatSplitsOverPages.setStyle(tblStyle) elements.append(tableThatSplitsOverPages) doc.build(elements)
def setTableData(self, queryset, fields, title): self.data.append(Paragraph("%s" % title, self.styles['Heading3'])) data = [] header = False for row in queryset: if not header: data.append([f["name"] for f in fields]) header = True ctx = Context({"object": row }) values = [ Template(h["bit"]).render(ctx) for h in fields ] data.append(values) table = PDFTable(data,None,None,None,1) ts = [ ('ALIGNMENT', (0,0), (-1,-1), 'LEFT'), ('LINEBELOW', (0,0), (-1,-0), 2, colors.black), ('LINEBELOW', (0,1), (-1,-1), 0.8, colors.lightgrey), ('FONT', (0,0), (-1, -1), "Helvetica", 8), ('ROWBACKGROUNDS', (0,0), (-1, -1), [colors.whitesmoke, colors.white]), ] if self.hasfooter is True: ts.append(('LINEABOVE', (0,-1), (-1,-1), 1, colors.red)) ts.append(('LINEBELOW', (0,-1), (-1,-1), 2, colors.red)) ts.append(('LINEBELOW', (0,-1), (-1,-1), 0.8, colors.lightgrey)) ts.append(('FONT', (0,-1), (-1, -1), "Helvetica", 8)) table.setStyle(TableStyle(ts)) table.hAlign = "LEFT" self.data.append(table)
def build_index_Casse(self, records, sito): if os.name == 'posix': home = os.environ['HOME'] elif os.name == 'nt': home = os.environ['HOMEPATH'] home_DB_path = ('%s%s%s') % (home, os.sep, 'pyarchinit_DB_folder') logo_path = ('%s%s%s') % (home_DB_path, os.sep, 'logo.jpg') logo = Image(logo_path) logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth logo.drawWidth = 1.5 * inch logo.hAlign = "LEFT" styleSheet = getSampleStyleSheet() styNormal = styleSheet['Normal'] styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.pink) styH1 = styleSheet['Heading3'] data = self.datestrfdate() lst = [logo] lst.append( Paragraph( "<b>ELENCO CASSE CAMPIONI</b><br/><b>Scavo: %s, Data: %s</b>" % (sito, data), styH1)) table_data = [] for i in range(len(records)): exp_index = CASSE_index_pdf_sheet(records[i]) table_data.append(exp_index.getTable()) styles = exp_index.makeStyles() colWidths = [20, 350, 250, 100] table_data_formatted = Table(table_data, colWidths, style=styles) table_data_formatted.hAlign = "LEFT" # table_data_formatted.setStyle(styles) lst.append(table_data_formatted) lst.append(Spacer(0, 0)) filename = ('%s%s%s') % (self.PDF_path, os.sep, 'elenco_casse_campioni.pdf') f = open(filename, "wb") doc = SimpleDocTemplate(f, pagesize=(29 * cm, 21 * cm), showBoundary=0, topMargin=15, bottomMargin=40, leftMargin=30, rightMargin=30) # doc.build(lst, canvasmaker=NumberedCanvas_Sindex) doc.build(lst) f.close()
def setTableData(self, queryset, fields, title): """ set table data @var queryset: data @var fields: table column headings @var title: Table Heading """ data = [] header = False c = 0; #prepare the data for row in queryset: if not header: data.append([f["name"] for f in fields]) header = True ctx = Context({"object": row }) values = [ Template(h["bit"]).render(ctx) for h in fields ] data.append(values) table = PDFTable(data,None,None,None,1) #table rows n cols formatting ts = [ ('ALIGNMENT', (0,0), (-1,-1), 'LEFT'), ('LINEBELOW', (0,0), (-1,-0), 2, colors.black), ('LINEBELOW', (0,1), (-1,-1), 0.8, colors.lightgrey), ('FONT', (0,0), (-1, -1), "Times-Roman", self.fontSize), ('ROWBACKGROUNDS', (0,0), (-1, -1), [colors.whitesmoke, colors.white]), ('LEFTPADDING', (0,0), (-1, -1), 1), ('RIGHTPADDING', (0,0), (-1, -1), 1), ('TOPPADDING', (0,0), (-1, -1), 1), ('BOTTOMPADDING', (0,0), (-1, -1), 1), ] #last row formatting when required if self.hasfooter is True: ts.append(('LINEABOVE', (0,-1), (-1,-1), 1, colors.black)) ts.append(('LINEBELOW', (0,-1), (-1,-1), 2, colors.black)) ts.append(('LINEBELOW', (0,3), (-0,-0), 2, colors.green)) ts.append(('LINEBELOW', (0,-1), (-1,-1), 0.8, colors.lightgrey)) ts.append(('FONT', (0,-1), (-1, -1), "Times-Roman", 7)) table.setStyle(TableStyle(ts)) table.hAlign = "LEFT" self.data.append(table) """ The number of rows per page for two columns is about 90. using this information you can figure how many pages the table is going to overlap hence you place a header/subtitle in that position for it to be printed appropriately """ c = len(queryset)/90 if int(c)< c: c = int(c) + 1 for i in range(c): self.headers.append(title)
def generatepdf(ipblock, zip_files_path, reportspath): combined_files(zip_files_path, reportspath) renu_report(ipblock, zip_files_path, reportspath) company_reports(ipblock, zip_files_path, reportspath) os.remove(reportspath + '\AllFiles.csv') readfiles = glob.glob(os.path.join(reportspath, "*.csv")) for filename in readfiles: if "combined_files" in filename: os.remove(reportspath + '\combined_files.csv') filena, file_extension = os.path.splitext(filename) filenam = str(filena.split("\\")[-1]) # Content. line1 = "Vulnerability Report for " content = line1 + filenam content2 = line1 + filenam + " continued ... " def logo(canvas, doc): logo_img = 'logo.png' canvas.drawImage(logo_img, 300, 730) canvas.drawString(100, 715, content) def logo2(canvas, doc): logo_img = 'logo.png' canvas.drawImage(logo_img, 300, 730) canvas.drawString(100, 715, content2) pdfReportPages = str(filena) + '.pdf' doc = SimpleDocTemplate(pdfReportPages, pagesize=letter) elements = [] col1 = "TIMESTAMP" col2 = "HOST" col3 = "NAME OF VULNERABILITY" data = [[col1, col2, col3]] with open(filename) as infile: for line in infile: reader = csv.reader(infile) data.extend(list(reader)) tableThatSplitsOverPages = Table(data, [5 * cm, 6 * cm, 5 * cm], repeatRows=1) tableThatSplitsOverPages.hAlign = 'LEFT' tblStyle = TableStyle([ ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LINEBELOW', (0, 0), (-1, -1), 1, colors.black), ('INNERGRID', (0, 0), (-1, -1), 1.5, colors.black), ('BOX', (0, 0), (-1, -1), 1.5, colors.black) ]) tblStyle.add('BACKGROUND', (0, 0), (-1, -1), colors.lightblue) tblStyle.add('BACKGROUND', (0, 1), (-1, -1), colors.white) tableThatSplitsOverPages.setStyle(tblStyle) elements.append(tableThatSplitsOverPages) doc.topMargin = 1.3 * inch doc.build(elements, onFirstPage=logo, onLaterPages=logo2) del data[:] os.remove(filename)
def __type_prestation_secondrow(self): typePresta_data = [[ self.__autreTypePresta_checkbox(), Paragraph(u"Autre prestatation (à préciser):"+self.__prestaType_precisions(), self.paragraph_style)],] typePresta_style = TableStyle([self.fontsize_style,('VALIGN',(1,0),(1,0),'MIDDLE')]) colWidths=[25, 500] typePresta_table = Table(data=typePresta_data, style=typePresta_style, colWidths=colWidths) typePresta_table.spaceAfter = 20 typePresta_table.hAlign = 0 self.elements.append(typePresta_table)
def pdfInsejcable(self): # si le titre est dans l'affichage, insehre un peu d'espace if len(self.insejcable) > 1: self.flowables.append(Spacer(C_CEL, C_CEL)) table = Table(self.insejcable) table.hAlign = "LEFT" self.flowables.append(KeepTogether(table)) self.insejcable.clear()
def build_P_sheets(self, records, sito): home = os.environ['HFF_HOME'] self.width, self.height = (A3) home_DB_path = '{}{}{}'.format(home, os.sep, 'HFF_DB_folder') logo_path = '{}{}{}'.format(home_DB_path, os.sep, 'banner.png') logo = Image(logo_path) logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth logo.drawWidth = 1.5 * inch logo.hAlign = "LEFT" styleSheet = getSampleStyleSheet() styNormal = styleSheet['Normal'] styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.pink) styH1 = styleSheet['Heading3'] data = self.datestrfdate() list = [] list.append(logo) list.append( Paragraph( "<b>HFF Archaeological Survey UW - Photo Index</b><br/><br/><b>Location: %s, Date: %s</b><br/>" % (sito, data), styH1)) table_data = [] for i in range(len(records)): exp_index = Photo_index_pdf(records[i]) table_data.append(exp_index.getTable()) styles = exp_index.makeStyles() colWidths = [50, 100, 120, 190, 120, 190] table_data_formatted = Table(table_data, colWidths, style=styles) table_data_formatted.hAlign = "LEFT" list.append(table_data_formatted) list.append(Spacer(0, 0)) filename = '{}{}{}'.format(self.PDF_path, os.sep, 'Photo_index_UW.pdf') f = open(filename, "wb") doc = SimpleDocTemplate(f, pagesize=A2, showBoundary=0, topMargin=15, bottomMargin=40, leftMargin=30, rightMargin=30) doc.build(list, canvasmaker=NumberedCanvas_USindex) f.close()
def produce(self, module): str_competence = ' \n'.join([ '- {0} ({1})'.format(c.nom, c.code) for c in module.competence_set.all() ]) str_sous_competence = '' for c in module.competence_set.all(): for sc in c.souscompetence_set.all(): str_sous_competence += '- {0} (voir {1})\n'.format( sc.nom, c.code) str_res = ' \n'.join([ '- {0}'.format(c.nom) for c in module.ressource_set.all() ]) # for future use str_objectif = ' \n'.join( ['- {0}'.format(c.nom) for c in module.objectif_set.all()]) self.story.append(Paragraph(module.__str__(), style_bold)) self.story.append(Spacer(0, 0.5 * cm)) data = [ ['Domaine', module.processus.domaine.__str__()], ['Processus', module.processus.__str__()], ['Situation emblématique', module.situation], ['Compétences visées', str_competence], ['Plus-value sur le CFC ASE', str_sous_competence], ['Objectifs', str_objectif], ['Didactique', module.didactique], ['Evaluation', module.evaluation], ['Type', '{0}, obligatoire'.format(module.type)], ['Semestre', 'Sem. {0}'.format(module.semestre)], ['Présentiel', '{0} heures'.format(module.total_presentiel)], ['Travail personnel', '{0} heures'.format(module.travail_perso)], ['Responsable', module.processus.domaine.responsable.descr_pdf()] ] formated_data = [] for foo in data: formated_data.append([ Preformatted(foo[0], style_normal, maxLineLength=15), Preformatted(foo[1], style_normal, maxLineLength=85), ]) t = Table(data=formated_data, colWidths=[4 * cm, 13 * cm]) t.hAlign = TA_LEFT t.setStyle(tblstyle=TableStyle([ ('SIZE', (0, 0), (-1, -1), 7), ('ALIGN', (0, 0), (-1, -1), 'LEFT'), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LEFTPADDING', (0, 0), (-1, -1), 0), ])) self.story.append(t) self.build(self.story)
def chwstatus_pdf(request): # this is again some quick and dirty sample code elements = [] styles = getSampleStyleSheet() styles['Title'].alignment = TA_LEFT styles['Title'].fontName = styles['Heading2'].fontName = "Helvetica" styles["Normal"].fontName = "Helvetica" styles["Normal"].fontSize = 10 styles["Normal"].fontWeight = "BOLD" filename = mkstemp(".pdf")[-1] doc = SimpleDocTemplate(filename) elements.append(Paragraph("RapidResponse MVP Kenya: CHW Last 30 Days Perfomance Report", styles['Title'])) clinics = Provider.objects.values('clinic').distinct() for clinic in clinics: queryset, fields = chwstatus_build_report(clinic["clinic"]) c = Facility.objects.filter(id=clinic["clinic"])[0] elements.append(Paragraph("%s" % c.name, styles['Heading3'])) data = [] header = False for row in queryset: if not header: data.append([f["name"] for f in fields]) header = True ctx = Context({"object": row }) values = [ Template(h["bit"]).render(ctx) for h in fields ] data.append(values) table = PDFTable(data,None,None,None,1) table.setStyle(TableStyle([ ('ALIGNMENT', (0,0), (-1,-1), 'LEFT'), ('LINEBELOW', (0,0), (-1,-0), 2, colors.black), ('LINEBELOW', (0,1), (-1,-1), 0.8, colors.lightgrey), ('FONT', (0,0), (-1, -1), "Helvetica", 8), ('ROWBACKGROUNDS', (0,0), (-1, -1), [colors.whitesmoke, colors.white]), ])) table.hAlign = "LEFT" elements.append(table) '''ctable = PDFTable(cdata) ctable.setStyle(TableStyle([ ('ALIGNMENT', (0,0), (-1,-1), 'LEFT'), ('FONT', (0,0), (-1, -1), "Helvetica", 8) ])) elements.append(ctable) ''' #elements.append(Paragraph("Created: %s" % datetime.now().strftime("%d/%m/%Y"), styles["Normal"])) #doc.pagesize = landscape(A4) doc.build(elements, onFirstPage=myFirstPage, onLaterPages=myLaterPages) response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = "attachment; filename=%s" % filename response.write(open(filename).read()) os.remove(filename) return response
def addDefaultTable(self,data): tblStyle = TableStyle([('TEXTCOLOR',(0,0),(-1,-1),black), ('VALIGN',(0,0),(-1,-1),'TOP'), ('INNERGRID',(0,0),(-1,-1),1,black), ('BOX',(0,0),(-1,-1),1,black), ('BACKGROUND',(0,0),(-1,0),lightblue)]) t = Table(data,colWidths="*") t.hAlign = 'LEFT' t.setStyle(tblStyle) self.story.append(t)
def addTable(datad): #al.debug("Adding data to table: " + str(datad)) t = Table(datad, cols * [ hpitch * unit ], rows * [ vpitch * unit ]) t.hAlign = "LEFT" t.setStyle(TableStyle([("VALIGN", (0,0), (-1,-1), "TOP")])) # If we have more than 8 labels vertically, use a smaller font if rows > 8: t.setStyle(TableStyle([("VALIGN", (0,0), (-1,-1), "TOP"), ("FONTSIZE", (0,0), (-1,-1), 8)])) elements.append(t)
def partab(left,right,tabamt): data = [[left,right]] t = Table(data) t.hAlign = 'LEFT' t.setStyle(TableStyle([('LEFTPADDING',(0,0),(1,0),0)])) t.setStyle(TableStyle([('TOPPADDING',(0,0),(1,0),0)])) t.setStyle(TableStyle([('BOTTOMPADDING',(0,0),(1,0),0)])) t.setStyle(TableStyle([('ALIGN',(0,0),(1,0),'LEFT')])) t._argW[0]=tabamt return t
def build_index_Finds(self, records, sito): home = os.environ['PYARCHINIT_HOME'] home_DB_path = '{}{}{}'.format(home, os.sep, 'pyarchinit_DB_folder') logo_path = '{}{}{}'.format(home_DB_path, os.sep, 'logo.jpg') logo = Image(logo_path) logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth logo.drawWidth = 1.5 * inch logo.hAlign = "LEFT" styleSheet = getSampleStyleSheet() styNormal = styleSheet['Normal'] styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.pink) styH1 = styleSheet['Heading3'] data = self.datestrfdate() lst = [] lst.append(logo) lst.append( Paragraph( "<b>ELENCO MATERIALI</b><br/><b>Scavo: %s, Data: %s</b>" % (sito, data), styH1)) table_data = [] for i in range(len(records)): exp_index = FINDS_index_pdf_sheet(records[i]) table_data.append(exp_index.getTable()) styles = exp_index.makeStyles() colWidths = [70, 110, 110, 110, 35, 35, 60, 60, 60, 60] table_data_formatted = Table(table_data, colWidths, style=styles) table_data_formatted.hAlign = "LEFT" lst.append(table_data_formatted) lst.append(Spacer(0, 0)) filename = '{}{}{}'.format(self.PDF_path, os.sep, 'elenco_materiali.pdf') f = open(filename, "wb") doc = SimpleDocTemplate(f, pagesize=(29 * cm, 21 * cm), showBoundary=0, topMargin=15, bottomMargin=40, leftMargin=30, rightMargin=30) doc.build(lst, canvasmaker=NumberedCanvas_FINDSindex) f.close()
def data_print(self): start_date = self.entryStartDate.get() print(start_date) end_date = self.entryEndDate.get() print(end_date) mydb = mysql.connector.connect(host="localhost", user="******", passwd="root", database="SCADA") mycursor = mydb.cursor() mycursor.execute( "SELECT * FROM sensor1 WHERE time BETWEEN '%s' AND '%s' " % (start_date, end_date)) myresult = mycursor.fetchall() for x in myresult: print( str(x[0]) + " Temperature : " + str(x[1]) + " RH : " + str(x[2])) pdfReportPages = "report.pdf" doc = SimpleDocTemplate(pdfReportPages, pagesize=A4) # container for the "Flowable" objects elements = [] styles = getSampleStyleSheet() styleN = styles["Normal"] # Make heading for each column and start data list column1Heading = "Time" column2Heading = "Temperature (°C)" column3Heading = "RH (%)" # Assemble data for each column using simple loop to append it into data list data = [[column1Heading, column2Heading, column3Heading]] for x in myresult: data.append([str(x[0]), str(x[1]), str(x[2])]) tableThatSplitsOverPages = Table(data, [4 * cm, 2.9 * cm, 2.5 * cm], repeatRows=1) tableThatSplitsOverPages.hAlign = 'CENTRE' tblStyle = TableStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LINEBELOW', (0, 0), (-1, -1), 1, colors.black), ('BOX', (0, 0), (-1, -1), 1, colors.black), ('BOX', (1, 0), (-2, -1), 1, colors.black), ('BOX', (0, 0), (0, -1), 1, colors.black)]) tblStyle.add('BACKGROUND', (0, 0), (-1, 0), colors.lightblue) tblStyle.add('BACKGROUND', (0, 1), (-1, -1), colors.white) tableThatSplitsOverPages.setStyle(tblStyle) elements.append(tableThatSplitsOverPages) doc.build(elements) os.startfile('report.pdf')
def build_index_individui_de(self, records, sito): home = os.environ['PYARCHINIT_HOME'] conn = Connection() lo_path = conn.logo_path() lo_path_str = lo_path['logo'] home_DB_path = '{}{}{}'.format(home, os.sep, 'pyarchinit_DB_folder') if not bool(lo_path_str): logo_path = '{}{}{}'.format(home_DB_path, os.sep, 'logo.jpg') else: logo_path = lo_path_str logo = Image(logo_path) logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth logo.drawWidth = 1.5 * inch logo.hAlign = "LEFT" styleSheet = getSampleStyleSheet() styNormal = styleSheet['Normal'] styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.pink) styH1 = styleSheet['Heading3'] data = self.datestrfdate() lst = [] lst.append(logo) lst.append( Paragraph( "<b>LISTE INDIVIDUEL</b><br/><b>Ausgrabungsstätte: %s, Datum: %s</b>" % (sito, data), styH1)) table_data = [] for i in range(len(records)): exp_index = Individui_index_pdf_sheet(records[i]) table_data.append(exp_index.getTable_de()) styles = exp_index.makeStyles() colWidths = [60, 60, 60, 60, 60, 250] table_data_formatted = Table(table_data, colWidths, style=styles) table_data_formatted.hAlign = "LEFT" lst.append(table_data_formatted) # lst.append(Spacer(0,2)) filename = '{}{}{}'.format(self.PDF_path, os.sep, 'liste_individuel.pdf') f = open(filename, "wb") doc = SimpleDocTemplate(f, pagesize=(29 * cm, 21 * cm), showBoundary=0) doc.build(lst, canvasmaker=NumberedCanvas_Individuiindex) f.close()
def render(self): venue = [["\uf017", Paragraph(self.time, styles["xs-event"])], ["\uf041", Paragraph(self.venue_name, styles["xs-event"])], ["", Paragraph(self.place, styles["xs-event"])]] table = Table(venue, style=self.table_style, spaceAfter=8, colWidths=[8, None]) table.hAlign = "LEFT" table.vAlign = "TOP" return KeepTogether([ Paragraph(self.name, styles["xs-event-title"]), table, ])
def addTable(datad): #al.debug("Adding data to table: " + str(datad)) t = Table(datad, cols * [hpitch * unit], rows * [vpitch * unit]) t.hAlign = "LEFT" t.setStyle(TableStyle([("VALIGN", (0, 0), (-1, -1), "TOP")])) # If we have more than 8 labels vertically, use a smaller font if rows > 8: t.setStyle( TableStyle([("VALIGN", (0, 0), (-1, -1), "TOP"), ("FONTSIZE", (0, 0), (-1, -1), 8)])) elements.append(t)
def build_index_US(self, records, sito): if os.name == 'posix': home = os.environ['HOME'] elif os.name == 'nt': home = os.environ['HOMEPATH'] home_DB_path = ('%s%s%s') % (home, os.sep, 'pyarchinit_DB_folder') logo_path = ('%s%s%s') % (home_DB_path, os.sep, 'logo.jpg') logo = Image(logo_path) logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth logo.drawWidth = 1.5 * inch logo.hAlign = "LEFT" styleSheet = getSampleStyleSheet() styNormal = styleSheet['Normal'] styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.pink) styH1 = styleSheet['Heading3'] data = self.datestrfdate() lst = [] lst.append(logo) lst.append( Paragraph( "<b>ELENCO UNITA' STRATIGRAFICHE</b><br/><b>Scavo: %s, Data: %s</b>" % (sito, data), styH1)) table_data = [] for i in range(len(records)): exp_index = US_index_pdf_sheet(records[i]) table_data.append(exp_index.getTable()) styles = exp_index.makeStyles() colWidths = [28, 28, 120, 45, 58, 45, 58, 55, 64, 64, 52, 52, 52] table_data_formatted = Table(table_data, colWidths, style=styles) table_data_formatted.hAlign = "LEFT" lst.append(table_data_formatted) lst.append(Spacer(0, 2)) dt = datetime.datetime.now() filename = ('%s%s%s_%s_%s_%s_%s_%s_%s%s') % ( self.PDF_path, os.sep, 'elenco_us', dt.day, dt.month, dt.year, dt.hour, dt.minute, dt.second, ".pdf") f = open(filename, "wb") doc = SimpleDocTemplate(f, pagesize=(29 * cm, 21 * cm), showBoundary=0) doc.build(lst, canvasmaker=NumberedCanvas_USindex) f.close()
def download_pdf_1klasse_1run(request, klasse, run): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="Klasse{0}_{1}.pdf" '.format(klasse,run) # buffer buffer = io.BytesIO() # create pdf object p = canvas.Canvas(buffer, pagesize=landscape(A4)) styles =getSampleStyleSheet() styleBH = styles["Normal"] styleBH.alignment = TA_CENTER # Insert the content to the pdf, done with Reportlab documentation klassen = Schulklasse.objects.order_by('Name') lehrers = Lehrer.objects.order_by('Name') tage = Tag.objects.order_by('Index') stunden = Stunde.objects.order_by('Index') Run = OptimierungsErgebnis.objects.get(Index=run) data= [['Stunden']] for tag in tage: data[0].append(str(tag.Tag).encode('utf-8')) for stunde in stunden: data.append([str(stunde.Stunde).encode('utf-8')]) for tag in tage: data[-1].append("") Klasse = Schulklasse.objects.get(Name=klasse) for stunde in stunden: for tag in tage: celldata= Klasse.lehreinheit_set.filter(Zeitslot__Stunde=stunde, Zeitslot__Tag=tag, run=Run).all() cellobject = "" for lehreinheit in celldata: row_num = stunde.Index tag_num = tag.Index cellobject += "{0} ({1})\n".format(lehreinheit.Schulfach.Name, lehreinheit.Lehrer.Kurzname) data[row_num][tag_num] = cellobject width, height = A4 table = Table(data, hAlign='RIGHT') table.setStyle(TableStyle([ ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('BACKGROUND',(0,0),(-1,0),colors.lavender), ('BACKGROUND',(0,0),(0,-1),colors.lavender), ('INNERGRID',(0,0),(-1,-1),0.25, colors.black) ])) table.wrapOn(p, width, height) table.drawOn(p, 5*cm, 6*cm) table.hAlign='TA_CENTER' p.showPage() p.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
def build_index_AR(self, records, divelog_id): HOME = os.environ['HFF_HOME'] PDF_path = '{}{}{}'.format(HOME, os.sep, "HFF_PDF_folder") home_DB_path = '{}{}{}'.format(HOME, os.sep, 'HFF_DB_folder') logo_path = '{}{}{}'.format(home_DB_path, os.sep, 'banner.png') logo = Image(logo_path) ## if test_image.drawWidth < 800: logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth logo.drawWidth = 1.5 * inch # logo_path2 = '{}{}{}'.format(home_DB_path, os.sep, 'logo2.png') # logo2 = Image(logo_path2) # ## if test_image.drawWidth < 800: # logo2.drawHeight = 0.5*inch*logo2.drawHeight / logo2.drawWidth # logo2.drawWidth = 0.5*inch # #1 row logo.hAlign = "LEFT" styleSheet = getSampleStyleSheet() styNormal = styleSheet['Normal'] styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.pink) styH1 = styleSheet['Heading3'] data = self.datestrfdate() lst = [] lst.append(logo) lst.append( Paragraph("<b>Artefact List</b><br/><b>Data: %s</b>" % (data), styH1)) table_data1 = [] for i in range(len(records)): exp_index = AR_index_pdf(records[i]) table_data1.append(exp_index.getTable()) styles = exp_index.makeStyles() colWidths = [42, 60, 45, 45, 45, 58, 45, 58, 55, 64, 64, 52, 52, 65] table_data1_formatted = Table(table_data1, colWidths, style=styles) table_data1_formatted.hAlign = "LEFT" lst.append(table_data1_formatted) lst.append(Spacer(0, 2)) filename = '{}{}{}'.format(self.PDF_path, os.sep, 'artefact_list.pdf') f = open(filename, "wb") doc = SimpleDocTemplate(f, pagesize=(29 * cm, 21 * cm), showBoundary=0) doc.build(lst, canvasmaker=NumberedCanvas_USindex) f.close()
def add_header_content(elements): styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) styles.add(ParagraphStyle(name='Left', alignment=TA_LEFT)) # get environmental scenario data # Column headers for ev data # BUName,EVName,UseMetric,Wind,Slope,FM1,FM10,FM100,FM1000,FMDuff,FMHerb,FMShrub,ConCanopy,ConShrub,ConPiles ev = ev_data.ev_data() bu_name = 'None' if not ev.valid else ev.get_parameter_value('BUName') ev_name = 'None' if not ev.valid else ev.get_parameter_value('EVName') use_metric = ev.get_parameter_value('UseMetric') # Title ptext = '<font size={}>FCCS 3.0 Surface Fire Behavior Report</font>'.format( const.FONTSIZE_TITLE) elements.append(Paragraph(ptext, styles["Center"])) # Table for date, bu name, and ev name cols = [70, 200] header_data = [] today = datetime.date.today() header_data.append( ['Report date:', '{}'.format(today.strftime('%B %d, %Y'))]) header_data.append(['Unit Name:', '{}'.format(bu_name)]) header_data.append(['EV Name:', '{}'.format(ev_name)]) header_table = Table(header_data, colWidths=cols) header_table.hAlign = 'LEFT' tbl_style = TableStyle([('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('ALIGN', (0, 0), (-1, 1), 'LEFT'), ('LEFTPADDING', (0, 0), (-1, -1), 0), ('LEADING', (0, 0), (-1, -1), 4), ('FONTSIZE', (0, 0), (-1, -1), 10)]) header_table.setStyle(tbl_style) elements.append(Spacer(1, 6)) elements.append(header_table) elements.append(Spacer(1, 6)) explanatory_text = '<font size=8>The surface fire behavior report includes predicted surface fire rate of spread (ROS), flame length (FL), and total reaction intensity (RI) and reaction intensity by surface fuel stratum including shrubs, herb, wood, and litter-lichen-moss (LLM).' elements.append(Paragraph(explanatory_text, styles["Left"])) elements.append(Spacer(1, 6)) ptext = '<font size=8>Parameters:\tWind ({}{}) Slope ({}%) 1hrFM ({}%) 10hrFM ({}%) 100hrFM ({}%) ShrubFM ({}%) HerbFM ({}%)</font>'.format( ev.get_parameter_value('Wind'), 'kph' if use_metric else "mph", ev.get_parameter_value('Slope'), ev.get_parameter_value('FM1'), ev.get_parameter_value('FM10'), ev.get_parameter_value('FM100'), ev.get_parameter_value('FMShrub'), ev.get_parameter_value('FMHerb')) elements.append(Paragraph(ptext, styles["Normal"])) elements.append(Spacer(1, 6))
def ejcritRejsolution(self, tropDeSolutions, nbRejsolutions, nbCellulesOccupees, valeurs, verts): # commence par afficher les grilles en attente self.pdfGrilles() miniGrilleStyle = self.grilleStyle() miniGrilleStyle.extend([('FONTSIZE', (0, 0), (-1, -1), 7), ('TOPPADDING', (0, 0), (-1, -1), 4)]) texte = ''' Un programme qui n'est pas du tout anthropomorphique celui-là, a rejsolu prejventivement la grille proposeje... <br/>qui a %d cellules dejjah affectejes... <br/>''' % (nbCellulesOccupees) if nbRejsolutions == 0: texte += """<b>Cette grille n'a aucune solution !! </b> <br/>Le sudoku anthropomorphique n'en trouvera donc pas... """ elif tropDeSolutions: texte += """<b>Cette grille a plus de %d solutions !!</b> <br/>Le sudoku anthropomorphique n'en trouvera donc pas parce qu'il ne sait pas faire de choix... """ % (nbRejsolutions) elif nbRejsolutions == 1: texte += """<b>Cette grille a une solution et une seule ! </b> <br/>Le sudoku anthropomorphique va faire ce qu'il peut pour la trouver... """ else: texte += """<b>Cette grille a %d solutions ! </b> <br/>Le sudoku anthropomorphique n'en trouvera donc pas parce qu'il ne sait pas faire de choix... """ % (nbRejsolutions) if nbRejsolutions == 1: grilleValeurs = [['' for i in range(9)] for i in range(9)] for (x, y), valeur in valeurs: grilleValeurs[x][y] = str(valeur) for x, y in verts: miniGrilleStyle.append( ('BACKGROUND', (y, x), (y, x), colors.lightgreen)) #cree la table avec les valeurs et la taille de chaque cellule grille = Table(grilleValeurs, C_CEL2, C_CEL2) grille.setStyle(miniGrilleStyle) table = Table([[Paragraph(texte, self.explicationsStyle), grille]], [14.2 * cm, C_TAB2 + 2 * C_CEL2]) table.setStyle([ #('INNERGRID', (0,0), (-1,-1), 0.1, colors.black), #('BOX', (0,0), (-1,-1), 0.1, colors.black), ('LEFTPADDING', (0, 0), (-1, -1), 0), ('ALIGN', (0, 0), (-1, -1), 'LEFT'), ('VALIGN', (0, 0), (-1, -1), 'TOP') ]) table.hAlign = "LEFT" self.flowables.append(KeepTogether(table)) else: self.flowables.append( KeepTogether(Paragraph(texte, self.explicationsStyle)))
def build_index_Documentazione(self, records, sito): if os.name == 'posix': home = os.environ['HOME'] elif os.name == 'nt': home = os.environ['HOMEPATH'] home_DB_path = ('%s%s%s') % (home, os.sep, 'pyarchinit_DB_folder') logo_path = ('%s%s%s') % (home_DB_path, os.sep, 'logo.jpg') logo = Image(logo_path) logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth logo.drawWidth = 1.5 * inch logo.hAlign = "LEFT" styleSheet = getSampleStyleSheet() styNormal = styleSheet['Normal'] styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.pink) styH1 = styleSheet['Heading3'] data = self.datestrfdate() lst = [] lst.append(logo) lst.append( Paragraph( "<b>ELENCO DOCUMENTAZIONE</b><br/><b>Scavo: %s, Data: %s</b>" % (sito, data), styH1)) table_data = [] for i in range(len(records)): exp_index = Documentazione_index_pdf_sheet(records[i]) table_data.append(exp_index.getTable()) styles = exp_index.makeStyles() colWidths = [100, 100, 60, 60, 60, 150] table_data_formatted = Table(table_data, colWidths, style=styles) table_data_formatted.hAlign = "LEFT" lst.append(table_data_formatted) #lst.append(Spacer(0,2)) filename = ('%s%s%s') % (self.PDF_path, os.sep, 'elenco_documentazione.pdf') f = open(filename, "wb") doc = SimpleDocTemplate(f, pagesize=(29 * cm, 21 * cm), showBoundary=0) doc.build(lst, canvasmaker=NumberedCanvas_Documentazioneindex) f.close()
def pdf_report(dir, report_data): filename = os.path.join(dir, "Entfernungspauschale.pdf") zeilen = [ ['Datum', 'Adresse', 'Kunde', 'Entfernung\n(km)'], ] for fahrten in report_data["eindeutige_fahrten"].values(): for fahrt in fahrten: # Fahrten am Tag adresse = fahrt["adresse"] adresse = adresse.replace(", ", "\n") zeilen.append([fahrt["datum"], adresse, fahrt["kunde"], fahrt["entfernung"]]) styles = getSampleStyleSheet() doc = SimpleDocTemplate(filename, pagesize=A4, topMargin=15 * mm, bottomMargin=15 * mm, title="Entfernungspauschale") story = list() story.append(Paragraph('Fahrtenliste', styles['Heading1'])) story.append(Paragraph(report_data["name"] or "", styles['Heading2'])) story.append(Paragraph(report_data["report_beschreibung"], styles['Heading3'])) t = Table(zeilen, colWidths=[80, 200, 100, 60], repeatRows=(0,)) t.hAlign = 'LEFT' t.spaceBefore = 10 t.spaceAfter = 10 t.setStyle(TableStyle( [('BOX', (0, 0), (-1, -1), 0.5, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey), ('INNERGRID', (0, 0), (-1, -1), 0.5, colors.black)])) story.append(t) story.append(Paragraph(' ', styles['Normal'])) story.append(Paragraph(f'Insgesamt gefahrene Strecke: {report_data["summe_entfernung"]} km.', styles['Normal'])) story.append(Paragraph(' ', styles['Normal'])) kilometerpauschale_faktor = _format_decimal(report_data["kilometerpauschale_faktor"]) kilometerpauschale = _format_decimal(report_data["kilometerpauschale"]) story.append(Paragraph( f'Entfernungspauschale: {report_data["summe_entfernung"]} km' f' * {kilometerpauschale_faktor} EUR/km' f' = <b>{kilometerpauschale} EUR</b>', styles['Normal'])) title = f"Fahrtenliste: {report_data['von']} - {report_data['bis']}" def _onLaterPages(canvas, doc): canvas.saveState() canvas.setFont('Helvetica', 8) canvas.drawString(10 * mm, 10 * mm, title) canvas.restoreState() doc.build(story, canvasmaker=NumberedCanvas, onLaterPages=_onLaterPages) return filename
def addTableIpSrc(self,ndata): data = [["Group","Ip Source","Count"]] for i in ndata: data.append([i["group_name"],i["ip_src"],i["ip_src_count"]]) tblStyle = TableStyle([('TEXTCOLOR',(0,0),(-1,-1),black), ('VALIGN',(0,0),(-1,-1),'TOP'), ('BOX',(0,0),(-1,-1),1,black), ('INNERGRID',(0,0),(-1,-1),1,black), ('BACKGROUND',(0,0),(2,0),lightblue)]) t = Table(data,colWidths="*") t.hAlign = 'LEFT' t.setStyle(tblStyle) self.story.append(t)
def FullLine(self, line, value): self.story.append(Spacer(0, .1 * inch)) self.PGraph(line) result = Table([["", value]], colWidths = [inch*.2, inch*4]) result.setStyle( TableStyle( [('LINEBELOW', (1, 0), (1, -1), 0.5, colors.black), ('BOTTOMPADDING', (0,0), (0,-1), 0), ('TOPPADDING', (0, 0), (0, -1), 5), ] )) result.hAlign = 'LEFT' self.story.append(result)
def make_pdf_dividends_table(df: pd.DataFrame): """Формирует и форматирует pdf таблицу с дивидендными выплатами""" data = make_list_of_lists_dividends(df) style = TableStyle([('LINEBEFORE', (1, 0), (1, -1), LINE_WIDTH, LINE_COLOR), ('LINEABOVE', (0, 1), (-1, 2), LINE_WIDTH, LINE_COLOR), ('ALIGN', (1, 1), (-1, -1), 'RIGHT'), ('ALIGN', (0, 0), (0, -1), 'CENTRE')]) table = Table(data=data, style=style) table.hAlign = 'LEFT' return table
def make_story(text, width, colors): for x in range(len(text)): t0 = Table([text[x]], colWidths=width[x]) t0.hAlign = "LEFT" for i in range(len(colors[x])): t0.setStyle( TableStyle([('GRID', (0, 0), (-1, -1), 1, black), ('BACKGROUND', (i, 0), (i, 0), colors[x][i])])) elements.append(t0)
def make_pdf_table(df: pd.DataFrame): """Формирует и форматирует pdf-таблицу доходности портфеля и индекса""" data = make_list_of_lists_table(df) style = TableStyle([('LINEBEFORE', (1, 0), (1, -1), LINE_WIDTH, LINE_COLOR), ('LINEABOVE', (0, 1), (-1, 2), LINE_WIDTH, LINE_COLOR), ('ALIGN', (1, 1), (-1, -1), 'RIGHT'), ('ALIGN', (0, 0), (-1, 0), 'CENTRE')]) table = Table(data, style=style) table.hAlign = 'LEFT' return table
def table(self, data, styles, colWidths=(10, ), styleTable=False): table = Table( self.tabelize(data, styles), colWidths=self.columnize(*colWidths) ) table.hAlign = 'LEFT' if styleTable: table.setStyle(TableStyle([ ('BOX', (0,0), (-1,-1), 0.5, colors.black), ('INNERGRID', (0,0), (-1,-1), 0.5, colors.black), ('VALIGN', (0,0), (-1,-1), 'MIDDLE'), ])) return table
def __lc_abandon(self, typeEvenement): abandonPresta_data = [[self.__abandon_checkbox(typeEvenement), u"A ABANDONNE EN COURS DE PRESTATION A LA DATE DU: " + self.__abandon_date(typeEvenement)], [None, Paragraph(u"<strong>Indiquer le motif: </strong>" + self.__abandon_motif(typeEvenement), self.paragraph_style) ] ] colWidths = [25, 500] abandonPresta_style = TableStyle([('FONTSIZE', (1,0), (1,0), self.grandePolice), ('VALIGN',(1,0),(1,0),'TOP'), ('FONTSIZE', (1,1), (1,1), self.basePolice), ]) abandonPresta = Table(abandonPresta_data, style=abandonPresta_style, colWidths=colWidths) abandonPresta.hAlign = 0 abandonPresta.spaceAfter = 20 self.elements.append(abandonPresta)
def build_index_Foto_2(self, records, sito): home = os.environ['HFF_HOME'] home_DB_path = '{}{}{}'.format(home, os.sep, 'HFF_DB_folder') logo_path = '{}{}{}'.format(home_DB_path, os.sep, 'banner.png') logo = Image(logo_path) logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth logo.drawWidth = 1.5 * inch logo.hAlign = "LEFT" styleSheet = getSampleStyleSheet() styNormal = styleSheet['Normal'] styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.pink) styH1 = styleSheet['Heading3'] data = self.datestrfdate() lst = [] lst.append(logo) lst.append( Paragraph( "<b>List photo artefact</b><br/><b> Site: %s, Date: %s</b>" % (sito, data), styH1)) table_data = [] for i in range(len(records)): exp_index = FOTO_index_pdf_sheet_2(records[i]) table_data.append(exp_index.getTable()) styles = exp_index.makeStyles() colWidths = [70, 70, 70, 200] table_data_formatted = Table(table_data, colWidths, style=styles) table_data_formatted.hAlign = "LEFT" lst.append(table_data_formatted) lst.append(Spacer(0, 2)) dt = datetime.datetime.now() filename = ('%s%s%s_%s_%s_%s_%s_%s_%s%s') % ( self.PDF_path, os.sep, 'List photo artefact', dt.day, dt.month, dt.year, dt.hour, dt.minute, dt.second, ".pdf") f = open(filename, "wb") doc = SimpleDocTemplate(f, pagesize=A4) doc.build(lst, canvasmaker=NumberedCanvas_USsheet) f.close()
def report(self, asistencia, title): doc = SimpleDocTemplate( self.buffer, rightMargin=72, leftMargin=72, topMargin=30, bottomMargin=72, pagesize=self.pageSize) styles = getSampleStyleSheet() styles.add(ParagraphStyle( name="TableHeader", fontSize=11, alignment=TA_CENTER,)) styles.add(ParagraphStyle( name="ParagraphTitle", fontSize=11, alignment=TA_JUSTIFY)) styles.add(ParagraphStyle( name="Justify", alignment=TA_JUSTIFY)) # create document data = [] data.append(Paragraph(title, styles['Title'])) data.append(Paragraph("Proyecto: {0}".format(asistencia.proyecto), styles["Heading2"])) data.append(Paragraph("Responsable: {}".format(asistencia.proyecto.responsable_rel.persona), styles["Heading2"])) total = asistencia.items.count() presentes = asistencia.items.filter(estado__no_ocioso=True).count() prec_percentage = [presentes, (total-presentes), ] llabels = ['% presentes', '% ausentes', ] pie_chart = self.pie_chart_draw(prec_percentage, llabels) data.append(pie_chart) table_data = [] # table header table_data.append([ Paragraph('Nombre', styles['TableHeader']), Paragraph('Estado de asistencia', styles['TableHeader']),]) for item in asistencia.items.all().order_by('persona'): table_data.append([ item.persona, item.estado]) wh_table = Table(table_data, colWidths=[doc.width/8.0*5, doc.width/8.0*3]) wh_table.hAlign = 'LEFT' wh_table.setStyle(TableStyle( [('INNERGRID', (0, 0), (-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)])) data.append(wh_table) doc.build(data, onFirstPage=self.pageNumber, onLaterPages=self.pageNumber) pdf = self.buffer.getvalue() self.buffer.close() return pdf
def assemble_document(datafile, outfile, pollutant): # create the document doc = create_document(output_filename) # "Flowable" objects container elements = [] # header content add_header_content(elements, pollutant) # retrieve data and set up column spacing contents = get_content(datafile, pollutant) cols = [ 45, 110, 65, 65, 65, 65, 65, 65, 65 ] # Assemble data for each column using simple loop to append it into data list data = [] data.append([i.split('~')[0] if '~' in i else i for i in contents.columns.tolist()]) # add the actual data for i in contents.index: data.append(list(contents.irow(i).values)) # add the table style -- this applies formatting to the table table_that_splits_over_pages= Table(data, colWidths=cols, repeatRows=1) table_that_splits_over_pages.hAlign = 'LEFT' tbl_style = TableStyle([('TEXTCOLOR',(0,0),(-1,-1),colors.black), ('VALIGN',(0,0),(-1,-1),'TOP'), ('ALIGN',(0,0),(0,0), 'CENTER'), ('FONTSIZE',(0,1),(-1,-1),8), ('INNERGRID', (0,1), (-1,-1), 0.5, colors.black), ('BOX',(0,0),(-1,1),1,colors.black), ('BOX',(0,1),(-1,-1),1,colors.black)]) tbl_style.add('BACKGROUND',(0,0),(-1,1),colors.lightblue) tbl_style.add('BACKGROUND',(0,1),(-1,-1),colors.white) table_that_splits_over_pages.setStyle(tbl_style) elements.append(table_that_splits_over_pages) # - put it all together doc.build(elements, canvasmaker=num_canvas.NumberedCanvas)
def addTableIpDstByGroup(self,ndata): data = [["IP Dst","Count"]] for i in ndata: data.append([i["ip_dst"],i["ip_dst_count"]]) tblStyle = TableStyle([('TEXTCOLOR',(0,0),(-1,-1),black), ('VALIGN',(0,0),(-1,-1),'TOP'), ('LINEBELOW',(0,0),(-1,-1),1,black), ('BOX',(0,0),(-1,-1),1,black), ('BOX',(0,0),(0,-1),1,black), ('BACKGROUND',(0,0),(1,0),lightblue)]) t = Table(data,colWidths="*") t.hAlign = 'LEFT' t.setStyle(tblStyle) self.story.append(t)
def add_header_content(elements): styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) # get environmental scenario data # Column headers for ev data # BUName,EVName,UseMetric,Wind,Slope,FM1,FM10,FM100,FM1000,FMDuff,FMHerb,FMShrub,ConCanopy,ConShrub,ConPiles ev = ev_data.ev_data() bu_name = 'None' if not ev.valid else ev.get_parameter_value('BUName') use_metric = ev.get_parameter_value('UseMetric') unitsize = ev.get_parameter_value('UnitSize') permit = ev.get_parameter_value('Permit') fire_type = ev.get_parameter_value('Type') # Title ptext = '<font size={}>Consume 4.2 Consumption by Stratum Report</font>'.format( const.FONTSIZE_TITLE) elements.append(Paragraph(ptext, styles["Center"])) # Table for date, bu name, and ev name cols = [100, 200] header_data = [] today = datetime.date.today() header_data.append( ['Report date:', '{}'.format(today.strftime('%B %d, %Y'))]) header_data.append(['Unit Name:', '{}'.format(bu_name)]) header_data.append([ 'Units of measure:', '{}'.format('Mg/ha' if use_metric else "tons/acre") ]) header_data.append(['Unit size:', '{}'.format(unitsize)]) header_data.append( ['Fire type:', '{}'.format("" if 0.0 == fire_type else fire_type)]) header_data.append( ['Permit#:', '{}'.format("" if 0.0 == permit else permit)]) header_table = Table(header_data, colWidths=cols) header_table.hAlign = 'LEFT' tbl_style = TableStyle([('TEXTCOLOR', (0, 0), (-1, -1), colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('ALIGN', (0, 0), (-1, 1), 'LEFT'), ('LEFTPADDING', (0, 0), (-1, -1), 0), ('LEADING', (0, 0), (-1, -1), 4), ('FONTSIZE', (0, 0), (-1, -1), 10)]) header_table.setStyle(tbl_style) elements.append(Spacer(1, 6)) elements.append(header_table) elements.append(Spacer(1, 12))
def appendix7(self): self.new_page() self.add_to_toc('Приложение 7', 'Протокол теплового контроля') self.put('Приложение 7', 'Regular Right Italic', 0.5) self.zakl_header('теплового контроля') self.measurers('инфракрас') self.spacer(.3) image1 = self.fetch_image( FileStorage.objects.get(pk=self.data['files']['therm1'][0]['id']).fileupload, height=7, width=7 ) image2 = self.fetch_image( FileStorage.objects.get(pk=self.data['files']['therm2'][0]['id']).fileupload, height=7, width=7 ) table_data = [[image1, image2]] table = Table(table_data,colWidths=self.columnize(5, 5)) table.hAlign = 'CENTER' table_style = ( ('VALIGN', (0,0), (-1,-1), 'MIDDLE'), ('ALIGN', (0,0), (-1,-1), 'CENTER'), ('TOPPADDING', (0,0), (-1,-1), 0), ('BOTTOMPADDING', (0,0), (-1,-1), 3), ) table.setStyle(TableStyle(table_style)) self.Story.append(table) self.spacer(0.2) therm_data = self.data['therm'] tc = ThermClass.objects.get(pk=therm_data['tclass']) therm_data.update(dict(tclass=tc.get_name_display(), tclass_t_max=str(tc.t_max))) template = [ ['Температурный класс', '{tclass}'], ['Максимально допустимая температура поверхности оболочки, °C', '{tclass_t_max}'], ['Расстояние до объекта, м', '{distance}'], ['Температура окружающей среды, °С', '{temp_env}'], ['Максимальная температура, °С', '{temp_max}'], ['Минимальная температура, °С', '{temp_min}'], ['Средняя температура, °С', '{temp_avg}'], ['Соответствие норме', '{correct}'], ] para_style = ( ('Regular', 'Regular Center Tall'), ) self.add(template, [8,2], self.get_style(para_style, template), table_style, data=therm_data, styleTable=True, spacer=.5 ) self.category_controller('ТК')
def build_index_Casse(self, records, sito): if os.name == "posix": home = os.environ["HOME"] elif os.name == "nt": home = os.environ["HOMEPATH"] home_DB_path = ("%s%s%s") % (home, os.sep, "pyarchinit_DB_folder") logo_path = ("%s%s%s") % (home_DB_path, os.sep, "logo.jpg") logo = Image(logo_path) logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth logo.drawWidth = 1.5 * inch logo.hAlign = "LEFT" styleSheet = getSampleStyleSheet() styNormal = styleSheet["Normal"] styBackground = ParagraphStyle("background", parent=styNormal, backColor=colors.pink) styH1 = styleSheet["Heading3"] data = self.datestrfdate() lst = [logo] lst.append(Paragraph("<b>ELENCO CASSE CAMPIONI</b><br/><b>Scavo: %s, Data: %s</b>" % (sito, data), styH1)) table_data = [] for i in range(len(records)): exp_index = CASSE_index_pdf_sheet(records[i]) table_data.append(exp_index.getTable()) styles = exp_index.makeStyles() colWidths = [20, 350, 250, 100] table_data_formatted = Table(table_data, colWidths, style=styles) table_data_formatted.hAlign = "LEFT" # table_data_formatted.setStyle(styles) lst.append(table_data_formatted) lst.append(Spacer(0, 0)) filename = ("%s%s%s") % (self.PDF_path, os.sep, "elenco_casse_campioni.pdf") f = open(filename, "wb") doc = SimpleDocTemplate( f, pagesize=(29 * cm, 21 * cm), showBoundary=0, topMargin=15, bottomMargin=40, leftMargin=30, rightMargin=30 ) # doc.build(lst, canvasmaker=NumberedCanvas_Sindex) doc.build(lst) f.close()
def build_index_Periodizzazione_en(self, records, sito): home = os.environ['PYARCHINIT_HOME'] home_DB_path = '{}{}{}'.format(home, os.sep, 'pyarchinit_DB_folder') logo_path = '{}{}{}'.format(home_DB_path, os.sep, 'logo.jpg') logo = Image(logo_path) logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth logo.drawWidth = 1.5 * inch logo.hAlign = "LEFT" styleSheet = getSampleStyleSheet() styNormal = styleSheet['Normal'] styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.pink) styH1 = styleSheet['Heading3'] data = self.datestrfdate() lst = [] lst.append(logo) lst.append( Paragraph( "<b>LIST PERIODIZATION</b><br/><b>Site: %s, Date: %s</b>" % (sito, data), styH1)) table_data = [] for i in range(len(records)): exp_index = Periodizzazione_index_pdf_sheet(records[i]) table_data.append(exp_index.getTable_en()) styles = exp_index.makeStyles() colWidths = [60, 60, 150, 150, 300] table_data_formatted = Table(table_data, colWidths, style=styles) table_data_formatted.hAlign = "LEFT" lst.append(table_data_formatted) # lst.append(Spacer(0,2)) filename = '{}{}{}'.format(self.PDF_path, os.sep, 'list_periodization.pdf') f = open(filename, "wb") doc = SimpleDocTemplate(f, pagesize=(29 * cm, 21 * cm), showBoundary=0) doc.build(lst, canvasmaker=NumberedCanvas_Periodizzazioneindex) f.close()
def formatData(tabledata, doc): elements = [] constData = [] #elements.append(GraphicsFlowable(tabledata[4])) elements.append(Spacer(width=1, height=30)) style = ParagraphStyle(name='Normal', fontName='Helvetica-Bold', fontSize=9,) elements.append(Paragraph("Constant Data",style)) med = int(round(float(len(tabledata[1]))/2)) for index, item in enumerate(tabledata[1]): if index < med: constData.append([tabledata[0][index]+":", item]) else: constData[index-med].append(tabledata[0][index]+":") constData[index-med].append(item) const = Table(constData,4*[doc.width/4]) const.hAlign = "LEFT" const.setStyle(TableStyle([('BOX', (0,0), (-1,-1), 0.25, colors.black), ('LINEABOVE', (0,0), (3,0), 2, colors.black), ('LEFTPADDING', (1,0), (1,-1), 10), ('LEFTPADDING', (3,0), (3,-1), 10)])) elements.append(const) if tabledata[3]: elements.append(Paragraph("Event Data",style)) for datalist in tabledata[3]: varData = [] for i, item in enumerate(datalist): varData.append([tabledata[2][i], item]) var = Table(varData,2*[doc.width/2]) var.hAlign = "LEFT" var.setStyle(TableStyle([('BOX', (0,0), (-1,-1), 0.25, colors.black), ('LINEABOVE', (0,0), (3,0), 2, colors.black)])) elements.append(var) return elements
def add_table(self,data,para=False): def splitter(txt): if len(txt)>95: N = len(txt)/95 parts = [] for n in xrange(N): parts.append(txt[95*n:95*n+95]) parts.append(txt[95*N:]) txt = '' for p in parts: txt += p+'\n' return txt else: return txt data_para = [] for dat in data: temp = [] for da in dat: if isinstance(da,str): if da.endswith('.png'): temp.append(get_and_scale(da,0.35)) else: if para: temp.append(Paragraph(da,self.styles["Normal"])) else: if len(da) > 95: da = splitter(da) temp.append(da) else: if para: temp.append(Paragraph(str(da),self.styles["Normal"])) else: temp.append(da) data_para.append(temp) t=Table(data_para) t.setStyle(TableStyle([('ALIGN',(0,0), (-1,-1),'LEFT'), ('VALIGN',(0,0), (-1,-1), 'TOP'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black)])) t.hAlign='LEFT' self.elements.append(t) self.elements.append(Spacer(1, 12))
def build_index_US(self, records, sito): if os.name == 'posix': home = os.environ['HOME'] elif os.name == 'nt': home = os.environ['HOMEPATH'] home_DB_path = ('%s%s%s') % (home, os.sep, 'pyarchinit_DB_folder') logo_path = ('%s%s%s') % (home_DB_path, os.sep, 'logo.jpg') logo = Image(logo_path) logo.drawHeight = 1.5*inch*logo.drawHeight / logo.drawWidth logo.drawWidth = 1.5*inch logo.hAlign = "LEFT" styleSheet = getSampleStyleSheet() styNormal = styleSheet['Normal'] styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.pink) styH1 = styleSheet['Heading3'] data = self.datestrfdate() lst = [] lst.append(logo) lst.append(Paragraph("<b>ELENCO UNITA' STRATIGRAFICHE</b><br/><b>Scavo: %s, Data: %s</b>" % (sito, data), styH1)) table_data = [] for i in range(len(records)): exp_index = US_index_pdf_sheet(records[i]) table_data.append(exp_index.getTable()) styles = exp_index.makeStyles() colWidths=[28,28,120,45,58,45,58,55,64,64,52,52,52] table_data_formatted = Table(table_data, colWidths, style=styles) table_data_formatted.hAlign = "LEFT" lst.append(table_data_formatted) lst.append(Spacer(0,2)) dt = datetime.datetime.now() filename = ('%s%s%s_%s_%s_%s_%s_%s_%s%s') % (self.PDF_path, os.sep, 'elenco_us', dt.day, dt.month, dt.year, dt.hour, dt.minute, dt.second, ".pdf") f = open(filename, "wb") doc = SimpleDocTemplate(f, pagesize=(29*cm, 21*cm), showBoundary=0) doc.build(lst, canvasmaker=NumberedCanvas_USindex) f.close()
def AddTable(self, structure, col1Width=inch*1.5): result = Table(structure, # rowHeights = [inch*0.2], colWidths = [col1Width, inch*4]) result.setStyle( TableStyle( [('ALIGN', (0, 0), (0, -1), 'RIGHT'), ('VALIGN', (0, 0), (-1, -1), 'BOTTOM'), # ('VALIGN', (0, 1), (0, 1), 'TOP'), ('FONTSIZE', (0, 0), (0, -1), 8), ('LINEBELOW', (1, 0), (1, -1), 0.5, colors.black), ('BOTTOMPADDING', (0,0), (1,-1), 0), ('TOPPADDING', (0, 0), (1, -1), 10), ] )) result.hAlign = 'LEFT' self.story.append(result)
def SigLine(self, string): self.story.append(Spacer(0, .2 * inch)) result = Table([["", string, "", "Date"]], colWidths= [inch, inch*3, .2 * inch, inch*1]) result.setStyle( TableStyle( [('ALIGN', (1, 0), (1, -1), 'LEFT'), ('ALIGN', (2, 0), (2, -1), 'RIGHT'), ('VALIGN', (0, 0), (-1, -1), 'BOTTOM'), ('FONTSIZE', (0, 0), (-1, -1), 8), ('LINEABOVE', (1, 0), (1, 0), 0.5, colors.black), ('LINEABOVE', (3, 0), (3, 0), 0.5, colors.black), ('BOTTOMPADDING', (0,0), (1,-1), 0), ('TOPPADDING', (0, 0), (1, -1), 0), ] )) result.hAlign = 'LEFT' self.story.append(result)
def gerarCabecalho(self): textoLateral, linTexto = 'sua visão, perfeita', 1 estiloCabecalho = [ ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), ("HALIGN", (0, 0), (-1, -1), "LEFT"), ('FONTNAME', (0, linTexto), (-1, linTexto), 'Times-Bold'), ('ALIGN', (0, linTexto), (-1, linTexto), 'RIGHT'), ('FONTSIZE', (0,linTexto), (-1,linTexto), 13), ("VALIGN", (0, linTexto), (-1, linTexto), "TOP"), ] imgLogo = Image(dirname(abspath(sys.executable)) + "/famotica.jpg") # tamanho original: 360x86 imgLogo._restrictSize(200, 47) tabCabecalho = Table([ [imgLogo], [textoLateral] ]) tabCabecalho.setStyle(estiloCabecalho) tabCabecalho.hAlign = 'LEFT' return tabCabecalho
def build_index_Campioni(self, records, sito): if os.name == 'posix': home = os.environ['HOME'] elif os.name == 'nt': home = os.environ['HOMEPATH'] home_DB_path = ('%s%s%s') % (home, os.sep, 'pyarchinit_DB_folder') logo_path = ('%s%s%s') % (home_DB_path, os.sep, 'logo.jpg') logo = Image(logo_path) logo.drawHeight = 1.5*inch*logo.drawHeight / logo.drawWidth logo.drawWidth = 1.5*inch logo.hAlign = "LEFT" styleSheet = getSampleStyleSheet() styNormal = styleSheet['Normal'] styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.pink) styH1 = styleSheet['Heading3'] data = self.datestrfdate() lst = [] lst.append(logo) lst.append(Paragraph("<b>ELENCO CAMPIONI</b><br/><b>Scavo: %s, Data: %s</b>" % (sito, data), styH1)) table_data = [] for i in range(len(records)): exp_index = Campioni_index_pdf_sheet(records[i]) table_data.append(exp_index.getTable()) styles = exp_index.makeStyles() colWidths=[60,150,60, 60,60, 250, 60] table_data_formatted = Table(table_data, colWidths, style=styles) table_data_formatted.hAlign = "LEFT" lst.append(table_data_formatted) #lst.append(Spacer(0,2)) filename = ('%s%s%s') % (self.PDF_path, os.sep, 'elenco_campioni.pdf') f = open(filename, "wb") doc = SimpleDocTemplate(f, pagesize=(29*cm, 21*cm), showBoundary=0) doc.build(lst, canvasmaker=NumberedCanvas_Campioniindex) f.close()
def render(self, two_column): ''' ''' bodytext = getSampleStyleSheet()['BodyText'] row_color = pdf_color(self.color) style = todo_style(color=row_color) row = [''] * 11 if two_column else [''] * 23 limit = 33 if two_column else 75 if len(self.value) > limit: self.value = self.value[:limit] + '...' row[0] = self.mark if self.complete else '' ptext = '<font color=%s>%s</font>'%(row_color, self.value) row[1] = Paragraph(ptext, bodytext) todo = Table([row], colWidths=20, rowHeights=20) todo.setStyle(TableStyle(style)) todo.hAlign = 'LEFT' self.data = todo
def drawTable(self, data): t = Table(data, None, None, None, 1, 1, 1) extraStyle = [] for i in range(len(data[1:])): if data[1:][i][0] == 'Free' or data[1:][i][0] == 'Used': extraStyle.append(('BACKGROUND', (0, i + 1), (-1, i + 1), colors.orange)) if data[1:][i][0] == 'SwapUsage' or data[1:][i][0] == 'LMK File': extraStyle.append(('BACKGROUND', (0, i + 1), (-1, i + 1), colors.lightgreen)) t.setStyle(TableStyle([('FONT', (0, 0), (-1, -1), 'Helvetica'), ('BACKGROUND', (0, 0), (-1, 0), colors.deepskyblue), ('FONTSIZE', (0, 0), (-1, -1), 10), ('GRID', (0, 0), (-1, -1), 1, colors.black), ('ALIGN', (1, 1), (-1, -1), 'RIGHT'), ('ALIGN', (1, 0), (-1, 0), 'CENTER'), ('TOPPADDING', (0, 0), (-1, -1), 4), ('BOTTOMPADDING', (0, 0), (-1, -1), 4), ] + extraStyle)) t.hAlign = 'LEFT' return t
def end_table(self): draw_data = [] for col in sorted(self.report_data.keys()): draw_data.append([]) for row in self.report_data[col]: draw_data[col].append(row) # print "drawing:\n%s\n\n" % str(draw_data) # print "%d | %d" % self.cmax t = Table(draw_data) t.hAlign = "LEFT" t.setStyle( TableStyle([("BOX", (0, 0), (-1, -1), 0.25, colors.black), ("GRID", (0, 0), (-1, -1), 0.5, colors.black)]) ) self.tables.append(t)