【问题标题】:Reportlab - Unicode characters appear as boxes in unicode-supported fontReportlab - Unicode 字符以支持 unicode 的字体显示为框
【发布时间】:2017-12-13 14:02:16
【问题描述】:

尝试通过 python 3 使用 reportlab 编写包含宏 (ā ēī ō ū) 的文档,但宏显示为框 (■)。该文档是用 Arial 字体编写的——但如果我在文字处理器中打开文件以检查字体,则这些框是“Segoe UI Symbol”字体。

用于在 Arial 中作为支持广泛 unicode 字符的字体导入(这似乎有效):

import reportlab.rl_config
reportlab.rl_config.warnOnMissingFontGlyphs = 0
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
pdfmetrics.registerFont(TTFont('Arial', 'Arial.ttf'))

我也是通过json导入字典,在记事本中打开json文件时是这样的:

{"example1":"b\u0101s"}

程序读写这个字典:

from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
doc = SimpleDocTemplate("hello.pdf")
Story = [Spacer(1,2*inch)]
style = styles["Normal"]
with open('CompDict.json','r') as f:
        m_dic=json.load(f)
for key,value in m_dic:
     p=Paragraph(key+":"+value,style)
     Story.append(p)
doc.build(Story)

结果应该是带有example1:bās 的pdf,但输出为example1:b■s

【问题讨论】:

  • 只是一个观察:您显示的 JSON sn-p 不是有效的 JSON(需要双引号)。但这可能与您的问题无关。
  • Python 2.x 还是 3?
  • 我使用的是 python 3.6

标签: python unicode reportlab


【解决方案1】:
#Here I am writing chunks of code, hope you will understand

from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer  
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle   
from reportlab.lib.enums import TA_CENTER,TA_JUSTIFY       
from reportlab.pdfbase import pdfmetrics      
from reportlab.pdfbase.ttfonts import TTFont   
from reportlab.lib.fonts import addMapping

pdfmetrics.registerFont(TTFont('devaNagri', 'NotoSerifDevanagari.ttf')) # devaNagri is a folder located in **/usr/share/fonts/truetype** and 'NotoSerifDevanagari.ttf' file you just download it from https://www.google.com/get/noto/#sans-deva and move to devaNagri folder.

addMapping('devaNagri', 0, 0, 'NotoSerifDevanagari') #devnagri is a folder name and NotoSerifDevanagari is file name 

style = getSampleStyleSheet()   
style.add(ParagraphStyle(name="ParagraphTitle", alignment=TA_JUSTIFY, fontName="devaNagri")) # after mapping fontName define your folder name.   
paragraph = Paragraph('your unicode string', style["ParagraphTitle"])

【讨论】:

    【解决方案2】:

    在此链接下找到您的角色:

    UTF-8 encoding table and Unicode characters

    1. 转到表的(utf-in 文字)行。

    2. 你会看到一些:\xc3\x85 类似的字符。选择你的角色...

    3. 然后对于文本输出,在您的代码中输入如下内容:

      Canvas.drawString(x,y,'\xc3\x85') => 它将打印Å ...

    因此您必须将字典项更改为 UTF-8 LITERALS,因为它无法理解 "b\u0101s"Unicode,有很多方法可以这样做...

    最好的问候

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-02
      • 2016-09-01
      • 1970-01-01
      • 2019-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-17
      相关资源
      最近更新 更多