在ReportLab中,我有一个由2个垂直框架组成的页面模板。我要在这里实现的是-在页面上(第一帧)放置一些动态文本之后,我想转到第二帧的顶部。
我试图通过从第一个框架计算文本对象的高度,然后插入一个高度等于(doc.height-从第一个框架的文本对象的重量)的垫片来实现这一点。但是,这不起作用。这是简化的代码及其输出。
from reportlab.lib.pagesizes import A4, landscape
from reportlab.lib.units import inch
from reportlab.lib.styles import ParagraphStyle
from reportlab.platypus import *
if __name__ == "__main__":
style_1 = ParagraphStyle(name='Stylo',
fontName='Helvetica',
fontSize=20,
leading=12)
doc = BaseDocTemplate('test_spacer.pdf', showBoundary=1,
pagesize=landscape(A4), topMargin=30,
bottomMargin=30,
leftMargin=30, rightMargin=30)
frameCount = 2
frameWidth = (doc.width) / frameCount
frameHeight = doc.height - .05 * inch
frames = []
column = Frame(doc.leftMargin, doc.bottomMargin, 200, doc.height - .05* inch)
frames.append(column)
column = Frame(doc.leftMargin + 200, doc.bottomMargin, frameWidth - 200, doc.height - .05 * inch)
frames.append(column)
doc.addPageTemplates([PageTemplate(id='framess', frames=frames)])
story = []
for i, x in enumerate(['A', 'B', 'C']):
text = x*10*(i+1)
p1 = Paragraph(text, style_1)
w, h1 = p1.wrap(200, doc.height)
p2 = Paragraph(text*2, style_1)
w, h2 = p2.wrap(200, doc.height)
story.append(p1)
story.append(p2)
spac_height = ((doc.height) - (h1 + h2))
story.append(Spacer(width=0, height=spac_height))
story.append(Paragraph('This should be on the top of the 2nd Frame!' + x, style_1))
story.append(PageBreak())
doc.build(story)
有人知道我在这里做错了吗?谢谢!
最佳答案
我建议您尝试使用FrameBreak
而不是Spacer
,因为我认为休息是解决您问题的更好方法。
这是代码的修改版本,以显示结果:
import random
from reportlab.lib.pagesizes import A4, landscape
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import inch
from reportlab.platypus import (
BaseDocTemplate, PageTemplate, PageBreak, Frame, FrameBreak, Spacer, Paragraph,
)
if __name__ == "__main__":
style_1 = ParagraphStyle(
name='Stylo',
fontName='Helvetica',
fontSize=10,
leading=12)
doc = BaseDocTemplate(
'test_spacer.pdf',
showBoundary=1,
pagesize=landscape(A4),
topMargin=1*inch,
bottomMargin=1*inch,
leftMargin=1*inch,
rightMargin=1*inch)
frameCount = 2
frameWidth = doc.width / frameCount
frameHeight = doc.height - 0.05*inch
frame_list = [
Frame(
x1=doc.leftMargin,
y1=doc.bottomMargin,
width=frameWidth,
height=frameHeight),
Frame(
x1=doc.leftMargin + frameWidth,
y1=doc.bottomMargin,
width=frameWidth,
height=frameHeight),
]
doc.addPageTemplates([PageTemplate(id='frames', frames=frame_list), ])
story = []
for i, x in enumerate(['A', 'B', 'C']):
# add text in first frame
for _ in range(3):
story.append(
Paragraph(
x * random.randint(50, 100),
style_1))
# jump to next frame
story.append(FrameBreak())
# add text in second frame
story.append(
Paragraph(
'This should be on the top of the 2nd Frame! ' + x,
style_1))
story.append(PageBreak())
doc.build(story)
它提供以下输出(此图像仅显示前2页):