htmlgoogle-chromegoprintingchromedp

What is a valid html for WithFooterTemplate method of PrintToPDF function in chromedp?


We have tried to add page numbers to our printed html page. But we didn't succeed. Right now the code looks like this.

chromedp.ActionFunc(func(ctx context.Context) error {
            var err error
            buf, _, err = page.PrintToPDF().
                WithFooterTemplate("<span class=pageNumber></span>").
                WithDisplayHeaderFooter(true).
                Do(ctx)
            return err
        }),

Here is the source code of that method. Found it here https://github.com/chromedp/cdproto/blob/master/page/page.go#L812

// WithHeaderTemplate HTML template for the print header. Should be valid
// HTML markup with following classes used to inject printing values into them:
// - date: formatted print date - title: document title - url: document location
// - pageNumber: current page number - totalPages: total pages in the document
// For example, <span class=title></span> would generate span containing the
// title.
func (p PrintToPDFParams) WithHeaderTemplate(headerTemplate string) *PrintToPDFParams {
    p.HeaderTemplate = headerTemplate
    return &p
}

For some reason we couldn't find any valid html to inject here. With that code the result looks this: there is a header, because I didn't provide a template for that, but the footer is empty even though I have provided a template to render page numbers


Solution

  • Found a solution:

    buf, _, err = page.PrintToPDF().
                    WithDisplayHeaderFooter(true).
                    WithHeaderTemplate(`<span></span>`).
                    WithFooterTemplate(`<span style="font-size: 10px"><span class="pageNumber"></span>/<span class="totalPages"></span></span>`).
                    Do(ctx)
    

    I don't understand why, but it works.