• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python fonts.addMapping函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



在下文中一共展示了addMapping函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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))
开发者ID:jeffersontito,项目名称:geraldo,代码行数:32,代码来源:pdf.py


示例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
开发者ID:svilendobrev,项目名称:rl2wx,代码行数:28,代码来源:fonts.py


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


示例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')
开发者ID:Distrotech,项目名称:reportlab,代码行数:27,代码来源:test_paragraphs.py


示例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)
开发者ID:yl812708519,项目名称:tornado_test_web,代码行数:10,代码来源:contract.py


示例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)
开发者ID:pjyuan,项目名称:App,代码行数:33,代码来源:save2PDF.py


示例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')
                )
开发者ID:tieugene,项目名称:rml2pdf,代码行数:26,代码来源:trml2pdf.py


示例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)
开发者ID:kevin-garnett,项目名称:openerp-from-oneyoung,代码行数:33,代码来源:__init__.py


示例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
开发者ID:jwarlander,项目名称:pycalendargen,代码行数:49,代码来源:PyCalendarGen.py


示例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()
开发者ID:BackupTheBerlios,项目名称:cuon-svn,代码行数:48,代码来源:CalendarGen.py


示例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)
开发者ID:EtherGraf,项目名称:mwlib.rl,代码行数:16,代码来源:fontconfig.py


示例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)
开发者ID:sharefuntech,项目名称:syn,代码行数:57,代码来源:getpdf.py


示例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
开发者ID:vandorjw,项目名称:django-invoice,代码行数:46,代码来源:pdf.py


示例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
开发者ID:BackupTheBerlios,项目名称:griffith-svn,代码行数:56,代码来源:PluginExportPDF.py


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


示例16: registerTypeFace

def registerTypeFace(face):
    assert isinstance(face, TypeFace), 'Not a TypeFace: %s' % face
    _typefaces[face.name] = face
    # HACK - bold/italic do not apply for type 1, so egister
    # all combinations of mappings.
    from reportlab.lib import fonts
    ttname = string.lower(face.name)
    if not face.name in standardFonts:
        fonts.addMapping(ttname, 0, 0, face.name)
        fonts.addMapping(ttname, 1, 0, face.name)
        fonts.addMapping(ttname, 0, 1, face.name)
        fonts.addMapping(ttname, 1, 1, face.name)
开发者ID:alexissmirnov,项目名称:donomo,代码行数:12,代码来源:pdfmetrics.py


示例17: register_fonts_from_paths

def register_fonts_from_paths(regular, italic=None, bold=None, bolditalic=None, font_name='Reporting'):
    """
    Pass paths to TTF files which should be used for the PDFDocument
    """
    pdfmetrics.registerFont(TTFont('%s' % font_name, regular))
    pdfmetrics.registerFont(TTFont('%s-Italic' % font_name, italic or regular))
    pdfmetrics.registerFont(TTFont('%s-Bold' % font_name, bold or regular))
    pdfmetrics.registerFont(TTFont('%s-BoldItalic' % font_name, bolditalic or bold or regular))

    addMapping('%s' % font_name, 0, 0, '%s' % font_name)  # regular
    addMapping('%s' % font_name, 0, 1, '%s-Italic' % font_name)  # italic
    addMapping('%s' % font_name, 1, 0, '%s-Bold' % font_name)  # bold
    addMapping('%s' % font_name, 1, 1, '%s-BoldItalic' % font_name)  # bold & italic
开发者ID:peicheng,项目名称:vosae-app,代码行数:13,代码来源:utils.py


示例18: 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.findall('registerFont'):
                name = font.get('fontName').encode('ascii')
                fname = font.get('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
开发者ID:Buyanbat,项目名称:XacCRM,代码行数:14,代码来源:trml2pdf.py


示例19: 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
开发者ID:jordotech,项目名称:trml2pdf,代码行数:14,代码来源:trml2pdf.py


示例20: __init__

 def __init__(self, pdf_file, xml_file,country_name):
     pdfmetrics.registerFont(TTFont('Arial', 'fonts/Arial.ttf'))
     pdfmetrics.registerFont(TTFont('Arial-Bold', 'fonts/Arial-Bold.ttf'))
     pdfmetrics.registerFont(TTFont('Arial-Italic', 'fonts/Arial-Italic.ttf'))
     addMapping('Arial',0,0,'Arial')
     addMapping('Arial',0,1,'Arial-Italic')
     addMapping('Arial',1,0,'Arial-Bold')
     
     self.country = country_name
     self.styles = getSampleStyleSheet()
     self.e = ElementTree.parse(xml_file).getroot()
     self.width, self.height =  int(self.e.getchildren()[0].get("width")), int(self.e.getchildren()[0].get("height"))
     self.c = canvas.Canvas(pdf_file, pagesize=(self.width,self.height))
     self.fonts = {}
     for page in self.e.findall("page"):
         for fontspec in page.findall("fontspec"):
             font = {}
             font["size"] = int(fontspec.get("size"))
             font["color"] = fontspec.get("color")
             font["background"] = fontspec.get("background")
             if fontspec.get("indent") is not None:
                 font["indent"] = fontspec.get("indent")
             else:
                 font["indent"] = "0"
             if fontspec.get("padding") is not None:
                 font["padding"] = fontspec.get("padding")
             else:
                 font["padding"] = "0"
             self.fonts[fontspec.get("id")] = font 
开发者ID:akmiller01,项目名称:alexm-util,代码行数:29,代码来源:render.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python logger.warnOnce函数代码示例发布时间:2022-05-26
下一篇:
Python colors.toColor函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap