Geraldo/ReportLab生成的PDF中Unicode字符显示为框框
我在用Geraldo和ReportLab生成PDF报告时遇到了一些与Unicode相关的问题。
当包含亚洲字符的Unicode字符串被放入报告中时,它们在输出的PDF里显示为黑色方块。这个例子(http://dl.dropbox.com/u/2627296/report.pdf)是用以下代码生成的:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from geraldo import Report, ReportBand, ObjectValue
from geraldo.generators import PDFGenerator
class UnicodeReport(Report):
title = 'Report'
class band_detail(ReportBand):
elements = [ObjectValue(attribute_name='name')]
if __name__ == '__main__':
objects = [{'name': u'한국어/조선말'}, {'name': u'汉语/漢語'}, {'name': u'オナカップ'}]
rpt = UnicodeReport(queryset=objects)
rpt.generate_by(PDFGenerator, filename='/tmp/report.pdf')
我使用的是Python 2.7.1,Geraldo 0.4.14和ReportLab 2.5。系统是64位的Ubuntu 11.04。这个.oy文件也是UTF-8编码的。在Document Viewer 2.32.0、Okular 0.12.2和Adobe Reader 9中查看PDF时,黑色方块是可见的。
非常感谢任何帮助!
1 个回答
1
你应该按照官方示例来指定字体名称,具体可以参考这个链接 "附加字体"。使用 additional_fonts
和 default_style
:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from geraldo import Report, ReportBand, ObjectValue
from geraldo.generators import PDFGenerator
class UnicodeReport(Report):
title = 'Report'
additional_fonts = {
'wqy': '/usr/share/fonts/wqy-zenhei/wqy-zenhei.ttc'
}
default_style = {'fontName': 'wqy'}
class band_detail(ReportBand):
elements = [ObjectValue(attribute_name='name')]
if __name__ == '__main__':
objects = [{'name': u'한국어/조선말'}, {'name': u'汉语/漢語'}, {'name': u'オナカップ'}]
rpt = UnicodeReport(queryset=objects)
rpt.generate_by(PDFGenerator, filename='/tmp/report.pdf')
ObjectValue()
还有一个命名参数 style
:
elements = [ObjectValue(attribute_name='name', style={'fontName': 'wqy'})]
这个字体是开源的,可以在这里下载: http://sourceforge.net/projects/wqy/files/ (我记得它是和 Ubuntu 11.04 一起提供的)