def build_index_US(self, records, sito):
        if os.name == 'posix':
            home = os.environ['HOME']
        elif os.name == 'nt':
            home = os.environ['HOMEPATH']

        home_DB_path = ('%s%s%s') % (home, os.sep, 'pyarchinit_DB_folder')
        logo_path = ('%s%s%s') % (home_DB_path, os.sep, 'logo.jpg')

        logo = Image(logo_path)
        logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth
        logo.drawWidth = 1.5 * inch
        logo.hAlign = "LEFT"

        styleSheet = getSampleStyleSheet()
        styNormal = styleSheet['Normal']
        styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.pink)
        styH1 = styleSheet['Heading3']

        data = self.datestrfdate()

        lst = []
        lst.append(logo)
        lst.append(
            Paragraph("<b>ELENCO UNITA' STRATIGRAFICHE</b><br/><b>Scavo: %s,  Data: %s</b>" % (sito, data), styH1))

        table_data = []
        for i in range(len(records)):
            exp_index = US_index_pdf_sheet(records[i])
            table_data.append(exp_index.getTable())

        styles = exp_index.makeStyles()
        colWidths = [28, 28, 120, 45, 58, 45, 58, 55, 64, 64, 52, 52, 52]

        table_data_formatted = Table(table_data, colWidths, style=styles)
        table_data_formatted.hAlign = "LEFT"

        lst.append(table_data_formatted)
        lst.append(Spacer(0, 2))

        filename = ('%s%s%s') % (self.PDF_path, os.sep, 'elenco_us.pdf')
        f = open(filename, "wb")

        doc = SimpleDocTemplate(f, pagesize=(29 * cm, 21 * cm), showBoundary=0)
        doc.build(lst, canvasmaker=NumberedCanvas_USindex)

        f.close()
Exemple #2
0
    def getTable(self):
        styleSheet = getSampleStyleSheet()
        styNormal = styleSheet['Normal']
        styNormal.spaceBefore = 20
        styNormal.spaceAfter = 20
        styNormal.alignment = 0  # LEFT
        styNormal.fontSize = 9
     

        #1 row
        a_location_ = Paragraph( str(self.location_), styNormal)
        name_site = Paragraph( "<b>Name</b><br/>" +str(self.name_site), styNormal)
        #photolog2 = Paragraph("<b>Photolog</b><br/>", styInt)
        
        #pp= range(len(self.photolog)))
        photologs2 = eval(self.photo_material)
        camera_id='' 
        material=''
        quantity=''
        dec=''
           
           
       
        for i in photologs2:
            if camera_id=='':
                try:
                    camera_id += str(i[0]) + "<br/>"
                    material +=  str(i[1]) + "<br/>"
                    quantity +=  str(i[2]) + "<br/>"
                    dec +=  str(i[3]) + "<br/>"
                except:
                    pass
            else:
                try:
                    camera_id +=  ' ' + str(i[0]) + "<br/>"
                    material += ' ' + str(i[1]) + "<br/>"
                    quantity +=   ' ' + str(i[2]) + "<br/>"
                    dec +=   ' ' + str(i[3]) + "<br/>"
                except:
                    pass
                                
        camera_id = Paragraph("<b>ID</b><br/>" + str(camera_id), styNormal)
        material = Paragraph("<b>Material</b><br/>" + str(material), styNormal)
        quantity = Paragraph("<b>Quantity</b><br/>" + str(quantity), styNormal)
        dec = Paragraph("<b>Photo Description</b><br/>" + str(dec), styNormal)
        data =[
            
            name_site,
            camera_id,
            material,
            quantity,
            dec
            ]
        return data
 def doSome():
     for i in range(10):
         story.append(Paragraph('Heading 1 always starts a new page (%d)' % len(story), h1))
         for j in range(3):
             story.append(Paragraph('Heading1 paragraphs should always'
                             'have a page break before.  Heading 2 on the other hand'
                             'should always have a FRAME break before (%d)' % len(story), bt))
             story.append(Paragraph('Heading 2 always starts a new frame (%d)' % len(story), h2))
             story.append(Paragraph('Heading1 paragraphs should always'
                             'have a page break before.  Heading 2 on the other hand'
                             'should always have a FRAME break before (%d)' % len(story), bt))
             for j in range(3):
                 story.append(Paragraph(randomText(theme=PYTHON, sentences=2)+' (%d)' % len(story), bt))
                 story.append(Paragraph('I should never be at the bottom of a frame (%d)' % len(story), h3))
                 story.append(Paragraph(randomText(theme=PYTHON, sentences=1)+' (%d)' % len(story), bt))
Exemple #4
0
def drawrelationshipcs(can, resultsbuffer):
    can.setFont("Helvetica", 24)
    sec_title = "System Heat Balance"
    can.drawString(25, 750, sec_title)

    desc_text = "The following figure shows the relationship between the chilled water" \
                " system operating efficiency and the cooling load. As the figure shows, with " \
                "the Cooling load ranges between 800 RT to 1100 RT, the efficiency hovers between " \
                "0.75/RT to 0.91KW/RT."
    stylesheet = getSampleStyleSheet()
    paragraph = Paragraph(desc_text, stylesheet['Normal'])
    aW, aH = 500, 600
    w, h = paragraph.wrap(aW, aH)
    if w <= aW and h <= aH:
        paragraph.drawOn(can, 25, 700)

    drawing = Drawing(600, 400)
    data = [((801, 0.7), (903, 0.8), (799, 0.84), (1002, 0.97), (1101, 0.89)),
            ((987, 0.98), (1007, 1.1), (1102, 0.98), (987, 0.95), (908, 0.89))]
    lp = LinePlot()
    lp.x = 50
    lp.y = 50
    lp.height = 250
    lp.width = 400
    lp.data = data
    lp.joinedLines = 0
    lp.lines.symbol = makeMarker('FilledCircle')
    # lp.lines.symbol = makeMarker('Circle')
    # lp.lines[1].symbol = makeMarker('Circle')
    lp.lineLabelFormat = '%2.0f'
    lp.strokeColor = colors.black
    lp.xValueAxis.valueMin = 0
    lp.xValueAxis.valueMax = 1200
    lp.xValueAxis.valueSteps = [
        0.00, 200.00, 400.00, 600.00, 800.00, 1000.00, 1200.00
    ]
    lp.xValueAxis.labelTextFormat = '%2.1f'
    lp.yValueAxis.valueMin = 0
    lp.yValueAxis.valueMax = 1.2
    lp.yValueAxis.valueSteps = [
        0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2
    ]
    drawing.add(lp)
    drawing.drawOn(can, 50, 350)

    can.showPage()
 def main():
     from reportlab.graphics.barcode.code128 import Code128
     from reportlab.platypus import Spacer, SimpleDocTemplate
     from reportlab.lib.units import inch, cm
     from reportlab.lib.styles import getSampleStyleSheet
     from reportlab.platypus.paragraph import Paragraph
     from reportlab.platypus.flowables import KeepTogether
     import os
     styles = getSampleStyleSheet()
     styleN = styles['Normal']
     styleH = styles['Heading1']
     story = []
     storyAdd = story.append
     for s in (
             'BBBB123456BBB',
             'BBBB12345BBB',
             'BBBB1234BBB',
             'BBBB123BBB',
             'BBBB12BBB',
             'BBBB1BBB',
             'BBBB123456aa',
             'BBBB1234aa',
             'BBBB123aa',
             'BBBB12aa',
             'BBBB1aa',
             'BBBB123456',
             'BBBB12345',
             'BBBB1234',
             'BBBB123',
             'BBBB12',
             'BBBB1',
             '\xf11234B',
             'Ba\xf11234B',
             'Ba12',
             'Ba123B',
             'Ba1234B',
             'BBBB1234567',
             'BBBB1234567aa',
     ):
         storyAdd(
             KeepTogether(
                 [Paragraph('Code 128 %r' % s, styleN),
                  Code128(s)]))
         storyAdd(Spacer(inch, inch))
     SimpleDocTemplate('code128-out.pdf').build(story)
Exemple #6
0
    def wrap(self, availWidth, availHeight):
        "All table properties should be known by now."

        # makes an internal table which does all the work.
        # we draw the LAST RUN's entries!  If there are
        # none, we make some dummy data to keep the table
        # from complaining
        if len(self._lastEntries) == 0:
            _tempEntries = [(0,'Placeholder for table of contents',0,None)]
        else:
            _tempEntries = self._lastEntries

        def drawTOCEntryEnd(canvas, kind, label):
            '''Callback to draw dots and page numbers after each entry.'''
            page, level = [ int(x) for x in label.split(',') ]
            x, y = canvas._curr_tx_info['cur_x'], canvas._curr_tx_info['cur_y']
            style = self.levelStyles[level]
            pagew = stringWidth('  %d' % page, style.fontName, style.fontSize)
            if self.dotsMinLevel >= 0 and level >= self.dotsMinLevel:
                dotw = stringWidth(' . ', style.fontName, style.fontSize)
                dotsn = int((availWidth-x-pagew)/dotw)
            else:
                dotsn = dotw = 0

            tx = canvas.beginText(availWidth-pagew-dotsn*dotw, y)
            tx.setFont(style.fontName, style.fontSize)
            tx.textLine('%s  %d' % (dotsn * ' . ', page))
            canvas.drawText(tx)
        self.canv.drawTOCEntryEnd = drawTOCEntryEnd

        tableData = []
        for (level, text, pageNum, key) in _tempEntries:
            style = self.levelStyles[level]
            if key:
                text = '<a href="#%s">%s</a>' % (key, text)
            para = Paragraph('%s<onDraw name="drawTOCEntryEnd" label="%d,%d"/>' % (text, pageNum, level), style)
            if style.spaceBefore:
                tableData.append([Spacer(1, style.spaceBefore),])
            tableData.append([para,])

        self._table = Table(tableData, colWidths=(availWidth,),
                            style=self.tableStyle)

        self.width, self.height = self._table.wrapOn(self.canv,availWidth, availHeight)
        return (self.width, self.height)
Exemple #7
0
    def do_table_wrap(self, availWidth, availHeight):
        styles = getSampleStyleSheet()
        sN = styles['Normal']
        sN.alignment = TA_CENTER
        data = [["" for x in range(12)] for y in range(3)]

        data[0][1] = Paragraph(
            "<br/><br/><strong>%s</strong>" % self.master.pathologist.fullname,
            sN)
        data[1][1] = Paragraph(
            self.master.pathologist.get_designation_display(), sN)
        data[2][1] = Paragraph(
            "PRC LIC #: %s" % self.master.pathologist.license, sN)

        data[0][7] = Paragraph(
            "<br/><br/><br/><strong>%s</strong>" %
            self.master.medical_technologist.fullname, sN)
        data[1][7] = Paragraph(
            self.master.medical_technologist.get_designation_display(), sN)
        data[2][7] = Paragraph(
            "PRC LIC #: %s" % self.master.medical_technologist.license, sN)

        w = availWidth - self.margin * 2
        spacer = int(w * 0.05)
        remWidth = (w - (spacer * 4)) / 8
        colWidths = [spacer] + \
            [remWidth] * 4 + \
            [spacer] * 2 + \
            [remWidth] * 4 + \
            [spacer]
        self.table = Table(data, colWidths=colWidths)
        self.table.setStyle(
            TableStyle([
                # config padding
                ('TOPPADDING', (0, 0), (-1, -1), 0),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
                # lines
                ('LINEBELOW', (1, 0), (4, 0), 1, black),
                ('LINEBELOW', (7, 0), (10, 0), 1, black),
                # ('GRID', (0, 0), (-1, -1), 1, black),
                # Column 1
                ('SPAN', (1, 0), (4, 0)),
                ('SPAN', (1, 1), (4, 1)),
                ('SPAN', (1, 2), (4, 2)),
                # Column 2
                ('SPAN', (7, 0), (10, 0)),
                ('SPAN', (7, 1), (10, 1)),
                ('SPAN', (7, 2), (10, 2)),
            ]))
        self.table.canv = self.canv
        return self.table.wrap(availWidth, availHeight)
Exemple #8
0
    def test(self):
        outPDF = "test_compare.pdf"
        pageSize = pagesizes.portrait(pagesizes.A4)
        canv = Canvas(outPDF, pagesize=pageSize)

        # common variables
        W, H = 5 * cm, 20 * cm
        kifMode = "shrink"  # overflow/truncate/shrink/error

        # hyphenated column
        p = HyParagraph(testdata, sth)
        story = [p]
        frame = KeepInFrame(W, H, story, mode=kifMode)
        w, h = frame.wrapOn(canv, W, H)
        x, y = 100, 100
        frame.drawOn(canv, x, y + (H - h))
        canv.setLineWidth(2)
        canv.setStrokeColor(black)
        canv.circle(x, y, 10)
        canv.setStrokeColor(red)
        canv.rect(x, y, W, H)
        canv.setLineWidth(1)
        canv.setStrokeColor(blue)
        canv.rect(x, y + (H - h), w, h)

        # non-hyphenated column
        p = Paragraph(testdata, st)
        story = [p]
        frame = KeepInFrame(W, H, story, mode=kifMode)
        w, h = frame.wrapOn(canv, W, H)
        x, y = 300, 100
        frame.drawOn(canv, x, y + (H - h))
        canv.setLineWidth(2)
        canv.setStrokeColor(black)
        canv.circle(x, y, 10)
        canv.setStrokeColor(red)
        canv.rect(x, y, W, H)
        canv.setLineWidth(1)
        canv.setStrokeColor(blue)
        canv.rect(x, y + (H - h), w, h)

        canv.showPage()
        canv.save()
    def build_index_Struttura(self, records, sito):
        home = os.environ['PYARCHINIT_HOME']

        home_DB_path = '{}{}{}'.format(home, os.sep, 'pyarchinit_DB_folder')
        logo_path = '{}{}{}'.format(home_DB_path, os.sep, 'logo.jpg')

        logo = Image(logo_path)
        logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth
        logo.drawWidth = 1.5 * inch
        logo.hAlign = "LEFT"

        styleSheet = getSampleStyleSheet()
        styNormal = styleSheet['Normal']
        styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.pink)
        styH1 = styleSheet['Heading3']

        data = self.datestrfdate()

        lst = []
        lst.append(logo)
        lst.append(Paragraph("<b>ELENCO STRUTTURE</b><br/><b>Scavo: %s,  Data: %s</b>" % (sito, data), styH1))

        table_data = []
        for i in range(len(records)):
            exp_index = Struttura_index_pdf_sheet(records[i])
            table_data.append(exp_index.getTable())

        styles = exp_index.makeStyles()
        colWidths = [60, 60, 80, 80, 80, 50, 50, 50, 50, 100]

        table_data_formatted = Table(table_data, colWidths, style=styles)
        table_data_formatted.hAlign = "LEFT"

        lst.append(table_data_formatted)
        # lst.append(Spacer(0,2))

        filename = '{}{}{}'.format(self.PDF_path, os.sep, 'elenco_strutture.pdf')
        f = open(filename, "wb")

        doc = SimpleDocTemplate(f, pagesize=(29 * cm, 21 * cm), showBoundary=0)
        doc.build(lst, canvasmaker=NumberedCanvas_STRUTTURAindex)

        f.close()
Exemple #10
0
    def __init__(self, name, showBoundary=0, **kw):

        frames = [
            Frame(15 * mm,
                  40 * mm,
                  self.width - 30 * mm,
                  self.height - 75 * mm,
                  id='normal',
                  leftPadding=0,
                  bottomPadding=0,
                  rightPadding=0,
                  topPadding=0,
                  showBoundary=showBoundary)
        ]
        BaseInvoiceTemplate.__init__(self,
                                     name,
                                     frames=frames,
                                     showBoundary=showBoundary,
                                     **kw)

        self.senderFrame = Frame(20 * mm,
                                 self.height - 35 * mm + 20,
                                 60 * mm,
                                 20 * mm,
                                 id='sender',
                                 leftPadding=0,
                                 bottomPadding=0,
                                 rightPadding=0,
                                 topPadding=0,
                                 showBoundary=showBoundary)
        self.senderFooterFrame = Frame(15 * mm,
                                       12 * mm,
                                       55 * mm,
                                       20 * mm,
                                       id='senderfooter',
                                       leftPadding=0,
                                       bottomPadding=0,
                                       rightPadding=0,
                                       topPadding=0,
                                       showBoundary=showBoundary)
        self.sendertext = s = []
        for line in kw.get('senderaddr', []):
            s.append(Paragraph(line, self.smallstyle))
 def test5(self):
     '''extreme test inspired by Moritz Pfeiffer https://bitbucket.org/moritzpfeiffer/'''
     with self.assertRaises(LayoutError):
         text = """
         Clearly, the natural general principle that will subsume this case is
         not subject to a parasitic gap construction.  Presumably, most of the
         methodological work in modern linguistics can be defined in such a way
         as to impose the system of base rules exclusive of the lexicon.  In the
         discussion of resumptive pronouns following (81), the fundamental error
         of regarding functional notions as categorial is to be regarded as a
         descriptive <span color="red">fact</span>.<br/>So far, the earlier discussion of deviance is not
         quite equivalent to a parasitic gap construction.  To characterize a
         linguistic level L, a case of semigrammaticalness of a different sort
         may remedy and, at the same time, eliminate irrelevant intervening
         contexts in selectional <span color="red">rules</span>.<br/>
         Summarizing, then, we assume that the descriptive power of the base
         component can be defined in such a way as to impose nondistinctness in
         the sense of distinctive feature theory.
         """
         styleSheet = getSampleStyleSheet()
         story = []
         story.append(Paragraph(text, styleSheet['Normal']))
         doc = BaseDocTemplate(
             outputfile('test_platypus_much_too_large.pdf'),
             pagesize=portrait(A4),
             pageTemplates=[
                 PageTemplate(
                     'page_template',
                     [
                         Frame(0,
                               0,
                               0,
                               0,
                               leftPadding=0,
                               rightPadding=0,
                               topPadding=0,
                               bottomPadding=0,
                               id='DUMMY_FRAME')
                     ],
                 )
             ],
         )
         doc.build(story)
Exemple #12
0
        def gpsCoordStringer(textfield1, textfield2, textfield3, textfield4,
                             styleKey):
            gpsString = []
            if len(dfl(textfield1)) > 0:
                if (dfl(textfield1) and dfl(textfield2)):
                    # min([len(dfl(textfield1)),len(dfl(textfield2))]) testing length control.
                    gpsString.append('<b>GPS: </b>' + dfl(textfield1) + ', ' +
                                     dfl(textfield2))
                if dfl(textfield3):
                    gpsString.append(
                        ' ± ' +
                        str(round(float(dfl(textfield3)), 0)).split('.')[0] +
                        'm')
                if dfl(textfield4):
                    gpsString.append(', <b>Elevation: </b>' + dfl(textfield4) +
                                     'm')

                return Paragraph(''.join(gpsString),
                                 style=self.stylesheet(styleKey))
Exemple #13
0
 def build_index_SHIPWRECK(self, records, divelog_id):
     HOME = os.environ['HFF_HOME']
     PDF_path = '{}{}{}'.format(HOME, os.sep, "HFF_PDF_folder")
     home_DB_path = '{}{}{}'.format(HOME, os.sep, 'HFF_DB_folder')
     logo_path = '{}{}{}'.format(home_DB_path, os.sep, 'banner.png')
     logo = Image(logo_path)
     ##      if test_image.drawWidth < 800:
     logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth
     logo.drawWidth = 1.5 * inch
     # logo_path2 = '{}{}{}'.format(home_DB_path, os.sep, 'logo2.png')
     # logo2 = Image(logo_path2)
     # ##      if test_image.drawWidth < 800:
     # logo2.drawHeight = 0.5*inch*logo2.drawHeight / logo2.drawWidth
     # logo2.drawWidth = 0.5*inch
     # #1 row
     logo.hAlign = "LEFT"
     styleSheet = getSampleStyleSheet()
     styNormal = styleSheet['Normal']
     styBackground = ParagraphStyle('background',
                                    parent=styNormal,
                                    backColor=colors.pink)
     styH1 = styleSheet['Heading3']
     data = self.datestrfdate()
     lst = []
     lst.append(logo)
     lst.append(
         Paragraph("<b>SHIPWRECK List</b><br/><b>Data: %s</b>" % (data),
                   styH1))
     table_data1 = []
     for i in range(len(records)):
         exp_index = SHIPWRECK_index_pdf(records[i])
         table_data1.append(exp_index.getTable())
     styles = exp_index.makeStyles()
     colWidths = [70, 100, 100, 100, 100, 70, 70]
     table_data1_formatted = Table(table_data1, colWidths, style=styles)
     table_data1_formatted.hAlign = "LEFT"
     lst.append(table_data1_formatted)
     lst.append(Spacer(0, 2))
     filename = ('%s%s%s') % (self.PDF_path, os.sep, 'SHIPWRECK_list.pdf')
     f = open(filename, "wb")
     doc = SimpleDocTemplate(f, pagesize=(29 * cm, 21 * cm), showBoundary=0)
     doc.build(lst, canvasmaker=NumberedCanvas_USindex)
     f.close()
    def wrap(self, availWidth, availHeight):
        "All table properties should be known by now."

        # makes an internal table which does all the work.
        # we draw the LAST RUN's entries!  If there are
        # none, we make some dummy data to keep the table
        # from complaining
        if len(self._lastEntries) == 0:
            _tempEntries = [(0,'Placeholder for table of contents',0,None)]
        else:
            _tempEntries = self._lastEntries

        def drawTOCEntryEnd(canvas, kind, label):
            '''Callback to draw dots and page numbers after each entry.'''
            label = label.split(',')
            page, level, key = int(label[0]), int(label[1]), eval(label[2],{})
            style = self.getLevelStyle(level)
            if self.dotsMinLevel >= 0 and level >= self.dotsMinLevel:
                dot = ' . '
            else:
                dot = ''
            if self.formatter: page = self.formatter(page)
            drawPageNumbers(canvas, style, [(page, key)], availWidth, availHeight, dot)
        self.canv.drawTOCEntryEnd = drawTOCEntryEnd

        tableData = []
        for (level, text, pageNum, key) in _tempEntries:
            style = self.getLevelStyle(level)
            if key:
                text = '<a href="#%s">%s</a>' % (key, text)
                keyVal = repr(key).replace(',','\\x2c').replace('"','\\x2c')
            else:
                keyVal = None
            para = Paragraph('%s<onDraw name="drawTOCEntryEnd" label="%d,%d,%s"/>' % (text, pageNum, level, keyVal), style)
            if style.spaceBefore:
                tableData.append([Spacer(1, style.spaceBefore),])
            tableData.append([para,])

        self._table = Table(tableData, colWidths=(availWidth,), style=self.tableStyle)

        self.width, self.height = self._table.wrapOn(self.canv,availWidth, availHeight)
        return (self.width, self.height)
    def testUl(self):
        from reportlab.platypus import BaseDocTemplate, PageTemplate, Frame, PageBegin
        from reportlab.lib.units import inch
        class MyDocTemplate(BaseDocTemplate):
            _invalidInitArgs = ('pageTemplates',)

            def __init__(self, filename, **kw):
                self.allowSplitting = 0
                BaseDocTemplate.__init__(self, filename, **kw)
                self.addPageTemplates(
                        [
                        PageTemplate('normal',
                                [Frame(inch, inch, 6.27*inch, 9.69*inch, id='first',topPadding=0,rightPadding=0,leftPadding=0,bottomPadding=0,showBoundary=ShowBoundaryValue(color="red"))],
                                ),
                        ])

        styleSheet = getSampleStyleSheet()
        normal = ParagraphStyle(name='normal',fontName='Times-Roman',fontSize=12,leading=1.2*12,parent=styleSheet['Normal'])
        normal_just = ParagraphStyle(name='normal_just',parent=normal,alignment=TA_JUSTIFY,spaceAfter=12)
        text0 = '''Furthermore, a subset of English sentences interesting on quite
independent grounds is not quite equivalent to a stipulation to place
the constructions into these various categories. We will bring evidence in favor of
The following thesis:  most of the methodological work in modern
linguistics can be defined in such a way as to impose problems of
phonemic and morphological analysis.'''
        story =[]
        a = story.append
        for mode in (0,1,2,3,4):
            text = text0
            if mode==1:
                text = text.replace('English sentences','<b>English sentences</b>').replace('quite equivalent','<i>quite equivalent</i>')
                text = text.replace('the methodological work','<b>the methodological work</b>').replace('to impose problems','<i>to impose problems</i>')
                a(Paragraph('Justified paragraph in normal/bold/italic font',style=normal))
            elif mode==2:
                text = '<b>%s</b>' % text
                a(Paragraph('Justified paragraph in bold font',style=normal))
            elif mode==3:
                text = '<i>%s</i>' % text
                a(Paragraph('Justified paragraph in italic font',style=normal))
            elif mode==4:
                text = text.replace('English ','English&nbsp;').replace('quite ','quite&nbsp;')
                text = text.replace(' methodological','&nbsp;methodological').replace(' impose','&nbsp;impose')
                a(Paragraph('Justified paragraph in normal font & some hard spaces',style=normal))
            else:
                a(Paragraph('Justified paragraph in normal font',style=normal))

            a(Paragraph(text,style=normal_just))
        doc = MyDocTemplate(outputfile('test_platypus_paragraphs_just.pdf'))
        doc.build(story)
Exemple #16
0
 def beforeDrawPage(self, canvas, doc):
     canvas.setFont(serif_font, 8)
     canvas.saveState()
     if pdfstyles.show_title_page_footer:
         canvas.line(footer_margin_hor, footer_margin_vert,
                     page_width - footer_margin_hor, footer_margin_vert)
         footertext = [_(titlepagefooter)]
         if pdfstyles.show_creation_date:
             locale.setlocale(locale.LC_ALL, '')
             footertext.append(pdfstyles.creation_date_txt % time.strftime(
                 pdfstyles.creation_date_format, time.localtime()))
         lines = [
             formatter.cleanText(line, escape=False) for line in footertext
         ]
         txt = '<br/>'.join(
             line if isinstance(line, unicode) else unicode(line, 'utf-8')
             for line in lines)
         p = Paragraph(txt, text_style(mode='footer'))
         w, h = p.wrap(print_width, print_height)
         canvas.translate((page_width - w) / 2.0,
                          footer_margin_vert - h - 0.25 * cm)
         p.canv = canvas
         p.draw()
     canvas.restoreState()
     if self.cover:
         width, height = self._scale_img(pdfstyles.title_page_image_size,
                                         self.cover)
         if pdfstyles.title_page_image_pos[0] == None:
             x = (page_width - width) / 2.0
         else:
             x = max(
                 0,
                 min(page_width - width, pdfstyles.title_page_image_pos[0]))
         if pdfstyles.title_page_image_pos[1] == None:
             y = (page_height - height) / 2.0
         else:
             y = max(
                 0,
                 min(page_height - height,
                     pdfstyles.title_page_image_pos[1]))
         canvas.drawImage(self.cover, x, y, width, height)
Exemple #17
0
 def test_issue181(self):
     '''issue #181 rasied by Daniel Turecek'''
     from reportlab.lib.styles import ParagraphStyle as PS
     from reportlab.platypus import Paragraph, SimpleDocTemplate, PageBreak
     style = PS(fontname='Helvetica', name='Title', fontSize=10, leading=12, alignment=1)
     add = [].append
     add(Paragraph('<a name="top"/>Top', style))
     add(Paragraph('<a href="#test">Local Link</a>', style))
     add(Paragraph('<a href="document:test">Document Link</a>', style))
     add(Paragraph('<a href="www.reportlab.com">website</a>', style))
     add(PageBreak())
     add(Paragraph('<a name="test"/>Anchor', style))
     add(Paragraph('<a href="#top">top</a>', style))
     doc = SimpleDocTemplate(outputfile("test_issue181.pdf"))
     doc.build(add.__self__)
Exemple #18
0
    def getintestazione(self):
        styleSheet = getSampleStyleSheet()
        styNormal = styleSheet['Normal']
        styNormal.spaceBefore = 20
        styNormal.spaceAfter = 20
        styNormal.alignment = 0  # LEFT
        styNormal.fontSize = 9
        #1 row

        divelog1 = Paragraph("DIVEID", styNormal)
        area_id1 = Paragraph("Area", styNormal)
        photo_id1 = Paragraph("PhotoID", styNormal)
        description_p1 = Paragraph("Description", styNormal)
        video_id1 = Paragraph("VideoID", styNormal)
        description_v1 = Paragraph("Description", styNormal)
def applyStyle(row, font, colspacing):
    tmpRow = []
    for i, cell in enumerate(row):
        for fontsize in [8, 7, 6, 5]:
            lines = simpleSplit(str(cell), font, fontsize, colspacing[i])

            if len(lines) < 3 and ((len(lines) * fontsize * 1.2)) < 19:
                style = ParagraphStyle(
                    name='normal',
                    alignment=1,
                    leading=fontsize,
                    # leftIndent=0,
                    # borderPadding=0,
                    # rightIndent=0,
                    # spaceBefore=0,
                    # spaceAfter=0,
                    wordWrap=None,
                    fontSize=fontsize)
                break
        tmpRow.append(Paragraph(str(cell), style))
    return tmpRow
Exemple #20
0
    def run():
        objects_to_draw = []
        from reportlab.lib.styles import ParagraphStyle
        #from paragraph import Paragraph
        from reportlab.platypus.doctemplate import SimpleDocTemplate

        #need a style
        normal = ParagraphStyle('normal')
        normal.firstLineIndent = 18
        normal.spaceBefore = 6
        from reportlab.lib.randomtext import randomText
        import random
        for i in range(15):
            height = 0.5 + (2*random.random())
            box = XBox(6 * inch, height * inch, 'Box Number %d' % i)
            objects_to_draw.append(box)
            para = Paragraph(randomText(), normal)
            objects_to_draw.append(para)

        SimpleDocTemplate('doctemplate.pdf').build(objects_to_draw,
            onFirstPage=myFirstPage,onLaterPages=myLaterPages)
Exemple #21
0
    def render(self):
        buff = BytesIO()
        try:
            doc = ReportTemplate(buff)
            styles = self.styles
            story = []

            story.append(MasterInfo(master=self.master))
            story.append(Paragraph(self.master.title, styles['Title']))

            for row in self.rows():
                story.append(row)

            doc.multiBuild(story)
            buff.flush()

            raw_value = buff.getvalue()
        finally:
            buff.close()

        return raw_value
Exemple #22
0
    def wrap(self, availWidth, availHeight):
        width = availWidth * .8
        colwidth = width / 3

        row_count = len(self.data)
        row_height = availHeight / row_count

        fontsize = int((row_height * 1000) / 2)
        print "row_height = ", row_height
        print "fontsize = ", fontsize
        if fontsize > 14:
            fontsize = 14

        sH = self.styles["Heading2"]
        sH.fontSize = fontsize + 2
        sN = self.styles["Normal"]
        sN.fontSize = fontsize
        sN.alignment = TA_CENTER
        fontSmall = fontsize - 4
        data = []
        for l in self.data:
            row = []
            for idx, m in enumerate(l):
                if m:
                    if idx == 0:
                        sN.alignment = TA_RIGHT
                    else:
                        sN.alignment = TA_CENTER
                    if idx == 2:
                        sN.fontSize = fontSmall
                    else:
                        sN.fontSize = fontsize
                    row.append(Paragraph(m, sN))
                else:
                    row.append("xxx")
            data.append(row)

        self.table = Table(data, colWidths=[colwidth] * 3, hAlign='CENTER')
        self.table.canv = self.canv
        return self.table.wrap(width, availHeight)
Exemple #23
0
 def beforeDrawPage(self, canvas, doc):
     canvas.setFont(serif_font, 8)
     canvas.saveState()
     if pdfstyles.show_title_page_footer:
         canvas.line(footer_margin_hor, footer_margin_vert,
                     page_width - footer_margin_hor, footer_margin_vert)
         footertext = [_(titlepagefooter)]
         if pdfstyles.show_creation_date:
             footertext.append(
                 'PDF generated at: %s' %
                 strftime("%a, %d %b %Y %H:%M:%S %Z", gmtime()))
         p = Paragraph(
             '<br/>'.join([
                 formatter.cleanText(line, escape=False)
                 for line in footertext
             ]), text_style(mode='footer'))
         w, h = p.wrap(print_width, print_height)
         canvas.translate((page_width - w) / 2.0, 0.2 * cm)
         p.canv = canvas
         p.draw()
     canvas.restoreState()
     if self.cover:
         width, height = self._scale_img(pdfstyles.title_page_image_size,
                                         self.cover)
         if pdfstyles.title_page_image_pos[0] == None:
             x = (page_width - width) / 2.0
         else:
             x = max(
                 0,
                 min(page_width - width, pdfstyles.title_page_image_pos[0]))
         if pdfstyles.title_page_image_pos[1] == None:
             y = (page_height - height) / 2.0
         else:
             y = max(
                 0,
                 min(page_height - height,
                     pdfstyles.title_page_image_pos[1]))
         canvas.drawImage(self.cover, x, y, width, height)
    def test(self):    
        stylesheet = getSampleStyleSheet()
        normal = stylesheet['BodyText']
        normal.fontName = "Helvetica"
        normal.fontSize = 12
        normal.leading = 16
        normal.alignment = TA_JUSTIFY
    
        text = "Bedauerlicherweise ist ein Donaudampfschiffkapit\xc3\xa4n auch <font color='red'>nur</font> <font color='green'>ein</font> Dampfschiffkapit\xc3\xa4n."
        tagFormat = '%s'
        # strange behaviour when using next code line
        # (same for '<a href="http://www.reportlab.org">%s</a>'
        tagFormat = '<font color="red">%s</font>'

        #text = " ".join([tagFormat % w for w in text.split()])
        
        story = [Paragraph((text + " ") * 3, style=normal)]

        from reportlab.lib import pagesizes
        PAGESIZE = pagesizes.landscape(pagesizes.A4)
        
        doc = TwoFrameDocTemplate(outputfile('test_paragraphs_splitframe.pdf'), pagesize=PAGESIZE)
        doc.build(story)
Exemple #25
0
    def wrap(self, availWidth, availHeight):
        "All table properties should be known by now."
        # makes an internal table which does all the work.
        # we draw the LAST RUN's entries!  If there are
        # none, we make some dummy data to keep the table
        # from complaining
        if len(self._lastEntries) == 0:
            _tempEntries = [('Placeholder for index',[0,1,2])]
        else:
            _tempEntries = self._lastEntries.items()
            _tempEntries.sort()

        tableData = []
        for (text, pageNumbers) in _tempEntries:
            #right col style is right aligned
            allText = text + ': ' + string.join(map(str, pageNumbers), ', ')
            para = Paragraph(allText, self.textStyle)
            tableData.append([para])

        self._table = Table(tableData, colWidths=[availWidth])

        self.width, self.height = self._table.wrapOn(self.canv,availWidth, availHeight)
        return (self.width, self.height)
Exemple #26
0
    def afterPage(self):
        """Called after each page has been processed"""

        # saveState keeps a snapshot of the canvas state, so you don't
        # mess up any rendering that platypus will do later.
        self.canv.saveState()

        # Reset the origin to (0, 0), remember, we can restore the
        # state of the canvas later, so platypus should be unaffected.
        self.canv._x = 0
        self.canv._y = 0

        style = getSampleStyleSheet()

        p = Paragraph("This is drawn after the page!", style["Normal"])

        # Wraps and draws the paragraph onto the canvas
        # You can change the last 2 parameters (canv, x, y)
        p.wrapOn(self.canv, 2*inch, 2*inch)
        p.drawOn(self.canv, 1*inch, 3*inch)

        # Now we restore the canvas back to the way it was.
        self.canv.restoreState()
def textAccum2():
    doc = MyDocTemplate(outputfile('test_platypus_accum2.pdf'),
                        pagesize=(8.5 * inch, 11 * inch),
                        showBoundary=1)
    story = []
    story.append(Paragraph("A table with 500 rows", styleSheet['BodyText']))
    sty = [
        ('GRID', (0, 0), (-1, -1), 1, colors.green),
        ('BOX', (0, 0), (-1, -1), 2, colors.red),
        ('FONTNAME', (0, 0), (-1, -1), 'Helvetica'),
        ('FONTSIZE', (0, 0), (-1, -1), 10),
    ]

    def myCV(s, fontName='Helvetica', fontSize=10, maxWidth=72):
        return '\n'.join(simpleSplit(s, fontName, fontSize, maxWidth))

    data = [[
        PA.onDrawStr(str(i + 1), i + 1),
        myCV("xx " * (i % 10), maxWidth=100 - 12),
        myCV("blah " * (i % 40), maxWidth=200 - 12)
    ] for i in range(500)]
    t = LongTable(data, style=sty, colWidths=[50, 100, 200])
    story.append(t)
    doc.build(story)
    def getTable_de(self):
        styleSheet = getSampleStyleSheet()
        styNormal = styleSheet['Normal']
        styNormal.spaceBefore = 20
        styNormal.spaceAfter = 20
        styNormal.alignment = 0  # LEFT
        styNormal.fontSize = 9

        # self.unzip_rapporti_stratigrafici()

        periodo = Paragraph("<b>Period</b><br/>" + str(self.periodo),
                            styNormal)

        fase = Paragraph("<b>Phase</b><br/>" + str(self.fase), styNormal)

        if str(self.cron_iniziale) == "None":
            cron_iniziale = Paragraph(
                "<b>Anfangschronologie</b><br/>" + str(self.cron_iniziale),
                styNormal)
        else:
            cron_iniziale = Paragraph("<b>Anfangschronologie</b><br/>",
                                      styNormal)

        if str(self.cron_finale) == "None":
            cron_finale = Paragraph(
                "<b>Letzte Chronologie</b><br/>" + str(self.cron_finale),
                styNormal)
        else:
            cron_finale = Paragraph("<b>Letzte Chronologie</b><br/>",
                                    styNormal)

        datazione_estesa = Paragraph(
            "<b>Erweiterte Datierung</b><br/>" + str(self.datazione_estesa),
            styNormal)

        data = [periodo, fase, cron_iniziale, cron_finale, datazione_estesa]

        return data
Exemple #29
0
def drawsystempeakefficieny(can, resultsbuffer):
    can.setFont("Helvetica", 24)
    sec_title = "System Peak Efficiency Breakdown"
    can.drawString(25, 750, sec_title)

    desc_text = "The system operating peak efficiency measures the peak efficiency value between " \
                "the selected dates for different parts of the system."
    stylesheet = getSampleStyleSheet()
    paragraph = Paragraph(desc_text, stylesheet['Normal'])
    aW, aH = 500, 600
    w, h = paragraph.wrap(aW, aH)
    if w <= aW and h <= aH:
        paragraph.drawOn(can, 25, 700)

    peak = (ce_peak, chwp_peak, cwp_peak, ct_peak) = (0.656, 0.075, 0.024,
                                                      0.027)
    overall_peak = sum(peak)
    chiller_peak_str = Paragraph("Chiller Efficiency", stylesheet['Normal'])
    chwp_peak_str = Paragraph("Chilled Water Pump Efficiency",
                              stylesheet['Normal'])
    cwp_peak_str = Paragraph("Condenser Water Pump Efficiency",
                             stylesheet['Normal'])
    ct_peak_str = Paragraph("Cooling Tower Efficiency", stylesheet['Normal'])
    overall_peak_str = Paragraph("Overall Efficiency", stylesheet['Normal'])
    data = [[' ', 'Peak', 'Unit'], [chiller_peak_str, ce_peak, 'KW/RT'],
            [chwp_peak_str, chwp_peak, 'KW/RT'],
            [cwp_peak_str, cwp_peak, 'KW/RT'], [ct_peak_str, ct_peak, 'KW/RT'],
            [overall_peak_str, overall_peak, 'KW/RT']]
    t = Table(data, [2.5 * inch, inch, inch], 6 * [0.5 * inch])
    t.setStyle(
        TableStyle([
            ('TEXTCOLOR', (1, 1), (-2, -1), colors.red),
            ('TEXTCOLOR', (0, 0), (0, -1), colors.blue),
            ('TEXTCOLOR', (0, -1), (0, -1), colors.green),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
        ]))
    t.wrapOn(can, 500, 500)
    t.drawOn(can, 100, 450)

    can.showPage()
Exemple #30
0
def drawsystemefficiency(can, resultsbuffer):
    can.setFont("Helvetica", 24)
    sec_title = "System Efficiency Breakdown"
    can.drawString(25, 750, sec_title)

    desc_text = "The system operating efficiency consists of the metrics of different parts" \
                "in the system: chillers, chilled water pumps, condenser water pumps and cooling" \
                "towers. Here we demonstrate the average efficiency measured for each day from () " \
                "to ()."
    stylesheet = getSampleStyleSheet()
    paragraph = Paragraph(desc_text, stylesheet['Normal'])
    aW, aH = 500, 600
    w, h = paragraph.wrap(aW, aH)
    if w <= aW and h <= aH:
        paragraph.drawOn(can, 25, 700)

    chiller_efficiency = Paragraph("Chiller Efficiency", stylesheet['Normal'])
    chwp_efficiency = Paragraph("Chilled Water Pump Efficiency",
                                stylesheet['Normal'])
    cwp_efficiency = Paragraph("Condenser Water Pump Efficiency",
                               stylesheet['Normal'])
    ct_efficiency = Paragraph("Cooling Tower Efficiency", stylesheet['Normal'])
    overall_efficiency = Paragraph("Overall Efficiency", stylesheet['Normal'])
    data = [[' ', '1st Day', '2nd Day', '3rd Day', 'unit'],
            [chiller_efficiency, '0.712', '0.734', '0.723', 'KW/RT'],
            [chwp_efficiency, '0.043', '0.076', '0.034', 'KW/RT'],
            [cwp_efficiency, '0.040', '0.041', '0.042', 'KW/RT'],
            [ct_efficiency, '0.029', '0.021', '0.023', 'KW/RT'],
            [overall_efficiency, '0.784', '0.831', '0.780', 'KW/RT']]
    t = Table(data, 5 * [1 * inch], 6 * [1 * inch])
    t.setStyle(
        TableStyle([
            ('TEXTCOLOR', (1, 1), (-2, -1), colors.red),
            ('TEXTCOLOR', (0, 0), (0, -1), colors.blue),
            ('TEXTCOLOR', (0, -1), (0, -1), colors.green),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
        ]))
    t.wrapOn(can, 500, 500)
    t.drawOn(can, 100, 250)
    can.showPage()