对于在Go中处理图片和PDF并添加文本,推荐使用github.com/jung-kurt/gofpdf包。这是一个纯Go实现的PDF生成库,支持加载图片作为模板并添加文本内容。
以下是一个示例,展示如何加载图片作为发票模板,添加文本信息,并保存为PDF:
package main
import (
"github.com/jung-kurt/gofpdf"
"log"
)
func main() {
// 创建PDF实例,使用毫米作为单位,A4纸张
pdf := gofpdf.New("P", "mm", "A4", "")
// 添加一页
pdf.AddPage()
// 加载图片作为背景模板(支持JPEG、PNG格式)
pdf.ImageOptions("invoice_template.jpg", 0, 0, 210, 297, false, gofpdf.ImageOptions{ImageType: "JPG"}, 0, "")
// 设置字体
pdf.SetFont("Arial", "", 12)
// 添加发票信息(坐标单位:毫米)
pdf.SetXY(30, 50) // 设置位置
pdf.Cell(40, 10, "发票号码: INV-2023-001")
pdf.SetXY(30, 65)
pdf.Cell(40, 10, "日期: 2023-10-27")
pdf.SetXY(30, 80)
pdf.Cell(40, 10, "金额: $1,250.00")
pdf.SetXY(30, 95)
pdf.Cell(40, 10, "客户: ABC公司")
// 保存PDF文件
err := pdf.OutputFileAndClose("invoice_2023-001.pdf")
if err != nil {
log.Fatal(err)
}
}
如果需要更复杂的布局和文本定位,可以使用gofpdf的表格功能:
func createInvoiceWithTable() {
pdf := gofpdf.New("P", "mm", "A4", "")
pdf.AddPage()
// 加载模板图片
pdf.ImageOptions("template.jpg", 0, 0, 210, 297, false, gofpdf.ImageOptions{}, 0, "")
// 设置字体
pdf.SetFont("Arial", "B", 16)
// 添加标题
pdf.SetXY(0, 20)
pdf.CellFormat(210, 10, "商业发票", "", 0, "C", false, 0, "")
// 设置表格数据
pdf.SetFont("Arial", "", 12)
pdf.SetXY(20, 60)
// 创建简单表格
headers := []string{"项目", "数量", "单价", "总价"}
data := [][]string{
{"产品A", "2", "$50.00", "$100.00"},
{"产品B", "1", "$150.00", "$150.00"},
{"服务费", "1", "$100.00", "$100.00"},
}
// 绘制表格
colWidths := []float64{80, 30, 40, 40}
// 表头
for i, header := range headers {
pdf.CellFormat(colWidths[i], 10, header, "1", 0, "C", false, 0, "")
}
pdf.Ln(-1)
// 表格内容
for _, row := range data {
for i, cell := range row {
pdf.CellFormat(colWidths[i], 10, cell, "1", 0, "C", false, 0, "")
}
pdf.Ln(-1)
}
// 总计
pdf.SetXY(130, 150)
pdf.CellFormat(40, 10, "总计:", "0", 0, "R", false, 0, "")
pdf.CellFormat(40, 10, "$350.00", "1", 0, "C", false, 0, "")
pdf.OutputFileAndClose("invoice_with_table.pdf")
}
如果需要处理更复杂的PDF模板,可以结合github.com/signintech/gopdf包:
import (
"github.com/signintech/gopdf"
"image/jpeg"
"os"
)
func useGoPdf() {
pdf := gopdf.GoPdf{}
pdf.Start(gopdf.Config{PageSize: *gopdf.PageSizeA4})
// 添加页面
pdf.AddPage()
// 加载图片作为背景
file, err := os.Open("template.jpg")
if err != nil {
panic(err)
}
img, err := jpeg.Decode(file)
if err != nil {
panic(err)
}
// 添加图片到PDF
pdf.ImageFrom(img, 0, 0, gopdf.PageSizeA4)
// 设置字体
pdf.AddTTFFont("arial", "arial.ttf")
pdf.SetFont("arial", "", 14)
// 添加文本
pdf.SetXY(30, 50)
pdf.Text("发票信息")
pdf.OutputAndClose("output.pdf")
}
安装命令:
go get github.com/jung-kurt/gofpdf
go get github.com/signintech/gopdf
gofpdf的优势在于纯Go实现、无外部依赖,支持UTF-8编码,可以精确控制文本位置。对于发票生成场景,建议先使用设计工具创建好模板图片,然后通过坐标定位添加动态文本内容。