本文整理汇总了Python中reportlab.pdfbase.pdfmetrics.getFont函数的典型用法代码示例。如果您正苦于以下问题:Python getFont函数的具体用法?Python getFont怎么用?Python getFont使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getFont函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_instanceStringWidth
def test_instanceStringWidth(self):
from reportlab.pdfbase.pdfmetrics import registerFont, getFont, _fonts, unicode2T1
from reportlab.pdfbase.ttfonts import TTFont
ttfn = 'Vera'
t1fn = 'Times-Roman'
registerFont(TTFont(ttfn, "Vera.ttf"))
ttf = getFont(ttfn)
t1f = getFont(t1fn)
testCp1252 = b'copyright \xa9 trademark \x99 registered \xae ReportLab! Ol\xe9!'
enc='cp1252'
senc = 'utf8'
ts = b'ABCDEF\xce\x91\xce\xb2G'
utext = b'ABCDEF\xce\x91\xce\xb2G'.decode(senc)
fontSize = 12
defns="ttfn t1fn ttf t1f testCp1252 enc senc ts utext fontSize ttf.face ttf.face.charWidths ttf.face.defaultWidth t1f.widths t1f.encName t1f.substitutionFonts _fonts"
import sys
F = []
def tfunc(f,ts,fontSize,enc,funcs,i):
w1 = funcs[i][0](f,ts,fontSize,enc)
w2 = funcs[1][0](f,ts,fontSize,enc) #python version
if abs(w1-w2)>=1e-10: F.append("stringWidth%s(%r,%r,%s,%r)-->%r != f._py_stringWidth(...)-->%r" % (fontType,f,ts,fontSize,enc,w1,w2))
for font,fontType in ((t1f,'T1'),(ttf,'TTF')):
funcs = getFuncs('instanceStringWidth'+fontType)
for i,kind in enumerate(('c','py')):
for j in (3,2,1,0): #we run several times to allow the refcounts to stabilize
if j: rcv = getrc(defns)
tfunc(font,testCp1252,fontSize,enc,funcs,i)
tfunc(font,ts,fontSize,senc,funcs,i)
tfunc(font,utext,fontSize,senc,funcs,i)
if not j:
rcc = checkrc(defns,rcv)
if rcc: F.append("%s %s refcount diffs (%s)" % (fontType,kind,rcc))
assert not F,"instanceStringWidth failures\n\t%s" % '\n\t'.join(F)
示例2: define
def define(self, name, engine, enginefontname):
"""Define a new font.
``name`` is the name that will be used for this font in the
presentation text.
``engine`` is the font engine. MagicPoint supports several,
but mgp2pdf supports only "xfont".
``enginefontname`` is the name of the font according to the
font engine. For ``xfont`` it can be "family", "family-weight"
or "family-weight-slant". Or it can be a fontconfig pattern.
"""
if engine != "xfont":
raise NotImplementedError("unsupported font engine %s" % engine)
if '-' in enginefontname and ':' not in enginefontname:
if enginefontname.count('-') == 1:
# family-weight
family, weight = enginefontname.split('-')
weight = self.weights.get(weight, weight)
enginefontname = '%s:weight=%s' % (family, weight)
elif enginefontname.count('-') == 2:
# family-weight-slant
family, weight, slant = enginefontname.split('-')
weight = self.weights.get(weight, weight)
slant = {'i': 'italic', 'r': 'roman'}[slant]
enginefontname = '%s:weight=%s:slant=%s' % (family, weight, slant)
filename = subprocess.Popen(
['fc-match', enginefontname, '-f', '%{file}'],
stdout=subprocess.PIPE).communicate()[0].strip()
if not filename:
sys.exit('Could not find the font file for %s' % enginefontname)
log.debug("Font %s: %s -> %s" % (name, enginefontname, filename))
pdfmetrics.registerFont(TTFont(name, filename))
pdfmetrics.getFont(name) # just see if raises
示例3: test_instanceStringWidth
def test_instanceStringWidth(self):
from reportlab.pdfbase.pdfmetrics import registerFont, getFont, _fonts, unicode2T1
from reportlab.pdfbase.ttfonts import TTFont
ttfn = 'Vera'
t1fn = 'Times-Roman'
registerFont(TTFont(ttfn, "Vera.ttf"))
ttf = getFont(ttfn)
t1f = getFont(t1fn)
testCp1252 = 'copyright %s trademark %s registered %s ReportLab! Ol%s!' % (chr(169), chr(153),chr(174), chr(0xe9))
enc='cp1252'
senc = 'utf8'
ts = 'ABCDEF\xce\x91\xce\xb2G'
utext = 'ABCDEF\xce\x91\xce\xb2G'.decode(senc)
fontSize = 12
defns="ttfn t1fn ttf t1f testCp1252 enc senc ts utext fontSize ttf.face ttf.face.charWidths ttf.face.defaultWidth t1f.widths t1f.encName t1f.substitutionFonts _fonts"
rcv = getrc(defns)
def tfunc(f,ts,fontSize,enc):
w1 = f.stringWidth(ts,fontSize,enc)
w2 = f._py_stringWidth(ts,fontSize,enc)
assert abs(w1-w2)<1e-10,"f(%r).stringWidthU(%r,%s,%r)-->%r != f._py_stringWidth(...)-->%r" % (f,ts,fontSize,enc,w1,w2)
tfunc(t1f,testCp1252,fontSize,enc)
tfunc(t1f,ts,fontSize,senc)
tfunc(t1f,utext,fontSize,senc)
tfunc(ttf,ts,fontSize,senc)
tfunc(ttf,testCp1252,fontSize,enc)
tfunc(ttf,utext,fontSize,senc)
rcc = checkrc(defns,rcv)
assert not rcc, "rc diffs (%s)" % rcc
示例4: testStringWidth
def testStringWidth(self):
from _rl_accel import stringWidthU
from reportlab.pdfbase.pdfmetrics import _py_stringWidth, getFont, registerFont, _fonts
from reportlab.pdfbase.ttfonts import TTFont
ttfn = 'Vera'
t1fn = 'Times-Roman'
registerFont(TTFont(ttfn, "Vera.ttf"))
ttf = getFont(ttfn)
t1f = getFont(t1fn)
testCp1252 = 'copyright %s trademark %s registered %s ReportLab! Ol%s!' % (chr(169), chr(153),chr(174), chr(0xe9))
enc='cp1252'
senc = 'utf8'
intern(senc)
ts = 'ABCDEF\xce\x91\xce\xb2G'
utext = 'ABCDEF\xce\x91\xce\xb2G'.decode('utf8')
fontSize = 12
stringWidthU(testCp1252,t1fn,fontSize,enc) #avoid obscure startup initialization problems
defns="ttfn t1fn ttf t1f testCp1252 enc senc ts utext fontSize ttf.face ttf.face.charWidths ttf.face.defaultWidth t1f.widths t1f.encName t1f.substitutionFonts _fonts"
rcv = getrc(defns) #first count
def tfunc(ts,fn,fontSize,enc):
w1 = stringWidthU(ts,fn,fontSize,enc)
w2 = _py_stringWidth(ts,fn,fontSize,enc)
assert abs(w1-w2)<1e-10,"stringWidthU(%r,%r,%s,%r)-->%r != _py_stringWidth(...)-->%r" % (ts,fn,fontSize,enc,w1,w2)
tfunc(testCp1252,t1fn,fontSize,enc)
tfunc(ts,t1fn,fontSize,senc)
tfunc(utext,t1fn,fontSize,senc)
tfunc(ts,ttfn,fontSize,senc)
tfunc(testCp1252,ttfn,fontSize,enc)
tfunc(utext,ttfn,fontSize,senc)
rcc = checkrc(defns,rcv) #second count and compare
assert not rcc, "rc diffs (%s)" % rcc
示例5: registerFonts
def registerFonts(fontlist):
"""
Registeres specified fonts for use in PDF.
fontlist -- list of (fontname, relpath) tuples
fontname -- name for font registration
relpath -- path to TTF font relative to this function
"""
from os import path, sep
from inspect import getfile, currentframe
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
for (fontname, relpath) in fontlist:
# check if already registered
try:
pdfmetrics.getFont(fontname)
continue # font already registered
except KeyError:
pass # font not registered
selfPath = path.dirname(path.abspath(getfile(currentframe())))
ttfFile = selfPath + sep + relpath
pdfmetrics.registerFont(TTFont(fontname, ttfFile))
示例6: testStringWidth
def testStringWidth(incFontSize):
'''example from the reportlab test set'''
from _rl_accel import stringWidthU
from reportlab.pdfbase.pdfmetrics import _py_stringWidth, getFont, registerFont, _fonts
from reportlab.pdfbase.ttfonts import TTFont
ttfn = 'Luxi-Serif'
t1fn = 'Times-Roman'
registerFont(TTFont(ttfn, "luxiserif.ttf"))
ttf = getFont(ttfn)
t1f = getFont(t1fn)
testCp1252 = 'copyright %s trademark %s registered %s ReportLab! Ol%s!' % (chr(169), chr(153),chr(174), chr(0xe9))
enc='cp1252'
senc = 'utf8'
intern(senc)
ts = 'ABCDEF\xce\x91\xce\xb2G'
utext = 'ABCDEF\xce\x91\xce\xb2G'.decode('utf8')
fontSize = 12
defns="ttfn t1fn ttf t1f testCp1252 enc senc ts utext fontSize ttf.face ttf.face.charWidths ttf.face.defaultWidth t1f.widths t1f.encName t1f.substitutionFonts _fonts"
rcv = getrc(defns) #compute initial ref
def tfunc(ts,fn,fontSize,enc):
w1 = stringWidthU(ts,fn,fontSize,enc)
w2 = _py_stringWidth(ts,fn,fontSize,enc)
assert abs(w1-w2)<1e-10,"stringWidthU(%r,%r,%s,%r)-->%r != _py_stringWidth(...)-->%r" % (ts,fn,fontSize,enc,w1,w2)
tfunc(testCp1252,t1fn,fontSize,enc)
tfunc(ts,t1fn,fontSize,senc)
tfunc(utext,t1fn,fontSize,senc)
tfunc(ts,ttfn,fontSize,senc)
tfunc(testCp1252,ttfn,fontSize,enc)
tfunc(utext,ttfn,fontSize,senc)
if incFontSize:
z = fontSize #simulate adding a reference to fontSize
print checkrc(defns,rcv)
示例7: select_fontname
def select_fontname(fontname, default_fontname):
if fontname not in pdfmetrics.getRegisteredFontNames()\
or fontname not in pdfmetrics.standardFonts:
# let reportlab attempt to find it
try:
pdfmetrics.getFont(fontname)
except Exception:
_logger.warning('Could not locate font %s, substituting default: %s',
fontname, default_fontname)
fontname = default_fontname
return fontname
示例8: setFont
def setFont(self, node):
fontname = node.get('name')
if fontname not in pdfmetrics.getRegisteredFontNames()\
or fontname not in pdfmetrics.standardFonts:
# let reportlab attempt to find it
try:
pdfmetrics.getFont(fontname)
except Exception:
_logger.debug('Could not locate font %s, substituting default: %s',
fontname,
self.canvas._fontname)
fontname = self.canvas._fontname
return self.canvas.setFont(fontname, utils.unit_get(node.get('size')))
示例9: select_fontname
def select_fontname(fontname, default_fontname):
if fontname not in pdfmetrics.getRegisteredFontNames()\
or fontname not in pdfmetrics.standardFonts:
# let reportlab attempt to find it
try:
pdfmetrics.getFont(fontname)
except Exception:
addition = ""
if " " in fontname:
addition = ". Your font contains spaces which is not valid in RML."
_logger.warning('Could not locate font %s, substituting default: %s%s',
fontname, default_fontname, addition)
fontname = default_fontname
return fontname
示例10: Dessine_macaron
def Dessine_macaron(self, texte="", rond=False):
""" Dessine un cadre arrondi et un texte dans le coin haut droit de la case """
# Dessine le rectangle de fond
if self.parent.dictDonnees["case_macaron_mix_couleurs"] == False :
case_macaron_bord_couleur = self.parent.dictDonnees["case_macaron_bord_couleur"]
case_macaron_fond_couleur = self.parent.dictDonnees["case_macaron_fond_couleur"]
else :
# Mix de couleur
couleur = MixCouleurs()
case_macaron_bord_couleur = wx.Colour(*couleur)
case_macaron_fond_couleur = wx.Colour(*couleur)
self.canvas.setStrokeColor(ColorWxToPdf(case_macaron_bord_couleur, alpha=self.parent.dictDonnees["case_macaron_bord_alpha"]/100.0))
self.canvas.setFillColor(ColorWxToPdf(case_macaron_fond_couleur, alpha=self.parent.dictDonnees["case_macaron_fond_alpha"]/100.0))
if self.parent.dictDonnees["case_macaron_type"] == "rond" :
self.canvas.circle(x_cen=self.largeur_case - self.parent.dictDonnees["case_macaron_largeur"] / 2.0 -5, y_cen=self.hauteur_case - self.parent.dictDonnees["case_macaron_hauteur"] / 2.0 -5, r=self.parent.dictDonnees["case_macaron_taille_police"]-3, stroke=True, fill=True)
largeur, hauteur = self.parent.dictDonnees["case_macaron_largeur"] + 10, self.parent.dictDonnees["case_macaron_hauteur"] + 10
else :
self.canvas.roundRect(x=self.largeur_case - self.parent.dictDonnees["case_macaron_largeur"], y=self.hauteur_case - self.parent.dictDonnees["case_macaron_hauteur"], width=self.parent.dictDonnees["case_macaron_largeur"] + self.parent.dictDonnees["case_macaron_radius"], height=self.parent.dictDonnees["case_macaron_hauteur"] + self.parent.dictDonnees["case_macaron_radius"], radius=self.parent.dictDonnees["case_macaron_radius"], stroke=True, fill=True)
largeur, hauteur = self.parent.dictDonnees["case_macaron_largeur"], self.parent.dictDonnees["case_macaron_hauteur"]
# Calcule la hauteur du texte
face = pdfmetrics.getFont(self.parent.dictDonnees["case_macaron_nom_police"]).face
hauteur_font = face.ascent * self.parent.dictDonnees["case_macaron_taille_police"] / 1000.0
# Ecrit le texte
self.canvas.setFont(self.parent.dictDonnees["case_macaron_nom_police"], size=self.parent.dictDonnees["case_macaron_taille_police"])
self.canvas.setFillColor(ColorWxToPdf(self.parent.dictDonnees["case_macaron_texte_couleur"], alpha=1))
self.canvas.drawCentredString(self.largeur_case - largeur + largeur / 2.0, self.hauteur_case - (hauteur / 2.0 + hauteur_font / 2.0), texte)
示例11: hDraw
def hDraw(self, c, msg, fnt, x, y):
"Helper - draws it with a box around"
c.setFont(fnt, 16, 16)
font = pdfmetrics.getFont(fnt)
c.drawString(x, y, msg)
width = font.stringWidth(msg, 16)
c.rect(x,y,width,16,stroke=1,fill=0)
示例12: draw_text
def draw_text(string, text, font, size, width, leading=None):
if leading:
text.setFont(font, size, leading=leading)
else:
text.setFont(font, size)
font = pdfmetrics.getFont(font)
if font.stringWidth(string, size) > width:
bits = string.split(' ')
while bits:
did_something = False
for i in range(1, len(bits) + 1):
if font.stringWidth(' '.join(bits[:i]), size) > width:
if i == 1:
i = 2
text.textLine(' '.join(bits[:i - 1]))
bits = bits[i - 1:]
did_something = True
break
if not did_something:
text.textLine(' '.join(bits))
break
else:
text.textLine(string)
示例13: _formatText
def _formatText(self, text):
"Generates PDF text output operator(s)"
if self._dynamicFont:
#it's a truetype font and should be utf8. If an error is raised,
results = []
font = pdfmetrics.getFont(self._fontname)
try: #assume UTF8
stuff = font.splitString(text, self._canvas._doc)
except UnicodeDecodeError:
#assume latin1 as fallback
from reportlab.pdfbase.ttfonts import latin1_to_utf8
from reportlab.lib.logger import warnOnce
warnOnce('non-utf8 data fed to truetype font, assuming latin-1 data')
text = latin1_to_utf8(text)
stuff = font.splitString(text, self._canvas._doc)
for subset, chunk in stuff:
if subset != self._curSubset:
pdffontname = font.getSubsetInternalName(subset, self._canvas._doc)
results.append("%s %s Tf %s TL" % (pdffontname, fp_str(self._fontsize), fp_str(self._leading)))
self._curSubset = subset
chunk = self._canvas._escape(chunk)
results.append("(%s) Tj" % chunk)
return string.join(results, ' ')
else:
text = self._canvas._escape(text)
return "(%s) Tj" % text
示例14: telemetry
def telemetry(font, size):
"""
Return telemetry information about a given font.
Returns a dict, with the following members:
{
'm_width': float, approximated 'em square' size (rough),
'ascent': float, maximum height of text above baseline,
'descent': float, maxmim height of text below baseline,
'max_height': float, ascent+descent
}
"""
face = getFont(font).face
# +30% 'fudge' factor
m_width = stringWidth('M', font, size)*1.3
ascent = float(face.ascent)*m_width/1000
descent = float(face.descent*-1)*m_width/1000
return {
'm_width': m_width,
'ascent': ascent,
'descent': descent,
'max_height': ascent+descent,
}
示例15: _calcHeight
def _calcHeight(self):
dy = self.dy
yGap = self.yGap
thisy = upperlefty = self.y - dy
fontSize = self.fontSize
ascent=getFont(self.fontName).face.ascent/1000.
if ascent==0: ascent=0.718 # default (from helvetica)
ascent *= fontSize
leading = fontSize*1.2
deltay = self.deltay
if not deltay: deltay = max(dy,leading)+self.autoYPadding
columnCount = 0
count = 0
lowy = upperlefty
lim = self.columnMaximum - 1
for name in self._getTexts(self.colorNamePairs):
y0 = thisy+(dy-ascent)*0.5
y = y0 - _getLineCount(name)*leading
leadingMove = 2*y0-y-thisy
newy = thisy-max(deltay,leadingMove)-yGap
lowy = min(y,newy,lowy)
if count==lim:
count = 0
thisy = upperlefty
columnCount = columnCount + 1
else:
thisy = newy
count = count+1
return upperlefty - lowy