jung-kurt/gofpdf pdf 生成操作

基于jung-kurt/gofpdf 生成pdf 文件

参考demo

  • main.go
package main
import (
    "fmt"
    "log"
    "github.com/gobuffalo/packr/v2"
    "github.com/jung-kurt/gofpdf"
    "github.com/shirou/gopsutil/v3/mem"
)
func main() {
    box := packr.New("pdf", "./font")
    pdf := gofpdf.New("P", "mm", "A4", "")
    arialBytes, err := box.Find("arial.ttf")
    if err != nil {
        log.Fatal(err)
    }
    arialItalicBytes, err := box.Find("arial_italic.ttf")
    if err != nil {
        log.Fatal(err)
    }
    arialBoldBytes, err := box.Find("arial_bold.ttf")
    if err != nil {
        log.Fatal(err)
    }
    notoSansBytes, err := box.Find("NotoSansSC-Regular.ttf")
    if err != nil {
        log.Fatal(err)
    }
    pdf.AddUTF8FontFromBytes("ArialTrue", "", arialBytes)
    pdf.AddUTF8FontFromBytes("ArialTrue", "I", arialItalicBytes)
    pdf.AddUTF8FontFromBytes("ArialTrue", "B", arialBoldBytes)
    pdf.AddUTF8FontFromBytes("NotoSansSC-Regular", "", notoSansBytes)
    pdf.SetFont("NotoSansSC-Regular", "", 16)
    pdf.AddPage()
    v, _ := mem.VirtualMemory()
    htmlStr := fmt.Sprintf("内存信息: Total: %v, Free:%v, UsedPercent:%f%%
", v.Total, v.Free, v.UsedPercent)
    _, lineHt := pdf.GetFontSize()
    html := pdf.HTMLBasicNew()
    html.Write(lineHt, htmlStr)
    err = pdf.OutputFileAndClose("mem-report.pdf")
    if err != nil {
        log.Fatalln("some wrong: ", err.Error())
    }
}
  • 代码说明
    通过packr进行字体文件的嵌入,同时集成了gopsutil 过去系统内存,然后输出pdf文件
  • 效果

说明

网上的一些说法gopdf不支持中文是不对的,是支持的,但是比较推荐使用signintech/gopdf,毕竟还在维护,支持的特性也不错

参考资料

https://github.com/jung-kurt/gofpdf
https://github.com/gobuffalo/packr
https://github.com/adobe-fonts/source-han-sans
https://github.com/shirou/gopsutil
https://github.com/jung-kurt/gofpdf/issues/120
https://github.com/signintech/gopdf
https://github.com/rongfengliang/gopdf-learning

原文地址:https://www.cnblogs.com/rongfengliang/p/14073346.html