Python Reportlab - 无法打印特殊字符

Ash*_*h K 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()
Run Code Online (Sandbox Code Playgroud)

我期望以下输出

 Some text
 Some other text with &
Run Code Online (Sandbox Code Playgroud)

但我得到的输出是

 Some text
 Some other text with
Run Code Online (Sandbox Code Playgroud)

'&' 在哪里消失了。

我搜索了一些论坛,它们说我需要将其编码为,&但是没有比编码每个特殊字符更简单的方法来处理这个问题吗?

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

man*_*ica 6

您应该将 &、< 和 > 替换为&amp;,&lt;&gt;。一种简单的方法是使用 Python 转义函数:

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

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

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