I'm trying to add long paragraphs in my reportlab document.
It succeeds when I just add the whole text, like:
self.story.append(Paragraph(text, STYLE_PARAGRAPH))
and build it using
self.doc.multiBuild(self.story, canvasmaker=MyCanvas)
The problem is, that line breaks (\n
) are not considered. I tried to replace them with <br/>
, but this seems not to be supported by platypus, I get an error that the br
tag is unknown.
My next attempt was to split it into separate paragraphs:
for p in text.replace('\r', '').split('\n'):
self.story.append(Paragraph(p, STYLE_PARAGRAPH))
which leads to:
reportlab.platypus.doctemplate.LayoutError: Splitting error(n==1) on page 47 in [...]
Any idea what I'm doing wrong?
-- UPDATE --
As Adam said, <br/>
should work, but it did not in my case. After long hours of debugging, I found that an import was wrong:
Correct:
from reportlab.platypus import Paragraph
My import:
from reportlab.platypus.para import Paragraph
While I have no idea why the wrong import does work anyway.
The line break tag <br/>
should work with PLATYPUS as shown in Figure 6-8 of the ReportLab User Guide on page 78. There is an error if a self-closing line break <br/>
is not used. The tags <br>
and </br>
will cause an error.
I created and tested a short example to demonstrate this with a long paragraph that contains line breaks. There are two line break tags after the third sentence and at the end of the paragraph. The paragraph was repeated to demonstrate it on multiple pages.
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import SimpleDocTemplate, Paragraph
stylesheet = getSampleStyleSheet()
stylesheet.add(ParagraphStyle(name='Paragraph', spaceAfter=10))
elements = []
# Create a long paragraph with multiple line breaks.
paragraph = "Lorem ipsum dolor sit amet, consectetur adipiscing elit." * 3
paragraph += "<br/><br/>"
paragraph += "Lorem ipsum dolor sit amet, consectetur adipiscing elit." * 10
paragraph += "<br/><br/>"
paragraph *= 10
elements.append(Paragraph(paragraph, stylesheet['Paragraph']))
pdf = SimpleDocTemplate('example.pdf', pagesize=letter)
pdf.build(elements)