[英]Python Reportlab - Unable to print special characters
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 -*-"
,但這不能解決我的問題
您應該用&
替換&,<和> &
, <
和>
。 一種簡單的方法是使用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"]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.