-
-
Notifications
You must be signed in to change notification settings - Fork 172
/
code.go
103 lines (83 loc) · 2.45 KB
/
code.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package code
import (
"bytes"
"image"
"image/jpeg"
"github.com/boombuler/barcode/code128"
"github.com/boombuler/barcode/ean"
"github.com/johnfercher/maroto/v2/pkg/consts/barcode"
libBarcode "github.com/boombuler/barcode"
"github.com/boombuler/barcode/datamatrix"
"github.com/boombuler/barcode/qr"
"github.com/johnfercher/maroto/v2/pkg/consts/extension"
"github.com/johnfercher/maroto/v2/pkg/core/entity"
"github.com/johnfercher/maroto/v2/pkg/props"
)
// codeInstance is the singleton of code, opted to use a singleton to ensure that
// this will not be instantiated more than once since there is no need to do this
// because code is stateless.
var codeInstance *code = nil
type code struct{}
// New create a Code (Singleton).
func New() *code {
if codeInstance == nil {
codeInstance = &code{}
}
return codeInstance
}
// GenDataMatrix is responsible to generate a data matrix byte array.
func (c *code) GenDataMatrix(code string) (*entity.Image, error) {
dataMatrix, err := datamatrix.Encode(code)
if err != nil {
return nil, err
}
return c.getImage(dataMatrix)
}
// GenQr is responsible to generate a qr code byte array.
func (c *code) GenQr(code string) (*entity.Image, error) {
qrCode, err := qr.Encode(code, qr.M, qr.Auto)
if err != nil {
return nil, err
}
return c.getImage(qrCode)
}
// GenBar is responsible to generate a barcode byte array.
func (c *code) GenBar(code string, _ *entity.Cell, prop *props.Barcode) (*entity.Image, error) {
barcodeGen := getBarcodeClosure(prop.Type)
barCode, err := barcodeGen(code)
if err != nil {
return nil, err
}
width := float64(barCode.Bounds().Dx())
heightPercentFromWidth := prop.Proportion.Height / prop.Proportion.Width
height := int(width * heightPercentFromWidth)
scaledBarCode, err := libBarcode.Scale(barCode, int(width), height)
if err != nil {
return nil, err
}
return c.getImage(scaledBarCode)
}
func getBarcodeClosure(barcodeType barcode.Type) func(code string) (libBarcode.BarcodeIntCS, error) {
switch barcodeType {
case barcode.EAN:
return ean.Encode
default:
return code128.Encode
}
}
func (c *code) getImage(img image.Image) (*entity.Image, error) {
var buf bytes.Buffer
err := jpeg.Encode(&buf, img, nil)
if err != nil {
return nil, err
}
imgEntity := &entity.Image{
Bytes: buf.Bytes(),
Extension: extension.Jpg,
Dimensions: &entity.Dimensions{
Width: float64(img.Bounds().Dx()),
Height: float64(img.Bounds().Dy()),
},
}
return imgEntity, nil
}