-
Notifications
You must be signed in to change notification settings - Fork 0
/
fpdf.go
3318 lines (3153 loc) · 93.9 KB
/
fpdf.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
/*
* Copyright (c) 2013-2014 Kurt Jung (Gmail: kurt.w.jung)
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package gofpdf
// Version: 1.7
// Date: 2011-06-18
// Author: Olivier PLATHEY
// Port to Go: Kurt Jung, 2013-07-15
import (
"bytes"
"encoding/binary"
"encoding/json"
"fmt"
"image"
"image/color"
"image/gif"
"image/jpeg"
"image/png"
"io"
"io/ioutil"
"math"
"os"
"path"
"strings"
"time"
)
type fmtBuffer struct {
bytes.Buffer
}
func (b *fmtBuffer) printf(fmtStr string, args ...interface{}) {
b.Buffer.WriteString(fmt.Sprintf(fmtStr, args...))
}
func fpdfNew(orientationStr, unitStr, sizeStr, fontDirStr string, size SizeType) (f *Fpdf) {
f = new(Fpdf)
if orientationStr == "" {
orientationStr = "P"
}
if unitStr == "" {
unitStr = "mm"
}
if sizeStr == "" {
sizeStr = "A4"
}
if fontDirStr == "" {
fontDirStr = "."
}
f.page = 0
f.n = 2
f.pages = make([]*bytes.Buffer, 0, 8)
f.pages = append(f.pages, bytes.NewBufferString("")) // pages[0] is unused (1-based)
f.pageSizes = make(map[int]SizeType)
f.state = 0
f.fonts = make(map[string]fontDefType)
f.fontFiles = make(map[string]fontFileType)
f.diffs = make([]string, 0, 8)
f.images = make(map[string]*ImageInfoType)
f.pageLinks = make([][]linkType, 0, 8)
f.pageLinks = append(f.pageLinks, make([]linkType, 0, 0)) // pageLinks[0] is unused (1-based)
f.links = make([]intLinkType, 0, 8)
f.links = append(f.links, intLinkType{}) // links[0] is unused (1-based)
f.inHeader = false
f.inFooter = false
f.lasth = 0
f.fontFamily = ""
f.fontStyle = ""
f.SetFontSize(12)
f.underline = false
f.SetDrawColor(0, 0, 0)
f.SetFillColor(0, 0, 0)
f.SetTextColor(0, 0, 0)
f.colorFlag = false
f.ws = 0
f.fontpath = fontDirStr
// Core fonts
f.coreFonts = map[string]bool{
"courier": true,
"helvetica": true,
"times": true,
"symbol": true,
"zapfdingbats": true,
}
// Scale factor
switch unitStr {
case "pt", "point":
f.k = 1.0
case "mm":
f.k = 72.0 / 25.4
case "cm":
f.k = 72.0 / 2.54
case "in", "inch":
f.k = 72.0
default:
f.err = fmt.Errorf("incorrect unit %s", unitStr)
return
}
f.unitStr = unitStr
// Page sizes
f.stdPageSizes = make(map[string]SizeType)
f.stdPageSizes["a3"] = SizeType{841.89, 1190.55}
f.stdPageSizes["a4"] = SizeType{595.28, 841.89}
f.stdPageSizes["a5"] = SizeType{420.94, 595.28}
f.stdPageSizes["letter"] = SizeType{612, 792}
f.stdPageSizes["legal"] = SizeType{612, 1008}
if size.Wd > 0 && size.Ht > 0 {
f.defPageSize = size
} else {
f.defPageSize = f.getpagesizestr(sizeStr)
if f.err != nil {
return
}
}
f.curPageSize = f.defPageSize
// Page orientation
orientationStr = strings.ToLower(orientationStr)
switch orientationStr {
case "p", "portrait":
f.defOrientation = "P"
f.w = f.defPageSize.Wd
f.h = f.defPageSize.Ht
// dbg("Assign h: %8.2f", f.h)
case "l", "landscape":
f.defOrientation = "L"
f.w = f.defPageSize.Ht
f.h = f.defPageSize.Wd
default:
f.err = fmt.Errorf("incorrect orientation: %s", orientationStr)
return
}
f.curOrientation = f.defOrientation
f.wPt = f.w * f.k
f.hPt = f.h * f.k
// Page margins (1 cm)
margin := 28.35 / f.k
f.SetMargins(margin, margin, margin)
// Interior cell margin (1 mm)
f.cMargin = margin / 10
// Line width (0.2 mm)
f.lineWidth = 0.567 / f.k
// Automatic page break
f.SetAutoPageBreak(true, 2*margin)
// Default display mode
f.SetDisplayMode("default", "default")
if f.err != nil {
return
}
f.acceptPageBreak = func() bool {
return f.autoPageBreak
}
// Enable compression
f.SetCompression(true)
f.blendList = make([]blendModeType, 0, 8)
f.blendList = append(f.blendList, blendModeType{}) // blendList[0] is unused (1-based)
f.blendMap = make(map[string]int)
f.gradientList = make([]gradientType, 0, 8)
f.gradientList = append(f.gradientList, gradientType{}) // gradientList[0] is unused
// Set default PDF version number
f.pdfVersion = "1.3"
f.layerInit()
return
}
// NewCustom returns a pointer to a new Fpdf instance. Its methods are
// subsequently called to produce a single PDF document. NewCustom() is an
// alternative to New() that provides additional customization. This function
// is demonstrated in tutorial 15.
func NewCustom(init *InitType) (f *Fpdf) {
return fpdfNew(init.OrientationStr, init.UnitStr, init.SizeStr, init.FontDirStr, init.Size)
}
// New returns a pointer to a new Fpdf instance. Its methods are subsequently
// called to produce a single PDF document.
//
// orientationStr specifies the default page orientation. For portrait mode,
// specify "P" or "Portrait". For landscape mode, specify "L" or "Landscape".
// An empty string will be replaced with "P".
//
// unitStr specifies the unit of length used in size parameters for elements
// other than fonts, which are always measured in points. Specify "pt" for
// point, "mm" for millimeter, "cm" for centimeter, or "in" for inch. An empty
// string will be replaced with "mm".
//
// sizeStr specifies the page size. Acceptable values are "A3", "A4", "A5",
// "Letter", or "Legal". An empty string will be replaced with "A4".
//
// fontDirStr specifies the file system location in which font resources will
// be found. An empty string is replaced with ".". This argument only needs to
// reference an actual directory if a font other than one of the core
// fonts is used. The core fonts are "courier", "helvetica" (also called
// "arial"), "times", and "zapfdingbats" (also called "symbol").
func New(orientationStr, unitStr, sizeStr, fontDirStr string) (f *Fpdf) {
return fpdfNew(orientationStr, unitStr, sizeStr, fontDirStr, SizeType{0, 0})
}
// Ok returns true if no processing errors have occurred.
func (f *Fpdf) Ok() bool {
return f.err == nil
}
// Err returns true if a processing error has occurred.
func (f *Fpdf) Err() bool {
return f.err != nil
}
// SetErrorf sets the internal Fpdf error with formatted text to halt PDF
// generation; this may facilitate error handling by application. If an error
// condition is already set, this call is ignored.
//
// See the documentation for printing in the standard fmt package for details
// about fmtStr and args.
func (f *Fpdf) SetErrorf(fmtStr string, args ...interface{}) {
if f.err == nil {
f.err = fmt.Errorf(fmtStr, args...)
}
}
// String satisfies the fmt.Stringer interface and summarizes the Fpdf
// instance.
func (f *Fpdf) String() string {
return "Fpdf " + cnFpdfVersion
}
// SetError sets an error to halt PDF generation. This may facilitate error
// handling by application. See also Ok(), Err() and Error().
func (f *Fpdf) SetError(err error) {
if f.err == nil && err != nil {
f.err = err
}
}
// Error returns the internal Fpdf error; this will be nil if no error has occurred.
func (f *Fpdf) Error() error {
return f.err
}
// GetPageSize returns the current page's width and height. This is the paper's
// size. To compute the size of the area being used, subtract the margins (see
// GetMargins()).
func (f *Fpdf) GetPageSize() (width, height float64) {
width = f.w
height = f.h
return
}
// GetMargins returns the left, top, right, and bottom margins. The first three
// are set with the SetMargins() method. The bottom margin is set with the
// SetAutoPageBreak() method.
func (f *Fpdf) GetMargins() (left, top, right, bottom float64) {
left = f.lMargin
top = f.tMargin
right = f.rMargin
bottom = f.bMargin
return
}
// SetMargins defines the left, top and right margins. By default, they equal 1
// cm. Call this method to change them. If the value of the right margin is
// less than zero, it is set to the same as the left margin.
func (f *Fpdf) SetMargins(left, top, right float64) {
f.lMargin = left
f.tMargin = top
if right < 0 {
right = left
}
f.rMargin = right
}
// SetLeftMargin defines the left margin. The method can be called before
// creating the first page. If the current abscissa gets out of page, it is
// brought back to the margin.
func (f *Fpdf) SetLeftMargin(margin float64) {
f.lMargin = margin
if f.page > 0 && f.x < margin {
f.x = margin
}
}
// GetCellMargin returns the cell margin. This is the amount of space before
// and after the text within a cell that's left blank, and is in units passed
// to New(). It defaults to 1mm.
func (f *Fpdf) GetCellMargin() float64 {
return f.cMargin
}
// SetCellMargin sets the cell margin. This is the amount of space before and
// after the text within a cell that's left blank, and is in units passed to
// New().
func (f *Fpdf) SetCellMargin(margin float64) {
f.cMargin = margin
}
// SetFontLocation sets the location in the file system of the font and font
// definition files.
func (f *Fpdf) SetFontLocation(fontDirStr string) {
f.fontpath = fontDirStr
}
// SetHeaderFunc sets the function that lets the application render the page
// header. The specified function is automatically called by AddPage() and
// should not be called directly by the application. The implementation in Fpdf
// is empty, so you have to provide an appropriate function if you want page
// headers. fnc will typically be a closure that has access to the Fpdf
// instance and other document generation variables.
func (f *Fpdf) SetHeaderFunc(fnc func()) {
f.headerFnc = fnc
}
// SetFooterFunc sets the function that lets the application render the page
// footer. The specified function is automatically called by AddPage() and
// Close() and should not be called directly by the application. The
// implementation in Fpdf is empty, so you have to provide an appropriate
// function if you want page footers. fnc will typically be a closure that has
// access to the Fpdf instance and other document generation variables.
func (f *Fpdf) SetFooterFunc(fnc func()) {
f.footerFnc = fnc
}
// SetTopMargin defines the top margin. The method can be called before
// creating the first page.
func (f *Fpdf) SetTopMargin(margin float64) {
f.tMargin = margin
}
// SetRightMargin defines the right margin. The method can be called before
// creating the first page.
func (f *Fpdf) SetRightMargin(margin float64) {
f.rMargin = margin
}
// SetAutoPageBreak enables or disables the automatic page breaking mode. When
// enabling, the second parameter is the distance from the bottom of the page
// that defines the triggering limit. By default, the mode is on and the margin
// is 2 cm.
func (f *Fpdf) SetAutoPageBreak(auto bool, margin float64) {
f.autoPageBreak = auto
f.bMargin = margin
f.pageBreakTrigger = f.h - margin
}
// SetDisplayMode defines the way the document is to be displayed by the
// viewer. The zoom level can be set: pages can be displayed entirely on
// screen, occupy the full width of the window, use real size, be scaled by a
// specific zooming factor or use viewer default (configured in the Preferences
// menu of Adobe Reader). The page layout can be specified too: single at once,
// continuous display, two columns or viewer default.
//
// zoomStr can be "fullpage" to display the entire page on screen, "fullwidth"
// to use maximum width of window, "real" to use real size (equivalent to 100%
// zoom) or "default" to use viewer default mode.
//
// layoutStr can be "single" to display one page at once, "continuous" to
// display pages continuously, "two" to display two pages on two columns, or
// "default" to use viewer default mode.
func (f *Fpdf) SetDisplayMode(zoomStr, layoutStr string) {
if f.err != nil {
return
}
if layoutStr == "" {
layoutStr = "default"
}
switch zoomStr {
case "fullpage", "fullwidth", "real", "default":
// || !is_string($zoom))
f.zoomMode = zoomStr
default:
f.err = fmt.Errorf("incorrect zoom display mode: %s", zoomStr)
return
}
switch layoutStr {
case "single", "continuous", "two", "default":
f.layoutMode = layoutStr
default:
f.err = fmt.Errorf("incorrect layout display mode: %s", layoutStr)
return
}
}
// SetCompression activates or deactivates page compression with zlib. When
// activated, the internal representation of each page is compressed, which
// leads to a compression ratio of about 2 for the resulting document.
// Compression is on by default.
func (f *Fpdf) SetCompression(compress bool) {
// if(function_exists('gzcompress'))
f.compress = compress
// else
// $this->compress = false;
}
// SetTitle defines the title of the document. isUTF8 indicates if the string
// is encoded in ISO-8859-1 (false) or UTF-8 (true).
func (f *Fpdf) SetTitle(titleStr string, isUTF8 bool) {
if isUTF8 {
titleStr = utf8toutf16(titleStr)
}
f.title = titleStr
}
// SetSubject defines the subject of the document. isUTF8 indicates if the
// string is encoded in ISO-8859-1 (false) or UTF-8 (true).
func (f *Fpdf) SetSubject(subjectStr string, isUTF8 bool) {
if isUTF8 {
subjectStr = utf8toutf16(subjectStr)
}
f.subject = subjectStr
}
// SetAuthor defines the author of the document. isUTF8 indicates if the string
// is encoded in ISO-8859-1 (false) or UTF-8 (true).
func (f *Fpdf) SetAuthor(authorStr string, isUTF8 bool) {
if isUTF8 {
authorStr = utf8toutf16(authorStr)
}
f.author = authorStr
}
// SetKeywords defines the keywords of the document. keywordStr is a
// space-delimited string, for example "invoice August". isUTF8 indicates if
// the string is encoded
func (f *Fpdf) SetKeywords(keywordsStr string, isUTF8 bool) {
if isUTF8 {
keywordsStr = utf8toutf16(keywordsStr)
}
f.keywords = keywordsStr
}
// SetCreator defines the creator of the document. isUTF8 indicates if the
// string is encoded in ISO-8859-1 (false) or UTF-8 (true).
func (f *Fpdf) SetCreator(creatorStr string, isUTF8 bool) {
if isUTF8 {
creatorStr = utf8toutf16(creatorStr)
}
f.creator = creatorStr
}
// AliasNbPages defines an alias for the total number of pages. It will be
// substituted as the document is closed. An empty string is replaced with the
// string "{nb}". This method is demonstrated in tutorial 2.
func (f *Fpdf) AliasNbPages(aliasStr string) {
if aliasStr == "" {
aliasStr = "{nb}"
}
f.aliasNbPagesStr = aliasStr
}
// Begin document
func (f *Fpdf) open() {
f.state = 1
}
// Close terminates the PDF document. It is not necessary to call this method
// explicitly because Output(), OutputAndClose() and OutputFileAndClose() do it
// automatically. If the document contains no page, AddPage() is called to
// prevent the generation of an invalid document.
func (f *Fpdf) Close() {
if f.err == nil {
if f.clipNest > 0 {
f.err = fmt.Errorf("clip procedure must be explicitly ended")
} else if f.transformNest > 0 {
f.err = fmt.Errorf("transformation procedure must be explicitly ended")
}
}
if f.err != nil {
return
}
if f.state == 3 {
return
}
if f.page == 0 {
f.AddPage()
if f.err != nil {
return
}
}
// Page footer
if f.footerFnc != nil {
f.inFooter = true
f.footerFnc()
f.inFooter = false
}
// Close page
f.endpage()
// Close document
f.enddoc()
return
}
// PageSize returns the width and height of the specified page in the units
// established in New(). These return values are followed by the unit of
// measure itself. If pageNum is zero or otherwise out of bounds, it returns
// the default page size, that is, the size of the page that would be added by
// AddPage(). This function is demonstrated in tutorial 15.
func (f *Fpdf) PageSize(pageNum int) (wd, ht float64, unitStr string) {
sz, ok := f.pageSizes[pageNum]
if ok {
sz.Wd, sz.Ht = sz.Wd/f.k, sz.Ht/f.k
} else {
sz = f.defPageSize // user units
}
return sz.Wd, sz.Ht, f.unitStr
}
// AddPageFormat adds a new page with non-default orientation or size. See
// AddPage() for more details.
//
// See New() for a description of orientationStr.
//
// size specifies the size of the new page in the units established in New().
//
// This function is demonstrated in tutorial 15.
func (f *Fpdf) AddPageFormat(orientationStr string, size SizeType) {
if f.err != nil {
return
}
if f.state == 0 {
f.open()
}
familyStr := f.fontFamily
style := f.fontStyle
if f.underline {
style += "U"
}
fontsize := f.fontSizePt
lw := f.lineWidth
dc := f.color.draw
fc := f.color.fill
tc := f.color.text
cf := f.colorFlag
if f.page > 0 {
// Page footer
if f.footerFnc != nil {
f.inFooter = true
f.footerFnc()
f.inFooter = false
}
// Close page
f.endpage()
}
// Start new page
f.beginpage(orientationStr, size)
// Set line cap style to current value
// f.out("2 J")
f.outf("%d J", f.capStyle)
// Set line width
f.lineWidth = lw
f.outf("%.2f w", lw*f.k)
// Set font
if familyStr != "" {
f.SetFont(familyStr, style, fontsize)
if f.err != nil {
return
}
}
// Set colors
f.color.draw = dc
if dc.str != "0 G" {
f.out(dc.str)
}
f.color.fill = fc
if fc.str != "0 g" {
f.out(fc.str)
}
f.color.text = tc
f.colorFlag = cf
// Page header
if f.headerFnc != nil {
f.inHeader = true
f.headerFnc()
f.inHeader = false
}
// Restore line width
if f.lineWidth != lw {
f.lineWidth = lw
f.outf("%.2f w", lw*f.k)
}
// Restore font
if familyStr != "" {
f.SetFont(familyStr, style, fontsize)
if f.err != nil {
return
}
}
// Restore colors
if f.color.draw.str != dc.str {
f.color.draw = dc
f.out(dc.str)
}
if f.color.fill.str != fc.str {
f.color.fill = fc
f.out(fc.str)
}
f.color.text = tc
f.colorFlag = cf
return
}
// AddPage adds a new page to the document. If a page is already present, the
// Footer() method is called first to output the footer. Then the page is
// added, the current position set to the top-left corner according to the left
// and top margins, and Header() is called to display the header.
//
// The font which was set before calling is automatically restored. There is no
// need to call SetFont() again if you want to continue with the same font. The
// same is true for colors and line width.
//
// The origin of the coordinate system is at the top-left corner and increasing
// ordinates go downwards.
//
// See AddPageFormat() for a version of this method that allows the page size
// and orientation to be different than the default.
func (f *Fpdf) AddPage() {
if f.err != nil {
return
}
// dbg("AddPage")
f.AddPageFormat(f.defOrientation, f.defPageSize)
return
}
// PageNo returns the current page number.
func (f *Fpdf) PageNo() int {
return f.page
}
// SetPage set the new page number and returns the previous page number.
func (f *Fpdf) SetPage(newPage int) int {
oldPage := f.page
f.page = newPage
return oldPage
}
type clrType struct {
r, g, b float64
ir, ig, ib int
gray bool
str string
}
func colorComp(v int) (int, float64) {
if v < 0 {
v = 0
} else if v > 255 {
v = 255
}
return v, float64(v) / 255.0
}
func colorValue(r, g, b int, grayStr, fullStr string) (clr clrType) {
clr.ir, clr.r = colorComp(r)
clr.ig, clr.g = colorComp(g)
clr.ib, clr.b = colorComp(b)
clr.gray = clr.ir == clr.ig && clr.r == clr.b
if len(grayStr) > 0 {
if clr.gray {
clr.str = sprintf("%.3f %s", clr.r, grayStr)
} else {
clr.str = sprintf("%.3f %.3f %.3f %s", clr.r, clr.g, clr.b, fullStr)
}
} else {
clr.str = sprintf("%.3f %.3f %.3f", clr.r, clr.g, clr.b)
}
return
}
// SetDrawColor defines the color used for all drawing operations (lines,
// rectangles and cell borders). It is expressed in RGB components (0 - 255).
// The method can be called before the first page is created and the value is
// retained from page to page.
func (f *Fpdf) SetDrawColor(r, g, b int) {
f.color.draw = colorValue(r, g, b, "G", "RG")
if f.page > 0 {
f.out(f.color.draw.str)
}
}
// GetDrawColor returns the current draw color as RGB components (0 - 255).
func (f *Fpdf) GetDrawColor() (int, int, int) {
return f.color.draw.ir, f.color.draw.ig, f.color.draw.ib
}
// SetFillColor defines the color used for all filling operations (filled
// rectangles and cell backgrounds). It is expressed in RGB components (0
// -255). The method can be called before the first page is created and the
// value is retained from page to page.
func (f *Fpdf) SetFillColor(r, g, b int) {
f.color.fill = colorValue(r, g, b, "g", "rg")
f.colorFlag = f.color.fill.str != f.color.text.str
if f.page > 0 {
f.out(f.color.fill.str)
}
}
// GetFillColor returns the current fill color as RGB components (0 - 255).
func (f *Fpdf) GetFillColor() (int, int, int) {
return f.color.fill.ir, f.color.fill.ig, f.color.fill.ib
}
// SetTextColor defines the color used for text. It is expressed in RGB
// components (0 - 255). The method can be called before the first page is
// created and the value is retained from page to page.
func (f *Fpdf) SetTextColor(r, g, b int) {
f.color.text = colorValue(r, g, b, "g", "rg")
f.colorFlag = f.color.fill.str != f.color.text.str
}
// GetTextColor returns the current text color as RGB components (0 - 255).
func (f *Fpdf) GetTextColor() (int, int, int) {
return f.color.text.ir, f.color.text.ig, f.color.text.ib
}
// GetStringWidth returns the length of a string in user units. A font must be
// currently selected.
func (f *Fpdf) GetStringWidth(s string) float64 {
if f.err != nil {
return 0
}
w := 0
for _, ch := range []byte(s) {
if ch == 0 {
break
}
w += f.currentFont.Cw[ch]
}
return float64(w) * f.fontSize / 1000
}
// SetLineWidth defines the line width. By default, the value equals 0.2 mm.
// The method can be called before the first page is created and the value is
// retained from page to page.
func (f *Fpdf) SetLineWidth(width float64) {
f.lineWidth = width
if f.page > 0 {
f.outf("%.2f w", width*f.k)
}
}
// SetLineCapStyle defines the line cap style. styleStr should be "butt",
// "round" or "square". A square style projects from the end of the line. The
// method can be called before the first page is created and the value is
// retained from page to page.
func (f *Fpdf) SetLineCapStyle(styleStr string) {
var capStyle int
switch styleStr {
case "round":
capStyle = 1
case "square":
capStyle = 2
default:
capStyle = 0
}
if capStyle != f.capStyle {
f.capStyle = capStyle
if f.page > 0 {
f.outf("%d J", f.capStyle)
}
}
}
// Line draws a line between points (x1, y1) and (x2, y2) using the current
// draw color, line width and cap style.
func (f *Fpdf) Line(x1, y1, x2, y2 float64) {
f.outf("%.2f %.2f m %.2f %.2f l S", x1*f.k, (f.h-y1)*f.k, x2*f.k, (f.h-y2)*f.k)
}
func fillDrawOp(styleStr string) (opStr string) {
switch strings.ToUpper(styleStr) {
case "F":
opStr = "f"
case "FD", "DF":
opStr = "B"
default:
opStr = "S"
}
return
}
// Rect outputs a rectangle of width w and height h with the upper left corner
// positioned at point (x, y).
//
// It can be drawn (border only), filled (with no border) or both. styleStr can
// be "F" for filled, "D" for outlined only, or "DF" or "FD" for outlined and
// filled. An empty string will be replaced with "D". Drawing uses the current
// draw color and line width centered on the rectangle's perimeter. Filling
// uses the current fill color.
func (f *Fpdf) Rect(x, y, w, h float64, styleStr string) {
f.outf("%.2f %.2f %.2f %.2f re %s", x*f.k, (f.h-y)*f.k, w*f.k, -h*f.k, fillDrawOp(styleStr))
}
// Circle draws a circle centered on point (x, y) with radius r.
//
// styleStr can be "F" for filled, "D" for outlined only, or "DF" or "FD" for
// outlined and filled. An empty string will be replaced with "D". Drawing uses
// the current draw color and line width centered on the circle's perimeter.
// Filling uses the current fill color.
//
// See tutorial 11 for an example of this function.
func (f *Fpdf) Circle(x, y, r float64, styleStr string) {
f.Ellipse(x, y, r, r, 0, styleStr)
}
// Ellipse draws an ellipse centered at point (x, y). rx and ry specify its
// horizontal and vertical radii.
//
// degRotate specifies the counter-clockwise angle in degrees that the ellipse
// will be rotated.
//
// styleStr can be "F" for filled, "D" for outlined only, or "DF" or "FD" for
// outlined and filled. An empty string will be replaced with "D". Drawing uses
// the current draw color and line width centered on the ellipse's perimeter.
// Filling uses the current fill color.
//
// See tutorial 11 for an example of this function.
func (f *Fpdf) Ellipse(x, y, rx, ry, degRotate float64, styleStr string) {
f.Arc(x, y, rx, ry, degRotate, 0, 360, styleStr)
}
// Polygon draws a closed figure defined by a series of vertices specified by
// points. The x and y fields of the points use the units established in New().
// The last point in the slice will be implicitly joined to the first to close
// the polygon.
//
// styleStr can be "F" for filled, "D" for outlined only, or "DF" or "FD" for
// outlined and filled. An empty string will be replaced with "D". Drawing uses
// the current draw color and line width centered on the ellipse's perimeter.
// Filling uses the current fill color.
//
// See tutorial 25 for an example of this function.
func (f *Fpdf) Polygon(points []PointType, styleStr string) {
if len(points) > 2 {
for j, pt := range points {
if j == 0 {
f.point(pt.X, pt.Y)
} else {
f.outf("%.5f %.5f l ", pt.X*f.k, (f.h-pt.Y)*f.k)
}
}
f.outf("%.5f %.5f l ", points[0].X*f.k, (f.h-points[0].Y)*f.k)
f.outf(fillDrawOp(styleStr))
}
}
// Outputs current point
func (f *Fpdf) point(x, y float64) {
f.outf("%.2f %.2f m", x*f.k, (f.h-y)*f.k)
}
// Outputs quadratic curve from current point
func (f *Fpdf) curve(cx0, cy0, x1, y1, cx1, cy1 float64) {
f.outf("%.5f %.5f %.5f %.5f %.5f %.5f c", cx0*f.k, (f.h-cy0)*f.k, x1*f.k,
(f.h-y1)*f.k, cx1*f.k, (f.h-cy1)*f.k)
}
// Curve draws a single-segment quadratic Bézier curve. The curve starts at
// the point (x0, y0) and ends at the point (x1, y1). The control point (cx,
// cy) specifies the curvature. At the start point, the curve is tangent to the
// straight line between the start point and the control point. At the end
// point, the curve is tangent to the straight line between the end point and
// the control point.
//
// styleStr can be "F" for filled, "D" for outlined only, or "DF" or "FD" for
// outlined and filled. An empty string will be replaced with "D". Drawing uses
// the current draw color, line width, and cap style centered on the curve's
// path. Filling uses the current fill color.
//
// See tutorial 11 for an example of this function.
func (f *Fpdf) Curve(x0, y0, cx, cy, x1, y1 float64, styleStr string) {
f.point(x0, y0)
f.outf("%.5f %.5f %.5f %.5f v %s", cx*f.k, (f.h-cy)*f.k, x1*f.k, (f.h-y1)*f.k,
fillDrawOp(styleStr))
}
// CurveCubic draws a single-segment cubic Bézier curve. The curve starts at
// the point (x0, y0) and ends at the point (x1, y1). The control points (cx0,
// cy0) and (cx1, cy1) specify the curvature. At the start point, the curve is
// tangent to the straight line between the start point and the control point
// (cx0, cy0). At the end point, the curve is tangent to the straight line
// between the end point and the control point (cx1, cy1).
//
// styleStr can be "F" for filled, "D" for outlined only, or "DF" or "FD" for
// outlined and filled. An empty string will be replaced with "D". Drawing uses
// the current draw color, line width, and cap style centered on the curve's
// path. Filling uses the current fill color.
//
// See tutorials 11 and 20 for examples of this function.
func (f *Fpdf) CurveCubic(x0, y0, cx0, cy0, x1, y1, cx1, cy1 float64, styleStr string) {
f.point(x0, y0)
f.outf("%.5f %.5f %.5f %.5f %.5f %.5f c %s", cx0*f.k, (f.h-cy0)*f.k,
cx1*f.k, (f.h-cy1)*f.k, x1*f.k, (f.h-y1)*f.k, fillDrawOp(styleStr))
}
// Arc draws an elliptical arc centered at point (x, y). rx and ry specify its
// horizontal and vertical radii.
//
// degRotate specifies the angle that the arc will be rotated. degStart and
// degEnd specify the starting and ending angle of the arc. All angles are
// specified in degrees and measured counter-clockwise from the 3 o'clock
// position.
//
// styleStr can be "F" for filled, "D" for outlined only, or "DF" or "FD" for
// outlined and filled. An empty string will be replaced with "D". Drawing uses
// the current draw color, line width, and cap style centered on the arc's
// path. Filling uses the current fill color.
//
// See tutorial 11 for an example of this function.
func (f *Fpdf) Arc(x, y, rx, ry, degRotate, degStart, degEnd float64, styleStr string) {
x *= f.k
y = (f.h - y) * f.k
rx *= f.k
ry *= f.k
segments := int(degEnd-degStart) / 60
if segments < 2 {
segments = 2
}
angleStart := degStart * math.Pi / 180
angleEnd := degEnd * math.Pi / 180
angleTotal := angleEnd - angleStart
dt := angleTotal / float64(segments)
dtm := dt / 3
if degRotate != 0 {
a := -degRotate * math.Pi / 180
f.outf("q %.5f %.5f %.5f %.5f %.5f %.5f cm", math.Cos(a), -1*math.Sin(a),
math.Sin(a), math.Cos(a), x, y)
x = 0
y = 0
}
t := angleStart
a0 := x + rx*math.Cos(t)
b0 := y + ry*math.Sin(t)
c0 := -rx * math.Sin(t)
d0 := ry * math.Cos(t)
f.point(a0/f.k, f.h-(b0/f.k))
for j := 1; j <= segments; j++ {
// Draw this bit of the total curve
t = (float64(j) * dt) + angleStart
a1 := x + rx*math.Cos(t)
b1 := y + ry*math.Sin(t)
c1 := -rx * math.Sin(t)
d1 := ry * math.Cos(t)
f.curve((a0+(c0*dtm))/f.k,
f.h-((b0+(d0*dtm))/f.k),
(a1-(c1*dtm))/f.k,
f.h-((b1-(d1*dtm))/f.k),
a1/f.k,
f.h-(b1/f.k))
a0 = a1
b0 = b1
c0 = c1
d0 = d1
}
f.out(fillDrawOp(styleStr))
if degRotate != 0 {
f.out("Q")
}
}
// SetAlpha sets the alpha blending channel. The blending effect applies to
// text, drawings and images.
//
// alpha must be a value between 0.0 (fully transparent) to 1.0 (fully opaque).
// Values outside of this range result in an error.
//
// blendModeStr must be one of "Normal", "Multiply", "Screen", "Overlay",
// "Darken", "Lighten", "ColorDodge", "ColorBurn","HardLight", "SoftLight",
// "Difference", "Exclusion", "Hue", "Saturation", "Color", or "Luminosity". An
// empty string is replaced with "Normal".
//
// To reset normal rendering after applying a blending mode, call this method
// with alpha set to 1.0 and blendModeStr set to "Normal".
//
// See tutorial 12 for an example of this function, including samples of each blending mode.
func (f *Fpdf) SetAlpha(alpha float64, blendModeStr string) {
if f.err != nil {
return
}
var bl blendModeType
switch blendModeStr {
case "Normal", "Multiply", "Screen", "Overlay",
"Darken", "Lighten", "ColorDodge", "ColorBurn", "HardLight", "SoftLight",
"Difference", "Exclusion", "Hue", "Saturation", "Color", "Luminosity":
bl.modeStr = blendModeStr
case "":
bl.modeStr = "Normal"
default:
f.err = fmt.Errorf("unrecognized blend mode \"%s\"", blendModeStr)