Exemplo n.º 1
0
    def add(self, flowable, canv, trySplit=0):
        # mainlog.debug("HeadingsFrame.add {}, at top {}".format(type(flowable), self.top_of_frame))

        if isinstance(flowable, HeaderSetter):
            self._header_maker = flowable._header_maker

        if self.top_of_frame and self._header_maker:
            self.top_of_frame = False
            mainlog.debug("add header")
            for f in self._header_maker.make():
                res = Frame.add(self, f, canv, trySplit=0)

        return Frame.add(self, flowable, canv, trySplit)
Exemplo n.º 2
0
    def draw_label(label, canvas, size):
        width, height = size

        margin_x = 8 * mm
        margin_y = 6 * mm

        canvas.translate(margin_x, margin_y)

        width -= margin_x * 2
        height -= margin_y * 2

        qr_size = height
        qr_image = make_qr_image(label.qr_data())
        with tempfile.NamedTemporaryFile(suffix='.png') as F:
            qr_image.save(F.name)

            canvas.drawImage(
                F.name,
                width - qr_size,
                0,
                width=qr_size,
                height=qr_size,
            )

        spacing = 6 * mm
        frame_size = (width - qr_size - spacing, height)

        frame = Frame(
            0,
            0,
            *frame_size,
            leftPadding=0,
            bottomPadding=0,
            rightPadding=0,
            topPadding=0,
        )

        style = ParagraphStyle(
            'name',
            fontName='Courier-Bold',
            fontSize=32,
            leading=32,
            textColor=(0.2, 0.2, 0.2),
        )

        frame.add(Paragraph(str(label), style), canvas)
Exemplo n.º 3
0
    def keydraw(self):
        hFrame1 = Frame(15.45 * cm, 1 * cm, 4.75 * cm, 11.5 * cm)
        hFrame2 = Frame(10.55 * cm, 1 * cm, 4.75 * cm, 11.5 * cm)
        hFrame1.addFromList(self.keyh[:26], self.c)
        hFrame2.addFromList(self.keyh[26:], self.c)
        vFrame1 = Frame(5.7 * cm, 1 * cm, 4.75 * cm, 11.5 * cm)
        vFrame2 = Frame(0.8 * cm, 1 * cm, 4.75 * cm, 11.5 * cm)
        vFrame1.addFromList(self.keyv[:26], self.c)
        vFrame2.addFromList(self.keyv[26:], self.c)
        tFrame = Frame(0.8 * cm,
                       11.3 * cm,
                       19.4 * cm,
                       16.1 * cm,
                       showBoundary=1)
        tFrame.add(self.table, self.c)
        self.c.drawCentredString(10.5 * cm, 28.4 * cm,
                                 'Created with WordCrusader by Yotam Hochman')

        self.c.save()
    def add(self, flowable, canvas, trySplit=0):
        result = Frame.add(self, flowable, canvas, trySplit=trySplit)
        if result == 0:
            return result
        
        # Slight hack: we're assuming that trySplit==0 iff this flowable
        # is an already-split portion of another flowable. So we don't want
        # to draw a line below it, since it's not the end of an entry.
        # This assumes that this frame's parent doctemplate allowSplitting
        # has not been changed from the default.
        if trySplit == 0:
            return result

        canvas.saveState()
        canvas.setStrokeColor(colors.gray)
        fudge = flowable.getSpaceAfter() / 2.0
        canvas.line(self._x, self._y + fudge, self._x + self.width, self._y + fudge)
        canvas.restoreState()
        return result
Exemplo n.º 5
0
    def add_default_info(self, canvas, doc):
        canvas.saveState()
        logo_frame = Frame(0, doc.height - 3.8 * cm, 3.5 * cm, 4 * cm)
        logo_frame.add(self.get_register_logo(), canvas)

        header_frame = Frame(4 * cm, doc.height - 3 * cm, doc.width - 5 * cm,
                             3 * cm)
        header_frame.add(self.get_header(), canvas)

        trusty_frame = Frame(0, 0, 6 * cm, doc.height - 4 * cm)
        trusty_frame.add(self.get_trusty(), canvas)
        canvas.drawImage("inc/logo_watermark.png", 267, 300, 200, 236)
        canvas.setFont("Helvetica", 7)
        canvas.drawString(4, 4, "Report Generated by: DS MANAGER")

        canvas.restoreState()
Exemplo n.º 6
0
    def draw_label(label, canvas, size):
        width, height = size

        margin_x = 8 * mm
        margin_y = 6 * mm

        canvas.translate(margin_x, margin_y)

        width -= margin_x * 2
        height -= margin_y * 2

        frame_size = (width, height)

        frame = Frame(
            0,
            0,
            *frame_size,
            leftPadding=0,
            bottomPadding=0,
            rightPadding=0,
            topPadding=0,
        )

        font_size = 32
        for attempt in range(50):
            style = ParagraphStyle(
                'name',
                fontName='Courier-Bold',
                fontSize=font_size,
                leading=font_size,
                textColor=(0.0, 0.0, 0.0),
            )

            if frame.add(Paragraph(str(label), style), canvas):
                break

            font_size = font_size * 0.95
Exemplo n.º 7
0
    def render_using_config(self, config):

        # draw outline if in debug
        if self.debug or config.get('debug'):
            self.draw_debug_outline( config )
            
        # get the text to render
        text = self.extract_content(config)

        # choose the method to draw the string
        text_align = config['text-align']

        if text_align == 'centre':
            style_alignment = TA_CENTER
        elif text_align == 'left':
            style_alignment = TA_LEFT
        else:
            raise Exception( "Unhandled value for 'text-align': '%s'" % text_align )

        if config['overflow'] == 'wrap':
            frame = Frame( config['x'], config['y'], config['w'], config['h'], )
        
            # create a paragraph style
            font_size = config['font-size']                
            style = ParagraphStyle( name='test' )
            style.fontName  = config['font-family']
            style.alignment = style_alignment
        
            while font_size > minimum_font_size:
                style.fontSize = font_size
                style.leading  = font_size
        
                para =  Paragraph( text, style )
        
                if frame.add( para, self.canvas ):
                    break
        
                # Paragraph was too big - shrink the font size
                font_size -= 1
                
        
        elif config['overflow'] == 'shrink':
            
            font_size = config['font-size']                
        
            while font_size > minimum_font_size:
                self.canvas.setFont( config['font-family'], font_size )
                if self.canvas.stringWidth(text) <= config['w']:
                    break
                font_size -= 1
            
            if text_align == 'centre':
                self.canvas.drawCentredString(
                    config['x'] + config['w'] / 2,
                    config['y'] + config['h'] - config['font-size'],
                    text
                )
            elif text_align == 'left':
                self.canvas.drawString(
                    config['x'],
                    config['y'] + config['h'] - config['font-size'],
                    text
                )
            else:
                raise Exception( "Unhandled value for 'text-align': '%s'" % text_align )
                                
        else:
            raise Exception( "Unhandled value of 'overflow': '%s'" % config['overflow'])
 def add (self, flowable, canv, trySplit=0):
     flowable._atTop = self._atTop
     return Frame.add(self, flowable, canv, trySplit)
Exemplo n.º 9
0
def lastfm(name):

    def getXML(benis):
        xml = urlopen("http://normalisr.com/?username="******"&chart=artist&type=overall&format=xml2")
        local_file = open(
            config.Settings['directories']['thumbs'] + benis + '.xml', "w")
        local_file.write(xml.read())
        local_file.close()
        return config.Settings['directories']['thumbs'] + benis + '.xml'

    os.chdir(config.Settings['directories']['thumbs'])
    if os.path.isfile(name + '.pdf') and os.path.isfile(name + '.png'):
        os.remove(name + '.pdf')
        os.remove(name + '.png')

    xmlname = config.Settings['directories']['thumbs'] + name + '.xml'

    if os.path.isfile(name + '.xml'):
        if os.stat(xmlname).st_mtime < time.time() - 86400 / 2 or request.query.freshen:
            xml = getXML(name)
        else:
            xml = xmlname
    else:
        xml = getXML(name)

    canvas = Canvas(name + '.pdf', pagesize=(232.5, 410))
    frame = Frame(0, 0, 232.5, 410, showBoundary=1)
    pdfmetrics.registerFont(TTFont('benis', 'ipaexg.ttf'))
    pdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf'))

    canvas.drawString(100, 750, "Welcome to Reportlab!")

    times = time.strftime("%a, %d %b %Y %H:%M:%S +10:00",
                          time.localtime(os.stat(xmlname).st_mtime))

    table_data = [['My top artists overall', '', '']]

    print xml
    tree = etree.parse(xml)
    root = tree.getroot()
    rows = []
    for child in root:
        for ch in child:
            if int(ch.attrib['normalised']) <= 20:
                artist = ch[0].text.encode('utf-8')
                clipamount = 200
                while stringWidth(artist, 'benis', 10) > 130:
                    artist = artist[:clipamount] + '...'
                    clipamount -= 1
                    # print artist, clipamount, stringWidth(artist,'benis',10)
                print artist, clipamount, stringWidth(artist, 'benis', 10)
                # else:
                #     artist = ch[0].text.encode('utf-8')
                table_data.append(
                    [ch.attrib['normalised'], artist, str(round(float(ch[11].text) / 60, 1)) + ' hours'])

    table_data.append(['Last updated: ' + times, '', ''])

    table_style = [
        ("FONTNAME", (0, 0), (2, 21), 'benis'),
        ("FONTSIZE", (0, 0), (2, 20), 10),
        ("FONTSIZE", (0, -1), (2, -1), 8),
        ('GRID', (0, 0), (2, 20), 1, black),
        ('SPAN', (0, 0), (2, 0)),
        ('SPAN', (0, -1), (2, -1)),
        ('ALIGN', (2, 1), (2, 20), 'RIGHT'),
        ('ALIGN', (0, 0), (2, 0), 'CENTER'),
        ('ALIGN', (0, 1), (0, 20), 'CENTER'),
        ('ALIGN', (0, -1), (2, -1), 'CENTER')
    ]

    table = Table(table_data, (20, 140, 70), style=table_style)
    frame.add(table, canvas)
    canvas.save()

    if request.query.transparent:
        subprocess.check_output('cd ' + config.Settings['directories']['thumbs'] +
                                '; gs -q -dNOPAUSE -dBATCH -sDEVICE=pngalpha -r80 -dEPSCrop -sOutputFile="%s.png" "%s.pdf"' % (name, name), shell=True)
    else:
        subprocess.check_output('cd ' + config.Settings['directories']['thumbs'] +
                                '; convert -density 80 "%s[0]" -trim "%s.png"' % (name + '.pdf', name), shell=True)
    return static_file(name + '.png', root=config.Settings['directories']['thumbs'])
Exemplo n.º 10
0
def toc_page(c, saved_list):
    """ Creates table of contents page. 

    saved_list -- list of tuples (strings), (title, fig)
    c -- canvas
    """
    watermark(c)

    styles = getSampleStyleSheet()
    info = []
    # styles["ToC_info"] = ParagraphStyle("Normal",
    #     parent=styles["Normal"],
    #     fontSize=12,
    #     fontName="Times-Roman")

    INFO_TXT = "This report was generated by SATAlytics on {}. The software tool SATAlytics summarizes, analyzes and visualizes chemical analysis data.".format(
        time.strftime("%B %d, %Y"))

    # display title of page
    c.setFont("Helvetica-Bold", 20, leading=None)
    c.drawCentredString(325, 750, "Table of Contents")

    # display table of contents
    ## if using drawString():
    c.setFont("Helvetica-Oblique", 16, leading=None)
    # c.setLineWidth(1)
    # c.setDash(1, 2) #dots
    y = 700
    saved_text = []
    for i in range(len(saved_list)):
        # # if using paragraphs:
        saved_text.append(
            Paragraph("<i>" + saved_list[i][0] + "</i>", styles["Heading2"]))
        saved_text.append(
            Paragraph("<para align=\"RIGHT\">{}".format(i + 3),
                      styles["Heading2"]))

    fr = Frame(65,
               150,
               515,
               550,
               leftPadding=0,
               bottomPadding=0,
               rightPadding=0,
               topPadding=0,
               id=None,
               showBoundary=0)
    side_bar(c)
    footer(c)
    c.setFont("Helvetica-Bold", 20, leading=None)  # otherwise green printing
    for para in saved_text:
        while fr.add(para, c) == 0:
            fr.split(para, c)
            # new page
            c.showPage()
            watermark(c)

            # display title of page
            c.setFont("Helvetica-Bold", 20, leading=None)
            c.drawCentredString(325, 750, "Table of Contents")

            # display table of contents
            c.setFont("Helvetica-Oblique", 16, leading=None)

            fr = Frame(65,
                       150,
                       515,
                       550,
                       leftPadding=0,
                       bottomPadding=0,
                       rightPadding=0,
                       topPadding=0,
                       id=None,
                       showBoundary=0)

    # draw line
    c.setLineWidth(1)
    c.setStrokeColorRGB(0, 0, 0)
    c.line(65, 60, 565, 60)

    info.append(Paragraph(INFO_TXT, styles["Normal"]))
    f = Frame(65,
              50,
              515,
              50,
              leftPadding=0,
              bottomPadding=0,
              rightPadding=0,
              topPadding=0,
              id=None,
              showBoundary=0)
    f.addFromList(info, c)
    ## use text object for that

    side_bar(c)
    footer(c)
Exemplo n.º 11
0
    def render_using_config(self, config):

        # draw outline if in debug
        if self.debug or config.get('debug'):
            self.draw_debug_outline(config)

        # get the text to render
        text = self.extract_content(config)

        # choose the method to draw the string
        text_align = config['text-align']

        if text_align == 'centre':
            style_alignment = TA_CENTER
        elif text_align == 'left':
            style_alignment = TA_LEFT
        else:
            raise Exception("Unhandled value for 'text-align': '%s'" %
                            text_align)

        if config['overflow'] == 'wrap':
            frame = Frame(
                config['x'],
                config['y'],
                config['w'],
                config['h'],
            )

            # create a paragraph style
            font_size = config['font-size']
            style = ParagraphStyle(name='test')
            style.fontName = config['font-family']
            style.alignment = style_alignment

            while font_size > minimum_font_size:
                style.fontSize = font_size
                style.leading = font_size

                para = Paragraph(text, style)

                if frame.add(para, self.canvas):
                    break

                # Paragraph was too big - shrink the font size
                font_size -= 1

        elif config['overflow'] == 'shrink':

            font_size = config['font-size']

            while font_size > minimum_font_size:
                self.canvas.setFont(config['font-family'], font_size)
                if self.canvas.stringWidth(text) <= config['w']:
                    break
                font_size -= 1

            if text_align == 'centre':
                self.canvas.drawCentredString(
                    config['x'] + config['w'] / 2,
                    config['y'] + config['h'] - config['font-size'], text)
            elif text_align == 'left':
                self.canvas.drawString(
                    config['x'],
                    config['y'] + config['h'] - config['font-size'], text)
            else:
                raise Exception("Unhandled value for 'text-align': '%s'" %
                                text_align)

        else:
            raise Exception("Unhandled value of 'overflow': '%s'" %
                            config['overflow'])
Exemplo n.º 12
0
    def _draw_front_frame(self, canvas, width, height):
        front_frame = Frame(
            self.border_front[Border.LEFT],
            self.border_front[Border.BOTTOM],
            width - self.border_front[Border.LEFT] -
            self.border_front[Border.RIGHT],
            height - self.border_front[Border.TOP] -
            self.border_front[Border.BOTTOM],
            leftPadding=self.TEXT_MARGIN,
            bottomPadding=self.TEXT_MARGIN,
            rightPadding=self.TEXT_MARGIN,
            topPadding=self.TEXT_MARGIN,
        )

        # DEBUG
        # front_frame.drawBoundary(canvas)

        title_paragraph = self._get_title_paragraph()

        # Nasty hack alert!
        # There is no way to know how big the text will be and Frame only
        # supports top to bottom layout. This means we have no way of
        # knowing the maximum image size.
        #
        # As a hack to get around this, we have to:
        #  1. mock out the paragraphs drawOn method
        #  2. "draw" the paragraph
        #  3. Calculate how tall it was
        #  4. Reset the frame and restore the original drawOn

        def mock(*args, **kwargs):
            pass

        original_drawOn = title_paragraph.drawOn
        title_paragraph.drawOn = mock
        result = front_frame.add(title_paragraph, canvas)
        if not result:
            raise Exception("Failed to draw title in front frame")

        title_height = (front_frame.y1 + front_frame.height - front_frame._y +
                        self.TEXT_MARGIN)
        title_paragraph.drawOn = original_drawOn
        front_frame._reset()

        available_height = front_frame.height - title_height - self.TEXT_MARGIN * 2

        image_width, image_height = get_image_size(
            self.front_image_path,
            front_frame.width,
            available_height,
        )

        elements = []

        # Add spacer if image doesn't fully fill frame
        space = front_frame.height - (image_height + title_height)
        if space > 0:
            elements.append(Spacer(front_frame.width, space / 2))

        elements.append(Image(self.front_image_path, image_width,
                              image_height))

        # Add second spacer
        if space > 0:
            elements.append(Spacer(front_frame.width, space / 2))

        elements.append(title_paragraph)
        front_frame.addFromList(elements, canvas)
Exemplo n.º 13
0
 def add (self, flowable, canv, trySplit=0):
     flowable._atTop = self._atTop
     return Frame.add(self, flowable, canv, trySplit)