本文整理汇总了Python中reportlab.lib.fonts.addMapping函数的典型用法代码示例。如果您正苦于以下问题:Python addMapping函数的具体用法?Python addMapping怎么用?Python addMapping使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了addMapping函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: prepare_additional_fonts
def prepare_additional_fonts(self):
"""This method loads additional fonts and register them using ReportLab
PDF metrics package.
Just supports TTF fonts, for a while."""
if not self.report.additional_fonts:
return
for font_family_name, fonts_or_file in self.report.additional_fonts.iteritems():
# Supports font family with many styles (i.e: normal, italic, bold, bold-italic, etc.)
if isinstance(fonts_or_file, (list, tuple, dict)):
for font_item in fonts_or_file:
# List of tuples with format like ('font-name', 'font-file', True/False bold, True/False italic)
if isinstance(font_item, (list, tuple)):
font_name, font_file, is_bold, is_italic = font_item
pdfmetrics.registerFont(TTFont(font_name, font_file))
addMapping(font_family_name, is_bold, is_italic, font_name)
# List of dicts with format like {'file': '', 'name': '', 'bold': False, 'italic': False}
elif isinstance(font_item, dict):
pdfmetrics.registerFont(TTFont(font_item["name"], font_item["file"]))
addMapping(
font_family_name,
font_item.get("bold", False),
font_item.get("italic", False),
font_item["name"],
)
# Old style: font name and file path
else:
pdfmetrics.registerFont(TTFont(font_family_name, fonts_or_file))
示例2: register_font
def register_font(font_name, family=""):
try:
return _registered_font_names[font_name]
except KeyError:
pass
found = ff.getFontsWithAttributes(name=font_name)
if not found:
# print '%(font_name)s not found, loading default for rl_config %(res)s' % locals()
res = rl_config.defaultGraphicsFontName
else:
descr = found[0]
if descr.typeCode == "ttf":
font = TTFont(descr.name, descr.fileName)
else:
face = pdfmetrics.EmbeddedType1Face(descr.metricsFileName, descr.fileName)
pdfmetrics.registerTypeFace(face)
font = pdfmetrics.Font(font_name, font_name, rl_config.defaultEncoding)
pdfmetrics.registerFont(font)
res = font_name
if 10:
from reportlab.lib.fonts import addMapping
bold = int("Bold" in font_name)
italic = int("Italic" in font_name)
addMapping(family or font_name, bold, italic, font_name)
_registered_font_names[font_name] = res
return res
示例3: getStyle
def getStyle(self):
'''
Returns the style (color and font details) specified
by the user through a dictionary
'''
fontDB = QFontDatabase()
matchFont=self.sysFonts.matchingFontName(str(self.elFont.rawName()))
qFontStyle=str(fontDB.styleString(self.elFont))
matchFontStyle=''
if qFontStyle.find("Normal")!=-1:
matchFontStyle=matchFont
else:
matchFontStyle=matchFont + " " + qFontStyle
#Register the fonts to be used in the report
fontStyle=self._buildFontFamily()
for k,v in fontStyle.iteritems():
#self.InfoMessage(k + ", " + v)
pdfmetrics.registerFont(TTFont(k,v))
#Add font mappings
psMappings=self._postScriptMappings(fontStyle)
for ps in psMappings:
addMapping(matchFont,ps["Bold"],ps["Italic"],ps["Style"])
dStyle={}
dStyle["fontName"]=matchFontStyle
dStyle["fontSize"]=self.elFont.pointSize()
dStyle["alignment"]=self.hAlign
dStyle["textColor"]=HexColor(str(self.elFontColor.name()))
return dStyle
示例4: getAFont
def getAFont():
'''register a font that supports most Unicode characters'''
I = []
font_name = 'DejaVuSans'
I.append([(font_name, 0, 0, font_name),
(font_name, 1, 0, font_name + '-Bold'),
(font_name, 0, 1, font_name + '-Oblique'),
(font_name, 1, 1, font_name + '-BoldOblique'),
])
font_name = 'FreeSerif'
I.append([(font_name, 0, 0, font_name),
(font_name, 1, 0, font_name + 'Bold'),
(font_name, 0, 1, font_name + 'Italic'),
(font_name, 1, 1, font_name + 'BoldItalic'),
])
for info in I:
n = 0
for font in info:
fontName = font[3]
try:
pdfmetrics.registerFont(ttfonts.TTFont(fontName,fontName + '.ttf'))
addMapping(*font)
n += 1
except:
pass
if n==4: return font[0]
raise ValueError('could not find suitable font')
示例5: Create_PDF_into_buffer
def Create_PDF_into_buffer(html, font_file_path):
# # 注册字体
pdfmetrics.registerFont(TTFont('yahei', font_file_path))
#
fonts.addMapping('song', 0, 0, 'song')
fonts.addMapping('song', 0, 1, 'song')
DEFAULT_FONT['helvetica'] = 'yahei'
xhtml2pdf.reportlab_paragraph.Paragraph.wrap = wrap
return pisaDocument(html)
示例6: txt2PDF
def txt2PDF(path):
pdfmetrics.registerFont(TTFont('song', 'SURSONG.TTF'))
pdfmetrics.registerFont(TTFont('hei', 'SIMHEI.TTF'))
fonts.addMapping('song', 0, 0, 'song')
fonts.addMapping('song', 0, 1, 'song')
fonts.addMapping('song', 1, 0, 'hei')
fonts.addMapping('song', 1, 1, 'hei')
f=file(path)
content = f.read()
contentList = content.split('\n')
#print contentList
stylesheet=getSampleStyleSheet()
normalStyle = copy.deepcopy(stylesheet['Normal'])
###设置PDF中文字字体
normalStyle.fontName ='hei' #字体为黑体
normalStyle.fontSize = 14.5 #字体大小
normalStyle.leading = 30 #行间距
normalStyle.firstLineIndent = 32 #首行缩进
story = []
for text in contentList:
#story.append(Paragraph(unicode(text, "utf-8" ), normalStyle))
#story.append(Paragraph(text.decode('utf-8'), normalStyle))
story.append(Paragraph(text.decode('gbk'), normalStyle))
pdfPath = path.split('.')[0] + '.pdf'
txtName = path.split('.')[0].split('/')[-1]
doc = SimpleDocTemplate(pdfPath,
rightMargin=20,leftMargin=20,
topMargin=20,
bottomMargin=20)
doc.build(story)
示例7: docinit
def docinit(self, els):
from reportlab.lib.fonts import addMapping
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
for node in els:
for font in node.getElementsByTagName('registerFont'):
name = font.getAttribute('fontName').encode('ascii')
fname = font.getAttribute('fontFile').encode('ascii')
pdfmetrics.registerFont(TTFont(name, fname))
addMapping(name, 0, 0, name) #normal
addMapping(name, 0, 1, name) #italic
addMapping(name, 1, 0, name) #bold
addMapping(name, 1, 1, name) #italic and bold
for font in node.getElementsByTagName('registerTTFont'):
name = font.getAttribute('faceName').encode('ascii')
fname = font.getAttribute('fileName').encode('ascii')
pdfmetrics.registerFont(TTFont(name, fname)) # , subfontIndex=subfontIndex
for font in node.getElementsByTagName('registerFontFamily'):
pdfmetrics.registerFontFamily(
font.getAttribute('normal').encode('ascii'),
normal = font.getAttribute('normal').encode('ascii'),
bold = font.getAttribute('bold').encode('ascii'),
italic = font.getAttribute('italic').encode('ascii'),
boldItalic = font.getAttribute('boldItalic').encode('ascii')
)
示例8: loadFonts
def loadFonts():
from reportlab import rl_config
rl_config.warnOnMissingFontGlyphs = 0
logger = netsvc.Logger()
for dirname in rl_config.TTFSearchPath:
for filename in [x for x in os.listdir(dirname)
if x.lower().endswith('.ttf') and rl_isreg(x, dirname)
]:
try:
face = ttfonts.TTFontFace(filename)
face.extractInfo(0) # Only header is needed
except ttfonts.TTFError, reason:
logger.notifyChannel(
'init', netsvc.LOG_WARNING,
'module report_truetype: registration of font file %s failed: %s' % (
filename, reason.message
))
else:
logger.notifyChannel(
'init', netsvc.LOG_INFO,
'module report_truetype: registering font %s (%s)' % (
face.name, filename
))
font = ttfonts.TTFont(face.name, filename)
pdfmetrics.registerFont(font)
if not font._multiByte:
# Already done in registerFont with multi-byte fonts
ttname = font.fontName.lower()
fonts.addMapping(ttname, 0, 0, font.fontName)
fonts.addMapping(ttname, 1, 0, font.fontName)
fonts.addMapping(ttname, 0, 1, font.fontName)
fonts.addMapping(ttname, 1, 1, font.fontName)
示例9: run
def run(args):
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.fonts import addMapping
# Process args
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description='Generate calendar pages in PDF format.',
epilog='''PyCalendarGen 0.9.5, Copyright (C) 2005-2012 Johan Wärlander
PyCalendarGen comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to redistribute it under certain conditions. See the
file COPYING for details.''')
parser.add_argument('year', type=str, metavar='YYYY',
help='The 4-digit starting year for the calendar '
'page, like 2012.')
parser.add_argument('month', type=str, metavar='MM[-NN]',
help='The number of the month you want to generate '
'a page for, like 05 for May. If of the format '
'MM-NN, it describes a range of up to 12 months. '
'In this case, if NN < MM, it means the calendar '
'wraps into month NN of the next year.')
parser.add_argument('filename', type=str, nargs='?',
help='The name of the PDF file to be written. By '
'default, it will be named like YYYY-MM.pdf.')
parser.add_argument('--cover-image', type=str, metavar='FILENAME', nargs='?',
help='Generate a cover page using the specified image.')
parser.add_argument('--monthly-image-dir', type=str, metavar='DIRECTORY', nargs='?',
help='Generate an opposing page for each month, with '
'an image taken by cycling through the files of '
'the specified directory in alphabetical order.')
parser.add_argument('-v', '--verbose', action='store_true',
help='Verbose output.')
args = parser.parse_args()
# Load fonts
for spec in fonttable:
pdfmetrics.registerFont(TTFont(spec[0], spec[1]))
for font in fontmap:
try:
addMapping(font[0], font[1], font[2], font[3])
if args.verbose:
print font
print "added."
except Exception, e:
print "Error adding Font:"
print e
示例10: run
def run(args):
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.fonts import addMapping
# Load fonts
for spec in fonttable:
pdfmetrics.registerFont(TTFont(spec[0], spec[1]))
for font in fontmap:
addMapping(font[0], font[1], font[2], font[3])
# Font test page
if 0:
c = Canvas("fonts.pdf", pagesize=portrait(A4))
ypos = 100
for font in fonttable:
c.setFont(font[0], 24)
c.drawString(100, ypos, font[0])
ypos += 24
c.save()
# Process args
if len(args) == 4:
fname = args[3]
else:
fname = args[1] + '-' + args[2] + '.pdf'
# Draw the calendar
c = Canvas(fname, pagesize=landscape(A4))
year = int(args[1])
month = args[2]
if len(month.split('-')) > 1:
start = int(month.split('-')[0])
end = int(month.split('-')[1])
if end < start:
for m in range(12-start+1):
drawCalendarPage(c, year, start+m)
for m in range(end):
drawCalendarPage(c, year+1, 1+m)
else:
for m in range(end-start+1):
drawCalendarPage(c, year, start+m)
else:
month = int(month)
drawCalendarPage(c, year, month)
c.save()
示例11: registerReportlabFonts
def registerReportlabFonts(self, font_list):
font_variants = ['', 'bold', 'italic', 'bolditalic']
for font in font_list:
if not font.get('name'):
continue
if font.get('type') == 'cid':
pdfmetrics.registerFont(UnicodeCIDFont(font['name']))
else:
for (i, font_variant) in enumerate(font_variants):
if i == len(font.get('file_names')) or not self.fontInstalled(font):
break
full_font_name = font['name'] + font_variant
pdfmetrics.registerFont(TTFont(full_font_name, self.getAbsFontPath(font.get('file_names')[i]) ))
italic = font_variant in ['italic', 'bolditalic']
bold = font_variant in ['bold', 'bolditalic']
addMapping(font['name'], bold, italic, full_font_name)
示例12: writePDF
def writePDF(issue,duzhe):
reportlab.rl_config.warnOnMissingFontGlyphs = 0
pdfmetrics.registerFont(TTFont('song',"simsun.ttc"))
pdfmetrics.registerFont(TTFont('hei',"msyh.ttc"))
fonts.addMapping('song', 0, 0, 'song')
fonts.addMapping('song', 0, 1, 'song')
fonts.addMapping('song', 1, 0, 'hei')
fonts.addMapping('song', 1, 1, 'hei')
stylesheet=getSampleStyleSheet()
normalStyle = copy.deepcopy(stylesheet['Normal'])
normalStyle.fontName ='song'
normalStyle.fontSize = 11
normalStyle.leading = 11
normalStyle.firstLineIndent = 20
titleStyle = copy.deepcopy(stylesheet['Normal'])
titleStyle.fontName ='song'
titleStyle.fontSize = 15
titleStyle.leading = 20
firstTitleStyle = copy.deepcopy(stylesheet['Normal'])
firstTitleStyle.fontName ='song'
firstTitleStyle.fontSize = 20
firstTitleStyle.leading = 20
firstTitleStyle.firstLineIndent = 50
smallStyle = copy.deepcopy(stylesheet['Normal'])
smallStyle.fontName ='song'
smallStyle.fontSize = 8
smallStyle.leading = 8
story = []
story.append(Paragraph("<b>读者{0}期</b>".format(issue), firstTitleStyle))
for eachColumn in duzhe:
story.append(Paragraph('__'*28, titleStyle))
story.append(Paragraph('<b>{0}</b>'.format(eachColumn), titleStyle))
for eachArticle in duzhe[eachColumn]:
story.append(Paragraph(eachArticle["title"],normalStyle))
story.append(flowables.PageBreak())
for eachColumn in duzhe:
for eachArticle in duzhe[eachColumn]:
story.append(Paragraph("<b>{0}</b>".format(eachArticle["title"]),titleStyle))
story.append(Paragraph(" {0} {1}".format(eachArticle["writer"],eachArticle["from"]),smallStyle))
para=eachArticle["context"].split(" ")
for eachPara in para:
story.append(Paragraph(eachPara,normalStyle))
story.append(flowables.PageBreak())
#story.append(Paragraph("context",normalStyle))
doc = SimpleDocTemplate("duzhe"+issue+".pdf")
print "Writing PDF..."
doc.build(story)
示例13: draw
def draw(self, invoice, stream):
""" Draws the invoice """
# embed unicode font
pdfmetrics.registerFont(
TTFont('FreeSans', join(STATIC_DIR, 'FreeSans.ttf'))
)
addMapping('FreeSans', 0, 0, 'FreeSans')
self.baseline = -2*cm
canvas = Canvas(stream, pagesize=A4)
canvas.setCreator("django-invoice")
canvas.setAuthor(smart_text(invoice.contractor))
canvas.setTitle(smart_text(invoice))
canvas.translate(0, 29.7*cm)
canvas.setFont(self.FONT_NAME, 10)
canvas.saveState()
self.draw_header(invoice, canvas)
canvas.restoreState()
canvas.saveState()
self.draw_subscriber(invoice, canvas)
canvas.restoreState()
canvas.saveState()
self.draw_contractor(invoice, canvas)
canvas.restoreState()
canvas.saveState()
self.draw_info(invoice, canvas)
canvas.restoreState()
canvas.saveState()
self.draw_items(invoice, canvas)
canvas.restoreState()
canvas.saveState()
self.draw_footer(invoice, canvas)
canvas.restoreState()
canvas.showPage()
canvas.save()
canvas = None
self.baseline = 0
示例14: create_styles
def create_styles(self):
self.styles = getSampleStyleSheet()
if self.config.get('font', '') != '':
self.fontName = 'custom_font'
fontfilename = self.config.get('font', '')
(fontfilenamebase, fontfilenameextension) = os.path.splitext(fontfilename)
pdfmetrics.registerFont(TTFont(self.fontName, fontfilename))
addMapping(self.fontName, 0, 0, self.fontName)
# build font family if available to support <b> and <i>
if os.path.isfile(fontfilenamebase + 'bd' + fontfilenameextension):
pdfmetrics.registerFont(TTFont(self.fontName + '-bold', fontfilenamebase + 'bd' + fontfilenameextension))
addMapping(self.fontName, 1, 0, self.fontName + '-bold')
if os.path.isfile(fontfilenamebase + 'bi' + fontfilenameextension):
pdfmetrics.registerFont(TTFont(self.fontName + '-bolditalic', fontfilenamebase + 'bi' + fontfilenameextension))
addMapping(self.fontName, 1, 1, self.fontName + '-bolditalic')
if os.path.isfile(fontfilenamebase + 'i' + fontfilenameextension):
pdfmetrics.registerFont(TTFont(self.fontName + '-italic', fontfilenamebase + 'i' + fontfilenameextension))
addMapping(self.fontName, 0, 1, self.fontName + '-italic')
else:
self.fontName = "Helvetica"
if self.config.get('font_size', '') != '':
self.base_font_size = int(self.config.get('font_size'))
else:
self.base_font_size = 18
title_font_size = self.base_font_size
heading1_font_size = self.base_font_size - 8
heading2_font_size = self.base_font_size - 3
heading3_font_size = self.base_font_size - 11
normal_font_size = self.base_font_size - 13
if heading1_font_size < 4:
heading1_font_size = 4
if heading2_font_size < 4:
heading2_font_size = 4
if heading3_font_size < 4:
heading3_font_size = 4
if normal_font_size < 4:
normal_font_size = 4
# adjust font
for (name, style) in self.styles.byName.items():
style.fontName = self.fontName
#adjust font sizes
self.styles['Title'].fontSize = title_font_size
self.styles['Title'].leading = title_font_size + 2
self.styles['Normal'].fontSize = normal_font_size
self.styles['Normal'].leading = normal_font_size + 2
self.styles['Heading1'].fontSize = heading1_font_size
self.styles['Heading1'].leading = heading1_font_size + 2
self.styles['Heading2'].fontSize = heading2_font_size
self.styles['Heading2'].leading = heading2_font_size + 2
self.styles['Heading3'].fontSize = heading3_font_size
self.styles['Heading3'].leading = heading3_font_size + 2
示例15: registerFontFamily
def registerFontFamily(family,normal=None,bold=None,italic=None,boldItalic=None):
from reportlab.lib import fonts
if not normal: normal = family
family = family.lower()
if not boldItalic: boldItalic = italic or bold or normal
if not bold: bold = normal
if not italic: italic = normal
fonts.addMapping(family, 0, 0, normal)
fonts.addMapping(family, 1, 0, bold)
fonts.addMapping(family, 0, 1, italic)
fonts.addMapping(family, 1, 1, boldItalic)