栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

ReportLab:使用中文/ Unicode字符

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ReportLab:使用中文/ Unicode字符

这个问题使我整个星期都着迷,所以由于是周末,所以我潜入其中,并精确地找到了一个我称之为

MultiFontParagraph
正常的解决方案,但
Paragraph
有很大的不同,您可以准确地设置字体后备顺序。

例如,我从互联网上提取的此随机日语文本使用以下字体回退

"Bauhaus", "Arial","HanaMinA"
。它检查第一个字体是否具有该字符的字形,如果是,则使用它,否则,它回退到下一个字体。当前的代码不是很有效,因为它在每个字符周围放置了标签,可以很容易地解决这个问题,但是为了清楚起见,我在这里没有这样做。

使用以下代码,我创建了上面的示例:

foreign_string = u'6905u897fu963fu79d1u8857uff0cu5927u53a6uff03u5927'P = MultiFontParagraph(foreign_string, styles["Normal"],          [  ("Bauhaus", "C:WindowsFonts\BAUHS93.TTF"),  ("Arial", "C:WindowsFonts\arial.ttf"),  ("HanaMinA", 'C:WindowsFontsHanaMinA.ttf')])

MultiFontParagraph

(git)的来源如下:

from reportlab.pdfbase import pdfmetricsfrom reportlab.pdfbase.ttfonts import TTFontfrom reportlab.platypus import Paragraphclass MultiFontParagraph(Paragraph):    # Created by B8Vrede for http://stackoverflow.com/questions/35172207/    def __init__(self, text, style, fonts_locations):        font_list = []        for font_name, font_location in fonts_locations: # Load the font font = TTFont(font_name, font_location) # Get the char width of all known symbols font_widths = font.face.charWidths # Register the font to able it use pdfmetrics.registerFont(font) # Store the font and info in a list for lookup font_list.append((font_name, font_widths))        # Set up the string to hold the new text        new_text = u''        # Loop through the string        for char in text: # Loop through the fonts for font_name, font_widths in font_list:     # Check whether this font know the width of the character     # If so it has a Glyph for it so use it     if ord(char) in font_widths:         # Set the working font for the current character         new_text += u'<font name="{}">{}</font>'.format(font_name, char)         break        Paragraph.__init__(self, new_text, style)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/637148.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号