Esempio n. 1
0
 def __init__(self, writer):
     MyTemplates._AbstractTemplate.__init__(self, writer)
     (x,y,width,height) = (2.0*cm, 2.0*cm, 15.0*cm, 25.0*cm)
     mainFrame = Frame(x, y, width, height, id='MainFrame')
     page = PageTemplate('normal', [mainFrame,], self.onPage, self.onPageEnd)
     self.addPageTemplates(page)
Esempio n. 2
0
 def __init__(self, filename, **kw):
     frame1 = Frame(2.5 * cm, 2.5 * cm, 15 * cm, 25 * cm, id='F1')
     self.allowSplitting = 0
     BaseDocTemplate.__init__(self, filename, **kw)
     template = PageTemplate('normal', [frame1], myMainPageFrame)
     self.addPageTemplates(template)
Esempio n. 3
0
 def __init__(self, filename, **kw):
     self.allowSplitting = 0
     BaseDocTemplate.__init__(self, filename, **kw)
     template = PageTemplate(
         'normal', [Frame(2.5 * cm, 2.5 * cm, 15 * cm, 25 * cm, id='F1')])
     self.addPageTemplates(template)
Esempio n. 4
0
#tutorial 50
#CREATE PORTRAIT & LANDSCAPE ORIENTATION TOGETHER IN SAME PDF
from reportlab.platypus.doctemplate import SimpleDocTemplate, PageTemplate, PageBreak
from reportlab.pdfgen import canvas
from reportlab.platypus import Paragraph, SimpleDocTemplate, PageTemplate, NextPageTemplate, Frame
from reportlab.lib.styles import getSampleStyleSheet
pdf = SimpleDocTemplate("tutorial50.pdf")
frame1 = Frame(10, 20, 600, 1000, showBoundary=1)
frame2 = Frame(10, 20, 1000, 700, showBoundary=1)
port = PageTemplate(id="p", pagesize=[800, 1200], frames=[frame1])
land = PageTemplate(id="l", pagesize=[1200, 900], frames=[frame2])
pdf.addPageTemplates([port, land])
text = "text"
flow_obj = []
styles = getSampleStyleSheet()
ptext = Paragraph(text, style=styles["Normal"])
flow_obj.append(ptext)

flow_obj.append(NextPageTemplate("l"))
flow_obj.append(PageBreak())
flow_obj.append(ptext)
flow_obj.append(NextPageTemplate("p"))
flow_obj.append(PageBreak())
flow_obj.append(ptext)
pdf.build(flow_obj)
 def __init__(self, filename, **kw):
     frame1 = Frame(2.5 * cm, 2.5 * cm, 15 * cm, 25 * cm, id='F1')
     self.allowSplitting = 0
     apply(BaseDocTemplate.__init__, (self, filename), kw)
     self.addPageTemplates(PageTemplate('normal', [frame1], mainPageFrame))
Esempio n. 6
0
def exportToPDF(path,
                title,
                author,
                description,
                container,
                marker_beg,
                marker_end,
                replace_where,
                replace_by,
                tmargin=30,
                bmargin=20,
                lmargin=30,
                rmargin=20,
                font='Helvetica',
                size=12,
                mode='Bold'):
    """
    This function produce the pdf itself with all the preferences 

    Parameters:
    -----------
    string: path
        Where it will be save

    string: title
        Document's title

    string: author
        Document's author

    string: description
        A short description of the file

    class: container
        Instance of the program

    integer: *margin
        The top, bottom, left and right margin

    string: font
        Font name

    integer: size
        Basic size of the text.

    string: mode
        Modes: Bold, Replace, Raw

    string: marker_beg, marker_end, replace_where, replace_by
        Strip sentence variables

    Returns:
    --------
    other pages

    """

    if font == 'Times-Roman':
        fontbold = 'Times-Bold'
    if font == 'Courier':
        fontbold = 'Courier-Bold'
    if font == 'Helvetica':
        fontbold = 'Helvetica-Bold'

    phrase_base = ParagraphStyle(name='phrase_base',
                                 fontName=font,
                                 fontSize=size,
                                 alignment=TA_JUSTIFY,
                                 leftIndent=0.5 * inch)
    heading_1 = ParagraphStyle(name='heading_1',
                               fontName=fontbold,
                               fontSize=size + 4,
                               leading=22,
                               spaceBefore=12,
                               spaceAfter=6)
    heading_2 = ParagraphStyle(name='heading_2',
                               fontName=fontbold,
                               fontSize=size + 2,
                               leading=18,
                               spaceBefore=6,
                               spaceAfter=6)
    heading_3 = ParagraphStyle(name='heading_3',
                               fontName=font,
                               fontSize=size + 1,
                               leading=14,
                               spaceBefore=6,
                               spaceAfter=6)
    centered = ParagraphStyle(name='centered',
                              fontName=font,
                              fontSize=18,
                              leading=26,
                              alignment=1,
                              spaceAfter=26)
    desc_style = ParagraphStyle(name='desc_style',
                                fontName=font,
                                fontSize=size + 2)
    title_style = ParagraphStyle(name='title_style',
                                 fontName=font,
                                 fontSize=size + 12)
    author_style = ParagraphStyle(name='author_style',
                                  fontName=font,
                                  fontSize=size + 3)

    doc = MyDocTemplate(path,
                        pagesize=A4,
                        rightMargin=rmargin * mm,
                        leftMargin=lmargin * mm,
                        topMargin=tmargin * mm,
                        bottomMargin=bmargin * mm)
    doc.title = title
    doc.author = author
    doc.description = description

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

    doc.addPageTemplates([
        PageTemplate('first', frames=frameT, onPage=myFirstPage),
        PageTemplate('toc', frames=frameT, onPage=myTOCPages),
        PageTemplate('laters', frames=frameT, onPage=myLaterPages)
    ])

    Story = []
    Story.append(Spacer(1, 12))
    Story.append(Paragraph(title, title_style))
    Story.append(Spacer(1, 50))
    Story.append(Paragraph(author, author_style))
    Story.append(Spacer(1, 150))
    Story.append(Paragraph(description, desc_style))
    Story.append(NextPageTemplate('toc'))
    Story.append(PageBreak())

    Story.append(Paragraph('Table of contents', centered))
    toc = TableOfContents()
    toc.levelStyles = [heading_1, heading_2, heading_3]
    Story.append(toc)

    Story.append(NextPageTemplate('laters'))
    Story.append(PageBreak())

    sections = container.listSections()
    if "Not Classified" in sections:
        sections.remove("Not Classified")

    for snum, sec in enumerate(sections):
        Story.append(Paragraph(str(snum + 1) + '.  ' + sec, heading_1))
        Story.append(Spacer(1, 12))

        components = container.listComponents(qsections=[sec])
        if "Not Classified" in components:
            components.remove("Not Classified")

        for compnum, comp in enumerate(components):
            Story.append(
                Paragraph(
                    str(snum + 1) + '.' + str(compnum + 1) + '.  ' + comp,
                    heading_2))
            Story.append(Spacer(1, 12))

            strategies = container.listStrategies(qsections=[sec],
                                                  qsubsections=[comp])
            if "Not Classified" in strategies:
                strategies.remove("Not Classified")

            nummenos = 0

            for stranum, stra in enumerate(strategies):

                Story.append(
                    Paragraph(
                        str(snum + 1) + '.' + str(compnum + 1) + '.' +
                        str(stranum - nummenos + 1) + '.  ' + stra, heading_3))
                Story.append(Spacer(1, 12))
                lista = container.listSentences(section=[sec],
                                                subsection=[comp],
                                                function=[stra])

                if lista == []:
                    Story.pop()
                    Story.pop()
                    nummenos += 1

                for lista in container.listSentences(section=[sec],
                                                     subsection=[comp],
                                                     function=[stra]):
                    if lista != []:
                        idv, secv, subsv, funcv, sentv, refv = lista
                        if sentv != 'NULL':
                            if mode != 'Raw':
                                sentv = container.adjustSentence(
                                    sentv, marker_beg, marker_end,
                                    replace_where, replace_by, mode)
                            if refv == 'NULL':
                                refv = 'None'
                            ptext = sentv + ' Reference: ' + refv
                            Story.append(Paragraph(ptext, phrase_base))
                            Story.append(Spacer(1, 12))

    doc.multiBuild(Story)
Esempio n. 7
0
    def __init__(self, filename, **kw):
        self.allowSplitting = 0
        apply(BaseDocTemplate.__init__, (self, filename), kw)
        template = PageTemplate('normal', [Frame(0.1 * inch, 0.1 * inch,
                                11 * inch, 8 * inch, id='F1')])
        self.addPageTemplates(template)

        self.centered = PS(
            name='centered',
            fontSize=30,
            leading=16,
            alignment=1,
            spaceAfter=20)

        self.centered_index = PS(
            name='centered_index',
            fontSize=24,
            leading=16,
            alignment=1,
            spaceAfter=20)

        self.small_centered = PS(
            name='small_centered',
            fontSize=14,
            leading=16,
            alignment=1,
            spaceAfter=20)

        self.h1 = PS(
            name='Heading1',
            fontSize=16,
            leading=16)

        self.h2 = PS(
            name='Heading2',
            fontSize=14,
            leading=14)

        self.h2_center = PS(
            name='Heading2Center',
            alignment=1,
            fontSize=14,
            leading=14)

        self.h2_invisible = PS(
            name='Heading2Invisible',
            alignment=1,
            textColor='#FFFFFF',
            fontSize=14,
            leading=14)

        self.mono = PS(
            name='Mono',
            fontName='Courier',
            fontSize=16,
            leading=16)

        self.normal = PS(
            name='Normal',
            fontSize=16,
            leading=16)

        self.toc = TableOfContents()
        self.toc.levelStyles = [
            PS(fontName='Times-Bold', fontSize=14, name='TOCHeading1',
                leftIndent=20, firstLineIndent=-20, spaceBefore=2, leading=16),
            PS(fontSize=10, name='TOCHeading2', leftIndent=40,
                firstLineIndent=-20, spaceBefore=0, leading=8),
        ]
Esempio n. 8
0
    topPadding=0,
    id='frame_design_one',
    showBoundary=1,
    overlapAttachedSpace=None,
    _debug=None
  )

# create a template page for document that have frames created allow change
# design when build the document.
# is possible have many diferents types of pages design for a same document
page_design_one = PageTemplate(
    id='page_design_one',
    frames=[frame_design_one],
    # onPage=_doNothing,
    # onPageEnd=_doNothing,
    pagesize=(100,100), # this override pagesize of the BaseDocTemplate
    autoNextPageTemplate=None,
    cropBox=None,
    artBox=None,
    trimBox=None,
    bleedBox=None
  )

# create a new document
# not is neccesary send all options for inicializate the document
# required parameters:
#   - filename -> a string name or InputStream
document = BaseDocTemplate(
    # pagesize=(400,400), # this is override for a pagesize of the PageTemplate
    pageTemplate=[], # add list of page template for here or use 'addPageTemplates()'
    showBoundary=1,
    filename=BytesIO(),
Esempio n. 9
0
    def view(self, request):
        presentation = self.obj

        passwords = request.session.get('passwords', dict())

        response = HttpResponse(mimetype='application/pdf')

        pagesize = getattr(pagesizes, settings.PDF_PAGESIZE)
        width, height = pagesize

        class DocTemplate(BaseDocTemplate):
            def afterPage(self):
                self.handle_nextPageTemplate('Later')

        def column_frame(left):
            return Frame(left, inch / 2,
                           width=width / 2 - 0.75 * inch, height = height - inch,
                          leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, showBoundary=False)

        def prepare_first_page(canvas, document):
            p1 = Paragraph(presentation.title, styles['Heading'])
            p2 = Paragraph(presentation.owner.get_full_name(), styles['SubHeading'])
            avail_width = width - inch
            avail_height = height - inch
            w1, h1 = p1.wrap(avail_width, avail_height)
            w2, h2 = p2.wrap(avail_width, avail_height)
            f = Frame(inch / 2, inch / 2, width - inch, height - inch,
                      leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0)
            f.addFromList([p1, p2], canvas)

            document.pageTemplate.frames[0].height -= h1 + h2 + inch / 2
            document.pageTemplate.frames[1].height -= h1 + h2 + inch / 2

            canvas.saveState()
            canvas.setStrokeColorRGB(0, 0, 0)
            canvas.line(width / 2, inch / 2, width / 2, height - inch - h1 - h2)
            canvas.restoreState()

        def prepare_later_page(canvas, document):
            canvas.saveState()
            canvas.setStrokeColorRGB(0, 0, 0)
            canvas.line(width / 2, inch / 2, width / 2, height - inch / 2)
            canvas.restoreState()

        def getStyleSheet():
            stylesheet = StyleSheet1()
            stylesheet.add(ParagraphStyle(name='Normal',
                                          fontName='Times-Roman',
                                          fontSize=8,
                                          leading=10,
                                          spaceAfter=18))
            stylesheet.add(ParagraphStyle(name='SlideNumber',
                                          parent=stylesheet['Normal'],
                                          alignment=TA_RIGHT,
                                          fontSize=6,
                                          leading=8,
                                          rightIndent=3,
                                          spaceAfter=0))
            stylesheet.add(ParagraphStyle(name='Heading',
                                          parent=stylesheet['Normal'],
                                          fontSize=20,
                                          leading=24,
                                          alignment=TA_CENTER,
                                          spaceAfter=0))
            stylesheet.add(ParagraphStyle(name='SubHeading',
                                          parent=stylesheet['Normal'],
                                          fontSize=16,
                                          leading=20,
                                          alignment=TA_CENTER))
            return stylesheet

        styles = getStyleSheet()

        items = presentation.items.filter(hidden=False)

        content = []

        for index, item in enumerate(items):
            text = []
            values = item.get_fieldvalues(owner=request.user)
            for value in values:
                text.append('<b>%s</b>: %s<br />' % (value.resolved_label, value.value))
            annotation = item.annotation
            if annotation:
                text.append('<b>%s</b>: %s<br />' % ('Annotation', annotation))
            try:
                p = Paragraph(''.join(text), styles['Normal'])
            except (AttributeError, KeyError, IndexError):
                # this sometimes triggers an error in reportlab
                p = None
            if p:
                image = get_image_for_record(item.record, presentation.owner, 100, 100, passwords)
                if image:
                    try:
                        i = flowables.Image(image, kind='proportional',
                                            width=1 * inch, height=1 * inch)
                        p = flowables.ParagraphAndImage(p, i)
                    except IOError:
                        pass
                content.append(flowables.KeepTogether(
                    [Paragraph('%s/%s' % (index + 1, len(items)), styles['SlideNumber']), p]))

        first_template = PageTemplate(id='First',
                                      frames=[column_frame(inch / 2), column_frame(width / 2 + 0.25 * inch)],
                                      pagesize=pagesize,
                                      onPage=prepare_first_page)
        later_template = PageTemplate(id='Later',
                                      frames=[column_frame(inch / 2), column_frame(width / 2 + 0.25 * inch)],
                                      pagesize=pagesize,
                                      onPage=prepare_later_page)

        doc = DocTemplate(response)
        doc.addPageTemplates([first_template, later_template])
        doc.build(content)

        return response