Переход к следующему кадру в ReportLab - PullRequest
2 голосов
/ 17 мая 2019

В ReportLab у меня есть шаблон страницы, состоящий из 2 вертикальных фреймов.Здесь я пытаюсь добиться того, чтобы после размещения некоторого динамического текста на странице (первый кадр) я хотел бы перейти к началу второго кадра.

Я попытался добиться этого путем вычислениявысота текстовых объектов из 1-го кадра, а затем вставка Spacer с высотой, равной (doc.height - вес текстовых объектов из 1-го кадра).Однако это не работает.Это упрощенный код и его вывод.

   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)

enter image description here

Кто-нибудь знает, что я здесь не так делаю?Спасибо!

1 Ответ

1 голос
/ 17 мая 2019

Я предлагаю вам попробовать 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 страницы):

enter image description here

...