Search code examples
pythonpdfreportlab

ReportLab - How to apply PageTemplate to all pages (more than two pages)?


In general I would like to create a pdf document with multiple pages, where each page has the same layout (PageTemplate).

My created paragraph (very_long_text) spans over two or more pages, but I only managed to define the same PageTemplate for the first two pages.

How can I modify the code, so that each page (more than two pages) considers the defined PageTemplate?

# Create document object
        doc = SimpleDocTemplate(output_path, 
                                pagesize=(self.config.PAGE_WIDTH * mm, self.config.PAGE_HEIGHT* mm), 
                                rightMargin=self.config.PAGE_MARGIN_RIGHT*mm, 
                                leftMargin=self.config.PAGE_MARGIN_LEFT*mm, 
                                topMargin=self.config.PAGE_MARGIN_TOP*mm,
                                bottomMargin=self.config.PAGE_MARGIN_BOTTOM*mm)

        # Create column frame
        # [Some frames are defined here, namely, col1,col2,...]

        
        # Add PageTemplates
        firstPage =  PageTemplate(id="firstPage",frames=[col1, col2, col3, col4, col5, col6])
        laterPages = PageTemplate(id="LaterPages",frames=[col1, col2, col3, col4, col5, col6])
        doc.addPageTemplates([firstPage,laterPages])

        # Create Story
        story = [NextPageTemplate(['*', 'LaterPages'])]
        story = []

        # Create style
        paraStyle = ParagraphStyle(name="Normal",
                                fontName=self.config.FONT_NAME,
                                fontSize=self.config.FONT_SIZE,
                                alignment=TA_JUSTIFY,
                                splitLongWords=1,
                                hyphenationLang = "de_DE",
                                borderWidth=1,
                                backColor="#FFFF00")

        story.append(Paragraph(very_long_text, paraStyle))

        doc.build(story)

Solution

  • Try switching from SimpleDocTemplate to BaseDocTemplate. I had the same problem with SimpleDocTemplate and switching fixed it for me. In my case when I added NextPageTemplate to the story it was only being applied to the first page of flowables that spanned multiple pages. Once I switched to BaseDocTemplate, the template was applied to each page.