2

I am trying to change the page template dynamically using the onPage callback for the PageTemplate using handle_nextPageTemplate method.

If you look at the generated PDF, the second page does not get the correct PageTemplate switch happening.

Following is the source I am trying to use.

import sys, os, json
from reportlab.lib.units import mm
from reportlab.lib.pagesizes import A4, LETTER
from reportlab.platypus import BaseDocTemplate, Paragraph, Spacer, Frame, PageTemplate

page = {
    "size": [A4[0], LETTER[1]] ,
        "width": A4[0],
        "height": A4[1],
        "margin": {
            "left": 16*mm,
            "right": 16*mm,
            "top": 20*mm,
            "bottom": 20*mm,
        },
}


def drawHeader(canv, doc):
    '''Called before the new page draw is started.
    '''
    print("draw Header called !")
    # change the next page template before the next page template is called.
    if doc.page % 2 == 0:
        doc.handle_nextPageTemplate('t2')
    else:
        doc.handle_nextPageTemplate('t1')

pdfpath = os.path.abspath(os.path.join(os.path.dirname(__file__), "testTemplate.pdf"))
doc = BaseDocTemplate(pdfpath, pagesize=page["size"], 
                                showBoundary=0)

# generate 2 different templates
x = page['margin']['left']
y = page['margin']['bottom']
w = page['width'] - page['margin']['left'] - page['margin']['right']
h = page['height'] - page['margin']['bottom'] - page['margin']['top']

frame1 = Frame(x, y, w, h, bottomPadding=0, leftPadding=0, topPadding=0, rightPadding=0, id="f1", showBoundary=True)
template1 = PageTemplate(id='t1', frames=[frame1], onPage=drawHeader)

h2 = h - page['margin']['bottom']

frame2 = Frame(x, y, w, h2, id="f2", bottomPadding=0, leftPadding=0, topPadding=0, rightPadding=0, showBoundary=True)
template2 = PageTemplate(id='t2', frames=[frame2], onPage=drawHeader)

story = [
    Paragraph("This is first para."),
    Paragraph("This is 2 para."),
    Spacer(3*mm, 10*mm),
    Paragraph("This is 3 para."*1000),
    Spacer(3*mm, 10*mm),
    # PageBreak(),
    Paragraph("this is second text"),
    Spacer(3*mm, 10*mm),
    Paragraph("this is 22 text <br/>"*500),
    Spacer(3*mm, 10*mm),
    Paragraph("this is 33 text"),
]

doc.addPageTemplates([template1, template2])
doc.build(story)

Can someone help me with this ?

Ronak SHAH
  • 171
  • 2
  • 11

0 Answers0