我们从Python开源项目中,提取了以下30个代码示例,用于说明如何使用reportlab.platypus.Spacer()。
def add_header(self): # # aiddata logo # logo = self.assets_dir + '/templates/aid_data.png' # im = Image(logo, 2.188*inch, 0.5*inch) # im.hAlign = 'LEFT' # self.Story.append(im) # self.Story.append(Spacer(1, 0.25*inch)) # title ptext = '<font size=20>AidData GeoQuery Request Documentation</font>' self.Story.append(Paragraph(ptext, self.styles['Center'])) # report generation info
def test_11_drawing(self): from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph from reportlab.pdfbase import pdfmetrics from reportlab.graphics.shapes import Drawing, Rect from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) stylesheet = getSampleStyleSheet() elements = [] doc = SimpleDocTemplate("demo.pdf") elements.append(Paragraph('<font name="chsFont">JY.zenist.song - ??</font>', stylesheet['Title'])) elements.append(Spacer(1,12)) d = Drawing(400,200) d.add(Rect(50,50,300,100, fillColor=colors.yellow)) elements.append(d) doc.build(elements)
def test_09_docTemplate(self): from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) stylesheet = getSampleStyleSheet() elements = [] doc = SimpleDocTemplate("demo.pdf") elements.append(Paragraph('<font name="chsFont">AUT OOM????</font>', stylesheet['Title'])) elements.append(Spacer(1,12)) doc.build(elements)
def add_str_content(self, content, size=9, Bold=False, indent=(0.05*inch, 0.05*inch), style=None): ''' ?????? :param content: ?????? :param size: ????,??9 :param Bold: ????,??False :param indent: ??????,(???,???) :param style: ???? ''' if style == None: style = styles["Normal"] __content = "<font name='chsFont' size=%s>%s</font>" % (size, content) if Bold: __content = "<b>%s</b>" % __content p = Paragraph(__content, style) self.__content.append(Spacer(PAGE_WIDTH, indent[0])) self.__content.append(p) self.__content.append(Spacer(PAGE_WIDTH, indent[1]))
def add_timeline(self): ptext = '<b><font size=14>Processing Timeline</font></b>' self.Story.append(Paragraph(ptext, self.styles['Normal'])) self.Story.append(Spacer(1, 0.1*inch)) data = [ [self.request['stage'][0]['name'], self.time_str(self.request['stage'][0]['time'])], [self.request['stage'][1]['name'], self.time_str(self.request['stage'][1]['time'])], [self.request['stage'][2]['name'], self.time_str(self.request['stage'][2]['time'])], [self.request['stage'][3]['name'], self.time_str(int(time.time()))] # ['complete', self.time_str(self.request['stage'][3]['time'])] ] data = [[i[0], pg(i[1], 1)] for i in data] t = Table(data) t.setStyle(TableStyle([ ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black) ])) self.Story.append(t)
def add_question(self, question): self.pdf_elements.append( Paragraph(question, self.body_style), ) self.pdf_elements.append(Spacer(1, 4))
def add_answer_list(self, answers): for answer in answers: self.pdf_elements.append( Paragraph(answer, self.notes_style), ) self.pdf_elements.append(Spacer(1, 1))
def go(self): doc = SimpleDocTemplate("demo.pdf") Story = [Spacer(1, 2*inch)] style = styles["Normal"] for i in range(100): bogustext = ("This is Paragraph number %s. " % i) * 20 p = Paragraph(bogustext, style) Story.append(p) Story.append(Spacer(1, 0.2*inch)) doc.build(Story, onFirstPage=self.myFirstPage, onLaterPages=self.myLaterPage)
def test_08_table(self): from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph, Table from reportlab.lib.units import inch from reportlab.lib.enums import TA_JUSTIFY from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.lib import fonts, colors pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) stylesheet = getSampleStyleSheet() elements = [] doc = SimpleDocTemplate("demo.pdf") elements.append(Paragraph('<font name="chsFont">AUT OOM????</font>', stylesheet['Title'])) elements.append(Spacer(1,12)) stylesheet.add(ParagraphStyle(name="Justify", alignment=TA_JUSTIFY)) stylesheet['Justify'].contName = 'chsFont' data = [] data.append(["???","???","???"]) data.append(["120","6","50"]) ts = [('INNERGRID',(0,0),(-1,-1),0.25, colors.black),("BOX",(0,0),(-1,-1),0.25,colors.black),('FONT',(0,0),(-1,-1), 'chsFont')] table = Table(data, 2.1*inch, 0.24*inch, ts) elements.append(table) doc.build(elements)
def test_23_linePlotCharts(self): from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors from reportlab.lib.units import inch from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph from reportlab.pdfbase import pdfmetrics from reportlab.graphics.shapes import Drawing from reportlab.pdfbase.ttfonts import TTFont from reportlab.graphics.charts.lineplots import LinePlot from reportlab.graphics.widgets.markers import makeMarker pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) stylesheet = getSampleStyleSheet() elements = [] doc = SimpleDocTemplate("demo.pdf") elements.append(Paragraph('<font name="chsFont">JY.zenist.song - ??</font>', stylesheet['Title'])) elements.append(Spacer(1,1*inch)) d = Drawing(400,200) data = [ [(1,1), (2,2), (2.5,1), (3,3), (4,5)], ] lp = LinePlot() lp.x = 5 lp.y = 5 lp.height = 190 lp.width = 390 lp.data = data lp.joinedLines = 1 lp.lines[0].symbol = makeMarker('FilledCircle') d.add(lp) elements.append(d) doc.build(elements)
def test_24_PieCharts(self): from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors from reportlab.lib.units import inch from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph from reportlab.pdfbase import pdfmetrics from reportlab.graphics.shapes import Drawing from reportlab.pdfbase.ttfonts import TTFont from reportlab.graphics.charts.piecharts import Pie pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) stylesheet = getSampleStyleSheet() elements = [] doc = SimpleDocTemplate("demo.pdf") elements.append(Paragraph('<font name="chsFont">JY.zenist.song - ??</font>', stylesheet['Title'])) elements.append(Spacer(1,1*inch)) d = Drawing(400,200) data = [13,5,20,22,37,45] pc = Pie() pc.x = 65 pc.y = 15 pc.width = 150 pc.height = 150 pc.data = data pc.labels = ['a','b','c','d','e','f'] d.add(pc) elements.append(d) doc.build(elements)
def add_empty_line(self, lines=1): '''????''' self.__content.append(Spacer(PAGE_WIDTH, 0.3*inch*lines))
def AddPage(self): self.Score_Table=Table(self.Score_Data,[self.cW1*cm]+8*[self.cW*cm], [self.rH1*cm]+[self.rH2*cm]+14*[self.rH*cm]) #self.Attendance_Table=Table(self.Attendance_Data,[self.cW*2.2*cm]+4*[self.cW*2*cm],5*[self.rH*cm]) self.Attendance_Table=Table(self.Attendance_Data,[self.cW1*cm]+4*[self.cW*2*cm],5*[self.rH*cm]) self.Score_Table.setStyle(TableStyle(self.Score_T_Style)) self.Attendance_Table.setStyle(TableStyle(self.Attendance_T_Style)) self.elements.append(self.Score_Table) self.elements.append(Spacer(1, 15)) self.elements.append(self.Attendance_Table) self.elements.append(PageBreak())
def AddPage(self): #self.Score_Table=Table(self.Score_Data,[.3*inch]+[1*inch]+8*[0.6*inch], [.8*inch]+[.6*inch]+14*[0.35*inch]) self.Score_Table=Table(self.Score_Data,[.5*inch]+[(self.cW1*cm)-.5*inch]+8*[self.cW*cm], [self.rH1*cm]+[self.rH2*cm]+14*[self.rH*cm]) self.Attendance_Table=Table(self.Attendance_Data,[self.cW*2.2*cm]+4*[self.cW*2*cm],5*[self.rH*cm]) self.Score_Table.setStyle(TableStyle(self.Score_T_Style)) self.Attendance_Table.setStyle(TableStyle(self.Attendance_T_Style)) self.elements.append(self.Score_Table) self.elements.append(Spacer(1, 18)) self.elements.append(self.Attendance_Table) self.elements.append(PageBreak())
def Add_Consolidation(self): fill=16-self.table_count self.elements.append(Spacer(1, fill*15)) self.Consolidation_Table=Table(self.CONSOLIDATION,[9*cm]+[4*cm]+[1*cm]*3+[9*cm]*3,[.3*cm]+[.3*cm]*4) self.Consolidation_Table.setStyle(TableStyle(self.Consolidation_Style)) self.elements.append(Spacer(1, 10)) self.elements.append(self.Consolidation_Table)
def AddPage(self): self.Score_Table=Table(self.Score_Data,[self.cW1*cm]+8*[self.cW*cm], [self.rH1*cm]+[self.rH2*cm]+14*[self.rH*cm]) self.Attendance_Table=Table(self.Attendance_Data,[self.cW*2.2*cm]+4*[self.cW*2*cm],5*[self.rH*cm]) self.Score_Table.setStyle(TableStyle(self.Score_T_Style)) self.Attendance_Table.setStyle(TableStyle(self.Attendance_T_Style)) self.elements.append(self.Score_Table) self.elements.append(Spacer(1, 15)) self.elements.append(self.Attendance_Table) self.elements.append(PageBreak())
def AddPage(self): #self.Score_Table=Table(self.Score_Data,[.3*inch]+[1*inch]+8*[0.6*inch], [.8*inch]+[.6*inch]+14*[0.35*inch]) self.Score_Table=Table(self.Score_Data,[.3*inch]+[(self.cW1*cm)-.3*inch]+8*[self.cW*cm], [self.rH1*cm]+[self.rH2*cm]+14*[self.rH*cm]) self.Attendance_Table=Table(self.Attendance_Data,[self.cW*2.2*cm]+4*[self.cW*2*cm],5*[self.rH*cm]) self.Score_Table.setStyle(TableStyle(self.Score_T_Style)) self.Attendance_Table.setStyle(TableStyle(self.Attendance_T_Style)) self.elements.append(self.Score_Table) self.elements.append(Spacer(1, 15)) self.elements.append(self.Attendance_Table) self.elements.append(PageBreak())
def get_template(self, template_file, url): formatted_time = time.ctime() company = self.application.config['mailer.company_name'] sender = self.application.config['mailer.source_email_alias'] 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 build_doc(self): rid = self.request_id print 'build_doc: ' + rid # try: self.doc = SimpleDocTemplate(self.output, pagesize=letter) # build doc call all functions self.add_header() self.Story.append(Spacer(1, 0.5*inch)) self.add_info() self.Story.append(Spacer(1, 0.3*inch)) self.add_timeline() self.Story.append(Spacer(1, 0.3*inch)) self.add_cite_and_contents() self.Story.append(PageBreak()) self.add_meta() self.Story.append(PageBreak()) self.add_notes() self.Story.append(PageBreak()) self.add_additional() self.output_doc() return True # except: # return False # documentation header
def add_info(self): ptext = '<b><font size=14>Report Info</font></b>' self.Story.append(Paragraph(ptext, self.styles['BodyText'])) self.Story.append(Spacer(1, 0.1*inch)) data = [ ['Request Name', self.request['custom_name']], ['Request Id', str(self.request['_id'])], ['Email', self.request['email']], ['Generated on', self.time_str()], ['Download Link', '<a href="http://{0}/query/#!/status/{1}">{0}/query/#!/status/{1}</a>'.format( self.download_server, self.request['_id'])] ] data = [[i[0], pg(i[1], 1)] for i in data] t = Table(data) t.setStyle(TableStyle([ ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black) ])) self.Story.append(t) # full request timeline / other processing info
def pdfgen(relevant_extracts, sector, keywords): today = datetime.datetime.today() today.replace(second=0, microsecond=0) outputdir = join('..', 'output') if not exists(outputdir): mkdir(outputdir) chdir(outputdir) doc = SimpleDocTemplate('%s_%s.pdf' % (sector, today.strftime("%Y-%m-%d_%H.%M"))) template = PageTemplate('normal', [Frame(2.5*cm, 2.5*cm, 15*cm, 25*cm, id='F1')]) doc.addPageTemplates(template) Story = [Spacer(1,0.5*inch)] styleSheet=getSampleStyleSheet() style = styleSheet['BodyText'] title = Paragraph('<para align=center><b>%s Industry Earnings Call Transcripts Report</b></para>' % sector, style) Story.append(title) subtitle = Paragraph('<para align=center>Keywords: %s</para>' % ", ".join(keywords), style) Story.append(subtitle) Story.append(Spacer(1,0.5*inch)) for extract in relevant_extracts: Story.append(Paragraph("From %s" % extract["title"], h1)) Story.append(Paragraph("Published on %s at %s" % (extract["date"], extract["time"]), h1)) text = Preformatted(extract["bodyContent"].encode('utf8'), style, maxLineLength=100) Story.append(text) Story.append(Spacer(1,0.2*inch)) doc.build(Story)
def main(): context = { 'instructor': INSTRUCTOR, 'course': COURSE, 'student': STUDENT, 'hours': HOURS, } styles = getSampleStyleSheet() styles.add( ParagraphStyle( name='Justify', alignment=TA_JUSTIFY, fontSize=16, leading=22 ) ) elements = [] certificate_txt = render(TEXT_PATH, context) paragraphs = certificate_txt.split(os.linesep) elements.append(Spacer(1, 50)) for p in paragraphs: elements.append(Paragraph(p, styles['Justify'])) elements.append(Spacer(1, 16)) certificate = tempfile.NamedTemporaryFile() doc = SimpleDocTemplate(certificate, topMargin=3 * cm, bottomMargin=0) doc.pagesize = landscape(A4) doc.build(elements) output = PdfFileWriter() template_file = open('template.pdf', 'rb') input1 = PdfFileReader(template_file) page1 = input1.getPage(0) content = PdfFileReader(certificate) page1.mergePage(content.getPage(0)) output.addPage(page1) save_file = open(SAVE_AS, 'wb') output.write(save_file) print('Certificado gerado com sucesso em %s' % SAVE_AS)
def main(): from reportlab.graphics.barcode.code128 import Code128 from reportlab.platypus import Spacer, SimpleDocTemplate from reportlab.lib.units import inch, cm from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus.paragraph import Paragraph from reportlab.platypus.flowables import KeepTogether import os styles = getSampleStyleSheet() styleN = styles['Normal'] styleH = styles['Heading1'] story = [] storyAdd = story.append for s in ( 'BBBB123456BBB', 'BBBB12345BBB', 'BBBB1234BBB', 'BBBB123BBB', 'BBBB12BBB', 'BBBB1BBB', 'BBBB123456aa', 'BBBB1234aa', 'BBBB123aa', 'BBBB12aa', 'BBBB1aa', 'BBBB123456', 'BBBB12345', 'BBBB1234', 'BBBB123', 'BBBB12', 'BBBB1', '\xf11234B', 'Ba\xf11234B', 'Ba12', 'Ba123B', 'Ba1234B', 'BBBB1234567', 'BBBB1234567aa', ): storyAdd(KeepTogether([Paragraph('Code 128 %r' % s, styleN),Code128(s)])) storyAdd(Spacer(inch,inch)) SimpleDocTemplate('code128-out.pdf').build(story)
def generatePdf(transductor_id): import time from reportlab.lib.enums import TA_JUSTIFY from reportlab.lib.pagesizes import letter from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.units import inch doc = SimpleDocTemplate("src/report/static/Relatorio"+transductor_id+".pdf", pagesize=letter, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) Story = [] logo = "src/report/static/currentGraphic"+transductor_id+".png" logo2 = "src/report/static/voltageGraphic"+transductor_id+".png" logo3 = "src/report/static/activePowerGraphic"+transductor_id+".png" logo4 = "src/report/static/reactivePowerGraphic"+transductor_id+".png" logo5 = "src/report/static/apparentPowerGraphic"+transductor_id+".png" magName = "Pythonista" issueNum = 12 subPrice = "99.00" limitedDate = "03/05/2010" freeGift = "tin foil hat" formatted_time = time.ctime() full_name = "SME-UnB" address_parts = ["Campus Universitario UnB", "Brasilia-DF, 70910-900"] im = Image(logo, 8 * inch, 5 * inch) im2 = Image(logo2, 8 * inch, 5 * inch) im3 = Image(logo3, 8 * inch, 5 * inch) im4 = Image(logo4, 8 * inch, 5 * inch) im5 = Image(logo5, 8 * inch, 5 * inch) Story.append(im) Story.append(im2) Story.append(im3) Story.append(im4) Story.append(im5) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) ptext = '<font size=12>%s</font>' % formatted_time Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) ptext = '<font size=12>%s</font>' % full_name Story.append(Paragraph(ptext, styles["Normal"])) for part in address_parts: ptext = '<font size=12>%s</font>' % part.strip() Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) Story.append(Spacer(1, 12)) ptext = '<font size=12>{ % trans Report Energy Monitoring % }</font>' Story.append(Paragraph(ptext, styles["Normal"])) doc.build(Story) return 1
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']))) 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=='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 ! else: sys.stderr.write('Warning: flowable not yet implemented: %s !\n' % (node.localName,)) return None
def test_21_barCharts(self): from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph from reportlab.pdfbase import pdfmetrics from reportlab.graphics.shapes import Drawing from reportlab.pdfbase.ttfonts import TTFont from reportlab.graphics.charts.barcharts import VerticalBarChart pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) stylesheet = getSampleStyleSheet() elements = [] doc = SimpleDocTemplate("demo.pdf") elements.append(Paragraph('<font name="chsFont">JY.zenist.song - ??</font>', stylesheet['Title'])) elements.append(Spacer(1,12)) d = Drawing(400,200) data = [ (13,5,20,22,37,45,19,4), (14,6,21,23,38,46,20,5) ] bc = VerticalBarChart() bc.x = 50 bc.y = 50 bc.height = 125 bc.width = 300 bc.data = data bc.strokeColor = colors.black bc.groupSpacing = 10 bc.barSpacing = 2.5 bc.valueAxis._valueMin = 0 bc.valueAxis._valueMax = 50 bc.valueAxis._valueStep = 10 bc.categoryAxis.categoryNames = ['1','2','3','4','5','6','7','8'] # bc.categoryAxis.style = 'stacked' d.add(bc) elements.append(d) doc.build(elements)