def create_intro(self): self.elements += [ pdf.Spacer(0, 0.25 * inch), pdf.Paragraph(self.crawler.novel_title or 'N/A', style=self.styles['Title']), pdf.Spacer(0, 0.1 * inch), pdf.Table( [[self.crawler.novel_author or 'N/A']], style=pdf.TableStyle([ ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('SIZE', (0, 0), (-1, -1), 12), ]), ), pdf.Spacer(0, 0.5 * inch), ] if self.app.book_cover: self.elements += [pdf.Image(self.app.book_cover, height=5 * inch)] else: self.elements += [pdf.Spacer(0, 5 * inch)] # end if self.elements += [ pdf.Spacer(0, 0.5 * inch), pdf.Table( [['Generated by <Lightnovel Crawler>'], ['https://github.com/dipu-bd/lightnovel-crawler']], style=pdf.TableStyle([ ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ]), ), ] self.elements += [pdf.PageBreak()]
def _create_story(self): # Set up an empty list to hold the story story = [] # Import the report styles styles = report_styles.get_report_styles() # Create a page break story = self._make_page_break(story, self.PORTRAIT) # Section title title_str = '<strong>References</strong>' story.append(self._make_title(title_str)) story.append(p.Spacer(0, 0.1 * u.inch)) # List of references used references = [ ''' Cohen, J. 1960. "A coefficient of agreement for nominal scales." Educational and Psychological Measurement 20: 37-46. ''', ''' Kennedy, RE, Z Yang and WB Cohen. 2010. "Detecting trends in forest disturbance and recovery using yearly Landsat time series: 1. Landtrendr -- Temporal segmentation algorithms." Remote Sensing of Environment 114(2010): 2897-2910. ''', ''' Ohmann, JL, MJ Gregory and HM Roberts. 2014 (in press). "Scale considerations for integrating forest inventory plot data and satellite image data for regional forest mapping." Remote Sensing of Environment. ''', ''' O'Neil, TA, KA Bettinger, M Vander Heyden, BG Marcot, C Barrett, TK Mellen, WM Vanderhaegen, DH Johnson, PJ Doran, L Wunder, and KM Boula. 2001. "Structural conditions and habitat elements of Oregon and Washington. Pages 115-139 in: Johnson, DH and TA O'Neil, editors. 2001. "Wildlife-habitat relationships in Oregon and Washington." Oregon State University Press, Corvallis, OR. ''', ] # Print all references for reference in references: para = p.Paragraph(reference, styles['body_style']) story.append(para) story.append(p.Spacer(0, 0.10 * u.inch)) # Return this story return story
def add_table(self, rows, column_sizes, style=[]): real_style = platypus.TableStyle([ ("GRID", (0, 0), (-1, -1), 0.8, (0, 0, 0)), ("BACKGROUND", (0, 0), (-1, 0), (0.8471, 0.8941, 0.7373)), ] + style) sizes = [s * mm for s in column_sizes] self.story.extend([ platypus.Spacer(1, 3 * mm), platypus.Table(rows, colWidths=sizes, style=real_style), platypus.Spacer(1, 3 * mm), ])
def _create_story(self, scatter_files): # Set up an empty list to hold the story story = [] # Import the report styles styles = report_styles.get_report_styles() # Create a page break story = self._make_page_break(story, self.PORTRAIT) # Section title title_str = '<strong>Local-Scale Accuracy Assessment: ' title_str += 'Scatterplots of Observed vs. Predicted ' title_str += 'Values for Continuous Variables at ' title_str += 'Plot Locations</strong>' story.append(self._make_title(title_str)) story.append(p.Spacer(0, 0.2 * u.inch)) # Scatter explanation scatter_str = ''' These scatterplots compare the observed plot values against predicted (modeled) values for each plot used in the GNN model. We use a modified leave-one-out (LOO) approach. In traditional LOO accuracy assessment, a model is run with <i>n</i>-1 plots and then accuracy is determined at the plot left out of modeling, for all plots used in modeling. Because of computing limitations, we use a 'second-nearest-neighbor' approach. We develop our models with all plots, but in determining accuracy, we don't allow a plot to assign itself as a neighbor at the plot location. This yields similar accuracy assessment results as a true cross-validation approach, but probably slightly underestimates the true accuracy of the distributed (first-nearest-neighbor) map.<br/><br/> The observed value comes directly from the plot data, whereas the predicted value comes from the GNN prediction for the plot location. The GNN prediction is the mean of pixel values for a window that approximates the field plot configuration.<br/><br/> The correlation coefficients, normalized Root Mean Squared Errors (RMSE), and coefficients of determination (R-square) are given. The RMSE is normalized by dividing the RMSE by the observed mean value. ''' story.append(p.Paragraph(scatter_str, styles['body_style'])) story.append(p.Spacer(0, 0.1 * u.inch)) # Create a table of scatterplots and add to story story.append(self._make_figure_table(scatter_files)) # Return this story return story
def _create(self): """ Does the final creation of the Platypus Table object. Including a correct numeration for the Table of Tables list. Typically this Method will be called by the _PreBuild-Method of the Story class. :return: story with all final objects for pdf rendering :rtype: list of platypus objects ready for rendering. """ style = [('GRID', (0, 0), (-1, -1), 1.0, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey)] data = [] # Add the Header to the data data.append(build_table_header(["Testcase_ID", "Name", "Result"])) for testcase in self._testcases: data.append(build_table_row([url_str(testcase.id, testcase.doors_url), html_str(testcase.name), color_result(testcase.test_result)])) story = [] table = plat.Table(data, colWidths=[SUMMARY_ID_WIDTH, SUMMARY_NAME_WIDTH, SUMMARY_RESULT_WIDTH], style=style) story.append(table) self.append_caption(story) story.append(plat.Spacer(1, 1 * cm)) if self.summary: data2 = [] # Add the Header to the data data2.append(build_table_header(["Test(s) Performed", color_result(ValAssessmentStates.PASSED.upper()), color_result(ValAssessmentStates.FAILED.upper()), color_result(ValAssessmentStates.NOT_ASSESSED.upper())])) data2.append([self._passed + self._failed + self._notassessed, self._passed, self._failed, self._notassessed]) table2 = plat.Table(data2, style=style) story.append(table2) story.append(plat.Spacer(1, 1 * cm)) return story
def _create(self): """ Does the final creation of the Platypus Table object. Including a correct numeration for the Table of Tables list. Typically this Method will be called by the _PreBuild-Method of the Story class. :return: story with all final objects for pdf rendering :rtype: list of platypus objects ready for rendering. """ story = [] style = [('GRID', (0, 0), (-1, -1), 1.0, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey)] data = [build_table_header(['TaskId', 'Error Code', 'Description', 'Details'])] for inct in sorted(self._job.incidents, key=attrgetter('task_id')): if inct.type == self._type: data.append(build_table_row([inct.task_id, inct.code, html_str(inct.desc), html_str(inct.src)])) table = plat.Table(data, style=style, colWidths=[INCDNT_TASK_WIDTH, INCDNT_ERROR_WIDTH, INCDNT_DESC_WIDTH, INCDNT_SOURCE_WIDTH]) story.append(table) self.append_caption(story) story.append(plat.Spacer(1, 1 * cm)) return story
def _create(self): """ Does the final creation of the Platypus Table object. Including a correct nummeration for the Table of Tables list. Typically this Method will be called by the _PreBuild-Method of the Story class. :return: story with all final objects for pdf rendering :rtype: list of platypus objects ready for rendering. """ story = [] style = [('GRID', (0, 0), (-1, -1), 1.0, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.darkgrey)] data = [build_table_header(['Job_ID', 'Crashes', 'Exceptions', 'Errors'])] all_err = 0 all_exc = 0 all_crs = 0 for job in self._runtime_details: data.append([job.jobid, job.crash_count, job.exception_count, job.error_count]) all_err += job.error_count all_exc += job.exception_count all_crs += job.crash_count data.append(['sum', all_crs, all_exc, all_err]) style.append(('BACKGROUND', (0, -1), (-1, -1), colors.lightgrey)) table = plat.Table(data, style=style) # create table number, caption and add to summaries: story.append(table) self.append_caption(story) story.append(plat.Spacer(1, 1 * cm)) return story
def pdf_elements(self): # layout grid = [('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('ALIGN', (1, 0), (-1, -1), 'RIGHT'), ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold')] # typeset some rows in bold for i in range(len(self.entries)): e = self.entries[i] if not 'bold' in e: continue if not 'indent' in e: grid.append( ('FONTNAME', (0, i + 1), (-1, i + 1), 'Helvetica-Bold')) elif e['indent'] == 1: grid.append(('FONTNAME', (0, i + 1), (-1, i + 1), 'Helvetica-BoldOblique')) elif e['indent'] >= 2: grid.append( ('FONTNAME', (0, i + 1), (-1, i + 1), 'Helvetica-Oblique')) # build list of 'Flowable' objects elements = [] elements.append(pl.Spacer(1, 0.8 * inch)) t = pl.Table([self.headings] + self.data) t.setStyle(pl.TableStyle(grid)) elements.append(t) return elements
def _create(self): """ Does the final creation of the Platypus Heading object. Including a correct numeration for the headings. Typically this Method will be called by the _PreBuild-Method of the Story class. :return: story with all final objects for pdf rendering :rtype: list of platypus objects ready for rendering. """ story = [] # if pageBreak: # self._story.append(PageBreak()) if self.level > 0: story.append(plat.Spacer(1, 1.5 * cm)) # Get Current Section Number num = self._build_section_number_string(self.level) story.append( plat.Paragraph(num + " " + self.heading, self.header[self.level if self.level < 4 else 3])) return story
def make(self): data = copy(self.table_data) t = platypus.Table(data, repeatRows=0, colWidths=self.col_widths) t.setStyle(self.style) spacer = platypus.Spacer(1,30) return [t, spacer]
def _create(self): """ Does the final creation of the Platypus Table object. Including a correct numeration for the Table of Tables list. Typically this Method will be called by the _PreBuild-Method of the Story class. :return: story with all final objects for pdf rendering :rtype: list of platypus objects ready for rendering. """ story = [] data = [] if self._header is not None: data.append(build_table_header(self._header)) if self._cellstyle: data += [ build_table_row(f, style=self._cellstyle) for f in self._data ] else: data += self._data table = plat.Table(data, repeatRows=1, **self._kwargs) table.keepWithNext = True story.append(plat.Spacer(1, 0.2 * cm)) story.append(table) # story.append(plat.Spacer(1, 1 * cm)) self.append_caption(story) return story
def _flowable(self, n): tags = { 'name': lambda node: self.__name(node), 'para': lambda node: platypus.Paragraph(self._textual(node), self.styles.para_style_get(node), **(utils.attr_get(node, [], {'bulletText': 'str'}))), 'xpre': lambda node: platypus.XPreformatted(self._textual(node), self.styles.para_style_get(node), **(utils.attr_get(node, [], {'bulletText': 'str', 'dedent': 'int', 'frags': 'int'}))), 'pre': lambda node: platypus.Preformatted(self._textual(node), self.styles.para_style_get(node), **(utils.attr_get(node, [], {'bulletText': 'str', 'dedent': 'int'}))), 'illustration': lambda node: self._illustration(node), 'blockTable': lambda node: self._table(node), 'title': lambda node: platypus.Paragraph(self._textual(node), reportlab.lib.styles.getSampleStyleSheet()['Title'], **(utils.attr_get(node, [], {'bulletText': 'str'}))), 'h1': lambda node: platypus.Paragraph(self._textual(node), reportlab.lib.styles.getSampleStyleSheet()['Heading1'], **(utils.attr_get(node, [], {'bulletText': 'str'}))), 'h2': lambda node: platypus.Paragraph(self._textual(node), reportlab.lib.styles.getSampleStyleSheet()['Heading2'], **(utils.attr_get(node, [], {'bulletText': 'str'}))), 'h3': lambda node: platypus.Paragraph(self._textual(node), reportlab.lib.styles.getSampleStyleSheet()['Heading3'], **(utils.attr_get(node, [], {'bulletText': 'str'}))), 'image': lambda node: platypus.Image(node.getAttribute('file'), mask=(250, 255, 250, 255, 250, 255), **(utils.attr_get(node, ['width', 'height', 'preserveAspectRatio', 'anchor']))), 'spacer': lambda node: platypus.Spacer( width=utils.unit_get(node.getAttribute('width') if node.hasAttribute('width') else '1cm'), height=utils.unit_get(node.getAttribute('length'))), 'barCode': lambda node: code39.Extended39(self._textual(node)), 'pageBreak': lambda node: platypus.PageBreak(), # FIXME: it is not in RML std 'nextPage': lambda node: platypus.PageBreak(), 'condPageBreak': lambda node: platypus.CondPageBreak(**(utils.attr_get(node, ['height']))), 'setNextTemplate': lambda node: platypus.NextPageTemplate(str(node.getAttribute('name'))), 'nextFrame': lambda node: platypus.CondPageBreak(1000), # TODO: change the 1000 ! 'ul': lambda node: self._list(node), 'keepInFrame': lambda node: self.__keep_in_frame(node), } retvalue = tags.get(n.localName) if retvalue: return retvalue(n) else: sys.stderr.write('Warning: flowable not yet implemented: %s !\n' % (n.localName,))
def header(txt, style=HeaderStyleList[0], klass=platypus.Paragraph, sep=0.3): """Low-level interface func to ReportLab headers.""" s = platypus.Spacer(0.2 * inch, sep * inch) para = klass(txt, style) sect = [s, para] result = platypus.KeepTogether(sect) return result
def story_title(survey, info=dict()): story = [ platypus.Paragraph(str(line), stylesheet['Title']) for line in survey.title.split('\n') ] story += [ platypus.FrameBreak(), ] keys = list(survey.info.keys()) if keys: keys.sort() table = [[ platypus.Paragraph(str(key), stylesheet['Normal']), platypus.Paragraph(str(survey.info[key]), stylesheet['Normal']) ] for key in keys] story += [ platypus.Table(table, colWidths=(50 * mm, None)), ] if info: story += [platypus.Spacer(0, 10 * mm)] keys = list(info.keys()) keys.sort() table = [[ platypus.Paragraph(str(key), stylesheet['Normal']), platypus.Paragraph(str(info[key]), stylesheet['Normal']) ] for key in keys] story += [ platypus.Table(table, colWidths=(50 * mm, None)), ] story += [platypus.NextPageTemplate('Normal'), platypus.PageBreak()] return story
def create_pdf(self, invoice, header_image): self.is_valid(invoice, raise_exception=True) # Create the document template buff = io.BytesIO() doc = platypus.SimpleDocTemplate(buff, title=invoice.description, pagesize=A4) invoice_settings = InvoiceSettings.objects.settings() vat_settings = VatSettings.objects.settings() # Container for the 'Flowable' objects elements = [] elements.append( self._table_header(invoice, invoice_settings, vat_settings, header_image)) elements.append(platypus.Spacer(1, 12)) elements.append(self._table_lines(invoice)) elements.append(self._table_totals(invoice)) for text in self._text_footer(invoice_settings.footer): elements.append(self._para(text)) # write the document to disk doc.build(elements, canvasmaker=NumberedCanvas) pdf = buff.getvalue() buff.close() invoice_filename = '{}.pdf'.format(invoice.invoice_number) invoice.pdf.save(invoice_filename, ContentFile(pdf)) return invoice_filename
def _flowable(self, node): if node.localName == 'para': style = self.styles.para_style_get(node) return platypus.Paragraph(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText': 'str'}))) elif node.localName == 'name': self.styles.names[ node.getAttribute('id')] = node.getAttribute('value') return None elif node.localName == 'xpre': style = self.styles.para_style_get(node) return platypus.XPreformatted(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText': 'str', 'dedent': 'int', 'frags': 'int'}))) elif node.localName == 'pre': style = self.styles.para_style_get(node) return platypus.Preformatted(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText': 'str', 'dedent': 'int'}))) elif node.localName == 'illustration': return self._illustration(node) elif node.localName == 'blockTable': return self._table(node) elif node.localName == 'title': styles = reportlab.lib.styles.getSampleStyleSheet() style = styles['Title'] return platypus.Paragraph(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText': 'str'}))) elif node.localName == 'h1': styles = reportlab.lib.styles.getSampleStyleSheet() style = styles['Heading1'] return platypus.Paragraph(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText': 'str'}))) elif node.localName == 'h2': styles = reportlab.lib.styles.getSampleStyleSheet() style = styles['Heading2'] return platypus.Paragraph(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText': 'str'}))) elif node.localName == 'h3': styles = reportlab.lib.styles.getSampleStyleSheet() style = styles['Heading3'] return platypus.Paragraph(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText': 'str'}))) elif node.localName == 'image': return platypus.Image(node.getAttribute('file'), mask=(250, 255, 250, 255, 250, 255), **(utils.attr_get(node, ['width', 'height', 'preserveAspectRatio', 'anchor']))) elif node.localName == 'spacer': if node.hasAttribute('width'): width = utils.unit_get(node.getAttribute('width')) else: width = utils.unit_get('1cm') length = utils.unit_get(node.getAttribute('length')) return platypus.Spacer(width=width, height=length) elif node.localName == 'barCode': return code39.Extended39(self._textual(node)) elif node.localName == 'pageBreak': return platypus.PageBreak() elif node.localName == 'condPageBreak': return platypus.CondPageBreak(**(utils.attr_get(node, ['height']))) elif node.localName == 'setNextTemplate': return platypus.NextPageTemplate(str(node.getAttribute('name'))) elif node.localName == 'nextFrame': return platypus.CondPageBreak(1000) # TODO: change the 1000 ! elif node.localName == 'ul': return self._list(node) else: sys.stderr.write( 'Warning: flowable not yet implemented: %s !\n' % (node.localName,)) return None
def print_employees_badges(dao): global header_text global sub_header_text header_text = "" sub_header_text = _("Employees badges") s = ParagraphStyle(name="zou", fontName='Helvetica', alignment=TA_CENTER) badges_per_line = 3 array = [] row = [] employees = dao.employee_dao.all() if len(employees) == 0: return i = 0 for employee in employees: row.append([ Paragraph(employee.fullname, s), platypus.Spacer(0, 0.25 * cm), createBarcodeDrawing('EAN13', value=str( BarCodeIdentifier.code_for(employee)), barHeight=1 * cm) ]) i = i + 1 if i == badges_per_line: array.append(row) row = [] i = 0 if i > 0: array.append(row) t = platypus.Table(array, repeatRows=0, colWidths=[6 * cm] * badges_per_line, rowHeights=[3 * cm] * len(array)) # Repeat the table header ts = platypus.TableStyle([('FONT', (0, 0), (-1, -1), 'Helvetica', 8)]) ts.add('ALIGN', (0, 0), (-1, -1), 'CENTER') ts.add('VALIGN', (0, 0), (-1, -1), 'MIDDLE') ts.add("LEFTPADDING", (0, 0), (-1, -1), 0) ts.add("RIGHTPADDING", (0, 0), (-1, -1), 0) ts.add('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black) ts.add('BOX', (0, 0), (-1, -1), 0.25, colors.black) t.setStyle(ts) complete_document = [] complete_document.append(t) filename = make_pdf_filename("EmployeeBadges") ladderDoc = start_PDF(filename) ladderDoc.build(complete_document, canvasmaker=NumberedCanvas) open_pdf(filename)
def add_space(self, space): """ Add a Space before the next Item of the story. :param space: wanted space in cm. :type space: float :return: - """ self._story.append(plat.Spacer(1, space * cm))
def header(Elements, txt, style=HeaderStyle): s = platypus.Spacer(0.2 * inch, 0.2 * inch) Elements.append(s) style.alignment = 1 style.fontName = self.psfont style.fontSize = 18 style.borderWidth = 0 para = platypus.Paragraph(txt, style) Elements.append(para)
def create_chapter(self, content): for tag in content.children: if not tag.name: self.elements += [ pdf.Spacer(0, 0.15 * inch), pdf.Paragraph(str(tag), self.styles['Normal']), ] elif re.match(r'h\d', tag.name): self.elements += [ pdf.Paragraph(tag.text, self.styles[tag.name]), ] elif tag.name == 'p': self.elements += [ pdf.Spacer(0, 0.15 * inch), pdf.Paragraph(tag.text, self.styles['Normal']), ] # elif re.match(r'b|strong|label', tag.name): # run = paragraph.add_run(tag.text) # run.bold = True # elif re.match(r'i|em|cite', tag.name): # run = paragraph.add_run(tag.text) # run.italic = True # elif re.match(r'u', tag.name): # run = paragraph.add_run(tag.text) # run.underline = True # elif re.match(r'sub', tag.name): # run = paragraph.add_run(tag.text) # run.font.subscript = True # elif re.match(r'sup', tag.name): # run = paragraph.add_run(tag.text) # run.font.superscript = True # elif re.match(r'pre|code|kdb', tag.name): # run = paragraph.add_run(tag.text) # run.font.outline = True # else: # paragraph.add_run(tag.text) # end if # end for self.elements += [pdf.PageBreak()]
def story(self): story, tmp = Question.story(self) if self.obj.calculate.count: for box in self.obj.boxes: story.append( answers.Choice(box.text, self.obj.calculate.values[box.value], self.obj.calculate.significant[box.value])) story = [platypus.KeepTogether(story)] if len(self.text) > 0: story.append(platypus.Spacer(0, 3 * mm)) story.extend(self.text) return story, False
def _create(self): """ Does the final creation of the Platypus Table object. Including a correct numeration for the Table of Tables list. Typically this Method will be called by the _PreBuild-Method of the Story class. :return: story with all final objects for pdf rendering :rtype: list of platypus objects ready for rendering. """ style = [('GRID', (0, 0), (-1, -1), 1.0, colors.black), ('BACKGROUND', (0, 0), (-1, 0), colors.darkgrey)] data = [] # Add the Header to the dat rowcount = 0 for testcase in self._testcases: # Add TestCase information style.append(('BACKGROUND', (0, rowcount), (-1, rowcount), colors.darkgrey)) data.append(build_table_row([url_str(testcase.id, testcase.doors_url), html_str(testcase.name), '', '', color_result(testcase.test_result), ''], self.cols_out)) rowcount += 1 style.append(('BACKGROUND', (0, rowcount), (-1, rowcount), colors.lightgrey)) data.append(build_table_row(filter_cols(['Teststep_ID', 'Name', 'Expected Result', 'Measured Result', 'Test Result', 'ASMT'], self.cols_out))) rowcount += 1 # Ad Teststeps information for step in testcase.test_steps: data.append(build_table_row([url_str(step.id, step.doors_url), html_str(step.name), html_str(step.exp_result), html_str(step.meas_result), color_result(step.test_result), html_str(step.issue)], self.cols_out)) rowcount += 1 story = [] # adjust column widths based on widths of table with all columns cadd = ((sum(TEST_DETAILS_WIDTHS) - sum(filter_cols(TEST_DETAILS_WIDTHS, self.cols_out))) / len(filter_cols(TEST_DETAILS_WIDTHS, self.cols_out))) col_widths = filter_cols([i + cadd for i in TEST_DETAILS_WIDTHS], self.cols_out) table = plat.Table(data, style=style, colWidths=col_widths) story.append(table) self.append_caption(story) story.append(plat.Spacer(1, 1 * cm)) return story
def _table_header(self, invoice, invoice_settings, vat_settings, header_image): """ Create a table for the top section of the invoice (before the project description and invoice detail) """ left = [] right = [] # left hand content left.append(self._para(self._text_invoice_address(invoice))) left.append(platypus.Spacer(1, 12)) left.append(self._table_invoice_detail(invoice)) # right hand content if header_image: right.append(self._image(header_image)) right.append( self._para( self._text_our_address(invoice_settings.name_and_address))) right.append(self._bold(invoice_settings.phone_number)) if vat_settings.vat_number: right.append( self._para(self._text_our_vat_number(vat_settings.vat_number))) heading = [platypus.Paragraph(invoice.description, self.head_1)] # If the invoice has a logo, then the layout is different if header_image: data = [ [ heading + left, # left right, # right ], ] else: data = [ [ heading, # left (row one) [], # right (row one) ], [ left, # left (row two) right, # right (row two) ], ] return platypus.Table( data, colWidths=[300, 140], style=[ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LEFTPADDING', (0, 0), (-1, -1), 0), #('GRID', (0, 0), (-1, -1), self.GRID_LINE_WIDTH, colors.grey), ])
def __preamble(self): """Compose the beginning of the report """ date = datetime.today().isoformat(' ') owner = 'PyMVPA v. %s' % mvpa2.__version__ if self.author is not None: owner += ' Author: %s' % self.author return [ rplp.Spacer(1, 0.8 * rplu.inch), rplp.Paragraph("Generated on " + date, self.style), rplp.Paragraph(owner, self.style) ] + self.__flowbreak
def _create(self): """ Does the final creation of the Platypus Table object. Including a correct numeration for the Table of Tables list. Typically this Method will be called by the _PreBuild-Method of the Story class. :return: story with all final objects for pdf rendering :rtype: list of platypus objects ready for rendering. """ story = [] style = [('GRID', (0, 0), (-1, -1), 1.0, colors.black), ('BACKGROUND', (0, 0), (0, 6), colors.lightgrey)] data = [] data.append(build_table_row(['Testcase Name', html_str(self._testcase.name)])) data.append(build_table_row(['Testcase Identifier', url_str(self._testcase.id, self._testcase.doors_url)])) data.append(build_table_row(['Playlist/Recording', html_str(self._testcase.collection)])) # data.append(['Files Processed', self._testcase.processed_files]) #Todo: rh data.append(['Time Processed [H:M:S]', sec_to_hms_string(self._testcase.total_time)]) data.append(['Distance Processed [km]', str(self._testcase.total_dist)]) table = plat.Table(data, style=style, colWidths=[TESTCASE1_DESCR_WIDTH, TESTCASE1_VALUE_WIDTH]) story.append(table) style = [('GRID', (0, 0), (-1, -1), 1.0, colors.black), ('BACKGROUND', (0, 0), (3, 0), colors.lightgrey)] data = [build_table_header(['Teststep', 'Expected Result', 'Measured Result', 'Test Result'])] for step in self._testcase.test_steps: data.append(build_table_row([url_str(step.id, step.doors_url), html_str(step.exp_result), html_str(step.meas_result), color_result(step.test_result)])) table = plat.Table(data, style=style, colWidths=[TESTCASE2_ID_WIDTH, TESTCASE2_MEAS_WIDTH, TESTCASE2_MEAS_WIDTH, TESTCASE2_RESULT_WIDTH]) story.append(table) self.append_caption(story) story.append(plat.Spacer(1, 1 * cm)) return story
def pdf_maker(trialnumber, ptname, footer): ''' Makes a PDF with a top text, image, and bottom text. Inputs:- trialnumber: number of trials to plot (indexing from zero) ptname: patient name (string) to put in top text footer: text string for bottom text ''' from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet import reportlab.platypus as platypus from reportlab.lib.units import cm fileprefix = 'emg-plot-' filesuffix = '.png' toptext = '<font size=14><b>EMG for %s</b></font>' % ptname pdf_path = tkFileDialog.asksaveasfilename(initialdir='C:', initialfile='EMG report %s.pdf' %ptname) doc = platypus.SimpleDocTemplate(pdf_path, topMargin = cm, bottomMargin = cm, rightMargin = cm, leftMargin = cm) story = [] # Make new, indented text style. style = getSampleStyleSheet()['Normal'] indented = ParagraphStyle( 'indented', parent=style, leftIndent=2*cm ) for n in range(trialnumber+1): story.append(platypus.Paragraph(toptext, indented)) story.append(platypus.Spacer(1,0.1*cm)) graph = platypus.Image(str(fileprefix+str(n)+filesuffix)) graph._restrictSize(19*cm, 24*cm) story.append(graph) #story.append(platypus.Spacer(1,0.5*cm)) footer = footer.replace('\n','<br />\n') #Reportlab's Paragraph ignores newlines story.append(platypus.Paragraph(footer, indented)) story.append(platypus.PageBreak()) print('docbuild ran in %s' %pdf_path) doc.build(story)
def report(self, invoice, user, response): self._is_valid(invoice, raise_exception=True) # Create the document template doc = platypus.SimpleDocTemplate( response, title='Report - Invoice Time Analysis', pagesize=A4 ) # Container for the 'Flowable' objects elements = [] elements.append(self._head( 'Time analysis by user and ticket for invoice {}'.format( invoice.invoice_number ) )) elements.append(platypus.Spacer(1, 12)) elements.append(self._table_lines(invoice)) elements.append(self._para( 'Printed {} by {}'.format(timezone.now(), user.username) )) doc.build(elements)
def _create(self, story): """ creates the pdf story, called during `report.Build` :param story: pdf story to add paragraphs to :type story: list of `pdf.Story` elements """ # add logo story.append( plat.Image(io.BytesIO(logo.CONTI_CORP_LOGO), width=logo.CONTI_LOGO_SIZE[0] * 0.5, height=logo.CONTI_LOGO_SIZE[1] * 0.5)) story.append(plat.Spacer(1, 2 * cm)) # add title story.append(plat.Paragraph(self.title, self.TITLE_STYLE)) story.append(plat.Spacer(1, 1 * cm)) # add title story.append(plat.Paragraph("for", self.TITLE_STYLE)) story.append(plat.Spacer(1, 1 * cm)) # add checkpoint story.append(plat.Paragraph(self.checkpoint, self.TITLE_STYLE)) story.append(plat.Paragraph(self.add_info, self.TITLE_STYLE)) story.append(plat.Spacer(1, 3 * cm)) # confidence statement story.append( plat.Paragraph( '<para alignment="center">%s</para>' % self.confidential_level, self.TITLE_STYLE)) story.append(plat.Spacer(1, 3 * cm)) # Add Date story.append(plat.Spacer(1, 7 * cm)) story.append(plat.Paragraph(self.date, self.CENTER_STYLE)) story.append(plat.PageBreak())
def get_template(self, url): formatted_time = time.ctime() company = self.application.config['mailer.company_name'] sender = self.application.config['mailer.source_email_alias'] template_file = self.config['template_file'] story = [] click_me = saxutils.escape(self.config['link_text']) link = '<font color=blue><link href="' + url + '">' + click_me + '</link></font>' logo_path = self.config['logo'] if logo_path: img = platypus.Image(logo_path, 2 * inch, inch) story.append(img) style_sheet = styles.getSampleStyleSheet() style_sheet.add( styles.ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) ptext = '<font size=10>' + formatted_time + '</font>' story.append(platypus.Spacer(1, 12)) story.append(platypus.Paragraph(ptext, style_sheet['Normal'])) story.append(platypus.Spacer(1, 12)) with open(template_file, 'r') as file_h: for line in file_h: story.append(platypus.Paragraph(line, style_sheet['Normal'])) story.append(platypus.Spacer(1, 8)) story.append(platypus.Paragraph(link, style_sheet['Justify'])) story.append(platypus.Spacer(1, 12)) ptext = '<font size=10>Sincerely,</font>' story.append(platypus.Paragraph(ptext, style_sheet['Normal'])) story.append(platypus.Spacer(1, 12)) ptext = '<font size=10>' + sender + '</font>' story.append(platypus.Paragraph(ptext, style_sheet['Normal'])) story.append(platypus.Spacer(1, 12)) ptext = '<font size=10>' + company + '</font>' story.append(platypus.Paragraph(ptext, style_sheet['Normal'])) return story
def _flowable(self, node, extra_style=None): if node.tag=='pto': return self._pto(node) if node.tag=='para': style = self.styles.para_style_get(node) if extra_style: style.__dict__.update(extra_style) result = [] for i in self._textual(node).split('\n'): result.append(platypus.Paragraph(i, style, **(utils.attr_get(node, [], {'bulletText':'str'})))) return result elif node.tag=='barCode': try: from reportlab.graphics.barcode import code128 from reportlab.graphics.barcode import code39 from reportlab.graphics.barcode import code93 from reportlab.graphics.barcode import common from reportlab.graphics.barcode import fourstate from reportlab.graphics.barcode import usps from reportlab.graphics.barcode import createBarcodeDrawing except ImportError: _logger.warning("Cannot use barcode renderers:", exc_info=True) return None args = utils.attr_get(node, [], {'ratio':'float','xdim':'unit','height':'unit','checksum':'int','quiet':'int','width':'unit','stop':'bool','bearers':'int','barWidth':'float','barHeight':'float'}) codes = { 'codabar': lambda x: common.Codabar(x, **args), 'code11': lambda x: common.Code11(x, **args), 'code128': lambda x: code128.Code128(str(x), **args), 'standard39': lambda x: code39.Standard39(str(x), **args), 'standard93': lambda x: code93.Standard93(str(x), **args), 'i2of5': lambda x: common.I2of5(x, **args), 'extended39': lambda x: code39.Extended39(str(x), **args), 'extended93': lambda x: code93.Extended93(str(x), **args), 'msi': lambda x: common.MSI(x, **args), 'fim': lambda x: usps.FIM(x, **args), 'postnet': lambda x: usps.POSTNET(x, **args), 'ean13': lambda x: createBarcodeDrawing('EAN13', value=str(x), **args), 'qrcode': lambda x: createBarcodeDrawing('QR', value=x, **args), } code = 'code128' if node.get('code'): code = node.get('code').lower() return codes[code](self._textual(node)) elif node.tag=='name': self.styles.names[ node.get('id')] = node.get('value') return None elif node.tag=='xpre': style = self.styles.para_style_get(node) return platypus.XPreformatted(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText':'str','dedent':'int','frags':'int'}))) elif node.tag=='pre': style = self.styles.para_style_get(node) return platypus.Preformatted(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText':'str','dedent':'int'}))) elif node.tag=='illustration': return self._illustration(node) elif node.tag=='blockTable': return self._table(node) elif node.tag=='title': styles = reportlab.lib.styles.getSampleStyleSheet() style = styles['Title'] return platypus.Paragraph(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText':'str'}))) elif re.match('^h([1-9]+[0-9]*)$', (node.tag or '')): styles = reportlab.lib.styles.getSampleStyleSheet() style = styles['Heading'+str(node.tag[1:])] return platypus.Paragraph(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText':'str'}))) elif node.tag=='image': image_data = False if not node.get('file'): if node.get('name'): if node.get('name') in self.doc.images: _logger.debug("Image %s read ", node.get('name')) image_data = self.doc.images[node.get('name')].read() else: _logger.warning("Image %s not defined", node.get('name')) return False else: import base64 newtext = node.text if self.localcontext: newtext = utils._process_text(self, node.text or '') image_data = base64.decodestring(newtext) if not image_data: _logger.debug("No inline image data") return False image = StringIO(image_data) else: _logger.debug("Image get from file %s", node.get('file')) image = _open_image(node.get('file'), path=self.doc.path) return platypus.Image(image, mask=(250,255,250,255,250,255), **(utils.attr_get(node, ['width','height']))) elif node.tag=='spacer': if node.get('width'): width = utils.unit_get(node.get('width')) else: width = utils.unit_get('1cm') length = utils.unit_get(node.get('length')) return platypus.Spacer(width=width, height=length) elif node.tag=='section': return self.render(node) elif node.tag == 'pageNumberReset': return PageReset() elif node.tag in ('pageBreak', 'nextPage'): return platypus.PageBreak() elif node.tag=='condPageBreak': return platypus.CondPageBreak(**(utils.attr_get(node, ['height']))) elif node.tag=='setNextTemplate': return platypus.NextPageTemplate(str(node.get('name'))) elif node.tag=='nextFrame': return platypus.CondPageBreak(1000) # TODO: change the 1000 ! elif node.tag == 'setNextFrame': from reportlab.platypus.doctemplate import NextFrameFlowable return NextFrameFlowable(str(node.get('name'))) elif node.tag == 'currentFrame': from reportlab.platypus.doctemplate import CurrentFrameFlowable return CurrentFrameFlowable(str(node.get('name'))) elif node.tag == 'frameEnd': return EndFrameFlowable() elif node.tag == 'hr': width_hr=node.get('width') or '100%' color_hr=node.get('color') or 'black' thickness_hr=node.get('thickness') or 1 lineCap_hr=node.get('lineCap') or 'round' return platypus.flowables.HRFlowable(width=width_hr,color=color.get(color_hr),thickness=float(thickness_hr),lineCap=str(lineCap_hr)) else: sys.stderr.write('Warning: flowable not yet implemented: %s !\n' % (node.tag,)) return None