Python reportlab.pdfbase.pdfmetrics.stringWidth() Examples

The following are 30 code examples of reportlab.pdfbase.pdfmetrics.stringWidth(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module reportlab.pdfbase.pdfmetrics , or try the search function .
Example #1
Source File: codecharts.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def hBoxText(msg, canvas, x, y, fontName):
    """Helper for stringwidth tests on Asian fonts.

    Registers font if needed.  Then draws the string,
    and a box around it derived from the stringWidth function"""
    canvas.saveState()
    try:
        font = pdfmetrics.getFont(fontName)
    except KeyError:
        font = cidfonts.UnicodeCIDFont(fontName)
        pdfmetrics.registerFont(font)

    canvas.setFillGray(0.8)
    canvas.rect(x,y,pdfmetrics.stringWidth(msg, fontName, 16),16,stroke=0,fill=1)
    canvas.setFillGray(0)
    canvas.setFont(fontName, 16,16)
    canvas.drawString(x,y,msg)
    canvas.restoreState() 
Example #2
Source File: renderPDF.py    From stdm with GNU General Public License v2.0 6 votes vote down vote up
def drawString(self, stringObj):
        if self._fill:
            S = self._tracker.getState()
            text_anchor, x, y, text, enc = S['textAnchor'], stringObj.x,stringObj.y,stringObj.text, stringObj.encoding
            if not text_anchor in ['start','inherited']:
                font, font_size = S['fontName'], S['fontSize']
                textLen = stringWidth(text, font, font_size, enc)
                if text_anchor=='end':
                    x -= textLen
                elif text_anchor=='middle':
                    x -= textLen*0.5
                elif text_anchor=='numeric':
                    x -= numericXShift(text_anchor,text,textLen,font,font_size,enc)
                else:
                    raise ValueError, 'bad value for textAnchor '+str(text_anchor)
            t = self._canvas.beginText(x,y)
            t.textLine(text)
            self._canvas.drawText(t) 
Example #3
Source File: paragraph.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def _do_dots_frag(cur_x, cur_x_s, maxWidth, xs, tx):
    text,fontName,fontSize,textColor,backColor,dy = _getDotsInfo(xs.style)
    txtlen = tx._canvas.stringWidth(text, fontName, fontSize)
    if cur_x_s+txtlen<=maxWidth:
        if tx._fontname!=fontName or tx._fontsize!=fontSize:
            tx.setFont(fontName,fontSize)
        maxWidth += getattr(tx,'_dotsOffsetX',tx._x0)
        tx.setTextOrigin(0,xs.cur_y+dy)
        setXPos(tx,cur_x_s-cur_x)
        n = int((maxWidth-cur_x_s)/txtlen)
        setXPos(tx,maxWidth - txtlen*n)
        if xs.textColor!=textColor:
            tx.setFillColor(textColor)
        if backColor: xs.backColors.append((cur_x,maxWidth,backColor))
        tx._textOut(n*text,1)
        if dy: tx.setTextOrigin(tx._x0,xs.cur_y-dy) 
Example #4
Source File: common.py    From stdm with GNU General Public License v2.0 6 votes vote down vote up
def drawHumanReadable(self):
        if self.humanReadable:
            #we have text
            from reportlab.pdfbase.pdfmetrics import getAscent, stringWidth
            s = str(self._humanText())
            fontSize = self.fontSize
            fontName = self.fontName
            w = stringWidth(s,fontName,fontSize)
            width = self._width
            if self.quiet:
                width -= self.lquiet+self.rquiet
                x = self.lquiet
            else:
                x = 0
            if w>width: fontSize *= width/float(w)
            y = 1.07*getAscent(fontName)*fontSize/1000.
            self.annotate(x+width/2.,-y,s,fontName,fontSize) 
Example #5
Source File: renderPDF.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def drawString(self, stringObj):
        if self._fill:
            S = self._tracker.getState()
            text_anchor, x, y, text, enc = S['textAnchor'], stringObj.x,stringObj.y,stringObj.text, stringObj.encoding
            if not text_anchor in ['start','inherited']:
                font, font_size = S['fontName'], S['fontSize']
                textLen = stringWidth(text, font, font_size, enc)
                if text_anchor=='end':
                    x -= textLen
                elif text_anchor=='middle':
                    x -= textLen*0.5
                elif text_anchor=='numeric':
                    x -= numericXShift(text_anchor,text,textLen,font,font_size,enc)
                else:
                    raise ValueError('bad value for textAnchor '+str(text_anchor))
            t = self._canvas.beginText(x,y)
            t.textLine(text)
            self._canvas.drawText(t) 
Example #6
Source File: paragraph.py    From stdm with GNU General Public License v2.0 6 votes vote down vote up
def _do_dots_frag(cur_x, cur_x_s, maxWidth, xs, tx):
    text,fontName,fontSize,textColor,backColor,dy = _getDotsInfo(xs.style)
    txtlen = tx._canvas.stringWidth(text, fontName, fontSize)
    if cur_x_s+txtlen<=maxWidth:
        if tx._fontname!=fontName or tx._fontsize!=fontSize:
            tx.setFont(fontName,fontSize)
        maxWidth += getattr(tx,'_dotsOffsetX',tx._x0)
        tx.setTextOrigin(0,xs.cur_y+dy)
        setXPos(tx,cur_x_s-cur_x)
        n = int((maxWidth-cur_x_s)/txtlen)
        setXPos(tx,maxWidth - txtlen*n)
        if xs.textColor!=textColor:
            tx.setFillColor(textColor)
        if backColor: xs.backColors.append((cur_x,maxWidth,backColor))
        tx._textOut(n*text,1)
        if dy: tx.setTextOrigin(tx._x0,xs.cur_y-dy) 
Example #7
Source File: paragraph.py    From stdm with GNU General Public License v2.0 6 votes vote down vote up
def _handleBulletWidth(bulletText,style,maxWidths):
    '''work out bullet width and adjust maxWidths[0] if neccessary
    '''
    if bulletText:
        if isinstance(bulletText,basestring):
            bulletWidth = stringWidth( bulletText, style.bulletFontName, style.bulletFontSize)
        else:
            #it's a list of fragments
            bulletWidth = 0
            for f in bulletText:
                bulletWidth = bulletWidth + stringWidth(f.text, f.fontName, f.fontSize)
        bulletRight = style.bulletIndent + bulletWidth + 0.6 * style.bulletFontSize
        indent = style.leftIndent+style.firstLineIndent
        if bulletRight > indent:
            #..then it overruns, and we have less space available on line 1
            maxWidths[0] -= (bulletRight - indent) 
Example #8
Source File: common.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def drawHumanReadable(self):
        if self.humanReadable:
            #we have text
            from reportlab.pdfbase.pdfmetrics import getAscent, stringWidth
            s = str(self._humanText())
            fontSize = self.fontSize
            fontName = self.fontName
            w = stringWidth(s,fontName,fontSize)
            width = self._width
            if self.quiet:
                width -= self.lquiet+self.rquiet
                x = self.lquiet
            else:
                x = 0
            if w>width: fontSize *= width/float(w)
            y = 1.07*getAscent(fontName)*fontSize/1000.
            self.annotate(x+width/2.,-y,s,fontName,fontSize) 
Example #9
Source File: paragraph.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def _handleBulletWidth(bulletText,style,maxWidths):
    '''work out bullet width and adjust maxWidths[0] if neccessary
    '''
    if bulletText:
        if isinstance(bulletText,strTypes):
            bulletWidth = stringWidth( bulletText, style.bulletFontName, style.bulletFontSize)
        else:
            #it's a list of fragments
            bulletWidth = 0
            for f in bulletText:
                bulletWidth += stringWidth(f.text, f.fontName, f.fontSize)
        bulletLen = style.bulletIndent + bulletWidth + 0.6 * style.bulletFontSize
        if style.wordWrap=='RTL':
            indent = style.rightIndent+style.firstLineIndent
        else:
            indent = style.leftIndent+style.firstLineIndent
        if bulletLen > indent:
            #..then it overruns, and we have less space available on line 1
            maxWidths[0] -= (bulletLen - indent) 
Example #10
Source File: codecharts.py    From stdm with GNU General Public License v2.0 6 votes vote down vote up
def hBoxText(msg, canvas, x, y, fontName):
    """Helper for stringwidth tests on Asian fonts.

    Registers font if needed.  Then draws the string,
    and a box around it derived from the stringWidth function"""
    canvas.saveState()
    try:
        font = pdfmetrics.getFont(fontName)
    except KeyError:
        font = cidfonts.UnicodeCIDFont(fontName)
        pdfmetrics.registerFont(font)

    canvas.setFillGray(0.8)
    canvas.rect(x,y,pdfmetrics.stringWidth(msg, fontName, 16),16,stroke=0,fill=1)
    canvas.setFillGray(0)
    canvas.setFont(fontName, 16,16)
    canvas.drawString(x,y,msg)
    canvas.restoreState() 
Example #11
Source File: textlabels.py    From stdm with GNU General Public License v2.0 6 votes vote down vote up
def _text2PathDescription(text, x=0, y=0, fontName=_baseGFontName, fontSize=1000,
                            anchor='start', truncate=1, pathReverse=0):
    global _gs
    if not _gs:
        import _renderPM
        _gs = _renderPM.gstate(1,1)
    from reportlab.graphics import renderPM
    renderPM._setFont(_gs,fontName,fontSize)
    P = []
    if not anchor=='start':
        textLen = stringWidth(text, fontName,fontSize)
        if anchor=='end':
            x = x-textLen
        elif anchor=='middle':
            x = x - textLen/2.
    for g in _gs._stringPath(text,x,y):
        P.extend(_processGlyph(g,truncate=truncate,pathReverse=pathReverse))
    return P 
Example #12
Source File: legends.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def _getWidths(i,s, fontName, fontSize, subCols):
    S = []
    aS = S.append
    if isSeq(s):
        for j,t in enumerate(s):
            sc = subCols[j,i]
            fN = getattr(sc,'fontName',fontName)
            fS = getattr(sc,'fontSize',fontSize)
            m = [stringWidth(x, fN, fS) for x in t.split('\n')]
            m = max(sc.minWidth,m and max(m) or 0)
            aS(m)
            aS(sc.rpad)
        del S[-1]
    else:
        sc = subCols[0,i]
        fN = getattr(sc,'fontName',fontName)
        fS = getattr(sc,'fontSize',fontSize)
        m = [stringWidth(x, fN, fS) for x in s.split('\n')]
        aS(max(sc.minWidth,m and max(m) or 0))
    return S 
Example #13
Source File: legends.py    From stdm with GNU General Public License v2.0 6 votes vote down vote up
def _getWidths(i,s, fontName, fontSize, subCols):
    S = []
    aS = S.append
    if isSeqType(s):
        for j,t in enumerate(s):
            sc = subCols[j,i]
            fN = getattr(sc,'fontName',fontName)
            fS = getattr(sc,'fontSize',fontSize)
            m = [stringWidth(x, fN, fS) for x in t.split('\n')]
            m = max(sc.minWidth,m and max(m) or 0)
            aS(m)
            aS(sc.rpad)
        del S[-1]
    else:
        sc = subCols[0,i]
        fN = getattr(sc,'fontName',fontName)
        fS = getattr(sc,'fontSize',fontSize)
        m = [stringWidth(x, fN, fS) for x in s.split('\n')]
        aS(max(sc.minWidth,m and max(m) or 0))
    return S 
Example #14
Source File: utils.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def makeCircularString(x, y, radius, angle, text, fontName, fontSize, inside=0, G=None,textAnchor='start'):
    '''make a group with circular text in it'''
    if not G: G = Group()

    angle %= 360
    pi180 = pi/180
    phi = angle*pi180
    width = stringWidth(text, fontName, fontSize)
    sig = inside and -1 or 1
    hsig = sig*0.5
    sig90 = sig*90

    if textAnchor!='start':
        if textAnchor=='middle':
            phi += sig*(0.5*width)/radius
        elif textAnchor=='end':
            phi += sig*float(width)/radius
        elif textAnchor=='numeric':
            phi += sig*float(numericXShift(textAnchor,text,width,fontName,fontSize,None))/radius

    for letter in text:
        width = stringWidth(letter, fontName, fontSize)
        beta = float(width)/radius
        h = Group()
        h.add(String(0, 0, letter, fontName=fontName,fontSize=fontSize,textAnchor="start"))
        h.translate(x+cos(phi)*radius,y+sin(phi)*radius)    #translate to radius and angle
        h.rotate((phi-hsig*beta)/pi180-sig90)               # rotate as needed
        G.add(h)                                            #add to main group
        phi -= sig*beta                                     #increment

    return G 
Example #15
Source File: paragraph.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def __new__(cls,value,frag,encoding):
        self = unicode.__new__(cls,value)
        self._frag = frag
        if hasattr(frag,'cbDefn'):
            w = getattr(frag.cbDefn,'width',0)
            self._width = w
        else:
            self._width = stringWidth(value,frag.fontName,frag.fontSize)
        return self 
Example #16
Source File: generatereport.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _header_footer(self, canvas, doc):
        # Save the state of our canvas so we can draw on it
        canvas.saveState()
        
        style_right = ParagraphStyle(name='right', parent=self.bodystyle, fontName='arialuni',
                fontSize=10, alignment=TA_RIGHT)
        
        fieldsight_logo = Image('http://' + self.base_url +'/static/images/fs1.jpg')
        fieldsight_logo._restrictSize(1.5 * inch, 1.5 * inch)
        

        # headerleft = Paragraph("FieldSight", self.bodystyle)
        headerright = Paragraph(self.project_name, style_right)

        # w1, h1 = headerleft.wrap(doc.width, doc.topMargin)
        w2, h2 = headerright.wrap(doc.width, doc.topMargin)

        textWidth = stringWidth(self.project_name, fontName='arialuni',
                fontSize=10) 
        
        fieldsight_logo.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin + 12)
        headerright.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin + 20)
        try:
            project_logo = Image(self.project_logo)
            project_logo._restrictSize(0.4 * inch, 0.4 * inch)
            project_logo.drawOn(canvas, headerright.width + doc.leftMargin -0.5 * inch - textWidth, doc.height + doc.topMargin + 10)
        except:
            pass        
        # header.drawOn(canvas, doc.leftMargin + doc.width, doc.height + doc.topMargin +20)
        
        # Footer
        footer = Paragraph('Page no. '+str(canvas._pageNumber), style_right)
        w, h = footer.wrap(doc.width, doc.bottomMargin)
        footer.drawOn(canvas, doc.leftMargin, h + 40)
 
        # Release the canvas
        canvas.restoreState() 
Example #17
Source File: gen.py    From cwg with GNU General Public License v3.0 5 votes vote down vote up
def draw_footer(canvas, font_size, y):
    text1 = 'Created with ' + PROGRAM_FULLNAME;
    text2 = PROGRAM_WEBSITE;
    text2_w = stringWidth(text2, FONT_NAME, FOOTER_FONT_SIZE);
    text2_x = PAGE_SIZE[0]-GRID_OFFSET-text2_w;
    canvas.setFont(FONT_NAME, font_size);
    canvas.drawString(GRID_OFFSET, y, text1);
    canvas.drawString(text2_x, y, text2);
    y -= 0.2*FONT_SIZE;
    canvas.linkURL('www.' + text2, (text2_x, y, \
                    text2_x + text2_w, y + 0.8*FONT_SIZE)); 
Example #18
Source File: textsplit.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def getCharWidths(word, fontName, fontSize):
    """Returns a list of glyph widths.  Should be easy to optimize in _rl_accel

    >>> getCharWidths('Hello', 'Courier', 10)
    [6.0, 6.0, 6.0, 6.0, 6.0]
    >>> from reportlab.pdfbase.cidfonts import UnicodeCIDFont
    >>> from reportlab.pdfbase.pdfmetrics import registerFont
    >>> registerFont(UnicodeCIDFont('HeiseiMin-W3'))
    >>> getCharWidths(u'\u6771\u4EAC', 'HeiseiMin-W3', 10)   #most kanji are 100 ems
    [10.0, 10.0]
    """
    #character-level function call; the performance is going to SUCK

    return [stringWidth(uChar, fontName, fontSize) for uChar in word] 
Example #19
Source File: corp.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def _sw(self,f=None,l=None):
        text = self._text
        if f is None: f = 0
        if l is None: l = len(text)
        return stringWidth(text[f:l],self._fontName,self._fontSize) 
Example #20
Source File: paragraph.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def minWidth(self):
        'Attempt to determine a minimum sensible width'
        frags = self.frags
        nFrags= len(frags)
        if not nFrags: return 0
        if nFrags==1:
            f = frags[0]
            fS = f.fontSize
            fN = f.fontName
            words = hasattr(f,'text') and split(f.text, ' ') or f.words
            func = lambda w, fS=fS, fN=fN: stringWidth(w,fN,fS)
        else:
            words = _getFragWords(frags)
            func  = lambda x: x[0]
        return max(map(func,words)) 
Example #21
Source File: pdf.py    From correios with Apache License 2.0 5 votes vote down vote up
def _posting_list_footer(self, pdf, width, x1, y1, x2, y2):
        canvas = pdf.canvas

        canvas.rect(x1, y1, width, 38 * mm)
        canvas.setFont("Helvetica-Bold", size=9)
        canvas.drawCentredString(x2 - (width / 2), y1 + 38 * mm - 10, self.footer_title_text)
        canvas.setFont("Helvetica", size=8)
        canvas.drawString(x1 + 2 * mm, y1 + 28 * mm, self.footer_disclaimer)
        text_width = stringWidth(self.footer_stamp_text, "Helvetica", 8)
        canvas.drawString(x2 - 2 * mm - text_width, y1 + 28 * mm, self.footer_stamp_text)
        text = Paragraph(self.footer_signature_text, style=self.signature_style)
        text.wrap(stringWidth(self.footer_disclaimer, "Helvetica", 8), 10 * mm)
        text.drawOn(canvas, x1 + 2 * mm, y1 + 2 * mm)

    # noinspection PyUnusedLocal 
Example #22
Source File: canvas.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def stringWidth(self, text, fontName=None, fontSize=None):
        "gets width of a string in the given font and size"
        return pdfmetrics.stringWidth(text, fontName or self._fontname,
                                    (fontSize,self._fontsize)[fontSize is None])

    # basic graphics modes 
Example #23
Source File: canvas.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def drawRightString(self, x, y, text, mode=None):
        """Draws a string right-aligned with the x coordinate"""
        width = self.stringWidth(text, self._fontname, self._fontsize)
        t = self.beginText(x - width, y)
        if mode is not None: t.setTextRenderMode(mode)
        t.textLine(text)
        self.drawText(t) 
Example #24
Source File: para.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def width(self, engine):
        from reportlab.pdfbase.pdfmetrics import stringWidth
        content = self.content
        if not content:
            content = []
        tuple = (self.tagname, self.attdict, content, self.extra)
        op = self.op = self.getOp(tuple, engine)
        #print op.__class__
        #print op.pcontent
        #print self
        s = str(op)
        return stringWidth(s, engine.fontName, engine.fontSize) 
Example #25
Source File: shapes.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def numericXShift(tA,text,w,fontName,fontSize,encoding=None,pivotCharacter='.'):
    dp = getattr(tA,'_dp',pivotCharacter)
    i = text.rfind(dp)
    if i>=0:
        dpOffs = getattr(tA,'_dpLen',0)
        w = dpOffs + stringWidth(text[:i],fontName,fontSize,encoding)
    return w 
Example #26
Source File: testshapes.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def getDrawing09():
    """This tests rotated strings

    Some renderers will have a separate mechanism for font drawing.  This test
    just makes sure strings get transformed the same way as regular graphics."""
    D = Drawing(400, 200)

    fontName = _FONTS[0]
    fontSize = 12
    text = "I should be totally horizontal and enclosed in a box"
    textWidth = stringWidth(text, fontName, fontSize)


    g1 = Group(
            String(20, 20, text, fontName=fontName, fontSize = fontSize),
            Rect(18, 18, textWidth + 4, fontSize + 4, fillColor=None)
            )
    D.add(g1)

    text = "I should slope up by 15 degrees, so my right end is higher than my left"
    textWidth = stringWidth(text, fontName, fontSize)
    g2 = Group(
            String(20, 20, text, fontName=fontName, fontSize = fontSize),
            Rect(18, 18, textWidth + 4, fontSize + 4, fillColor=None)
            )
    g2.translate(0, 50)
    g2.rotate(15)
    D.add(g2)

    return D 
Example #27
Source File: lineplots.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def _maxWidth(T, fontName, fontSize):
    '''return max stringWidth for the list of strings T'''
    if type(T) not in (type(()),type([])): T = (T,)
    T = filter(None,T)
    return T and max(map(lambda t,sW=stringWidth,fN=fontName, fS=fontSize: sW(t,fN,fS),T)) or 0 
Example #28
Source File: shapes.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def getBounds(self):
        # assumes constant drop of 0.2*size to baseline
        t = self.text
        w = stringWidth(t,self.fontName,self.fontSize,self.encoding)
        tA = self.textAnchor
        x = self.x
        if tA!='start':
            if tA=='middle':
                x -= 0.5*w
            elif tA=='end':
                x -= w
            elif tA=='numeric':
                x -= numericXShift(tA,t,w,self.fontName,self.fontSize,self.encoding)
        return (x, self.y - 0.2 * self.fontSize, x+w, self.y + self.fontSize) 
Example #29
Source File: shapes.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def _textBoxLimits(text, font, fontSize, leading, textAnchor, boxAnchor):
    w = 0
    for t in text:
        w = max(w,stringWidth(t,font, fontSize))

    h = len(text)*leading
    yt = fontSize
    if boxAnchor[0]=='s':
        yb = -h
        yt = yt - h
    elif boxAnchor[0]=='n':
        yb = 0
    else:
        yb = -h/2.0
        yt = yt + yb

    if boxAnchor[-1]=='e':
        xb = -w
        if textAnchor=='end': xt = 0
        elif textAnchor=='start': xt = -w
        else: xt = -w/2.0
    elif boxAnchor[-1]=='w':
        xb = 0
        if textAnchor=='end': xt = w
        elif textAnchor=='start': xt = 0
        else: xt = w/2.0
    else:
        xb = -w/2.0
        if textAnchor=='end': xt = -xb
        elif textAnchor=='start': xt = xb
        else: xt = 0

    return xb, yb, w, h, xt, yt 
Example #30
Source File: shapes.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def getEast(self):
        return self.x + stringWidth(self.text,self.fontName,self.fontSize, self.encoding)