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 make_plot(df: pd.DataFrame, width: float, height: float): """Строит график стоимости портфеля и возвращает объект pdf-изображения.""" _, ax = plt.subplots(1, 1, figsize=(width / inch, height / inch)) ax.spines["top"].set_visible(False) ax.spines["bottom"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["left"].set_visible(False) ax.yaxis.set_major_formatter(plt.FuncFormatter("{:.0f}%".format)) plt.grid(True, "major", lw=0.5, c="black", alpha=0.3) plt.tick_params(bottom=False, top=False, left=False, right=False) portfolio = portfolio_cum_return(df) * 100 - 100 total_return_index = index_cum_return(df) * 100 - 100 plt.plot(portfolio.values) plt.plot(total_return_index.values) x = total_return_index.index.astype(str).str.slice(stop=7) x_ticks_loc = range(0, len(x), 12) x_ticks_labels = x[x_ticks_loc] plt.yticks(fontsize=8) plt.xticks(x_ticks_loc, x_ticks_labels, fontsize=8) plt.legend( ("Portfolio", "MOEX Russia Net Total Return (Resident)"), fontsize=8, frameon=False, ) file = BytesIO() plt.savefig(file, dpi=300, format="png", transparent=True) return platypus.Image(file, width, height)
def getImageFromZODB(self, name, owner): """Retrieves an Image from a ZODB object """ # AVS try: # try to get it from ZODB img_pointer = getattr(owner, name) image = PIL_Image.open( cStringIO.StringIO(str(img_pointer.data))) width = img_pointer.width height = img_pointer.height filename = img_pointer.filename suffix = filename.split('.')[-1] try: tmp_img = file(tempfile.mktemp(suffix=suffix), 'w+b') tmp_img.write(img_pointer.data) tmp_img.close() except IOError: return [] p_img = platypus.Image(tmp_img.name, width=width / 2, height=height / 2) return (p_img) #return ((p_img, width, height)) except AttributeError: # not found ! return None
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 _make_figure_table(image_files): # Add the images to a list of lists cols = 2 table = [] row = [] for (i, fn) in enumerate(image_files): row.append(p.Image(fn, 3.4 * u.inch, 3.0 * u.inch)) if (i % cols) == (cols - 1): table.append(row) row = [] # Determine if there are any images left to print if len(row) != 0: for i in range(len(row), cols): row.append(p.Paragraph('', styles['body_style'])) table.append(row) # Style this into a reportlab table and add to the story width = 3.75 * u.inch t = p.Table(table, colWidths=[width, width]) t.setStyle( p.TableStyle([ ('ALIGNMENT', (0, 0), (-1, -1), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'CENTER'), ('TOPPADDING', (0, 0), (-1, -1), 6.0), ('BOTTOMPADDING', (0, 0), (-1, -1), 6.0), ])) return t
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 img(self,filename, width=None,height=None, style=None): if style is None: style = self.getDefaultParaStyle() elem = platypus.Image(filename,width,height) elem.style = style return self.append(elem)
def _build_report(): stylesheet = getSampleStyleSheet() builder = [ platypus.Paragraph("Report document", stylesheet["Heading1"]), platypus.Paragraph(to_paragraph(HEADER), stylesheet["Normal"]), ] for scan_prefix, scan_info in results.items(): excel_filename = f"{scan_prefix}.xlsx" workbook = openpyxl.load_workbook(excel_filename) df = pd.read_excel(excel_filename, engine="openpyxl") df = df[list(table_fields)] for attr, col_info in table_fields.items(): precision = col_info.get("precision") if precision is not None: col = getattr(df, attr) setattr(df, attr, [f"%.{precision}f" % item for item in col]) style = platypus.TableStyle([ ("FACE", (0, 0), (-1, 0), "Times-Bold"), ("ALIGN", (0, 0), (-1, 0), "CENTER"), ("GRID", (0, 0), (-1, -1), 0.25, colors.black), ("ALIGN", (1, 0), (-1, -1), "RIGHT"), ]) header = [ col_info.get("label", attr) for attr, col_info in table_fields.items() ] table = platypus.Table([header] + np.array(df).tolist(), repeatRows=1) table.setStyle(style) plot = platypus.Image(f"{scan_prefix}.png") plot.drawWidth = 8.0 * units.inch plot.drawHeight = 6.67 * units.inch builder.extend([ platypus.Paragraph(scan_info["title"], stylesheet["Heading1"]), platypus.Paragraph( f"Data generated: {workbook.properties.created}", stylesheet["Normal"], ), platypus.Paragraph(to_paragraph(scan_info["info"]), stylesheet["Normal"]), platypus.Paragraph("Scan Information", stylesheet["Heading2"]), platypus.Paragraph(to_paragraph(SCAN_INFO), stylesheet["Normal"]), platypus.PageBreakIfNotEmpty(), plot, platypus.Paragraph("Plot / Table Information", stylesheet["Heading2"]), platypus.Paragraph(to_paragraph(PLOT_INFO), stylesheet["Normal"]), platypus.Paragraph(f"{scan_info['title']}: Scan Data Table", stylesheet["Heading2"]), table, platypus.PageBreakIfNotEmpty(), ]) return builder
def pdf(filename, serialNumber, load, capacity, cutoffVoltage): doc = SimpleDocTemplate(filename, pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) styles = getSampleStyleSheet() Story = [] spacing = 3 im = plat.Image("grin_header.jpg", 7 * inch, 1 * inch) Story.append(im) Story.append(Spacer(1, spacing)) ptext = '<font size=18>Your Battery Test Results:</font>' Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 3 * spacing)) ptext = '<font size=12>Time of Test: %s</font>' % time.ctime() Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, spacing)) ptext = '<font size=12>Pack Serial #: %s</font>' % serialNumber Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, spacing)) ptext = "<font size=12>Load Current: %.2f A</font>" % load Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, spacing)) ptext = '<font size=12>Test Capacity: %.2f Ah</font>' % capacity Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, spacing)) ptext = '<font size=12>Cutoff Voltage: %.2f V</font>' % cutoffVoltage Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, spacing)) im = plat.Image(serialNumber + ".jpg", 7 * inch, 5 * inch) Story.append(im) Story.append(Spacer(1, spacing)) doc.build(Story)
def elem2flow(self, elem, style, width): "Convert this element to an iteration of flowables." #print "elem2flow(%r)" % elem.__class__.__name__ if isinstance(elem, html.PRE): assert len(elem.content) == 1 yield platypus.Preformatted(elem.content[0].text, style) elif isinstance(elem, html.UL): for li in elem.content: istyle = self.getElementStyle(li, parent=elem) for fl in self.elem2flow(li, istyle, width): yield fl elif isinstance(elem, html.LI): yield self.makepar(elem.toxml(), style) elif elem.__class__ is html.IMG: yield platypus.Image() elif isinstance(elem, html.TABLE): t = self.pdftable(elem, width, style) #pt=PdfTable(elem) #t=pt.buildTable(width,style) if t is None: return #print "gonna yield", t yield t #elif elem.fragmentable: elif isinstance(elem, html.Container): #print "fragmentable %s" % elem.__class__.__name__ frags = [] for e in elem.content: if e.fragmentable: #print "gonna elem2frags(%s)"% e.__class__.__name__ for f in self.elem2frags(e, style): frags.append(f) elif e.flowable: # found non-fragmentable element inside a flowable if len(frags) > 0: yield self.makepar("", style, frags=frags) for ee in self.elem2flow(e, style, width): yield ee frags = [] ## if e.__class__ is html.IMG: ## yield self.makepar("",style,frags=frags) ## yield platypus.Image() ## frags=[] #elif e.__class__ is H1: # yield self.makepar("",style,frags=frags) yield self.makepar("", style, frags=frags) #yield platypus.Table(data) else: raise "Cannot flow %r" % elem
def getImageEls(self, imgFilename, hdrText=None, width=None, height=None, scale=None, tScale=None): resultEls = [] if hdrText is not None: resultEls.append( platypus.Paragraph(hdrText, style=HeaderStyleList[3])) img = PIL.Image.open(imgFilename) initWidth, initHeight = img.size ratio = initHeight / float(initWidth) #imdraw = svg2rlg(imgFilename) if tScale is not None: tWidth = int(initWidth * tScale / 100.0) tHeight = int(initHeight * tScale / 100.0) img.thumbnail((tWidth, tHeight), PIL.Image.ANTIALIAS) img.save(imgFilename + ".thumbnail", "PNG") imgEl = platypus.Image(imgFilename + ".thumbnail") else: imgEl = platypus.Image(imgFilename) resultEls.append(imgEl) if width is not None: imgEl.drawWidth = width if height is None: imgEl.drawHeight = int(width * ratio) if height is not None: imgEl.drawHeight = height if scale is not None: img = PIL.Image.open(imgFilename) initWidth, initHeight = img.size imgEl.drawWidth = int(initWidth * scale / 100.0) imgEl.drawHeight = int(initHeight * scale / 100.0) imgEl.hAlign = 'CENTER' return resultEls
def pdf_response_rl(self, question, filename, download=False): """ Use the ReportLab api and the Model Objects provided by the context dict in this views pipeline. """ import reportlab.platypus as RL import reportlab.lib.styles as SL from io import BytesIO flo = [] out = BytesIO() # create a byte buffer to hold PDF data pdf = RL.SimpleDocTemplate(out) pdf.showBoundary = 1 pdf.leftMargin = pdf.rightMargin = pdf.leftMargin / 2 pdf.topMargin = pdf.bottomMargin = pdf.topMargin / 2 ss = SL.getSampleStyleSheet() h1 = RL.Paragraph("Question:", ss['Heading1']) h2 = RL.Paragraph(f"{str(question)}", ss['Heading2']) h3 = RL.Paragraph("Choices:", ss['Heading3']) hl = RL.HRFlowable(width='100%') if question.question_img: img = RL.Image(question.question_img.path, width=100, height=75, hAlign="LEFT") flo += [img, hl] flo += [h1, h2, hl, h3] ps = [ RL.Paragraph(f"{str(c)} [{c.votes} votes]", ss['BodyText']) for c in question.choice_set.all() ] ul = [RL.ListItem(x, value='sparkle') for x in ps] lf = RL.ListFlowable(ul, bulletType='bullet') flo += [lf] flo += [hl] try: pdf.build(flo) except Exception as e: message = (f"Unable to generate PDF from <hl><pre>{html}</pre>") return HttpResponse(message, status=500) out.seek(0) # reset byte buffer pointer to the start if download: return FileResponse(out, as_attachment=True, filename=filename) return FileResponse(out, filename=filename)
def write_image(self, data): fn = ImageExtras.write_image_tempfile(data) i = platypus.Image(fn) self.scale_image(i) factor = 1 MAX_WIDTH = self.doc.frame_width * 0.35 MAX_HEIGHT = self.doc.frame_height * 0.5 if i.drawWidth > MAX_WIDTH: factor = MAX_WIDTH / i.drawWidth if i.drawHeight > MAX_HEIGHT: f = MAX_HEIGHT / i.drawHeight if f < factor: factor = f if factor < 1.0: self.scale_image(i, factor) self.image = i
def write_image(self, data: bytes): buf = BytesIO(data) i = platypus.Image(buf) self.scale_image(i) factor = 1 MAX_WIDTH = self.doc.frame_width * 0.35 MAX_HEIGHT = self.doc.frame_height * 0.5 if i.drawWidth > MAX_WIDTH: factor = MAX_WIDTH / i.drawWidth if i.drawHeight > MAX_HEIGHT: f = MAX_HEIGHT / i.drawHeight if f < factor: factor = f if factor < 1.0: self.scale_image(i, factor) self.image = i
def make_plot(portfolio: Portfolio, width: float, height: float): """Строит диаграмму структуры портфеля и возвращает объект pdf-изображения.""" position_value = drop_small_positions(portfolio) position_share = position_value[:-1] / position_value[PORTFOLIO] labels = position_share.index + position_share.apply(lambda x: f"\n{x:.1%}") _, ax = plt.subplots(1, 1, figsize=(width / inch, height / inch)) _, texts = ax.pie( position_share, labels=labels, startangle=90, counterclock=False, labeldistance=1.2, ) plt.setp(texts, size=8) ax.axis("equal") file = BytesIO() plt.savefig(file, dpi=300, format="png", transparent=True) return platypus.Image(file, width, height)
def getImageFromFS(self, name, width=None, height=None): """Retrieves an Image from the ZODB file system """ location = self.context.aq_parent try: # try to get it from ZODB img_pointer = getattr(location, name) fp = expandpath(img_pointer._filepath) if not width: width = img_pointer.width if not height: height = img_pointer.height p_img = platypus.Image(fp, width=width / 2, height=height / 2) return (p_img) except AttributeError: # not found ! return None
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 generic_feature_report(feature_object, output_file): import reportlab.platypus as platypus from reportlab.lib.styles import getSampleStyleSheet elements = [] doc = platypus.SimpleDocTemplate(output_file) style_sheet = getSampleStyleSheet() # pge_img = platypus.Image('https://www.cecsb.org/wp-content/uploads/2013/05/PGE-LOGO-1024x259.png') # elements.append(pge_img) elements.append(platypus.Paragraph('FEATURE REPORT',style_sheet['Heading1'])) table = platypus.Table(feature_object.build_field_order()) elements.append(table) if feature_object.att_res: for att in feature_object.att_res: elements.append(platypus.Image(att['DOWNLOAD_URL'])) doc.build(elements) return(output_file)
def __call__(self, arg): res = list(arg) if self.verbose: print('Render:', res[0]) if hasCDX: smi = res[self.smiCol] tmpName = self.tempHandler.get('.jpg') try: img = chemdraw.SmilesToPilImage(smi) w, h = img.size aspect = float(h) / w img.save(tmpName) img = platypus.Image(tmpName) img.drawWidth = self.width img.drawHeight = aspect * self.width res[self.smiCol] = img except Exception: import traceback traceback.print_exc() res[self.smiCol] = 'Failed' return res
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 __call__(self, arg): res = list(arg) if self.verbose: sys.stderr.write('Render(%d): %s\n' % (self.smiCol, str(res[0]))) smi = res[self.smiCol] tmpName = self.tempHandler.get('.gif') aspect = 1 width = 300 height = aspect * width ok = cactvs.SmilesToGif(smi, tmpName, (width, height)) if ok: try: img = platypus.Image(tmpName) img.drawWidth = self.width img.drawHeight = aspect * self.width except Exception: ok = 0 if ok: res[self.smiCol] = img else: # FIX: maybe include smiles here in a Paragraph? res[self.smiCol] = 'Failed' return res
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
for file in f: img = cv2.imread(os.path.join(r, file)) if img is not None: files.append(os.path.join(r, file)) doc1 = rs.SimpleDocTemplate("BlockchainImages.pdf", pagesize=pages.A4, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) Story = [] ##Initialization for Table Paragraph = rs.Paragraph styles = getSampleStyleSheet() style_right = ParagraphStyle(name='right', parent=styles['Normal'], alignment=TA_RIGHT) for i in range(0, len(files) - 1): im = rs.Image(os.path.join(files[i]), 7 * inch, 4 * inch) text = str(((py.image_to_string(Image.open(os.path.join(files[i])))))) text = text.replace('-\n', '') Story.append(im) # appending Image Story.append(Paragraph(text, styles["Normal"])) #Extracted Text doc1.build(Story) print("end")
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
def getExamples(): """Returns all the example flowable objects""" styleSheet = getSampleStyleSheet() story = [] #make a style with indents and spacing sty = ParagraphStyle('obvious', None) sty.leftIndent = 18 sty.rightIndent = 18 sty.firstLineIndent = 18 sty.spaceBefore = 6 sty.spaceAfter = 6 story.append( Paragraph( """Now for some demo stuff - we need some on this page, even before we explain the concepts fully""", styleSheet['BodyText'])) p = Paragraph( """ Platypus is all about fitting objects into frames on the page. You are looking at a fairly simple Platypus paragraph in Debug mode. It has some gridlines drawn around it to show the left and right indents, and the space before and after, all of which are attributes set in the style sheet. To be specific, this paragraph has left and right indents of 18 points, a first line indent of 36 points, and 6 points of space before and after itself. A paragraph object fills the width of the enclosing frame, as you would expect.""", sty) p.debug = 1 #show me the borders story.append(p) story.append( Paragraph( """Same but with justification 1.5 extra leading and green text.""", styleSheet['BodyText'])) p = Paragraph( """ <para align=justify leading="+1.5" fg=green><font color=red>Platypus</font> is all about fitting objects into frames on the page. You are looking at a fairly simple Platypus paragraph in Debug mode. It has some gridlines drawn around it to show the left and right indents, and the space before and after, all of which are attributes set in the style sheet. To be specific, this paragraph has left and right indents of 18 points, a first line indent of 36 points, and 6 points of space before and after itself. A paragraph object fills the width of the enclosing frame, as you would expect.</para>""", sty) p.debug = 1 #show me the borders story.append(p) story.append( platypus.XBox(4 * inch, 0.75 * inch, 'This is a box with a fixed size')) story.append( Paragraph( """ All of this is being drawn within a text frame which was defined on the page. This frame is in 'debug' mode so you can see the border, and also see the margins which it reserves. A frame does not have to have margins, but they have been set to 6 points each to create a little space around the contents. """, styleSheet['BodyText'])) story.append(FrameBreak()) ####################################################################### # Examples Page 2 ####################################################################### story.append( Paragraph( """ Here's the base class for Flowable... """, styleSheet['Italic'])) code = '''class Flowable: """Abstract base class for things to be drawn. Key concepts: 1. It knows its size 2. It draws in its own coordinate system (this requires the base API to provide a translate() function. """ def __init__(self): self.width = 0 self.height = 0 self.wrapped = 0 def drawOn(self, canvas, x, y): "Tell it to draw itself on the canvas. Do not override" self.canv = canvas self.canv.saveState() self.canv.translate(x, y) self.draw() #this is the bit you overload self.canv.restoreState() del self.canv def wrap(self, availWidth, availHeight): """This will be called by the enclosing frame before objects are asked their size, drawn or whatever. It returns the size actually used.""" return (self.width, self.height) ''' story.append(Preformatted(code, styleSheet['Code'], dedent=4)) story.append(FrameBreak()) ####################################################################### # Examples Page 3 ####################################################################### story.append( Paragraph("Here are some examples of the remaining objects above.", styleSheet['Italic'])) story.append( Paragraph("This is a bullet point", styleSheet['Bullet'], bulletText='O')) story.append( Paragraph("Another bullet point", styleSheet['Bullet'], bulletText='O')) story.append( Paragraph( """Here is a Table, which takes all kinds of formatting options...""", styleSheet['Italic'])) story.append(platypus.Spacer(0, 12)) g = platypus.Table( (('', 'North', 'South', 'East', 'West'), ('Quarter 1', 100, 200, 300, 400), ('Quarter 2', 100, 200, 300, 400), ('Total', 200, 400, 600, 800)), (72, 36, 36, 36, 36), (24, 16, 16, 18)) style = platypus.TableStyle([ ('ALIGN', (1, 1), (-1, -1), 'RIGHT'), ('ALIGN', (0, 0), (-1, 0), 'CENTRE'), ('GRID', (0, 0), (-1, -1), 0.25, colors.black), ('LINEBELOW', (0, 0), (-1, 0), 2, colors.black), ('LINEBELOW', (1, -1), (-1, -1), 2, (0.5, 0.5, 0.5)), ('TEXTCOLOR', (0, 1), (0, -1), colors.black), ('BACKGROUND', (0, 0), (-1, 0), (0, 0.7, 0.7)) ]) g.setStyle(style) story.append(g) story.append(FrameBreak()) ####################################################################### # Examples Page 4 - custom fonts ####################################################################### # custom font with LettError-Robot font import reportlab.rl_config reportlab.rl_config.warnOnMissingFontGlyphs = 0 from reportlab.pdfbase import pdfmetrics fontDir = os.path.join(_RL_DIR, 'fonts') face = pdfmetrics.EmbeddedType1Face( os.path.join(fontDir, 'DarkGardenMK.afm'), os.path.join(fontDir, 'DarkGardenMK.pfb')) faceName = face.name # should be 'DarkGardenMK' pdfmetrics.registerTypeFace(face) font = pdfmetrics.Font(faceName, faceName, 'WinAnsiEncoding') pdfmetrics.registerFont(font) # put it inside a paragraph. story.append( Paragraph( """This is an ordinary paragraph, which happens to contain text in an embedded font: <font name="DarkGardenMK">DarkGardenMK</font>. Now for the real challenge...""", styleSheet['Normal'])) styRobot = ParagraphStyle('Robot', styleSheet['Normal']) styRobot.fontSize = 16 styRobot.leading = 20 styRobot.fontName = 'DarkGardenMK' story.append( Paragraph("This whole paragraph is 16-point DarkGardenMK.", styRobot)) story.append(FrameBreak()) if _GIF: story.append( Paragraph( "Here is an Image flowable obtained from a string filename.", styleSheet['Italic'])) story.append(platypus.Image(_GIF)) story.append( Paragraph( "Here is an Image flowable obtained from a utf8 filename.", styleSheet['Italic'])) #story.append(platypus.Image(fileName2FSEnc(_GIF))) story.append( Paragraph( "Here is an Image flowable obtained from a string file url.", styleSheet['Italic'])) story.append(platypus.Image(getFurl(_GIF))) story.append( Paragraph("Here is an Image flowable obtained from an open file.", styleSheet['Italic'])) story.append(platypus.Image(open_for_read(_GIF, 'b'))) story.append(FrameBreak()) try: img = platypus.Image( 'http://www.reportlab.com/rsrc/encryption.gif') story.append( Paragraph( "Here is an Image flowable obtained from a string http url.", styleSheet['Italic'])) story.append(img) except: story.append( Paragraph( "The image could not be obtained from a string http url.", styleSheet['Italic'])) story.append(FrameBreak()) if _JPG: img = platypus.Image(_JPG) story.append( Paragraph( "Here is an JPEG Image flowable obtained from a filename.", styleSheet['Italic'])) story.append(img) story.append( Paragraph( "Here is an JPEG Image flowable obtained from an open file.", styleSheet['Italic'])) img = platypus.Image(open_for_read(_JPG, 'b')) story.append(img) story.append(FrameBreak()) return story
def __createPdfFromImages(self, src_images_path): doc = platypus.SimpleDocTemplate(self.__pdfPath) doc.leftMargin = 0 doc.bottomMargin = 0 doc.rightMargin = 0 doc.topMargin = 0 pageWidth = PAGE_WIDTH_MM * self.__scale story = [] hasStory = False i = 1 for image_file in src_images_path: try: pilImg = Image.open(image_file) print('Adding ' + basename(image_file) + ' to pdf document...') except Exception: print('Cannot access a file: ' + image_file) continue imageWidth = pilImg.size[0] print('imageWidth:', imageWidth) imageHeight = pilImg.size[1] print('imageHeight:', imageHeight) # desc = 'Paragraph number desc_file = join(dirname(image_file), DESC_FILE_NAME) print('desc_file:', desc_file) desc = None if exists(desc_file): desc = read_desc(desc_file) print('desc:', desc) if desc is not None and not DESC_DONE.get(desc_file, False): para = Paragraph(desc, style_heading1) story.append(para) DESC_DONE[desc_file] = True #put different spaces before first and second images on every page if not i % 2: story.append( platypus.Spacer(1, self.__space_before_image1 * inch)) else: story.append( platypus.Spacer(1, self.__space_before_image2 * inch)) repImg = platypus.Image(image_file, pageWidth, pageWidth * (imageHeight / imageWidth)) story.append(repImg) #put some space after every image if not i % 2: story.append( platypus.Spacer(1, self.__space_after_image1 * inch)) else: story.append( platypus.Spacer(1, self.__space_after_image2 * inch)) #break page after every 2 images if not i % 2: story.append(platypus.PageBreak()) i += 1 print('OK') hasStory = True doc.build(story) if hasStory: print("Pdf file was created successfully") else: print("Pdf file was not created") if exists(self.__pdfPath): remove(self.__pdfPath) return hasStory
def on_page(self, canv, doc): """This function is used to write pages. :param canv: -- widget that provides structured graphics facilities :param doc: -- document template """ canv.saveState() plp = plat.Paragraph( "Continental<br/>ADAS", ParagraphStyle(name="plb", fontSize=8, fontName="Calibri", alignment=TA_CENTER, leading=8)) pcp = plat.Paragraph( COPYRIGHT, ParagraphStyle(name="pcb", fontSize=6, fontName="Calibri", alignment=TA_CENTER, leading=5)) www = 18.7 * cm _, hhh = pcp.wrap(www, doc.bottomMargin) prr = plat.Paragraph( "%s" % (doc.build_page_index_string()), # doc.page ParagraphStyle(name="pr", fontSize=8, fontName="Calibri", alignment=TA_CENTER)) tft = plat.Table([[plp, pcp, prr]], [3.2 * cm, www, 3.2 * cm], ident="bottomTable") tft.setStyle( plat.TableStyle([ ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ])) tft.wrapOn(canv, www, hhh) tft.drawOn(canv, doc.leftMargin, self.GLOB_PAGE_BOTTOM_MARGIN - 0.2 * cm) plp = plat.Image( io.BytesIO(logo.CONTI_CORP_LOGO), 4 * cm, 4 * cm * logo.CONTI_LOGO_SIZE[1] / float(logo.CONTI_LOGO_SIZE[0])) pss = ParagraphStyle(name="pst", fontSize=14, FontName="Calibri", alignment=TA_CENTER) pcp = plat.Paragraph("Algorithm Report", pss) # pr = Paragraph(self._headerInfo[4], ps) tft = plat.Table([[plp, pcp]], [4.2 * cm, 20.9 * cm], ident="topTable") tft.setStyle( plat.TableStyle([ ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ])) tft.wrapOn(canv, 10 * cm, hhh) tft.drawOn(canv, doc.leftMargin, self.GLOB_PAGE_WIDTH + 3.5 * cm) canv.restoreState()
def figure(self, fig=None, name=None, savefig_kwargs={}, **kwargs): """Add a figure to the report Parameters ---------- fig : None or str or `figure.Figure` Figure to place into report: `str` is treated as a filename, `Figure` stores it into a file under directory and embeds into the report, and `None` takes the current figure savefig_kwargs : dict Additional keyword arguments to provide savefig with (e.g. dpi) **kwargs Passed to :class:`reportlab.platypus.Image` constructor """ if externals.exists('pylab', raise_=True): import pylab as pl figure = pl.matplotlib.figure if fig is None: fig = pl.gcf() if isinstance(fig, figure.Figure): # Create directory if needed if not (os.path.exists(self._filename) and os.path.isdir(self._filename)): os.makedirs(self._filename) # Figure out the name for image self.__nfigures += 1 if name is None: name = 'Figure#' name = name.replace('#', str(self.__nfigures)) # Save image fig_filename = os.path.join(self._filename, '%s.%s' % (name, self.fig_ext)) if __debug__ and not self in debug.handlers: debug("REP_", "Saving figure '%s' into %s" % (fig, fig_filename)) fig.savefig(fig_filename, **savefig_kwargs) # adjust fig to the one to be included fig = fig_filename if __debug__ and not self in debug.handlers: debug("REP", "Adding figure '%s'" % fig) im = rplp.Image(fig, **kwargs) # If the inherent or provided width/height are too large -- shrink down imsize = (im.drawWidth, im.drawHeight) # Reduce the size if necessary so reportlab does not puke later on r = [float(d) / m for d, m in zip(imsize, self.pagesize)] maxr = max(r) if maxr > 1.0: if __debug__ and not self in debug.handlers: debug("REP_", "Shrinking figure by %.3g" % maxr) im.drawWidth /= maxr im.drawHeight /= maxr self._story.append(im)
def render_image(img: DG.Image) -> Flowable: """Convert an Image in to a Platypus version""" return platypus.Image(str(img.filename), height=img.height.points(), width=img.width.points())
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>' para = p.Paragraph(title_str, styles['section_style']) t = p.Table([[para]], colWidths=[7.5 * u.inch]) t.setStyle( p.TableStyle([ ('TOPPADDING', (0, 0), (-1, -1), 6), ('BOTTOMPADDING', (0, 0), (-1, -1), 6), ('BACKGROUND', (0, 0), (-1, -1), '#957348'), ('ALIGNMENT', (0, 0), (-1, -1), 'LEFT'), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('GRID', (0, 0), (-1, -1), 0.25, colors.black), ])) story.append(t) 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. ''' para = p.Paragraph(scatter_str, styles['body_style']) story.append(para) story.append(p.Spacer(0, 0.1 * u.inch)) # Add the scatterplot images to a list of lists table_cols = 2 scatter_table = [] scatter_row = [] for (i, fn) in enumerate(scatter_files): scatter_row.append(p.Image(fn, 3.4 * u.inch, 3.0 * u.inch)) if (i % table_cols) == (table_cols - 1): scatter_table.append(scatter_row) scatter_row = [] # Determine if there are any scatterplots left to print if len(scatter_row) != 0: for i in range(len(scatter_row), table_cols): scatter_row.append(p.Paragraph('', styles['body_style'])) scatter_table.append(scatter_row) # Style this into a reportlab table and add to the story width = 3.75 * u.inch t = p.Table(scatter_table, colWidths=[width, width]) t.setStyle( p.TableStyle([ ('ALIGNMENT', (0, 0), (-1, -1), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'CENTER'), ('TOPPADDING', (0, 0), (-1, -1), 6.0), ('BOTTOMPADDING', (0, 0), (-1, -1), 6.0), ])) story.append(t) # Return this story return story