pythonplaywrightplaywright-python

Playwright - issue with the footer template parsing


Playwright (Python) save a page as PDF function works fine when there's no customisation in the header or footer. However, when I try to introduce a custom footer, the values don't seem to get injected appropriately.

Example code:

from playwright.sync_api import sync_playwright

def generate_pdf_with_page_numbers():
    with sync_playwright() as p:
        browser = p.chromium.launch()
        context = browser.new_context()
        page = context.new_page()

        # Navigate to the desired page
        page.goto('https://example.com')

        # Generate PDF with page numbers in the footer
        pdf = page.pdf(
            path="output.pdf",
            format="A4",
            display_header_footer=True,
            footer_template="""
                <div style="width: 100%; text-align: center; font-size: 10px;">
                    Page {{pageNumber}} of {{totalPages}}
                </div>
            """,
            margin={"top": "40px", "bottom": "40px"}
        )

        browser.close()

# Run the function to generate the PDF
generate_pdf_with_page_numbers()

I was expecting:

Page 1 of 1

But actually I get:

Page {{pageNumber}} of {{totalPages}}

Do you see any issue with this code?


Solution

  • From the Playwright docs, header_template (which has the same format as footer_template) provides a number of magic class names you can use to inject certain pieces of data into the page:

    from playwright.sync_api import sync_playwright # 1.44.0
    
    
    def generate_pdf_with_page_numbers():
        with sync_playwright() as p:
            browser = p.chromium.launch()
            context = browser.new_context()
            page = context.new_page()
            page.goto("https://example.com")
            pdf = page.pdf(
                path="output.pdf",
                format="A4",
                display_header_footer=True,
                footer_template="""
                    <div style="width: 100%; text-align: center; font-size: 10px;">
                        Page <span class="pageNumber"></span> of
                        <span class="totalPages"></span>
                        <div class="title"></div>
                        <div class="url"></div>
                        <div class="date"></div>
                    </div>
                """,
                margin={"top": "40px", "bottom": "40px"}
            )
            browser.close()
    
    
    if __name__ == "__main__":
        generate_pdf_with_page_numbers()
    

    Run the code, open output.pdf and observe the title, date, URL and pages injected into the footer.