在 Go (Golang) 中生成 PDF 报告:完整指南
创建 PDF 文档是 Web 开发中的常见任务,尤其是在构建企业系统、金融应用或教育平台时。Go 语言 (Golang) 提供了多个强大的 PDF 生成库,能够创建从简单文本报告到包含表格、图表和图像的复杂多页文档。在本文中,我们将探讨三种流行的方法:gofpdf、maroto 以及与 wkhtmltopdf 的集成。
1. gofpdf 库——低层级 PDF 控制
gofpdf 是 Go 语言中最古老且最灵活的 PDF 生成库之一。它提供对页面每个元素的完全控制,但对于复杂布局需要编写更多代码。
安装
go get github.com/jung-kurt/gofpdf示例:带标题和表格的简单报告
package main
import ( "github.com/jung-kurt/gofpdf")
func main() { pdf := gofpdf.New("P", "mm", "A4", "") pdf.AddPage() pdf.SetFont("Arial", "B", 16) pdf.Cell(40, 10, "销售报告") pdf.Ln(12)
// 表格标题 pdf.SetFont("Arial", "B", 12) headers := []string{"商品", "数量", "价格"} for _, h := range headers { pdf.CellFormat(40, 10, h, "1", 0, "C", false, 0, "") } pdf.Ln(-1)
// 数据 pdf.SetFont("Arial", "", 12) data := [][]string{{"笔记本电脑", "5", "45000"}, {"鼠标", "12", "1500"}} for _, row := range data { for _, cell := range row { pdf.CellFormat(40, 10, cell, "1", 0, "C", false, 0, "") } pdf.Ln(-1) }
err := pdf.OutputFileAndClose("report.pdf") if err != nil { panic(err) }}优点:依赖最少,完全控制,支持 Unicode(TrueType 字体)。
缺点:缺少现成组件(表格、图表),需要手动计算位置。
2. maroto 库——基于网格的高层级生成
maroto 构建于 gofpdf 之上,提供基于网格的组件化方法,简化了复杂布局的创建。非常适合标准报告:发票、送货单、价目表。
安装
go get github.com/johnfercher/maroto/v2示例:带徽标和表格的报告
package main
import ( "github.com/johnfercher/maroto/v2/pkg/core" "github.com/johnfercher/maroto/v2/pkg/props" "github.com/johnfercher/maroto/v2")
func main() { m := maroto.NewMaroto(maroto.WithMaxGridSize(12)) m.RegisterHeader(func() { m.Row(20, func() { m.Col(3, func() { m.FileImage("logo.png", props.Rect{ Percent: 80, Center: true, }) }) m.Col(9, func() { m.Text("TechnoService 有限责任公司", props.Text{ Style: props.Bold, Size: 16, }) }) }) })
m.Row(10, func() { m.Col(12, func() { m.Table([]string{"名称", "数量", "金额"}, [][]string{ {"24\\" 显示器", "2", "40000"}, {"键盘", "5", "7500"}, }, props.Table{ Content: props.TableContent{ GridSizes: []uint{6, 3, 3}, }, }) }) })
document, _ := m.Generate() _ = document.Save("invoice.pdf")}优点:快速开发,自动对齐,内置表格、二维码和条形码支持。
缺点:更