2013-10-31 94 views
2

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 -*-"但这并不解决我的问题

+2

欢迎堆栈溢出!看起来你希望我们为你写一些代码。 尽管许多用户愿意为遇险的编码人员编写代码,但他们通常仅在海报已尝试自行解决问题时才提供帮助。 证明这一努力的一个好方法是包含迄今为止编写的代码, 示例输入(如果有的话),期望的输出和实际获得的输出(控制台输出,堆栈跟踪,编译器错误 - 无论什么适用)。 您提供的细节越多,您可能收到的答案越多。检查[常见问题]和[问] –

+0

可能的重复[报告实验室无法处理希伯来语(unicode)](http://stackoverflow.com/questions/10958904/report-lab-cant-handle-hebrew-unicode) – sdasdadas

+0

没有sdasdadas。该线程给出的解决方案不能解决我的问题 –

回答

3

此时应更换&,<和>与&amp;&lt;&gt;。一个简单的方法来做到这一点是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"]))