コード例 #1
0
ファイル: pdffill.py プロジェクト: hesrerem/pdffill
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)
コード例 #2
0
ファイル: executive.py プロジェクト: pianodaemon/knight-rider
    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
コード例 #3
0
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)
コード例 #4
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)
コード例 #5
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)
コード例 #6
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
コード例 #7
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"
コード例 #8
0
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)
コード例 #9
0
ファイル: pdffill.py プロジェクト: hesrerem/pdffill
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)
コード例 #10
0
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)
コード例 #11
0
def create_doc(frame_num):
    doc = BaseDocTemplate(
        'medium_highlights.pdf',
        pagesize=A4,
        topMargin=1*inch,
        bottomMargin=1*inch,
        leftMargin=0.5*inch,
        rightMargin=0.5*inch)

    frameCount = frame_num
    frameWidth = (doc.width- 0.1*inch) / frameCount
    frameHeight = doc.height - 0.05*inch

    frame_list = [
        Frame(
            x1=doc.leftMargin,
            y1=doc.bottomMargin,
            width=frameWidth,
            height=frameHeight),
        Frame(
            x1=doc.leftMargin + frameWidth + 0.1*inch,
            y1=doc.bottomMargin,
            width=frameWidth,
            height=frameHeight),
    ]
    template = platypus.PageTemplate(frames=frame_list)
    doc.addPageTemplates(template)

    return doc
コード例 #12
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)
コード例 #13
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)
コード例 #14
0
ファイル: test.py プロジェクト: priya-I/ReadyMade
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
コード例 #15
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
コード例 #16
0
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)
コード例 #17
0
ファイル: p0149.py プロジェクト: pythonpatterns/patterns
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)
コード例 #18
0
ファイル: pdf.py プロジェクト: Make-Munich/postix
def get_default_document(_buffer, footer: str = None) -> BaseDocTemplate:
    def on_page(canvas, doc, footer=footer):
        canvas.saveState()
        if footer:
            canvas.setFontSize(8)
            for i, line in enumerate(footer.split('\n')[::-1]):
                canvas.drawCentredString(PAGESIZE[0] / 2, 25 + (3.5 * i) * mm,
                                         line.strip())
            canvas.restoreState()

    doc = BaseDocTemplate(
        _buffer,
        pagesize=PAGESIZE,
        leftMargin=25 * mm,
        rightMargin=20 * mm,
        topMargin=20 * mm,
        bottomMargin=20 * mm,
    )
    frame = Frame(doc.leftMargin,
                  doc.bottomMargin,
                  doc.width,
                  doc.height,
                  leftPadding=0,
                  rightPadding=0,
                  topPadding=0,
                  bottomPadding=0,
                  id='normal')
    doc_template = PageTemplate(id='all',
                                pagesize=PAGESIZE,
                                frames=[frame],
                                onPage=on_page)
    doc.addPageTemplates([doc_template])
    return doc
コード例 #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)
コード例 #20
0
ファイル: reporteVertical.py プロジェクト: mfreyeso/SIPREM
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
コード例 #21
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)
コード例 #22
0
ファイル: Reporter.py プロジェクト: timjordan37/AnyScan
    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)
コード例 #23
0
ファイル: viewsdata.py プロジェクト: zeppter0/zeppter
    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")
コード例 #24
0
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)
コード例 #25
0
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
コード例 #26
0
ファイル: layouts.py プロジェクト: 12foo/event-flyer-factory
    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)
コード例 #27
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
コード例 #28
0
class MyPDFdoc():
    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 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
コード例 #30
0
ファイル: report.py プロジェクト: Jonamaita/TrackMantos
    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
コード例 #31
0
ファイル: layouts.py プロジェクト: 12foo/event-flyer-factory
    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)
コード例 #32
0
ファイル: layouts.py プロジェクト: 12foo/event-flyer-factory
    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)
コード例 #33
0
    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)
コード例 #34
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)
コード例 #35
0
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
コード例 #36
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)
コード例 #37
0
ファイル: crhPDF.py プロジェクト: ciscrh/python-crhLib
def pdfDocTemplate(filename):
    """create document template sized as required"""

    doc = BaseDocTemplate(filename, pagesize = pdfPageSz, 
        leftMargin = pdfMargin, rightMargin = pdfMargin, topMargin = pdfMargin, 
        bottomMargin = pdfMargin, creator = gv.getVar('progName'),
        author = pdfAuthorTxt, subject = pdfSubjectTxt, title = pdfTitleTxt, 
        keywords = pdfKeywordsTxt, pageCompression = 1)
    # normal frame as for SimpleFlowDocument
    frameN = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, id='normal')
    doc.addPageTemplates([PageTemplate(id = 'all',frames = frameN, onPage = allPages)])
    return doc
コード例 #38
0
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)
コード例 #39
0
ファイル: reputils.py プロジェクト: sdrewe/python-dev
def build_pdf(filename, content):
    doc = BaseDocTemplate(filename, showBoundary=0)
    # doc.watermark = 'Draft'
    doc.addPageTemplates([
        PageTemplate(frames=[
            Frame(doc.leftMargin,
                  doc.bottomMargin,
                  doc.width,
                  doc.height,
                  id=None),
        ]),
    ])
    doc.build(content, canvasmaker=NumberedCanvas)
コード例 #40
0
def report_gen(body, title, httpresponse, user):
    styles = getSampleStyleSheet()
    styleNormal = styles['Normal']
    styleHeading = styles['Heading1']
    styleHeading.alignment = 1
    num_rows = len(body) - 1
    total_pages = (num_rows // 29) + 1

    def head_footer(canvas, doc):
        canvas.saveState()
        P = Paragraph(
            "Report Generated: {}    By: {} - Stock Database V{}".format(
                datetime.datetime.today().strftime("%d/%m/%Y"), user,
                __version__), styleNormal)
        w, h = P.wrap(doc.width, doc.bottomMargin)
        P.drawOn(canvas, doc.leftMargin, h)
        P = Paragraph(
            "Page {} of {}".format(canvas.getPageNumber(), total_pages),
            styleNormal)
        w, h = P.wrap(doc.width, doc.bottomMargin)
        P.drawOn(canvas, doc.width + doc.leftMargin, h)

        P = Paragraph("{}".format(title), styleHeading)
        w, h = P.wrap(doc.width + doc.leftMargin + doc.rightMargin,
                      doc.topMargin)
        P.drawOn(canvas, 0, doc.height + doc.topMargin)
        #canvas.drawCentredString((doc.width+doc.leftMargin+doc.rightMargin)/2.0, doc.height+doc.topMargin, title)
        #pdb.set_trace()
        canvas.restoreState()

    TABLE = Table(data=body, repeatRows=1)
    TABLE.setStyle(
        TableStyle([('FONTSIZE', (0, 0), (-1, -1), 8),
                    ('ALIGN', (0, 0), (-1, -1), "CENTER")]))
    table = []
    table.append(TABLE)
    doc = BaseDocTemplate(httpresponse,
                          topMargin=12,
                          bottomMargin=20,
                          pagesize=landscape(A4))

    frame = Frame(doc.leftMargin,
                  doc.bottomMargin,
                  doc.width,
                  doc.height,
                  id='normal')
    template = PageTemplate(id='table', frames=frame, onPage=head_footer)
    doc.addPageTemplates([template])

    doc.build(table)
    return doc
コード例 #41
0
def create_pdf():

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

    # 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=[[[I], [I], [I]],
                [[I], [I], [I]],
                [[I], [I], [I]]]
    # Create a table
    CatBox = Table(table_data, 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("BottomAlignTable.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)
コード例 #42
0
ファイル: layouts.py プロジェクト: 12foo/event-flyer-factory
    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)
コード例 #43
0
ファイル: print2.py プロジェクト: liyang19901122/GMS
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)  
コード例 #44
0
ファイル: bor_generator.py プロジェクト: icucinema/cintranet
 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)
コード例 #45
0
ファイル: listados.py プロジェクト: pkom/gesties
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
コード例 #46
0
ファイル: labels.py プロジェクト: mathuin/pyment
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)
コード例 #47
0
ファイル: __init__.py プロジェクト: jeffbaumes/schoolplanner
def _create_pdfdoc(pdfdoc, story):
    """
    Creates PDF doc from story.
    """
    pdf_doc = BaseDocTemplate(
        pdfdoc, pagesize=letter,
        leftMargin=inch, rightMargin=inch,
        topMargin=inch, bottomMargin=inch)
    main_frame = Frame(
        inch, inch,
        letter[0] - 2 * inch, letter[1] - 2 * inch,
        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)
コード例 #48
0
ファイル: exporters.py プロジェクト: JRodDynamite/pretix
    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()
コード例 #49
0
ファイル: RiskManagement.py プロジェクト: sgros/RMT
def main(xmlDir):
	riskManagement = RiskManagement(xmlDir)

	print "Generating PDF report"
	pdfmetrics.registerFont(TTFont('FreeSans', '/usr/share/fonts/gnu-free/FreeSans.ttf'))
	pdfmetrics.registerFont(TTFont('FreeSans-Bold', '/usr/share/fonts/gnu-free/FreeSansBold.ttf'))
	pdfmetrics.registerFont(TTFont('FreeSans-Italic', '/usr/share/fonts/gnu-free/FreeSansOblique.ttf'))
	pdfmetrics.registerFont(TTFont('FreeSans-BoldItalic', '/usr/share/fonts/gnu-free/FreeSansBoldOblique.ttf'))

	# ['BodyText', 'Code', 'Bullet', 'Title', 'Normal', 'Definition', 'Heading6', 'Heading4', 'Heading5', 'Heading2', 'Heading3', 'Italic', 'Heading1']
	styles = getSampleStyleSheet()
	styles['Heading1'].fontName = 'FreeSans-Bold'
	styles['Heading2'].fontName = 'FreeSans-Bold'
	styles['Heading3'].fontName = 'FreeSans-Bold'
	styles['Heading4'].fontName = 'FreeSans-Bold'
	styles['Heading5'].fontName = 'FreeSans-Bold'
	styles['BodyText'].fontName = 'FreeSans'
	#styles['Heading1'].backColor = colors.red
	#styles['Heading2'].backColor = colors.red
	#styles['Heading3'].backColor = colors.red
	styles['Heading4'].backColor = colors.red
	#styles['Heading5'].backColor = colors.red
	doc = BaseDocTemplate('RiskAssessmentReport.pdf', pagesize=A4)
	frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, id='normal')
	template = PageTemplate(id='test', frames=frame)
	doc.addPageTemplates([template])
	pageElements = []
	pageElements.extend(riskManagement.getRisksByResourceReportInPDF(doc, styles))
	pageElements.append(PageBreak())
	pageElements.extend(riskManagement.getInformationSourcesReportInPDF(doc, styles))
	pageElements.append(PageBreak())
	pageElements.extend(riskManagement.getThreatReportInPDF(doc, styles))
	pageElements.append(PageBreak())
	pageElements.extend(riskManagement.getVulnerabilityReportInPDF(doc, styles))
	doc.build(pageElements)

	#dumpInformationSources(riskManagement)
	#dumpThreats(riskManagement)
	#dumpVulnerabilities(riskManagement)
	#dumpIdentifiedThreats(riskManagement)
	#dumpIdentifiedVulnerabilities(riskManagement)
	#dumpIdentifiedRisks(riskManagement)
	#dumpIdentifiedRisksByResource(riskManagement)
	#dumpIdentifiedRiskForOrganization(riskManagement)
	dumpIdentifiedRisksByResourceHierarchy(riskManagement, "r00000")
コード例 #50
0
ファイル: p0159.py プロジェクト: pythonpatterns/patterns
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)
コード例 #51
0
ファイル: namepdf.py プロジェクト: acspike/Arpeggio
def make_page(clef, note):
    #create the basic page and frames
    doc = BaseDocTemplate('name_'+clef+note+'.pdf', pagesize=(4.25*inch,2.75*inch), leftMargin=0, bottomMargin=0, topMargin=0, rightMargin=0)
    margin = 0.25 * inch
    frameCount = 1
    frameWidth = (doc.width / frameCount) - (2.0 * margin)
    frameHeight = doc.height
    frames = []
    #construct a frame for each column
    for frame in range(frameCount):
        leftMargin = margin + frame * (frameWidth + (2.0 * margin))
        column = Frame(leftMargin, doc.bottomMargin, frameWidth, frameHeight, topPadding=0, bottomPadding=0, rightPadding=0, leftPadding=0)
        frames.append(column)
    
        template = PageTemplate(frames=frames)
    doc.addPageTemplates(template) 
    
    story = [CText(frameWidth,2.75*inch,note.upper(),clef + ' clef')]
    doc.build(story)
コード例 #52
0
ファイル: p0148.py プロジェクト: pythonpatterns/patterns
def build_pdf(filename):
    doc = BaseDocTemplate(filename)
    doc.addPageTemplates(
        [
            PageTemplate(
                frames=[
                    Frame(
                        doc.leftMargin,    # x
                        doc.bottomMargin,  # y 
                        doc.width,         # frame width
                        doc.height,        # frame height
                        id=None
                    ),
                ]
            ),
        ]
    )
    flowables = [
        Paragraph('some text. ' * 20, ParagraphStyle('default')),
    ]
    doc.build(flowables)
コード例 #53
0
def makeMapCutOut():
    ''' Make PDF of PocketPidge's generic Map insert. '''

    posts = []
    pageHeight, pageWidth = A4
    A4_Landscape = [pageWidth, pageHeight]

    formPages = (
    CareersInfo(None),
    UsefulInformation(None),
    CareersInfo(None),
    UsefulInformation(None),
    CareersInfo(None),
    UsefulInformation(None),
    CareersInfo(None),
    UsefulInformation(None),
    TownMapLeft(None),
    TownMapRight(None),
    TownMapLeft(None),
    TownMapRight(None),
    TownMapLeft(None),
    TownMapRight(None),
    TownMapLeft(None),
    TownMapRight(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("map.pdf", pagesize=A4_Landscape)
    template = PageTemplate(frames=createFrames(pageWidth, pageHeight, 4, 2))
    document.addPageTemplates(template)
    document.build(posts)
コード例 #54
0
ファイル: views.py プロジェクト: SevenKeys/Invoices
def print_preview(request):
    output = BytesIO()
    doc = BaseDocTemplate(output, pagesize=size)
    pdf = Pdf(json.loads(request.GET[COMPONENTS]), size[1], inch, .50)

    def frame(canvas, doc):
        pdf.header_footer(canvas)
    doc.addPageTemplates([PageTemplate(frames=Frame(doc.leftMargin, pdf.body_y(), doc.width, pdf.body_y_size()), onPage=frame)])
    story = []
    products = [['Description', 'Category', 'Unit prize', 'Units', 'Tax', 'Amount']]
    for i in range(40):
        products.append(['Product %s' % i, 'Category %s' % i, i, i, i, i])
    table = Table(products)
    table.setStyle(build_table_style(ArchetypeField.objects.filter(archetype=request.GET['archetype'])))
    story.append(table)
    doc.build(story)
    pdf_output = output.getvalue()
    output.close()
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
    response.write(pdf_output)
    return response
コード例 #55
0
ファイル: pdf.py プロジェクト: ECAConcordia/internal-webapp
class PDFReceipt:

    def __init__(self, receipt):
        global receipt_info
        if type(receipt) is not Receipt:
            raise ValueError('receipt passed to PDFReceipt is not, in fact, a Receipt object')
        self.story = []
        self.receipt = receipt
        receipt_info = self.make_receipt_details()
        self.filename = path_join(RECEIPT_DOCS_DIR, 'Receipt %i.pdf') % (int(self.receipt.pk), )
        self.b = BaseDocTemplate(self.filename, pagesize=letter)
        self.f1 = Frame(0.5*inch, 0.5*inch, 7.5*inch, 7.5*inch, showBoundary=1)
        self.p = PageTemplate(id='t1', frames=[self.f1, ], onPage=receipt_details)
        self.b.addPageTemplates(self.p)
        self.make_story()
        self.b.build(self.story)

    def make_story(self):
        rows = [['Item', 'Quantity', 'Unit cost', 'Amount'], ]
        for lineitem in self.receipt.lineitem_set.all():
            rows.append([
                str(lineitem.item.name),
                str(lineitem.quantity),
                "$%.2f" % lineitem.item.cost,
                "$%.2f" % lineitem.amount])
        rows.append(['', '', Paragraph('<b>TOTAL</b>', styles['Normal']), Paragraph("<b>$%.2f</b>" % self.receipt.receipt_total(), styles['Normal'])])
        t = Table(rows, repeatRows=1, splitByRow=True, colWidths=[3.5*inch, 1*inch, 1*inch, 1*inch], style=[('ALIGN', (1, 0), (-1, -1), 'RIGHT'),])
        self.story.append(t)

    def make_receipt_details(self):
        return [
            ['Date', self.receipt.timestamp.strftime('%B %d, %Y')],
            ['Purchaser', Paragraph(self.receipt.buyer.full_name, styles['Normal'])],
            ['Payment method', self.receipt.paymeth],
            ['Employee', Paragraph("%s %s" % (self.receipt.seller.first_name, self.receipt.seller.last_name), styles['Normal'])],
            ['Receipt #', str(self.receipt.pk)],
        ]
コード例 #56
0
def makePromo():
    ''' Make PDF of MyPidge promotional flyer. '''
    posts = []
    pageHeight, pageWidth = A4
    A4_Landscape = [pageWidth, pageHeight]
    formPages = (
    PromoFront(None),
    PromoFront(None),
    PromoFront(None),
    PromoFront(None),
    PromoFront(None),
    PromoFront(None),
    PromoFront(None),
    PromoFront(None),
    PromoBack(None),
    PromoBack(None),
    PromoBack(None),
    PromoBack(None),
    PromoBack(None),
    PromoBack(None),
    PromoBack(None),
    PromoBack(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("promo.pdf", pagesize=A4_Landscape)
    template = PageTemplate(frames=createFrames(pageWidth, pageHeight, 4, 2))
    document.addPageTemplates(template)
    document.build(posts)
コード例 #57
0
ファイル: box.py プロジェクト: kihamo/coins
    def draw(self, file):
        self._init_document()

        doc = BaseDocTemplate(file, pagesize=A4, title='Boxes', showBoundary=1)

        page_width, page_height = doc.pagesize

        box_params = {
            'width': self.width,
            'height': self.height,
            'showBoundary': 1
        }

        box1_params = {
            'x1': .5 * cm,
            'y1': page_height - self.height - .5 * cm
        }

        box2_params = {
            'x1': .5 * cm,
            'y1': page_height - (self.height - .5 * cm) * 2
        }

        box1_params.update(box_params)
        box2_params.update(box_params)

        box1_frame = Frame(**box1_params)
        box2_frame = Frame(**box2_params)

        doc.addPageTemplates(PageTemplate(frames=box1_frame))
        doc.addPageTemplates(PageTemplate(frames=box2_frame))

        elements = [
            Paragraph(self.coin.issue.name, self.styles.get('Justify'))
        ]
        doc.build(elements)
コード例 #58
0
ファイル: reportes.py プロジェクト: brayanL/SICEM
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
コード例 #59
0
ファイル: printing.py プロジェクト: alfredo/django-badger
def _real_render(request, stream, slug, claim_group, deferred_awards, debug,
                 scale_factor=1.0):
    """Render the pages of badge codes."""
    doc = BaseDocTemplate(stream, topMargin=0, bottomMargin=0,
                          leftMargin=0, rightMargin=0, allowSplitting=0)
    
    if debug: show_boundary = 1
    else: show_boundary = 0

    # Build frames for labels in the template
    frames = []
    for r_idx in range(0, rows):
        for c_idx in range(0, columns):
            left_pos = left_margin + (c_idx * (width + horizontal_spacing))
            top_pos = (top_margin + (r_idx * (height + vertical_spacing)))
            frames.append(Frame(
                left_pos, top_pos, width, height,
                leftPadding=0, rightPadding=0,
                bottomPadding=0, topPadding=0,
                showBoundary=show_boundary
            ))

    # Add the template to the page.
    template = PageTemplate(pagesize=page_size, frames=frames)
    doc.addPageTemplates(template)

    # Fill out the template with claim codes.
    items = []
    for da in deferred_awards:
        badge = da.badge
        award_url = request.build_absolute_uri(da.get_claim_url())

        image_fin = badge.image.file
        image_fin.open()
        badge_img = StringIO(image_fin.read())

        # TODO: Stop abusing the Google Charts API and get our own QR code
        # baking on premises.
        try:
            qr_url = ("http://api.qrserver.com/v1/create-qr-code/?%s" %
                urllib.urlencode({'size':'%sx%s' % (250, 250), 
                                  'data':award_url}))
            qr_img = StringIO(urllib2.urlopen(qr_url).read())
        except Exception, e:
            return HttpResponse('QR code generation failed: %s' % e,
                                status=500)

        # Build the badge label out as a table...
        table_data = (
            (
                (
                    Image(badge_img, 0.75 * inch * scale_factor,
                          0.75 * inch * scale_factor),
                    resize_para(badge.title, 
                          max_width=1.75 * inch * scale_factor),
                ),
                (
                    Image(qr_img, 0.6 * inch, 0.6 * inch),
                    Paragraph(request.build_absolute_uri('/'), ParagraphStyle(
                        name='normal', alignment=TA_CENTER,
                        fontName='Helvetica', fontSize=8, leading=8)),
                    Paragraph(da.claim_code.upper(), ParagraphStyle(
                        name='code', alignment=TA_CENTER,
                        fontName='Courier', fontSize=11, leading=11)),
                ),
            ),
        )

        table_style = (
            ('ALIGN', (0,0), (-1,-1), 'CENTER'),  
        )

        if debug:
            table_style = table_style + (
                ('GRID', (0,0), (-1,-1), 1, colors.black),  
            )

        items.append(Table(table_data, style=table_style))
        items.append(FrameBreak())
コード例 #60
-1
ファイル: layouts.py プロジェクト: 12foo/event-flyer-factory
    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)