-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathelements.go
2510 lines (2264 loc) · 85.1 KB
/
elements.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package reportbro
import (
"bytes"
b64 "encoding/base64"
"fmt"
"image"
_ "image/jpeg"
_ "image/png"
"log"
"mime"
"os"
"reflect"
"regexp"
"strings"
"time"
"github.com/dustin/go-humanize"
"github.com/jinzhu/now"
"github.com/jung-kurt/gofpdf"
"github.com/jung-kurt/gofpdf/contrib/barcode"
uuid "github.com/satori/go.uuid"
"github.com/spf13/cast"
"github.com/vincent-petithory/dataurl"
"github.com/vjeantet/jodaTime"
)
type DocElementBaseProvider interface {
base() *DocElementBase
init(report *report, data map[string]interface{})
renderPDF(containerOffsetX float64, containerOffsetY float64, pdfDoc *FPDFRB)
cleanup()
prepare(ctx Context, pdfDoc *FPDFRB, onlyVerify bool)
hasUncompletedPredecessor(completedElements map[int]bool) bool
getNextRenderElement(offsetY float64, containerHeight float64, ctx Context, pdfDoc *FPDFRB) (DocElementBaseProvider, bool)
isPrinted(ctx Context) bool
finishEmptyElement(offsetY float64)
setHeight(height float64)
addRows(rows []*TableRow, allowSplit bool, availableHeight float64, offsetY float64, containerHeight float64, ctx Context, pdfDoc *FPDFRB) int
}
type DocElementBase struct {
Type string
Report *report
ID int
Y float64
RenderY float64
RenderBottom float64
Bottom float64
Height float64
PrintIf string
RemoveEmptyElement bool
SpreadsheetHide bool
SpreadsheetColumn *string
SpreadsheetAddEmptyRow bool
FirstRenderElement bool
RenderingComplete bool
Predecessors []DocElementBaseProvider
Successors []DocElementBaseProvider
SortOrder float64
X float64
Width float64
RenderingBottom bool
Border Border
BorderStyle BorderStyle
BackgroundColor Color
TotalHeight float64
UsedStyle *textStyle
Complete bool
TableElement bool
BorderColor Color
ZIndex int
}
func (self *DocElementBase) base() *DocElementBase {
return self
}
func (self *DocElementBase) init(report *report, data map[string]interface{}) {
self.Report = report
self.ID = 0
self.Y = float64(GetIntValue(data, "y"))
self.RenderY = 0
self.RenderBottom = 0
self.Bottom = self.Y
self.Height = 0
self.PrintIf = ""
self.RemoveEmptyElement = false
self.SpreadsheetHide = true
self.SpreadsheetColumn = nil
self.SpreadsheetAddEmptyRow = false
self.FirstRenderElement = true
self.RenderingComplete = false
self.Predecessors = make([]DocElementBaseProvider, 0)
self.Successors = make([]DocElementBaseProvider, 0)
self.Border = BorderNone
self.SortOrder = 1 // sort order for elements with same "y"-value
self.ZIndex = 0
}
func (self *DocElementBase) isPredecessor(elem DocElementBaseProvider) bool {
// if bottom of element is above y-coord of first predecessor we do not need to store
// the predecessor here because the element is already a predecessor of the first predecessor
return (self.Y >= elem.base().Bottom && (len(self.Predecessors) == 0 || len(self.Predecessors) > 0 && elem.base().Bottom > self.Predecessors[0].base().Y))
}
func (self *DocElementBase) addPredecessor(predecessor DocElementBaseProvider) {
self.Predecessors = append(self.Predecessors, predecessor)
predecessor.base().Successors = append(predecessor.base().Successors, self.base())
}
// returns true in case there is at least one predecessor which is not completely rendered yet
func (self *DocElementBase) hasUncompletedPredecessor(completedElements map[int]bool) bool {
for _, predecessor := range self.Predecessors {
if notInElement(predecessor.base().ID, completedElements) || !predecessor.base().RenderingComplete {
return true
}
}
return false
}
func (self *DocElementBase) GetOffsetY() float64 {
maxOffsetY := 0.0
for _, predecessor := range self.Predecessors {
offsetY := predecessor.base().RenderBottom + (self.Y - predecessor.base().Bottom)
if offsetY > maxOffsetY {
maxOffsetY = offsetY
}
}
return maxOffsetY
}
func (self *DocElementBase) clearPredecessors() {
self.Predecessors = make([]DocElementBaseProvider, 0)
}
func (self *DocElementBase) prepare(ctx Context, pdfDoc *FPDFRB, onlyVerify bool) {
return
}
func (self *DocElementBase) isPrinted(ctx Context) bool {
if self.PrintIf != "" {
return cast.ToBool(ctx.evaluateExpression(self.PrintIf, self.ID, "printIf"))
}
return true
}
func (self *DocElementBase) finishEmptyElement(offsetY float64) {
if self.RemoveEmptyElement {
self.RenderBottom = offsetY
} else {
self.RenderBottom = offsetY + self.Height
}
self.RenderingComplete = true
}
func (self *DocElementBase) getNextRenderElement(offsetY float64, containerHeight float64, ctx Context, pdfDoc *FPDFRB) (DocElementBaseProvider, bool) {
self.RenderingComplete = true
return nil, true
}
func (self *DocElementBase) renderPDF(containerOffsetX float64, containerOffsetY float64, pdfDoc *FPDFRB) {
return
}
func (self *DocElementBase) renderSpreadsheet(row int, col int, ctx Context, renderer Renderer) {
return
}
func (self DocElementBase) cleanup() {
return
}
func (self *DocElementBase) setHeight(height float64) {}
func (self *DocElementBase) addRows(rows []*TableRow, allowSplit bool, availableHeight float64, offsetY float64, containerHeight float64, ctx Context, pdfDoc *FPDFRB) int {
return 0
}
func NewDocElementBase(report *report, data map[string]interface{}) *DocElementBase {
docElementBase := DocElementBase{}
docElementBase.init(report, data)
return &docElementBase
}
type DocElement struct {
DocElementBase
}
func (self *DocElement) init(report *report, data map[string]interface{}) {
self.DocElementBase.init(report, data)
self.ID = GetIntValue(data, "id")
self.ZIndex = GetIntValue(data, "zIndex")
self.X = float64(GetIntValue(data, "x"))
self.Width = float64(GetIntValue(data, "width"))
self.Height = float64(GetIntValue(data, "height"))
self.Bottom = self.Y + self.Height
}
func (self *DocElement) getNextRenderElement(offsetY float64, containerHeight float64, ctx Context, pdfDoc *FPDFRB) (DocElementBaseProvider, bool) {
if offsetY+self.Height <= containerHeight {
self.RenderY = offsetY
self.RenderBottom = offsetY + self.Height
self.RenderingComplete = true
return self, true
}
return nil, false
}
// @staticmethod
func drawBorder(x float64, y float64, width float64, height float64, renderElementType RenderElementType, borderStyle Style, pdfDoc *FPDFRB) {
pdfDoc.Fpdf.SetDrawColor(borderStyle.base().BorderStyle.BorderColor.R, borderStyle.base().BorderStyle.BorderColor.G, borderStyle.base().BorderStyle.BorderColor.B)
pdfDoc.Fpdf.SetLineWidth(borderStyle.base().BorderStyle.BorderWidth)
borderOffset := borderStyle.base().BorderStyle.BorderWidth / 2
borderX := x + borderOffset
borderY := y + borderOffset
borderWidth := width - borderStyle.base().BorderStyle.BorderWidth
borderHeight := height - borderStyle.base().BorderStyle.BorderWidth
if borderStyle.base().BorderStyle.BorderAll && renderElementType == RenderElementTypeComplete {
pdfDoc.Fpdf.Rect(borderX, borderY, borderWidth, borderHeight, "D")
} else {
if borderStyle.base().BorderStyle.BorderLeft && (renderElementType == RenderElementTypeComplete || renderElementType == RenderElementTypeFirst) {
pdfDoc.Fpdf.Line(borderX, borderY, borderX+borderWidth, borderY)
}
if borderStyle.base().BorderStyle.BorderTop && (renderElementType == RenderElementTypeComplete || renderElementType == RenderElementTypeFirst) {
pdfDoc.Fpdf.Line(borderX, borderY, borderX+borderWidth, borderY)
}
if borderStyle.base().BorderStyle.BorderRight {
pdfDoc.Fpdf.Line(borderX+borderWidth, borderY, borderX+borderWidth, borderY+borderHeight)
}
if borderStyle.base().BorderStyle.BorderBottom && (renderElementType == RenderElementTypeComplete || renderElementType == RenderElementTypeLast) {
pdfDoc.Fpdf.Line(borderX, borderY+borderHeight, borderX+borderWidth, borderY+borderHeight)
}
}
}
func NewDocElement(report *report, data map[string]interface{}) *DocElement {
docElement := DocElement{}
docElement.init(report, data)
return &docElement
}
type ImageElement struct {
DocElement
Eval bool
Source string
Content string
IsContent bool
Image string
ImageFile string
ImageFilename string
HorizontalAlignment HorizontalAlignment
VerticalAlignment VerticalAlignment
BackgroundColor Color
RemoveEmptyElement bool
Link string
SpreadsheetHide bool
SpreadsheetColumn int
SpreadsheetAddEmptyRow bool
ImageKey string
ImageType string
Image64 string
ImageFP []byte
ImageHeight float64
UsedStyle textStyle
SpaceTop float64
SpaceBottom float64
}
func (self *ImageElement) init(report *report, data map[string]interface{}) {
self.DocElement.init(report, data)
self.Eval = GetBoolValue(data, "eval")
self.Source = GetStringValue(data, "source")
self.Content = GetStringValue(data, "content")
self.IsContent = GetBoolValue(data, "isContent")
if self.Source == "" {
self.IsContent = true
}
self.Image = GetStringValue(data, "image")
self.ImageFilename = GetStringValue(data, "imageFilename")
self.HorizontalAlignment = GetHorizontalAlignment(GetStringValue(data, "horizontalAlignment"))
self.VerticalAlignment = GetVerticalAlignment(GetStringValue(data, "verticalAlignment"))
self.BackgroundColor = NewColor(GetStringValue(data, "backgroundColor"))
self.PrintIf = GetStringValue(data, "printIf")
self.RemoveEmptyElement = GetBoolValue(data, "removeEmptyElement")
self.Link = GetStringValue(data, "link")
self.SpreadsheetHide = GetBoolValue(data, "spreadsheet_hide")
self.SpreadsheetColumn = GetIntValue(data, "spreadsheet_column")
self.SpreadsheetAddEmptyRow = GetBoolValue(data, "spreadsheet_addEmptyRow")
self.ImageKey = ""
self.ImageType = ""
self.ImageFP = nil
self.TotalHeight = 0
self.ImageHeight = 0
self.UsedStyle = NewTextStyle(data, "")
}
func (self *ImageElement) setHeight(height float64) {
self.Height = height
self.SpaceTop = 0.0
self.SpaceBottom = 0.0
totalHeight := 0.0
if self.ImageHeight > 0 {
totalHeight = self.ImageHeight
}
self.TotalHeight = totalHeight
}
func (self *ImageElement) prepare(ctx Context, pdfDoc *FPDFRB, onlyVerify bool) {
if self.ImageKey != "" {
return
}
imgDataB64 := ""
isURL := false
if self.Source != "" {
parameterName := stripParameterName(self.Source)
parameter := ctx.getParameter(stripParameterName(self.Source), nil)
if parameter != nil {
sourceparameter := parameter.(map[string]interface{})[parameterName].(Parameter)
if sourceparameter.Type == ParameterTypeString {
imageKey, _ := ctx.getData(sourceparameter.Name, nil)
if imageKey != nil {
self.ImageKey = imageKey.(string)
}
isURL = true
} else if sourceparameter.Type == ParameterTypeImage {
// image is available as base64 encoded or
// file object (only possible if report data is passed directly from python code
// and not via web request)
imgData, _ := ctx.getData(sourceparameter.Name, nil)
if reflect.TypeOf(imgData) == reflect.TypeOf("") {
imgDataB64 = imgData.(string)
}
} else {
log.Println(Error{Message: "errorMsgInvalidImageSourceparameter", ObjectID: self.base().ID, Field: "source"})
}
} else {
source := pyStrip(self.Source, "")
if source[0:2] == "${" && source[len(source)-1:len(source)] == "}" {
log.Println(Error{Message: "errorMsgMissingparameter", ObjectID: self.base().ID, Field: "source"})
}
self.ImageKey = self.Source
isURL = true
}
}
if self.IsContent {
parameterName := stripParameterName(self.Content)
parameter := ctx.getParameter(parameterName, nil)
if parameter != nil {
sourceparameter := parameter.(map[string]interface{})[parameterName].(Parameter)
imgData, parameterExists := ctx.getData(sourceparameter.Name, nil)
if parameterExists {
imgDataB64 = imgData.(string)
}
}
}
if imgDataB64 == "" && !isURL && self.ImageFP == nil {
if self.ImageFilename != "" && self.Image != "" {
// static image base64 encoded within image element
imgDataB64 = self.Image
self.ImageKey = self.ImageFilename
}
}
if imgDataB64 != "" {
self.Image64 = imgDataB64
re, _ := regexp.Compile(`^data:image/(.+);base64,`)
m := re.MatchString(imgDataB64)
if !m {
log.Println(Error{Message: "errorMsgInvalidImage", ObjectID: self.base().ID, Field: "source"})
}
dataURL, _ := dataurl.DecodeString(imgDataB64)
extensions, _ := mime.ExtensionsByType(dataURL.MediaType.ContentType()) // [.jfif, .jpe, .jpeg, .jpg]
invalid := map[string]string{
".": "",
".jpe": ".jpg",
"jpeg": "jpg",
"jpe": "jpg",
"jfif": "jpg",
}
imageType := extensions[0]
for s, r := range invalid {
imageType = strings.Replace(imageType, s, r, -1)
}
self.ImageType = imageType
imgData, _ := b64.StdEncoding.DecodeString(strings.Replace(imgDataB64, "^data:image/.+;base64,", "", -1))
self.ImageFP = imgData
} else if isURL {
// if !(self.ImageKey && (self.ImageKey.startswith("http://") || strings.HasPrefix(self.imageKey, "https://"))) {
// log.Println(Error{Message: "errorMsgInvalidImageSource", ObjectID: self.base().ID, Field: "source"})
// }
// pos = self.imageKey.rfind('.')
// if pos != -1 {
// self.ImageType = self.ImageKey[pos+1:]
// } else {
// self.ImageType = ""
// }
}
if self.ImageType != "" {
if !inArray(self.ImageType, []string{"png", "jpg", "jpeg"}) {
log.Println(Error{Message: "errorMsgUnsupportedImageType", ObjectID: self.base().ID, Field: "source"})
}
if self.ImageKey == "" {
self.ImageKey = "image_" + strings.ToUpper(fmt.Sprint(uuid.NewV4())) + "." + self.ImageType
// self.ImageKey = "image_" + string(self.base().ID) + "." + self.ImageType
}
}
self.Image = ""
if self.Link != "" {
self.Link = ctx.fillParameters(self.Link, self.base().ID, "link", "")
}
}
func (self *ImageElement) renderPDF(containerOffsetX float64, containerOffsetY float64, pdfDoc *FPDFRB) {
x := self.X + containerOffsetX
y := self.RenderY + containerOffsetY
if self.BackgroundColor.Transparent == false {
pdfDoc.Fpdf.SetFillColor(self.BackgroundColor.R, self.BackgroundColor.G, self.BackgroundColor.B)
pdfDoc.Fpdf.Rect(x, y, self.Width, self.Height, "F")
}
if self.ImageKey != "" {
options := gofpdf.ImageOptions{
ReadDpi: false,
AllowNegativePosition: true,
}
dataURL, _ := dataurl.DecodeString(self.Image64)
image, _, err := image.DecodeConfig(bytes.NewReader([]byte(dataURL.Data)))
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
}
// Detect if either width or height has been made smaller than original at all
cwidth := false
imageWidth := float64(image.Width)
if float64(image.Width) >= self.Width {
aW := (float64(image.Width) / float64(image.Height)) * self.Height
if aW < self.Width {
imageWidth = aW
cwidth = true
} else {
imageWidth = self.Width
cwidth = true
}
}
// If has been made smaller on either axis, we must adjust the other axis to match the aspect ratio
cheight := false
imageHeight := float64(image.Height)
if float64(image.Height) >= self.Height {
aH := self.Width / (float64(image.Width) / float64(image.Height))
if aH < self.Height {
imageHeight = aH
cheight = true
} else {
imageHeight = self.Height
cheight = true
}
}
if cwidth {
imageHeight = imageWidth / (float64(image.Width) / float64(image.Height))
}
if cheight {
imageWidth = (float64(image.Width) / float64(image.Height)) * imageHeight
}
imageX := x
switch self.HorizontalAlignment {
case HorizontalAlignmentCenter:
imageX += ((self.Width - imageWidth) / 2)
break
case HorizontalAlignmentRight:
imageX += (self.Width - imageWidth)
break
}
imageY := y
switch self.VerticalAlignment {
case VerticalAlignmentMiddle:
imageY += ((self.Height - imageHeight) / 2)
break
case VerticalAlignmentBottom:
imageY += (self.Height - imageHeight)
break
}
options.ImageType = self.ImageType
if options.ImageType != "" {
pdfDoc.Fpdf.RegisterImageOptionsReader(self.ImageKey, options, bytes.NewReader(dataURL.Data))
pdfDoc.Fpdf.ImageOptions(self.ImageKey, imageX, imageY, imageWidth, imageHeight, false, options, 0, "")
}
}
if self.Link != "" {
// horizontal and vertical alignment of image within given width and height
// by keeping original image aspect ratio
offsetY := 0.0
offsetX := offsetY
imageDisplayWidth, imageDisplayHeight := 0.0, 0.0
imageWidth, imageHeight := self.Width, self.Height
if imageWidth <= self.Width && imageHeight <= self.Height {
imageDisplayWidth, imageDisplayHeight = imageWidth, imageHeight
} else {
sizeRatio := imageWidth / imageHeight
tmp := self.Width / sizeRatio
if tmp <= self.Height {
imageDisplayWidth = self.Width
imageDisplayHeight = tmp
} else {
imageDisplayWidth = self.Height * sizeRatio
imageDisplayHeight = self.Height
}
}
if self.HorizontalAlignment == HorizontalAlignmentCenter {
offsetX = ((self.Width - imageDisplayWidth) / 2)
} else if self.HorizontalAlignment == HorizontalAlignmentRight {
offsetX = self.Width - imageDisplayWidth
}
if self.VerticalAlignment == VerticalAlignmentMiddle {
offsetY = ((self.Height - imageDisplayHeight) / 2)
} else if self.VerticalAlignment == VerticalAlignmentBottom {
offsetY = self.Height - imageDisplayHeight
}
linkID := pdfDoc.Fpdf.AddLink()
pdfDoc.Fpdf.Link(x+offsetX, y+offsetY, imageDisplayWidth, imageDisplayHeight, linkID)
}
}
func (self *ImageElement) renderSpreadsheet(row int, col int, ctx Context, renderer Renderer) (int, int) {
if self.ImageKey != "" {
if self.SpreadsheetColumn != 0 {
col = cast.ToInt(self.SpreadsheetAddEmptyRow) - 1
}
renderer.insertImage(row, col, self.ImageKey, self.Width)
if self.SpreadsheetAddEmptyRow {
row += 2
} else {
row++
}
}
return row, col
}
func (self *ImageElement) cleanup() {
if self.ImageKey != "" {
self.ImageKey = ""
}
}
func (self *ImageElement) getNextRenderElement(offsetY float64, containerHeight float64, ctx Context, pdfDoc *FPDFRB) (DocElementBaseProvider, bool) {
self.RenderingComplete = true // Hacky
if offsetY+self.Height <= containerHeight {
self.RenderY = offsetY
self.RenderBottom = offsetY + self.Height
self.RenderingBottom = true
return self, true
}
return nil, false
}
func NewImageElement(report *report, data map[string]interface{}) *ImageElement {
imageElement := ImageElement{}
imageElement.init(report, data)
return &imageElement
}
type BarCodeElement struct {
DocElement
Content string
Format string
DisplayValue bool
RemoveEmptyElement bool
SpreadsheetHide bool
SpreadsheetColumn int
SpreadsheetColspan int
SpreadsheetAddEmptyRow bool
ImageKey *string
ImageHeight float64
}
func (self *BarCodeElement) init(report *report, data map[string]interface{}) {
self.DocElement.init(report, data)
self.Content = GetStringValue(data, "content")
self.Format = strings.ToLower(GetStringValue(data, "format"))
if self.Format != "code128" {
panic(self.Format)
}
self.DisplayValue = GetBoolValue(data, "displayValue")
self.PrintIf = GetStringValue(data, "printIf")
self.RemoveEmptyElement = GetBoolValue(data, "removeEmptyElement")
self.SpreadsheetHide = GetBoolValue(data, "spreadsheet_hide")
self.SpreadsheetColumn = GetIntValue(data, "spreadsheet_column")
self.SpreadsheetColspan = GetIntValue(data, "spreadsheet_colspan")
self.SpreadsheetAddEmptyRow = GetBoolValue(data, "spreadsheet_addEmptyRow")
self.ImageKey = nil
if self.DisplayValue == true {
self.ImageHeight = self.Height - 22.0
} else {
self.ImageHeight = self.Height
}
}
func (self *BarCodeElement) isPrinted(ctx Context) bool {
if self.Content == "" {
return false
}
return self.DocElementBase.isPrinted(ctx)
}
func (self *BarCodeElement) prepare(ctx Context, pdfDoc *FPDFRB, onlyVerify bool) {
if self.ImageKey != nil {
return
}
self.Content = ctx.fillParameters(self.Content, self.ID, "content", "")
if self.Content != "" {
self.Width = 136
imageKey := barcode.RegisterCode128(pdfDoc.Fpdf, self.Content)
self.ImageKey = &imageKey
}
}
func (self *BarCodeElement) getNextRenderElement(offsetY float64, containerHeight float64, ctx Context, pdfDoc *FPDFRB) (DocElementBaseProvider, bool) {
if offsetY+self.Height <= containerHeight {
self.RenderY = offsetY
self.RenderBottom = offsetY + self.Height
self.RenderingComplete = true
return self, true
}
return nil, false
}
func (self *BarCodeElement) renderPDF(containerOffsetX float64, containerOffsetY float64, pdfDoc *FPDFRB) {
x := self.X + containerOffsetX
y := self.RenderY + containerOffsetY
if self.ImageKey != nil {
barcode.Barcode(pdfDoc.Fpdf, *self.ImageKey, x, y, self.Width, self.ImageHeight, false)
if self.DisplayValue != false {
pdfDoc.Fpdf.SetFont("courier", "B", 18)
pdfDoc.Fpdf.SetTextColor(0, 0, 0)
contentWidth := pdfDoc.Fpdf.GetStringWidth(self.Content)
OffsetX := (self.Width - contentWidth) / 2
pdfDoc.Fpdf.Text(x+OffsetX, y+self.ImageHeight+20, self.Content)
}
}
}
func (self *BarCodeElement) renderSpreadsheet(row int, col int, ctx Context, renderer Renderer) (int, int) {
if self.Content != "" {
cellFormat := ""
if self.SpreadsheetColumn != 0 {
col = self.SpreadsheetColumn - 1
}
renderer.write(row, col, self.SpreadsheetColspan, self.Content, cellFormat, self.Width)
if self.SpreadsheetAddEmptyRow {
row += 2
} else {
row++
}
col++
}
return row, col
}
func (self BarCodeElement) cleanup() {
if self.ImageKey != nil {
// os.unlink(self.imageKey)
self.ImageKey = nil
}
}
func NewBarCodeElement(report *report, data map[string]interface{}) *BarCodeElement {
barCodeElement := BarCodeElement{}
barCodeElement.init(report, data)
return &barCodeElement
}
type LineElement struct {
DocElement
Color Color
}
func (self *LineElement) init(report *report, data map[string]interface{}) {
self.DocElement.init(report, data)
self.Color = NewColor(GetStringValue(data, "color"))
self.PrintIf = GetStringValue(data, "printIf")
}
func (self *LineElement) renderPDF(containerOffsetX float64, containerOffsetY float64, pdfDoc *FPDFRB) {
pdfDoc.Fpdf.SetDrawColor(self.Color.R, self.Color.G, self.Color.B)
pdfDoc.Fpdf.SetLineWidth(self.Height)
x := self.X + containerOffsetX
y := self.Y + containerOffsetY + (self.Height / 2)
pdfDoc.Fpdf.Line(x, y, x+self.Width, y)
}
func (self *LineElement) getNextRenderElement(offsetY float64, containerHeight float64, ctx Context, pdfDoc *FPDFRB) (DocElementBaseProvider, bool) {
if offsetY+self.Height <= containerHeight {
self.RenderY = offsetY
self.RenderBottom = offsetY + self.Height
self.RenderingBottom = true
self.RenderingComplete = true
return self, true
}
return nil, false
}
func NewLineElement(report *report, data map[string]interface{}) *LineElement {
lineElement := LineElement{}
lineElement.init(report, data)
return &lineElement
}
type PageBreakElement struct {
DocElementBase
}
func (self *PageBreakElement) init(report *report, data map[string]interface{}) {
self.DocElementBase.init(report, data)
self.ID = GetIntValue(data, "id")
self.X = 0.0
self.Width = 0.0
self.SortOrder = 0 // sort order for elements with same 'y'-value, render page break before other elements
}
func (self *PageBreakElement) getNextRenderElement(offsetY float64, containerHeight float64, ctx Context, pdfDoc *FPDFRB) (DocElementBaseProvider, bool) {
return self, true
}
func NewPageBreakElement(report *report, data map[string]interface{}) *PageBreakElement {
pageBreakElement := PageBreakElement{}
pageBreakElement.init(report, data)
return &pageBreakElement
}
type TextElement struct {
DocElement
Content string
Eval bool
Style textStyle
Pattern string
Link string
CsCondition string
ConditionalStyle *textStyle
TextHeight float64
LineIndex int
LineHeight float64
LinesCount int
TextLines []TextLine
SpaceTop float64
SpaceBottom float64
SpreadsheetCellFormat *int
SpreadsheetCellFormatinitialized bool
SpreadsheetColspan int
AlwaysPrintOnSamePage bool
}
func (self *TextElement) init(report *report, data map[string]interface{}) {
self.Type = DocElementTypeText.String()
self.DocElement.init(report, data)
self.Content = GetStringValue(data, "content")
self.Eval = GetBoolValue(data, "eval")
if GetIntValue(data, "styleId") != 0 {
if style, ok := report.Styles[cast.ToString(GetIntValue(data, "styleId"))]; ok {
self.Style = style
} else {
log.Println(Error{Message: fmt.Sprintf("Style for text element %s not found", self.ID)})
}
} else {
self.Style = NewTextStyle(data, "")
}
self.PrintIf = GetStringValue(data, "printIf")
self.Pattern = GetStringValue(data, "pattern")
self.Link = GetStringValue(data, "link")
self.CsCondition = GetStringValue(data, "cs_condition")
if self.CsCondition != "" {
if GetStringValue(data, "cs_styleId") != "" {
if val, ok := report.Styles[cast.ToString(GetIntValue(data, "cs_styleId"))]; ok {
self.ConditionalStyle = &val
}
if self.ConditionalStyle == nil {
log.Println(Error{Message: fmt.Sprintf("Conditional style for text element %s not found", self.ID)})
}
} else {
style := NewTextStyle(data, "cs_")
self.ConditionalStyle = &style
}
} else {
self.ConditionalStyle = nil
}
if getDataType(self) == DataTypeTableTextElement {
self.RemoveEmptyElement = false
self.AlwaysPrintOnSamePage = false
} else {
self.RemoveEmptyElement = GetBoolValue(data, "removeEmptyElement")
self.AlwaysPrintOnSamePage = GetBoolValue(data, "alwaysPrintOnSamePage")
}
self.Height = float64(GetIntValue(data, "height"))
self.SpreadsheetHide = GetBoolValue(data, "spreadsheet_hide")
self.SpreadsheetColumn = StringPointer(cast.ToString(GetIntValue(data, "spreadsheet_column")))
self.SpreadsheetColspan = GetIntValue(data, "spreadsheet_colspan")
self.SpreadsheetAddEmptyRow = GetBoolValue(data, "spreadsheet_addEmptyRow")
self.TextHeight = 0.0
self.LineIndex = -1
self.LineHeight = 0
self.LinesCount = 0
self.TextLines = nil
self.UsedStyle = nil
self.SpaceTop = 0
self.SpaceBottom = 0
self.TotalHeight = 0
self.SpreadsheetCellFormat = nil
self.SpreadsheetCellFormatinitialized = false
}
func (self *TextElement) isPrinted(ctx Context) bool {
if self.RemoveEmptyElement && len(self.TextLines) == 0 {
return false
}
return self.DocElementBase.isPrinted(ctx)
}
func (self *TextElement) prepare(ctx Context, pdfDoc *FPDFRB, onlyVerify bool) {
var content interface{}
if self.Eval {
content = ctx.evaluateExpression(self.Content, self.ID, "content")
if self.Pattern != "" {
if (reflect.TypeOf(content) == reflect.TypeOf(0)) || (reflect.TypeOf(content) == reflect.TypeOf(0.0)) {
usedPattern := self.Pattern
patternHasCurrency := strings.Contains(usedPattern, "$")
if usedPattern != "" {
usedPattern = strings.Replace(usedPattern, "0", "#", -1)
usedPattern = strings.Replace(usedPattern, " ", "", -1)
if patternHasCurrency {
usedPattern = strings.Replace(usedPattern, "$", "", -1)
content = humanize.FormatFloat(usedPattern, cast.ToFloat64(content))
content = ctx.PatternCurrencySymbol + cast.ToString(content)
} else {
content = humanize.FormatFloat(usedPattern, cast.ToFloat64(content))
}
}
} else if reflect.TypeOf(content) == reflect.TypeOf(time.Time{}) {
usedPattern := self.Pattern
if usedPattern != "" {
t, err := now.Parse(cast.ToString(content))
if err == nil {
date := jodaTime.Format(usedPattern, t)
content = date
}
}
}
}
content = cast.ToString(content)
} else {
content = ctx.fillParameters(self.Content, self.ID, "content", self.Pattern)
}
if self.Link != "" {
self.Link = ctx.fillParameters(self.Link, self.ID, "link", "")
}
if self.CsCondition != "" {
if cast.ToBool(ctx.evaluateExpression(self.CsCondition, self.ID, "cs_condition")) {
self.UsedStyle = self.ConditionalStyle
} else {
self.UsedStyle = &self.Style
}
} else {
self.UsedStyle = &self.Style
}
if getDataType(self) == DataTypeTableTextElement {
if self.UsedStyle.VerticalAlignment != VerticalAlignmentTop && self.AlwaysPrintOnSamePage == false {
self.AlwaysPrintOnSamePage = true
}
}
availableWidth := self.Width - self.UsedStyle.PaddingLeft - self.UsedStyle.PaddingRight
self.TextLines = make([]TextLine, 0)
if pdfDoc.Fpdf != nil {
pdfDoc.Fpdf.SetFont(self.UsedStyle.Font, self.UsedStyle.FontStyle, self.UsedStyle.FontSize)
lines := make([]TextLine, 0)
if content != "" {
tmpLines := pdfDoc.Fpdf.SplitLines([]byte(cast.ToString(content)), availableWidth)
for split := 0; split < len(tmpLines); split++ {
lines = append(lines, NewTextLine(string(tmpLines[split]), availableWidth, self.UsedStyle, self.Link))
}
content = strings.Replace(cast.ToString(content), "\n", " \n ", -1)
}
self.LineHeight = self.UsedStyle.base().FontSize * self.UsedStyle.base().LineSpacing
self.LinesCount = len(lines)
if self.LinesCount > 0 {
self.TextHeight = float64((len(lines)-1))*self.LineHeight + self.UsedStyle.base().FontSize
}
self.LineIndex = 0
for _, line := range lines {
self.TextLines = append(self.TextLines, line)
}
if self.TableElement {
self.TotalHeight = max(self.TextHeight+self.UsedStyle.PaddingTop+self.UsedStyle.PaddingBottom, self.Height)
} else {
self.setHeight(self.Height)
}
} else {
self.Content = cast.ToString(content)
// set textLines so isPrinted can check for empty element when rendering spreadsheet
if content != "" {
self.TextLines = make([]TextLine, 0)
self.TextLines = append(self.TextLines, NewTextLine(cast.ToString(content), availableWidth, self.UsedStyle, self.Link))
}
}
}
func (self *TextElement) setHeight(height float64) {
self.Height = height
self.SpaceTop = 0.0
self.SpaceBottom = 0.0
totalHeight := 0.0
if self.TextHeight > 0 {
totalHeight = self.TextHeight + self.UsedStyle.PaddingTop + self.UsedStyle.PaddingBottom
}
if totalHeight < height {
remainingSpace := height - totalHeight
if self.UsedStyle.VerticalAlignment == VerticalAlignmentTop {
self.SpaceBottom = remainingSpace
} else if self.UsedStyle.VerticalAlignment == VerticalAlignmentMiddle {
self.SpaceTop = remainingSpace / 2
self.SpaceBottom = remainingSpace / 2
} else if self.UsedStyle.VerticalAlignment == VerticalAlignmentBottom {
self.SpaceTop = remainingSpace
}
}
self.TotalHeight = totalHeight + self.SpaceTop + self.SpaceBottom
}
func (self *TextElement) getNextRenderElement(offsetY float64, containerHeight float64, ctx Context, pdfDoc *FPDFRB) (DocElementBaseProvider, bool) {
availableHeight := containerHeight - offsetY
if self.AlwaysPrintOnSamePage && self.FirstRenderElement && self.TotalHeight > availableHeight && offsetY != 0 {
return nil, false
}
lines := make([]TextLine, 0)
remainingHeight := availableHeight
blockHeight := 0.0
textHeight := 0.0
textOffsetY := 0.0
if self.SpaceTop > 0 {
spaceTop := pyMin(self.SpaceTop, remainingHeight)
self.SpaceTop -= spaceTop
blockHeight += spaceTop
remainingHeight -= spaceTop
textOffsetY = spaceTop
}
if self.SpaceTop == 0 {
firstLine := true
for self.LineIndex < self.LinesCount {
lastLine := (self.LineIndex >= self.LinesCount-1)
lineHeight := self.LineHeight
if firstLine && self.UsedStyle != nil {
lineHeight = self.UsedStyle.FontSize
}
tmpHeight := lineHeight
if self.LineIndex == 0 {
tmpHeight += self.UsedStyle.PaddingTop
}
if lastLine && self.UsedStyle != nil {
tmpHeight += self.UsedStyle.PaddingBottom
}
if tmpHeight > remainingHeight {
break
}
lines = append(lines, self.TextLines[self.LineIndex])
remainingHeight -= tmpHeight
blockHeight += tmpHeight
textHeight += lineHeight
self.LineIndex++
firstLine = false
}
}
if self.LineIndex >= self.LinesCount && self.SpaceBottom > 0 {
spaceBottom := pyMin(self.SpaceBottom, remainingHeight)
self.SpaceBottom -= spaceBottom
blockHeight += spaceBottom