当前位置: 首页>>代码示例>>Python>>正文


Python pdfmetrics.stringWidth函数代码示例

本文整理汇总了Python中reportlab.pdfbase.pdfmetrics.stringWidth函数的典型用法代码示例。如果您正苦于以下问题:Python stringWidth函数的具体用法?Python stringWidth怎么用?Python stringWidth使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了stringWidth函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: draw_breakout_tail_label

    def draw_breakout_tail_label(self, label, width, height, obj):
        """
        Split the label into 4 quads, calculate the maximum size that the 
        main center label can be.  
        """
        topLeft = str(obj[0])
        bottomLeft = str(obj[1])
        topRight = str(obj[2])
        bottomRight = str(obj[3])
        middleCenter = str(obj[4])
        bottomCenter = str(obj[5])

        font = self.font
        fillColor = colors.HexColor("#00000")

        largeFontSize = 22
        smallFontSize = 7

        label.add(shapes.String(5, height-smallFontSize, topLeft, fontName=font, fontSize=smallFontSize, fillColor=fillColor))
        label.add(shapes.String(2, 2, bottomLeft, fontName=font, fontSize=smallFontSize, fillColor=fillColor))
        name_width = stringWidth(topRight, font, smallFontSize)
        label.add(shapes.String(width-(name_width+2), height-smallFontSize, topRight, fontName=font, fontSize=smallFontSize, fillColor=fillColor))
        name2_width = stringWidth(bottomRight, font, smallFontSize)
        label.add(shapes.String(width-(name2_width+2), 2, bottomRight, fontName=font, fontSize=smallFontSize, fillColor=fillColor))
        label.add(shapes.String(width/2.0, height-(largeFontSize+largeFontSize/5.0), middleCenter, textAnchor="middle", fontSize=largeFontSize, fillColor=fillColor))
        label.add(shapes.String(width/2.0, 2, bottomCenter, textAnchor="middle", fontSize=smallFontSize))
开发者ID:matt-dale,项目名称:designdb,代码行数:26,代码来源:old_PDF_printer.py

示例2: render

    def render(self):
        style = getSampleStyleSheet()['Normal']
        style.alignment = self.text_align
        style.fontName = self.font_name
        if self._layout.debug_fields:
            style.backColor = "rgba(255, 0, 0, 0.5)"

        if self.fit_text:
            original_size = self.font_size
            text_width = stringWidth(self.data, self.font_name, self.font_size)
            while text_width > self.width:
                self.font_size -= 1
                text_width = stringWidth(self.data, self.font_name, self.font_size)
            # Size has been adjusted. Lower text accordingly
            if original_size > self.font_size:
                self._offset_top = (original_size - self.font_size) / 2.0

        if self.height == 0:
            self.height = self.font_size
        style.fontSize = self.font_size
        style.leading = self.font_size


        p = Paragraph('<font color="%s">%s</font>' % (self.color, self.data), style)
        p.wrap(self.width, self.height)
        top = self._layout.height - self.top - self.height - self._offset_top
        p.drawOn(self._canvas, self.left, top)
开发者ID:suda,项目名称:stereo,代码行数:27,代码来源:text.py

示例3: makeCircularString

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
开发者ID:Aeium,项目名称:dotStudio,代码行数:31,代码来源:utils.py

示例4: getDrawing09

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
开发者ID:7o9,项目名称:stdm-plugin,代码行数:30,代码来源:testshapes.py

示例5: wrap

 def wrap(self, availWidth, availHeight):
     self.width = availWidth
     # Use a very simple algorithm because we are always working on
     # small amounts of text
     words = self.ltext.split()
     if not words:
         self._leftlines = []
         self._extraline = True
         return self.width, self.pitch
     lines = [words.pop(0)]
     while words:
         cw = words.pop(0)
         trial = lines[-1] + " " + cw
         width = stringWidth(trial, self.font, self.fontsize)
         if width > availWidth:
             lines.append(cw)
         else:
             lines[-1] = trial
     # Does the rtext fit on the last line?
     if self.rtext:
         trial = lines[-1] + " " + self.rtext
         extraline = stringWidth(trial, self.font, self.fontsize) > availWidth
     else:
         extraline = False
     height = len(lines) * self.pitch
     if extraline:
         height += self.pitch
     self._leftlines = lines
     self._extraline = extraline
     return self.width, height
开发者ID:sde1000,项目名称:quicktill,代码行数:30,代码来源:pdrivers.py

示例6: _break_text

def _break_text(text, line_width, font_name, font_size):
    
    space_width = stringWidth(' ', font_name, font_size)
    
    #text = text.decode('utf8')
    delimiter = u' '.decode('utf8')
    words = [word.encode('utf8') for word in text.split(delimiter)]
    
    lines = list()
    line = ''
    available_width = line_width
    while words:
        #Always add first word even if single word is wider than page
        if len(line) == 0:
            line = line + words[0]
            available_width = available_width -  stringWidth(words[0], font_name, font_size)
            del words[0]
        else:
            #We already have at least one word in line. Now we try to add more...
            next_word_width = stringWidth(words[0], font_name, font_size)
            if available_width >= space_width + next_word_width:
                line = line + ' ' + words[0]
                available_width = available_width - (space_width + next_word_width)
                del words[0]
            else:
                #We cannot add more words to current line
                lines.append(line)
                line = ''
                available_width = line_width
    if len(line) > 0:
        lines.append(line)
        
    return lines
开发者ID:jovanbrakus,项目名称:resumegen,代码行数:33,代码来源:generator.py

示例7: scale_font_size

def scale_font_size(text, max_width, font_name="Helvetica", font_size=50, scaling=0.8):
    """Measure the width of the text and shrink the font size until it fits."""
    text_width = stringWidth(text, font_name, font_size)
    while text_width > max_width:
        font_size *= scaling
        text_width = stringWidth(text, font_name, font_size)
    return font_size
开发者ID:jdidion,项目名称:labels,代码行数:7,代码来源:labelmaker.py

示例8: shrink_font

def shrink_font(text, width, start_size=10):
    font_size = start_size
    text_width = width - 10
    name_width = stringWidth(text, "Helvetica", font_size)
    while name_width > text_width:
        font_size *= 0.8
        name_width = stringWidth(text, "Helvetica", font_size)
    return font_size
开发者ID:bryndivey,项目名称:ohmanizer,代码行数:8,代码来源:labeler.py

示例9: nameWidth

 def nameWidth(self, name, fontSize):
     w = 0
     name_parts = name.split()
     for i, part in enumerate(name_parts):
         if i != 0:
             w += pdfmetrics.stringWidth(' ','MinionPro-Regular',fontSize)
         w += pdfmetrics.stringWidth(part[0],'MinionPro-Regular',fontSize)
         w += pdfmetrics.stringWidth(part[1:],'MinionPro-Regular',fontSize-2)
     return w
开发者ID:aarongilly,项目名称:dominiontabs,代码行数:9,代码来源:dominion_tabs.py

示例10: wrap_text

def wrap_text(text, max_width, font_name="Helvetica", font_size=50):
    text_width = stringWidth(text, font_name, font_size)
    nchar = len(text)
    new_text = [text]
    while text_width > max_width:
        nchar -= 1
        new_text = textwrap.wrap(text, nchar)
        text_width = max(stringWidth(t, font_name, font_size) for t in new_text)
    return new_text
开发者ID:jdidion,项目名称:labels,代码行数:9,代码来源:labelmaker.py

示例11: linebreak

 def linebreak(self,neumes,lyrics = None):
     """Break neumes and lyrics into lines"""
     cr = Cursor(0,0)
     lyricArray = re.split(' ',lyrics)
     # If lyric spans multiple neumes
     #   then see if lyric is wider than span
     #   else see if width of glypch is max of neume and lyric
     charSpace = 4 # default space between characters
     textOffset = 20 # default space lyrics appear below neumes
     #neumeArray = neume_dict.translate(neumes).split(' ')
     neumeArray = neumes.split(' ')
     neumePos = []
     lyricPos = []
     lyricIdx = 0
     for neume in neumeArray:
         #print("Neume length: " + str(pdfmetrics.stringWidth(neume,'EZ Psaltica',24)))
         nWidth = pdfmetrics.stringWidth(neume_dict.translate(neume),'EZ Psaltica',self.nFontSize)
         if nWidth > 1.0: # if it's not a gorgon or other small symbol
             # Neume might take lyric
             if lyricIdx < len(lyricArray):
                 lyr = lyricArray[lyricIdx]
             else:
                 lyr = ""
             lWidth = pdfmetrics.stringWidth(lyr,lyric_attrib['font'],lyric_attrib['font_size'])
             # Glyph width will be the max of the two if lyric isn't stretched out
             # across multiple neumes
             addLyric = False
             #if (lyr[-1] != "_") & (neume_dict.takesLyric(neume)):
             if (neume_dict.takesLyric(neume)):
                 glWidth = max(nWidth,lWidth)
                 lyricIdx += 1
                 addLyric = True
             else:
                 glWidth = nWidth
             if (glWidth + cr.x) >= self.lineWidth: # line break
                 cr.x, cr.y = 0, cr.y - self.lineHeight
                 # does it take a lyric syllable?
                 neumePos.append((cr.x,cr.y,neume_dict.translate(neume)))
             else: # no line break
                 # does it take a lyric syllable?
                 neumePos.append((cr.x,cr.y,neume_dict.translate(neume)))
             if (addLyric):
                 lyricPos.append((cr.x,cr.y-textOffset,lyr))
             cr.x += glWidth + charSpace
             
         else:
             # offsets for gorgon
             # offsets for apli
             # offset for kentima
             # offsets for omalon
             # offsets for antikenoma
             # offsets for eteron
             neumePos.append((cr.x - charSpace,cr.y,neume_dict.translate(neume)))
         
     #print neumePos
     return neumePos, lyricPos
开发者ID:jdaly101,项目名称:kassia,代码行数:56,代码来源:kassia.py

示例12: individual_header_font_size

 def individual_header_font_size(self, header, maximum_width):
     font_size = maximum_width
     
     width = stringWidth(header, self.formatter.header_font, font_size)
             
     while width > maximum_width:
         font_size -= 1
         width = stringWidth(header, self.formatter.header_font, font_size)
     
     return font_size
开发者ID:Hovercross,项目名称:rectory-apps,代码行数:10,代码来源:calendar_maker.py

示例13: _getWidth

def _getWidth(s,fontName, fontSize, sepSpace=0):
    if isSeqType(s):
        sum = 0
        for t in s:
            m = [stringWidth(x, fontName, fontSize) for x in t.split('\n')]
            sum += m and max(m) or 0
        sum += (len(s)-1)*sepSpace
        return sum
    m = [stringWidth(x, fontName, fontSize) for x in s.split('\n')]
    return m and max(m) or 0
开发者ID:alexissmirnov,项目名称:donomo,代码行数:10,代码来源:legends.py

示例14: drawPageNumbers

def drawPageNumbers(canvas, style, pages, availWidth, availHeight, dot=' . '):
    '''
    Draws pagestr on the canvas using the given style.
    If dot is None, pagestr is drawn at the current position in the canvas.
    If dot is a string, pagestr is drawn right-aligned. If the string is not empty,
    the gap is filled with it.
    '''
    pages.sort()
    pagestr = ', '.join([str(p) for p, _ in pages])
    x, y = canvas._curr_tx_info['cur_x'], canvas._curr_tx_info['cur_y']
    
    fontSize = style.fontSize
    pagestrw = stringWidth(pagestr, style.fontName, fontSize)
    
    #if it's too long to fit, we need to shrink to fit in 10% increments.
    #it would be very hard to output multiline entries.
    #however, we impose a minimum size of 1 point as we don't want an
    #infinite loop.   Ultimately we should allow a TOC entry to spill
    #over onto a second line if needed.
    freeWidth = availWidth-x
    while pagestrw > freeWidth and fontSize >= 1.0:
        fontSize = 0.9 * fontSize
        pagestrw = stringWidth(pagestr, style.fontName, fontSize)
        
    
    if isinstance(dot, strTypes):
        if dot:
            dotw = stringWidth(dot, style.fontName, fontSize)
            dotsn = int((availWidth-x-pagestrw)/dotw)
        else:
            dotsn = dotw = 0
        text = '%s%s' % (dotsn * dot, pagestr)
        newx = availWidth - dotsn*dotw - pagestrw
        pagex = availWidth - pagestrw
    elif dot is None:
        text = ',  ' + pagestr
        newx = x
        pagex = newx
    else:
        raise TypeError('Argument dot should either be None or an instance of basestring.')

    tx = canvas.beginText(newx, y)
    tx.setFont(style.fontName, fontSize)
    tx.setFillColor(style.textColor)
    tx.textLine(text)
    canvas.drawText(tx)

    commaw = stringWidth(', ', style.fontName, fontSize)
    for p, key in pages:
        if not key:
            continue
        w = stringWidth(str(p), style.fontName, fontSize)
        canvas.linkRect('', key, (pagex, y, pagex+w, y+style.leading), relative=1)
        pagex += w + commaw
开发者ID:CometHale,项目名称:lphw,代码行数:54,代码来源:tableofcontents.py

示例15: _getFragWords

def _getFragWords(frags):
    ''' given a Parafrag list return a list of fragwords
        [[size, (f00,w00), ..., (f0n,w0n)],....,[size, (fm0,wm0), ..., (f0n,wmn)]]
        each pair f,w represents a style and some string
        each sublist represents a word
    '''
    R = []
    W = []
    n = 0
    for f in frags:
        text = f.text
        #del f.text # we can't do this until we sort out splitting
                    # of paragraphs
        if text!='':
            S = split(text)
            if S==[]: S = ['']
            if W!=[] and text[0] in whitespace:
                W.insert(0,n)
                R.append(W)
                W = []
                n = 0

            for w in S[:-1]:
                W.append((f,w))
                n += stringWidth(w, f.fontName, f.fontSize)
                W.insert(0,n)
                R.append(W)
                W = []
                n = 0

            w = S[-1]
            W.append((f,w))
            n += stringWidth(w, f.fontName, f.fontSize)
            if text[-1] in whitespace:
                W.insert(0,n)
                R.append(W)
                W = []
                n = 0
        elif hasattr(f,'cbDefn'):
            W.append((f,''))
        elif hasattr(f, 'lineBreak'):
            #pass the frag through.  The line breaker will scan for it.
            if W!=[]:
                W.insert(0,n)
                R.append(W)
                W = []
                n = 0
            R.append([0,(f,'')])

    if W!=[]:
        W.insert(0,n)
        R.append(W)

    return R
开发者ID:ShaulBarkan,项目名称:PRION,代码行数:54,代码来源:paragraph.py


注:本文中的reportlab.pdfbase.pdfmetrics.stringWidth函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。