Python Reportlab段落没有越过下一页

时间:2013-11-09 03:48:45

标签: python pdf python-2.7 reportlab platypus

目前我正在尝试在python中使用PDF documents创建reportlab。在我的PDF的每一页上,它会有多个这样的问题:

enter image description here

环顾四周后,我尝试使用Platypus SimpleDocTemplatePlatypus Paragraph来实现此格式。像这样(仅供参考 - 这不是完整的代码,但我认为这会给你一个粗略的想法)

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)

它以我想要的方式创建问题,但每当问题到达页面末尾时,它就会分解问题及其答案。像这样:

enter image description here

我不希望这种情况发生,所以根据this SO answer,我尝试使用paragraph.keepWithNext = True,但它没有任何区别。

有没有办法在同一页面上保持我的问题+答案(如果没有足够的空间)?

1 个答案:

答案 0 :(得分:2)

将您的问题和答案放在KeepTogether个实例中:

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将尝试将列表中的所有内容保留在同一页面上。