从剧作家文档中,
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和页面。