代码之家  ›  专栏  ›  技术社区  ›  MaduKan

剧作家-页脚模板解析问题

  •  1
  • MaduKan  · 技术社区  · 1 年前

    Playwright(Python)将页面另存为PDF功能在页眉或页脚中没有自定义时工作良好。然而,当我尝试引入自定义页脚时,这些值似乎没有得到适当的注入。

    示例代码:

    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()
    
    

    我原本预计:

    Page 1 of 1
    

    但实际上我得到:

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

    你看到这段代码有什么问题吗?

    1 回复  |  直到 1 年前
        1
  •  1
  •   ggorlen Hoàng Huy Khánh    1 年前

    从剧作家文档中, header_template (其格式与 footer_template )提供了许多神奇的类名,您可以使用它们将某些数据注入页面:

    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()
    

    运行代码,打开output.pdf,观察注入页脚的标题、日期、URL和页面。

    推荐文章