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%%\n", 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM