reportlab中的条件分页符

问题描述 投票:8回答:4

我正在用Reportlab platypus创建PDF表格。我不知道,因为动态内容页面已满。如果我在页面的末尾,我该如何查看?

鸭嘴兽有没有方法检查页面末尾?

我有公司名单,每家公司都有多个业务部门负责。

   companies = [('company1', 'businessunit1', 500),
                ('company1', 'businessunit2',400),
                ('company2', 'businessunit3',200),
                ('company2', 'businessunit4', 700),
                ('company3', 'businessunit5', 800)
               ]

上面的列表应该为一个公司生成3个表,但是如果这个列表有多个公司将生成多个表,并且如果任何表到达页面末尾将会中断。

      fields = ['company name', 'business unit name', 'charge']
      for i, comp in enumerate(companies):
          charges = []
          document.append(Paragraph("<b>%s</b>" %comp[i][0], STYLES['COMPANY_NAME']))
          document.append(Spacer(1, 5))
          charges.append(comp[i][0])
          charges.append(comp[i][1])
          charges.append(comp[i][2])
          charges_table = LongTable([fields] + charges, colWidths=(30,150,100))
          charges_table.setStyle(TableStyle([
                          ('BACKGROUND', (0, 0), (-1, 0), colors.gray),
                          ('FONTSIZE', (0, 0), (-1, 0), 6),
                          ('GRID', (0, 0), (-1, -1), 1, colors.gray),
                          ('FONTSIZE', (0, 0), (-1, -1), 7),
                          ('TEXTCOLOR',(0,-1),(-1,-1),'#FF4500'),
                          ])
                          )

          charges_table.hAlign = 'CENTER'
          document.append(charges_table)
python django reportlab
4个回答
6
投票

您应该提供一些示例代码,以便我们知道您要完成的任务。为什么你想知道页面什么时候结束?要绘制新内容?打印出一些诊断信息?

假设您想在渲染页面后绘制内容,可以使用afterPage()类中提供的BaseDocTemplate方法。来自ReportLab的文档:

这是在页面处理之后调用的,紧接在当前页面模板的afterDrawPage方法之后。派生类可以使用它来执行依赖于页面中的信息的事情,例如字典页面上的第一个和最后一个字。

基本上,它是在绘制页面后由BaseDocTemplate调用的。在源代码中,它包含self,因为它是BaseDocTemplate类的一部分,所以你可以访问它的画布!

您可以在自己的脚本中覆盖该类,然后直接在画布上绘制。

from reportlab.platypus import BaseDocTemplate
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch
from reportlab.lib.pagesizes import A4
from reportlab.platypus import Paragraph

class MyDocTemplate(BaseDocTemplate):
    """Override the BaseDocTemplate class to do custom handle_XXX actions"""

    def __init__(self, *args, **kwargs):
        BaseDocTemplate.__init__(self, *args, **kwargs)

    def afterPage(self):
        """Called after each page has been processed"""

        # saveState keeps a snapshot of the canvas state, so you don't
        # mess up any rendering that platypus will do later.
        self.canv.saveState()

        # Reset the origin to (0, 0), remember, we can restore the
        # state of the canvas later, so platypus should be unaffected.
        self.canv._x = 0
        self.canv._y = 0

        style = getSampleStyleSheet()

        p = Paragraph("This is drawn after the page!", style["Normal"])

        # Wraps and draws the paragraph onto the canvas
        # You can change the last 2 parameters (canv, x, y)
        p.wrapOn(self.canv, 2*inch, 2*inch)
        p.drawOn(self.canv, 1*inch, 3*inch)

        # Now we restore the canvas back to the way it was.
        self.canv.restoreState()

现在你可以像在主逻辑中使用BaseDocTemplate一样使用MyDocTemplate

if __name__ == "__main__":

    doc = MyDocTemplate(
        'filename.pdf',
        pagesize=A4,
        rightMargin=.3*inch,
        leftMargin=.3*inch,
        topMargin=.3*inch, 
        bottomMargin=.3*inch
    )

    elements = [
        # Put your actual elements/flowables here, however you're generating them.
    ]

    doc.addPageTemplates([
        # Add your PageTemplates here if you have any, which you should!
    ])

    # Build your doc with your elements and go grab a beer
    doc.build(elements)

0
投票

你必须计算你自己使用的线。我使用的程序包括:

lin += inc
if lin > 580:
    doc.append(PageBreak())
    lin = 5

通过了解表使用了多少行,您可以知道它是否适合页面的其余部分。

我使用计数'点',所以我可以处理不同高度的线。


0
投票

在多个页面上打破一个表需要根据How to split ReportLab table across PDF page (side by side)?使用您自己的模板

表格到达页面末尾时应自动中断。但这是我发现的另一个例子:


0
投票

自动拆分longtable到多个页面,如下所示:

from reportlab.platypus import LongTable, TableStyle, BaseDocTemplate, Frame, PageTemplate
from reportlab.lib.pagesizes import letter
from reportlab.lib import colors


def test():
    doc = BaseDocTemplate(
        "test.pdf",
        pagesize=letter,
        rightMargin=72,
        leftMargin=72,
        topMargin=72,
        bottomMargin=18,
        showBoundary=True)

    elements = []
    datas = []
    for i, x in enumerate(range(1, 50)):
        datas.append([i, x])
    t = LongTable(datas)

    tableStyle = [
        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
        ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
    ]
    t.setStyle(TableStyle(tableStyle))
    elements.append(t)

    frame = Frame(
        doc.leftMargin, doc.bottomMargin, doc.width, doc.height, id='normal')
    doc.addPageTemplates([PageTemplate(id='longtable', frames=frame)])
    doc.build(elements)


if __name__ == '__main__':
    test()
© www.soinside.com 2019 - 2024. All rights reserved.