github.com/benoitkugler/goacve@v0.0.0-20201217100549-151ce6e55dc8/server/recufiscal/etiquettes.go (about) 1 package recufiscal 2 3 import ( 4 "bytes" 5 "fmt" 6 "math" 7 8 rd "github.com/benoitkugler/goACVE/server/core/rawdata" 9 "github.com/jung-kurt/gofpdf" 10 ) 11 12 const ( 13 nbLignes = 8 14 nbColonnes = 3 15 padding = 1 // en mm 16 nbLignesParCase = 8 17 fontSize = 8 18 ) 19 20 func heightNeeded(pdf *gofpdf.Fpdf, w, lh float64, text string) float64 { 21 a, b := pdf.GetAlpha() 22 pdf.SetAlpha(0, "") 23 y := pdf.GetY() 24 pdf.MultiCell(w, lh, text, "", "L", false) 25 height := pdf.GetY() - y 26 pdf.SetAlpha(a, b) 27 return height 28 } 29 30 // GenereEtiquettes renvoie un pdf. 31 func GenereEtiquettes(personnes []rd.BasePersonne) ([]byte, error) { 32 pdf := gofpdf.New("P", "mm", "A4", "") 33 pdf.SetFont("Arial", "", fontSize) 34 pdf.SetAutoPageBreak(false, 0) 35 pdf.AddPage() 36 xMargin, yMargin := 2., 4.5 37 pdf.SetMargins(xMargin, yMargin, -1) 38 w, h := pdf.GetPageSize() 39 areaWidth, areaHeight := w-2*xMargin, h-2*yMargin 40 etiquetteWidth, etiquetteHeight := areaWidth/nbColonnes, areaHeight/nbLignes 41 lh := (etiquetteHeight - 2) / nbLignesParCase 42 tr := pdf.UnicodeTranslatorFromDescriptor("") 43 pdf.SetXY(xMargin, yMargin) 44 contentWidth := etiquetteWidth - 2*padding 45 for i, pers := range personnes { 46 if i != 0 && i%(nbColonnes*nbLignes) == 0 { // nouvelle page 47 pdf.AddPage() 48 } else if i != 0 && i%nbColonnes == 0 { // nouvelle ligne 49 pdf.SetY(pdf.GetY() + etiquetteHeight) 50 } 51 text := fmt.Sprintf("%s \n%s \n%s %s", pers.NomPrenom(), 52 pers.Adresse.TrimSpace(), pers.CodePostal.TrimSpace(), pers.Ville.TrimSpace().ToUpper()) 53 x, y := pdf.GetXY() 54 h := heightNeeded(pdf, contentWidth, lh, text) 55 paddingTop := math.Max((etiquetteHeight-h)/2, padding) 56 pdf.SetXY(x+padding, y+paddingTop) 57 pdf.ClipRect(x, y, etiquetteWidth, etiquetteHeight, true) 58 pdf.MultiCell(contentWidth, lh, tr(text), "", "L", false) 59 pdf.ClipEnd() 60 pdf.SetXY(x+etiquetteWidth, y) 61 } 62 var out bytes.Buffer 63 if err := pdf.Output(&out); err != nil { 64 return nil, err 65 } 66 return out.Bytes(), nil 67 }