使用Go语言将数据传递给wkhtmltopdf的页脚

huangapple go评论91阅读模式
英文:

Pass data to footer with wkhtmltopdf in Go lang

问题

我正在使用go-wkhtmltopdf包来使用Go语言生成PDF。我正在使用下面的代码在PDF的每一页上显示页脚。我想要将一些动态数据传递给页脚以进行显示,但我找不到任何方法来实现。请帮忙。

import (
	"bytes"
	"encoding/base64"
	"fmt"
	htmlTemplate "html/template"
	"path"
	"strings"
	textTemplate "text/template"
	wkhtml "github.com/SebastiaanKlippert/go-wkhtmltopdf"
)

pdfg, err := wkhtml.NewPDFGenerator()
if err != nil {
	return nil, err
}
page := wkhtml.NewPageReader(strings.NewReader(util.FilterSmartQuotesEtc(html)))
page.FooterHTML.Set("templates/footer.html")
pdfg.AddPage(page)
err = pdfg.Create()

templates/footer.html是我想要传递数据的页脚文件。非常感谢任何帮助。

英文:

I am using go-wkhtmltopdf package to generate PDF with go lang. I am using below code to display a footer on every page in the PDF. I want to pass some dynamic data to the footer to display the same. I am not finding any way to do so. Please help

"bytes"
"encoding/base64"
"fmt"
htmlTemplate "html/template"
"path"
"strings"
textTemplate "text/template"
wkhtml "github.com/SebastiaanKlippert/go-wkhtmltopdf"

pdfg, err := wkhtml.NewPDFGenerator()
if err != nil {
	return nil, err
}
page := wkhtml.NewPageReader(strings.NewReader(util.FilterSmartQuotesEtc(html)))
page.FooterHTML.Set("templates/footer.html")
pdfg.AddPage(page)
err = pdfg.Create()

templates/footer.html is the footer file where I want to pass the data. Any help is really appreciated.

答案1

得分: 2

在HTML代码中,“动态数据”建议使用HTML模板(用于生成HTML输出的数据驱动模板,可防止代码注入)。

您可以使用模板ParseFiles()从页脚中获取所述模板,并注入您的动态数据(例如,参见“Golang HTML模板ParseFilesExecute”作为示例)。

> 我有一个要在页脚中打印的动态ID,我应该能够将其传递给页脚以显示它。

假设您有一个用于保存动态数据的结构体,例如:

type FooterData struct {
    ID string
}

并且假设您有一个(非常)简单的模板用于您的templates/footer.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <style>
        /* 您的页脚样式 */
    </style>
</head>
<body>
    <div>
        ID: {{.ID}}
    </div>
</body>
</html>

您可以创建一个函数将渲染后的HTML保存到临时文件并返回文件路径(用作page.FooterHTML.Set(footerHTML)的URL):

import (
    "io/ioutil"
    //...
)

func renderFooterHTML(templatePath string, data *FooterData) (string, error) {
    tmpl, err := htmlTemplate.ParseFiles(templatePath)
    if err != nil {
        return "", err
    }

    var buf bytes.Buffer
    err = tmpl.Execute(&buf, data)
    if err != nil {
        return "", err
    }

    // 将渲染后的HTML保存到临时文件
    tmpFile, err := ioutil.TempFile("", "footer-*.html")
    if err != nil {
        return "", err
    }

    if _, err := tmpFile.Write(buf.Bytes()); err != nil {
        return "", err
    }
    if err := tmpFile.Close(); err != nil {
        return "", err
    }

    return tmpFile.Name(), nil
}

然后修改您现有的代码以使用渲染后的页脚HTML:

import (
    "bytes"
    "encoding/base64"
    "fmt"
    htmlTemplate "html/template"
    "path"
    "strings"
    textTemplate "text/template"
    wkhtml "github.com/SebastiaanKlippert/go-wkhtmltopdf"
)

// ...

pdfg, err := wkhtml.NewPDFGenerator()
if err != nil {
    return nil, err
}

page := wkhtml.NewPageReader(strings.NewReader(util.FilterSmartQuotesEtc(html)))

// 使用您的动态数据渲染页脚HTML
footerData := &FooterData{
    ID: "您的动态ID",
}
footerFilePath, err := renderFooterHTML("templates/footer.html", footerData)
if err != nil {
    return nil, err
}

// 使用渲染后的页脚HTML文件
page.FooterHTML.Set(footerFilePath)

pdfg.AddPage(page)
err = pdfg.Create()

//...

// 完成后删除临时页脚文件
os.Remove(footerFilePath)

请将ID: "您的动态ID"中的字符串替换为实际的动态ID值。

英文:

"Dynamic data" in HTML code suggests using HTLM templates (data-driven templates for generating HTML output safe against code injection)

You can use the template ParseFiles() to get said template from your footer, and inject your dynamic data. (See for instance "Golang HTML Template ParseFiles and Execute" as an example)

> I have an ID to be printed in the footer which is dynamic and I should be able to pass it to the footer to display it.

Assuming you have a struct to hold your dynamic data, for instance:

type FooterData struct {
    ID string
}

And assuming a (very) simple template for your templates/footer.html:

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset=&quot;utf-8&quot;&gt;
    &lt;style&gt;
        /* Your footer styles */
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div&gt;
        ID: {{.ID}}
    &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;

You can create a function to save the rendered HTML to a temporary file and return the file path (to be used as URL for page.FooterHTML.Set(footerHTML)):

import (
    &quot;io/ioutil&quot;
    //...
)

func renderFooterHTML(templatePath string, data *FooterData) (string, error) {
    tmpl, err := htmlTemplate.ParseFiles(templatePath)
    if err != nil {
        return &quot;&quot;, err
    }

    var buf bytes.Buffer
    err = tmpl.Execute(&amp;buf, data)
    if err != nil {
        return &quot;&quot;, err
    }

    // Save the rendered HTML to a temporary file
    tmpFile, err := ioutil.TempFile(&quot;&quot;, &quot;footer-*.html&quot;)
    if err != nil {
        return &quot;&quot;, err
    }

    if _, err := tmpFile.Write(buf.Bytes()); err != nil {
        return &quot;&quot;, err
    }
    if err := tmpFile.Close(); err != nil {
        return &quot;&quot;, err
    }

    return tmpFile.Name(), nil
}

And then modify your existing code to use the rendered footer HTML:

import (
    &quot;bytes&quot;
    &quot;encoding/base64&quot;
    &quot;fmt&quot;
    htmlTemplate &quot;html/template&quot;
    &quot;path&quot;
    &quot;strings&quot;
    textTemplate &quot;text/template&quot;
    wkhtml &quot;github.com/SebastiaanKlippert/go-wkhtmltopdf&quot;
)

// ...

pdfg, err := wkhtml.NewPDFGenerator()
if err != nil {
    return nil, err
}

page := wkhtml.NewPageReader(strings.NewReader(util.FilterSmartQuotesEtc(html)))

// Render the footer HTML with your dynamic data
footerData := &amp;FooterData{
    ID: &quot;Your dynamic ID here&quot;,
}
footerFilePath, err := renderFooterHTML(&quot;templates/footer.html&quot;, footerData)
if err != nil {
    return nil, err
}

// Use the rendered footer HTML file
page.FooterHTML.Set(footerFilePath)

pdfg.AddPage(page)
err = pdfg.Create()

//...

// Delete the temporary footer file when you&#39;re done with it
os.Remove(footerFilePath)

Do replace the string in ID: &quot;Your dynamic ID here&quot; with your actual dynamic ID value.

huangapple
  • 本文由 发表于 2023年5月5日 18:00:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76180998.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定