johnfercher/maroto 以前有简单介绍过,是一个很不错的基于bootstrap 网格处理pdf的类库,但是此包对于中文处理不是很好
所以fork了一个版本,添加了中文的支持,同时升级依赖的jung-kurt/gofpdf 到v2
参考使用
- 核心代码
go.mod
module demopdf
go 1.15
require (
github.com/gobuffalo/packr/v2 v2.8.1
github.com/rongfengliang/maroto v1.1.2
github.com/stretchr/objx v0.2.0 // indirect
github.com/stretchr/testify v1.6.1 // indirect
golang.org/x/sys v0.0.0-20201024232916-9f70ab9862d5 // indirect
)
main.go
package main
import (
"fmt"
"log"
"os"
"time"
"github.com/rongfengliang/maroto/pkg/color"
"github.com/gobuffalo/packr/v2"
"github.com/rongfengliang/maroto/pkg/consts"
"github.com/rongfengliang/maroto/pkg/pdf"
"github.com/rongfengliang/maroto/pkg/props"
)
func main() {
box := packr.New("pdf", "../font")
begin := time.Now()
m := pdf.NewMarotoCustomSize(consts.Landscape, "C6", "mm", 114.0, 162.0)
m.SetPageMargins(5, 5, 5)
notoSansBytes, err := box.Find("NotoSansSC-Regular.ttf")
if err != nil {
log.Fatal(err)
}
m.AddUTF8FontFromBytes("notosanssc", "", notoSansBytes)
// m.AddUTF8FontFromBytes("notosanssc", "I", notoSansBytes)
m.AddUTF8FontFromBytes("notosanssc", "B", notoSansBytes)
// m.SetBorder(true)
headers := []string{"姓名", "年龄"}
contents := [][]string{
{"大龙", "11"},
{"rong", "233"},
}
m.TableList(headers, contents, props.TableList{
HeaderProp: props.TableListContent{
Family: consts.NotoSansSC,
GridSizes: []uint{3, 9},
},
ContentProp: props.TableListContent{
Family: consts.NotoSansSC,
GridSizes: []uint{3, 9},
},
Align: consts.Center,
AlternatedBackground: &color.Color{
Red: 100,
Green: 20,
Blue: 255,
},
HeaderContentSpace: 10.0,
Line: false,
})
m.Row(40, func() {
m.Col(4, func() {
_ = m.FileImage("biplane.jpg", props.Rect{
Center: true,
Percent: 50,
})
})
m.Col(4, func() {
m.Text("Gopher International Shipping, Inc.", props.Text{
Top: 12,
Size: 12,
Extrapolate: true,
})
})
m.ColSpace(4)
})
m.Line(10)
m.Row(30, func() {
m.Col(12, func() {
m.Text("北京市海淀区", props.Text{
Size: 10,
Align: consts.Right,
Family: consts.NotoSansSC,
})
m.Text("荣锋亮 TN 39021", props.Text{
Size: 10,
Align: consts.Right,
Family: consts.NotoSansSC,
Top: 10,
})
m.Text("United States (USA)", props.Text{
Size: 10,
Align: consts.Right,
Top: 20,
})
})
})
m.Row(30, func() {
m.Col(12, func() {
m.QrCode("https://cnblogs.com/rongfengliang")
})
})
err = m.OutputFileAndClose("customsize.pdf")
if err != nil {
fmt.Println("Could not save PDF:", err)
os.Exit(1)
}
end := time.Now()
fmt.Println(end.Sub(begin))
}
- 效果
说明
johnfercher/maroto 的设计很不错
参考资料
https://github.com/jung-kurt/gofpdf/issues/316
https://github.com/johnfercher/maroto
https://github.com/Vale-sail/maroto