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
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
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)
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
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))
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
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
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
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
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
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
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
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
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
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
def draw_aux_label(self, label, width, height, obj): """ just fill the label with the text """ fontSize = 22 if width > 127: fontSize = 40 textWidth = stringWidth(obj, self.font, fontSize) while textWidth > (width - 10): fontSize *= 0.5 textWidth = stringWidth(obj, self.font, fontSize) label.add(shapes.String(width/2.0, height-(fontSize+fontSize/5.0), obj, textAnchor="middle", fontSize=fontSize))
def fit_text_in_area(the_text,font_name,text_width_limit,text_height_limit): font_size = text_height_limit text_width = stringWidth(the_text, font_name, font_size) while ((text_width > text_width_limit) or (font_size > text_height_limit)): font_size *= 0.95 text_width = stringWidth(the_text, font_name, font_size) s = shapes.String(0, 0, the_text, fontName=font_name, fontSize=font_size, textAnchor="start") #pprint("text_height_limit = " + str(text_height_limit)) #pprint(s.dumpProperties()) #pprint(s) return s
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)
def draw_cable_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]) isBundle = obj[6] largeOrSmall = obj[7] font = self.font fillColor = colors.HexColor("#00000") if isBundle == True: if self.tagEnds == True: fillColor = colors.HexColor("#FFFFFF") r = shapes.Rect(0, 0, width, height) r.fillColor = colors.HexColor("#00000") r.strokeColor = None label.add(r) horizontalCenterLine = width/2.0 verticalCenterLine = height/2.0 if largeOrSmall == 'Large': largeFontSize = 32 smallFontSize = 10 elif largeOrSmall == 'Small': largeFontSize = 22 smallFontSize = 7 middleCenterTextWidth = stringWidth(middleCenter, font, largeFontSize) # start with large font size of 22 middleCenterTextHeight = largeFontSize*self.pointsToMM leftVerticalLimit = verticalCenterLine - middleCenterTextWidth/2.0 rightVerticalLimit = verticalCenterLine + middleCenterTextWidth/2.0 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)) if largeOrSmall == 'Large': label.add(shapes.String(width/2.0, height-(largeFontSize+largeFontSize/2.0), middleCenter, textAnchor="middle", fontSize=largeFontSize, fillColor=fillColor)) elif largeOrSmall == 'Small': label.add(shapes.String(width/2.0, height-(largeFontSize+largeFontSize/5.0), middleCenter, textAnchor="middle", fontSize=largeFontSize, fillColor=fillColor))
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)
def _handleBulletWidth(bulletText,style,maxWidths): '''work out bullet width and adjust maxWidths[0] if neccessary ''' if bulletText <> None: if type(bulletText) is StringType: 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] = maxWidths[0] - (bulletRight - indent)
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
def computeSize(self): # the thing will draw in its own coordinate system self._lineWidths = [] topPadding = self.topPadding leftPadding = self.leftPadding rightPadding = self.rightPadding bottomPadding = self.bottomPadding self._lines = simpleSplit(self._text,self.fontName,self.fontSize,self.maxWidth) if not self.width: self._width = leftPadding+rightPadding if self._lines: self._lineWidths = [stringWidth(line,self.fontName,self.fontSize) for line in self._lines] self._width += max(self._lineWidths) else: self._width = self.width self._height = self.height or ((self.leading or 1.2*self.fontSize) * len(self._lines)+topPadding+bottomPadding) self._ewidth = (self._width-leftPadding-rightPadding) self._eheight = (self._height-topPadding-bottomPadding) boxAnchor = self._getBoxAnchor() if boxAnchor in ['n','ne','nw']: self._top = -topPadding elif boxAnchor in ['s','sw','se']: self._top = self._height-topPadding else: self._top = 0.5*self._eheight self._bottom = self._top - self._eheight if boxAnchor in ['ne','e','se']: self._left = leftPadding - self._width elif boxAnchor in ['nw','w','sw']: self._left = leftPadding else: self._left = -self._ewidth*0.5 self._right = self._left+self._ewidth
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)
def get_full_text_extent(self, text): ascent,descent=_fontdata.ascent_descent[self.face_name] descent = (-descent) * self.font_size / 1000.0 ascent = ascent * self.font_size / 1000.0 height = ascent + descent width = pdfmetrics.stringWidth(text, self.face_name, self.font_size) return width, height, descent, height*1.2 # assume leading of 1.2*height
def drawit(F, w=400, h=200, fontSize=12, slack=2, gap=5): D = Drawing(w, h) th = 2 * gap + fontSize * 1.2 gh = gap + 0.2 * fontSize y = h maxx = 0 for fontName in F: y -= th text = ( fontName + ": I should be totally horizontal and enclosed in a box and end in alphabetagamma \xc2\xa2\xc2\xa9\xc2\xae\xc2\xa3\xca\xa5\xd0\x96\xd6\x83\xd7\x90\xd9\x82\xe0\xa6\x95\xce\xb1\xce\xb2\xce\xb3" ) textWidth = stringWidth(text, fontName, fontSize) maxx = max(maxx, textWidth + 20) D.add( Group( Rect( 8, y - gh, textWidth + 4, th, strokeColor=colors.red, strokeWidth=0.5, fillColor=colors.lightgrey, ), String(10, y, text, fontName=fontName, fontSize=fontSize), ) ) y -= 5 return maxx, h - y + gap, D
def test3(self): '''compare CJK splitting in some edge cases''' from reportlab.pdfgen.canvas import Canvas from reportlab.platypus.paragraph import Paragraph from reportlab.lib.styles import ParagraphStyle from reportlab.pdfbase import pdfmetrics from reportlab.lib.enums import TA_LEFT sty = ParagraphStyle('A') sty.fontSize = 15 sty.leading = sty.fontSize*1.2 sty.fontName = 'Courier' sty.alignment = TA_LEFT sty.wordWrap = 'CJK' p0=Paragraph('ABCDEFGHIJKL]N',sty) p1=Paragraph('AB<font color="red">C</font>DEFGHIJKL]N',sty) canv = Canvas('test_platypus_paragraph_cjk3.pdf') ix = len(canv._code) aW = pdfmetrics.stringWidth('ABCD','Courier',15) w,h=p0.wrap(aW,1000000) y = canv._pagesize[1]-72-h p0.drawOn(canv,72,y) w,h=p1.wrap(aW,1000000) y -= h+10 p1.drawOn(canv,72,y) w,h=p0.wrap(aW*0.25-2,1000000) y -= h+10 p0.drawOn(canv,72,y) w,h=p1.wrap(aW/4.-2,1000000) y -= h+10 p1.drawOn(canv,72,y) assert canv._code[ix:]==['q', '1 0 0 1 72 697.8898 cm', 'q', '0 0 0 rg', 'BT 1 0 0 1 0 57 Tm /F2 15 Tf 18 TL (ABCD) Tj T* (EFGH) Tj T* (IJKL]) Tj T* (N) Tj T* ET', 'Q', 'Q', 'q', '1 0 0 1 72 615.8898 cm', 'q', 'BT 1 0 0 1 0 57 Tm 18 TL /F2 15 Tf 0 0 0 rg (AB) Tj 1 0 0 rg (C) Tj 0 0 0 rg (D) Tj T* (EFGH) Tj T* (IJKL]) Tj T* (N) Tj T* ET', 'Q', 'Q', 'q', '1 0 0 1 72 353.8898 cm', 'q', '0 0 0 rg', 'BT 1 0 0 1 0 237 Tm /F2 15 Tf 18 TL (A) Tj T* (B) Tj T* (C) Tj T* (D) Tj T* (E) Tj T* (F) Tj T* (G) Tj T* (H) Tj T* (I) Tj T* (J) Tj T* (K) Tj T* (L) Tj T* (]) Tj T* (N) Tj T* ET', 'Q', 'Q', 'q', '1 0 0 1 72 91.88976 cm', 'q', 'BT 1 0 0 1 0 237 Tm 18 TL /F2 15 Tf 0 0 0 rg (A) Tj T* (B) Tj T* 1 0 0 rg (C) Tj T* 0 0 0 rg (D) Tj T* (E) Tj T* (F) Tj T* (G) Tj T* (H) Tj T* (I) Tj T* (J) Tj T* (K) Tj T* (L) Tj T* (]) Tj T* (N) Tj T* ET', 'Q', 'Q'] canv.showPage() canv.save()
def _draw_labels(self, cur_drawing, left_labels, right_labels): """Layout and draw sub-feature labels for the chromosome. Tries to place each label at the same vertical position as the feature it applies to, but will adjust the positions to avoid or at least reduce label overlap. Draws the label text and a coloured line linking it to the location (i.e. feature) it applies to. """ if not self._sub_components: return color_label = self._color_labels segment_width = (self.end_x_position - self.start_x_position) \ * self.chr_percent label_sep = (self.end_x_position - self.start_x_position) \ * self.label_sep_percent segment_x = self.start_x_position \ + 0.5 * (self.end_x_position - self.start_x_position - segment_width) y_limits = [] for sub_component in self._sub_components: y_limits.extend((sub_component.start_y_position, sub_component.end_y_position)) y_min = min(y_limits) y_max = max(y_limits) del y_limits # Now do some label placement magic... # from reportlab.pdfbase import pdfmetrics # font = pdfmetrics.getFont('Helvetica') # h = (font.face.ascent + font.face.descent) * 0.90 h = self.label_size for x1, x2, labels, anchor in [ (segment_x, segment_x - label_sep, _place_labels(left_labels, y_min, y_max, h), "end"), (segment_x + segment_width, segment_x + segment_width + label_sep, _place_labels(right_labels, y_min, y_max, h), "start"), ]: for (y1, y2, color, back_color, name) in labels: cur_drawing.add(Line(x1, y1, x2, y2, strokeColor=color, strokeWidth=0.25)) label_string = String(x2, y2, name, textAnchor=anchor) label_string.fontName = 'Helvetica' label_string.fontSize = h if color_label: label_string.fillColor = color if back_color: w = stringWidth(name, label_string.fontName, label_string.fontSize) if x1 > x2: w = w * -1.0 cur_drawing.add(Rect(x2, y2 - 0.1 * h, w, h, strokeColor=back_color, fillColor=back_color)) cur_drawing.add(label_string)
def _wrap_text(self, text, font_name, font_size): """ Wraps the given text so that it can fit inside the translation box. :param text: Text to wrap inside the translation box :param font_name: Font used for the render :param font_size: Font size used for the render :return: List of lines :rtype: list(str) """ text_wrap = list() for line in text.split('\n'): text_width = stringWidth(line, font_name, font_size) / inch line_wrap = list() if text_width > self.width: ratio = self.width / text_width line_length = int(len(line) * ratio) words = line.split(' ') sub_line = '' for word in words: if len(sub_line) + len(word) < line_length: sub_line += word + ' ' else: line_wrap.append(sub_line) sub_line = word + ' ' line_wrap.append(sub_line) else: line_wrap = [line] text_wrap.extend(line_wrap) return text_wrap
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
def drawCentredString(self, s, x, y, angle=0, text_anchor='middle'): if self.verbose: print "+++ SVGCanvas.drawCentredString" if self._fillColor != None: if not text_anchor in ['start', 'inherited']: textLen = stringWidth(s, self._font, self._fontSize) if text_anchor == 'end': x -= textLen elif text_anchor == 'middle': x -= textLen / 2. else: raise ValueError, 'bad value for text_anchor ' + str( text_anchor) self.drawString(x, y, text, angle=angle)
def draw_constrained_text(self, text, style, canvas, x, y, w, h, border=False): fontSize = style.fontSize from reportlab.pdfbase.pdfmetrics import stringWidth from reportlab.lib.utils import simpleSplit # while stringWidth(text, style.fontName, fontSize) > w: # fontSize -= 1 # while len(simpleSplit(text, style.fontName, fontSize, w)) > num_lines: # fontSize -= 1 if style.wordWrap == 'CJK': while stringWidth(text, style.fontName, fontSize) > w: fontSize -= 1 height = fontSize lines = [text] else: height = h + 1 while height > h: # print(stringWidth(text, style.fontName, fontSize), w) lines = simpleSplit(text, style.fontName, fontSize, w) height = fontSize * len(lines) # print(height, h) fontSize -= 1 fontSize += 1 # print('H: ', h, height) y_offset = (h - height) / 2 if border: canvas.rect(x, y, w, h, stroke=1, fill=0) # outer border canvas.rect(x, y + y_offset, w, height, stroke=1, fill=0) lines.reverse() for line in lines: textobject = canvas.beginText() textobject.setTextOrigin(x, y + y_offset) textobject.setFont(style.fontName, fontSize) # print(style.textColor, str(style.textColor)) textobject.setFillColorRGB(*normalizeRGB(style.textColor)) #textobject.setCharSpace(1.5) textobject.textLine(line) canvas.drawText(textobject) y_offset += fontSize
def getCharWidths(word, fontName, fontSize): """Returns a list of glyph widths. >>> 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]
def generateOverlay(password): packet = io.BytesIO() can = canvas.Canvas(packet, pagesize=landscape(A4)) text = can.beginText() password = password.upper() width = stringWidth(str(password), "Helvetica", 15) text.setTextOrigin(687 - (width / 2), 127) text.setFont("Helvetica", 15) text.setCharSpace(1.5) text.textLine(str(password)) can.drawText(text) can.save() packet.seek(0) return PdfFileReader(packet)
def __styledWrap__(self, style): fontName = getattr(style,'fontname',None) if fontName is None: fontName = style.fontName fontSize = getattr(style,'fontsize',None) if fontSize is None: fontSize = style.fontSize leading = getattr(style,'leading',1.2*fontSize) if fontSize is None: fontSize = style.fontSize L = asNative(self._text).split('\n') self._width = max([stringWidth(_, fontName, fontSize) for _ in L]) self._height = len(L)*leading return self._width, self._height
def add_front(canvas_param, theme, subtitle, pagesize=letter): """ 函数功能:为pdf文档添加功能,分“主题”、“副标题”两部分 :param canvas: :param pagesize: 页面大小,默认A4 :param theme: 主题字符串 :param subtitle: 副标题字符串 :return: """ PAGE_WIDTH = pagesize[0] PAGE_HEIGHT = pagesize[1] # 设置主标题字体并打印主标题 canvas_param.setFont("song", 30) canvas_param.drawString((PAGE_WIDTH-stringWidth(theme, fontName='song', fontSize=30))/2.0, PAGE_HEIGHT*0.618, theme) # 设置副标题字体并打印副标题 canvas_param.setFont("song", 14) canvas_param.drawString((PAGE_WIDTH-stringWidth(subtitle, fontName='song', fontSize=14))/2.0, PAGE_HEIGHT*0.15, subtitle) canvas_param.showPage() return canvas_param
def _calcFragWidth(self, frags): widths = [] width = self.BASE_WIDTH for frag in frags: width += stringWidth(getattr(frag, 'text', ''), frag.fontName, frag.fontSize) if hasattr(frag, 'lineBreak'): widths.append(width) width = self.BASE_WIDTH widths.append(width) return max(widths)
def get_width(pa): if pa.frags: ft = '' fs = 0 for f in pa.frags: ft += f.text fs = max(fs, f.fontSize) w = stringWidth(ft, fontName=f.fontName, fontSize=fs) + 10 else: w = 8 return w
def get_text_size(para_text, font_size=9, line_height=10, text_align='left', is_cell=False): initial_fonts() lines = para_text.split('\n') max_line = "" for line in lines: if len(line) > len(max_line): max_line = line width = stringWidth(max_line, "sans-serif", font_size) if is_cell: height = font_size * max(1, len(lines) * 2 / 3) else: height = font_size * len(lines) height += abs(line_height - font_size) * 2 return width / mm, height / mm
def drawLabel(label, width, height, obj): str_obj = str(obj) font_size = 50 text_width = width - 10 while stringWidth(str_obj, 'Helvetica', font_size) > text_width: font_size = font_size * .9 label.add( shapes.String(width / 2, height / 2, str_obj, fontName='Helvetica', fontSize=font_size, textAnchor='middle'))
def drawString(self, stringObj): if self._canvas._fillColor: S = self._tracker.getState() text_anchor, x, y, text = S['textAnchor'], stringObj.x,stringObj.y,stringObj.text if not text_anchor in ['start','inherited']: font, fontSize = S['fontName'], S['fontSize'] textLen = stringWidth(text, font,fontSize) if text_anchor=='end': x = x-textLen elif text_anchor=='middle': x = x - textLen/2 else: raise ValueError, 'bad value for text_anchor '+str(text_anchor) self._canvas.drawString(x,y,text)
def DrawTextItem(self, textitem, f): dc = wx.ClientDC(self.parent) # dummy dc for text extents g = self.gstate x = g.textMatrix[4] y = g.textMatrix[5] + g.textRise if g.wordSpacing > 0: textitem += ' ' wid, ht, descend, xlead = dc.GetFullTextExtent(textitem, f) if have_rlwidth and self.knownfont: # use ReportLab stringWidth if available width = stringWidth(textitem, g.font, g.fontSize) else: width = wid g.textMatrix[4] += (width + g.wordSpacing) # update current x position return ['DrawText', (textitem, x, -y - (ht - descend)), {}]
def dumpttf(fn, fontName=None, verbose=0): '''dump out known glyphs from a ttf file''' import os if not os.path.isfile(fn): raise IOError('No such file "%s"' % fn) from reportlab.pdfbase.pdfmetrics import registerFont, stringWidth from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfgen.canvas import Canvas if fontName is None: fontName = os.path.splitext(os.path.basename(fn))[0] dmpfn = '%s-ttf-dump.pdf' % fontName ttf = TTFont(fontName, fn) K = ttf.face.charToGlyph.keys() registerFont(ttf) c = Canvas(dmpfn) W, H = c._pagesize titleFontSize = 30 # title font size titleFontName = 'Helvetica' labelFontName = 'Courier' fontSize = 10 border = 36 dx0 = stringWidth('12345: ', fontName, fontSize) dx = dx0 + 20 dy = 20 K.sort() y = 0 page = 0 for i, k in enumerate(K): if y < border: if page: c.showPage() page += 1 y = H - border - titleFontSize c.setFont(titleFontName, titleFontSize) c.drawCentredString(W / 2.0, y, 'TrueType Font %s Page %d' % (fontName, page)) y -= 0.2 * titleFontSize + dy x = border c.setFont(labelFontName, 10) c.drawString(x, y, '%5.5x:' % k) c.setFont(fontName, 10) c.drawString(x + dx0, y, unichr(k).encode('utf8')) x += dx if x + dx > W - border: x = border y -= dy c.showPage() c.save() if verbose: print 'Font %s("%s") has %d glyphs\ndumped to "%s"' % (fontName, fn, len(K), dmpfn)
def adaptive_font_string(text, font_alias, font_size_in, max_font_size, min_font_size, max_text_width): if font_size_in > max_font_size: font_size_in = max_font_size text_width = int(stringWidth(text, font_alias, font_size_in) / mm) font_size = font_size_in do_shorten = False if text_width > max_text_width: if font_size_in <= min_font_size: # stop there: we don't have a font small enough do_shorten = True else: font_size_in -= 1 font_size, do_shorten = EventRegistrationPrint.adaptive_font_string(text, font_alias, font_size_in, max_font_size, min_font_size, max_text_width) return font_size, do_shorten
def create_invoice(): for i in range(2, 12): # Reading values from excel file invoice_number = sheet.cell(row=i, column=1).value Client_name = sheet.cell(row=i, column=2).value Client_email = sheet.cell(row=i, column=3).value Project_name = sheet.cell(row=i, column=4).value.lower() # Creating a pdf file and setting a naming convention c = canvas.Canvas(str(invoice_number) + '_' + Project_name + '.pdf') c.setPageSize((page_width, page_height)) # Drawing the image c.drawInlineImage( "C:\\Users\\LENOVO\\PycharmProjects\\Creating_Invoices\\logo.jpg", page_width - image_width - margin, page_height - image_height - margin, image_width, image_height) # Invoice information c.setFont('Arial', 80) text = 'INVOICE' text_width = stringWidth(text, 'Arial', 80) c.drawString((page_width - text_width) / 2, page_height - image_height - margin, text) y = page_height - image_height - margin * 4 x = 2 * margin x2 = x + 550 c.setFont('Arial', 45) c.drawString(x, y, 'invoice number: ') c.drawString(x2, y, invoice_number) y -= margin c.drawString(x, y, 'Issued to: ') c.drawString(x2, y, Client_name) y -= margin c.drawString(x, y, 'Client email id: ') c.drawString(x2, y, str(Client_email)) y -= margin c.drawString(x, y, 'Project name: ') c.drawString(x2, y, Project_name) y -= margin # Saving the pdf file c.save()
def build_morphbox(): text_to_dict() # print(categories) c = canvas.Canvas("output.pdf", bottomup=0, pagesize=landscape(A4)) c.setFont(main_font, font_size) # c.setDash(1,2) height, width = A4 margin_horizontal = 10 * mm margin_vertical = 10 * mm width = width - margin_horizontal * 2 height = height - margin_vertical * 2 cell_height = height / len(categories) title_cell_width = calculate_max_title_width() + 10 index_y = 0 for category in categories: cell_width = (width - title_cell_width) / len(categories[category]) c.rect(margin_horizontal, margin_vertical + index_y * cell_height, title_cell_width, cell_height) c.setFont(main_font_bold, font_size) c.drawString( margin_horizontal + 5, margin_vertical + (index_y * cell_height) + cell_height / 2 + 5, category) c.setFont(main_font, font_size) list_of_values = categories[category] for i in range(len(list_of_values)): label = list_of_values[i] img_x = margin_horizontal + title_cell_width + i * cell_width # + cell_width img_y = margin_vertical + index_y * cell_height # + cell_height c.saveState() c.translate(img_x, img_y) c.scale(1, -1) c.drawImage(f'processed/clip{label}.jpg', x=cell_width, y=0, width=-cell_width, height=-cell_height, preserveAspectRatio=True, anchor='c') c.restoreState() c.rect(margin_horizontal + title_cell_width + i * cell_width, margin_vertical + index_y * cell_height, cell_width, cell_height) text_width = stringWidth(label, main_font, font_size) #c.drawString(margin_horizontal + title_cell_width+i*cell_width+cell_width/2.0 - text_width/2.0, margin_vertical + index_y*cell_height+cell_height/2.0+5, label) # c.drawCentredString(title_cell_width+i*cell_width+cell_width/2.0, index_y*cell_height+cell_height/2.0, label) index_y = index_y + 1 c.save()
def getMaxTextSize(self, columns, default_font, default_font_size): if not columns: return 0, 0 max_text_length = max([ pdfmetrics.stringWidth( unicode(column.text), column.style.get('font_name', default_font), column.style.get('font_size', default_font_size), ) for column in columns ]) max_text_width = max([ column.style.get('font_size', default_font_size) for column in columns ]) return max_text_length, max_text_width
def ptitle(self, c, page=0, nr_pages=0): oy = 0.1 * cm c.translate(0, self._paper_plot_height + oy) qtime = QTime.fromString(self._time_string[-1], "hh:mm:ss:zzz") # stime = qtime.toString("hh:mm") stime = qtime.toString("h") + "h" + qtime.toString("mm") text = "Record name: {0}; duration: {1}; page: {2}/{3}".format( self._record_name, stime, page, nr_pages) d = stringWidth(text, self._default_font_name, self._default_font_size) c.drawString(self._paper_plot_width - d - 1, 0, text) c.translate(0, -self._paper_plot_height - oy)
def breakLines(self, width): for n in range(0, len(self.frags)): words = self.frags[n].text.split(' ') for nn in range(0, len(words)): wordWidth = pdfmetrics.stringWidth(words[nn], self.frags[n].fontName, self.frags[n].fontSize, self.encoding) w = wordWidth / width[0] if w > 1: words[nn] = '\n'.join( (split_word_in_eq(words[nn], int(math.ceil(w))))) self.frags[n].text = ' '.join(words) return Paragraph.breakLines(self, width)
def _text2PathDescription(text, x=0, y=0, fontName=_baseGFontName, fontSize=1000, anchor='start', truncate=1, pathReverse=0): from reportlab.graphics import renderPM, _renderPM _gs = _renderPM.gstate(1,1) 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
def drawCentredString(self, s, x, y, angle=0, text_anchor='middle', link_info=None): if self.verbose: print("+++ SVGCanvas.drawCentredString") if self._fillColor != None: if not text_anchor in ['start', 'inherited']: textLen = stringWidth(s,self._font,self._fontSize) if text_anchor=='end': x -= textLen elif text_anchor=='middle': x -= textLen/2. elif text_anchor=='numeric': x -= numericXShift(text_anchor,s,textLen,self._font,self._fontSize) else: raise ValueError('bad value for text_anchor ' + str(text_anchor)) self.drawString(s,x,y,angle=angle, link_info=link_info)
def __init__( self, text, font=None, colour=None, x=0, scale=None, width=None, ): font = font if font else self.font self.font = font self.text = text if scale > 0: self.font_size = self.scale = scale self.width = stringWidth(text, font, scale) else: self.width = 40 * PT_PER_MM str_width = stringWidth(text, font, 1000) self.font_size = self.scale = self.width / (str_width / 1000) self.height = self.height_of(text) * self.scale self.colour = colour if colour else black self.x = x
def write_name(label, width, height, name): # Write the title. label.add( shapes.String(5, height - 20, "Hello, my name is", fontName="Judson Bold", fontSize=20)) # Measure the width of the name and shrink the font size until it fits. font_size = 50 text_width = width - 10 name_width = stringWidth(name, "KatamotzIkasi", font_size) while name_width > text_width: font_size *= 0.8 name_width = stringWidth(name, "KatamotzIkasi", font_size) # Write out the name in the centre of the label with a random colour. s = shapes.String(width / 2.0, 15, name, textAnchor="middle") s.fontName = "KatamotzIkasi" s.fontSize = font_size s.fillColor = random.choice( (colors.black, colors.blue, colors.red, colors.green)) label.add(s)
def write_exercises(pdf, width, height, exercises): """Write multiplication exercises to pdf.""" column_width = (width - 2 * MARGIN_SIZE) / COLUMNS row_height = (height - 2 * MARGIN_SIZE) / ROWS for column in range(COLUMNS): for row in range(ROWS): point_x = column * column_width + MARGIN_SIZE point_y = row * row_height + MARGIN_SIZE exercise_text = exercises.pop() text_width = stringWidth(exercise_text, FONT_NAME, FONT_SIZE) pdf.drawString(point_x, point_y, exercise_text) pdf.line(point_x + text_width + SPACING, point_y, point_x + column_width - SPACING, point_y)
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))
def add_course_sponsor_logo(self): if not self.sponsors: return x = self.left_panel_center y = 4.3 text = self._("In Sponsorship with") self.draw_bidi_center_text(text, x, y, 0.125, color='grey-light') # Underline the sentence text_width = stringWidth(text, self.font, self.font_size) xu = self.bidi_x_axis(x * inch, offset=-text_width / 2.0) yu = (y - 0.1) * inch length = text_width if self.is_english else -text_width self.ctx.setStrokeColor(self.colors['grey-light']) self.ctx.setLineWidth(0.5) self.ctx.line(xu, yu, xu + length, yu) # Fetch the organization data organization = self.sponsors[0] logo = organization.get('logo', None) organization_name = organization.get('name') try: image = utils.ImageReader(self.path_builder(logo.url)) iw, ih = image.getSize() aspect = iw / float(ih) except IOError: image = None iw, aspect = 0, 0 height = inch / 2.1 width = height * aspect x = self.bidi_x_axis(x * inch, offset=width / 2.0) y -= 0.7 self.ctx.drawImage(image, x, y * inch, width, height, mask='auto') x = self.left_panel_center y -= 0.15 self.draw_bidi_center_text(organization_name, x, y, 0.09, color='grey-light')
def _draw_metadata(self, canvas): begin_top = 100 * mm textobject = canvas.beginText(self.left_margin, self.pagesize[1] - begin_top) textobject.setFont(self.font_regular, 8) textobject.textLine(pgettext('invoice', 'Order code')) textobject.moveCursor(0, 5) textobject.setFont(self.font_regular, 10) textobject.textLine(self.invoice.order.full_code) canvas.drawText(textobject) if self.invoice.is_cancellation: textobject = canvas.beginText(self.left_margin + 50 * mm, self.pagesize[1] - begin_top) textobject.setFont(self.font_regular, 8) textobject.textLine(pgettext('invoice', 'Cancellation number')) textobject.moveCursor(0, 5) textobject.setFont(self.font_regular, 10) textobject.textLine(self.invoice.number) canvas.drawText(textobject) textobject = canvas.beginText(self.left_margin + 100 * mm, self.pagesize[1] - begin_top) textobject.setFont(self.font_regular, 8) textobject.textLine(pgettext('invoice', 'Original invoice')) textobject.moveCursor(0, 5) textobject.setFont(self.font_regular, 10) textobject.textLine(self.invoice.refers.number) canvas.drawText(textobject) else: textobject = canvas.beginText(self.left_margin + 70 * mm, self.pagesize[1] - begin_top) textobject.textLine(pgettext('invoice', 'Invoice number')) textobject.moveCursor(0, 5) textobject.setFont(self.font_regular, 10) textobject.textLine(self.invoice.number) canvas.drawText(textobject) p = Paragraph(date_format(self.invoice.date, "DATE_FORMAT"), style=self.stylesheet['Normal']) w = stringWidth(p.text, p.frags[0].fontName, p.frags[0].fontSize) p.wrapOn(canvas, w, 15 * mm) date_x = self.pagesize[0] - w - self.right_margin p.drawOn(canvas, date_x, self.pagesize[1] - begin_top - 10 - 6) textobject = canvas.beginText(date_x, self.pagesize[1] - begin_top) textobject.setFont(self.font_regular, 8) if self.invoice.is_cancellation: textobject.textLine(pgettext('invoice', 'Cancellation date')) else: textobject.textLine(pgettext('invoice', 'Invoice date')) canvas.drawText(textobject)
def drawit(F,w=400,h=200,fontSize=12,slack=2,gap=5): D = Drawing(w,h) th = 2*gap + fontSize*1.2 gh = gap + .2*fontSize y = h maxx = 0 for fontName in F: y -= th text = fontName+asNative(b': I should be totally horizontal and enclosed in a box and end in alphabetagamma \xc2\xa2\xc2\xa9\xc2\xae\xc2\xa3\xca\xa5\xd0\x96\xd6\x83\xd7\x90\xd9\x82\xe0\xa6\x95\xce\xb1\xce\xb2\xce\xb3') textWidth = stringWidth(text, fontName, fontSize) maxx = max(maxx,textWidth+20) D.add( Group(Rect(8, y-gh, textWidth + 4, th, strokeColor=colors.red, strokeWidth=.5, fillColor=colors.lightgrey), String(10, y, text, fontName=fontName, fontSize = fontSize))) y -= 5 return maxx, h-y+gap, D
def drawString(self, stringObj): if self._canvas._fillColor: S = self._tracker.getState() text_anchor, x, y, text = S['textAnchor'], stringObj.x, stringObj.y, stringObj.text if not text_anchor in ('start', 'inherited'): font, fontSize = S['fontName'], S['fontSize'] textLen = stringWidth(text, font,fontSize) if text_anchor=='end': x -= textLen elif text_anchor=='middle': x -= textLen/2 elif text_anchor=='numeric': x -= numericXShift(text_anchor,text,textLen,font,fontSize) else: raise ValueError, 'bad value for text_anchor ' + str(text_anchor) self._canvas.drawString(text,x,y,link_info=self._get_link_info_dict(stringObj),**getattr(stringObj,'_svgAttrs',{}))
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 = x-textLen elif text_anchor=='middle': x = x - textLen/2 else: raise ValueError, 'bad value for textAnchor '+str(text_anchor) t = self._canvas.beginText(x,y) t.textLine(text) self._canvas.drawText(t)