forked from pdfcpu/pdfcpu
/
stamp.go
1394 lines (1087 loc) · 29.7 KB
/
stamp.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 2018 The pdfcpu Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package pdfcpu
import (
"bytes"
"fmt"
"math"
"path/filepath"
"strconv"
"strings"
"github.com/hhrutter/pdfcpu/pkg/filter"
"github.com/hhrutter/pdfcpu/pkg/log"
"github.com/hhrutter/pdfcpu/pkg/pdfcpu/fonts/metrics"
"github.com/pkg/errors"
)
const (
degToRad = math.Pi / 180
radToDeg = 180 / math.Pi
)
type matrix [3][3]float64
var errNoContent = errors.New("PDF page has no content")
var identMatrix = matrix{{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}
func (m matrix) multiply(n matrix) matrix {
var p matrix
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
for k := 0; k < 3; k++ {
p[i][j] += m[i][k] * n[k][j]
}
}
}
return p
}
func (m matrix) String() string {
return fmt.Sprintf("%3.2f %3.2f %3.2f\n%3.2f %3.2f %3.2f\n%3.2f %3.2f %3.2f\n",
m[0][0], m[0][1], m[0][2],
m[1][0], m[1][1], m[1][2],
m[2][0], m[2][1], m[2][2])
}
type simpleColor struct {
r, g, b float32 // intensities between 0 and 1.
}
func (sc simpleColor) String() string {
return fmt.Sprintf("r=%1.1f g=%1.1f b=%1.1f", sc.r, sc.g, sc.b)
}
const (
noDiagonal = iota
diagonalLLToUR
diagonalULToLR
)
// render mode
const (
rmFill = iota
rmStroke
rmFillAndStroke
)
type formCache map[*Rectangle]*IndirectRef
// Watermark represents the basic structure and command details for the commands "Stamp" and "Watermark".
type Watermark struct {
// configuration
text string // display text.
fileName string // display pdf page or png image.
page int // the page number of a PDF file.
onTop bool // if true this is a STAMP else this is a WATERMARK.
fontName string // supported are Adobe base fonts only. (as of now: Helvetica, Times-Roman, Courier)
fontSize int // font scaling factor.
color simpleColor // fill color(=non stroking color).
rotation float64 // rotation to apply in degrees. -180 <= x <= 180
diagonal int // paint along the diagonal.
opacity float64 // opacity the displayed text. 0 <= x <= 1
renderMode int // fill=0, stroke=1 fill&stroke=2
scale float64 // relative scale factor. 0 <= x <= 1
scaleAbs bool // true for absolute scaling.
// resources
ocg, extGState, font, image *IndirectRef
// for an image or PDF watermark
width, height int // image or page dimensions.
// for a PDF watermark
resDict *IndirectRef // page resource dict.
cs []byte // page content stream.
// page specific
bb *Rectangle // bounding box of the form representing this watermark.
vp *Rectangle // page dimensions for text alignment.
pageRot float64 // page rotation in effect.
form *IndirectRef // Forms are dependent on given page dimensions.
// house keeping
objs IntSet // objects for which wm has been applied already.
fCache formCache // form cache.
}
func (wm Watermark) typ() string {
if wm.isImage() {
return "image"
}
if wm.isPDF() {
return "pdf"
}
return "text"
}
func (wm Watermark) String() string {
var s string
if !wm.onTop {
s = "not "
}
t := wm.text
if len(t) == 0 {
t = wm.fileName
}
sc := "relative"
if wm.scaleAbs {
sc = "absolute"
}
return fmt.Sprintf("Watermark: <%s> is %son top, typ:%s\n"+
"%s %d points\n"+
"PDFpage#: %d\n"+
"scaling: %.1f %s\n"+
"color: %s\n"+
"rotation: %.1f\n"+
"diagonal: %d\n"+
"opacity: %.1f\n"+
"renderMode: %d\n"+
"bbox:%s\n"+
"vp:%s\n"+
"pageRotation: %.1f\n",
t, s, wm.typ(),
wm.fontName, wm.fontSize,
wm.page,
wm.scale, sc,
wm.color,
wm.rotation,
wm.diagonal,
wm.opacity,
wm.renderMode,
*wm.bb,
*wm.vp,
wm.pageRot,
)
}
// OnTopString returns "watermark" or "stamp" whichever applies.
func (wm Watermark) OnTopString() string {
s := "watermark"
if wm.onTop {
s = "stamp"
}
return s
}
// IsPDF returns whether the watermark content is an image or text.
func (wm Watermark) isPDF() bool {
return len(wm.fileName) > 0 && strings.ToLower(filepath.Ext(wm.fileName)) == ".pdf"
}
// IsImage returns whether the watermark content is an image or text.
func (wm Watermark) isImage() bool {
return len(wm.fileName) > 0 && strings.ToLower(filepath.Ext(wm.fileName)) != ".pdf"
}
func (wm *Watermark) calcBoundingBox() {
//fmt.Println("calcBoundingBox:")
var bb *Rectangle
if wm.isImage() || wm.isPDF() {
bb = RectForDim(wm.width, wm.height)
ar := bb.AspectRatio()
//fmt.Printf("calcBB: ar:%f scale:%f\n", ar, wm.scale)
//fmt.Printf("vp: %s\n", wm.vp)
if wm.scaleAbs {
bb.UR.X = wm.scale * bb.Width()
bb.UR.Y = bb.UR.X / ar
wm.bb = bb
return
}
if ar >= 1 {
bb.UR.X = wm.scale * wm.vp.Width()
bb.UR.Y = bb.UR.X / ar
//fmt.Printf("ar>1: %s\n", bb)
} else {
bb.UR.Y = wm.scale * wm.vp.Height()
bb.UR.X = bb.UR.Y * ar
//fmt.Printf("ar<=1: %s\n", bb)
}
wm.bb = bb
return
}
// font watermark
var w float64
if wm.scaleAbs {
wm.fontSize = int(float64(wm.fontSize) * wm.scale)
w = metrics.TextWidth(wm.text, wm.fontName, wm.fontSize)
} else {
w = wm.scale * wm.vp.Width()
wm.fontSize = metrics.FontSize(wm.text, wm.fontName, w)
}
wm.bb = Rect(0, -float64(wm.fontSize), w, float64(wm.fontSize)/10)
return
}
func (wm *Watermark) calcTransformMatrix() *matrix {
var sin, cos float64
r := wm.rotation
if wm.diagonal != noDiagonal {
// Calculate the angle of the diagonal with respect of the aspect ratio of the bounding box.
r = math.Atan(wm.vp.Height()/wm.vp.Width()) * float64(radToDeg)
if wm.bb.AspectRatio() < 1 {
r -= 90
}
if wm.diagonal == diagonalULToLR {
r = -r
}
}
// Apply negative page rotation.
r += wm.pageRot
sin = math.Sin(float64(r) * float64(degToRad))
cos = math.Cos(float64(r) * float64(degToRad))
// 1) Rotate
m1 := identMatrix
m1[0][0] = cos
m1[0][1] = sin
m1[1][0] = -sin
m1[1][1] = cos
// 2) Translate
m2 := identMatrix
var dy float64
if !wm.isImage() && !wm.isPDF() {
dy = wm.bb.LL.Y
}
m2[2][0] = wm.vp.Width()/2 + sin*(wm.bb.Height()/2+dy) - cos*wm.bb.Width()/2
m2[2][1] = wm.vp.Height()/2 - cos*(wm.bb.Height()/2+dy) - sin*wm.bb.Width()/2
m := m1.multiply(m2)
return &m
}
func onTopString(onTop bool) string {
e := "watermark"
if onTop {
e = "stamp"
}
return e
}
func parseWatermarkError(onTop bool) error {
s := onTopString(onTop)
return errors.Errorf("Invalid %s configuration string. Please consult pdfcpu help %s.\n", s, s)
}
func oneWatermarkOnlyError(onTop bool) error {
s := onTopString(onTop)
return errors.Errorf("Cannot apply %s. Only one watermark/stamp allowed.\n", s)
}
func setWatermarkType(s string, wm *Watermark) error {
ss := strings.Split(s, ":")
wm.text = ss[0]
ext := strings.ToLower(filepath.Ext(ss[0]))
if MemberOf(ext, []string{".jpg", ".jpeg", ".png", ".tif", ".tiff", ".pdf"}) {
wm.fileName = ss[0]
}
if len(ss) > 1 {
var err error
wm.page, err = strconv.Atoi(ss[1])
if err != nil {
return errors.Errorf("illegal page number value: %s\n", ss[1])
}
}
return nil
}
func supportedWatermarkFont(fn string) bool {
for _, s := range metrics.FontNames() {
if fn == s {
return true
}
}
return false
}
func parseWatermarkFontSize(s string, wm *Watermark) error {
fs, err := strconv.Atoi(s)
if err != nil {
return err
}
wm.fontSize = fs
return nil
}
func parseScaleFactor(s string) (float64, bool, error) {
ss := strings.Split(s, " ")
if len(ss) > 2 {
return 0, false, errors.Errorf("illegal scale string: 0.0 <= i <= 1.0 {abs|rel}, %s\n", s)
}
sc, err := strconv.ParseFloat(ss[0], 64)
if err != nil {
return 0, false, errors.Errorf("scale factor must be a float value: %s\n", ss[0])
}
if sc < 0 || sc > 1 {
return 0, false, errors.Errorf("illegal scale factor: 0.0 <= s <= 1.0, %s\n", ss[0])
}
var scaleAbs bool
if len(ss) == 2 {
switch ss[1] {
case "a", "abs":
scaleAbs = true
case "r", "rel":
scaleAbs = false
default:
return 0, false, errors.Errorf("illegal scale mode: abs|rel, %s\n", ss[1])
}
}
return sc, scaleAbs, nil
}
func parseWatermarkColor(s string, wm *Watermark) error {
cs := strings.Split(s, " ")
if len(cs) != 3 {
return errors.Errorf("illegal color string: 3 intensities 0.0 <= i <= 1.0, %s\n", s)
}
r, err := strconv.ParseFloat(cs[0], 32)
if err != nil {
return errors.Errorf("red must be a float value: %s\n", cs[0])
}
if r < 0 || r > 1 {
return errors.New("red: a color value is an intensity between 0.0 and 1.0")
}
wm.color.r = float32(r)
g, err := strconv.ParseFloat(cs[1], 32)
if err != nil {
return errors.Errorf("green must be a float value: %s\n", cs[1])
}
if g < 0 || g > 1 {
return errors.New("green: a color value is an intensity between 0.0 and 1.0")
}
wm.color.g = float32(g)
b, err := strconv.ParseFloat(cs[2], 32)
if err != nil {
return errors.Errorf("blue must be a float value: %s\n", cs[2])
}
if b < 0 || b > 1 {
return errors.New("blue: a color value is an intensity between 0.0 and 1.0")
}
wm.color.b = float32(b)
return nil
}
func parseWatermarkRotation(s string, setDiag bool, wm *Watermark) error {
if setDiag {
return errors.New("Please specify rotation or diagonal (r or d)")
}
r, err := strconv.ParseFloat(s, 64)
if err != nil {
return errors.Errorf("rotation must be a float value: %s\n", s)
}
if r < -180 || r > 180 {
return errors.Errorf("illegal rotation: -180 <= r <= 180 degrees, %s\n", s)
}
wm.rotation = r
wm.diagonal = noDiagonal
return nil
}
func parseWatermarkDiagonal(s string, setRot bool, wm *Watermark) error {
if setRot {
return errors.New("Please specify rotation or diagonal (r or d)")
}
d, err := strconv.Atoi(s)
if err != nil {
return errors.Errorf("illegal diagonal value: allowed 1 or 2, %s\n", s)
}
if d != diagonalLLToUR && d != diagonalULToLR {
return errors.New("diagonal: 1..lower left to upper right, 2..upper left to lower right")
}
wm.diagonal = d
wm.rotation = 0
return nil
}
func parseWatermarkOpacity(s string, wm *Watermark) error {
o, err := strconv.ParseFloat(s, 64)
if err != nil {
return errors.Errorf("opacity must be a float value: %s\n", s)
}
if o < 0 || o > 1 {
return errors.Errorf("illegal opacity: 0.0 <= r <= 1.0, %s\n", s)
}
wm.opacity = o
return nil
}
func parseWatermarkRenderMode(s string, wm *Watermark) error {
m, err := strconv.Atoi(s)
if err != nil {
return errors.Errorf("illegal mode value: allowed 0,1,2, %s\n", s)
}
if m != rmFill && m != rmStroke && m != rmFillAndStroke {
return errors.New("Valid rendermodes: 0..fill, 1..stroke, 2..fill&stroke")
}
wm.renderMode = m
return nil
}
// ParseWatermarkDetails parses a Watermark/Stamp command string into an internal structure.
func ParseWatermarkDetails(s string, onTop bool) (*Watermark, error) {
//fmt.Printf("watermark details: <%s>\n", s)
// Set default watermark
wm := Watermark{
onTop: onTop,
page: 1,
fontName: "Helvetica",
fontSize: 24,
scale: 0.5,
scaleAbs: false,
color: simpleColor{0.5, 0.5, 0.5}, // gray
diagonal: diagonalLLToUR,
opacity: 1.0,
renderMode: rmFill,
objs: IntSet{},
fCache: formCache{},
}
ss := strings.Split(s, ",")
setWatermarkType(ss[0], &wm)
if len(ss) == 1 {
return &wm, nil
}
var setDiag, setRot bool
for _, s := range ss[1:] {
ss1 := strings.Split(s, ":")
if len(ss1) != 2 {
return nil, parseWatermarkError(onTop)
}
k := strings.TrimSpace(ss1[0])
v := strings.TrimSpace(ss1[1])
//fmt.Printf("key:<%s> value<%s>\n", k, v)
var err error
switch k {
case "f": // font name
if !supportedWatermarkFont(v) {
err = errors.Errorf("%s is unsupported, try one of Helvetica, Times-Roman, Courier.\n", v)
}
wm.fontName = v
case "p": // font size in points
err = parseWatermarkFontSize(v, &wm)
case "s": // scale factor
wm.scale, wm.scaleAbs, err = parseScaleFactor(v)
case "c": // color
err = parseWatermarkColor(v, &wm)
case "r": // rotation
err = parseWatermarkRotation(v, setDiag, &wm)
setRot = true
case "d": // diagonal
err = parseWatermarkDiagonal(v, setRot, &wm)
setDiag = true
case "o": // opacity
err = parseWatermarkOpacity(v, &wm)
case "m": // render mode
err = parseWatermarkRenderMode(v, &wm)
default:
err = parseWatermarkError(onTop)
}
if err != nil {
return nil, err
}
}
return &wm, nil
}
func createFontResForWM(xRefTable *XRefTable, wm *Watermark) error {
d := NewDict()
d.InsertName("Type", "Font")
d.InsertName("Subtype", "Type1")
d.InsertName("BaseFont", wm.fontName)
ir, err := xRefTable.IndRefForNewObject(d)
if err != nil {
return err
}
wm.font = ir
return nil
}
func contentStream(xRefTable *XRefTable, o Object) ([]byte, error) {
o, err := xRefTable.Dereference(o)
if err != nil {
return nil, err
}
bb := []byte{}
switch o := o.(type) {
case StreamDict:
// Decode streamDict for supported filters only.
err := decodeStream(&o)
if err == filter.ErrUnsupportedFilter {
return nil, errors.New("unsupported filter: unable to decode content for PDF watermark")
}
if err != nil {
return nil, err
}
//fmt.Printf("found %d content bytes\n", len(o.Content))
bb = o.Content
case Array:
for _, o := range o {
if o == nil {
continue
}
sd, err := xRefTable.DereferenceStreamDict(o)
if err != nil {
return nil, err
}
// Decode streamDict for supported filters only.
err = decodeStream(sd)
if err == filter.ErrUnsupportedFilter {
return nil, errors.New("unsupported filter: unable to decode content for PDF watermark")
}
if err != nil {
return nil, err
}
//fmt.Printf("append %d content bytes\n", len(sd.Content))
bb = append(bb, sd.Content...)
//fmt.Printf("len bb = %d\n", len(bb))
}
}
if len(bb) == 0 {
return nil, errNoContent
}
return bb, nil
}
func identifyObjNrs(ctx *Context, o Object, objNrs IntSet) error {
switch o := o.(type) {
case IndirectRef:
objNrs[o.ObjectNumber.Value()] = true
o1, err := ctx.Dereference(o)
if err != nil {
return err
}
err = identifyObjNrs(ctx, o1, objNrs)
if err != nil {
return err
}
case Dict:
for _, v := range o {
err := identifyObjNrs(ctx, v, objNrs)
if err != nil {
return err
}
}
case StreamDict:
for _, v := range o.Dict {
err := identifyObjNrs(ctx, v, objNrs)
if err != nil {
return err
}
}
case Array:
for _, v := range o {
err := identifyObjNrs(ctx, v, objNrs)
if err != nil {
return err
}
}
}
return nil
}
func migrateObject(ctxSource, ctxDest *Context, o Object) error {
//fmt.Printf("migrateObject start %s\n", o)
// Identify involved objNrs.
objNrs := IntSet{}
err := identifyObjNrs(ctxSource, o, objNrs)
if err != nil {
return err
}
//fmt.Printf("objNrs = %v\n", objNrs)
// Create a lookup table mapping objNrs from ctxSource to ctxDest.
// Create lookup table for object numbers.
// The first number is the successor of the last number in ctxDest.
lookup := lookupTable(objNrs, *ctxDest.Size)
//fmt.Printf("lookup = %v\n", lookup)
// Patch indRefs of resourceDict.
patchObject(o, lookup)
//fmt.Printf("o(resDict) patched: %s\n", o)
// Patch all involved indRefs.
for i := range lookup {
//fmt.Printf("before patching old obj %d\n%s\n", i, ctxSource.Table[i].Object)
patchObject(ctxSource.Table[i].Object, lookup)
//fmt.Printf("after patching old obj\n%s\n", ctxSource.Table[i].Object)
}
// Migrate xrefTableEntries.
for k, v := range lookup {
//fmt.Printf("dest[%d]=src[%d]\n", v, k)
ctxDest.Table[v] = ctxSource.Table[k]
*ctxDest.Size++
}
//fmt.Printf("migrateObject end %s\n", o)
return nil
}
func createPDFResForWM(ctx *Context, wm *Watermark) error {
xRefTable := ctx.XRefTable
// This PDF file is assumed to be valid.
otherCtx, err := ReadFile(wm.fileName, NewDefaultConfiguration())
if err != nil {
return err
}
otherXRefTable := otherCtx.XRefTable
d, inhPAttrs, err := otherXRefTable.PageDict(wm.page)
if err != nil {
return err
}
if d == nil {
return errors.Errorf("unknown page number: %d\n", wm.page)
}
// Retrieve content stream bytes.
o, found := d.Find("Contents")
if !found {
return errors.New("PDF page has no content")
}
wm.cs, err = contentStream(otherXRefTable, o)
if err != nil {
return err
}
// Migrate all objects referenced by this external resource dict into this context.
err = migrateObject(otherCtx, ctx, inhPAttrs.resources)
if err != nil {
return err
}
//fmt.Printf("migrated resDict inhPAttrs.resources %s\n", inhPAttrs.resources)
// Create an object for this resDict in xRefTable.
ir, err := xRefTable.IndRefForNewObject(inhPAttrs.resources)
if err != nil {
return err
}
wm.resDict = ir
vp := viewPort(xRefTable, inhPAttrs)
//fmt.Printf("createPDFResForWM: vp = %s\n", vp)
wm.width = int(vp.Width())
wm.height = int(vp.Height())
return nil
}
func createImageResource(xRefTable *XRefTable, fileName string) (*IndirectRef, int, int, error) {
ext := strings.ToLower(filepath.Ext(fileName))
var f func(xRefTable *XRefTable, fileName string) (*StreamDict, error)
switch ext {
case ".png":
f = ReadPNGFile
case ".jpg", ".jpeg":
f = ReadJPEGFile
case ".tif", ".tiff":
f = ReadTIFFFile
default:
return nil, 0, 0, errors.Errorf("unsupported imagefile extension: %s", ext)
}
sd, err := f(xRefTable, fileName)
if err != nil {
return nil, 0, 0, err
}
w := *sd.IntEntry("Width")
h := *sd.IntEntry("Height")
indRef, err := xRefTable.IndRefForNewObject(*sd)
if err != nil {
return nil, 0, 0, err
}
return indRef, w, h, nil
}
func createImageResForWM(xRefTable *XRefTable, wm *Watermark) (err error) {
wm.image, wm.width, wm.height, err = createImageResource(xRefTable, wm.fileName)
return err
}
func createResourcesForWM(ctx *Context, wm *Watermark) error {
log.Debug.Println("createResourcesForWM begin")
xRefTable := ctx.XRefTable
if wm.isPDF() {
return createPDFResForWM(ctx, wm)
}
if wm.isImage() {
return createImageResForWM(xRefTable, wm)
}
return createFontResForWM(xRefTable, wm)
}
func createOCG(xRefTable *XRefTable, wm *Watermark) error {
name := "Background"
subt := "BG"
if wm.onTop {
name = "Watermark"
subt = "FG"
}
d := Dict(
map[string]Object{
"Name": StringLiteral(name),
"Type": Name("OCG"),
"Usage": Dict(
map[string]Object{
"PageElement": Dict(map[string]Object{"Subtype": Name(subt)}),
"View": Dict(map[string]Object{"ViewState": Name("ON")}),
"Print": Dict(map[string]Object{"PrintState": Name("ON")}),
"Export": Dict(map[string]Object{"ExportState": Name("ON")}),
},
),
},
)
ir, err := xRefTable.IndRefForNewObject(d)
if err != nil {
return err
}
wm.ocg = ir
return nil
}
func prepareOCPropertiesInRoot(rootDict Dict, wm *Watermark) error {
optionalContentConfigDict := Dict(
map[string]Object{
"AS": Array{
Dict(
map[string]Object{
"Category": NewNameArray("View"),
"Event": Name("View"),
"OCGs": Array{*wm.ocg},
},
),
Dict(
map[string]Object{
"Category": NewNameArray("Print"),
"Event": Name("Print"),
"OCGs": Array{*wm.ocg},
},
),
Dict(
map[string]Object{
"Category": NewNameArray("Export"),
"Event": Name("Export"),
"OCGs": Array{*wm.ocg},
},
),
},
"ON": Array{*wm.ocg},
"Order": Array{},
"RBGroups": Array{},
},
)
d := Dict(
map[string]Object{
"OCGs": Array{*wm.ocg},
"D": optionalContentConfigDict,
},
)
_, ok := rootDict.Find("OCProperties")
if !ok {
rootDict.Insert("OCProperties", d)
return nil
}
return oneWatermarkOnlyError(wm.onTop)
}
func createFormResDict(xRefTable *XRefTable, wm *Watermark) (*IndirectRef, error) {
if wm.isPDF() {
//return consolidated ResDict of for PDF/PageBoxColorInfo
return wm.resDict, nil
}
if wm.isImage() {
d := Dict(
map[string]Object{
"ProcSet": NewNameArray("PDF", "ImageC"),
"XObject": Dict(map[string]Object{"Im0": *wm.image}),
},
)
return xRefTable.IndRefForNewObject(d)
}
d := Dict(
map[string]Object{
"Font": Dict(map[string]Object{wm.fontName: *wm.font}),
"ProcSet": NewNameArray("PDF", "Text"),
},
)
return xRefTable.IndRefForNewObject(d)
}
func createForm(xRefTable *XRefTable, wm *Watermark, withBB bool) error {
// The forms bounding box is dependent on the page dimensions.
wm.calcBoundingBox()
bb := wm.bb
// Cache the form for every bounding box encountered.
ir, ok := wm.fCache[bb]
if ok {
//fmt.Printf("reusing form obj#%d\n", ir.ObjectNumber)
wm.form = ir
return nil
}
var b bytes.Buffer
if wm.isPDF() {
fmt.Fprintf(&b, "%f 0 0 %f 0 0 cm ", bb.Width()/wm.vp.Width(), bb.Height()/wm.vp.Height())
_, err := b.Write(wm.cs)
if err != nil {
return err
}
} else if wm.isImage() {
fmt.Fprintf(&b, "q %f 0 0 %f 0 0 cm /Im0 Do Q", bb.Width(), bb.Height())
} else {
// 12 font points result in a vertical displacement of 9.47
dy := -float64(wm.fontSize) / 12 * 9.47
wmForm := "0 g 0 G 0 i 0 J []0 d 0 j 1 w 10 M 0 Tc 0 Tw 100 Tz 0 TL %d Tr 0 Ts BT /%s %d Tf %f %f %f rg 0 %f Td (%s)Tj ET"
fmt.Fprintf(&b, wmForm, wm.renderMode, wm.fontName, wm.fontSize, wm.color.r, wm.color.g, wm.color.b, dy, wm.text)
}