Differences between revisions 1 and 2
Revision 1 as of 2008-08-08 07:43:16
Size: 2570
Editor: ZoomQuiet
Comment:
Revision 2 as of 2008-08-08 07:45:13
Size: 2622
Editor: ZoomQuiet
Comment:
Deletions are marked like this. Additions are marked like this.
Line 28: Line 28:

== 实例和分析 ==
 * attachment:html2pdf.7z

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 文档

  • 再次看到关于将 reStructurctedText、asciidoc、xhtml 转换为 PDF 格式的话题,
  • python 里用 Reportlab 应该比用 tex、docbook、fop 合适,

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

  • 而现有的使用 Reportlab 的程序改起来也麻烦,

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

  • 好处是现有程序和库 (比如现有的那堆 rst2pdf、html2pdf、wiki2pdf 等程序) 不用做任何改动就可以中文,

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

实例和分析

  • attachment:html2pdf.7z
  • 添加
    • ## 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]

MiscItems/2008-08-08 (last edited 2009-12-25 07:09:01 by localhost)