def create_pdf():

    I = Image('qr1.png')
    I.drawHeight = 18 * mm * I.drawHeight / I.drawWidth
    I.drawWidth = 18 * mm

    qr1 = genQR('hahahahah')

    # Create a frame
    CatBox_frame = Frame(
        x1=0 * mm,  # From left
        y1=0 * mm,  # From bottom
        height=75 * mm,
        width=110 * mm,
        leftPadding=0 * mm,
        bottomPadding=0 * mm,
        rightPadding=0 * mm,
        topPadding=0 * mm,
        showBoundary=1,
        id='CatBox_frame')

    table_data = [[qr1, qr1, qr1], [qr1, qr1, qr1], [qr1, qr1, qr1]]

    table_data2 = []
    qrcode_valarr = genNum()
    arrindex = 0
    for i in range(0, 3):
        t1 = []
        for j in range(0, 3):
            qr1 = genQR(qrcode_valarr[arrindex])
            arrindex = arrindex + 1
            t1.append(qr1)
        table_data2.append(t1)

    # Create a table
    CatBox = Table(table_data2, 36.6 * mm, 25 * mm, vAlign='BOTTOM')

    # Style the table
    CatBox.setStyle(
        TableStyle([('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE')]))

    # Trying to tell the table to be a bottom align object (when later put in frame)
    CatBox.Align = 'BOTTOM'
    CatBox.vAlign = 'BOTTOM'

    # Building the story
    #story = [CatBox] # adding CatBox table (alternative, story.add(CatBox))
    story = [TopPadder(CatBox)]

    # Establish a document
    doc = BaseDocTemplate("DanhSach_QRCode.pdf", pagesize=QRCode)

    # Creating a page template
    frontpage = PageTemplate(id='FrontPage', frames=[CatBox_frame])
    # Adding the story to the template and template to the document
    doc.addPageTemplates(frontpage)

    # Building doc
    doc.build(story)
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)
Exemple #3
0
 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)
Exemple #4
0
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
Exemple #5
0
    def __init__(self, path):

        self.path = path

        styles = getSampleStyleSheet()
        self._styleN = styles["Normal"]
        self._styleH1 = styles["Heading1"]
        self._styleH2 = styles["Heading2"]
        self.page = 0

        doc = BaseDocTemplate(self.path, pagesize=A4)
        frame = Frame(doc.leftMargin,
                      doc.bottomMargin,
                      doc.width,
                      doc.height - 2 * cm,
                      id="normal")
        template = PageTemplate(id="legal_doc",
                                frames=frame,
                                onPage=self.header_footer)
        doc.addPageTemplates([template])

        text = []
        for i in range(111):
            text.append(Paragraph("This is line %d." % i, self._styleN))

        doc.build(text)
Exemple #6
0
    def format_wrt(self, output_file, dat):
        self.logger.debug('dumping contents of dat: {}'.format(repr(dat)))

        doc = BaseDocTemplate(
            output_file,
            pagesize=letter,
            rightMargin=30,
            leftMargin=30,
            topMargin=30,
            bottomMargin=18,
        )
        story = []
        logo = Image(dat['LOGO'])
        logo.drawHeight = 3.8 * cm
        logo.drawWidth = 5.2 * cm

        qrcode = Image(dat['QRCODE'])
        qrcode.drawHeight = 3.2 * cm
        qrcode.drawWidth = 3.2 * cm

        story.append(self.__top_table(logo, dat))
        story.append(Spacer(1, 0.4 * cm))
        story.append(self.__customer_table(dat))
        story.append(Spacer(1, 0.4 * cm))
        story.append(self.__items_section(dat))
        story.append(Spacer(1, 0.4 * cm))
        story.append(self.__amount_section(dat))
        story.append(Spacer(1, 0.45 * cm))

        ct = self.__comments_section(dat)
        if ct is not None:
            story.append(ct)
        story.append(Spacer(1, 0.6 * cm))
        story.append(self.__info_cert_section(dat))
        story.append(self.__info_stamp_section(qrcode, dat))
        story.append(self.__info_cert_extra(dat))
        story.append(Spacer(1, 0.6 * cm))

        lt = self.__legend_section(dat)
        if lt is not None:
            story.append(lt)

        def fp_foot(c, d):
            c.saveState()
            width, height = letter
            c.setFont('Helvetica', 7)
            c.drawCentredString(width / 2.0, (1.00 * cm), dat['FOOTER_ABOUT'])
            c.restoreState()

        bill_frame = Frame(doc.leftMargin,
                           doc.bottomMargin,
                           doc.width,
                           doc.height,
                           id='bill_frame')

        doc.addPageTemplates([
            PageTemplate(id='biil_page', frames=[bill_frame], onPage=fp_foot),
        ])
        doc.build(story, canvasmaker=NumberedCanvas)
        return
Exemple #7
0
def create_report_with_full_log(working_dir):
    doc = BaseDocTemplate(
        "report3.pdf",
        pagesize=A4,
        rightMargin=72,
        leftMargin=72,
        topMargin=50,
        bottomMargin=80,
        showBoundary=False)

    elements = []

    styles = getSampleStyleSheet()

    frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height - 2 * cm, id='normal')

    sms_title = Paragraph('Messages history log table.', styles["Heading1"])
    call_title = Paragraph('Call history log table.', styles["Heading1"])

    elements.append(sms_title)
    elements.append(sms_table(working_dir))

    elements.append(PageBreak())

    elements.append(call_title)
    elements.append(call_table(working_dir))
    
    template = PageTemplate(id='longtable', frames=frame)
    doc.addPageTemplates([template])
    doc.build(elements)
Exemple #8
0
def create_report_with_more_columns(working_dir):
    doc = BaseDocTemplate(
        "report2.pdf",
        pagesize=A4,
        rightMargin=72,
        leftMargin=72,
        topMargin=50,
        bottomMargin=80,
        showBoundary=False)

    styles = getSampleStyleSheet()

    all_words_marking_title = Paragraph('Words marking through all chats', styles["Heading1"])

    elements = words_marking_by_chat(working_dir)
    elements.append(PageBreak())

    elements.append(all_words_marking_title)
    elements.append(all_words_marking_table(working_dir))

    frameWidth = doc.width/2
    frameHeight = doc.height-.05*cm
    frames = []
    for frame in range(2):
        leftMargin = doc.leftMargin + frame*frameWidth
        column = Frame(leftMargin, doc.bottomMargin, frameWidth, frameHeight)
        frames.append(column)
    template = PageTemplate(id='threecolumns', frames=frames)

    doc.addPageTemplates([template])
    doc.build(elements)
Exemple #9
0
 def build_earthwork_resume(self):
     doc = BaseDocTemplate(self.out_path + self.lb_id + " (Report).pdf",
                           pagesize=A4,
                           pageTemplates=[],
                           showBoundary=0,
                           leftMargin=2.54 * cm,
                           rightMargin=2.54 * cm,
                           topMargin=2.54 * cm,
                           bottomMargin=2.54 * cm,
                           allowSplitting=1,
                           title="Landbank Report",
                           author="GIS")
     doc.addPageTemplates([
         PageTemplate(frames=[
             Frame(
                 doc.leftMargin,
                 doc.bottomMargin,
                 doc.width,
                 doc.height,
                 id='left',
                 leftPadding=0.2 * cm,
                 rightPadding=0.2 * cm,
                 showBoundary=0  # set to 1 for debugging
             ),
         ]),
     ])
     doc.build(self.build_flowabel_resume(), canvasmaker=NumberedCanvas)
     return "success build resume"
Exemple #10
0
    def _build(self):

        # Setup document template
        doc = BaseDocTemplate(self.output_file,
                              pagesize=landscape(letter),
                              showBoundary=1)

        def fp_foot(c, d):
            c.saveState()
            width, height = landscape(letter)
            c.setFont('Helvetica', 7)
            c.drawCentredString(width / 2.0, (1.00 * cm), 'FOOTER_ABOUT')
            c.restoreState()

        executive_frame = Frame(15,
                                45,
                                27 * cm,
                                19.5 * cm,
                                leftPadding=0.1 * cm,
                                rightPadding=0,
                                topPadding=0,
                                bottomPadding=0,
                                id='executive_frame')

        doc.addPageTemplates([
            PageTemplate(id='executive_frame',
                         onPage=fp_foot,
                         frames=[executive_frame]),
        ])

        # Apply story to document
        doc.build(self.story)
        return
Exemple #11
0
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 go():
    #create the basic page and frames
    doc = BaseDocTemplate("phello.pdf",
                          leftMargin=10,
                          rightMargin=0,
                          topMargin=0,
                          bottomMargin=0)
    doc.pagesize = landscape(A4)

    frameCount = 2
    frameWidth = doc.height / frameCount
    frameHeight = doc.width - .05 * inch
    frames = []
    #construct a frame for each column
    for frame in range(frameCount):
        leftMargin = doc.leftMargin + frame * frameWidth
        column = Frame(leftMargin, doc.bottomMargin, frameWidth, frameHeight)
        print leftMargin, doc.bottomMargin, frameWidth, frameHeight

        frames.append(column)
    template = PageTemplate(frames=frames)
    doc.addPageTemplates(template)

    #	doc = SimpleDocTemplate("phello.pdf", id='TwoColumns')
    #	doc.pagesize = landscape(A4) ## TODO: make configurable

    Story = []
    style = styles["Normal"]
    style.fontName = 'Courier'
    style.fontSize = 6
    for monkey in monkeys:
        p = Preformatted(get_ttview(monkey[0], monkey[1], 15), style)
        Story.append(KeepTogether(p))
        Story.append(Spacer(1, 0.05 * inch))
    doc.build(Story)
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)
Exemple #14
0
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
Exemple #15
0
def save_cutlist(fname, job):
    """Generate a cutlist for the job in PDF format and save it in fname.pdf."""
    doc = BaseDocTemplate(
        pdf_ify(fname),
        pagesize=landscape(letter),
        leftMargin=0.5 * inch,
        rightMargin=0.5 * inch,
        topMargin=0.5 * inch,
        bottomMargin=0.5 * inch,
        title='Cutlist for ' + job.name,
        # author='',
        subject='Cabinet Calc Cutlist Report',
        # TODO: Get version below from program source
        creator='Cabinet Calc version 0.1',
        showBoundary=0)
    frameHdr, frameL, frameR = makeframes(doc)
    doc.addPageTemplates([
        PageTemplate(id='twoCol',
                     frames=[frameHdr, frameL, frameR],
                     onPage=all_pages)
    ])
    # Construct the cutlist content--i.e., the `elements' list of Flowables
    elements = content(job)
    # Fill out and layout the document. This saves the pdf file as well.
    doc.build(elements)
Exemple #16
0
 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)
def create_pdfdoc(pdfdoc, story):
    """
    Creates PDF doc from story.
    """
    pdf_doc = BaseDocTemplate(pdfdoc, pagesize = letter,
        leftMargin = MARGIN_SIZE, rightMargin = MARGIN_SIZE,
        topMargin = 24, bottomMargin = MARGIN_SIZE)

    second_frame = main_frame = Frame(MARGIN_SIZE, MARGIN_SIZE,
        width - 2 * MARGIN_SIZE, height - (24 + 72),
        leftPadding = 0, rightPadding = 0, bottomPadding = 0,
        topPadding = 0, id = 'main_frame', showBoundary=0)
    second_template = PageTemplate(id = 'second_template', frames=[second_frame], onPage=header)

    main_frame = Frame(MARGIN_SIZE, MARGIN_SIZE,
        width - 2 * MARGIN_SIZE, height - (24 + MARGIN_SIZE),
        leftPadding = 0, rightPadding = 0, bottomPadding = 0,
        topPadding = 0, id = 'main_frame', showBoundary=0)
    main_template = PageTemplate(id = 'main_template', frames = [main_frame], onPage=header)

    
    
    pdf_doc.addPageTemplates([main_template, second_template])

    pdf_doc.build(story)
Exemple #18
0
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
Exemple #19
0
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)
Exemple #20
0
    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)        
Exemple #21
0
def build_pdf(filename, flowables):
    doc = BaseDocTemplate(filename, showBoundary=1)

    words = "lorem ipsum dolor sit amet consetetur sadipscing elitr sed diam nonumy eirmod tempor invidunt ut labore et".split(
    )

    styles = getSampleStyleSheet()
    #Elements=[]

    #two columns
    frame1 = Frame(doc.leftMargin,
                   doc.bottomMargin,
                   doc.width / 2 - 6,
                   doc.height,
                   id='col1')
    frame2 = Frame(doc.leftMargin + doc.width / 2 + 6,
                   doc.bottomMargin,
                   doc.width / 2 - 6,
                   doc.height,
                   id='col2')

    doc.addPageTemplates([
        PageTemplate(id='TwoCol', frames=[frame1, frame2]),
    ])

    #Elements.append(Paragraph(" ".join([random.choice(words) for i in range(1000)]),styles['Normal']))

    #start the construction of the pdf
    #doc.build(Elements)
    doc.build(flowables)
Exemple #22
0
    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)
Exemple #23
0
 def render(self):
     """
     Render the file and return the HttpResponse with the file.
     :return: HttpResponse
     """
     doc = BaseDocTemplate(
         self.response,
         title="{0} - ServiceID {1}".format(self.ticket.client.full_name(), self.ticket.id),
         author='Digital Horizon'
     )
     doc.addPageTemplates([
         PageTemplate(
             frames=[
                 self.info_frame_left,
                 self.info_frame_right,
                 self.left_frame,
                 self.right_frame,
                 self.actions_frame,
                 self.parts_frame
             ], onPage=TicketPDF.build_page
         )
     ])
     self.print_client_info()
     self.print_device_info()
     self.print_problem()
     self.print_diagnosis()
     self.print_actions()
     self.print_parts()
     doc.build(self.story)
     return self.response
Exemple #24
0
    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)
Exemple #25
0
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
Exemple #26
0
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)
Exemple #27
0
    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)
Exemple #28
0
    def build_pdf(self):
        """Using different internal page methods and given the data provided build the report
        """
        # doc options to abstract and set
        # doc.creator
        # doc.encrypt
        # doc.author
        # doc.subject
        # doc.title
        style = self.styles["Normal"]
        doc = BaseDocTemplate(self._filename)

        # Flowables to be added to document
        Story = []

        # could create different sized frames and set addPageTemplate frames to array frames=[frame1, frame2]
        standard_frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, id='sframe')

        Story.append(NextPageTemplate('host'))
        # space for title page
        Story.append(PageBreak())
        
        # Host data
        Story.append(Paragraph('Scanned Hosts ---------------------', self.styles['Heading2']))
        for h in self._report['hosts']:
            if h.get_display_val():
                hname = f'Hostname: {h.get_display_name()}'
                ip = f'IP Address: {h.get_ip()}'
                mac = f'MAC Address: {h.get_mac_address()}'
                Story.append(Paragraph(hname, style))
                Story.append(Paragraph(ip, style))
                Story.append(Paragraph(mac, style))
                Story.append(Spacer(1, 0.2 * inch))

        # cpe data
        Story.append(Paragraph('CPEs ---------------------', self.styles['Heading2']))
        if self._report['cpes']:
            for c in self._report['cpes']:
                if self._report['cpes'][c][0]:
                    cpe = self._report['cpes'][c][0]
                    Story.append(Paragraph(cpe, style))
                    Story.append(Spacer(1, 0.2 * inch))
        else:
            Story.append(Paragraph('No CPEs found', style))

        # Vuln Data
        Story.append(Paragraph('Vulnerabilities ---------------------', self.styles['Heading2']))
        if self._report['vulns']:
            for v in self._report['vulns']:
                Story.append(Paragraph(v, style))
        else:
            Story.append(Paragraph('No vulnerabilities found.', style))

        doc.addPageTemplates([PageTemplate(id='title', frames=standard_frame, onPage=self.title_page),
                              PageTemplate(id='host', frames=standard_frame, onPage=self.host_page)])

        doc.build(Story)
def main(sFilename,invoice):
    pdf_file = sFilename
    t = get_table(invoice)
    Elements = []

    def pgHdr(c, doc):
      width,height = A4
      #c.saveState()
      #c.translate(.3 * inch, 0 * inch)

      # STUFF RELATED TO 2 INCH STTIC HEADER FOR FIRST PAGE
      #c.restoreState()
    def othPg(c,doc):
      width,height = A4


    styles = getSampleStyleSheet()
    Elements.append(Spacer(1,2*inch))
    style = styles["Normal"]

    for i in range(3):
        bogustext = ("This is Paragraph number %s.  " % i) * 2
        p = Paragraph(bogustext, style)
        Elements.append(p)
        Elements.append(Spacer(1,0.2*inch))

    doc = BaseDocTemplate(pdf_file,
                    pagesize=A4,
                    leftMargin=.3*inch,
                    rightMargin= .1 * inch,
                    topMargin= .1 * inch,
                    bottomMargin=.3 * inch,
                    showBoundary=0)
    #normal frame as for SimpleFlowDocument
    #frameT = Frame(doc.leftMargin + 2*inch, doc.bottomMargin, doc.width - 2.01*inch, doc.height - 4.1*inch, id='normal', showBoundary=0)
    #frameB = Frame(doc.leftMargin+2, doc.bottomMargin, 7.5*inch, 10*inch, id='small', showBoundary=0)

    frameT = Frame(doc.leftMargin , doc.bottomMargin + 1*inch, doc.width, doc.height, id='normal', showBoundary=0)
    frameB = Frame(doc.leftMargin , doc.bottomMargin + 1*inch, doc.width, doc.height, id='normal', showBoundary=0)

  



    doc.addPageTemplates([PageTemplate(id='First',frames=frameT,onPage=pgHdr),
                        PageTemplate(id='Later',frames=frameB,onPage=othPg)
                        ])
    Elements.append(NextPageTemplate('First'))
    Elements.append(NextPageTemplate('Later'))
    Elements.append(t)

    #doc.addPageTemplates([PageTemplate(id='First',onPage=pgHdr)])
    #Elements.append(BaseDocTemplate)
    #Elements.append(t)

    doc.build(Elements)
Exemple #30
0
    def pdfreader(self, book):

        style = getSampleStyleSheet()['Normal']
        style.fontName = 'Montserratd'
        #style.spaceBefore = 20
        style.leading = 24
        style.spaceBefore = 25

        elements = []

        doc = BaseDocTemplate(settings.BASE_DIR + '/media/downloadpdf/' +
                              str(book.pk) + '.pdf',
                              showBoundary=1,
                              pagesize=mobile_size)
        pdfmetrics.registerFont(
            TTFont('Montserrat',
                   settings.BASE_DIR + '/fonts/Hind-SemiBold.ttf'))
        pdfmetrics.registerFont(
            TTFont('Montserratd',
                   settings.BASE_DIR + '/fonts/Martel-ExtraLight.ttf'))

        frameT = Frame(5 * mm, 5 * mm, 110 * mm, 287 * mm, showBoundary=2)
        # TopCenter = Frame(1.2 * inch, height - 1.2 * inch, width - 2.4 * inch, 1 * inch, showBoundary=1, id='normal')

        frame1 = Frame(0, 0, doc.width / 2 - 3, doc.height, id='col1')
        frame2 = Frame(doc.leftMargin + doc.width,
                       doc.bottomMargin,
                       doc.width,
                       doc.height,
                       id='col2')

        doc.addPageTemplates([
            PageTemplate(id='basedoc', frames=frameT),
            #     PageTemplate(id='TwoCol', frames=[frame1, frame2]),
        ])
        im = Image(settings.BASE_DIR + '/media/' + str(book.book_image),
                   80 * mm, 200)
        styles = getSampleStyleSheet()
        yourStyle = ParagraphStyle(
            'yourtitle',
            fontName="Montserrat",
            fontSize=16,
            #       parent=style['Heading2'],
            alignment=1,
            leading=20,
            spaceAfter=30)
        # styletitle.alignment = TA_CENTER

        elements.append(Paragraph(book.book_title, yourStyle))
        elements.append(im)
        for txtd in strip_tags(book.book_data).split('\n'):
            elements.append(Paragraph(txtd, style))

        # start the construction of the pdf
        doc.build(elements, canvasmaker=NumberedCanvas)
        return HttpResponse("writer is susesss")
Exemple #31
0
 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)
Exemple #32
0
    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 generate_driver_information_exchange_sheet(data):
    stream_buffer = io.BytesIO()
    f = Frame(gutters[0], gutters[2], usable_width, usable_height, showBoundary=0)
    main_template = PageTemplate(id="main_template", frames=[f])
    doc = BaseDocTemplate(stream_buffer, pagesize=letter)
    doc.addPageTemplates(main_template)
    doc.build(create_report(data))

    stream_buffer.seek(0)
    return stream_buffer
Exemple #34
0
 def get(self, request, *args, **kwargs):
     if not self.get_queryset().exists():
         messages.warning(request, _("You don't have any proposals yet."))
         return redirect(request.event.orga_urls.submissions)
     with tempfile.NamedTemporaryFile(suffix=".pdf") as f:
         doc = BaseDocTemplate(
             f.name,
             pagesize=A4,
             leftMargin=0,
             rightMargin=0,
             topMargin=0,
             bottomMargin=0,
         )
         doc.addPageTemplates([
             PageTemplate(
                 id="All",
                 frames=[
                     Frame(
                         0,
                         0,
                         doc.width / 2,
                         doc.height,
                         leftPadding=0,
                         rightPadding=0,
                         topPadding=0,
                         bottomPadding=0,
                         id="left",
                     ),
                     Frame(
                         doc.width / 2,
                         0,
                         doc.width / 2,
                         doc.height,
                         leftPadding=0,
                         rightPadding=0,
                         topPadding=0,
                         bottomPadding=0,
                         id="right",
                     ),
                 ],
                 pagesize=A4,
             )
         ])
         doc.build(self.get_story(doc))
         f.seek(0)
         timestamp = now().strftime("%Y-%m-%d-%H%M")
         r = HttpResponse(
             content_type="application/pdf",
             headers={
                 "Content-Disposition":
                 f'attachment; filename="{request.event.slug}_submission_cards_{timestamp}.pdf"'
             },
         )
         r.write(f.read())
         return r
Exemple #35
0
    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)
Exemple #36
0
    def _make_pdf(self) -> bytes:
        """
		Crea el pdf a partir de story. Ademas inicializa el doc con los estilo de las hojas y el tamaño.

		return pdf
		"""
        # La clase io.BytesIO permite tratar un array de bytes como un fichero binario,
        # se utiliza como almacenamiento temporal dentro de python, para luego ser descargado todo el dato como pdf
        pdf_buffer = BytesIO()
        #c = canvas.Canvas(buffer)
        doc = BaseDocTemplate(
            pdf_buffer,
            pagesize=A4)  # Se pasa el pdf_buffer al BaseDocTemplate
        frame0 = Frame(doc.leftMargin,
                       doc.bottomMargin,
                       doc.width,
                       doc.height,
                       showBoundary=0,
                       id='normalBorde')  # Frames o marcos de la pagina
        # Plantillas de las hojas, cabecera, pie de pagina, marco de la pagina. Se
        # puede tener varias plantillas. Siempre partira de la primera plantilla
        doc.addPageTemplates([
            PageTemplate(id='primera_hoja',
                         frames=frame0,
                         onPage=self._cabecera_1,
                         onPageEnd=self._pie_pagina),
            PageTemplate(id='contenido',
                         frames=frame0,
                         onPage=self._cabecera_contenido,
                         onPageEnd=self._pie_pagina)
        ])
        # Creamos las hojas de Estilos
        estilo = getSampleStyleSheet()
        estilo.add(
            ParagraphStyle(name="titulo_tablas_graficas",
                           alignment=TA_CENTER,
                           fontSize=15,
                           fontName="Helvetica-Bold",
                           textColor=colors.Color(0.0390625, 0.4921875,
                                                  0.69140625)))
        estilo.add(
            ParagraphStyle(name="texto",
                           alignment=TA_LEFT,
                           fontSize=12,
                           fontName="Helvetica",
                           textColor=colors.Color(0, 0, 0)))
        kargs = self._make_table_graphics(
            estilo)  # Dicionario con las tablas y graficas para el story
        story = self._make_story(**kargs)
        doc.build(story)  # Se construye el pdf con el array story
        #Descargando todo el buffer
        pdf = pdf_buffer.getvalue()
        pdf_buffer.close()
        return pdf
Exemple #37
0
    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)
Exemple #38
0
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)
Exemple #39
0
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 create_report(self, buff=None):
        def get_method(section):
            try:
                method = getattr(self, "_section_" + section)
            except AttributeError:
                raise Exception("Section method not found: " + section)
            return method

        def page_number(canv, doc):
            page_num = Paragraph(
                str(doc.page),
                extend_style(styles["rc-aawp-main-content"],
                             alignment=TA_CENTER,
                             fontSize=8),
            )
            page_num.wrapOn(canv, self.page_size[0], 0)
            page_num.drawOn(canv, 0, 4.8 * mm)

        if not buff:
            buff = io.BytesIO()

        story = []
        for section in self.sections:
            elems = get_method(section)()
            for elem in elems:
                story.append(elem)

        page_t = PageTemplate('normal', [
            Frame(
                self.page_margin[0],
                self.page_margin[1],
                self.page_size[0] - self.page_margin[0] * 2,
                self.page_size[1] - self.page_margin[1] * 2,
                leftPadding=0,
                bottomPadding=0,
                rightPadding=0,
                topPadding=0,
            )
        ],
                              onPage=page_number)
        doc_t = BaseDocTemplate(
            buff,
            pagesize=letter,
            title=self.title,
            author=self.author,
            leftMargin=self.page_margin[0],
            rightMargin=self.page_margin[0],
            topMargin=self.page_margin[1],
            bottomMargin=self.page_margin[1],
        )
        doc_t.addPageTemplates(page_t)
        doc_t.build(story)
        buff.seek(0)
        return buff
def seatingChartByStudent(request, id):
    mealTime = models.MealTime.objects.get(pk=id)

    allStudents = set(mealTime.allStudents())
    seenStudents = set()

    data = []

    for tableAssignment in mealTime.tableassignment_set.all():
        table = tableAssignment.table
        student = tableAssignment.student

        data.append((student.first_name, student.last_name, table.description))

        seenStudents.add(student)

    leftovers = [(s.first_name, s.last_name) for s in (allStudents - seenStudents)]
    leftovers.sort(key=lambda s: (s[1], s[0]))
    data.sort(key=lambda s: (s[1], s[0]))
        
    normal = getSampleStyleSheet()["Normal"]
    heading = getSampleStyleSheet()["Title"]
    heading.fontSize = 40
    
    story=[]
    story.append(Paragraph(mealTime.name, heading))
    story.append(FrameBreak())
    story.append(NextPageTemplate("twoCol"))
    
    for first, last, table in data:
        story.append(Paragraph("%s %s: %s" % (first, last, table), normal))
    
    out = BytesIO()
    doc = BaseDocTemplate(out, pagesize=letter, author="Rectory School Seating Chart Generator", title=mealTime.name)
    
    top = Frame(doc.leftMargin, doc.height, doc.width, 100)
    frame1 = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height-75, id='col1')
    frame2 = Frame(doc.leftMargin+doc.width/2+6, doc.bottomMargin, doc.width/2-6, doc.height-75, id='col2')
    doc.addPageTemplates([PageTemplate(id='topColHeader',frames=[top, frame1,frame2]), ])
    
    frame1 = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height, id='col1')
    frame2 = Frame(doc.leftMargin+doc.width/2+6, doc.bottomMargin, doc.width/2-6, doc.height, id='col2')
    doc.addPageTemplates([PageTemplate(id='twoCol',frames=[frame1,frame2]), ])
    
    #start the construction of the pdf
    doc.build(story)
    
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'filename="{mealTime:} by student.pdf"'.format(mealTime=mealTime.name)

    response.write(out.getvalue())

    return response
Exemple #42
0
def build_pdf(filename, flowables):
    doc = BaseDocTemplate(filename)
    doc.addPageTemplates([
        PageTemplate(frames=[
            Frame(doc.leftMargin,
                  doc.bottomMargin,
                  doc.width,
                  doc.height,
                  id=None),
        ]),
    ])
    doc.build(flowables)
    def draw(self, output, story):
        from reportlab.platypus import BaseDocTemplate, Frame, PageTemplate

        PAGE_SIZE = A4
        MARGIN_SIZE = 15 * mm
        doc = BaseDocTemplate(output, pagesize=PAGE_SIZE, leftMargin=MARGIN_SIZE, rightMargin=MARGIN_SIZE,
                              topMargin=MARGIN_SIZE, bottomMargin=MARGIN_SIZE)
        main_frame = Frame(MARGIN_SIZE, MARGIN_SIZE, PAGE_SIZE[0] - 2 * MARGIN_SIZE, PAGE_SIZE[1] - 2 * MARGIN_SIZE,
                           leftPadding=0, rightPadding=0, bottomPadding=0, topPadding=0, id='main_frame')
        main_template = PageTemplate(id='main_template', frames=[main_frame])
        doc.addPageTemplates([main_template])
        doc.build(story)
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)
Exemple #45
0
    def render(self, articles, outfile):
        """
        render list of articles as PDF into a byte file-like output.
        """
        story = []

        self.render_header(story)
        self.render_articles(articles, story)

        # build the pdf document
        # to show frame boundaries set showBoundary=1
        doc = BaseDocTemplate(outfile, title='', author='')

        # first page, has space for drawing header
        firstPageTemplate = PageTemplate(
            id='First',
            autoNextPageTemplate='Next',
            frames=[
                Frame(doc.leftMargin,
                      doc.bottomMargin + doc.height - self.header_height,
                      doc.width,
                      self.header_height,
                      id='header'),
                Frame(doc.leftMargin,
                      doc.bottomMargin,
                      doc.width / 2 - 6,
                      doc.height - self.header_height,
                      id='col1'),
                Frame(doc.leftMargin + doc.width / 2 + 6,
                      doc.bottomMargin,
                      doc.width / 2 - 6,
                      doc.height - self.header_height,
                      id='col2')
            ])

        laterPagesTemplate = PageTemplate(id='Next',
                                          frames=[
                                              Frame(doc.leftMargin,
                                                    doc.bottomMargin,
                                                    doc.width / 2 - 6,
                                                    doc.height,
                                                    id='col1'),
                                              Frame(doc.leftMargin +
                                                    doc.width / 2 + 6,
                                                    doc.bottomMargin,
                                                    doc.width / 2 - 6,
                                                    doc.height,
                                                    id='col2')
                                          ])

        doc.addPageTemplates([firstPageTemplate, laterPagesTemplate])

        doc.build(story)
Exemple #46
0
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
Exemple #47
0
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
Exemple #48
0
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)
Exemple #49
0
def create_pdfdoc(pdfdoc, story):  
        """ 
        Creates PDF doc from story. 
        """  
        pdf_doc = BaseDocTemplate(pdfdoc, pagesize = PAGE_SIZE,  
            leftMargin = MARGIN_SIZE, rightMargin = MARGIN_SIZE,  
            topMargin = MARGIN_SIZE, bottomMargin = MARGIN_SIZE)  
        main_frame = Frame(MARGIN_SIZE, MARGIN_SIZE,  
            PAGE_SIZE[0] - 2 * MARGIN_SIZE, PAGE_SIZE[1] - 2 * 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)  
Exemple #50
0
    def fill(self, fname, pagesize, events, topspace, bottomspace, margins):
        doc = BaseDocTemplate(fname, pagesize=pagesize, leftMargin=margins, bottomMargin=bottomspace, rightMargin=margins, topMargin=topspace)
        featured = Frame(doc.leftMargin+0.4*inch, doc.bottomMargin+2*doc.height/3, doc.width-6-0.8*inch,
                doc.height/3-0.4*inch, id="featured")
        left_column = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, 2*doc.height/3, id="left")
        right_column = Frame(doc.leftMargin+doc.width/2+6, doc.bottomMargin, doc.width/2-6, 2*doc.height/3, id="right")
        doc.addPageTemplates(PageTemplate(frames=[featured, left_column, right_column]))

        story = []
        story.append(XLEvent(events[0]).render())
        story.append(SpacerLine(3*inch, 0))
        story.append(FrameBreak())
        for e in events[1:]:
            story.append(Event(e).render())
        doc.build(story)
Exemple #51
0
 def create_pdfdoc(pdfdoc, story, with_watermark):
     def generate_watermark(canvas, doc):
         if not with_watermark: return
         canvas.saveState()
         canvas.setFont("Courier", 60)
         canvas.translate(700, 50)
         canvas.setFillGray(0.8, 0.5)
         canvas.rotate(45)
         for z in range(0, 1200, 60):
             canvas.drawCentredString(0, z, with_watermark)
         canvas.restoreState()
     pdf_doc = BaseDocTemplate(pdfdoc, pagesize=PAGE_SIZE, leftMargin=MARGIN_SIZE, topMargin=MARGIN_SIZE, rightMargin=MARGIN_SIZE, bottomMargin=MARGIN_SIZE)
     main_frame = Frame(MARGIN_SIZE, MARGIN_SIZE, PAGE_SIZE[0] - 2 * MARGIN_SIZE, PAGE_SIZE[1] - 2 * MARGIN_SIZE, leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0, id='mainframe')
     main_template = PageTemplate(id='maintemplate', frames=[main_frame], onPage=generate_watermark)
     pdf_doc.addPageTemplates([main_template])
     pdf_doc.build(story)
Exemple #52
0
def _create_cover_letter(cover_letter_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(cover_letter_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

    elements = []

    elements.append(Paragraph('Dear Sir/Madam', styles['Left']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(Paragraph('Congratulations, your Wildlife Licensing application has been approved and the '
                              'corresponding licence has been issued.', styles['Left']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(
        Paragraph("You'll find your licence document in this envelope. Please read it carefully.", styles['Left']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    # Removed link to online system for beta
    #     elements.append(Paragraph('You also can access it from your Wildlife Licensing dashboard by copying and pasting '
    #                     'the following link in your browser:', styles['Left']))
    #     elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    #     elements.append(Paragraph(site_url, styles['Left']))
    #     elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    #     elements.append(Paragraph("Note: If you haven't been on the Wildlife Licensing site recently you might have to "
    #                               "login first before using the provided link.", styles['Left']))
    #     elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    if licence.cover_letter_message:
        for message in licence.cover_letter_message.split('\r\n'):
            if message:
                elements.append(Paragraph(message, styles['Left']))
            else:
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    elements.append(Paragraph('Best regards,', styles['Left']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(Paragraph('Parks and Wildlife Customer Portal', styles['Left']))

    doc.build(elements)

    return cover_letter_buffer
Exemple #53
0
    def build(self, style=1):
        self.h1 = self.styleSheet['Heading1']
        self.h1.fontName = 'Helvetica'
        self.bv = self.styleSheet['BodyText']
        self.bv.fontName = 'Helvetica'
        self.bv.fontSize = 7
        self.bv.spaceBefore = 0
        self.bv.spaceAfter = 0

        self.header = self.styleSheet['Heading3']
        self.header.fontName = 'Helvetica'

        self.data.append(Paragraph(translation.t(self.language, 'mediatumhelptitle'), self.h1))
        self.data.append(Paragraph(self.path, self.bv))

        self.data.append((FrameBreak()))

        # format content
        self.content = self.content.replace("\n", "")
        repl = {'p': 'BodyText', 'h1': 'Heading1', 'h2': 'Heading2', 'h3': 'Heading3', 'h4': 'Heading4', 'h5': 'Heading5', 'li': 'Bullet'}
        curstyle = "BodyText"
        for item in re.split(r'<(p|h[1-5]|li)>|<(/p|/h[1-5]|/li)>', self.content):
            if item and item != "":
                if item in repl.keys():
                    curstyle = repl[item]
                elif item[0] == "/" and item[1:] in repl.keys():
                    curstyle = ""
                else:
                    if item.strip != "" and curstyle != "":
                        print 'add', item, "-->", curstyle
                        if curstyle == "Bullet":
                            item = "- " + item
                            print "bullet", item
                        self.data.append(Paragraph(item, self.styleSheet[curstyle]))

        template = SimpleDocTemplate(config.get("paths.tempdir", "") + "help.pdf", showBoundary=0)
        tFirst = PageTemplate(id='First', onPage=self.myPages, pagesize=defaultPageSize)
        tNext = PageTemplate(id='Later', onPage=self.myPages, pagesize=defaultPageSize)

        template.addPageTemplates([tFirst, tNext])
        template.allowSplitting = 1
        BaseDocTemplate.build(template, self.data)

        template.canv.setAuthor(translation.t(self.language, "main_title"))
        template.canv.setTitle("%s \n'%s' - %s: %s" % (translation.t(self.language, "edit_stats_header"),
                                                       'sdfsdfsdf', translation.t(self.language, "edit_stats_period_header"), '2003'))
        return template.canv._doc.GetPDFData(template.canv)
Exemple #54
0
class Sheet:
    """
    Base class for sheets of labels.
    """
    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 __call__(self, data):
        # table style for outer table is middle center
        ts = [('ALIGN', (0, 0), (0, 0), 'CENTER'), ('VALIGN', (0, 0), (0, 0), 'MIDDLE')]
        # labels are list of tables containing actual rendered records
        Sheet = [Table([[record.render(self)]], style=ts, colWidths=self.labelw, rowHeights=self.labelh) for record in data]
        self.doc.build(Sheet)
Exemple #55
0
def __generar_pdf_general(response, docParametros, elementsFilaPage):
    buff = BytesIO()

    # frame_A4_Vertical = Frame(inch/3, inch/3, 555, 805, id='normal', showBoundary=0)
    # Frame_A5_Horizontal = Frame(inch/2, 20, 530, 375, id='a5', showBoundary=0)
    # Frame_A5_vertical = Frame(inch/3, inch/3, 384, 562, id='a5', showBoundary=0)
    doc = BaseDocTemplate(buff, pagesize=docParametros['pagesize'], title=docParametros['title'])
    if (docParametros['pagesize'] == A4 and docParametros['title'] not in 'Reporte Kardex'):
        print ("a4 v")
        doc.addPageTemplates([
            PageTemplate(id='cabecera', frames=Frame(inch/3, inch/3, 555, 805, id='normal', showBoundary=0),
                         onPage=__encabezado_A4_Vertical),
        ]
        )
    elif (docParametros['pagesize'] == landscape(A5)):
        print ("a5 h")
        doc.addPageTemplates([
            PageTemplate(id='cabecera', frames=Frame(inch/2, 20, 530, 375, id='a5', showBoundary=0),
                         onPage=__encabezado_A5_Horizontal),
        ]
        )
    elif (docParametros['pagesize'] == A5):
        print ("a5 v")
        doc.addPageTemplates([
            PageTemplate(id='cabecera', frames=Frame(inch/3, inch/3, 384, 562, id='a5', showBoundary=0),
                         onPage=__encabezado_A5_Vertical),
        ]
        )
    else:
        print ('cualquier papel sin encabezado')
        doc = SimpleDocTemplate(buff, pagesize=docParametros['pagesize'], rightMargin=20, leftMargin=20, topMargin=20,
                                bottomMargin=20, showBoundary=0,
                                title=docParametros['title'],)

    story = []
    #story.append(Spacer(0, 50))

    for i in elementsFilaPage:
         story.append(i)

    doc.build(story)
    response.write(buff.getvalue())
    #response.write()
    #mail.attach('factuJose.pdf', buff.getvalue(), 'application/pdf')
    #mail.send()
    buff.close()
    return response
Exemple #56
0
def listin_telefonico(request, curso=None, grupo=None):
    if not curso:
        curso = request.session.get('curso_academico').get('pk')
    else:
        curso_qs = Curso.objects.filter(slug=curso)
        if curso_qs:
            curso = curso_qs[0].id
        else:
            raise Http404
    alumnos = CursoGrupoAlumno.objects.filter(curso_grupo__curso_id=curso).order_by('curso_alumno__alumno')
    if grupo:
        alumnos = alumnos.filter(curso_grupo__grupo__grupo=grupo).order_by('curso_alumno__alumno')
    if len(alumnos) == 0:
        raise Http404
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')
    # response['Content-Disposition'] = 'attachment; filename="listin.pdf"'
    response['Content-Disposition'] = 'filename="listin.pdf"'
    # Create the PDF object, using the response object as its "file."
    buff = BytesIO()
    styles = getSampleStyleSheet()
    Elements = []
    doc = BaseDocTemplate(buff, leftMargin=2 * cm, rightMargin=0.5 * cm,
                          topMargin=2 * cm, bottomMargin=1 * cm, showBoundary=0)
    cabecera1 = request.session.get('centro', Configies.objects.all()[0].nombre_centro)
    cabecera2 = "Curso " + str(alumnos[0].curso_grupo.curso) + " - Listado telefónico de alumno/as " + (
    ("- Grupo: " + grupo) if grupo else "")

    def cabeceraYpie(canvas, doc):
        canvas.saveState()
        canvas.setFont('Helvetica-Bold', 14)
        canvas.drawCentredString(21 * cm / 2, 29 * cm, cabecera1)
        canvas.drawCentredString(21 * cm / 2, 28 * cm, cabecera2)
        canvas.setFont('Times-Roman', 10)
        canvas.drawCentredString(21 * cm / 2, cm, "Página {}".format(doc.page))
        canvas.restoreState()

    # normal frame as for SimpleFlowDocument
    frameT = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, id='normal')
    for alumno in alumnos:
        Elements.append(EntradaListin(alumno=alumno))
    doc.addPageTemplates([PageTemplate(id='OneCol', frames=frameT, onPage=cabeceraYpie)])
    # start the construction of the pdf
    doc.build(Elements)
    response.write(buff.getvalue())
    buff.close()
    return response
Exemple #57
0
    def create(self):
        from reportlab.platypus import BaseDocTemplate, PageTemplate
        from reportlab.lib.units import mm

        with tempfile.NamedTemporaryFile(suffix=".pdf") as f:
            Report.register_fonts()
            doc = BaseDocTemplate(f.name, pagesize=self.pagesize,
                                  leftMargin=15 * mm,
                                  rightMargin=15 * mm,
                                  topMargin=20 * mm,
                                  bottomMargin=15 * mm)
            doc.addPageTemplates([
                PageTemplate(id='All', frames=self.get_frames(doc), onPage=self.on_page, pagesize=self.pagesize)
            ])
            doc.build(self.get_story(doc))
            f.seek(0)
            return f.read()
Exemple #58
-1
    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)