Python Reportlab无法打印特殊字符

2024-09-28 17:22:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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()

预期输出I

^{pr2}$

但我得到的结果是

 Some text
 Some other text with

'&;'从哪里消失的。在

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

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


Tags: textfromimportdocpdfsomeutfreportlab
1条回答
网友
1楼 · 发布于 2024-09-28 17:22:27

应该用&amp;&lt;和{}替换&;、<;和>。一种简单的方法是Python escape函数:

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

但是,HTML标记需要具有真实的<;和>;,因此通常的用法如下:

^{pr2}$

相关问题 更多 >