Python reportlab.platypus 模块,SimpleDocTemplate() 实例源码

我们从Python开源项目中,提取了以下36个代码示例,用于说明如何使用reportlab.platypus.SimpleDocTemplate()

项目:ZLib    作者:zenist    | 项目源码 | 文件源码
def test_11_drawing(self):
        from reportlab.lib.styles import getSampleStyleSheet
        from reportlab.lib import colors
        from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph
        from reportlab.pdfbase import pdfmetrics
        from reportlab.graphics.shapes import Drawing, Rect
        from reportlab.pdfbase.ttfonts import TTFont

        pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc'))
        stylesheet = getSampleStyleSheet()

        elements = []
        doc = SimpleDocTemplate("demo.pdf")

        elements.append(Paragraph('<font name="chsFont">JY.zenist.song - ??</font>', stylesheet['Title']))
        elements.append(Spacer(1,12))

        d = Drawing(400,200)
        d.add(Rect(50,50,300,100, fillColor=colors.yellow))
        elements.append(d)

        doc.build(elements)
项目:king-phisher-plugins    作者:securestate    | 项目源码 | 文件源码
def process_attachment_file(self, input_path, output_path, target=None):
        output_path, _ = os.path.splitext(output_path)
        output_path += '.pdf'

        pdf_file = platypus.SimpleDocTemplate(
            output_path,
            pagesize=letter,
            rightMargin=72,
            leftMargin=72,
            topMargin=72,
            bottomMargin=18
        )

        url = self.application.config['mailer.webserver_url']
        if target is not None:
            url += '?uid=' + target.uid

        try:
            pdf_template = self.get_template(input_path, url)
            pdf_file.multiBuild(pdf_template)
        except Exception as err:
            self.logger.error('failed to build the pdf document', exc_info=True)
            return
        self.logger.info('wrote pdf file to: ' + output_path + ('' if target is None else ' with uid: ' + target.uid))
        return output_path
项目:callisto-core    作者:project-callisto    | 项目源码 | 文件源码
def generate_pdf_report(self, report_id, recipient):
        # PREPARE PDF
        report_buffer = BytesIO()
        doc = SimpleDocTemplate(
            report_buffer,
            pagesize=letter,
            rightMargin=72, leftMargin=72,
            topMargin=72, bottomMargin=72,
        )

        # COVER PAGE
        self.pdf_elements.extend(
            api.NotificationApi.get_cover_page(
                report_id=report_id,
                recipient=recipient,
            ),
        )

        # METADATA PAGE
        self.pdf_elements.extend(self.get_metadata_page(recipient))

        # REPORT
        self.pdf_elements.extend(
            [Paragraph("Report Questions", self.section_title_style)],
        )
        for item in self.report_data:
            question, answers = item.popitem()
            self.render_question(question, answers)

        doc.build(
            self.pdf_elements,
            onFirstPage=self.get_header_footer(recipient),
            onLaterPages=self.get_header_footer(recipient),
            canvasmaker=NumberedCanvas,
        )
        result = report_buffer.getvalue()
        report_buffer.close()
        return result
项目:tambox    作者:joseamaya    | 项目源码 | 文件源码
def imprimir(self):
        buffer = self.buffer
        doc = SimpleDocTemplate(buffer,
                                rightMargin=50,
                                leftMargin=50,
                                topMargin=20,
                                bottomMargin=50,
                                pagesize=self.pagesize)

        elements = []
        styles = getSampleStyleSheet()
        elements.append(self.tabla_encabezado(styles))
        elements.append(Spacer(1, 0.25 * cm))
        elements.append(self.tabla_datos(styles))
        elements.append(Spacer(1, 0.25 * cm))
        elements.append(self.tabla_detalle())
        elements.append(Spacer(1, 0.25 * cm))
        elements.append(self.tabla_observaciones())
        elements.append(Spacer(1, 0.25 * cm))
        elements.append(self.tabla_firmas())
        doc.build(elements)
        pdf = buffer.getvalue()
        buffer.close()
        return pdf
项目:tambox    作者:joseamaya    | 项目源码 | 文件源码
def imprimir_formato_consolidado_productos(self):
        buffer = self.buffer
        doc = SimpleDocTemplate(buffer,
                                rightMargin=50,
                                leftMargin=50,
                                topMargin=100,
                                bottomMargin=50,
                                pagesize=self.pagesize)

        elements = []
        productos = Producto.objects.all().order_by('descripcion')
        elements.append(self.tabla_detalle_consolidado_productos(productos))
        doc.build(elements, onFirstPage=self._header_footer, onLaterPages=self._header_footer)
        pdf = buffer.getvalue()
        buffer.close()
        return pdf
项目:tambox    作者:joseamaya    | 项目源码 | 文件源码
def imprimir_formato_consolidado_grupos(self):
        buffer = self.buffer
        doc = SimpleDocTemplate(buffer,
                                rightMargin=50,
                                leftMargin=50,
                                topMargin=100,
                                bottomMargin=50,
                                pagesize=self.pagesize)

        elements = []
        grupos = GrupoProductos.objects.filter(estado=True,
                                               son_productos=True).order_by('descripcion')
        elements.append(self.tabla_detalle_consolidado_grupo(grupos))

        doc.build(elements, onFirstPage=self._header_footer, onLaterPages=self._header_footer)
        pdf = buffer.getvalue()
        buffer.close()
        return pdf
项目:tichu-tournament    作者:aragos    | 项目源码 | 文件源码
def convertSourceFiles(filenames):
    "Helper function - makes minimal PDF document"

    from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, XPreformatted
    from reportlab.lib.styles import getSampleStyleSheet
    styT=getSampleStyleSheet()["Title"]
    styC=getSampleStyleSheet()["Code"]
    doc = SimpleDocTemplate("pygments2xpre.pdf")
    S = [].append
    for filename in filenames:
        S(Paragraph(filename,style=styT))
        src = open(filename, 'r').read()
        fmt = pygments2xpre(src)
        S(XPreformatted(fmt, style=styC))
    doc.build(S.__self__)
    print('saved pygments2xpre.pdf')
项目:ZLib    作者:zenist    | 项目源码 | 文件源码
def test_09_docTemplate(self):
        from reportlab.lib.styles import getSampleStyleSheet
        from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph
        from reportlab.pdfbase import pdfmetrics
        from reportlab.pdfbase.ttfonts import TTFont

        pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc'))
        stylesheet = getSampleStyleSheet()

        elements = []
        doc = SimpleDocTemplate("demo.pdf")

        elements.append(Paragraph('<font name="chsFont">AUT OOM????</font>', stylesheet['Title']))
        elements.append(Spacer(1,12))

        doc.build(elements)
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def main():
    import sys
    import urllib2
    from cStringIO import StringIO
    from reportlab.platypus import SimpleDocTemplate, Image, Paragraph, PageBreak
    from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet

    #This is needed because ReportLab accepts the StringIO as a file-like object,
    #but doesn't accept urllib2.urlopen's return value
    def get_image(url):
        u = urllib2.urlopen(url)
        return StringIO(u.read())

    styles = getSampleStyleSheet()
    styleN = ParagraphStyle(styles['Normal'])

    # build doc

    if len(sys.argv) > 1:
        fn = sys.argv[1]
    else:
        fn = "filename.pdf"
    doc = SimpleDocTemplate(open(fn, "wb"))
    elements = [
        Paragraph("Hello,", styleN),
        Image(get_image("http://www.red-dove.com/images/rdclogo.gif")),
        PageBreak(),
        Paragraph("world!", styleN),
        Image(get_image("http://www.python.org/images/python-logo.gif")),
    ]
    doc.build(elements, canvasmaker=NumberedCanvas)
项目:tambox    作者:joseamaya    | 项目源码 | 文件源码
def imprimir(self):
        y=300
        buffer = self.buffer
        izquierda = ParagraphStyle('parrafos',
                                   alignment = TA_LEFT,
                                   fontSize = 10,
                                   fontName="Times-Roman")
        doc = SimpleDocTemplate(buffer,
                                rightMargin=50,
                                leftMargin=50,
                                topMargin=20,
                                bottomMargin=50,
                                pagesize=self.pagesize)

        elements = [] 
        styles = getSampleStyleSheet()        
        elements.append(self.tabla_encabezado(styles))
        elements.append(Spacer(1, 0.25 * cm))
        elements.append(self.tabla_datos(styles))
        elements.append(Spacer(1, 0.25 * cm))
        elements.append(self.tabla_detalle())
        elements.append(Spacer(1,0.25 * cm))
        elements.append(self.tabla_total_letras())        
        elements.append(Spacer(1, 0.25 * cm))
        elements.append(self.tabla_otros())
        elements.append(Spacer(1, 0.25 * cm))
        elements.append(self.tabla_observaciones())
        elements.append(Spacer(1, 0.25 * cm))
        elements.append(self.tabla_afectacion_presupuestal())
        linea_firma = Line(280, y-250, 470, y-250)
        d = Drawing(100, 1)
        d.add(linea_firma)
        elements.append(d)
        doc.build(elements)
        pdf = buffer.getvalue()
        buffer.close()
        return pdf
项目:tambox    作者:joseamaya    | 项目源码 | 文件源码
def imprimir(self):
        y=300
        buffer = self.buffer
        izquierda = ParagraphStyle('parrafos',
                                   alignment = TA_LEFT,
                                   fontSize = 10,
                                   fontName="Times-Roman")
        doc = SimpleDocTemplate(buffer,
                                rightMargin=50,
                                leftMargin=50,
                                topMargin=20,
                                bottomMargin=50,
                                pagesize=self.pagesize)

        elements = [] 
        styles = getSampleStyleSheet()        
        elements.append(self.tabla_encabezado(styles))
        elements.append(Spacer(1, 0.25 * cm))
        elements.append(self.tabla_datos(styles))        
        elements.append(Spacer(1, 0.25 * cm))
        elements.append(self.tabla_detalle())
        elements.append(Spacer(1,0.25 * cm))
        elements.append(self.tabla_total())   
        elements.append(Spacer(1, 0.25 * cm))     
        elements.append(self.tabla_observaciones())
        elements.append(Spacer(1, 4 * cm))
        elements.append(self.tabla_firmas())        
        doc.build(elements, onFirstPage=self.pie_pagina, onLaterPages=self.pie_pagina)
        pdf = buffer.getvalue()
        buffer.close()
        return pdf
项目:tambox    作者:joseamaya    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs): 
        response = HttpResponse(content_type='application/pdf')
        pdf_name = "clientes.pdf"  # llamado clientes
        # la linea 26 es por si deseas descargar el pdf a tu computadora
        # response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
        buff = BytesIO()
        doc = SimpleDocTemplate(buff,
                                pagesize=letter,
                                rightMargin=40,
                                leftMargin=40,
                                topMargin=60,
                                bottomMargin=18,
                                )
        clientes = []
        styles = getSampleStyleSheet()
        header = Paragraph("Listado de Clientes", styles['Heading1'])
        clientes.append(header)
        headings = ('Nombre', 'Email', 'Edad', 'Direccion')
        allclientes = [(p.codigo, p.descripcion, p.precio_mercado, p.grupo_suministros) for p in Producto.objects.all()]

        t = Table([headings] + allclientes)
        t.setStyle(TableStyle(
            [
                ('GRID', (0, 0), (3, -1), 1, colors.dodgerblue),
                ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue),
                ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue)
            ]
        ))
        clientes.append(t)
        doc.build(clientes)
        response.write(buff.getvalue())
        buff.close()
        return response
项目:ZLib    作者:zenist    | 项目源码 | 文件源码
def go(self):
        doc = SimpleDocTemplate("demo.pdf")
        Story = [Spacer(1, 2*inch)]
        style = styles["Normal"]
        for i in range(100):
            bogustext = ("This is Paragraph number %s. " % i) * 20
            p = Paragraph(bogustext, style)
            Story.append(p)
            Story.append(Spacer(1, 0.2*inch))
        doc.build(Story, onFirstPage=self.myFirstPage, onLaterPages=self.myLaterPage)
项目:ZLib    作者:zenist    | 项目源码 | 文件源码
def test_08_table(self):
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
        from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph, Table
        from reportlab.lib.units import inch
        from reportlab.lib.enums import TA_JUSTIFY
        from reportlab.pdfbase import pdfmetrics
        from reportlab.pdfbase.ttfonts import TTFont
        from reportlab.lib import fonts, colors

        pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc'))
        stylesheet = getSampleStyleSheet()

        elements = []
        doc = SimpleDocTemplate("demo.pdf")

        elements.append(Paragraph('<font name="chsFont">AUT OOM????</font>', stylesheet['Title']))
        elements.append(Spacer(1,12))

        stylesheet.add(ParagraphStyle(name="Justify", alignment=TA_JUSTIFY))
        stylesheet['Justify'].contName = 'chsFont'

        data  = []
        data.append(["???","???","???"])
        data.append(["120","6","50"])
        ts = [('INNERGRID',(0,0),(-1,-1),0.25, colors.black),("BOX",(0,0),(-1,-1),0.25,colors.black),('FONT',(0,0),(-1,-1), 'chsFont')]
        table = Table(data, 2.1*inch, 0.24*inch, ts)
        elements.append(table)

        doc.build(elements)
项目:ZLib    作者:zenist    | 项目源码 | 文件源码
def test_23_linePlotCharts(self):
        from reportlab.lib.styles import getSampleStyleSheet
        from reportlab.lib import colors
        from reportlab.lib.units import inch
        from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph
        from reportlab.pdfbase import pdfmetrics
        from reportlab.graphics.shapes import Drawing
        from reportlab.pdfbase.ttfonts import TTFont
        from reportlab.graphics.charts.lineplots import LinePlot
        from reportlab.graphics.widgets.markers import makeMarker

        pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc'))
        stylesheet = getSampleStyleSheet()

        elements = []
        doc = SimpleDocTemplate("demo.pdf")

        elements.append(Paragraph('<font name="chsFont">JY.zenist.song - ??</font>', stylesheet['Title']))
        elements.append(Spacer(1,1*inch))

        d = Drawing(400,200)
        data = [
            [(1,1), (2,2), (2.5,1), (3,3), (4,5)],
        ]
        lp = LinePlot()
        lp.x = 5
        lp.y = 5
        lp.height = 190
        lp.width = 390
        lp.data = data
        lp.joinedLines = 1
        lp.lines[0].symbol = makeMarker('FilledCircle')
        d.add(lp)

        elements.append(d)

        doc.build(elements)
项目:ZLib    作者:zenist    | 项目源码 | 文件源码
def test_24_PieCharts(self):
        from reportlab.lib.styles import getSampleStyleSheet
        from reportlab.lib import colors
        from reportlab.lib.units import inch
        from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph
        from reportlab.pdfbase import pdfmetrics
        from reportlab.graphics.shapes import Drawing
        from reportlab.pdfbase.ttfonts import TTFont
        from reportlab.graphics.charts.piecharts import Pie

        pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc'))
        stylesheet = getSampleStyleSheet()

        elements = []
        doc = SimpleDocTemplate("demo.pdf")

        elements.append(Paragraph('<font name="chsFont">JY.zenist.song - ??</font>', stylesheet['Title']))
        elements.append(Spacer(1,1*inch))

        d = Drawing(400,200)
        data = [13,5,20,22,37,45]
        pc = Pie()
        pc.x = 65
        pc.y = 15
        pc.width = 150
        pc.height = 150
        pc.data = data
        pc.labels = ['a','b','c','d','e','f']
        d.add(pc)

        elements.append(d)

        doc.build(elements)
项目:smartschool    作者:asifkodur    | 项目源码 | 文件源码
def __init__(self,mypagesize=(21*cm,25*cm),passwd='',path="/tmp/report.pdf",auto_open=True):
        # Encrypts if password is passed as passwd='mypass'

        self.path=path
        self.auto_open=auto_open
        self.name="TEST"
        self.year="TEST"
        self.class_="TEST"
        self.roll_no="TEST"
        self.admission_no="TEST"
        self.school="test"
        styleSheet = getSampleStyleSheet()
        self.mypagesize=mypagesize
        self.elements = []


        enc=pdfencrypt.StandardEncryption(passwd,canPrint=0)


        self.doc = SimpleDocTemplate(self.path, pagesize=mypagesize,title="Performance Report",topMargin=.4*inch,bottomMargin=.3*inch,author="Asif Kodur",encrypt=enc)

        self.DB=db_operations()

        self.Set_Content()




        # Starts measurement

        self.cW1=(mypagesize[0]/cm)/4.8
        self.cW=(mypagesize[0]/cm)/11.6

        self.rH1=(mypagesize[1]/cm)/14
        self.rH2=(mypagesize[1]/cm)/19
        self.rH=(mypagesize[1]/cm)/25



        #end of measurement
项目:smartschool    作者:asifkodur    | 项目源码 | 文件源码
def __init__(self,mypagesize=(21*cm,25*cm)):


        self.path="/tmp/report.pdf"
        self.name="TEST"
        self.year="TEST"
        self.class_="TEST"
        self.roll_no="TEST"
        self.admission_no="TEST"
        self.school="test"
        styleSheet = getSampleStyleSheet()
        self.mypagesize=mypagesize
        self.elements = []
        self.doc = SimpleDocTemplate(self.path, pagesize=mypagesize,title="Performance Report",topMargin=.4*inch,bottomMargin=.3*inch,author="Asif Kodur")

        self.DB=db_operations()

        self.Set_Content()





        # Starts measurement

        self.cW1=(mypagesize[0]/cm)/4.8
        self.cW=(mypagesize[0]/cm)/11.6

        self.rH1=(mypagesize[1]/cm)/14
        self.rH2=(mypagesize[1]/cm)/19
        self.rH=(mypagesize[1]/cm)/25



        #end of measurement
项目:smartschool    作者:asifkodur    | 项目源码 | 文件源码
def __init__(self,mypagesize=(21*cm,25*cm)):

        self.name="TEST"
        self.year="TEST"
        self.class_="TEST"
        self.roll_no="TEST"
        self.admission_no="TEST"
        self.school="test"
        styleSheet = getSampleStyleSheet()
        self.mypagesize=mypagesize
        self.elements = []
        self.doc = SimpleDocTemplate("/tmp/report.pdf", pagesize=mypagesize,title="Performance Report",topMargin=.4*inch,bottomMargin=.3*inch,author="Asif Kodur")
        self.DB=db_operations()


        self.Set_Content()





        # Starts measurement

        self.cW1=(mypagesize[0]/cm)/5.25
        self.cW=(mypagesize[0]/cm)/11.6

        self.rH1=(mypagesize[1]/cm)/14
        self.rH2=(mypagesize[1]/cm)/19
        self.rH=(mypagesize[1]/cm)/25



        #end of measurement
项目:smartschool    作者:asifkodur    | 项目源码 | 文件源码
def __init__(self,mypagesize=(21*cm,25*cm)):


        self.path="/tmp/report.pdf"
        self.name="TEST"
        self.year="TEST"
        self.class_="TEST"
        self.roll_no="TEST"
        self.admission_no="TEST"
        self.school="test"
        styleSheet = getSampleStyleSheet()
        self.mypagesize=mypagesize
        self.elements = []
        self.doc = SimpleDocTemplate(self.path, pagesize=mypagesize,title="Performance Report",topMargin=.4*inch,bottomMargin=.3*inch,author="Asif Kodur")

        self.DB=db_operations()

        self.Set_Content()





        # Starts measurement

        self.cW1=(mypagesize[0]/cm)/4.8
        self.cW=(mypagesize[0]/cm)/11.6

        self.rH1=(mypagesize[1]/cm)/14
        self.rH2=(mypagesize[1]/cm)/19
        self.rH=(mypagesize[1]/cm)/25



        #end of measurement
项目:smartschool    作者:asifkodur    | 项目源码 | 文件源码
def __init__(self,mypagesize=(18*cm,22*cm)):

        styleSheet = getSampleStyleSheet()

        self.doc = SimpleDocTemplate("/tmp/Consolidated_report.pdf", pagesize=mypagesize,title="Performance Report",topMargin=.4*inch,bottomMargin=.3*inch,author="Asif Kodur")
项目:smartschool    作者:asifkodur    | 项目源码 | 文件源码
def __init__(self,mypagesize=A4):


        styleSheet = getSampleStyleSheet()

        self.doc = SimpleDocTemplate("/tmp/Promotion_List.pdf", pagesize=mypagesize,title="PromotionList Report",topMargin=.4*inch,bottomMargin=.3*inch,author="Asif Kodur")
项目:smartschool    作者:asifkodur    | 项目源码 | 文件源码
def __init__(self,mypagesize=(18*cm,22*cm)):

        self.path="/tmp/report_t2_only.pdf"

        self.name="TEST"
        self.year="TEST"
        self.class_="TEST"
        self.roll_no="TEST"
        self.admission_no="TEST"
        self.school="test"
        styleSheet = getSampleStyleSheet()
        self.mypagesize=mypagesize
        self.elements = []
        self.doc = SimpleDocTemplate(self.path, pagesize=mypagesize,title="Performance Report",topMargin=.4*inch,bottomMargin=.3*inch,author="Asif Kodur")
        self.Set_Content()






        # Starts measurement

        self.cW1=(mypagesize[0]/cm)/5.25
        self.cW=(mypagesize[0]/cm)/11.6

        self.rH1=(mypagesize[1]/cm)/14
        self.rH2=(mypagesize[1]/cm)/19
        self.rH=(mypagesize[1]/cm)/26.8



        #end of measurement
项目:smartschool    作者:asifkodur    | 项目源码 | 文件源码
def __init__(self,mypagesize=(18*cm,22*cm)):

        self.name="TEST"
        self.year="TEST"
        self.class_="TEST"
        self.roll_no="TEST"
        self.admission_no="TEST"
        self.school="test"
        styleSheet = getSampleStyleSheet()
        self.mypagesize=mypagesize
        self.elements = []
        self.doc = SimpleDocTemplate("/tmp/report.pdf", pagesize=mypagesize,title="Performance Report",topMargin=.4*inch,bottomMargin=.3*inch,author="Asif Kodur")
        self.Set_Content()





        # Starts measurement

        self.cW1=(mypagesize[0]/cm)/5.25
        self.cW=(mypagesize[0]/cm)/11.6

        self.rH1=(mypagesize[1]/cm)/14
        self.rH2=(mypagesize[1]/cm)/19
        self.rH=(mypagesize[1]/cm)/27



        #end of measurement
项目:smartschool    作者:asifkodur    | 项目源码 | 文件源码
def __init__(self,mypagesize=(18*cm,22*cm)):

        styleSheet = getSampleStyleSheet()

        self.doc = SimpleDocTemplate("/tmp/Consolidated_report.pdf", pagesize=mypagesize,title="Performance Report",topMargin=.4*inch,bottomMargin=.3*inch,author="Asif Kodur")
项目:geo-hpc    作者:itpir    | 项目源码 | 文件源码
def build_doc(self):

        rid = self.request_id
        print 'build_doc: ' + rid

        # try:

        self.doc = SimpleDocTemplate(self.output, pagesize=letter)

        # build doc call all functions

        self.add_header()
        self.Story.append(Spacer(1, 0.5*inch))
        self.add_info()
        self.Story.append(Spacer(1, 0.3*inch))
        self.add_timeline()
        self.Story.append(Spacer(1, 0.3*inch))
        self.add_cite_and_contents()
        self.Story.append(PageBreak())

        self.add_meta()
        self.Story.append(PageBreak())

        self.add_notes()
        self.Story.append(PageBreak())

        self.add_additional()

        self.output_doc()

        return True
        # except:
        #     return False


    # documentation header
项目:web-scraper    作者:acomets    | 项目源码 | 文件源码
def pdfgen(relevant_extracts, sector, keywords):
    today = datetime.datetime.today()
    today.replace(second=0, microsecond=0)

    outputdir = join('..', 'output')
    if not exists(outputdir):
        mkdir(outputdir)
    chdir(outputdir)

    doc = SimpleDocTemplate('%s_%s.pdf' % (sector, today.strftime("%Y-%m-%d_%H.%M")))
    template = PageTemplate('normal', [Frame(2.5*cm, 2.5*cm, 15*cm, 25*cm, id='F1')])
    doc.addPageTemplates(template)

    Story = [Spacer(1,0.5*inch)]
    styleSheet=getSampleStyleSheet()
    style = styleSheet['BodyText']
    title = Paragraph('<para align=center><b>%s Industry Earnings Call Transcripts Report</b></para>' % sector,
                      style)
    Story.append(title)
    subtitle = Paragraph('<para align=center>Keywords: %s</para>' % ", ".join(keywords),
                         style)
    Story.append(subtitle)
    Story.append(Spacer(1,0.5*inch))


    for extract in relevant_extracts:
        Story.append(Paragraph("From %s" % extract["title"], h1))
        Story.append(Paragraph("Published on %s at %s" % (extract["date"], extract["time"]), h1))
        text = Preformatted(extract["bodyContent"].encode('utf8'), style, maxLineLength=100)
        Story.append(text)
        Story.append(Spacer(1,0.2*inch))

    doc.build(Story)
项目:certificate    作者:gileno    | 项目源码 | 文件源码
def main():
    context = {
        'instructor': INSTRUCTOR,
        'course': COURSE,
        'student': STUDENT,
        'hours': HOURS,
    }
    styles = getSampleStyleSheet()
    styles.add(
        ParagraphStyle(
            name='Justify', alignment=TA_JUSTIFY, fontSize=16, leading=22
        )
    )
    elements = []
    certificate_txt = render(TEXT_PATH, context)
    paragraphs = certificate_txt.split(os.linesep)
    elements.append(Spacer(1, 50))
    for p in paragraphs:
        elements.append(Paragraph(p, styles['Justify']))
        elements.append(Spacer(1, 16))

    certificate = tempfile.NamedTemporaryFile()
    doc = SimpleDocTemplate(certificate, topMargin=3 * cm, bottomMargin=0)
    doc.pagesize = landscape(A4)
    doc.build(elements)

    output = PdfFileWriter()
    template_file = open('template.pdf', 'rb')
    input1 = PdfFileReader(template_file)
    page1 = input1.getPage(0)
    content = PdfFileReader(certificate)
    page1.mergePage(content.getPage(0))
    output.addPage(page1)
    save_file = open(SAVE_AS, 'wb')
    output.write(save_file)
    print('Certificado gerado com sucesso em %s' % SAVE_AS)
项目:reportlab    作者:xiaozheya    | 项目源码 | 文件源码
def rpt():
    story = []
    #??????????reportlab-userguide.pdf?chapter 6 Paragraph
    if READ_TYPE == 1:           #?????????
        rpt_title = '<para autoLeading="off" fontSize=10.5 align=center>'+Read.news_title+'<br/></para>'
        story.append(Paragraph(rpt_title, styleH))
        table_list=[]
        temp=[]
        temp.append(Read.news_author)
        temp.append(Read.news_time)
        table_list.append(temp)
        first_table = Table(table_list,colWidths=[225,225])
        first_table.setStyle(TableStyle([
        ('FONTNAME', (0, 0), (1, 0), 'msyhbd'),
        ('ALIGN', (1, 0), (1, 0), 'RIGHT'),  # ???
        ('ALIGN', (0, 0), (0, 0), 'LEFT'),
        ('FONTSIZE', (1, 2), (-1, -1), 10.5),  # ????
        ('TEXTCOLOR', (0, 0), (1, 0), colors.standardfl),
        ]))
        story.append(first_table)
        news_content_list=Read.news_content.splitlines()
        for i in range(len(news_content_list)):
            text = ''
            text += '<para autoLeading="off" fontSize=10.5 ><font face="msyh" >'
            text+=news_content_list[i]
            text +='</font></para>'
            story.append(Paragraph(text, normalStyle))
    if READ_TYPE==2:                  #??word?????????
        doc = docx.Document('test1.docx')
        length = len(doc.paragraphs)
        rpt_title = '<para autoLeading="off" fontSize=10.5 align=center>' + doc.paragraphs[0].text + '<br/></para>'
        story.append(Paragraph(rpt_title, styleH))
        rpt_title = '<para autoLeading="off" fontSize=10.5 align=right color=rgb(84,141,212)>' + doc.paragraphs[1].text + '<br/></para>'
        story.append(Paragraph(rpt_title, styleH))
        for i in range(2,length):
            text = ''
            if doc.paragraphs[i].style.name=='Heading 3' or doc.paragraphs[i].style.name=='Heading 2'or doc.paragraphs[i].style.name=='Heading 1':
                text+='<para autoLeading="off" fontSize=10.5 ><font face="msyhbd" >'
            else :
                text += '<para autoLeading="off" fontSize=10.5 ><font face="msyh" >'
            text+=doc.paragraphs[i].text
            text +='</font></para>'
            story.append(Paragraph(text, normalStyle))
        #?????????reportlab-userguide.pdf?chapter 7 Table
        table.parse_docx('test1.docx')
        component_data = table.component_data
        component_table = Table(component_data)
        component_table.setStyle(table_style.table_style)
        story.append(component_table)

    doc = SimpleDocTemplate('D:/HX/reportlab/bug1.pdf')
    doc.build(story)
项目:tambox    作者:joseamaya    | 项目源码 | 文件源码
def imprimir_formato_sunat_unidades_fisicas_producto(self, producto):
        desde = self.desde
        hasta = self.hasta
        almacen = self.almacen
        buffer = self.buffer
        self.valorizado = False
        izquierda = ParagraphStyle('parrafos',
                                   alignment=TA_LEFT,
                                   fontSize=11,
                                   fontName="Times-Roman")
        doc = SimpleDocTemplate(buffer,
                                rightMargin=50,
                                leftMargin=50,
                                topMargin=100,
                                bottomMargin=50,
                                pagesize=self.pagesize)

        elements = []
        periodo = Paragraph("PERIODO: " + desde.strftime('%d/%m/%Y') + ' - ' + hasta.strftime('%d/%m/%Y'), izquierda)
        elements.append(periodo)
        elements.append(Spacer(1, 0.25 * cm))
        ruc = Paragraph(u"RUC:" + EMPRESA.ruc, izquierda)
        elements.append(ruc)
        elements.append(Spacer(1, 0.25 * cm))
        razon_social = Paragraph(u"APELLIDOS Y NOMBRES, DENOMINACIÓN O RAZÓN SOCIAL: " + EMPRESA.razon_social, izquierda)
        elements.append(razon_social)
        elements.append(Spacer(1, 0.25 * cm))
        direccion = Paragraph(u"ESTABLECIMIENTO (1): " + EMPRESA.direccion(), izquierda)
        elements.append(direccion)
        elements.append(Spacer(1, 0.25 * cm))
        codigo = Paragraph(u"CÓDIGO DE LA EXISTENCIA: " + producto.codigo, izquierda)
        elements.append(codigo)
        elements.append(Spacer(1, 0.25 * cm))
        tipo = Paragraph(u"TIPO: B - EXISTENCIA", izquierda)
        """tipo = Paragraph(u"TIPO (TABLA 5): " + producto.tipo_existencia.codigo_sunat + " - " + producto.tipo_existencia.descripcion,
                         izquierda)"""
        elements.append(tipo)
        elements.append(Spacer(1, 0.25 * cm))
        descripcion = Paragraph(u"DESCRIPCIÓN: " + producto.descripcion, izquierda)
        elements.append(descripcion)
        elements.append(Spacer(1, 0.25 * cm))
        unidad = Paragraph(u"CÓDIGO DE LA UNIDAD DE MEDIDA (TABLA 6): " + producto.unidad_medida.codigo_sunat + " - " + producto.unidad_medida.descripcion,
                           izquierda)
        elements.append(unidad)
        elements.append(Spacer(1, 0.25 * cm))
        unidad = Paragraph(u"MÉTODO DE VALUACIÓN: PEPS",
                           izquierda)
        elements.append(unidad)
        elements.append(Spacer(1, 0.5 * cm))
        elements.append(self.tabla_detalle_unidades_fisicas(producto, desde, hasta, almacen))
        doc.build(elements, onFirstPage=self._header, onLaterPages=self._header)
        pdf = buffer.getvalue()
        buffer.close()
        return pdf
项目:tambox    作者:joseamaya    | 项目源码 | 文件源码
def imprimir_formato_sunat_valorizado_producto(self, producto):
        desde = self.desde
        hasta = self.hasta
        almacen = self.almacen
        buffer = self.buffer
        self.valorizado = True
        izquierda = ParagraphStyle('parrafos',
                                   alignment=TA_LEFT,
                                   fontSize=12,
                                   fontName="Times-Roman")
        doc = SimpleDocTemplate(buffer,
                                rightMargin=50,
                                leftMargin=50,
                                topMargin=100,
                                bottomMargin=50,
                                pagesize=self.pagesize)

        elements = []
        periodo = Paragraph("PERIODO: " + desde.strftime('%d/%m/%Y') + ' - ' + hasta.strftime('%d/%m/%Y'), izquierda)
        elements.append(periodo)
        elements.append(Spacer(1, 0.25 * cm))
        ruc = Paragraph(u"RUC:" + EMPRESA.ruc, izquierda)
        elements.append(ruc)
        elements.append(Spacer(1, 0.25 * cm))
        razon_social = Paragraph(u"APELLIDOS Y NOMBRES, DENOMINACIÓN O RAZÓN SOCIAL: " + EMPRESA.razon_social, izquierda)
        elements.append(razon_social)
        elements.append(Spacer(1, 0.25 * cm))
        direccion = Paragraph(u"ESTABLECIMIENTO (1): " + EMPRESA.direccion(), izquierda)
        elements.append(direccion)
        elements.append(Spacer(1, 0.25 * cm))
        codigo = Paragraph(u"CÓDIGO DE LA EXISTENCIA: " + producto.codigo, izquierda)
        elements.append(codigo)
        elements.append(Spacer(1, 0.25 * cm))
        tipo = Paragraph(u"TIPO: B - EXISTENCIA", izquierda)
        """tipo = Paragraph(u"TIPO (TABLA 5): " + producto.tipo_existencia.codigo_sunat + " - " + producto.tipo_existencia.descripcion,
                         izquierda)"""
        elements.append(tipo)
        elements.append(Spacer(1, 0.25 * cm))
        descripcion = Paragraph(u"DESCRIPCIÓN: " + producto.descripcion, izquierda)
        elements.append(descripcion)
        elements.append(Spacer(1, 0.25 * cm))
        unidad = Paragraph(u"CÓDIGO DE LA UNIDAD DE MEDIDA (TABLA 6): " + producto.unidad_medida.codigo_sunat + " - " + producto.unidad_medida.descripcion,
                           izquierda)
        elements.append(unidad)
        elements.append(Spacer(1, 0.25 * cm))
        unidad = Paragraph(u"MÉTODO DE VALUACIÓN: PEPS",
                           izquierda)
        elements.append(unidad)
        elements.append(Spacer(1, 0.5 * cm))
        elements.append(self.tabla_detalle_valorizado(producto, desde, hasta, almacen))
        doc.build(elements, onFirstPage=self._header, onLaterPages=self._header)
        pdf = buffer.getvalue()
        buffer.close()
        return pdf
项目:tambox    作者:joseamaya    | 项目源码 | 文件源码
def imprimir_formato_sunat_valorizado_todos(self):
        desde = self.desde
        hasta = self.hasta
        almacen = self.almacen
        buffer = self.buffer
        self.valorizado = True
        izquierda = ParagraphStyle('parrafos',
                                   alignment=TA_LEFT,
                                   fontSize=12,
                                   fontName="Times-Roman")
        doc = SimpleDocTemplate(buffer,
                                rightMargin=50,
                                leftMargin=50,
                                topMargin=100,
                                bottomMargin=50,
                                pagesize=self.pagesize)

        elements = []
        productos_kardex = Kardex.objects.exclude(cantidad_ingreso=0,
                                                  cantidad_salida=0).order_by().values('producto').distinct()
        productos = Producto.objects.filter(pk__in=productos_kardex).order_by('descripcion')
        for producto in productos:
            periodo = Paragraph("PERIODO: " + desde.strftime('%d/%m/%Y') + ' - ' + hasta.strftime('%d/%m/%Y'), izquierda)
            elements.append(periodo)
            elements.append(Spacer(1, 0.25 * cm))
            ruc = Paragraph(u"RUC:" + EMPRESA.ruc, izquierda)
            elements.append(ruc)
            elements.append(Spacer(1, 0.25 * cm))
            razon_social = Paragraph(u"APELLIDOS Y NOMBRES, DENOMINACIÓN O RAZÓN SOCIAL: " + EMPRESA.razon_social, izquierda)
            elements.append(razon_social)
            elements.append(Spacer(1, 0.25 * cm))
            direccion = Paragraph(u"ESTABLECIMIENTO (1): " + EMPRESA.direccion(), izquierda)
            elements.append(direccion)
            elements.append(Spacer(1, 0.25 * cm))
            codigo = Paragraph(u"CÓDIGO DE LA EXISTENCIA: " + producto.codigo, izquierda)
            elements.append(codigo)
            elements.append(Spacer(1, 0.25 * cm))
            tipo = Paragraph(u"TIPO: B - EXISTENCIA",izquierda)
            """tipo = Paragraph(u"TIPO (TABLA 5): " + producto.tipo_existencia.codigo_sunat + " - " + producto.tipo_existencia.descripcion,
                             izquierda)"""
            elements.append(tipo)
            elements.append(Spacer(1, 0.25 * cm))
            descripcion = Paragraph(u"DESCRIPCIÓN: " + producto.descripcion, izquierda)
            elements.append(descripcion)
            elements.append(Spacer(1, 0.25 * cm))
            unidad = Paragraph(u"CÓDIGO DE LA UNIDAD DE MEDIDA (TABLA 6): " + producto.unidad_medida.codigo_sunat + " - " + producto.unidad_medida.descripcion,
                               izquierda)
            elements.append(unidad)
            elements.append(Spacer(1, 0.25 * cm))
            unidad = Paragraph(u"MÉTODO DE VALUACIÓN: PEPS",
                               izquierda)
            elements.append(unidad)
            elements.append(Spacer(1, 0.5 * cm))
            elements.append(self.tabla_detalle_valorizado(producto, desde, hasta, almacen))
            elements.append(PageBreak())
        doc.build(elements, onFirstPage=self._header, onLaterPages=self._header)
        pdf = buffer.getvalue()
        buffer.close()
        return pdf
项目:infonex_crm    作者:asterix135    | 项目源码 | 文件源码
def call_report(request):
    event_assignment = get_object_or_404(EventAssignment,
                                         pk=request.session['assignment_id'])
    event = event_assignment.event
    user = request.user
    contact_history = Contact.objects.filter(
        event=event, author=user
    ).order_by('-date_of_contact')
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename="call_report.pdf"'
    buffr = BytesIO()

    styles = getSampleStyleSheet()
    cell_style = styles['BodyText']
    cell_style.alignment = TA_LEFT

    report_details = []
    title = Paragraph('Call Note Report', styles['title'])
    report_details.append(title)
    conf_details_text = event.number + ': ' + event.title + ' (' \
        + user.username+ ')'
    report_details.append(Paragraph(conf_details_text, styles['h2']))
    report = SimpleDocTemplate(buffr, pagesize=letter,
                               leftMargin=inch/2, rightMargin = inch/2)
    data = []
    for contact in contact_history:
        person = contact.person.name
        if contact.person.title:
            person = person + '<br/>' + contact.person.title
        if contact.person.company:
            person = person + '<br/>' + contact.person.company
        date = Paragraph(str(contact.date_of_contact.date()), cell_style)
        person = Paragraph(person, cell_style)
        notes = Paragraph(contact.notes[:3500], cell_style)
        data.append([date, person, notes])
        table = Table(data, [inch, 3 * inch, 4.5 * inch])
        table.setStyle(TableStyle([('VALIGN', (0,0), (-1, -1), 'TOP')]))
        report_details.append(table)
        data = []
    # if len(data) > 0:
    #     call_detail_table = Table(data, [inch, 2 * inch, 4.5 * inch])
    #     call_detail_table.setStyle(TableStyle([('VALIGN', (0,0),
    #                                             (-1, -1), 'TOP')]))
    #     report_details.append(call_detail_table)


    report.build(report_details)

    pdf = buffr.getvalue()
    buffr.close()
    response.write(pdf)
    return response
项目:smartschool    作者:asifkodur    | 项目源码 | 文件源码
def __init__(self,mypagesize=(21*cm,25*cm),passwd='',path="/tmp/report.pdf",auto_open=True):

        self.path=path
        self.auto_open=auto_open
        self.name="TEST"
        self.year="TEST"
        self.class_="TEST"
        self.roll_no="TEST"
        self.admission_no="TEST"
        self.school="test"
        styleSheet = getSampleStyleSheet()
        self.mypagesize=mypagesize
        self.elements = []


        enc=pdfencrypt.StandardEncryption(passwd,canPrint=0)

        self.doc = SimpleDocTemplate(self.path, pagesize=mypagesize,title="Performance Report",topMargin=.4*inch,bottomMargin=.3*inch,author="Asif Kodur",encrypt=enc)
        self.DB=db_operations()





        self.Set_Content()





        # Starts measurement

        self.cW1=(mypagesize[0]/cm)/5.25
        self.cW=(mypagesize[0]/cm)/11.6

        self.rH1=(mypagesize[1]/cm)/14
        self.rH2=(mypagesize[1]/cm)/19
        self.rH=(mypagesize[1]/cm)/25



        #end of measurement
项目:2016.2-SME_UnB    作者:fga-gpp-mds    | 项目源码 | 文件源码
def generatePdf(transductor_id):
    import time
    from reportlab.lib.enums import TA_JUSTIFY
    from reportlab.lib.pagesizes import letter
    from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image
    from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
    from reportlab.lib.units import inch

    doc = SimpleDocTemplate("src/report/static/Relatorio"+transductor_id+".pdf",
                            pagesize=letter,
                            rightMargin=72, leftMargin=72,
                            topMargin=72, bottomMargin=18)
    Story = []
    logo = "src/report/static/currentGraphic"+transductor_id+".png"
    logo2 = "src/report/static/voltageGraphic"+transductor_id+".png"
    logo3 = "src/report/static/activePowerGraphic"+transductor_id+".png"
    logo4 = "src/report/static/reactivePowerGraphic"+transductor_id+".png"
    logo5 = "src/report/static/apparentPowerGraphic"+transductor_id+".png"

    magName = "Pythonista"
    issueNum = 12
    subPrice = "99.00"
    limitedDate = "03/05/2010"
    freeGift = "tin foil hat"

    formatted_time = time.ctime()
    full_name = "SME-UnB"
    address_parts = ["Campus Universitario UnB", "Brasilia-DF, 70910-900"]

    im = Image(logo, 8 * inch, 5 * inch)
    im2 = Image(logo2, 8 * inch, 5 * inch)
    im3 = Image(logo3, 8 * inch, 5 * inch)
    im4 = Image(logo4, 8 * inch, 5 * inch)
    im5 = Image(logo5, 8 * inch, 5 * inch)

    Story.append(im)
    Story.append(im2)
    Story.append(im3)
    Story.append(im4)
    Story.append(im5)

    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
    ptext = '<font size=12>%s</font>' % formatted_time

    Story.append(Paragraph(ptext, styles["Normal"]))
    Story.append(Spacer(1, 12))

    ptext = '<font size=12>%s</font>' % full_name
    Story.append(Paragraph(ptext, styles["Normal"]))
    for part in address_parts:
        ptext = '<font size=12>%s</font>' % part.strip()
        Story.append(Paragraph(ptext, styles["Normal"]))

    Story.append(Spacer(1, 12))
    Story.append(Spacer(1, 12))
    ptext = '<font size=12>{ % trans Report Energy Monitoring % }</font>'
    Story.append(Paragraph(ptext, styles["Normal"]))

    doc.build(Story)
    return 1
项目:ZLib    作者:zenist    | 项目源码 | 文件源码
def test_21_barCharts(self):
        from reportlab.lib.styles import getSampleStyleSheet
        from reportlab.lib import colors
        from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph
        from reportlab.pdfbase import pdfmetrics
        from reportlab.graphics.shapes import Drawing
        from reportlab.pdfbase.ttfonts import TTFont
        from reportlab.graphics.charts.barcharts import VerticalBarChart

        pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc'))
        stylesheet = getSampleStyleSheet()

        elements = []
        doc = SimpleDocTemplate("demo.pdf")

        elements.append(Paragraph('<font name="chsFont">JY.zenist.song - ??</font>', stylesheet['Title']))
        elements.append(Spacer(1,12))

        d = Drawing(400,200)
        data = [
            (13,5,20,22,37,45,19,4),
            (14,6,21,23,38,46,20,5)
        ]
        bc = VerticalBarChart()
        bc.x = 50
        bc.y = 50
        bc.height = 125
        bc.width = 300
        bc.data = data
        bc.strokeColor = colors.black
        bc.groupSpacing = 10
        bc.barSpacing = 2.5

        bc.valueAxis._valueMin = 0
        bc.valueAxis._valueMax = 50
        bc.valueAxis._valueStep = 10

        bc.categoryAxis.categoryNames = ['1','2','3','4','5','6','7','8']
        # bc.categoryAxis.style = 'stacked'
        d.add(bc)

        elements.append(d)

        doc.build(elements)