def addTable(self,ndata,nkeys=None): data = [] if not nkeys: keys = self.hlib.getKeys(ndata) data.append(keys) else: keys = nkeys data.append(nkeys) for x in ndata: lister = [] for b in range(len(keys)): if keys[b] not in x: outb = None else: outb = x[keys[b]] t = Paragraph(str(outb),self.styles["Normal"]) lister.append(t) data.append(lister) 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),(-1,0),lightblue)]) t = LongTable(data,repeatRows=1) t.setStyle(tblStyle) self.story.append(t) self.story.append(CondPageBreak(6))
def heading2(self, chapter, text, outlinelabel='', fontname='', fontsize='', fontcolor=''): """Use to designate feature address/title(=text argument); chapter argument must be in _report.keys(). Elements of heading2 are bookmarked and shown in the PDF document outline.""" reportCh = self.report[chapter] #chNumber = reportCh[2].identity().split('>')[1].split('-')[0].strip() reportCh.append(CondPageBreak(inch)) self.seqchainChapterSection[chapter] += 1 self.seq.next( 'Section' ) # keeps track of total # of items in report & resets Fiqure sequencer fontTag = self.getFontTag(fontname, fontsize, fontcolor, 4) seqChapter, seqchainChapterSection = self.getChapterNoAndSectionNo( chapter) p = Paragraph( fontTag % '%d.%d)%s%s' % (seqChapter, seqchainChapterSection, html2space, GetUnicode(text)), self._H2) #p.outlineLabel = "Hello"+text reportCh.append(p) self.reportOutlineLabels[p.getPlainText()] = outlinelabel
def makeChapter(self, context, text, level, toc, numbered, sepChar, style, label=None): content = [] finalText = context.processTextCmds(text) if numbered: numberLabel = context.toc.renderChapterCounter(level, sepChar) finalText = numberLabel + sepChar + ' ' + finalText tocEntry = context.toc.createTOCEntry(finalText, level) chapter = context.paragraph( "<a name=\"%s\"/>%s" % (tocEntry._link, finalText), style) context.paragraphs.append(tocEntry) context.paragraphs.append(chapter) result = [CondPageBreak(2 * cm)] if toc: result.append(tocEntry) result.append(chapter) result.append(Spacer(1, 12 if level == 0 else 6)) content.append(KeepTogether(result)) return content
def clabel2(self, chapter, text, fontname='', fontsize='', fontcolor=''): """Use to label feature sub-sections; chapter argument must be in _report.keys(). Elements of clabel2 are NOT bookmarked for use in outline.""" reportCh = self.report[chapter] reportCh.append(CondPageBreak(inch)) fontTag = self.getFontTag(fontname, fontsize, fontcolor, 4) p = Paragraph(fontTag % GetUnicode(text), self._CL2) reportCh.append(p)
def _start_block(self, block, first=False): out = cStringIO.StringIO() if isinstance(block, ListEntry): out.write('<bullet>•</bullet>') if first: if isinstance(block, Header): self._story.append( CondPageBreak((7 - block.size) * pagesizes.inch / 2)) self._begin_incut(block) return out
def cheading2(self, chapter, text, outlinelabel='', fontname='', fontsize='', fontcolor=''): """Use to label feature sub-sections; chapter argument must be in _report.keys(). Elements of cheading2 are bookmarked for use in outline (child nodes of cheading1).""" reportCh = self.report[chapter] reportCh.append(CondPageBreak(inch)) fontTag = self.getFontTag(fontname, fontsize, fontcolor, 4) p = Paragraph(fontTag % GetUnicode(text), self._CH2) reportCh.append(p) self.reportOutlineLabels[p.getPlainText()] = outlinelabel
def outputTable(self, label, values): styleH = self.styles['title'] styleN = self.styles['default'] self.content.append(CondPageBreak(2 * inch)) self.content.append(Paragraph(label, styleH)) if not values: self.content.append(Paragraph('No New or Changed Fields.', styleN)) return fieldValueList = [[ Paragraph('<para alignment="right"><b>Plate</b></para>', styleN), Paragraph('<para alignment="right"><b>Field</b></para>', styleN), Paragraph('<b>Description</b>', styleN), Paragraph('<b>Value</b>', styleN) ]] for (plate, field, fdesc, fvalue) in values or []: list_value = self.escape_string(fvalue) if field < 0: field = '-' else: field = str(field) fieldValueList.append([ Paragraph('<para alignment="right">{0}.</para>'.format(plate), styleN), Paragraph('<para alignment="right">{0}.</para>'.format(field), styleN), Paragraph(fdesc, styleN), Paragraph('<para>{0}</para>'.format(list_value), styleN) ]) table = Table(fieldValueList, colWidths=[ 0.1 * 6.3 * inch, 0.1 * 6.3 * inch, 0.3 * 6.3 * inch, 0.5 * 6.3 * inch ], splitByRow=1, repeatRows=1, hAlign='LEFT') tablestyle = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LINEBEFORE', (3, 0), (3, -1), 1, lightgrey), ('LINEABOVE', (0, 0), (-1, -1), 1, lightgrey) ]) table.setStyle(tablestyle) self.content.append(table)
def genElements(self): colWidths = [25 * mm, 5 * mm, None] if self._type.lower() == "heading1": numString = u'%(Chapter01+)s.' elif self._type.lower() == "heading2": numString = u'%(Chapter01)s.%(Chapter02+)s.' elif self._type.lower() == "heading3": numString = u'%(Chapter01)s.%(Chapter02)s.%(Chapter03+)s.' elif self._type.lower() == "heading4": numString = u'%(Chapter01)s.%(Chapter02)s.%(Chapter03)s.' \ u'%(Chapter04+)s.' elif self._type.lower() == "heading5": numString = u'%(Chapter01)s.%(Chapter02)s.%(Chapter03)s.' \ u'%(Chapter04)s.%(Chapter05+)s.' elif self._type.lower() == "heading6": numString = u'%(Chapter01)s.%(Chapter02)s.%(Chapter03)s.' \ u'%(Chapter04)s.%(Chapter05)s.%(Chapter02+)s.' elif self._type.lower() == "title": numString = u'' else: numString = u'%(Chapter01)s.' p_1 = Paragraph(numString % self.getDocument().seq, self.getDocument().styles[self._type+"r"]) p_2 = Paragraph(self.getText(), \ self.getDocument().styles[self._type]) t_1 = Table([[p_1, None , p_2]], style=rpt_tbl_style, colWidths=colWidths, hAlign='LEFT') # for href stuff if hasattr(self._context, 'objectID'): t_1.ikoid = self._context.objectID if self.getDocument().firstH1Seen: t_1.keepWithNext = True t_1.ik_type = self._type if self._type.lower() == "heading1" or \ self._type.lower() == "title": if self.getDocument().firstH1Seen: return KeepTogether([CondPageBreak(A4[1]/5), t_1]) else: self.getDocument().firstH1Seen = True return t_1 else: return t_1
def process(self, block, context): if "layout" in block: pagedef = block["layout"] if isinstance(pagedef, str): for t in context.doc.doc.pageTemplates: if t.id == pagedef: template = t break else: style = context.doc.style identifier = pagedef["name"] if "name" in pagedef else str( len(context.doc.doc.pageTemplates)) # Get page size, can be an existing reportlab definition (A5, A4, A3, ...) or a custom size pageSize = pagedef["size"] if isinstance(pageSize, str) and hasattr(pagesizes, pageSize): size = getattr(pagesizes, pageSize) else: size = (pageSize[0] * cm, pageSize[1] * cm) # Compute page orientation if needed (supported keys are landscape and portrait) if "orientation" in pagedef and pagedef["orientation"] in [ "portrait", "landscape" ]: size = getattr(pagesizes, pagedef["orientation"])(size) template = PageTemplate( id=identifier, frames=Frame(style["marginL"], style["marginB"], size[0] - style["marginL"] - style["marginR"], size[1] - style["marginT"] - style["marginB"]), onPageEnd=context.doc.drawDecoration, pagesize=size) context.doc.doc.addPageTemplates(template) context.doc.pageRect = template.pagesize # Force the page layout to change just after the previous flowable has been drawn stick = "onPrevious" in block and block["onPrevious"] blocks = [cmn_utils_rp.Layout(template.id, context.doc.doc, stick)] if not stick: blocks.append(PageBreak()) return blocks else: return [CondPageBreak(0.9 * context.doc.currentHeight())]
def makeChapter(self, context, text, level, toc, numbered, sepChar, style, label=None): content = [] finalText = context.processTextCmds(text) numberLabel = '' if numbered: numberLabel = context.toc.renderChapterCounter(level, sepChar) finalText = numberLabel + sepChar + ' ' + finalText tocEntry = context.toc.createTOCEntry(finalText, level) chapter = context.paragraph( "<a name=\"%s\"/>%s" % (tocEntry._link, finalText), style) context.paragraphs.append(tocEntry) context.paragraphs.append(chapter) result = [CondPageBreak(2 * cm)] if toc: result.append(tocEntry) result.append(chapter) result.append(Spacer(1, 12 if level == 0 else 6)) content.append(KeepTogether(result)) if label and numbered: anchor = {} anchor['_name'] = tocEntry._link anchor['_label'] = numberLabel anchor['_text'] = text if anchor['_name'] in context.anchors: print("Warning: overwriting bookmark " + anchor['_name']) context.anchors[label] = anchor return content
def tide(story, doc): """This method will pre-calculate the size of the following flowable and force a page break on the story if the space available is not enough to contain the flowable. This avoids the break-up verses, choruses and tablatures.""" retval = [] frame_width = doc.width - doc.leftMargin - doc.rightMargin frame_height = doc.height - doc.topMargin - doc.bottomMargin for k in story: if not retval: retval.append(k) continue width, height = k.wrap(frame_width, frame_height) retval.append(CondPageBreak(height)) retval.append(k) return retval
def addTable(self, ndata): data = [] keys = self.getKeys(ndata) data.append(keys) for x in ndata: lister = [] for b in keys: outb = ndata[b] t = Paragraph(str(outb), self.styles["Normal"]) lister.append(t) data.append(lister) 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), (-1, 0), lightblue)]) t = LongTable(data, repeatRows=1) t.setStyle(tblStyle) self.story.append(t) self.story.append(CondPageBreak(6))
def next_frame(self): self.story.append(CondPageBreak(20 * cm))
def process(self, block, context): content = [] content.append(CondPageBreak(0.9 * context.doc.currentHeight())) return content
def conditionalPageBreak(self): self._story.append(CondPageBreak(self.MIN_HEIGHT_TABLE_AND_CHART))
def heading2(text): """Used to be 'lesson'""" getStory().append(CondPageBreak(inch)) p = Paragraph( '<seq template="%(Chapter)s.%(Section+)s "/>' + quickfix(text), H2) getStory().append(p)
def heading4(text): """Used to be most of the plain old 'head' sections""" getStory().append(CondPageBreak(inch)) p = Paragraph(quickfix(text), H4) getStory().append(p)
def CPage(inches): getStory().append(CondPageBreak(inches * inch))
def generatePdf(facility_name, Facility_data, Funding, current_year): """ generatePdf creates a PDF document based on the reporting data supplied. It is using very strict formatting, but is quite simple to edit. This function will print the name of the facility its working on, and any warnings that may arise. The excel document can be edited to fix warnings and to change the information in the PDFs. """ print("\nFacility report {}: {}".format(current_year, facility_name)) if not os.path.isdir("pdfs_onepagers/"): os.mkdir("pdfs_onepagers/") # Setting the document sizes and margins. showBoundary is useful for debugging doc = BaseDocTemplate( "pdfs_onepagers/{}_{}.pdf".format( current_year, facility_name.lower().replace(" ", "_")), pagesize=A4, rightMargin=18 * mm, leftMargin=14 * mm, topMargin=16 * mm, bottomMargin=20 * mm, showBoundary=0, ) # These are the fonts available, in addition to a number of "standard" fonts. # These are used in setting paragraph styles pdfmetrics.registerFont(TTFont("Lato-B", "Lato-Black.ttf")) # looks bolder pdfmetrics.registerFont(TTFont("Lato", "Lato-Regular.ttf")) # I have used spaceAfter, spaceBefore and leading to change the layout of the "paragraphs" created with these styles styles = getSampleStyleSheet() styles.add( ParagraphStyle( name="onepager_inner_heading", parent=styles["Heading1"], fontName="Lato-B", fontSize=10, color="#FF00AA", leading=16, spaceAfter=0, spaceBefore=8, )) styles.add( ParagraphStyle( name="onepager_chart_heading", parent=styles["Heading1"], fontName="Lato-B", fontSize=10, color="#FF00AA", leading=16, spaceAfter=4, spaceBefore=8, )) styles.add( ParagraphStyle( name="onepager_title", parent=styles["Heading1"], fontName="Lato-B", fontSize=16, bold=0, color="#000000", leading=16, spaceBefore=0, )) styles.add( ParagraphStyle( name="onepager_text", parent=styles["Normal"], fontName="Lato", fontSize=10, bold=0, color="#000000", leading=14, )) styles.add( ParagraphStyle( name="onepager_footnote", parent=styles["Normal"], fontName="Lato", fontSize=7, bold=0, color="#000000", leading=14, spaceBefore=20, )) # The document is set up with two frames, one frame is one column, and their widths are set according to SciLifeLab design policy frame1 = Frame( doc.leftMargin, doc.bottomMargin + (doc.height / 2), doc.width / 3, # - 3.5 * mm, (doc.height / 2) - 18 * mm, id="col1", # showBoundary=1, #this can be used to show where the frame sits - useful for setting up layout leftPadding=0 * mm, topPadding=5 * mm, rightPadding=0 * mm, bottomPadding=0 * mm, ) frame2 = Frame( doc.leftMargin + doc.width / 3 + 2 * mm, # 2 + 3.5 * mm, doc.bottomMargin + (doc.height / 2), doc.width / 3, # 2 - 3.5 * mm, (doc.height / 2) - 18 * mm, id="col2", # showBoundary=1, leftPadding=0 * mm, topPadding=5 * mm, rightPadding=0 * mm, bottomPadding=0 * mm, ) frame3 = Frame( doc.leftMargin + (3.5 * mm) + doc.width * 0.61, doc.bottomMargin + (doc.height / 2), doc.width / 2.7, # 2 - 3.5 * mm, (doc.height / 2) - 18 * mm, id="col3", # showBoundary=1, leftPadding=0 * mm, topPadding=5 * mm, rightPadding=0 * mm, bottomPadding=0 * mm, ) # top 3 frames contain the text # Next frames the Figures # Bar charts go first - divide the page in halves for them frame4 = Frame( doc.leftMargin, doc.bottomMargin + (doc.height / 4), doc.width / 2, # 2 - 3.5 * mm, (doc.height / 4), # + 50 * mm, # - 18 * mm, id="pic1", # showBoundary=1, leftPadding=0 * mm, topPadding=3 * mm, rightPadding=0 * mm, bottomPadding=0 * mm, ) frame5 = Frame( doc.leftMargin + (doc.width / 2), doc.bottomMargin + (doc.height / 4), doc.width / 2, # 2 - 3.5 * mm, (doc.height / 4), # + 50 * mm, # - 18 * mm, id="pic2", # showBoundary=1, leftPadding=0 * mm, topPadding=3 * mm, rightPadding=0 * mm, bottomPadding=0 * mm, ) # NOW 3 PIE CHARTS frame6 = Frame( doc.leftMargin, doc.bottomMargin, doc.width / 3, # 2 - 3.5 * mm, (doc.height / 4), # + 50 * mm, # - 18 * mm, id="pic3", # showBoundary=1, leftPadding=0 * mm, topPadding=0 * mm, rightPadding=0 * mm, bottomPadding=0 * mm, ) frame7 = Frame( doc.leftMargin + doc.width / 3, doc.bottomMargin, doc.width / 3, # 2 - 3.5 * mm, (doc.height / 4), # + 50 * mm, # - 18 * mm, id="pic4", # showBoundary=1, leftPadding=0 * mm, topPadding=0 * mm, rightPadding=0 * mm, bottomPadding=0 * mm, ) frame8 = Frame( doc.leftMargin + doc.width / 3 + doc.width / 3, doc.bottomMargin, doc.width / 3, # 2 - 3.5 * mm, (doc.height / 4), # + 50 * mm, # - 18 * mm, id="pic5", # showBoundary=1, leftPadding=0 * mm, topPadding=0 * mm, rightPadding=0 * mm, bottomPadding=0 * mm, ) header_content = Paragraph( "<b>{}</b><br/><font name=Lato size=12> {} platform</font>".format( (Facility_data["Facility"]).to_string(index=False), (Facility_data["Platform"]).to_string(index=False), ), styles["onepager_title"], ) template = PageTemplate( id="test", frames=[ frame1, frame2, frame3, frame4, frame5, frame6, frame7, frame8 ], onPage=partial(header, content=header_content), ) doc.addPageTemplates([template]) # frames=[frame1,frame2] # The Story list will contain all Paragraph and other elements. In the end this is used to build the document Story = [] ### Below here will be Paragraph and Image elements added to the Story, they flow through frames automatically, ### however I have set a framebreak to correctly organise things in left/right column. pd.options.display.max_colwidth = 600 Story.append( Paragraph( "<font color='#A7C947' name=Lato-B><b>Basic information</b></font>", styles["onepager_inner_heading"], )) # Drug Discovery and Development (DDD) is a platform. needs different formatting if facility_name == "Drug Discovery and Development": Story.append( Paragraph( "<font name=Lato-B><b>Platform directors: </b></font> {}". format((Facility_data["FD"]).to_string(index=False), ), styles["onepager_text"], )) Story.append( Paragraph( "<font name=Lato-B><b>SciLifeLab platform since: </b></font> {}" .format((Facility_data["SLL_since"]).to_string(index=False), ), styles["onepager_text"], )) else: Story.append( Paragraph( "<font name=Lato-B><b>Facility director(s): </b></font> {}". format((Facility_data["FD"]).to_string(index=False), ), styles["onepager_text"], )) Story.append( Paragraph( "<font name=Lato-B><b>Head(s) of facility: </b></font> {}". format((Facility_data["HOF"]).to_string(index=False), ), styles["onepager_text"], )) Story.append( Paragraph( "<font name=Lato-B><b>SciLifeLab facility since: </b></font> {}" .format((Facility_data["SLL_since"]).to_string(index=False), ), styles["onepager_text"], )) pd.options.display.max_colwidth = 600 Story.append( Paragraph( "<font name=Lato-B><b>Host university: </b></font>{}".format( (Facility_data["H_uni"]).to_string(index=False), ), styles["onepager_text"], )) Story.append( Paragraph( "<font name=Lato-B><b>FTEs: </b></font>{}".format( (Facility_data["FTEs"]).to_string(index=False), ), styles["onepager_text"], )) Story.append( Paragraph( u"<font name=Lato-B><b>FTEs financed by SciLifeLab: </b></font>{}". format((Facility_data["SLL_FTEs"]).to_string(index=False), ), styles["onepager_text"], )) Story.append( Paragraph( "<font color='#A7C947'><font name=Lato-B><b>Funding in {} (kSEK)</b></font></font>" .format(current_year), styles["onepager_inner_heading"], )) # Funding (need to have Scilifelab, other sources and then total) # SLL funding in file provided by OO. Calculated total using this and 'other funding' Story.append( Paragraph( "<font name=Lato-B><b>SciLifeLab: </b></font>{}".format( (Facility_data["Amount (kSEK)"]).to_string(index=False), ), styles["onepager_text"], )) # Scilifelab funding is in funding data and total funding is in there too, but other financiers vary # Need to take out Scilifelab funding and total funding to be able to go through other funders without issue fundwosll = Funding[~Funding.Financier.eq("SciLifeLab")] fundwoslltot = fundwosll[~fundwosll.Financier.eq("Total")] for i in fundwoslltot["Financier"].unique(): temp = fundwoslltot[(fundwoslltot["Financier"] == i)] if temp is not None: Story.append( Paragraph( "<font name=Lato-B><b>{}: </b></font>{}".format( i, temp["Amount (kSEK)"][ temp["Amount (kSEK)"].first_valid_index()], ), styles["onepager_text"], )) # now a line above the total value Story.append( HRFlowable( width="40%", thickness=0.5, lineCap="round", color=SCILIFE_COLOURS_GREYS[1], spaceBefore=1, spaceAfter=1, hAlign="LEFT", vAlign="BOTTOM", dash=None, )) # now the totals fundstot = Funding[Funding.Financier.eq("Total")] Story.append( Paragraph( "<font name=Lato-B><b>Total: </b></font>{}".format( (fundstot["Amount (kSEK)"]).to_string(index=False), ), styles["onepager_text"], )) Story.append(CondPageBreak(100 * mm)) ### RESOURCE ALLOCATION total_percentage = total_percentage = (int(Facility_data["RA_nat"]) + int(Facility_data["RA_int"]) + int(Facility_data["RA_tech"]) + int(Facility_data["RA_Ind"]) + int(Facility_data["RA_Health"]) + int(Facility_data["RA_ogov"])) if total_percentage == 100: Story.append( Paragraph( "<font color='#A7C947'><font name=Lato-B><b>Resource allocation {}</b></font></font>" .format(current_year), styles["onepager_inner_heading"], )) else: print( "WARNING: PERCENTAGE DOES NOT ADD UP TO 100 IN RESOURCE_ALLOCATION FOR", facility_name, total_percentage, ) Story.append( Paragraph( "<font color='#FF0000'><font name=Lato-B><b>Resource allocation {}</b></font></font>" .format(current_year), styles["onepager_inner_heading"], )) if int(Facility_data.RA_nat) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["RA_nat"])) Story.append( Paragraph( "<font name=Lato-B><b>Academia (national): </b></font>{}".format( tmp_input), styles["onepager_text"], )) if int(Facility_data.RA_int) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["RA_int"])) Story.append( Paragraph( "<font name=Lato-B><b>Academia (international): </b></font>{}". format(tmp_input), styles["onepager_text"], )) if int(Facility_data.RA_tech) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["RA_tech"])) Story.append( Paragraph( "<font name=Lato-B><b>Internal tech. dev.: </b></font>{}".format( tmp_input), styles["onepager_text"], )) if int(Facility_data.RA_Ind) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["RA_Ind"])) Story.append( Paragraph( "<font name=Lato-B><b>Industry: </b></font>{}".format(tmp_input), styles["onepager_text"], )) if int(Facility_data.RA_Health) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["RA_Health"])) Story.append( Paragraph( "<font name=Lato-B><b>Healthcare: </b></font>{}".format(tmp_input), styles["onepager_text"], )) if int(Facility_data.RA_ogov) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["RA_ogov"])) Story.append( Paragraph( "<font name=Lato-B><b>Other gov. agencies: </b></font>{}".format( tmp_input), styles["onepager_text"], )) # Story.append(CondPageBreak(50 * mm)) ### USER FEES - reagents, instruments... total_percentage = (int(Facility_data["UF_reag"]) + int(Facility_data["UF_instr"]) + int(Facility_data["UF_sal"]) + int(Facility_data["UF_rent"]) + int(Facility_data["UF_other"])) if total_percentage == 100: Story.append( Paragraph( "<font color='#A7C947'><font name=Lato-B><b>User Fees {}</b></font></font>" .format(current_year), styles["onepager_inner_heading"], )) else: print( "WARNING: PERCENTAGE DOES NOT ADD UP TO 100 IN COSTS FOR", facility_name, total_percentage, ) Story.append( Paragraph( "<font color='#FF0000'><font name=Lato-B><b>User Fees {}</b></font></font>" .format(current_year), styles["onepager_inner_heading"], )) Story.append( Paragraph( "<font name=Lato-B><b>Total (kSEK): </b></font>{}".format( (Facility_data["UF_Tot"]).to_string(index=False), ), styles["onepager_text"], )) Story.append( HRFlowable( width="40%", thickness=0.5, lineCap="round", color=SCILIFE_COLOURS_GREYS[1], spaceBefore=1, spaceAfter=1, hAlign="LEFT", vAlign="BOTTOM", dash=None, )) if int(Facility_data.UF_reag) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["UF_reag"])) Story.append( Paragraph( "<font name=Lato-B><b>Reagents: </b></font>{}".format(tmp_input), styles["onepager_text"], )) if int(Facility_data.UF_instr) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["UF_instr"])) Story.append( Paragraph( "<font name=Lato-B><b>Instrument: </b></font>{}".format(tmp_input), styles["onepager_text"], )) if int(Facility_data.UF_sal) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["UF_sal"])) Story.append( Paragraph( "<font name=Lato-B><b>Salaries: </b></font>{}".format(tmp_input), styles["onepager_text"], )) if int(Facility_data.UF_rent) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["UF_rent"])) Story.append( Paragraph( "<font name=Lato-B><b>Rent: </b></font>{}".format(tmp_input), styles["onepager_text"], )) if int(Facility_data.UF_other) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["UF_other"])) Story.append( Paragraph( "<font name=Lato-B><b>Other: </b></font>{}".format(tmp_input), styles["onepager_text"], )) Story.append(CondPageBreak(100 * mm)) ### USER FEES BY SECTOR total_percentage = (int(Facility_data["UF_sect_nat"]) + int(Facility_data["UF_sect_int"]) + int(Facility_data["UF_sect_ind"]) + int(Facility_data["UF_sect_health"]) + int(Facility_data["UF_sect_othgov"])) if total_percentage == 100: Story.append( Paragraph( "<font color='#A7C947'><font name=Lato-B><b>User fees by sector {}</b></font></font>" .format(current_year), styles["onepager_inner_heading"], )) else: print( "WARNING: PERCENTAGE DOES NOT ADD UP TO 100 IN USER FEES FOR", facility_name, total_percentage, ) Story.append( Paragraph( "<font color='#FF0000'><font name=Lato-B><b>User fees by sector {}</b></font></font>" .format(current_year), styles["onepager_inner_heading"], )) if int(Facility_data.UF_sect_nat) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["UF_sect_nat"])) Story.append( Paragraph( "<font name=Lato-B><b>Academia (national): </b></font>{}".format( tmp_input), styles["onepager_text"], )) if int(Facility_data.UF_sect_int) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["UF_sect_int"])) Story.append( Paragraph( "<font name=Lato-B><b>Academia (international): </b></font>{}". format(tmp_input), styles["onepager_text"], )) if int(Facility_data.UF_sect_ind) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["UF_sect_ind"])) Story.append( Paragraph( "<font name=Lato-B><b>Industry: </b></font>{}".format(tmp_input), styles["onepager_text"], )) if int(Facility_data.UF_sect_health) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["UF_sect_health"])) Story.append( Paragraph( "<font name=Lato-B><b>Healthcare: </b></font>{}".format(tmp_input), styles["onepager_text"], )) if int(Facility_data.UF_sect_othgov) == 0: tmp_input = "-" else: tmp_input = "{}%".format(int(Facility_data["UF_sect_othgov"])) Story.append( Paragraph( "<font name=Lato-B><b>Other gov. agencies: </b></font>{}".format( tmp_input), styles["onepager_text"], )) # Story.append(CondPageBreak(50 * mm)) #### SERVICES Story.append( Paragraph( "<font color='#A7C947'><font name=Lato-B><b>Services</b></font></font>", styles["onepager_inner_heading"], )) if Facility_data["Services"].notnull: pd.options.display.max_colwidth = 600 bullet_pointing = Facility_data["Services"].to_string(index=False) bullet_points = bullet_pointing.replace("\\n", "*") bullet_points = bullet_points.split("*") # .explode(bullet_points) for bullet in bullet_points: Story.append(Paragraph(bullet, styles["onepager_text"])) else: Story.append( Paragraph( "Service information goes here, please input text in excel file", styles["onepager_text"], )) # special notes # This puts an asterisk at the bottom of the services, with some info if there was any in the data file if facility_name == "Mass Cytometry (KI)": Story.append( Paragraph( "Note: publication data is combined for the two Mass Cytometry facilities", styles["onepager_footnote"], )) elif facility_name == "Mass Cytometry (LiU)": Story.append( Paragraph( "Note: publication data is combined for the two Mass Cytometry facilities", styles["onepager_footnote"], )) else: print("no special notes for this facility") # Now I need to put in the Figures.. (5 plots if data is available for everything, or some might be missing) # figs already made in .svg format, they need to be imported Story.append(CondPageBreak(200 * mm)) # move to next frame # pubs by cat first, then pubs by JIF Story.append( Paragraph( "<font color='#A7C947' name=Lato-B><b>Publication by category</b></font>", styles["onepager_chart_heading"], )) filepath_cats = "/Users/liahu895/Documents/GitHub/IAB_2021/Facility_one_pagers/Updated_2021scripts/Plots/pubcat_plots/{}_cats.svg".format( (facility_name), ) isFile_cats = os.path.isfile(filepath_cats) if isFile_cats == True: im_cats = svg2rlg(filepath_cats) im_cats = Image(im_cats, width=70 * mm, height=55 * mm) im_cats.hAlign = "CENTER" Story.append(im_cats) else: Story.append( Paragraph( "No publication data available", styles["onepager_text"], )) # Now JIF barchart Story.append(CondPageBreak(200 * mm)) # move to next frame Story.append( Paragraph( "<font color='#A7C947' name=Lato-B><b>Publication by Journal Impact Factor</b></font>", styles["onepager_chart_heading"], )) filepath_JIF = "/Users/liahu895/Documents/GitHub/IAB_2021/Facility_one_pagers/Updated_2021scripts/Plots/JIF_plots/{}_JIF.svg".format( (facility_name), ) isFile_JIF = os.path.isfile(filepath_JIF) if isFile_JIF == True: im_JIF = svg2rlg(filepath_JIF) im_JIF = Image(im_JIF, width=70 * mm, height=55 * mm) im_JIF.hAlign = "CENTER" Story.append(im_JIF) else: Story.append( Paragraph( "No publication data available", styles["onepager_text"], )) Story.append(CondPageBreak(200 * mm)) # move to next frame # # Now the pie charts (in the lowest part of the page)- ascending year left to right Story.append( Paragraph( "<font color='#A7C947' name=Lato-B><b>Users {}</b></font>".format( int(current_year) - 2), styles["onepager_chart_heading"], )) filepath_u18 = "/Users/liahu895/Documents/GitHub/IAB_2021/Facility_one_pagers/Updated_2021scripts/Plots/Aff_Pies/{}_{}_affs.svg".format( (facility_name), (int(current_year) - 2), ) isFile_u18 = os.path.isfile(filepath_u18) if isFile_u18 == True: im_u18 = svg2rlg(filepath_u18) im_u18 = Image(im_u18, width=58 * mm, height=58 * mm) im_u18.hAlign = "CENTER" Story.append(im_u18) else: Story.append( Paragraph( "No user information", styles["onepager_text"], )) Story.append(CondPageBreak(200 * mm)) # move to next frame Story.append( Paragraph( "<font color='#A7C947' name=Lato-B><b>Users {}</b></font>".format( int(current_year) - 1), styles["onepager_chart_heading"], )) filepath_u19 = "/Users/liahu895/Documents/GitHub/IAB_2021/Facility_one_pagers/Updated_2021scripts/Plots/Aff_Pies/{}_{}_affs.svg".format( (facility_name), (int(current_year) - 1), ) isFile_u19 = os.path.isfile(filepath_u19) if isFile_u19 == True: im_u19 = svg2rlg(filepath_u19) im_u19 = Image(im_u19, width=58 * mm, height=58 * mm) im_u19.hAlign = "CENTER" Story.append(im_u19) else: Story.append( Paragraph( "No user information", styles["onepager_text"], )) Story.append(CondPageBreak(200 * mm)) # move to next frame Story.append( Paragraph( "<font color='#A7C947' name=Lato-B><b>Users {}</b></font>".format( int(current_year)), styles["onepager_chart_heading"], )) filepath_u20 = "/Users/liahu895/Documents/GitHub/IAB_2021/Facility_one_pagers/Updated_2021scripts/Plots/Aff_Pies/{}_{}_affs.svg".format( (facility_name), (int(current_year)), ) isFile_u20 = os.path.isfile(filepath_u20) if isFile_u20 == True: im_u20 = svg2rlg(filepath_u20) im_u20 = Image(im_u20, width=58 * mm, height=58 * mm) im_u20.hAlign = "CENTER" Story.append(im_u20) else: Story.append( Paragraph( "No user information", styles["onepager_text"], )) # Finally, build the document. doc.build(Story)
def _print_paragraph(self, block, level=None, root=False, width=1.0): if isinstance(block, Code): return self._print_code(block, root) if isinstance(block, Table): return self._print_table(block, table_width=width) if isinstance(block, PageSpacer): if block.isbreak: if block.iscond: return self._story.append( CondPageBreak(block.height * self.PAGE_HEIGHT)) return self._story.append(PageBreak()) if block.style: self._set_page_template(block.style) # Break to a new page unless we already have whole page available. This trick # is used to render cheatsheets both in book and in separate PDF without extra page return self._story.append(NextPageTemplate(block.style)) return self._story.append( Spacer(0, block.height * self.PAGE_HEIGHT)) # Save state to get paragraphs if isinstance(block, FlowableIncut): width = block.coords.get('w', width) self._save_state() elif root and isinstance(block, Incut): self._save_state() # Pick paragraph style based on block nature style = self._styles['default'] if isinstance(block, Header): style = self._styles['h{0}'.format(block.size)] elif isinstance(block, BlockQuote): style = self._styles['blockquote'] elif root: style = self._styles['root'] # Generate style for lists on-the-fly if level: style = ParagraphStyle('style{0}'.format(id(block)), parent=style, bulletIndent=(level * 10), spaceAfter=0, spaceBefore=0) # Generate paragraph's text. PLATYPUS doesn't support hiearchial paragraphs like HTML do, # so we linearize blocks into paragraphs list: each time subblock appear, we complete # current paragraph and start a new one. # For Incuts which may have subparagraphs, we add two colored paragraphs before and after # so they will be distinguishable. Span is another exception -- it doesn't rendered as # separate paragraph, but as a <span> within paragraph. out = self._start_block(block, True) for part in block.parts: if isinstance(part, Block) and not isinstance(part, Span): out = self._end_block(root, out, block, style) # Allow to use "root" style for root lists, but forbid it in tables and incuts, etc. childroot = False if isinstance(part, ListEntry) or isinstance(part, ListBlock): level = getattr(part, 'level', None) childroot = root if isinstance(part, Code) or isinstance(part, Table): childroot = root self._print_paragraph(part, level, root=childroot, width=width) continue if isinstance(part, Image): # Create separate paragraph for large images img = self._print_image(part, width) if not isinstance(img, RLImage) or ( img._width > self.MAX_INLINE_IMAGE_SIZE or img._height > self.MAX_INLINE_IMAGE_SIZE): out = self._end_block(root, out, block, style) # We want to keep image together with a paragraph before if self._story: img = _ImageBlock(self._story.pop(), img) self._story.append(img) continue self._part_to_strio(part, out, style.fontSize) self._end_block(root, out, block, style, True) if isinstance(block, FlowableIncut): incut = _FlowableIncut(block.coords, self._restore_state()) return self._story.append(incut) if root and isinstance(block, Incut): incut = KeepTogether(self._restore_state()) return self._story.append(incut)
def _begin_incut(self, block): incut_style, incut_message = self._incut_format(block) if incut_style: self._story.append(CondPageBreak(pagesizes.inch / 2)) self._story.append(RLParagraph(incut_message, style=incut_style))
def CPage(self, chapter, inches): self.report[chapter].append(CondPageBreak(inches * inch))