forked from signintech/gopdf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gopdf.go
2431 lines (2052 loc) · 63.5 KB
/
gopdf.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 gopdf
import (
"bufio"
"bytes"
"compress/zlib" // for constants
"errors"
"fmt"
"image"
"image/jpeg"
"image/png"
"io"
"log"
"math"
"os"
"strconv"
"strings"
"time"
"github.com/phpdave11/gofpdi"
)
const subsetFont = "SubsetFont"
// the default margin if no margins are set
const defaultMargin = 10.0 //for backward compatible
var ErrEmptyString = errors.New("empty string")
var ErrMissingFontFamily = errors.New("font family not found")
var ErrUndefinedCacheContentImage = errors.New("cacheContentImage is undefined")
var ErrInvalidRectangleCoordinates = errors.New("Invalid coordinates for the rectangle")
var ErrInvalidRectangleRadius = errors.New("Radius length cannot exceed rectangle height or width")
// GoPdf : A simple library for generating PDF written in Go lang
type GoPdf struct {
//page Margin
//leftMargin float64
//topMargin float64
margins Margins
pdfObjs []IObj
config Config
anchors map[string]anchorOption
indexOfCatalogObj int
/*---index ของ obj สำคัญๆ เก็บเพื่อลด loop ตอนค้นหา---*/
//index ของ obj pages
indexOfPagesObj int
//number of pages
numOfPagesObj int
//index ของ obj page อันแรก
indexOfFirstPageObj int
//ต่ำแหน่งปัจจุบัน
curr Current
indexEncodingObjFonts []int
indexOfContent int
//index ของ procset ซึ่งควรจะมีอันเดียว
indexOfProcSet int
//IsUnderline bool
// Buffer for io.Reader compliance
buf bytes.Buffer
//pdf PProtection
pdfProtection *PDFProtection
encryptionObjID int
// content streams only
compressLevel int
//info
isUseInfo bool
info *PdfInfo
//outlines
outlines *OutlinesObj
indexOfOutlinesObj int
//header and footer functions
headerFunc func()
footerFunc func()
// gofpdi free pdf document importer
fpdi *gofpdi.Importer
//placeholder text
placeHolderTexts map[string]([]placeHolderTextInfo)
}
type DrawableRectOptions struct {
Rect
X float64
Y float64
PaintStyle PaintStyle
Transparency *Transparency
extGStateIndexes []int
}
type CropOptions struct {
X float64
Y float64
Width float64
Height float64
}
type ImageOptions struct {
DegreeAngle float64
VerticalFlip bool
HorizontalFlip bool
X float64
Y float64
Rect *Rect
Mask *MaskOptions
Crop *CropOptions
Transparency *Transparency
extGStateIndexes []int
}
type ImageFromOption struct {
Format string //jpeg,png
X float64
Y float64
Rect *Rect
}
type MaskOptions struct {
ImageOptions
BBox *[4]float64
Holder ImageHolder
}
type lineOptions struct {
extGStateIndexes []int
}
type polygonOptions struct {
extGStateIndexes []int
}
// SetLineWidth : set line width
func (gp *GoPdf) SetLineWidth(width float64) {
gp.curr.lineWidth = gp.UnitsToPoints(width)
gp.getContent().AppendStreamSetLineWidth(gp.UnitsToPoints(width))
}
// SetCompressLevel : set compress Level for content streams
// Possible values for level:
//
// -2 HuffmanOnly, -1 DefaultCompression (which is level 6)
// 0 No compression,
// 1 fastest compression, but not very good ratio
// 9 best compression, but slowest
func (gp *GoPdf) SetCompressLevel(level int) {
errfmt := "compress level too %s, using %s instead\n"
if level < -2 { //-2 = zlib.HuffmanOnly
fmt.Fprintf(os.Stderr, errfmt, "small", "DefaultCompression")
level = zlib.DefaultCompression
} else if level > zlib.BestCompression {
fmt.Fprintf(os.Stderr, errfmt, "big", "BestCompression")
level = zlib.BestCompression
return
}
// sanity check complete
gp.compressLevel = level
}
// SetNoCompression : compressLevel = 0
func (gp *GoPdf) SetNoCompression() {
gp.compressLevel = zlib.NoCompression
}
// SetLineType : set line type ("dashed" ,"dotted")
//
// Usage:
// pdf.SetLineType("dashed")
// pdf.Line(50, 200, 550, 200)
// pdf.SetLineType("dotted")
// pdf.Line(50, 400, 550, 400)
func (gp *GoPdf) SetLineType(linetype string) {
gp.getContent().AppendStreamSetLineType(linetype)
}
// SetCustomLineType : set custom line type
//
// Usage:
// pdf.SetCustomLineType([]float64{0.8, 0.8}, 0)
// pdf.Line(50, 200, 550, 200)
func (gp *GoPdf) SetCustomLineType(dashArray []float64, dashPhase float64) {
for i := range dashArray {
gp.UnitsToPointsVar(&dashArray[i])
}
gp.UnitsToPointsVar(&dashPhase)
gp.getContent().AppendStreamSetCustomLineType(dashArray, dashPhase)
}
// Line : draw line
//
// Usage:
// pdf.SetTransparency(gopdf.Transparency{Alpha: 0.5,BlendModeType: gopdf.ColorBurn})
// pdf.SetLineType("dotted")
// pdf.SetStrokeColor(255, 0, 0)
// pdf.SetLineWidth(2)
// pdf.Line(10, 30, 585, 30)
// pdf.ClearTransparency()
func (gp *GoPdf) Line(x1 float64, y1 float64, x2 float64, y2 float64) {
gp.UnitsToPointsVar(&x1, &y1, &x2, &y2)
transparency, err := gp.getCachedTransparency(nil)
if err != nil {
transparency = nil
}
var opts = lineOptions{}
if transparency != nil {
opts.extGStateIndexes = append(opts.extGStateIndexes, transparency.extGStateIndex)
}
gp.getContent().AppendStreamLine(x1, y1, x2, y2, opts)
}
// RectFromLowerLeft : draw rectangle from lower-left corner (x, y)
func (gp *GoPdf) RectFromLowerLeft(x float64, y float64, wdth float64, hght float64) {
gp.UnitsToPointsVar(&x, &y, &wdth, &hght)
opts := DrawableRectOptions{
X: x,
Y: y,
PaintStyle: DrawPaintStyle,
Rect: Rect{W: wdth, H: hght},
}
gp.getContent().AppendStreamRectangle(opts)
}
// RectFromUpperLeft : draw rectangle from upper-left corner (x, y)
func (gp *GoPdf) RectFromUpperLeft(x float64, y float64, wdth float64, hght float64) {
gp.UnitsToPointsVar(&x, &y, &wdth, &hght)
opts := DrawableRectOptions{
X: x,
Y: y + hght,
PaintStyle: DrawPaintStyle,
Rect: Rect{W: wdth, H: hght},
}
gp.getContent().AppendStreamRectangle(opts)
}
// RectFromLowerLeftWithStyle : draw rectangle from lower-left corner (x, y)
// - style: Style of rectangule (draw and/or fill: D, F, DF, FD)
// D or empty string: draw. This is the default value.
// F: fill
// DF or FD: draw and fill
func (gp *GoPdf) RectFromLowerLeftWithStyle(x float64, y float64, wdth float64, hght float64, style string) {
opts := DrawableRectOptions{
X: x,
Y: y,
Rect: Rect{
H: hght,
W: wdth,
},
PaintStyle: parseStyle(style),
}
gp.RectFromLowerLeftWithOpts(opts)
}
func (gp *GoPdf) RectFromLowerLeftWithOpts(opts DrawableRectOptions) error {
gp.UnitsToPointsVar(&opts.X, &opts.Y, &opts.W, &opts.H)
imageTransparency, err := gp.getCachedTransparency(opts.Transparency)
if err != nil {
return err
}
if imageTransparency != nil {
opts.extGStateIndexes = append(opts.extGStateIndexes, imageTransparency.extGStateIndex)
}
gp.getContent().AppendStreamRectangle(opts)
return nil
}
// RectFromUpperLeftWithStyle : draw rectangle from upper-left corner (x, y)
// - style: Style of rectangule (draw and/or fill: D, F, DF, FD)
// D or empty string: draw. This is the default value.
// F: fill
// DF or FD: draw and fill
func (gp *GoPdf) RectFromUpperLeftWithStyle(x float64, y float64, wdth float64, hght float64, style string) {
opts := DrawableRectOptions{
X: x,
Y: y,
Rect: Rect{
H: hght,
W: wdth,
},
PaintStyle: parseStyle(style),
}
gp.RectFromUpperLeftWithOpts(opts)
}
func (gp *GoPdf) RectFromUpperLeftWithOpts(opts DrawableRectOptions) error {
gp.UnitsToPointsVar(&opts.X, &opts.Y, &opts.W, &opts.H)
opts.Y += opts.H
imageTransparency, err := gp.getCachedTransparency(opts.Transparency)
if err != nil {
return err
}
if imageTransparency != nil {
opts.extGStateIndexes = append(opts.extGStateIndexes, imageTransparency.extGStateIndex)
}
gp.getContent().AppendStreamRectangle(opts)
return nil
}
// Oval : draw oval
func (gp *GoPdf) Oval(x1 float64, y1 float64, x2 float64, y2 float64) {
gp.UnitsToPointsVar(&x1, &y1, &x2, &y2)
gp.getContent().AppendStreamOval(x1, y1, x2, y2)
}
// Br : new line
func (gp *GoPdf) Br(h float64) {
gp.UnitsToPointsVar(&h)
gp.curr.Y += h
gp.curr.X = gp.margins.Left
}
// SetGrayFill set the grayscale for the fill, takes a float64 between 0.0 and 1.0
func (gp *GoPdf) SetGrayFill(grayScale float64) {
gp.curr.txtColorMode = "gray"
gp.curr.grayFill = grayScale
gp.getContent().AppendStreamSetGrayFill(grayScale)
}
// SetGrayStroke set the grayscale for the stroke, takes a float64 between 0.0 and 1.0
func (gp *GoPdf) SetGrayStroke(grayScale float64) {
gp.curr.grayStroke = grayScale
gp.getContent().AppendStreamSetGrayStroke(grayScale)
}
// SetX : set current position X
func (gp *GoPdf) SetX(x float64) {
gp.UnitsToPointsVar(&x)
gp.curr.setXCount++
gp.curr.X = x
}
// GetX : get current position X
func (gp *GoPdf) GetX() float64 {
return gp.PointsToUnits(gp.curr.X)
}
// SetNewY : set current position y, and modified y if add a new page.
// Example:
// For example, if the page height is set to 841px, MarginTop is 20px,
// MarginBottom is 10px, and the height of the element(such as text) to be inserted is 25px,
// because 10<25, you need to add another page and set y to 20px.
// Because of called AddPage(), X is set to MarginLeft, so you should specify X if needed,
// or make sure SetX() is after SetNewY(), or using SetNewXY().
// SetNewYIfNoOffset is more suitable for scenarios where the offset does not change, such as pdf.Image().
func (gp *GoPdf) SetNewY(y float64, h float64) {
gp.UnitsToPointsVar(&y)
gp.UnitsToPointsVar(&h)
if gp.curr.Y+h > gp.curr.pageSize.H-gp.MarginBottom() {
gp.AddPage()
y = gp.MarginTop() // reset to top of the page.
}
gp.curr.Y = y
}
// SetNewYIfNoOffset : set current position y, and modified y if add a new page.
// Example:
// For example, if the page height is set to 841px, MarginTop is 20px,
// MarginBottom is 10px, and the height of the element(such as image) to be inserted is 200px,
// because 10<200, you need to add another page and set y to 20px.
// Tips: gp.curr.X and gp.curr.Y do not change when pdf.Image() is called.
func (gp *GoPdf) SetNewYIfNoOffset(y float64, h float64) {
gp.UnitsToPointsVar(&y)
gp.UnitsToPointsVar(&h)
if y+h > gp.curr.pageSize.H-gp.MarginBottom() { // using new y(*y) instead of gp.curr.Y
gp.AddPage()
y = gp.MarginTop() // reset to top of the page.
}
gp.curr.Y = y
}
// SetNewXY : set current position x and y, and modified y if add a new page.
// Example:
// For example, if the page height is set to 841px, MarginTop is 20px,
// MarginBottom is 10px, and the height of the element to be inserted is 25px,
// because 10<25, you need to add another page and set y to 20px.
// Because of AddPage(), X is set to MarginLeft, so you should specify X if needed,
// or make sure SetX() is after SetNewY().
func (gp *GoPdf) SetNewXY(y float64, x, h float64) {
gp.UnitsToPointsVar(&y)
gp.UnitsToPointsVar(&h)
if gp.curr.Y+h > gp.curr.pageSize.H-gp.MarginBottom() {
gp.AddPage()
y = gp.MarginTop() // reset to top of the page.
}
gp.curr.Y = y
gp.SetX(x)
}
/*
//experimental
func (gp *GoPdf) SetNewY(y float64, h float64) float64 {
gp.UnitsToPointsVar(&y)
gp.UnitsToPointsVar(&h)
if gp.curr.Y+h > gp.curr.pageSize.H-gp.MarginBottom() {
gp.AddPage()
y = gp.MarginTop() // reset to top of the page.
}
gp.curr.Y = y
return gp.GetY()
}
//experimental
func (gp *GoPdf) SetNewYIfNoOffset(y float64, h float64) float64 {
gp.UnitsToPointsVar(&y)
gp.UnitsToPointsVar(&h)
if y+h > gp.curr.pageSize.H-gp.MarginBottom() { // using new y(*y) instead of gp.curr.Y
gp.AddPage()
y = gp.MarginTop() // reset to top of the page.
}
gp.curr.Y = y
return gp.GetY()
}
//experimental
func (gp *GoPdf) SetNewXY(y float64, x, h float64) float64{
gp.UnitsToPointsVar(&y)
gp.UnitsToPointsVar(&h)
if gp.curr.Y+h > gp.curr.pageSize.H-gp.MarginBottom() {
gp.AddPage()
y = gp.MarginTop() // reset to top of the page.
}
gp.curr.Y = y
gp.SetX(x)
return gp.GetY()
}
*/
// SetY : set current position y
func (gp *GoPdf) SetY(y float64) {
gp.UnitsToPointsVar(&y)
gp.curr.Y = y
}
// GetY : get current position y
func (gp *GoPdf) GetY() float64 {
return gp.PointsToUnits(gp.curr.Y)
}
// SetXY : set current position x and y
func (gp *GoPdf) SetXY(x, y float64) {
gp.UnitsToPointsVar(&x)
gp.curr.setXCount++
gp.curr.X = x
gp.UnitsToPointsVar(&y)
gp.curr.Y = y
}
// ImageByHolder : draw image by ImageHolder
func (gp *GoPdf) ImageByHolder(img ImageHolder, x float64, y float64, rect *Rect) error {
gp.UnitsToPointsVar(&x, &y)
rect = rect.UnitsToPoints(gp.config.Unit)
imageOptions := ImageOptions{
X: x,
Y: y,
Rect: rect,
}
return gp.imageByHolder(img, imageOptions)
}
func (gp *GoPdf) ImageByHolderWithOptions(img ImageHolder, opts ImageOptions) error {
gp.UnitsToPointsVar(&opts.X, &opts.Y)
opts.Rect = opts.Rect.UnitsToPoints(gp.config.Unit)
imageTransparency, err := gp.getCachedTransparency(opts.Transparency)
if err != nil {
return err
}
if imageTransparency != nil {
opts.extGStateIndexes = append(opts.extGStateIndexes, imageTransparency.extGStateIndex)
}
if opts.Mask != nil {
maskTransparency, err := gp.getCachedTransparency(opts.Mask.ImageOptions.Transparency)
if err != nil {
return err
}
if maskTransparency != nil {
opts.Mask.ImageOptions.extGStateIndexes = append(opts.Mask.ImageOptions.extGStateIndexes, maskTransparency.extGStateIndex)
}
gp.UnitsToPointsVar(&opts.Mask.ImageOptions.X, &opts.Mask.ImageOptions.Y)
opts.Mask.ImageOptions.Rect = opts.Mask.ImageOptions.Rect.UnitsToPoints(gp.config.Unit)
extGStateIndex, err := gp.maskHolder(opts.Mask.Holder, *opts.Mask)
if err != nil {
return err
}
opts.extGStateIndexes = append(opts.extGStateIndexes, extGStateIndex)
}
return gp.imageByHolder(img, opts)
}
func (gp *GoPdf) maskHolder(img ImageHolder, opts MaskOptions) (int, error) {
var cacheImage *ImageCache
var cacheContentImage *cacheContentImage
for _, imgcache := range gp.curr.ImgCaches {
if img.ID() == imgcache.Path {
cacheImage = &imgcache
break
}
}
if cacheImage == nil {
maskImgobj := &ImageObj{IsMask: true}
maskImgobj.init(func() *GoPdf {
return gp
})
maskImgobj.setProtection(gp.protection())
err := maskImgobj.SetImage(img)
if err != nil {
return 0, err
}
if opts.Rect == nil {
if opts.Rect, err = maskImgobj.getRect(); err != nil {
return 0, err
}
}
if err := maskImgobj.parse(); err != nil {
return 0, err
}
if gp.indexOfProcSet != -1 {
index := gp.addObj(maskImgobj)
cacheContentImage = gp.getContent().GetCacheContentImage(index, opts.ImageOptions)
procset := gp.pdfObjs[gp.indexOfProcSet].(*ProcSetObj)
procset.RelateXobjs = append(procset.RelateXobjs, RelateXobject{IndexOfObj: index})
imgcache := ImageCache{
Index: index,
Path: img.ID(),
Rect: opts.Rect,
}
gp.curr.ImgCaches[index] = imgcache
gp.curr.CountOfImg++
}
} else {
if opts.Rect == nil {
opts.Rect = gp.curr.ImgCaches[cacheImage.Index].Rect
}
cacheContentImage = gp.getContent().GetCacheContentImage(cacheImage.Index, opts.ImageOptions)
}
if cacheContentImage != nil {
extGStateInd, err := gp.createTransparencyXObjectGroup(cacheContentImage, opts)
if err != nil {
return 0, err
}
return extGStateInd, nil
}
return 0, ErrUndefinedCacheContentImage
}
func (gp *GoPdf) createTransparencyXObjectGroup(image *cacheContentImage, opts MaskOptions) (int, error) {
bbox := opts.BBox
if bbox == nil {
bbox = &[4]float64{
// correct BBox values is [opts.X, gp.curr.pageSize.H - opts.Y - opts.Rect.H, opts.X + opts.Rect.W, gp.curr.pageSize.H - opts.Y]
// but if compress pdf through ghostscript result file can't open correctly in mac viewer, because mac viewer can't parse BBox value correctly
// all other viewers parse BBox correctly (like Adobe Acrobat Reader, Chrome, even Internet Explorer)
// that's why we need to set [0, 0, gp.curr.pageSize.W, gp.curr.pageSize.H]
-gp.curr.pageSize.W * 2,
-gp.curr.pageSize.H * 2,
gp.curr.pageSize.W * 2,
gp.curr.pageSize.H * 2,
// Also, Chrome pdf viewer incorrectly recognize BBox value, that's why we need to set twice as much value
// for every mask element will be displayed
}
}
groupOpts := TransparencyXObjectGroupOptions{
BBox: *bbox,
ExtGStateIndexes: opts.extGStateIndexes,
XObjects: []cacheContentImage{*image},
}
transparencyXObjectGroup, err := GetCachedTransparencyXObjectGroup(groupOpts, gp)
if err != nil {
return 0, err
}
sMaskOptions := SMaskOptions{
Subtype: SMaskLuminositySubtype,
TransparencyXObjectGroupIndex: transparencyXObjectGroup.Index,
}
sMask := GetCachedMask(sMaskOptions, gp)
extGStateOpts := ExtGStateOptions{SMaskIndex: &sMask.Index}
extGState, err := GetCachedExtGState(extGStateOpts, gp)
if err != nil {
return 0, err
}
return extGState.Index + 1, nil
}
func (gp *GoPdf) imageByHolder(img ImageHolder, opts ImageOptions) error {
cacheImageIndex := -1
for _, imgcache := range gp.curr.ImgCaches {
if img.ID() == imgcache.Path {
cacheImageIndex = imgcache.Index
break
}
}
if cacheImageIndex == -1 { //new image
//create img object
imgobj := new(ImageObj)
if opts.Mask != nil {
imgobj.SplittedMask = true
}
imgobj.init(func() *GoPdf {
return gp
})
imgobj.setProtection(gp.protection())
err := imgobj.SetImage(img)
if err != nil {
return err
}
if opts.Rect == nil {
if opts.Rect, err = imgobj.getRect(); err != nil {
return err
}
}
err = imgobj.parse()
if err != nil {
return err
}
index := gp.addObj(imgobj)
if gp.indexOfProcSet != -1 {
//ยัดรูป
procset := gp.pdfObjs[gp.indexOfProcSet].(*ProcSetObj)
gp.getContent().AppendStreamImage(index, opts)
procset.RelateXobjs = append(procset.RelateXobjs, RelateXobject{IndexOfObj: index})
//เก็บข้อมูลรูปเอาไว้
var imgcache ImageCache
imgcache.Index = index
imgcache.Path = img.ID()
imgcache.Rect = opts.Rect
gp.curr.ImgCaches[index] = imgcache
gp.curr.CountOfImg++
}
if imgobj.haveSMask() {
smaskObj, err := imgobj.createSMask()
if err != nil {
return err
}
imgobj.imginfo.smarkObjID = gp.addObj(smaskObj)
}
if imgobj.isColspaceIndexed() {
dRGB, err := imgobj.createDeviceRGB()
if err != nil {
return err
}
dRGB.getRoot = func() *GoPdf {
return gp
}
imgobj.imginfo.deviceRGBObjID = gp.addObj(dRGB)
}
} else { //same img
if opts.Rect == nil {
opts.Rect = gp.curr.ImgCaches[cacheImageIndex].Rect
}
gp.getContent().AppendStreamImage(cacheImageIndex, opts)
}
return nil
}
// Image : draw image
func (gp *GoPdf) Image(picPath string, x float64, y float64, rect *Rect) error {
gp.UnitsToPointsVar(&x, &y)
rect = rect.UnitsToPoints(gp.config.Unit)
imgh, err := ImageHolderByPath(picPath)
if err != nil {
return err
}
imageOptions := ImageOptions{
X: x,
Y: y,
Rect: rect,
}
return gp.imageByHolder(imgh, imageOptions)
}
func (gp *GoPdf) ImageFrom(img image.Image, x float64, y float64, rect *Rect) error {
return gp.ImageFromWithOption(img, ImageFromOption{
Format: "png",
X: x,
Y: y,
Rect: rect,
})
}
func (gp *GoPdf) ImageFromWithOption(img image.Image, opts ImageFromOption) error {
if img == nil {
return errors.New("Invalid image")
}
gp.UnitsToPointsVar(&opts.X, &opts.Y)
opts.Rect = opts.Rect.UnitsToPoints(gp.config.Unit)
r, w := io.Pipe()
go func() {
bw := bufio.NewWriter(w)
var err error
switch opts.Format {
case "png":
err = png.Encode(bw, img)
case "jpeg":
err = jpeg.Encode(bw, img, nil)
}
bw.Flush()
if err != nil {
w.CloseWithError(err)
} else {
w.Close()
}
}()
imgh, err := ImageHolderByReader(bufio.NewReader(r))
if err != nil {
return err
}
imageOptions := ImageOptions{
X: opts.X,
Y: opts.Y,
Rect: opts.Rect,
}
return gp.imageByHolder(imgh, imageOptions)
}
// AddPage : add new page
func (gp *GoPdf) AddPage() {
emptyOpt := PageOption{}
gp.AddPageWithOption(emptyOpt)
}
// AddPageWithOption : add new page with option
func (gp *GoPdf) AddPageWithOption(opt PageOption) {
opt.TrimBox = opt.TrimBox.UnitsToPoints(gp.config.Unit)
opt.PageSize = opt.PageSize.UnitsToPoints(gp.config.Unit)
page := new(PageObj)
page.init(func() *GoPdf {
return gp
})
if !opt.isEmpty() { //use page option
page.setOption(opt)
gp.curr.pageSize = opt.PageSize
if opt.isTrimBoxSet() {
gp.curr.trimBox = opt.TrimBox
}
} else { //use default
gp.curr.pageSize = &gp.config.PageSize
gp.curr.trimBox = &gp.config.TrimBox
}
page.ResourcesRelate = strconv.Itoa(gp.indexOfProcSet+1) + " 0 R"
index := gp.addObj(page)
if gp.indexOfFirstPageObj == -1 {
gp.indexOfFirstPageObj = index
}
gp.curr.IndexOfPageObj = index
gp.numOfPagesObj++
//reset
gp.indexOfContent = -1
gp.resetCurrXY()
if gp.headerFunc != nil {
gp.headerFunc()
gp.resetCurrXY()
}
if gp.footerFunc != nil {
gp.footerFunc()
gp.resetCurrXY()
}
}
func (gp *GoPdf) AddOutline(title string) {
gp.outlines.AddOutline(gp.curr.IndexOfPageObj+1, title)
}
// AddOutlineWithPosition add an outline with position
func (gp *GoPdf) AddOutlineWithPosition(title string) *OutlineObj {
return gp.outlines.AddOutlinesWithPosition(gp.curr.IndexOfPageObj+1, title, gp.config.PageSize.H-gp.curr.Y+20)
}
// AddHeader - add a header function, if present this will be automatically called by AddPage()
func (gp *GoPdf) AddHeader(f func()) {
gp.headerFunc = f
}
// AddFooter - add a footer function, if present this will be automatically called by AddPage()
func (gp *GoPdf) AddFooter(f func()) {
gp.footerFunc = f
}
// Start : init gopdf
func (gp *GoPdf) Start(config Config) {
gp.start(config)
}
func (gp *GoPdf) StartWithImporter(config Config, importer *gofpdi.Importer) {
gp.start(config, importer)
}
func (gp *GoPdf) start(config Config, importer ...*gofpdi.Importer) {
gp.config = config
gp.init(importer...)
//init all basic obj
catalog := new(CatalogObj)
catalog.init(func() *GoPdf {
return gp
})
pages := new(PagesObj)
pages.init(func() *GoPdf {
return gp
})
gp.outlines = new(OutlinesObj)
gp.outlines.init(func() *GoPdf {
return gp
})
gp.indexOfCatalogObj = gp.addObj(catalog)
gp.indexOfPagesObj = gp.addObj(pages)
gp.indexOfOutlinesObj = gp.addObj(gp.outlines)
gp.outlines.SetIndexObjOutlines(gp.indexOfOutlinesObj)
//indexOfProcSet
procset := new(ProcSetObj)
procset.init(func() *GoPdf {
return gp
})
gp.indexOfProcSet = gp.addObj(procset)
if gp.isUseProtection() {
gp.pdfProtection = gp.createProtection()
}
gp.placeHolderTexts = make(map[string][]placeHolderTextInfo)
}
// convertNumericToFloat64 : accept numeric types, return float64-value
func convertNumericToFloat64(size interface{}) (fontSize float64, err error) {
switch size := size.(type) {
case float32:
return float64(size), nil
case float64:
return float64(size), nil
case int:
return float64(size), nil
case int16:
return float64(size), nil
case int32:
return float64(size), nil
case int64:
return float64(size), nil
case int8:
return float64(size), nil
case uint:
return float64(size), nil
case uint16:
return float64(size), nil
case uint32:
return float64(size), nil
case uint64:
return float64(size), nil
case uint8:
return float64(size), nil
default:
return 0.0, fmt.Errorf("fontSize must be of type (u)int* or float*, not %T", size)
}
}
// SetFontWithStyle : set font style support Regular or Underline
// for Bold|Italic should be loaded appropriate fonts with same styles defined
// size MUST be uint*, int* or float64*
func (gp *GoPdf) SetFontWithStyle(family string, style int, size interface{}) error {
fontSize, err := convertNumericToFloat64(size)
if err != nil {
return err
}
found := false
i := 0
max := len(gp.pdfObjs)
for i < max {
if gp.pdfObjs[i].getType() == subsetFont {
obj := gp.pdfObjs[i]
sub, ok := obj.(*SubsetFontObj)
if ok {
if sub.GetFamily() == family && sub.GetTtfFontOption().Style == style&^Underline {
gp.curr.FontSize = fontSize
gp.curr.FontStyle = style
gp.curr.FontFontCount = sub.CountOfFont
gp.curr.FontISubset = sub
found = true
break
}
}
}
i++
}
if !found {
return ErrMissingFontFamily
}
return nil
}
// SetFont : set font style support "" or "U"
// for "B" and "I" should be loaded appropriate fonts with same styles defined
// size MUST be uint*, int* or float64*
func (gp *GoPdf) SetFont(family string, style string, size interface{}) error {
return gp.SetFontWithStyle(family, getConvertedStyle(style), size)
}
// SetFontSize : set the font size (and only the font size) of the currently
// active font
func (gp *GoPdf) SetFontSize(fontSize float64) error {
gp.curr.FontSize = fontSize
return nil
}
// SetCharSpacing : set the character spacing of the currently active font
func (gp *GoPdf) SetCharSpacing(charSpacing float64) error {
gp.UnitsToPointsVar(&charSpacing)
gp.curr.CharSpacing = charSpacing
return nil