forked from signintech/gopdf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gopdf.go
1806 lines (1522 loc) · 45.9 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
"fmt"
"image"
"image/jpeg"
"io"
"io/ioutil"
"log"
"math"
"os"
"strconv"
"time"
"github.com/phpdave11/gofpdi"
"github.com/pkg/errors"
)
const subsetFont = "SubsetFont"
// the default margin if no margins are set
const defaultMargin = 10.0 //for backward compatible
//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
// gofpdi free pdf document importer
fpdi *gofpdi.Importer
}
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 {
VerticalFlip bool
HorizontalFlip bool
X float64
Y float64
Rect *Rect
Mask *MaskOptions
Crop *CropOptions
Transparency *Transparency
extGStateIndexes []int
}
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)
}
//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)
}
//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)
}
//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, errors.New("cacheContentImage is undefined")
}
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 {
gp.UnitsToPointsVar(&x, &y)
rect = rect.UnitsToPoints(gp.config.Unit)
r, w := io.Pipe()
go func() {
bw := bufio.NewWriter(w)
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: x,
Y: y,
Rect: 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()
}
func (gp *GoPdf) AddOutline(title string) {
gp.outlines.AddOutline(gp.curr.IndexOfPageObj+1, title)
}
//Start : init gopdf
func (gp *GoPdf) Start(config Config) {
gp.config = config
gp.init()
//สร้าง 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()
}
}
// 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, errors.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 apropriate 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 errors.New("not found font family")
}
return nil
}
//SetFont : set font style support "" or "U"
// for "B" and "I" should be loaded apropriate 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
}
//WritePdf : wirte pdf file
func (gp *GoPdf) WritePdf(pdfPath string) error {
return ioutil.WriteFile(pdfPath, gp.GetBytesPdf(), 0644)
}
func (gp *GoPdf) Write(w io.Writer) error {
return gp.compilePdf(w)
}
func (gp *GoPdf) Read(p []byte) (int, error) {
if gp.buf.Len() == 0 && gp.buf.Cap() == 0 {
if err := gp.compilePdf(&gp.buf); err != nil {
return 0, err
}
}
return gp.buf.Read(p)
}
// Close clears the gopdf buffer.
func (gp *GoPdf) Close() error {
gp.buf = bytes.Buffer{}
return nil
}
func (gp *GoPdf) compilePdf(w io.Writer) error {
gp.prepare()
err := gp.Close()
if err != nil {
return err
}
max := len(gp.pdfObjs)
writer := newCountingWriter(w)
//io.WriteString(w, "%PDF-1.7\n\n")
fmt.Fprint(writer, "%PDF-1.7\n\n")
linelens := make([]int, max)
i := 0
for i < max {
objID := i + 1
linelens[i] = writer.offset
pdfObj := gp.pdfObjs[i]
fmt.Fprintf(writer, "%d 0 obj\n", objID)
pdfObj.write(writer, objID)
io.WriteString(writer, "endobj\n\n")
i++
}
gp.xref(writer, writer.offset, linelens, i)
return nil
}
type (
countingWriter struct {
offset int
writer io.Writer
}
)
func newCountingWriter(w io.Writer) *countingWriter {
return &countingWriter{writer: w}
}
func (cw *countingWriter) Write(b []byte) (int, error) {
n, err := cw.writer.Write(b)
cw.offset += n
return n, err
}
//GetBytesPdfReturnErr : get bytes of pdf file
func (gp *GoPdf) GetBytesPdfReturnErr() ([]byte, error) {
err := gp.Close()
if err != nil {
return nil, err
}
err = gp.compilePdf(&gp.buf)
return gp.buf.Bytes(), err
}
//GetBytesPdf : get bytes of pdf file
func (gp *GoPdf) GetBytesPdf() []byte {
b, err := gp.GetBytesPdfReturnErr()
if err != nil {
log.Fatalf("%s", err.Error())
}
return b
}
//Text write text start at current x,y ( current y is the baseline of text )
func (gp *GoPdf) Text(text string) error {
text, err := gp.curr.FontISubset.AddChars(text)
if err != nil {
return err
}
err = gp.getContent().AppendStreamText(text)
if err != nil {
return err
}
return nil
}
//CellWithOption create cell of text ( use current x,y is upper-left corner of cell)
func (gp *GoPdf) CellWithOption(rectangle *Rect, text string, opt CellOption) error {
transparency, err := gp.getCachedTransparency(opt.Transparency)
if err != nil {
return err
}
if transparency != nil {
opt.extGStateIndexes = append(opt.extGStateIndexes, transparency.extGStateIndex)
}
rectangle = rectangle.UnitsToPoints(gp.config.Unit)
text, err = gp.curr.FontISubset.AddChars(text)
if err != nil {
return err
}
if err := gp.getContent().AppendStreamSubsetFont(rectangle, text, opt); err != nil {
return err
}
return nil
}
//Cell : create cell of text ( use current x,y is upper-left corner of cell)
//Note that this has no effect on Rect.H pdf (now). Fix later :-)
func (gp *GoPdf) Cell(rectangle *Rect, text string) error {
rectangle = rectangle.UnitsToPoints(gp.config.Unit)
defaultopt := CellOption{
Align: Left | Top,
Border: 0,
Float: Right,
}
text, err := gp.curr.FontISubset.AddChars(text)
if err != nil {
return err
}
err = gp.getContent().AppendStreamSubsetFont(rectangle, text, defaultopt)
if err != nil {
return err
}
return nil
}
//MultiCell : create of text with line breaks ( use current x,y is upper-left corner of cell)
func (gp *GoPdf) MultiCell(rectangle *Rect, text string) error {
var line []rune
x := gp.GetX()
var totalLineHeight float64
length := len([]rune(text))
// get lineHeight
text, err := gp.curr.FontISubset.AddChars(text)
if err != nil {
return err
}
_, lineHeight, _, err := createContent(gp.curr.FontISubset, text, gp.curr.FontSize, nil)
if err != nil {
return err
}
for i, v := range []rune(text) {
if totalLineHeight+lineHeight > rectangle.H {
break
}
lineWidth, _ := gp.MeasureTextWidth(string(line))
runeWidth, _ := gp.MeasureTextWidth(string(v))
if lineWidth+runeWidth > rectangle.W {
gp.Cell(&Rect{W: rectangle.W, H: lineHeight}, string(line))
gp.Br(lineHeight)
gp.SetX(x)
totalLineHeight = totalLineHeight + lineHeight
line = nil
}
line = append(line, v)
if i == length-1 {
gp.Cell(&Rect{W: rectangle.W, H: lineHeight}, string(line))
gp.Br(lineHeight)
gp.SetX(x)
}
}
return nil
}
// SplitText splits text into multiple lines based on width.
func (gp *GoPdf) SplitText(text string, width float64) ([]string, error) {
var lineText []rune
var lineTexts []string
utf8Texts := []rune(text)
utf8TextsLen := len(utf8Texts) // utf8 string quantity
if utf8TextsLen == 0 {
return lineTexts, errors.New("empty string")
}
for i := 0; i < utf8TextsLen; i++ {
lineWidth, err := gp.MeasureTextWidth(string(lineText))
if err != nil {
return nil, err
}
runeWidth, err := gp.MeasureTextWidth(string(utf8Texts[i]))
if err != nil {