golang html转pdf
时间: 2023-09-30 14:12:37 浏览: 57
你可以使用 Go 语言中的第三方库实现 HTML 转 PDF。一个常用的库是 gofpdf,它支持将 HTML 转换为 PDF。
以下是一个简单的示例:
```
package main
import (
"fmt"
"github.com/jung-kurt/gofpdf"
"github.com/jung-kurt/gofpdf/contrib/gofpdi"
"github.com/jung-kurt/gofpdf/internal/example"
"io/ioutil"
)
func main() {
pdf := gofpdf.New("P", "mm", "A4", "")
pdf.AddPage()
htmlStr := example.HTMLLorem()
htmlBytes := []byte(htmlStr)
htmlFile, err := ioutil.TempFile("", "example.html")
if err != nil {
panic(err)
}
defer htmlFile.Close()
_, err = htmlFile.Write(htmlBytes)
if err != nil {
panic(err)
}
pdfg := gofpdi.NewImporter()
tplIdx := pdfg.ImportPage(pdf, htmlFile.Name(), "/MediaBox")
pdfg.UseImportedTemplate(pdf, tplIdx, 0, 0, 210, 297)
err = pdf.OutputFileAndClose("example.pdf")
if err != nil {
panic(err)
}
fmt.Println("PDF generated successfully")
}
```
这个例子将 HTML 转换为 PDF 并将其保存到磁盘上。你可以根据需要自定义页面大小和其他参数。