def __init__(self, filename, **kw): BaseDocTemplate.__init__(self, filename, **kw) self.addPageTemplates( [ PageTemplate(id='plain', frames=[Frame(2.5*cm, 2.5*cm, 16*cm, 25*cm, id='F1')] ), LeftPageTemplate(), RightPageTemplate() ] )
def __init__(self, filename, **kw): frame1 = Frame(2.5 * cm, 2.5 * cm, 15 * cm, 25 * cm, id='F1') self.allowSplitting = 0 BaseDocTemplate.__init__(self, filename, **kw) template1 = PageTemplate('normal', [frame1], myMainPageFrame) frame2 = Frame(2.5 * cm, 16 * cm, 15 * cm, 10 * cm, id='F2', showBoundary=1) frame3 = Frame(2.5 * cm, 2.5 * cm, 15 * cm, 10 * cm, id='F3', showBoundary=1) template2 = PageTemplate('updown', [frame2, frame3]) self.addPageTemplates([template1, template2])
def __init__(self, filename, **kw): frame1 = Frame(inch, inch, A4[0] - 2 * inch, A4[1] - 2 * inch, id='F1') self.allowSplitting = 0 BaseDocTemplate.__init__(self, filename, **kw) template = PageTemplate('normal', [frame1], myMainPageFrame) self.addPageTemplates(template) top_margin = A4[1] - inch bottom_margin = inch left_margin = inch right_margin = A4[0] - inch frame_width = right_margin - left_margin
def drawCard(index, item): p.saveState() p.translate(0, height / 3 * (2 - index % 3)) # retrieve record while making sure it's accessible to presentation owner record = Record.filter_one_by_access(presentation.owner, item.record.id) if record: image = get_image_for_record(record, presentation.owner, 800, 800, passwords) if image: p.drawImage(image, inch / 2, inch / 2, width=width / 2 - inch, height=height / 3 - inch, preserveAspectRatio=True) f = Frame(width / 2 + inch / 2, inch / 2, width=width / 2 - inch, height=height / 3 - inch, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0) data = [] data.append( getParagraph('%s/%s' % (index + 1, len(items)), styles['SlideNumber'])) values = item.get_fieldvalues(owner=request.user) for value in values: v = value.value if len( value.value) < 100 else value.value[:100] + '...' data.append( getParagraph( '<b>%s:</b> %s' % (value.resolved_label, v), styles['Data'])) annotation = item.annotation if annotation: data.append( getParagraph( '<b>%s:</b> %s' % ('Annotation', annotation), styles['Data'])) data = filter(None, data) f.addFromList(data, p) if data: p.setFont('Helvetica', 8) p.setFillColorRGB(0, 0, 0) p.drawRightString(width - inch / 2, inch / 2, '...') p.restoreState()
def set_basic_templates(doc): from reportlab.platypus.frames import Frame from reportlab.platypus.doctemplate import PageTemplate from reportlab.lib.units import cm doc._calc() #taken from reportlab source code (magic) templates = [] #the front page framing cover_frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, leftPadding=0, rightPadding=10, topPadding=3 * cm, bottomPadding=5 * cm) templates.append( PageTemplate(id='Cover', frames=cover_frame, onPage=_cover_page, pagesize=doc.pagesize)) #normal frame, for the TOC frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, id='normal', rightPadding=0, leftPadding=0) templates.append( PageTemplate(id='TOC', frames=frame, onPage=toc_page, pagesize=doc.pagesize)) doc.addPageTemplates(templates)
def __init__(self, id=-1, pageSize=TAILLE_PAGE, doc=None): self.pageWidth = pageSize[0] self.pageHeight = pageSize[1] ## # Récupère les coordonnées du cadre principal ## cadre_principal = doc.modeleDoc.FindObjet("cadre_principal") ## x, y, l, h = doc.modeleDoc.GetCoordsObjet(cadre_principal) ## global CADRE_CONTENU ## CADRE_CONTENU = (x, y, l, h) x, y, l, h = 0, 0, self.pageWidth, self.pageHeight frame1 = Frame(x, y, l, h, id='F1', leftPadding=0, topPadding=0, rightPadding=0, bottomPadding=0) PageTemplate.__init__(self, id, [frame1], Template)
def __init__(self, filename, **kw): frame1 = Frame(2.5 * cm, 2.5 * cm, 15 * cm, 25 * cm, id='F1') self.allowSplitting = 0 BaseDocTemplate.__init__(self, filename, **kw) template1 = PageTemplate('normal', [frame1], myMainPageFrame) frame2 = Frame(2.5 * cm, 16 * cm, 15 * cm, 10 * cm, id='F2', showBoundary=1) frame3 = Frame(2.5 * cm, 2.5 * cm, 15 * cm, 10 * cm, id='F3', showBoundary=1) greenBoundary = ShowBoundaryValue(color=toColor('darkgreen'), width=0.5) templateX = PageTemplate('templateX', [ Frame(3 * cm, 7.5 * cm, 14 * cm, 4 * cm, id='XF4', showBoundary=greenBoundary), Frame(3 * cm, 2.5 * cm, 14 * cm, 4 * cm, id='XF5', showBoundary=greenBoundary) ]) template2 = PageTemplate('updown', [frame2, frame3]) self.addPageTemplates([template1, template2, templateX])
def build(self, flowables, onFirstPage=_doNothing, onLaterPages=_doNothing, canvasmaker=Canvas): #Override the build method self._calc() #in case we changed margins sizes etc self.canvas = canvasmaker firstFrame = Frame( 10, # X 0, # Y A4[0] - 20, # width A4[1] - 106, # height id='normal') secondFrame = Frame( 10, # X 0, # Y A4[0] - 20, # width A4[1] - 46, # height #showBoundary=True, id='normal') self.addPageTemplates([ PageTemplate(id='First', frames=[firstFrame], pagesize=self.pagesize, onPage=onFirstPage), PageTemplate(id='Later', frames=[secondFrame], pagesize=self.pagesize, onPage=onLaterPages), ]) if onFirstPage is _doNothing and hasattr(self, 'onFirstPage'): self.pageTemplates[0].beforeDrawPage = self.onFirstPage if onLaterPages is _doNothing and hasattr(self, 'onLaterPages'): self.pageTemplates[1].beforeDrawPage = self.onLaterPages BaseDocTemplate.build(self, flowables, canvasmaker=canvasmaker)
def build(self, flowables): self._calc() #in case we changed margins sizes etc frameT = Frame(self.leftMargin, self.bottomMargin, self.width, self.height, id='normal', leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0) self.addPageTemplates( [PageTemplate(id='First', frames=frameT, pagesize=self.pagesize)]) BaseDocTemplate.build(self, flowables, canvasmaker=self._canvasMaker)
def multiBuild(self, story, filename=None, canvasMaker=Canvas, maxPasses=10, onFirstPage=_doNothing, onLaterPages=_doNothing): self._calc() #in case we changed margins sizes etc frameT = Frame(self.leftMargin, self.bottomMargin, self.width, self.height, id='normal') self.addPageTemplates([ PageTemplate(id='Later', frames=frameT, onPageEnd=onLaterPages, pagesize=self.pagesize) ]) if onLaterPages is _doNothing and hasattr(self, 'onLaterPages'): self.pageTemplates[0].beforeDrawPage = self.onLaterPages SimpleDocTemplate.multiBuild(self, story, maxPasses, canvasmaker=canvasMaker) self._prepareTOC() contentFile = self.filename self.filename = FileDummy() self.pageTemplates = [] self.addPageTemplates([ PageTemplate(id='First', frames=frameT, onPage=onFirstPage, pagesize=self.pagesize) ]) if onFirstPage is _doNothing and hasattr(self, 'onFirstPage'): self.pageTemplates[0].beforeDrawPage = self.onFirstPage self.addPageTemplates([ PageTemplate(id='Later', frames=frameT, onPageEnd=self.laterPages, pagesize=self.pagesize) ]) if onLaterPages is _doNothing and hasattr(self, 'onLaterPages'): self.pageTemplates[1].beforeDrawPage = self.onLaterPages SimpleDocTemplate.multiBuild(self, self._tocStory, maxPasses, canvasmaker=canvasMaker) self.mergePDFs(self.filename, contentFile)
def createFrame(self, frame_id="Portrait", x1=0., y1=0., width=0., height=0., left_padding=0., bottom_padding=0., right_padding=0., top_padding=0., overlap=None): """ Frame reportlab internal signature:: width x2,y2 +---------------------------------+ | l top_padding r | h | e +-------------------------+ i | e | f | | g | i | t | | h | g | | | t | h | p | | | t | a | | p | | d | | a | | | | d | | +-------------------------+ | | bottom padding | +---------------------------------+ (x1,y1) <-- lower left corner """ def makeRandomId(length=3, chars=string.ascii_lowercase): """ create a file id of lower case ascii characters with length """ return ''.join(random.choice(chars) for _ in range(length)) return Frame(x1, y1, width, height, leftPadding=left_padding, bottomPadding=bottom_padding, rightPadding=right_padding, topPadding=top_padding, id=f"{frame_id}_{makeRandomId()}", showBoundary=self.showBoundary, overlapAttachedSpace=overlap, _debug=None)
def __init__(self, filename, **kw): BaseDocTemplate.__init__(self, filename, **kw) template = PageTemplate('normal', [ Frame(0, 0, A4[0], A4[1], leftPadding=31.8 * mm, bottomPadding=25.4 * mm, rightPadding=31.8 * mm, topPadding=25.4 * mm) ], onPageEnd=self.footer) # 定义页面模版,页脚可有可无 self.addPageTemplates(template) # 加入页面模版
def __init__(self, filename, **kw): self.allowSplitting = 0 BaseDocTemplate.__init__(self, filename, **kw) frameT = Frame(self.leftMargin, self.bottomMargin, self.width, self.height, id='F1') template_title_page = PageTemplate('title_page', frames=frameT, onPage=title_page) template_later_pages = PageTemplate('later_pages', frames=frameT, onPage=later_pages) self.addPageTemplates(template_title_page) self.addPageTemplates(template_later_pages)
def test6(self): """test of single/multi-frag text and shrinkSpace calculation""" pagesize = (200 + 20, 400) canv = Canvas(outputfile('test_platypus_breaking_lelegaifax.pdf'), pagesize=pagesize) f = Frame(10, 0, 200, 400, showBoundary=ShowBoundaryValue(dashArray=(1, 1)), leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0) style = ParagraphStyle( 'normal', fontName='Helvetica', fontSize=11.333628, spaceBefore=20, hyphenationLang='en-US', alignment=TA_JUSTIFY, spaceShrinkage=0.05, ) text1 = """My recent use case was the preparation""" text2 = """<span color='red'>My </span> recent use case was the preparation""" ix0 = len(canv._code) f.addFromList([ Paragraph(text1, style), Paragraph(text2, style), ], canv) self.assertEqual( canv._code[ix0:], [ 'q', '0 0 0 RG', '.1 w', '[1 1] 0 d', 'n 10 0 200 400 re S', 'Q', 'q', '1 0 0 1 10 388 cm', 'q', '0 0 0 rg', 'BT 1 0 0 1 0 .666372 Tm /F1 11.33363 Tf 12 TL -0.157537 Tw' ' (My recent use case was the preparation) Tj T* 0 Tw ET', 'Q', 'Q', 'q', '1 0 0 1 10 356 cm', 'q', 'BT 1 0 0 1 0 .666372 Tm -0.157537 Tw 12 TL /F1 11.33363 Tf 1 0 0 rg' ' (My ) Tj 0 0 0 rg (recent use case was the preparation) Tj T* 0 Tw ET', 'Q', 'Q' ], 'Lele Gaifax bug example did not produce the right code', ) canv.showPage() canv.save()
def __init__(self, cover=None, id=None, onPage=_doNothing, onPageEnd=_doNothing, pagesize=(page_width, page_height)): id = 'TitlePage' frames = Frame(page_margin_left, page_margin_bottom, print_width, print_height) PageTemplate.__init__(self, id=id, frames=frames, onPage=onPage, onPageEnd=onPageEnd, pagesize=pagesize) self.cover = cover
def prepare_first_page(canvas, document): p1 = Paragraph(presentation.title, styles['Heading']) p2 = Paragraph(presentation.owner.get_full_name(), styles['SubHeading']) avail_width = width - inch avail_height = height - inch w1, h1 = p1.wrap(avail_width, avail_height) w2, h2 = p2.wrap(avail_width, avail_height) f = Frame(inch / 2, inch / 2, width - inch, height - inch, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0) f.addFromList([p1, p2], canvas) document.pageTemplate.frames[0].height -= h1 + h2 + inch / 2 document.pageTemplate.frames[1].height -= h1 + h2 + inch / 2 canvas.saveState() canvas.setStrokeColorRGB(0, 0, 0) canvas.line(width / 2, inch / 2, width / 2, height - inch - h1 - h2) canvas.restoreState()
def test5(self): '''extreme test inspired by Moritz Pfeiffer https://bitbucket.org/moritzpfeiffer/''' with self.assertRaises(LayoutError): text = """ Clearly, the natural general principle that will subsume this case is not subject to a parasitic gap construction. Presumably, most of the methodological work in modern linguistics can be defined in such a way as to impose the system of base rules exclusive of the lexicon. In the discussion of resumptive pronouns following (81), the fundamental error of regarding functional notions as categorial is to be regarded as a descriptive <span color="red">fact</span>.<br/>So far, the earlier discussion of deviance is not quite equivalent to a parasitic gap construction. To characterize a linguistic level L, a case of semigrammaticalness of a different sort may remedy and, at the same time, eliminate irrelevant intervening contexts in selectional <span color="red">rules</span>.<br/> Summarizing, then, we assume that the descriptive power of the base component can be defined in such a way as to impose nondistinctness in the sense of distinctive feature theory. """ styleSheet = getSampleStyleSheet() story = [] story.append(Paragraph(text, styleSheet['Normal'])) doc = BaseDocTemplate( outputfile('test_platypus_much_too_large.pdf'), pagesize=portrait(A4), pageTemplates=[ PageTemplate( 'page_template', [ Frame(0, 0, 0, 0, leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0, id='DUMMY_FRAME') ], ) ], ) doc.build(story)
def draw(self): # set position for the frame self.pos_x, self.pos_y = self._get_current_position(self.canv) # XXX This is false, height=drawHeigh and drawHeight should take into # account the frame padding height = (self.drawHeight + self.frame_attrs['leftPadding'] + self.frame_attrs['rightPadding']) width = (self.drawWidth + self.frame_attrs['topPadding'] + self.frame_attrs['bottomPadding']) self.frame = Frame(self.pos_x, self.pos_y, width, height, **self.frame_attrs) if self.overflow: # Hack, We lie by setting the new created frame as default frame # of the doc template # To avoid problems when calling keep_in_frame.wrap # See platypus.flowables "def _listWrapOn" _doctemplate = self.canv._doctemplate # save state current_frame = getattr(_doctemplate, 'frame', None) _doctemplate.frame = self.frame # Check if PTO is defined if self.pto_trailer or self.pto_header: ptocontainer = PTOContainer(self.div_story[:], self.pto_trailer, self.pto_header) ptocontainer.canv = self.canv pto_size = ptocontainer.wrap(self.drawWidth, self.drawHeight) # XXX Round the height to avoid problems with decimal if int(pto_size[1]) > int(self.drawHeight): pto_story = ptocontainer.split(self.drawWidth, self.drawHeight) self.frame.addFromList(pto_story, self.canv) else: self.frame.addFromList([self.keep_in_frame], self.canv) else: self.frame.addFromList([self.keep_in_frame], self.canv) # restore state if current_frame: _doctemplate.frame = current_frame else: self.frame.addFromList(self.div_story[:], self.canv)
def __init__(self, filename, **kw): self.allowSplitting = 0 BaseDocTemplate.__init__(self, filename, **kw) self.addPageTemplates([ PageTemplate( 'normal', [ Frame(inch, inch, 6.27 * inch, 9.69 * inch, id='first', topPadding=0, rightPadding=0, leftPadding=0, bottomPadding=0, showBoundary=ShowBoundaryValue(color="red")) ], ), ])
def __init__(self, filename, cfgparser, **kw): self.allowSplitting = 0 # Inch graph size (width, height) self.graph_size = (float(cfgparser.get("page", "graph_width")), float(cfgparser.get("page", "graph_height"))) self.x_axis = ('Time', 12, '%m-%d %H:%M', 20) self.tablestyle = [ ('ROWBACKGROUNDS', (0, 0), (-1, -1), (colors.lightgrey, colors.white)), ('GRID', (0, 0), (-1, -1), 1, colors.toColor(cfgparser.get("string_table", "color"))), ('ALIGN', (0, 0), (-1, -1), cfgparser.get("string_table", "align")), ('LEFTPADDING', (0, 0), (-1, -1), int(cfgparser.get("string_table", "leftPadding"))), ('RIGHTPADDING', (0, 0), (-1, -1), int(cfgparser.get("string_table", "rightPadding"))), ('FONTSIZE', (0, 0), (-1, -1), int(cfgparser.get("string_table", "fontSize"))), ('FONTNAME', (0, 0), (-1, 0), cfgparser.get("string_table", "font")), ] BaseDocTemplate.__init__(self, filename, **kw) template = PageTemplate('normal', [Frame( float(cfgparser.get("page", "x1")) * inch, float(cfgparser.get("page", "y1")) * inch, float(cfgparser.get("page", "width")) * inch, float(cfgparser.get("page", "height")) * inch, id='F1')]) self.addPageTemplates(template) font_list = ["centered", "centered_index", "small_centered", "heading1", "heading1_centered", "heading1_invisible", "heading2", "heading2_centered", "heading2_invisible", "mono", "mono_centered", "normal", "front_title", "axes"] int_fields = ["fontSize", "leading", "alignment", "spaceAfter"] self.fonts = {} for font in font_list: sheet = getSampleStyleSheet() text = sheet['BodyText'] section = "font_%s" % font items = dict(cfgparser.items(section)) for i in int_fields: if i in items: items[i] = int(items[i]) tmp_ps = PS(font, parent=text) tmp_ps.__dict__.update(items) self.fonts[font] = tmp_ps
def __init__(self, cover=None, id=None, onPage=_doNothing, onPageEnd=_doNothing, pagesize=(page_width, page_height)): id = 'TitlePage' p = pdfstyles frames = Frame( p.title_margin_left, p.title_margin_bottom, p.page_width - p.title_margin_left - p.title_margin_right, p.page_height - p.title_margin_top - p.title_margin_bottom) PageTemplate.__init__(self, id=id, frames=frames, onPage=onPage, onPageEnd=onPageEnd, pagesize=pagesize) self.cover = cover
def myFirstPage(canvas, doc): canvas.saveState() canvas.setFont('Times-Bold', 16) canvas.drawCentredString(PAGE_WIDTH / 2.0, PAGE_HEIGHT - 108, title) canvas.setFont('Times-Roman', 9) canvas.drawString(inch, 0.75 * inch, "Page %d - %s" % (doc.page, title)) frame_width = PAGE_WIDTH - 200 hr = HRFlowable() space = Spacer(frame_width, 20) style = styles["Normal"] qr_info = """<para rightIndent=10 leftIndent=20 alignment=right>This document is signed with the QR code shown on the right. Validate it using a Barcode Scanner.""" par = Paragraph(qr_info, style) im = Image("qrcode.png", 101, 101) pandi = ParagraphAndImage(par, im, xpad=3, ypad=30, side='right') frame = Frame(100, 0, frame_width, 200, showBoundary=1) frame.add(hr, canvas) frame.add(space, canvas) frame.add(pandi, canvas) canvas.restoreState()
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 drawHeader(self): self.drawLogo() styles = getSampleStyleSheet() sN = styles['Normal'] sH = styles['Heading1'] sH.fontName = "OldEngMT" sH.textColor = red sH.leading = 18 sH.fontSize = 16 sN.fontSize = 9 sN.leading = 10 sN.alignment = sH.alignment = TA_CENTER sN.spaceBefore = sH.spaceBefore = 0 sN.spaceAfter = sH.spaceAfter = 0 story = [] story.append(Paragraph("Holy Child Colleges of Butuan - Hospital", sH)) story.append(Paragraph("<b>(JP Esteves Clinical Laboratory)</b>", sN)) story.append( Paragraph("2nd St., Guingona Subd., " + "Butuan City, Philippines", sN)) story.append(Paragraph("Tel. No.: +63 (85) 342-5186", sN)) story.append(Paragraph("Telefax No.: +63 (95) 342-397/225-6872", sN)) story.append(Paragraph("email: [email protected]", sN)) w, h = self.pagesize f = Frame(0, h - self.topMargin, w, self.topMargin, showBoundary=False) f.addFromList(story, self.canv) self.canv.setStrokeColor(red) self.canv.setLineWidth(3) self.canv.line( 0.15 * cm, h - self.topMargin, w - 0.15 * cm, h - self.topMargin, )
def __init__(self, filename, context, **kw): BaseDocTemplate.__init__(self, filename, **kw) self.toc_index = 0 self.main_frame_attr = { 'x1': self.leftMargin, 'y1': self.bottomMargin, 'width': self.width, 'height': self.height, 'id': 'normal', 'showBoundary': self.showBoundary } # We keep the main frame reference to resize it during the build self.main_frame = Frame(**self.main_frame_attr) self.main_frame_change = False template_attrs = { 'id': 'now', 'frames': [self.main_frame], 'pagesize': kw['pagesize'] } page_template = PageTemplate(**template_attrs) self.platypus_header_calculate = False self.platypus_header_height = None self.platypus_footer = None self.context = context self.addPageTemplates([page_template]) self.toc_high_level = self.context.toc_high_level self.frame_attr = { 'leftPadding': 0, 'bottomPadding': 6, 'rightPadding': 0, 'topPadding': 6, 'showBoundary': 0 } self.context = context # calculate width available self.width_available = self.width self.width_available -= self.frame_attr['leftPadding'] self.width_available -= self.frame_attr['rightPadding']
def build(self,flowables,onFirstPage=_doNothing, onLaterPages=_doNothing, canvasmaker=canvas.Canvas): """build the document using the flowables. Annotate the first page using the onFirstPage function and later pages using the onLaterPages function. The onXXX pages should follow the signature def myOnFirstPage(canvas, document): # do annotations and modify the document ... The functions can do things like draw logos, page numbers, footers, etcetera. They can use external variables to vary the look (for example providing page numbering or section names). """ self._calc() #in case we changed margins sizes etc frameT = Frame(self.leftMargin, self.bottomMargin, self.width, self.height, id='normal') self.addPageTemplates([PageTemplate(id='First',frames=frameT, onPage=onFirstPage,pagesize=self.pagesize), PageTemplate(id='Later',frames=frameT, onPage=onLaterPages,pagesize=self.pagesize)]) if onFirstPage is _doNothing and hasattr(self,'onFirstPage'): self.pageTemplates[0].beforeDrawPage = self.onFirstPage if onLaterPages is _doNothing and hasattr(self,'onLaterPages'): self.pageTemplates[1].beforeDrawPage = self.onLaterPages BaseDocTemplate.build(self,flowables, canvasmaker=canvasmaker)
def CreateFrame(self, pageTemplate, element): ident = element.get("id", "default") x1 = self._ConvertNumber(element, "x1", 0) y1 = self._ConvertNumber(element, "y1", 0) defaultWidth, defaultHeight = self.document.pagesize width = self._ConvertNumber(element, "width", defaultWidth) height = self._ConvertNumber(element, "height", defaultHeight) leftPadding = self._ConvertNumber(element, "leftPadding", 0) rightPadding = self._ConvertNumber(element, "rightPadding", 0) topPadding = self._ConvertNumber(element, "topPadding", 0) bottomPadding = self._ConvertNumber(element, "bottomPadding", 0) showBoundary = self._ConvertNumber(element, "showBoundary", 0) frame = Frame(x1, y1, width, height, leftPadding=leftPadding, rightPadding=rightPadding, topPadding=topPadding, bottomPadding=bottomPadding, showBoundary=showBoundary) pageTemplate.frames.append(frame)
def init_doc(self, title): def proposal_footer(canvas, doc): canvas.saveState() canvas.setFont('Helvetica', 10) PAGE_WIDTH = defaultPageSize[0] footer_text = "%s %s - %s, %s %s" % (self.user.first_name, self.user.last_name, self.user.get_profile().address.street.replace("\n", ", ").replace("\r", ""), self.user.get_profile().address.zipcode, self.user.get_profile().address.city) if self.user.get_profile().address.country: footer_text = footer_text + u", %s" % (self.user.get_profile().address.country) canvas.drawCentredString(PAGE_WIDTH / 2.0, 0.5 * inch, footer_text) extra_info = u"SIRET : %s" % (self.user.get_profile().company_id) if self.user.get_profile().vat_number: extra_info = u"%s - N° TVA : %s" % (extra_info, self.user.get_profile().vat_number) canvas.drawCentredString(PAGE_WIDTH / 2.0, 0.35 * inch, extra_info) canvas.restoreState() self.doc = BaseDocTemplate(self.response, title=title, leftMargin=0.5 * inch, rightMargin=0.5 * inch) frameT = Frame(self.doc.leftMargin, self.doc.bottomMargin, self.doc.width, self.doc.height + 0.5 * inch, id='normal') self.doc.addPageTemplates([PageTemplate(id='all', frames=frameT, onPage=proposal_footer), ])
def __init__(self, filename, **kw): frame1 = Frame(2.5 * cm, 2.5 * cm, 15 * cm, 25 * cm, id='F1') self.allowSplitting = 0 BaseDocTemplate.__init__(self, filename, **kw) template = PageTemplate('normal', [frame1], myMainPageFrame) self.addPageTemplates(template)
def atPage(self, name, pseudopage, declarations): c = self.c data = {} name = name or "body" pageBorder = None if declarations: result = self.ruleset([self.selector('*')], declarations) if declarations: data = result[0].values()[0] pageBorder = data.get("-pdf-frame-border", None) if name in c.templateList: log.warn( self.c.warning("template '%s' has already been defined", name)) if "-pdf-page-size" in data: c.pageSize = xhtml2pdf.default.PML_PAGESIZES.get( str(data["-pdf-page-size"]).lower(), c.pageSize) isLandscape = False if "size" in data: size = data["size"] if type(size) is not types.ListType: size = [size] sizeList = [] for value in size: valueStr = str(value).lower() if type(value) is types.TupleType: sizeList.append(getSize(value)) elif valueStr == "landscape": isLandscape = True elif valueStr in xhtml2pdf.default.PML_PAGESIZES: c.pageSize = xhtml2pdf.default.PML_PAGESIZES[valueStr] else: log.warn(c.warning("Unknown size value for @page")) if len(sizeList) == 2: c.pageSize = tuple(sizeList) if isLandscape: c.pageSize = landscape(c.pageSize) for prop in ("margin-top", "margin-left", "margin-right", "margin-bottom", "top", "left", "right", "bottom", "width", "height"): if prop in data: c.frameList.append( self._pisaAddFrame(name, data, first=True, border=pageBorder, size=c.pageSize)) break # Frames have to be calculated after we know the pagesize frameList = [] staticList = [] for fname, static, border, x, y, w, h, fdata in c.frameList: #fix frame sizing problem. if static: x, y, w, h = getFrameDimensions(fdata, c.pageSize[0], c.pageSize[1]) x, y, w, h = getCoords(x, y, w, h, c.pageSize) if w <= 0 or h <= 0: log.warn( self.c.warning( "Negative width or height of frame. Check @frame definitions." )) frame = Frame(x, y, w, h, id=fname, leftPadding=0, rightPadding=0, bottomPadding=0, topPadding=0, showBoundary=border or pageBorder) if static: frame.pisaStaticStory = [] c.frameStatic[static] = [frame] + c.frameStatic.get(static, []) staticList.append(frame) else: frameList.append(frame) background = data.get("background-image", None) if background: #should be relative to the css file background = self.c.getFile(background, relative=self.c.cssParser.rootPath) if not frameList: log.warn( c.warning( "missing explicit frame definition for content or just static frames" )) fname, static, border, x, y, w, h, data = self._pisaAddFrame( name, data, first=True, border=pageBorder, size=c.pageSize) x, y, w, h = getCoords(x, y, w, h, c.pageSize) if w <= 0 or h <= 0: log.warn( c.warning( "Negative width or height of frame. Check @page definitions." )) frameList.append( Frame(x, y, w, h, id=fname, leftPadding=0, rightPadding=0, bottomPadding=0, topPadding=0, showBoundary=border or pageBorder)) pt = PmlPageTemplate( id=name, frames=frameList, pagesize=c.pageSize, ) pt.pisaStaticList = staticList pt.pisaBackground = background pt.pisaBackgroundList = c.pisaBackgroundList if isLandscape: pt.pageorientation = pt.LANDSCAPE c.templateList[name] = pt c.template = None c.frameList = [] c.frameStaticList = [] return {}, {}