forked from pdfcpu/pdfcpu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
textField.go
749 lines (629 loc) · 16 KB
/
textField.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
/*
Copyright 2021 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 primitives
import (
"bytes"
"fmt"
"unicode/utf8"
"github.com/lanceInGz/pdfcpu/pkg/font"
"github.com/lanceInGz/pdfcpu/pkg/pdfcpu"
"github.com/pkg/errors"
)
// FieldFlags represents the PDF form field flags.
type FieldFlags int
const ( // See table 221 et.al.
FieldReadOnly FieldFlags = 1 << iota
FieldRequired
FieldNoExport
UnusedFlag4
UnusedFlag5
UnusedFlag6
UnusedFlag7
UnusedFlag8
UnusedFlag9
UnusedFlag10
UnusedFlag11
UnusedFlag12
FieldMultiline
FieldPassword
FieldNoToggleToOff
FieldRadio
FieldPushbutton
FieldCombo
FieldEdit
FieldSort
FieldFileSelect
FieldMultiselect
FieldDoNotSpellCheck
FieldDoNotScroll
FieldComb
FieldRichTextAndRadiosInUnison
FieldCommitOnSelChange
)
type TextField struct {
pdf *PDF
content *Content
Label *TextFieldLabel
ID string
Value string
Position [2]float64 `json:"pos"` // x,y
x, y float64
Width float64
Height float64
Dx, Dy float64
boundingBox *pdfcpu.Rectangle
Multiline bool
Font *FormFont // optional
Margin *Margin // applied to content box
Border *Border
BackgroundColor string `json:"bgCol"`
bgCol *pdfcpu.SimpleColor
Alignment string `json:"align"` // "Left", "Center", "Right"
horAlign pdfcpu.HAlignment
RTL bool
Rotation float64 `json:"rot"`
Hide bool
}
func (tf *TextField) validateID() error {
if tf.ID == "" {
return errors.New("pdfcpu: missing field id")
}
if tf.pdf.FieldIDs[tf.ID] {
return errors.Errorf("pdfcpu: duplicate form field: %s", tf.ID)
}
tf.pdf.FieldIDs[tf.ID] = true
return nil
}
func (tf *TextField) validatePosition() error {
if tf.Position[0] < 0 || tf.Position[1] < 0 {
return errors.Errorf("pdfcpu: field: %s pos value < 0", tf.ID)
}
tf.x, tf.y = tf.Position[0], tf.Position[1]
return nil
}
func (tf *TextField) validateWidth() error {
if tf.Width <= 0 {
return errors.Errorf("pdfcpu: field: %s width <= 0", tf.ID)
}
return nil
}
func (tf *TextField) validateHeight() error {
if tf.Height < 0 {
return errors.Errorf("pdfcpu: field: %s height < 0", tf.ID)
}
return nil
}
func (tf *TextField) validateFont() error {
if tf.Font != nil {
tf.Font.pdf = tf.pdf
if err := tf.Font.validate(); err != nil {
return err
}
}
return nil
}
func (tf *TextField) validateMargin() error {
if tf.Margin != nil {
if err := tf.Margin.validate(); err != nil {
return err
}
}
return nil
}
func (tf *TextField) validateBorder() error {
if tf.Border != nil {
tf.Border.pdf = tf.pdf
if err := tf.Border.validate(); err != nil {
return err
}
}
return nil
}
func (tf *TextField) validateBackgroundColor() error {
if tf.BackgroundColor != "" {
sc, err := tf.pdf.parseColor(tf.BackgroundColor)
if err != nil {
return err
}
tf.bgCol = sc
}
return nil
}
func (tf *TextField) validateHorAlign() error {
tf.horAlign = pdfcpu.AlignLeft
if tf.Alignment != "" {
ha, err := pdfcpu.ParseHorAlignment(tf.Alignment)
if err != nil {
return err
}
tf.horAlign = ha
}
return nil
}
func (tf *TextField) validateLabel() error {
if tf.Label != nil {
tf.Label.pdf = tf.pdf
if err := tf.Label.validate(); err != nil {
return err
}
}
return nil
}
func (tf *TextField) validate() error {
if err := tf.validateID(); err != nil {
return err
}
if err := tf.validatePosition(); err != nil {
return err
}
if err := tf.validateWidth(); err != nil {
return err
}
if err := tf.validateHeight(); err != nil {
return err
}
if err := tf.validateFont(); err != nil {
return err
}
if err := tf.validateMargin(); err != nil {
return err
}
if err := tf.validateBorder(); err != nil {
return err
}
if err := tf.validateBackgroundColor(); err != nil {
return err
}
if err := tf.validateHorAlign(); err != nil {
return err
}
return tf.validateLabel()
}
func (tf *TextField) font(name string) *FormFont {
return tf.content.namedFont(name)
}
func (tf *TextField) margin(name string) *Margin {
return tf.content.namedMargin(name)
}
func (tf *TextField) labelPos(labelHeight, w, g float64) (float64, float64) {
var x, y float64
bb, horAlign := tf.boundingBox, tf.Label.horAlign
switch tf.Label.relPos {
case pdfcpu.RelPosLeft:
x = bb.LL.X - g
if horAlign == pdfcpu.AlignLeft {
x -= w
if x < 0 {
x = 0
}
}
if tf.Multiline {
y = bb.UR.Y - labelHeight
} else {
y = bb.LL.Y
}
case pdfcpu.RelPosRight:
x = bb.UR.X + g
if horAlign == pdfcpu.AlignRight {
x += w
}
if tf.Multiline {
y = bb.UR.Y - labelHeight
} else {
y = bb.LL.Y
}
case pdfcpu.RelPosTop:
y = bb.UR.Y + g
x = bb.LL.X
if horAlign == pdfcpu.AlignRight {
x += bb.Width()
} else if horAlign == pdfcpu.AlignCenter {
x += bb.Width() / 2
}
case pdfcpu.RelPosBottom:
y = bb.LL.Y - g - labelHeight
x = bb.LL.X
if horAlign == pdfcpu.AlignRight {
x += bb.Width()
} else if horAlign == pdfcpu.AlignCenter {
x += bb.Width() / 2
}
}
return x, y
}
func (tf *TextField) renderLabel(r *pdfcpu.Rectangle, p *pdfcpu.Page, pageNr int, fonts pdfcpu.FontMap, fontSize int) error {
if tf.Label == nil {
return nil
}
l := tf.Label
pdf := tf.pdf
t := "Default"
if l.Value != "" {
t, _ = pdfcpu.ResolveWMTextString(l.Value, pdf.TimestampFormat, pageNr, pdf.pageCount())
}
w := float64(l.Width)
g := float64(l.Gap)
var f *FormFont
if l.Font != nil {
f = l.Font
if f.Name[0] == '$' {
// use named font
fName := f.Name[1:]
f0 := tf.font(fName)
if f0 == nil {
return errors.Errorf("pdfcpu: unknown font name %s", fName)
}
f.Name = f0.Name
if f.Size == 0 {
f.Size = f0.Size
}
if f.col == nil {
f.col = f0.col
}
}
} else {
// Use inherited named font "label".
f = tf.font("label")
if f == nil {
return errors.Errorf("pdfcpu: missing named font \"label\"")
}
}
if f.col == nil {
f.col = &pdfcpu.Black
}
fontName := f.Name
// Enforce input fontSize.
//fontSize := f.Size
col := f.col
id, err := tf.pdf.idForFontName(fontName, p.Fm, fonts, pageNr)
if err != nil {
return err
}
td := pdfcpu.TextDescriptor{
Text: t,
FontName: fontName,
FontKey: id,
FontSize: fontSize,
Scale: 1.,
ScaleAbs: true,
RTL: l.RTL, // for user fonts only!
}
if col != nil {
td.StrokeCol, td.FillCol = *col, *col
}
if l.bgCol != nil {
//td.ShowBorder = true
td.ShowBackground, td.ShowTextBB, td.BackgroundCol = true, true, *l.bgCol
}
// TODO Ensure bb.Height = tf.boundingBox.Height() with td.Height = tf.boundingBox.Height() ???
bb := pdfcpu.WriteMultiLine(new(bytes.Buffer), pdfcpu.RectForFormat("A4"), nil, td)
td.X, td.Y = tf.labelPos(bb.Height(), w, g)
if !tf.Multiline && bb.Height() < tf.boundingBox.Height() {
td.MBot = (tf.boundingBox.Height() - bb.Height()) / 2
td.MTop = td.MBot
}
td.HAlign, td.VAlign = l.horAlign, pdfcpu.AlignBottom
pdfcpu.WriteColumn(p.Buf, p.MediaBox, nil, td, 0)
return nil
}
func (tf *TextField) ensureFont(fontID, fontName string, fonts pdfcpu.FontMap) (*pdfcpu.IndirectRef, error) {
pdf := tf.pdf
font, ok := fonts[fontName]
if ok {
if font.Res.IndRef != nil {
return font.Res.IndRef, nil
}
ir, err := pdfcpu.EnsureFontDict(pdf.XRefTable, fontName, false, nil)
if err != nil {
return nil, err
}
font.Res.IndRef = ir
fonts[fontName] = font
return ir, nil
}
var (
indRef *pdfcpu.IndirectRef
err error
)
if pdf.Optimize != nil {
for objNr, fo := range pdf.Optimize.FormFontObjects {
//fmt.Printf("searching for %s - obj:%d fontName:%s prefix:%s\n", fontName, objNr, fo.FontName, fo.Prefix)
if fontName == fo.FontName {
//fmt.Println("Match!")
indRef = pdfcpu.NewIndirectRef(objNr, 0)
break
}
}
if indRef == nil {
for objNr, fo := range pdf.Optimize.FontObjects {
//fmt.Printf("searching for %s - obj:%d fontName:%s prefix:%s\n", fontName, objNr, fo.FontName, fo.Prefix)
if fontName == fo.FontName {
//fmt.Println("Match!")
indRef = pdfcpu.NewIndirectRef(objNr, 0)
break
}
}
}
}
if indRef == nil {
indRef, err = pdfcpu.EnsureFontDict(pdf.XRefTable, fontName, false, nil)
if err != nil {
return nil, err
}
}
font.Res = pdfcpu.Resource{IndRef: indRef}
fonts[fontName] = font
return indRef, nil
}
func (tf *TextField) renderText(lines []string, da, fontName string, fontSize int) []byte {
buf := new(bytes.Buffer)
fmt.Fprintf(buf, "/Tx BMC q 1 1 %.1f %.1f re W n ", tf.boundingBox.Width()-2, tf.boundingBox.Height()-2)
lh := font.LineHeight(fontName, fontSize)
y := (tf.boundingBox.Height()-font.LineHeight(fontName, fontSize))/2 + font.Descent(fontName, fontSize)
if len(lines) > 1 {
y = tf.boundingBox.Height() - font.LineHeight(fontName, fontSize)
}
for _, s := range lines {
lineBB := pdfcpu.CalcBoundingBox(s, 0, 0, fontName, fontSize)
w := tf.boundingBox.Width()
// Apply horizontal alignment.
x := 2.
switch tf.horAlign {
case pdfcpu.AlignCenter:
x = w/2 - lineBB.Width()/2
case pdfcpu.AlignRight:
x = w - lineBB.Width() - 2
}
s = pdfcpu.PrepBytes(s, fontName, tf.RTL)
fmt.Fprintf(buf, "BT %s %.2f %.2f Td (%s) Tj ET ", da, x, y, s)
y -= lh
}
fmt.Fprint(buf, "Q EMC ")
return buf.Bytes()
}
func (tf *TextField) irN(fontID, fontName string, fontSize int, col *pdfcpu.SimpleColor, da string, fonts pdfcpu.FontMap) (*pdfcpu.IndirectRef, error) {
s := tf.Value
if font.IsCoreFont(fontName) && utf8.ValidString(s) {
s = pdfcpu.DecodeUTF8ToByte(s)
}
lines := pdfcpu.SplitMultilineStr(s)
// TODO if no multifield then ignore \n = leave right now
bb := tf.renderText(lines, da, fontName, fontSize)
sd, err := tf.pdf.XRefTable.NewStreamDictForBuf(bb)
if err != nil {
return nil, err
}
sd.InsertName("Type", "XObject")
sd.InsertName("Subtype", "Form")
sd.InsertInt("FormType", 1)
sd.Insert("BBox", pdfcpu.NewNumberArray(0, 0, tf.boundingBox.Width(), tf.boundingBox.Height()))
sd.Insert("Matrix", pdfcpu.NewNumberArray(1, 0, 0, 1, 0, 0))
ir, err := tf.ensureFont(fontID, fontName, fonts)
if err != nil {
return nil, err
}
d := pdfcpu.Dict(
map[string]pdfcpu.Object{
"Font": pdfcpu.Dict(
map[string]pdfcpu.Object{
fontID: *ir,
},
),
},
)
sd.Insert("Resources", d)
if err := sd.Encode(); err != nil {
return nil, err
}
return tf.pdf.XRefTable.IndRefForNewObject(*sd)
}
func (tf *TextField) calcMargin() (float64, float64, float64, float64, error) {
mTop, mRight, mBottom, mLeft := 0., 0., 0., 0.
if tf.Margin != nil {
m := tf.Margin
if m.Name != "" && m.Name[0] == '$' {
// use named margin
mName := m.Name[1:]
m0 := tf.margin(mName)
if m0 == nil {
return mTop, mRight, mBottom, mLeft, errors.Errorf("pdfcpu: unknown named margin %s", mName)
}
m.mergeIn(m0)
}
if m.Width > 0 {
mTop = m.Width
mRight = m.Width
mBottom = m.Width
mLeft = m.Width
} else {
mTop = m.Top
mRight = m.Right
mBottom = m.Bottom
mLeft = m.Left
}
}
return mTop, mRight, mBottom, mLeft, nil
}
func (tf *TextField) calcFont() (*FormFont, error) {
var f *FormFont
if tf.Font != nil {
f = tf.Font
if f.Name[0] == '$' {
// use named font
fName := f.Name[1:]
f0 := tf.font(fName)
if f0 == nil {
return nil, errors.Errorf("pdfcpu: unknown font name %s", fName)
}
f.Name = f0.Name
if f.Size == 0 {
f.Size = f0.Size
}
if f.col == nil {
f.col = f0.col
}
}
} else {
// Use inherited named font "input".
f = tf.font("input")
if f == nil {
return nil, errors.Errorf("pdfcpu: missing named font \"input\"")
}
}
if f.col == nil {
f.col = &pdfcpu.Black
}
return f, nil
}
func (tf *TextField) prepareRect(mTop, mRight, mBottom, mLeft float64) (*pdfcpu.Rectangle, float64, float64) {
cBox := tf.content.Box()
r := cBox.CroppedCopy(0)
r.LL.X += mLeft
r.LL.Y += mBottom
r.UR.X -= mRight
r.UR.Y -= mTop
pdf := tf.pdf
x, y := pdfcpu.NormalizeCoord(tf.x, tf.y, cBox, pdf.origin, false)
if x == -1 {
// Center horizontally
x = cBox.Center().X - r.LL.X
} else if x > 0 {
x -= mLeft
if x < 0 {
x = 0
}
}
if y == -1 {
// Center vertically
y = cBox.Center().Y - r.LL.Y
} else if y > 0 {
y -= mBottom
if y < 0 {
y = 0
}
}
if x >= 0 {
x = r.LL.X + x
}
if y >= 0 {
y = r.LL.Y + y
}
// Position text horizontally centered for x < 0.
if x < 0 {
x = r.LL.X + r.Width()/2
}
// Position text vertically centered for y < 0.
if y < 0 {
y = r.LL.Y + r.Height()/2
}
// Apply offset.
x += tf.Dx
y += tf.Dy
return r, x, y
}
func (tf *TextField) prepareDict(f *FormFont, fonts pdfcpu.FontMap) (pdfcpu.Dict, error) {
pdf := tf.pdf
id := pdfcpu.StringLiteral(pdfcpu.EncodeUTF16String(tf.ID))
ff := FieldDoNotSpellCheck
if tf.Multiline {
// If set, the field may contain multiple lines of text;
// if clear, the field’s text shall be restricted to a single line.
// Adobe Reader ok, Mac Preview nope
ff += FieldMultiline
} else {
// If set, the field shall not scroll (horizontally for single-line fields, vertically for multiple-line fields)
// to accommodate more text than fits within its annotation rectangle.
// Once the field is full, no further text shall be accepted for interactive form filling;
// for non- interactive form filling, the filler should take care
// not to add more character than will visibly fit in the defined area.
// Adobe Reader ok, Mac Preview nope
ff += FieldDoNotScroll
}
d := pdfcpu.Dict(
map[string]pdfcpu.Object{
"Type": pdfcpu.Name("Annot"),
"Subtype": pdfcpu.Name("Widget"),
"FT": pdfcpu.Name("Tx"),
"Rect": tf.boundingBox.Array(),
"F": pdfcpu.Integer(pdfcpu.AnnPrint),
"Ff": pdfcpu.Integer(ff),
"Q": pdfcpu.Integer(tf.horAlign), // Adjustment: (0:L) 1:C 2:R
"T": id,
"TU": id,
},
)
if tf.bgCol != nil || tf.Border != nil {
appCharDict := pdfcpu.Dict{}
if tf.bgCol != nil {
appCharDict["BG"] = tf.bgCol.Array()
}
if tf.Border != nil && tf.Border.col != nil && tf.Border.Width > 0 {
appCharDict["BC"] = tf.Border.col.Array()
}
d["MK"] = appCharDict
}
if tf.Border != nil && tf.Border.Width > 0 {
d["Border"] = pdfcpu.NewIntegerArray(0, 0, tf.Border.Width)
}
if tf.Value != "" {
sl := pdfcpu.StringLiteral(pdfcpu.EncodeUTF16String(tf.Value))
d["DV"] = sl
d["V"] = sl
}
if pdf.InheritedDA != "" {
d["DA"] = pdfcpu.StringLiteral(pdf.InheritedDA)
}
//if f != nil {
col := f.col
fontID, err := pdf.ensureFormFont(f.Name)
if err != nil {
return d, err
}
da := fmt.Sprintf("/%s %d Tf %.2f %.2f %.2f rg", fontID, f.Size, col.R, col.G, col.B)
// Note: Mac Preview does not honor inherited "DA"
d["DA"] = pdfcpu.StringLiteral(da)
if tf.Value != "" {
irN, err := tf.irN(fontID, f.Name, f.Size, col, da, fonts)
if err != nil {
return d, err
}
d["AP"] = pdfcpu.Dict(map[string]pdfcpu.Object{"N": *irN})
}
//}
return d, nil
}
func (tf *TextField) render(p *pdfcpu.Page, pageNr int, fonts pdfcpu.FontMap) error {
mTop, mRight, mBottom, mLeft, err := tf.calcMargin()
if err != nil {
return err
}
r, x, y := tf.prepareRect(mTop, mRight, mBottom, mLeft)
f, err := tf.calcFont()
if err != nil {
return err
}
h := float64(f.Size) * 1.2
if tf.Multiline {
if tf.Height == 0 {
return errors.Errorf("pdfcpu: field: %s height == 0", tf.ID)
}
h = tf.Height
}
tf.boundingBox = pdfcpu.RectForWidthAndHeight(x, y, tf.Width, h)
d, err := tf.prepareDict(f, fonts)
if err != nil {
return err
}
p.Annots = append(p.Annots, d)
return tf.renderLabel(r, p, pageNr, fonts, f.Size)
}