1

I have this function generating files from html files and I can't seem to get a dynamic footer with page count to generate -> I need to be able to do this on the backend with Go/HTML so the javascript solutions don't work for me

Here's my code

{{define "Count"}}Invoice Footer{{end}}

{{define "invoiceFooter"}}

<foot>

    <script>

        var pdfInfo = {};
        var x = document.location.search.substring(1).split('&');
        for (var i in x) { var z = x[i].split('=',2); pdfInfo[z[0]] = unescape(z[1]); }
        function getPdfInfo() {
            var page = pdfInfo.page || 1;
            var pageCount = pdfInfo.topage || 1;
            document.getElementsByClassName('page').textContent = page;
            document.getElementsByClassName('topage').textContent = pageCount;
        }

    </script>
</foot>

<body style="border:0; margin: 0;" onload="getPdfInfo()">
<table style="border-bottom: 1px solid black; width: 100%">
    <tr>
        <td class="--footer-center"></td>
        <td style="text-align:center">
            Page <span class="page"></span> of <span class="topage"></span>
        </td>
    </tr>
</table>

{{end}}
func generatePDF(data *cs.FileData) (pdfgBytes []byte, err error) {

    var templ *template.Template

    _, err = os.Getwd()
    if err != nil {
        return nil, err
    }

    tmplFiles, err := fs.ReadDir(templateDir, "templates")
    if err != nil {
        return nil, err
    }

    files := []string{}
    for _, file := range tmplFiles {
        if file.IsDir() {
            continue
        }
        files = append(files, fmt.Sprintf("templates/%s", file.Name()))
    }

    // use Go's default HTML template generation tools to generate your HTML
    if templ = template.Must(template.ParseFS(templateDir, files...)); err != nil {
        return
    }

    // apply the parsed HTML template data and keep the result in a Buffer
    var body bytes.Buffer
    if err = templ.Execute(&body, data); err != nil {
        return
    }

    // Create new PDF generator
    pdfg, err := pdf.NewPDFGenerator()
    if err != nil {
        return
    }

    // read the HTML page as a PDF page
    page := pdf.NewPageReader(bytes.NewReader(body.Bytes()))

    // enable this if the HTML file contains local references such as images, CSS, etc.
    page.EnableLocalFileAccess.Set(true)

    //page := NewPage(`D:\body.html`)
    page.FooterHTML.Set(`--footer-html`)
    page.FooterCenter.Set("test")
    page.FooterFontSize.Set(7)
    //page.FooterRight.Set("[page]")

    // add the page to your generator
    pdfg.AddPage(page)

I've tried variations of all of these:

Medium Article Github Issue

Stack Overflow

  • @ NachoShaman were you able to get this working? I am having the same issue adding page numbers from the backend. Please help if you were able to achieve it. – girish May 03 '23 at 09:52

0 Answers0