TableOfContents

Include(ZPyUGnav)

文用 Reportlab 生成中文 PDF

Jiahua Huang <[email protected]>
reply-to        [email protected]
to      "Python.cn@google" <[email protected]>
date    Fri, Aug 8, 2008 at 15:13

subject [CPyUG:61808] 简单使用 Reportlab 生成中文 PDF 文档

不过 python-reportlab 默认没中文字体,也没中文换行,

便干脆用运行中修改的方式覆盖掉 reportlab.lib.fonts.ps2tt reportlab.lib.fonts.tt2ps reportlab.platypus.Paragraph.wrap 让强制用中文字体,强制尝试中文换行(,强制用 UTF-8 中文)

缺陷是连英文也没粗体斜体了。

添加
  • ## Hack for Chinese fonts ############################

   1 import reportlab.rl_config
   2 reportlab.rl_config.warnOnMissingFontGlyphs = 0
   3 import reportlab.pdfbase.pdfmetrics
   4 import reportlab.pdfbase.ttfonts
   5 reportlab.pdfbase.pdfmetrics.registerFont(reportlab.pdfbase.ttfonts.TTFont('song',
   6 '/usr/share/fonts/truetype/wqy/wqy-zenhei.ttf'))
   7 import reportlab.lib.fonts
   8 reportlab.lib.fonts.ps2tt = lambda psfn: ('song', 0, 0)
   9 reportlab.lib.fonts.tt2ps = lambda fn,b,i: 'song'
  10 ## for CJK Wrap
  11 import reportlab.platypus
  12 def wrap(self, availWidth, availHeight):
  13   # work out widths array for breaking
  14   self.width = availWidth
  15   leftIndent = self.style.leftIndent
  16   first_line_width = availWidth -
  17 (leftIndent+self.style.firstLineIndent) - self.style.rightIndent
  18   later_widths = availWidth - leftIndent - self.style.rightIndent
  19   try:
  20       self.blPara = self.breakLinesCJK([first_line_width, later_widths])
  21   except:
  22       self.blPara = self.breakLines([first_line_width, later_widths])
  23   self.height = len(self.blPara.lines) * self.style.leading
  24   return (self.width, self.height)
  25 
  26 reportlab.platypus.Paragraph.wrap = wrap
  27 
  28 import sys
  29 reload(sys)
  30 sys.setdefaultencoding('utf8')


反馈

创建 by -- ZoomQuiet [DateTime(2008-08-08T07:43:16Z)]

PageComment2

[:/PageCommentData:PageCommentData]