def __init__(self, output, fname, **kw): self.allowSplitting = 0 filename = fname BaseDocTemplate.__init__(self, filename, **kw) padding = dict(leftPadding=px(5), bottomPadding=px(5), rightPadding=px(5), topPadding=px(5)) template2 = PageTemplate('normal', [ Frame(0, 0, px(100), py(100), **padding, id='F1'), Frame(px(95), py(95), px(5), py(5), id='F3') ], onPage=self.add_page_number, onPageEnd=self.add_page_number) template1 = PageTemplate( 'cover', [Frame(0, 0, px(100), py(100), **padding, id='F2')], onPage=self.add_author, onPageEnd=self.add_author, autoNextPageTemplate=1) self.addPageTemplates([template1, template2]) self.stories = [] self.PB = PageBuilder(stories=self.stories) self.output = output self.header = None self.cover() self.section() self.build(self.stories)
def create_pdf(togen, template_page, pos, dat): "Create the pdf, stream api" document = BaseDocTemplate(togen) page = MyPage(template_page, name='background') document.addPageTemplates([page]) elements = [NextPageTemplate('background')] # may add flowables to element here # add absolute content for posname in dat: if posname.startswith("_"): # ignore extra info continue if posname not in pos: raise Exception("%s does not have a position" % posname) tup = pos[posname] x, y = tup[0], tup[1] width = tup[2] if len(tup)>2 else PAGE_WIDTH style = tup[3] if len(tup)>3 else DEFAULT_STYLE data = dat[posname] if type(data) in (str, unicode): page.addAbsParagraph(data, x, y, width, style) else: page.addAbsPrimitive(data, x, y, width) # don't need no style # create page document.multiBuild(elements)
def init(self, nomFichierSortie, identifiant): #self.styles = getSampleStyleSheet() self.tousLesStyles() self.identifiant = identifiant self.numeroPage = 0 self.doc = BaseDocTemplate(nomFichierSortie, pagesize=A4) framePremiehrePage = Frame(M_G, M_B, A4[0] - M_G - M_D, A4[1] - M_H - M_B - 3 * cm, id='framePremiehrePage') templatePremiehrePage = PageTemplate(id='PremiehrePage', frames=framePremiehrePage, onPage=self.enTestePremiehrePage) framePageSuivante = Frame(M_G, M_B, A4[0] - M_G - M_D, A4[1] - M_H - M_B - 1 * cm, id='framePageSuivante') templatePageSuivante = PageTemplate(id='pageSuivante', frames=framePageSuivante, onPage=self.enTestePageSuivante) self.doc.addPageTemplates( [templatePremiehrePage, templatePageSuivante]) self.flowables = [] self.grilles = [] self.titreGrille = [] self.tour = [] self.insejcable = [] #ejcrit le baratin du dejpart commun ah toutes les rejsolutions self.ejcritExplications()
def _create_bulk_licence_renewal(licences, site_url, buf=None): bulk_licence_renewal_frame = Frame(LETTER_PAGE_MARGIN, LETTER_PAGE_MARGIN, PAGE_WIDTH - 2 * LETTER_PAGE_MARGIN, PAGE_HEIGHT - 160, id='BulkLicenceRenewalFrame') bulk_licence_renewal_template = PageTemplate( id='BulkLicenceRenewalFrame', frames=[bulk_licence_renewal_frame], onPage=_create_letter_header_footer) if buf is None: buf = BytesIO() doc = BaseDocTemplate(buf, pageTemplates=[bulk_licence_renewal_template], pagesize=A4) # this is the only way to get data into the onPage callback function doc.site_url = site_url all_elements = [] for licence in licences: all_elements += _create_letter_address(licence) + [Spacer(1, LETTER_ADDRESS_BUFFER_HEIGHT)] + \ _create_licence_renewal_elements(licence) + _create_letter_signature() all_elements.append(PageBreak()) doc.build(all_elements) return doc
def setupDoc(self): self.doc = BaseDocTemplate(self.filename, pagesize=self.param.pageSize, leftMargin=15 * mm, bottomMargin=10 * mm, rightMargin=20 * mm, topMargin=10 * mm) firstFrame = Frame(self.doc.leftMargin, self.doc.bottomMargin, self.param.firstFrameWidth, self.param.firstFrameHeight, id='first', showBoundary=debug) laterFrame = Frame(self.doc.leftMargin, self.doc.bottomMargin, self.doc.width, self.doc.height, id='later') def changeTemplate(canvas, document): document.handle_nextPageTemplate('Later') def writeHead(canvas, document): self.writeHead(canvas) self.doc.addPageTemplates((PageTemplate(id='First', frames=firstFrame, onPage=writeHead, onPageEnd=changeTemplate), PageTemplate(id='Later', frames=laterFrame)))
def __init__(self, filename, **kw): frame1 = Frame(2.5*cm, 2.5*cm, 16*cm, 25*cm, id='Frame1') self.allowSplitting = 0 self.showBoundary = 1 BaseDocTemplate.__init__(self, filename, **kw) template = PageTemplate('normal', [frame1], myMainPageFrame) self.addPageTemplates(template)
def __init__(self, filename, **kwargs): self._doc = BaseDocTemplate(filename=filename, **kwargs) self._templates = [] self._frames = {} self._flowables = [] self._header = None self._footer = None
def create_pdf(data): report_header='./static/images/report-header.jpg' other_header='./static/images/report-header2.jpg' today=data[0] pname=data[1] orgname=data[2] mission=data[3] product=data[4] puser=data[5] inputs=data[6] outputs=data[7] controls=data[8] plots=data[9] regs=data[10] reporttext = [] #File Name pdfname="hello"+pname+"_"+today doc=BaseDocTemplate(pdfname,pagesize=letter) frame=Frame(doc.leftMargin,doc.bottomMargin,doc.width,doc.height,id='normal') template=PageTemplate(id='test',frames=frame,onPage=footer) doc.addPageTemplates([template]) styles = getSampleStyleSheet() methods="In keeping with the ReadyMade tenet to keep the analysis simple, we look for one key outcome variable that is highly correlated with the other available outcome variables " reporttext.append(Paragraph(methods,styles['Normal'])) doc.build(metext) return pdfname
def __init__(self, filename, **kw): m = 2 * cm cw, ch = (PAGESIZE[0] - 2 * m) / 2., (PAGESIZE[1] - 2 * m) f1 = Frame(m, m + 0.5 * cm, cw + 1.5 * cm, ch - 1 * cm, id='F1', leftPadding=0, topPadding=0, rightPadding=0, bottomPadding=0, showBoundary=True) f2 = Frame(cw + 4 * cm, m + 0.5 * cm, cw - 2.0 * cm, ch - 1 * cm, id='F2', leftPadding=0, topPadding=0, rightPadding=0, bottomPadding=0, showBoundary=True) BaseDocTemplate.__init__(self, filename, **kw) template = PageTemplate('template', [f1, f2]) self.addPageTemplates(template)
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, printfile, style=1): template = SimpleDocTemplate(printfile, showBoundary=0) tFirst = PageTemplate(id='First', frames=self.getStyle(1, style), onPage=self.myPages, pagesize=defaultPageSize) tNext = PageTemplate(id='Later', frames=self.getStyle(2, style), onPage=self.myPages, pagesize=defaultPageSize) template.addPageTemplates([tFirst, tNext]) template.allowSplitting = 1 BaseDocTemplate.build(template, self.data)
def __init__(self, path): self.path = path styles = getSampleStyleSheet() styles2 = getSampleStyleSheet() self._styleN = styles["Normal"] self._styleH1 = styles["Heading1"] self._styleH2 = styles["Heading2"] self._styleRightAlignment = styles2[ "Normal"] # to make sure we don't overwrite the normal styles (IS HACK) self._styleRightAlignment.alignment = 2 self._header = "" self._footer = "" self._pagenr = 0 self.doc = BaseDocTemplate(self.path, pagesize=A4) self.doc.leftMargin = 1 * cm self.doc.rightMargin = 1 * cm self.doc.bottomMargin = 1.5 * cm self.doc.topMargin = 1.5 * cm frame = Frame(self.doc.leftMargin, self.doc.bottomMargin, self.doc.width, self.doc.height - 2 * cm, id="normal") template = PageTemplate(id="legal_doc", frames=frame, onPage=self._header_footer) self.doc.addPageTemplates([template]) self.parts = []
def __init__(self, filename, **kw): frame1 = Frame(2.5 * cm, 2.5 * cm, 16 * cm, 25 * cm, id='Frame1') self.allowSplitting = 0 self.showBoundary = 1 BaseDocTemplate.__init__(self, filename, **kw) template = PageTemplate('normal', [frame1], myMainPageFrame) self.addPageTemplates(template)
def handle_flowable(self, flowables): f = flowables[0] BaseDocTemplate.handle_flowable(self, flowables) if hasattr(f, "link_object"): (obj, text) = f.link_object if type(obj).__name__ == "Club": if obj.departement != self.club_seen: key = "Departement{}".format(obj.departement) self.canv.bookmarkPage(key) self.canv.addOutlineEntry("Département {}".format(obj.departement), key, level=0, closed=1) self.club_seen = obj.departement level = 1 elif type(obj).__name__ == "Competition": if not self.competition_seen: key = "Competition" self.canv.bookmarkPage(key) self.canv.addOutlineEntry("Détail des compétitions", key, level=0, closed=1) self.competition_seen = True level = 1 else: level = 2 key = obj.link() self.canv.bookmarkPage(key) self.canv.addOutlineEntry(text, key, level=level, closed=1)
def _create_application(application_buffer, application): every_page_frame = Frame(PAGE_MARGIN, PAGE_MARGIN, PAGE_WIDTH - 2 * PAGE_MARGIN, PAGE_HEIGHT - 2 * PAGE_MARGIN, id='EveryPagesFrame') every_page_template = PageTemplate(id='EveryPages', frames=[every_page_frame]) doc = BaseDocTemplate(application_buffer, pageTemplates=[every_page_template], pagesize=A4) elements = [] elements.append(Paragraph(application.licence_type.name.encode('UTF-8'), styles['ApplicationTitle'])) # cannot use licence get_title_with_variants because licence isn't saved yet so can't get variants if application.variants.exists(): variants = '({})'.format(' / '.join(application.variants.all().values_list('name', flat=True))) elements.append(Paragraph(variants, styles['ApplicationVariantsTitle'])) elements.append(Spacer(1, SECTION_BUFFER_HEIGHT)) elements.append(_create_application_metadata(application)) elements.append(Spacer(1, SECTION_BUFFER_HEIGHT)) for field, datum in zip(application.licence_type.application_schema, application.data): _create_application_questionaire(field, datum, elements, 0) doc.build(elements) return application_buffer
def makeForm(): ''' Make PDF of MyPidge app form. ''' posts = [] pageWidth, pageHeight = A4 formPages = ( FormFront(None), FormFront(None), FormFront(None), FormFront(None), FormBack(None), FormBack(None), FormBack(None), FormBack(None), ) for (offset, frame) in enumerate(formPages): posts.append(frame.makeFrame()) if len(formPages)==(offset+1): # Break page at end of a PocketPidge # But need to do this twice if on an odd page posts.append(PageBreak()) else: posts.append(FrameBreak()) # Build File document = BaseDocTemplate("form.pdf", pagesize=A4) template = PageTemplate(frames=createFrames(pageWidth, pageHeight, 2, 2)) document.addPageTemplates(template) document.build(posts)
def build(self, flowables, 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 '''Header Region''' w, h = self.width, self.headerHeight x, y = self.leftMargin, self.pagesize[1] - self.topMargin - h frameHeader = Frame(x, y, w, h, id='Header') '''Content Region''' w, h = self.width - self.leftWidth, self.height - self.headerHeight - self.footerHeight - self.signatureHeight x, y = self.leftMargin + self.leftWidth, self.pagesize[ 1] - self.topMargin - self.headerHeight - h frameContent = Frame(x, y, w, h, id='Content') '''Signature Region''' w, h = w, self.signatureHeight x, y = x, y - h frameSignature = Frame(x, y, w, h, id='Signature') self.addPageTemplates([ PageTemplate(id='Normal', frames=(frameHeader, frameContent, frameSignature), onPageEnd=self.afterNormalPage) ]) BaseDocTemplate.build(self, flowables, canvasmaker=canvasmaker)
def build_pdf(filename): doc = BaseDocTemplate(filename) column_gap = 1 * cm doc.addPageTemplates( [ PageTemplate( frames=[ Frame( doc.leftMargin, doc.bottomMargin, doc.width / 2, doc.height, id='left', rightPadding=column_gap / 2, showBoundary=0 # set to 1 for debugging ), Frame( doc.leftMargin + doc.width / 2, doc.bottomMargin, doc.width / 2, doc.height, id='right', leftPadding=column_gap / 2, showBoundary=0 ), ] ), ] ) flowables = [ Paragraph('word ' * 700, ParagraphStyle('default')), ] doc.build(flowables)
def __init__(self,title, author, filename=None, size=(4,6), sb=0): (height,width,) = size if not filename: self.filename="%s-%sx%s.pdf" % (title,str(height),str(width)) else: self.filename=filename pagesize = (width*inch,height*inch) F=Frame(0,0,width*inch,height*inch, leftPadding=0.5*inch, bottomPadding=0.50*inch, rightPadding=0.25*inch, topPadding=0.25*inch, showBoundary=sb) PT = PageTemplate(id="Notecard", frames=[F,]) BaseDocTemplate.__init__(self, self.filename, pageTemplates=[PT,], pagesize=pagesize, showBoundary=sb, leftMargin=0, rightMargin=0, topMargin=0, bottomMargin=0, allowSplitting=1, title=title, author=author)
def build_PDF(self): #CREAMOS EL DOCTEMPLATE, a partir del BaseDocTemplate self.obtiene_fecha() directorio = '/home/pi/Desktop/Reportes_Generados/{}'.format( self.now.year) if not os.path.isdir(directorio): directorio += '/{}'.format(self.month) commands.getoutput( 'mkdir /home/pi/Desktop/Reportes_Generados/{}'.format( self.now.year)) if not os.path.isdir(directorio): commands.getoutput( 'mkdir /home/pi/Desktop/Reportes_Generados/{}/{}'.format( self.now.year, self.month)) print 'Directorio creado con éxito' else: directorio += '/{}'.format(self.month) if not os.path.isdir(directorio): commands.getoutput( 'mkdir /home/pi/Desktop/Reportes_Generados/{}/{}'.format( self.now.year, self.month)) print 'Directorio creado con éxito' #=============================== self.direc = '/home/pi/Desktop/Reportes_Generados/{}/{}/BCT_reporte_{}_{}.pdf'.format( self.now.year, self.month, self.fechaC, self.tiempoC) doc = BaseDocTemplate( self.direc, pageTemplates=[self.PTUnaColumna], #pageTemplates=[self.PTUnaColumna, self.PTDosColumnas], pagesize=letter) #Construimos el PDF ) self.page_init.append(self.t) self.page_init.append(self.story) doc.build(self.story)
class ReporteVertical(object): """docstring for ReporteVertical""" def __init__(self, nombreReporteP, directorioArchivoP, operadorP): super(ReporteVertical, self).__init__() self.PAGE_HEIGHT = letter[1] self.PAGE_WIDTH = letter[0] self.story = [] self.styles = getSampleStyleSheet() self.nombreReporte = str(nombreReporteP) self.dirArchivo = str(directorioArchivoP) self.tipoArchivo = ".pdf" global operador global imagenes operador = str(operadorP) imagenes = ['static/image/universidad.jpg', 'static/image/alcaldia.png'] def inicializarReporte(self, nombreReporteP): self.doc = BaseDocTemplate(nombreReporteP, pagesize=letter) def contenidoFrame(self): self.contenidoFrame = Frame(self.doc.leftMargin, (self.doc.height - self.doc.topMargin), self.doc.width, self.doc.height / 6, showBoundary=1) def constructorPaginas(self): self.doc.addPageTemplates([PageTemplate(id='reporte', frames=self.contenidoFrame, onPage =encabezado, onPageEnd=piePagina)]) def crearReporteVertical(self): try: self.inicializarReporte(os.path.join(self.dirArchivo, self.nombreReporte + self.tipoArchivo)) self.contenidoFrame() self.constructorPaginas() self.story.append(Paragraph("El viaje del navegante. Blog de Python", self.styles['Normal'])) self.doc.build(self.story) os.system(os.path.join(self.dirArchivo, self.nombreReporte + self.tipoArchivo)) except Exception, e: print e
def create_confirmation(confirmation_buffer, booking): every_page_frame = Frame(PAGE_MARGIN, PAGE_MARGIN, PAGE_WIDTH - 2 * PAGE_MARGIN, PAGE_HEIGHT - 160, id='EveryPagesFrame') every_page_template = PageTemplate(id='EveryPages', frames=every_page_frame, onPage=_create_letter_header_footer) doc = BaseDocTemplate(confirmation_buffer, pageTemplates=[every_page_template], pagesize=A4) elements = [] elements.append(Paragraph('BOOKING CONFIRMATION', styles['InfoTitleVeryLargeCenter'])) table_data = [] table_data.append([Paragraph('Campground', styles['BoldLeft']), Paragraph('{}, {}'.format(booking.campground.name, booking.campground.park.name), styles['BoldLeft'])]) if booking.first_campsite_list: campsites = [] if booking.campground.site_type == 0: for item in booking.first_campsite_list: campsites.append(item.name if item else "") elif booking.campground.site_type == 1 or 2: for item in booking.first_campsite_list: campsites.append(item.type.split(':', 1)[0] if item else "") campsite = ', '.join(campsites) result = {x: campsites.count(x) for x in campsites} for key, value in result.items(): campsite = ', '.join(['%sx %s' % (value, key) for (key, value) in result.items()]) table_data.append([Paragraph('Camp Site', styles['BoldLeft']), Paragraph(campsite, styles['Left'])]) table_data.append([Paragraph('Dates', styles['BoldLeft']), Paragraph(booking.stay_dates, styles['Left'])]) table_data.append([Paragraph('Number of guests', styles['BoldLeft']), Paragraph(booking.stay_guests, styles['Left'])]) table_data.append([Paragraph('Name', styles['BoldLeft']), Paragraph(u'{} {} ({})'.format(booking.details.get('first_name', ''), booking.details.get('last_name', ''), booking.customer.email if booking.customer else None), styles['Left'])]) table_data.append([Paragraph('Booking confirmation number', styles['BoldLeft']), Paragraph(booking.confirmation_number, styles['Left'])]) if booking.vehicle_payment_status: vehicle_data = [] for r in booking.vehicle_payment_status: data = [Paragraph(r['Type'], styles['Left']), Paragraph(r['Rego'], styles['Left'])] if r.get('Paid') is not None: if r['Paid'] == 'Yes': data.append(Paragraph('Entry fee paid', styles['Left'])) elif r['Paid'] == 'No': data.append(Paragraph('Unpaid', styles['Left'])) elif r['Paid'] == 'pass_required': data.append(Paragraph('Park Pass Required', styles['Left'])) vehicle_data.append(data) vehicles = Table(vehicle_data, style=TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')])) table_data.append([Paragraph('Vehicles', styles['BoldLeft']), vehicles]) else: table_data.append([Paragraph('Vehicles', styles['BoldLeft']), Paragraph('No vehicles', styles['Left'])]) if booking.campground.additional_info: table_data.append([Paragraph('Additional confirmation information', styles['BoldLeft']), Paragraph(booking.campground.additional_info, styles['Left'])]) elements.append(Table(table_data, colWidths=(200, None), style=TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')]))) doc.build(elements) return confirmation_buffer
def build(self, header_flowable, body_flowable, footer_flowable, canvasmaker=canvas.Canvas): """ Build the document using the flowables. Set up the page templates that the document can use """ self.header_flowable = header_flowable self.body_flowable = body_flowable self.footer_flowable = footer_flowable self.calc_body_size(header_flowable, footer_flowable, ) showBoundary = 0 # for debugging set to 1, otherwise 0 body_frame = Frame(self.leftMargin, self.bottomMargin + self.footer_height, self.printable_width, self.body_height, leftPadding = 0, bottomPadding = 0, rightPadding = 0, topPadding = 0, id = "body", showBoundary = showBoundary ) self.body_frame = body_frame self.normalPage = PageTemplate (id = 'Normal', frames = [body_frame,], onPage = self.add_page_decorators, pagesize = self.pagesize ) # @todo set these page templates up # self.evenPage = PageTemplate (id='even', # frames=frame_list, # onPage=self.onEvenPage, # pagesize=self.pagesize # ) # self.oddPage = PageTemplate (id='odd', # frames=frame_list, # onPage=self.onOddPage, # pagesize=self.pagesize # ) self.landscapePage = PageTemplate (id='Landscape', frames = [body_frame,], onPage=self.add_page_decorators, pagesize=landscape(self.pagesize) ) if self.defaultPage == "Landscape": self.addPageTemplates(self.landscapePage) else: self.addPageTemplates(self.normalPage) BaseDocTemplate.build(self, self.body_flowable, canvasmaker=canvasmaker)
def __init__(self, *args, **kwargs): BaseDocTemplate.__init__(self, *args, **kwargs) self.metadata = { "locations": { "signatures": list() } } self.sig_counter = 0
def __init__(self, *args, **kwargs): from reportlab.lib.units import cm if not kwargs.has_key('leftMargin'): kwargs['leftMargin'] = 1.5 * cm if not kwargs.has_key('rightMargin'): kwargs['rightMargin'] = 1.5 * cm if not kwargs.has_key('bottomMargin'): kwargs['bottomMargin'] = 1.5 * cm BaseDocTemplate.__init__(self, *args, **kwargs)
def handle_pageBreak(self, slow=None): self._breaks += 1 if self._breaks > 1 and self.page > 1 : frame = self.frame while (frame._y > 60) : para = Paragraph (u'\u3000.'.encode('utf8'), self.hiddenStyle) frame.add(para, self.canv, trySplit=0) BaseDocTemplate.handle_pageBreak(self, slow)
def __init__(self, *args, **kwargs): from reportlab.lib.units import cm kwargs.setdefault('leftMargin', 1.5 * cm) kwargs.setdefault('rightMargin', 1.5 * cm) kwargs.setdefault('bottomMargin', 1.5 * cm) BaseDocTemplate.__init__(self, *args, **kwargs)
def handle_frameBegin(self, resume=0): BaseDocTemplate.handle_frameBegin(self, resume=resume) self.frame.add(Paragraph(self.__headerLeft, header_left_style), self.canv) self.frame.add(Paragraph(self.__headerRight, header_right_style), self.canv) self.frame.add(Paragraph(" ".join(list(self.__section)), header_style), self.canv) self.frame.add(Rule(lineWidth=0.5, spaceBefore=2, spaceAfter=1), self.canv) if self.__entryTitle: self.frame.add(self.__entryTitle, self.canv)
def __init__(self, name, teacher): self.PAGE_WIDTH = A4[0] self.PAGE_HEIGHT = A4[1] self.CENTRE_WIDTH = self.PAGE_WIDTH/2.0 self.CENTRE_HEIGHT = self.PAGE_HEIGHT/2.0 BaseDocTemplate.__init__(self,name, pagesize=A4, topMargin=0.5*cm) self.fileName = name self.teacher = teacher
def __init__(self, doc): self.docname = doc self.page_counter = 2 self.w, self.h = letter self.doc = BaseDocTemplate(self.docname, pagesize=letter) self.landscape = Frame(self.doc.leftMargin, self.doc.bottomMargin, self.doc.height, self.doc.width, id="Normal") self.portrait = Frame(self.doc.leftMargin, self.doc.bottomMargin, self.doc.width, self.doc.height, id="Normal") self.tportrait = Frame(self.doc.leftMargin, self.doc.bottomMargin, self.doc.width, self.doc.height, id="Normal") ttemplate = PageTemplate(id='tportrait', frames=self.tportrait, onPage=self.make_title_page) ptemplate = PageTemplate(id='portrait', frames=self.portrait, onPage=self.make_portrait) ltemplate = PageTemplate(id='landscape', frames=self.landscape, onPage=self.make_landscape) self.doc.addPageTemplates([ttemplate, ptemplate, ltemplate]) self.styles = getSampleStyleSheet() self.start = "" self.end = "" self.story = [] self.pgType = "Letter" self.image = "" self.cimage = "" self.client = "" self.toc = TableOfContents() self.toc.levelStyles = [ PS(fontName='Times-Bold', fontSize=10, name='TOCHeading1', leftIndent=20, firstLineIndent=-20, spaceBefore=10, leading=16), PS(fontSize=10, name='TOCHeading2', leftIndent=40, firstLineIndent=-20, spaceBefore=5, leading=12), ]
def __init__(self, buffer=None, debug=False): # Buffer must be set! if buffer is None: raise ValueError("Buffer argument is required") else: self.buffer = buffer self.debug = debug # Label parameters are for Avery 6572. # TODO: allow this to be set via options or some other way. # ... a horrible part of me is considering adding a model for label sheets. self.width = 612 self.height = 792 self.top_margin = 36 self.bottom_margin = 36 self.left_margin = 9 self.right_margin = 9 self.rows = 5 self.cols = 3 self.row_gutter = 0 self.col_gutter = 9 # Calculate label width and height. self.labelw = int((self.width - self.left_margin - self.right_margin - (self.cols - 1) * self.col_gutter) / self.cols) self.labelh = int((self.height - self.top_margin - self.bottom_margin - (self.rows - 1) * self.row_gutter) / self.rows) # Get sample style sheet from styles. self.styles = getSampleStyleSheet() self.style = self.styles["Normal"] # Create document from base template. self.doc = BaseDocTemplate(self.buffer, pagesize=(self.width, self.height)) # Construct page template of "frames". Each frame contains one label. self.framelist = [( self.left_margin + y * (self.col_gutter + self.labelw), self.height - self.bottom_margin - self.labelh - x * (self.row_gutter + self.labelh), self.labelw, self.labelh, ) for x in range(self.rows) for y in range(self.cols)] self.doc.addPageTemplates([ PageTemplate(frames=[ Frame(a, b, c, d, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, showBoundary=(1 if self.debug else 0)) for (a, b, c, d) in self.framelist ]) ])
def generate_order_pdf(order, filename=_default_filename): firstpage = FirstPageTemplate(order=order) laterpages = LaterPageTemplate(order=order) doc = BaseDocTemplate(filename, pagesize=PAGESIZE, pageTemplates=[firstpage, laterpages]) story = [NextPageTemplate('later')] columns = [1.0 * cm, 2.75 * cm, 6 * cm, 3.25 * cm, 3 * cm, 1.5 * cm] data = [[ Paragraph('Qty', styleTH), Paragraph('ISBN', styleTH), Paragraph('Title', styleTH), Paragraph('Author', styleTH), Paragraph('Publisher', styleTH), Paragraph('Binding', styleTH), ]] def compare_titles(a, b): return cmp(a.book.title, b.book.title) for entry in sorted(order.order_entries, compare_titles): row = [ Paragraph(unicode(entry.quantity), styleTR), Paragraph(unicode(entry.book.isbn13), styleTR), Paragraph(unicode(entry.book.title), styleTR), Paragraph(unicode(entry.book.author_lastname()), styleTR), Paragraph(unicode(entry.book.publisher), styleTR), Paragraph(unicode(entry.book.binding), styleTR), ] data.append(row) table = Table(data, colWidths=columns, repeatRows=1) table.setStyle( TableStyle([ ('BOTTOMPADDING', (0, 0), (-1, -1), 0.5 * cm), ('VALIGN', (0, 0), (-1, -1), 'TOP'), #('FONT', (0, 0), (-1, 0), styleTH.fontName, styleTH.fontSize), #('LEADING', (0, 0), (-1, 0), styleTH.leading), #('FONT', (0, 1), (-1, -1), styleTR.fontName, styleTR.fontSize), #('LEADING', (0, 1), (-1, -1), styleTR.leading), ])) if len(order.order_entries) > 1: plural = 's' else: plural = '' story.append(Spacer(1, 1 * cm)) story.append(Paragraph("ATTENTION: ORDER DEPARTMENT", styleN)) story.append( Paragraph("<i>Special Instructions</i>:<b>" + order.comment + "</b>", styleN)) story.append( Paragraph('<i>Please send the following title' + plural + ':</i>', styleN)) story.append(table) doc.build(story, canvasmaker=NumberedCanvas)
def build(self, style=1): template = SimpleDocTemplate(config.get("paths.tempdir", "") + "print.pdf", showBoundary=0) tFirst = PageTemplate(id='First', frames=self.getStyle(1, style), onPage=self.myPages, pagesize=defaultPageSize) tNext = PageTemplate(id='Later', frames=self.getStyle(2, style), onPage=self.myPages, pagesize=defaultPageSize) template.addPageTemplates([tFirst, tNext]) template.allowSplitting = 1 BaseDocTemplate.build(template, self.data) return template.canv._doc.GetPDFData(template.canv)
def __init__(self,filename): self.mypage = MyPageTemp() self.filename = filename self.height = 12*inch self.width = 9*inch self.doc = BaseDocTemplate(self.filename, pagesize = (9*inch,12*inch)) self.doc.addPageTemplates(self.mypage) self.styles = getSampleStyleSheet() self.styleT = self.styles['Title'] self.styleT.fontName = 20
def __init__(self, *args, **kwargs): BaseDocTemplate.__init__(self, *args, **kwargs) self.numPages = 0 self._lastNumPages = 0 self.setProgressCallBack(self._onProgress_cb) # For batch reports with several PDFs concatenated self.restartDoc = False self.restartDocIndex = 0 self.restartDocPageNumbers = []
def build(self,flowables,onFirstPage=_doNothing, onLaterPages=_doNothing, canvasmaker=canvas.Canvas): 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 _calc(self): if self.defaultPage == "Landscape": self.pagesize = landscape(self.paper_size) else: self.pagesize = portrait(self.paper_size) BaseDocTemplate._calc(self) self.height = self.pagesize[PDF_HEIGHT] self.width = self.pagesize[PDF_WIDTH] self.printable_width = self.width - self.leftMargin - self.rightMargin - self.insideMargin self.printable_height = self.height - self.topMargin - self.bottomMargin
def fill(self, fname, pagesize, events, topspace, bottomspace, margins): doc = BaseDocTemplate(fname, pagesize=pagesize, leftMargin=margins, bottomMargin=bottomspace, rightMargin=margins, topMargin=topspace) left_column = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height-0.4*inch, id="left") right_column = Frame(doc.leftMargin+doc.width/2+6, doc.bottomMargin, doc.width/2-6, doc.height-0.4*inch, id="right") doc.addPageTemplates(PageTemplate(frames=[left_column, right_column])) story = [] for e in events: story.append(Event(e).render()) doc.build(story)
def _create_licence_renewal(licence_renewal_buffer, licence, site_url): every_page_frame = Frame(PAGE_MARGIN, PAGE_MARGIN, PAGE_WIDTH - 2 * PAGE_MARGIN, PAGE_HEIGHT - 160, id='EveryPagesFrame') every_page_template = PageTemplate(id='EveryPages', frames=every_page_frame, onPage=_create_header) doc = BaseDocTemplate(licence_renewal_buffer, pageTemplates=[every_page_template], pagesize=A4) # this is the only way to get data into the onPage callback function doc.site_url = site_url doc.build(_create_licence_renewal_elements(licence)) return licence_renewal_buffer
def __init__(self, *args, **kwargs): # letter 21.6 x 27.9 kwargs['pagesize'] = letter kwargs['rightMargin'] = 1 * cm kwargs['leftMargin'] = 1 * cm kwargs['topMargin'] = 4 * cm kwargs['bottomMargin'] = 2 * cm BaseDocTemplate.__init__(self, *args, **kwargs) self.styles = getSampleStyleSheet() self.header = {} self.data = []
def Print(doc, day = 1): params = yield Client().sGet(("params", None)) params['date'] = (params['date_from'] + timedelta(day-1)).strftime("%x") filename = tempfile.mktemp(".pdf") c = BaseDocTemplate(filename, pageTemplates=[MyTemplate(params)], pagesize=pagesizes.landscape(pagesizes.A4), rightMargin=1*cm,leftMargin=1*cm, topMargin=1*cm, bottomMargin=1*cm) c.build(doc) print("printing") PrintFile(filename)
def fill(self, fname, pagesize, events, topspace, bottomspace, margins): std_margin = 0.5*inch doc = BaseDocTemplate(fname, pagesize=pagesize, leftMargin=std_margin, bottomMargin=std_margin, rightMargin=std_margin, topMargin=std_margin) phonebank = Frame(doc.leftMargin, doc.bottomMargin+3*doc.height/4, doc.width, doc.height/4, id="featured") doc.addPageTemplates(PageTemplate(frames=[phonebank])) story = [] story.append(PBEvent(events[0]).render()) story.append(FrameBreak()) doc.build(story)
def fill(self, fname, pagesize, events, topspace, bottomspace, margins): doc = BaseDocTemplate(fname, pagesize=pagesize, leftMargin=margins, bottomMargin=bottomspace, rightMargin=margins, topMargin=topspace) column = Frame(doc.leftMargin, doc.bottomMargin, doc.width-6, doc.height, id="large") doc.addPageTemplates(PageTemplate(frames=[column])) story = [] for e in events: story.append(XLEvent(e).render()) story.append(SpacerLine(3*inch, 0)) story = story[:-1] doc.build(story)
def __init__(self, *args, **kw): BaseDocTemplate.__init__(self, *args, **kw) doc = self columns = [] columns.append(FancyFrame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height)) #doc.showBoundary = True doc.addPageTemplates([ PageTemplate(id='OneColumn', frames=columns), ])
def create_pdfdoc(dest_filename, story): pdf_doc = BaseDocTemplate(dest_filename, pagesize=PAGE_SIZE, leftMargin=SIDE_MARGIN_SIZE, rightMargin=SIDE_MARGIN_SIZE, topMargin=VERT_MARGIN_SIZE, bottomMargin=VERT_MARGIN_SIZE) main_frame = Frame(SIDE_MARGIN_SIZE, VERT_MARGIN_SIZE, PAGE_SIZE[0] - 2 * SIDE_MARGIN_SIZE, PAGE_SIZE[1] - 2 * VERT_MARGIN_SIZE, leftPadding = 0, rightPadding = 0, bottomPadding = 0, topPadding = 0, id = 'main_frame') main_template = PageTemplate(id = 'main_template', frames = [main_frame]) pdf_doc.addPageTemplates([main_template]) pdf_doc.build(story)
def __init__(self, file_handle=None): self.document = BaseDocTemplate(file_handle, showBoundary=1, leftMargin=0.1 * inch, rightMargin=0.1 * inch, topMargin=0.1 * inch, bottomMargin=0.1 * inch, pageSize=landscape(custom_page), allowSplitting=0, title="Statement of Collection Report", author="Francis T.M. Alfanta") self.build_templates()
def create_admissions_confirmation(confirmation_buffer, admissionsBooking, mooring_var): global DPAW_HEADER_LOGO global LETTER_IMAGE_WIDTH global LETTER_IMAGE_HEIGHT if mooring_var["TEMPLATE_GROUP"] == 'rottnest': DPAW_HEADER_LOGO = os.path.join(settings.BASE_DIR, 'mooring', 'static', 'mooring', 'img','logo-rottnest-island-sm.png') LETTER_IMAGE_WIDTH = LICENCE_HEADER_IMAGE_WIDTH/2.9 LETTER_IMAGE_HEIGHT = LICENCE_HEADER_IMAGE_HEIGHT/1.4 else: DPAW_HEADER_LOGO = os.path.join(settings.BASE_DIR, 'mooring', 'static', 'mooring','img','mooring_header.png') LETTER_IMAGE_WIDTH = LICENCE_HEADER_IMAGE_WIDTH/3.0 LETTER_IMAGE_HEIGHT = LICENCE_HEADER_IMAGE_HEIGHT/3.0 every_page_frame = Frame(PAGE_MARGIN, PAGE_MARGIN, PAGE_WIDTH - 2 * PAGE_MARGIN, PAGE_HEIGHT - 160, id='EveryPagesFrame') every_page_template = PageTemplate(id='EveryPages', frames=every_page_frame, onPage=_create_letter_header_footer) doc = BaseDocTemplate(confirmation_buffer, pageTemplates=[every_page_template], pagesize=A4) adl = AdmissionsLine.objects.filter(admissionsBooking=admissionsBooking) elements = [] elements.append(Paragraph('ADMISSIONS FEE PAYMENT CONFIRMATION', styles['InfoTitleVeryLargeCenter'])) table_data = [] table_data.append([Paragraph('Name', styles['BoldLeft']), Paragraph(u'{} ({})'.format(admissionsBooking.customer.get_full_name(), admissionsBooking.customer.email if admissionsBooking.customer else None), styles['Left'])]) table_data.append([Paragraph('Admission Fee confirmation number', styles['BoldLeft']), Paragraph(admissionsBooking.confirmation_number, styles['Left'])]) for line in adl: table_data.append([Paragraph('Date', styles['BoldLeft']), Paragraph(u'{}'.format(datetime.strftime(line.arrivalDate, '%d/%m/%Y')), styles['Left'])]) overnightStay = "" if(line.overnightStay): overnightStay = "Yes" else: overnightStay = "No" table_data.append([Paragraph('Overnight Stay', styles['BoldLeft']), Paragraph(u'{}'.format(overnightStay), styles['Left'])]) if admissionsBooking.noOfAdults > 0: table_data.append([Paragraph('Adults', styles['BoldLeft']), Paragraph(u'{}'.format(admissionsBooking.noOfAdults), styles['Left'])]) if admissionsBooking.noOfConcessions > 0: table_data.append([Paragraph('Concessions', styles['BoldLeft']), Paragraph(u'{}'.format(admissionsBooking.noOfConcessions), styles['Left'])]) if admissionsBooking.noOfChildren > 0: table_data.append([Paragraph('Children', styles['BoldLeft']), Paragraph(u'{}'.format(admissionsBooking.noOfChildren), styles['Left'])]) if admissionsBooking.noOfInfants > 0: table_data.append([Paragraph('Infants', styles['BoldLeft']), Paragraph(u'{}'.format(admissionsBooking.noOfInfants), styles['Left'])]) elements.append(Table(table_data, colWidths=(200, None), style=TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')]))) doc.build(elements) return confirmation_buffer
def __init__(self, *args, **kwargs): self.has_title_page = kwargs.pop('has_title_page', False) frame = Frame( left_margin, bottom_margin, frame_width, frame_height, id='normal', leftPadding=0, topPadding=0, rightPadding=0, bottomPadding=0 ) pageTemplates = [ PageTemplate(id='standard', frames=[frame]) ] BaseDocTemplate.__init__( self, pageTemplates=pageTemplates, *args, **kwargs )
def __init__(self, filename, org, margin=2*cm, sep=0.2*cm, **kw): self.allowSplitting = 0 BaseDocTemplate.__init__(self, filename, **kw) self.margin = margin self.w, self.h = self.pagesize self.sep = sep self.org = org template = PageTemplate('normal', frames=[Frame(self.leftMargin, self.bottomMargin, self.width, self.height, id='F1')], onPage=self.laterPages) self.addPageTemplates(template) self.PAGE_FOOTER_LEFT = _("LGPD Web App %s") self.PAGE_FOOTER_RIGHT = _("Pagina %d") self.GENERATED_ON = _("Relatorio gerado em {date}") self.POWERED_BY = _("Powered by")
def __init__(self, filename, org, margin=2*cm, sep=0.2*cm, **kw): self.allowSplitting = 0 BaseDocTemplate.__init__(self, filename, **kw) self.margin = margin self.w, self.h = self.pagesize self.sep = sep self.org = org template = PageTemplate('normal', frames=[Frame(self.leftMargin, self.bottomMargin, self.width, self.height, id='F1')], onPage=self.laterPages) self.addPageTemplates(template) self.PAGE_FOOTER_LEFT = _("GDPR Registry of Data Processing Activities for %s") self.PAGE_FOOTER_RIGHT = _("Page %d") self.GENERATED_ON = _("Report generated on {date}") self.POWERED_BY = _("Powered by")
def init_reportlab(self, save_to_file=True): self.styles = getSampleStyleSheet() self.buff = BytesIO() self.doc = BaseDocTemplate(os.path.join( self.output_path, self.filename) if save_to_file else self.buff, pagesize=self.page_format, leftMargin=self.page_margin * cm, rightMargin=self.page_margin * cm, topMargin=self.page_margin * cm, bottomMargin=self.page_margin * cm, showBoundary=0, allowSplitting=1) # define styles for paragraphs self.styles.add( ParagraphStyle('Header', fontSize=self.font_size, fontName=self.font_name, spaceBefore=self.space_before, spaceAfter=self.space_after, leading=self.font_size, alignment=TA_CENTER)) self.styles.add( ParagraphStyle( 'Move_Text', fontSize=self.font_size, fontName=self.font_name, spaceBefore=self.space_before, spaceAfter=self.space_after, leading=self.font_size, )) # TODO: Add more Layouts if False: pass elif self.page_layout == 'two_col': frame_width = self.doc.width / 2 - self.col_gap / 2 * cm frame1 = Frame(self.doc.leftMargin, self.doc.bottomMargin, frame_width, self.doc.height, id='col1') frame2 = Frame(self.doc.leftMargin + frame_width + self.col_gap * cm, self.doc.bottomMargin, frame_width, self.doc.height, id='col2') self.doc.addPageTemplates( [PageTemplate(id='twoCol', frames=[frame1, frame2])]) # Set board dimensions relative to the two column layout self.board_length = 0.8 * frame_width / cm # in cm self.tile_length = self.board_length / 8 # in cm
def _create_cover_letter(cover_letter_buffer, licence, site_url): cover_letter_frame = Frame(LETTER_PAGE_MARGIN, LETTER_PAGE_MARGIN, PAGE_WIDTH - 2 * LETTER_PAGE_MARGIN, PAGE_HEIGHT - 160, id='CoverLetterFrame') every_cover_letter_template = PageTemplate( id='CoverLetter', frames=cover_letter_frame, onPage=_create_letter_header_footer) doc = BaseDocTemplate(cover_letter_buffer, pageTemplates=[every_cover_letter_template], pagesize=A4) elements = [] elements += _create_letter_address(licence) elements.append(Spacer(1, LETTER_ADDRESS_BUFFER_HEIGHT)) elements += _create_letter_paragraph('{}'.format( licence.licence_type.name), style='LetterBoldLeft') elements += _create_letter_paragraph('Please find the licence attached.') elements += _create_letter_paragraph( 'Please ensure that all the licence conditions are complied with, including ' 'the forwarding of a return at the end of the licence period.') if licence.cover_letter_message: for message in licence.cover_letter_message.split('\r\n'): if message: elements.append(Paragraph(message, styles['LetterLeft'])) else: elements.append(Spacer(1, SECTION_BUFFER_HEIGHT)) elements.append(Spacer(1, SECTION_BUFFER_HEIGHT)) elements += _create_letter_paragraph( 'If you have any queries, please contact the Wildlife Licensing section ' 'on 9219 9831.') elements += _create_letter_signature() doc.build(elements) return cover_letter_buffer
def _create_licence_renewal(licence_renewal_buffer, licence, site_url): licence_renewal_frame = Frame(LETTER_PAGE_MARGIN, LETTER_PAGE_MARGIN, PAGE_WIDTH - 2 * LETTER_PAGE_MARGIN, PAGE_HEIGHT - 160, id='LicenceRenewalFrame') licence_renewal_template = PageTemplate(id='LicenceRenewalFrame', frames=[licence_renewal_frame], onPage=_create_letter_header_footer) doc = BaseDocTemplate(licence_renewal_buffer, pageTemplates=[licence_renewal_template], pagesize=A4) elements = _create_letter_address(licence) + [Spacer(1, LETTER_ADDRESS_BUFFER_HEIGHT)] + \ _create_licence_renewal_elements(licence) + _create_letter_signature() doc.build(elements) return licence_renewal_buffer
def fill(self, fname, pagesize, events, topspace, bottomspace, margins): tf = tempfile.NamedTemporaryFile(delete=False) pagesize = (pagesize[0] / 2 - 6, pagesize[1]) doc = BaseDocTemplate(tf.name, pagesize=pagesize, leftMargin=margins, bottomMargin=bottomspace, rightMargin=margins, topMargin=topspace) column = Frame(doc.leftMargin+6, doc.bottomMargin+0.5*inch, doc.width-6, 3.3*inch) rsvp = Frame(doc.leftMargin+6, doc.bottomMargin, doc.width-6, 0.5*inch) doc.addPageTemplates(PageTemplate(frames=[rsvp, column])) # render one side story = [] story.append(Paragraph("Please RSVP at map.berniesanders.com", styles["default"])) story.append(FrameBreak()) for e in events: story.append(Event(e).render()) doc.build(story) # now duplicate for 2-up src = PdfFileReader(open(tf.name, "rb")) out = PdfFileWriter() lhs = src.getPage(0) lhs.mergeTranslatedPage(lhs, lhs.mediaBox.getUpperRight_x(), 0, True) out.addPage(lhs) with open(fname.name, "wb") as outfile: out.write(outfile) os.remove(tf.name)