簡體   English   中英

Reportlab表拆分

[英]Reportlab Table split

我是ReportLab的新手,頁面模板。 我必須創建一個報告,其中有2個頁面模板-第一頁面使用標題頁面模板,所有其他頁面都使用通用模板。 報表必須將一個表拆分為多個頁面。 在首頁上,表格必須顯示在寬度較小的框架上,然后其余表格在較大的框架上顯示其余頁面。

當表格在不同頁面之間拆分時,如何更改列寬和表格樣式?

編輯:在這里我放一些代碼可以成功拆分,但在所有頁面上保持表相同的寬度

# ReportLab PDF Generation Library
from reportlab.pdfgen        import canvas
from reportlab.lib.units     import inch, cm
from reportlab.lib.pagesizes import letter, landscape
from reportlab.lib           import colors

from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import BaseDocTemplate, Frame, Paragraph, NextPageTemplate, PageBreak, PageTemplate, Spacer
from reportlab.platypus.tables import Table, TableStyle

# Constants
Font_Leading = 10
Word_Spacing = 0.0
Char_Spacing = 0.08

#global table
data= [['DATE', 'NAME', 'ITEM', 'AMOUNT', 'BALANCE'],
    ['01/12/15', 'William', 'ITEM1 RELATED STUFF', '365.00', '43.30']
    # CONSIDER MANY MORE ITEMS HERE
    # NUMBER FO ITMES VARYING IN WAY TO CAUSE 1 OR MORE PAGES
    # 3RD COLUMN WILL HAVE DESCRIPTIVE ITEM
    # WHICH WILL REPLACE WITH PARAGARPHS LATER ON
  ]
t=Table(data,repeatRows=1,
  colWidths=[.7*inch, 1*inch, 2.4*inch, .8*inch, .8*inch])
 #The top left cell is (0, 0) the bottom right is (-1, -1).
tStyle = TableStyle([
    # All Cells
    ('FONTSIZE', (0,0), (-1,-1), 8),
    ('TOPPADDING', (0,0), (-1,-1), 0),
    ('BOTTOMPADDING', (0,0), (-1,-1), 0),
    ('VALIGN', (0,0), (-1,-1), 'TOP'),
    ('LEADING', (0,0), (-1,-1), 10),
    # Top row
    ('BACKGROUND', (0,0), (-1,0), colors.maroon),
    ('TEXTCOLOR', (0,0), (-1,0), colors.white),
    ('ALIGN', (0,0), (-1,0), 'CENTRE'),
    # 3RD and 4th column,
    ('ALIGN', (3,0), (4,-1), 'RIGHT'),
    # Line commands
    # All
    ('BOX',(0,0),(-1,-1),.5,colors.black),
    # top row
    ('GRID',(0,0),(-1,0),.5,colors.black),
    # all columns
    ('LINEBEFORE',(0,0),(-1,-1),.5,colors.black),
    # last column
    ('LINEAFTER',(-1,0),(-1,-1),.5,colors.black),
    # last row
    ('LINEBELOW',(0,-1),(-1,-1),.5,colors.black)])
t.setStyle(tStyle)

def othPg(c, doc):
  t.colWidths = [.2*inch, .2*inch,4*inch, .2*inch, .2*inch]
  tStyle.add('BACKGROUND',(0,0),(-1,-1),colors.lightblue)
  x=1

def pgHdr(c, doc):
  width,height = letter
  c.saveState()
  c.translate(.3 * inch, 0 * inch)

# STUFF RELATED TO 2 INCH STTIC HEADER FOR FIRST PAGE
  c.restoreState()


def main():
  pdf_file = 'stmt.pdf'
  Elements = []
  doc = BaseDocTemplate(pdf_file,
                        pagesize=letter,
                        leftMargin=.3*inch,
                        rightMargin= .1 * inch,
                        topMargin= .1 * inch,
                        bottomMargin=.3 * inch,
                        showBoundary=1)
  #normal frame as for SimpleFlowDocument
  frameT = Frame(doc.leftMargin + 2*inch, doc.bottomMargin, doc.width - 2.01*inch, doc.height - 4.1*inch, id='normal', showBoundary=0)
  frameB = Frame(doc.leftMargin+2, doc.bottomMargin, 7.5*inch, 10*inch, id='small', showBoundary=1)



  doc.addPageTemplates([PageTemplate(id='First',frames=frameT,onPage=pgHdr),
                        PageTemplate(id='Later',frames=frameB,onPage=othPg)
                      ])
  Elements.append(NextPageTemplate('Later'))
  Elements.append(t)
  doc.build(Elements)

if __name__ == "__main__":
    sys.exit(main())

對於普通Table ,似乎不可能自動執行此操作(基於源代碼 )。 它可以在拆分時保留列寬,這很有意義,因為在分頁符之后更改表的布局會使最終用戶感到困惑。

您可以創建自己的Table版本,但該版本的確會改變列的大小,但這將涉及覆蓋Table的相當復雜的split函數。

因此,在您的情況下,最簡單且可能最可行的解決方案是使兩個模板中的框架具有相同的寬度。 然后,您根本不必更改列寬。

編輯:應OP的要求,我研究了一些選項,以使后一頁的樣式和列寬更加熟練。 基於此,我基於Reportlabs Table創建了以下類:

class LaterPagesTable(Table):
    def __init__(self, data, laterColWidths=None, laterStyle=None, **kwargs):
        Table.__init__(self, data, **kwargs)

        self._later_column_widths = laterColWidths
        self._later_style = laterStyle


    def split(self, availWidth, availHeight):
        self._calc(availWidth, availHeight)
        if self.splitByRow:
            if not rl_config.allowTableBoundsErrors and self._width>availWidth: return []
            tables = self._splitRows(availHeight)

            if len(tables):
                self.onLaterPages(tables[1])
            return tables
        else:
            raise NotImplementedError


    def onLaterPages(self, T):
        if self._later_column_widths:
            T._argW = self._later_column_widths

        if self._later_style:
            T.setStyle(self._later_style)

此類允許用戶使用關鍵字參數laterColWidthslaterStyle指定后面的頁面的樣式和laterColWidths laterStyle ,其語法與普通colWidthsstyle colWidths ,但是僅在放置表的部分上使用在原始頁面之外。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM