Python Reportlab - 无法打印特殊字符

时间:2013-10-31 16:41:23

标签: python reportlab

Python Reportlab

我在pdf "&"

中打印特殊字符时遇到问题
# -*- coding: utf-8 -*-
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.rl_config import defaultPageSize
from reportlab.lib.units import inch

styles = getSampleStyleSheet()

def myFirstPage(canvas, doc):
  canvas.saveState()

def go():
  doc = SimpleDocTemplate("phello.pdf")
  Story = [Spacer(1,2*inch)]
  Story.append(Paragraph("Some text", styles["Normal"]))
  Story.append(Paragraph("Some other text with &", styles["Normal"]))
  doc.build(Story, onFirstPage=myFirstPage) 

go()

我预计输出

 Some text
 Some other text with &

但我得到的输出是

 Some text
 Some other text with

'&'在哪里消失了。

我搜索了一些论坛,说我需要将其编码为&,但是处理这个问题并不比编码每个特殊字符更简单吗?

我在脚本的顶部添加了"# -*- coding: utf-8 -*-",但这并没有解决我的问题

1 个答案:

答案 0 :(得分:4)

你应该替换&,<和>使用&<>。一个简单的方法是Python转义函数:

from cgi import escape
Story.append(Paragraph(escape("Some other text with &"), styles["Normal"]))

然而,HTML标签需要具有真实的<和>所以典型的用法更像是:

text = "Some other text with &"
Story.append(Paragraph(escape("<b>" + text + "</b>"), styles["Normal"]))