question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[BUG] Header and Footer Templates don't work when generating a PDF

See original GitHub issue

Context:

  • Playwright Version: 1.22.0
  • Operating System: Windows 11
  • .NET version: .NET 6
  • Browser: Chromium

Code Snippet

using System.Threading.Tasks;
using Microsoft.Playwright;

class Program
{
    public static async Task Main()
    {
          using var playwright = await Playwright.CreateAsync();
          await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions()
           {
               Headless = true
           });
           
           string url = "https://en.wikipedia.org/wiki/Microsoft";
           var page = await browser.NewPageAsync();
           await page.GotoAsync(url, new PageGotoOptions()
           {
                WaitUntil = WaitUntilState.NetworkIdle
           });

           var pdfOptions = new PagePdfOptions()
           {
                DisplayHeaderFooter = true,
                HeaderTemplate = "<span style=\"font-size: 20px;color:#000000;\">HEADER</span>",
                FooterTemplate = "<span style=\"font-size: 20px;color:#000000;\">FOOTER</span>",
                PrintBackground = true,
                Path = "file.pdf"
           };
          await page.PdfAsync(pdfOptions);
    }
}

Describe the bug

The header and footer are not visible in the generated document. I’ve tried including HTML tags in the template, and all kinds of style teqniques, but I have never been able to get the header and footer to display for any webpage.

Issue Analytics

  • State:open
  • Created a year ago
  • Reactions:1
  • Comments:7

github_iconTop GitHub Comments

2reactions
leducvincommented, Sep 27, 2022

If it can help anyone, here are my findings about the header and footer template. Some of it is apparently undocumented.

I used the following documentation: https://playwright.dev/python/docs/api/class-page#page-pdf

  • You do need some margins defined. Either define these using the margin argument, or set prefer_css_page_size=True with margins defined in the @page CSS rule (I did the latter).
  • Header and footer are displayed initially with 0px font size. If you zoom in on your PDF you might be able to see them. You have to use CSS or element style to set a bigger font size.
  • The header and footer templates have to be completely self-contained. That means you can’t link to external CSS file or external images. For instance, you can include all the necessary CSS inside <head><style></style></head>. SVG images can be used by directly including the SVG code. Images can be used by using base64 encoding.
  • The header and footer are impervious to any CSS used in the rest of the document.
  • The CSS style applied to footer “bleeds” into the header. If you set all your rules in the footer template only, they will be applied in the header template too.
  • The header and footer do not respect the margins set using the margin argument or the margins set using CSS @page. You have to set the margins in the CSS included in the templates itself. I found that to center the header/footer properly, you can specify for example margin-left: 0.5in; and width: calc(100% - 1in);, which should work when your document’s body already has 0.5 inch margins left and right.

So, I would say, header and footer do work when generating PDF, but the documentation misses out on a lot of stuff and they are not easy to get to work properly.

Here is how I went about the problem. I used the python API. Also, I used the Jinja project to template the header and footer templates.

For example, something along the lines of:

header_template.html

<!DOCTYPE html>
<html lang="fr-CA">
  <head>
    <meta charset="utf-8">
    <!-- Note: CSS is applied from the footer.html template. -->
  </head>
  <body>
    <div class="htmlheader-wrapper">
        <div class="htmlheader-left">
            {{ logo_svg|string|safe }}
        </div>
        <div class="htmlheader-right">
            <hgroup id="reportheader">
                <h2 class="report-title" {{ report.name }}</h2>
                {% if report.subtitle %}
                <p>{{ report.subtitle }}</p>
                {% endif %}
            </hgroup>
        </div>
    </div>
  </body>
</html>

footer_template.html

<!DOCTYPE html>
<html lang="fr-CA">
  <head>
    <meta charset="utf-8">
    <style>
        {{ css|safe }}
    </style>
  </head>
  <body>
    <div class="htmlfooter-wrapper">
        <div class="htmlfooter-left">
            {% if report.footerleft %}
            <span>
                {{ report.footerleft }}
            </span>
            {% endif %}
        </div>
        <div class="htmlfooter-center">
            {% if report.footercenter %}
            <span>
                {{ report.footercenter }}
            </span>
            {% endif %}
        </div>
        <div class="htmlfooter-right">
            <span class="pageNumber"></span>
        </div>
    </div>
  </body>
</html>

and the CSS – defines footer left, center or right elements:

@page {   
    margin: 1.5in 0.5in 1.0in 0.5in;
    padding: 0;   
    size: letter landscape;
}

.htmlfooter-wrapper {
  display: grid;
  width: calc(100% - 1in);
  margin-left: 0.5in;
  margin-bottom: 0.25in;
  grid-template-columns: repeat(3, 1fr);
  gap: 0.25in;
  }

  .htmlfooter-left {
  grid-row-start: 1;
  grid-row-end: 2;
  grid-column-start: 1;
  grid-column-end: 2;
  text-align: left;
  }

  .htmlfooter-center {
  grid-row-start: 1;
  grid-row-end: 2;
  grid-column-start: 2;
  grid-column-end: 3;
  text-align: center;
  }

  .htmlfooter-right {
  grid-row-start: 1;
  grid-row-end: 2;
  grid-column-start: 3;
  grid-column-end: 4;
  text-align: right;
  }

  .htmlheader-wrapper {
    display: grid;
    width: calc(100% - 1in);
    margin-left: 0.5in;
    margin-top: 0.25in;
    grid-template-columns: 1fr 4fr;
    gap: 0.125in;
    }
  
    .htmlheader-left {
    grid-row-start: 1;
    grid-row-end: 2;
    grid-column-start: 1;
    grid-column-end: 2;
    text-align: left;
    vertical-align: top;
    overflow: visible;
    }
  
    .htmlheader-right {
    grid-row-start: 1;
    grid-row-end: 2;
    grid-column-start: 2;
    grid-column-end: 6;
    text-align: right;
    }

PDF creation:

with sync_playwright() as playwright:
    browser = playwright.chromium.launch(headless=True)
    context = browser.new_context()
    page = context.new_page()
    page.goto("file:///path/to/file", wait_until="networkidle")
    pdf_bytes = page.pdf(
        display_header_footer=True,
        landscape=True,
        print_background=True,
        prefer_css_page_size=True,
        header_template=header_template.render(
            report=report,
            logo_svg=svg_as_string,
        ),
        footer_template=footer_template.render(report=report, css=css_as_string),
    )
0reactions
leducvincommented, Sep 27, 2022

@DaveNatalieTripArc Unfortunately, I don’t know the answer to that question, but I suspect it’s not possible in the current state. It seems like it’s either with or without for all pages.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Issue about header and footer - Google Cloud Community
Everything works fine, but I have a problem with header and footer. ... I may advise not using header and footer with PDF...
Read more >
Puppeteer Header and Footer not displayed on first page
According to the Puppeteer Documentation: page.pdf(options). options <Object> Options object which might have the following properties:.
Read more >
Headers disappear in PDF - Microsoft Community
Here, headers and footers are retained when converting a Word document to PDF via File | Save As, as long as headers and...
Read more >
Fix Word documents missing header and footer areas - YouTube
Has Word stopped displaying the white space between the end of one page and the start of the next? In this video, I...
Read more >
Creating Header and Footer Templates for Word in ... - YouTube
If you need to reuse your headers and footers from one document on others, save them to your Building Blocks Organizer!
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found