reportlab中的条件分页符

2024-05-15 12:01:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Reportlab platypus创建PDFs表。我不知道,因为动态内容,页面什么时候满了。如果我在这一页的末尾,我怎样才能结账?

鸭嘴兽有没有办法检查页末?

我有公司名单,每家公司都有多个业务部门,并有各自的费用。

   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)

Tags: namefields列表table公司documentcompaniescolors
3条回答

你得自己数数用过的线。 我使用的程序包括:

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

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

我用数点的方法来处理不同高度的线条。

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

当表格到达页面末尾时,它们会自动断开。但我发现了另一个例子:

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

假设您想在页面呈现之后绘制一些内容,那么可以使用afterPage()方法,该方法在BaseDocTemplate类中提供。从ReportLab的文档中:

This is called after page processing, and immediately after the afterDrawPage method of the current page template. A derived class could use this to do things which are dependent on information in the page such as the first and last word on the page of a dictionary.

基本上,它是在绘制页面后由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)

相关问题 更多 >