Python Reportlab Paragraph not crossing over next page

Question:

Currently I am trying to create PDF documents with reportlab in python. On each page of my PDF , it will have multiple questions like this:

enter image description here

After looking around, i tried to achieve this format by using Platypus SimpleDocTemplate and Platypus Paragraph. Like this (FYI – this is not the complete code but i think this will give you a rough idea)

from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch

doc = SimpleDocTemplate('myfile.pdf')
Story = [Spacer(1,1.65*inch)]
style = styles['Normal']

quetsionno = Paragraph('Questoin no goes here',style)
myquestion = Paragraph('my question goes here',style)
myanswer1 = Paragraph('my answer1 goes here',style)
myanswer2 = Paragraph('my answer2 goes here',style)
myanswer3 = Paragraph('my answer3 goes here',style)

Story.append(quetsionno)     
Story.append(myquestion)
Story.append(myanswer1)
Story.append(myanswer2)
Story.append(myanswer3)
Story.append(Spacer(1,0.2*inch))

doc.build(Story)

It create the questions the way i want, but whenever the question reach toward the end of a page, it splits the question and it’s answers. Like this:

enter image description here

I don’t want that to happen, so according to this SO answer, I tried using paragraph.keepWithNext = True but it doesn’t make any difference.

Is there any way to keep my question+answers together in the same page (if there’s not enough space)?

Asked By: Chris Aung

||

Answers:

Keep your questions and answers together in a KeepTogether instance:

question = Paragraph('What color is the sky?', style)
answer1 = Paragraph('Red', style)
answer2 = Paragraph('Green', style)
answer3 = Paragraph('Blue', style)

Story.append(KeepTogether([question, answer1, answer2, answer3]))

ReportLab will try to keep everything in the list on the same page.

You can import the function with

from reportlab.platypus import KeepTogether

Answered By: Nitzle