Golang图片与PDF处理包:添加文本并保存为PDF

Golang图片与PDF处理包:添加文本并保存为PDF 基本上,我想为我的小生意编写一个简单的发票程序。我计划使用某种格式(图片/PDF/?)的空发票(已设计好),将其加载进来,填写所需的日期、金额等信息,然后将其另存为PDF(使用新的文件名)。有人能推荐一个可以实现这个功能的包吗?唯一“锁定”的是输出格式(PDF)……

最好能使用免费和开源的软件……

4 回复

使用 LaTeX。

更多关于Golang图片与PDF处理包:添加文本并保存为PDF的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


你能详细说明一下吗?我很久以前听说过LaTeX,但现在几乎记不起任何关于它的信息了……你具体指的是哪个包?

以下是我决定采用的前进方案,供将来参考,也希望能帮助到其他人:

步骤 1:我将从加载一张空白发票的图片开始,向其添加一些文本,并使用如下代码以新的文件名保存图片:

package main

import (
"github.com/gotk3/gotk3/cairo"
"github.com/gotk3/gotk3/gdk"
"github.com/gotk3/gotk3/gtk"
)

func main () {
// Load the image
image, err :=gdk.PixbufNewFromFile("/home/per/temp/test.png")
if err!=nil {
	panic(err)
}

// Get the image format
var format cairo.Format
if image.GetHasAlpha () {
	format = cairo.FORMAT_ARGB32
} else {
	format = cairo.FORMAT_RGB24
}

// Create a surface to draw on
width := image.GetWidth ()
height := image.GetHeight()
surface := cairo.CreateImageSurface (format, width, height)
if surface==nil {
	panic("surface is nil")
}
cr := cairo.Create(surface)

// Load the image into the surface
gtk.GdkCairoSetSourcePixBuf(cr,image,0,0)
cr.Paint()

// Write text
cr.SetSourceRGB(0,0,0)
cr.SetFontSize(20)
cr.SelectFontFace("tahoma",cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
cr.MoveTo(100.5,100)
cr.ShowText("test")

// Save the image
surface.WriteToPNG("/home/per/temp/test2.png")

// Clean up
surface = nil
cr = nil
}

步骤 2:我将获取步骤1中创建的图片,并使用 gofpdf 包将其放入一个新的 PDF 文件中:

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, "Hello world!!!")
pdf.Image("invoice.png",0,50,100,100,false,"",0,"")
err := pdf.OutputFileAndClose("hello.pdf")
if err!=nil {
	panic(err)
}
}

这对我来说已经足够好,并且看起来是可行的。

对于在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编码,可以精确控制文本位置。对于发票生成场景,建议先使用设计工具创建好模板图片,然后通过坐标定位添加动态文本内容。

回到顶部