Reputation: 21
Python Reportlab
:
I am facing problem while printing special characters in my pdf
like "&"
# -*- 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 Expected following output
Some text
Some other text with &
But the output I get is
Some text
Some other text with
Where did '&' get vanished.
I have searched some forums which say that I need to encode it as &
but is there not easier way to handle this than encoding each special character?
I have added "# -*- coding: utf-8 -*-"
at the top of my script but that does not solve my problem
Upvotes: 2
Views: 4349
Reputation: 3034
You should replace &, < and > with the &
, <
and >
. One easy way to do that is the Python escape function:
from cgi import escape
Story.append(Paragraph(escape("Some other text with &"), styles["Normal"]))
However, HTML tags need to have real < and > so a typical use would be more like:
text = "Some other text with &"
Story.append(Paragraph(escape("<b>" + text + "</b>"), styles["Normal"]))
Upvotes: 6