9

我正在使用 Reportlab 鸭嘴兽创建 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)
4

4 回答 4

7

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

假设你想在页面渲染后绘制一些东西,你可以使用类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()

现在您可以使用MyDocTemplate与在主逻辑中使用 BaseDocTemplate 相同的方式:

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)
于 2012-07-01T17:39:13.117 回答
0

您必须计算自己使用的行数。我使用的程序包括:

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

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

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

于 2012-07-05T18:58:17.123 回答
0

根据如何在 PDF 页面上拆分 ReportLab 表格(并排),将表格拆分为多个页面需要使用您自己的模板?

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

于 2012-07-06T20:19:42.207 回答
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()
于 2017-12-19T02:51:14.210 回答