Golang PDF生成处理
在Golang中生成PDF文档有什么推荐的库或工具吗?目前项目需要实现动态生成包含表格和图片的PDF报告,希望找一个性能较好、维护活跃的开源方案。尝试过几个库但遇到中文支持不佳或格式控制不够灵活的问题,大家有什么实际项目中使用过的成熟方案可以推荐?最好能分享一下集成经验和性能表现。
2 回复
推荐使用go-wkhtmltopdf或unidoc等库。go-wkhtmltopdf基于wkhtmltopdf,适合HTML转PDF;unidoc功能更全面,支持PDF创建、编辑和水印等。根据需求选择,注意性能与授权。
更多关于Golang PDF生成处理的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在Golang中生成和处理PDF,推荐使用以下库:
1. gofpdf
最流行的PDF生成库,功能全面:
package main
import (
"github.com/jung-kurt/gofpdf"
"log"
)
func main() {
pdf := gofpdf.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Arial", "B", 16)
pdf.Cell(40, 10, "Hello, PDF!")
err := pdf.OutputFileAndClose("hello.pdf")
if err != nil {
log.Fatal(err)
}
}
2. unidoc/unipdf
功能强大的商业级库:
package main
import (
"github.com/unidoc/unipdf/v3/creator"
"github.com/unidoc/unipdf/v3/model"
)
func main() {
c := creator.New()
// 添加段落
p := c.NewParagraph("Hello PDF")
p.SetFontSize(14)
c.Draw(p)
err := c.WriteToFile("output.pdf")
if err != nil {
panic(err)
}
}
3. 常用功能示例
添加图片
pdf.ImageOptions("image.jpg", 15, 15, 30, 0, false, gofpdf.ImageOptions{
ImageType: "JPG",
}, 0, "")
创建表格
pdf.SetFont("Arial", "", 12)
for i := 0; i < 5; i++ {
pdf.CellFormat(40, 10, fmt.Sprintf("Cell %d", i), "1", 0, "", false, 0, "")
}
设置页眉页脚
pdf.SetHeaderFunc(func() {
pdf.SetY(5)
pdf.SetFont("Arial", "I", 8)
pdf.Cell(0, 10, "Header Text")
})
4. PDF处理(读取、合并、拆分)
使用unipdf进行PDF操作:
// 合并PDF
func mergePDFs(inputPaths []string, outputPath string) error {
c := creator.New()
for _, path := range inputPaths {
reader, err := model.NewPdfReaderFromFile(path)
if err != nil {
return err
}
numPages, err := reader.GetNumPages()
if err != nil {
return err
}
for i := 1; i <= numPages; i++ {
page, err := reader.GetPage(i)
if err != nil {
return err
}
err = c.AddPage(page)
if err != nil {
return err
}
}
}
return c.WriteToFile(outputPath)
}
选择建议:
- gofpdf: 简单PDF生成,轻量级
- unipdf: 复杂需求,商业应用
- PDF处理: 推荐unipdf,功能更完整
这些库都能很好地处理中文,记得设置中文字体即可。

