/
form.go
342 lines (301 loc) · 8.71 KB
/
form.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
/*
* This file is subject to the terms and conditions defined in
* file 'LICENSE.md', which is part of this source code package.
*/
package model
import (
"fmt"
"github.com/xwc1125/gopdf/common"
"github.com/xwc1125/gopdf/core"
)
/*
FT = Btn, Tx, Ch, Sig
Btn = button
Tx = text
Ch = choice
Sig = signature
*/
// PdfAcroForm represents the AcroForm dictionary used for representation of form data in PDF.
type PdfAcroForm struct {
Fields *[]*PdfField
NeedAppearances *core.PdfObjectBool
SigFlags *core.PdfObjectInteger
CO *core.PdfObjectArray
DR *PdfPageResources
DA *core.PdfObjectString
Q *core.PdfObjectInteger
XFA core.PdfObject
container *core.PdfIndirectObject
}
// NewPdfAcroForm returns a new PdfAcroForm with an intialized container (indirect object).
func NewPdfAcroForm() *PdfAcroForm {
return &PdfAcroForm{
Fields: &[]*PdfField{},
container: core.MakeIndirectObject(core.MakeDict()),
}
}
// flattenFields returns a flattened list of field hierarchy.
func flattenFields(field *PdfField) []*PdfField {
list := []*PdfField{field}
for _, k := range field.Kids {
list = append(list, flattenFields(k)...)
}
return list
}
// AllFields returns a flattened list of all fields in the form.
func (form *PdfAcroForm) AllFields() []*PdfField {
if form == nil {
return nil
}
var fields []*PdfField
if form.Fields != nil {
for _, field := range *form.Fields {
fields = append(fields, flattenFields(field)...)
}
}
return fields
}
// signatureFields returns a slice of all signature fields in the form.
func (form *PdfAcroForm) signatureFields() []*PdfFieldSignature {
var sigfields []*PdfFieldSignature
for _, f := range form.AllFields() {
switch t := f.GetContext().(type) {
case *PdfFieldSignature:
sigf := t
sigfields = append(sigfields, sigf)
}
}
return sigfields
}
// newPdfAcroFormFromDict is used when loading forms from PDF files.
func (r *PdfReader) newPdfAcroFormFromDict(container *core.PdfIndirectObject, d *core.PdfObjectDictionary) (*PdfAcroForm, error) {
acroForm := NewPdfAcroForm()
if container != nil {
acroForm.container = container
container.PdfObject = core.MakeDict()
}
if obj := d.Get("Fields"); obj != nil {
fieldArray, ok := core.GetArray(obj)
if !ok {
return nil, fmt.Errorf("fields not an array (%T)", obj)
}
var fields []*PdfField
for _, obj := range fieldArray.Elements() {
container, isIndirect := core.GetIndirect(obj)
if !isIndirect {
if _, isNull := obj.(*core.PdfObjectNull); isNull {
common.Log.Trace("Skipping over null field")
continue
}
common.Log.Debug("Field not contained in indirect object %T", obj)
return nil, fmt.Errorf("field not in an indirect object")
}
field, err := r.newPdfFieldFromIndirectObject(container, nil)
if err != nil {
return nil, err
}
common.Log.Trace("AcroForm Field: %+v", *field)
fields = append(fields, field)
}
acroForm.Fields = &fields
}
if obj := d.Get("NeedAppearances"); obj != nil {
val, ok := core.GetBool(obj)
if ok {
acroForm.NeedAppearances = val
} else {
common.Log.Debug("ERROR: NeedAppearances invalid (got %T)", obj)
}
}
if obj := d.Get("SigFlags"); obj != nil {
val, ok := core.GetInt(obj)
if ok {
acroForm.SigFlags = val
} else {
common.Log.Debug("ERROR: SigFlags invalid (got %T)", obj)
}
}
if obj := d.Get("CO"); obj != nil {
arr, ok := core.GetArray(obj)
if ok {
acroForm.CO = arr
} else {
common.Log.Debug("ERROR: CO invalid (got %T)", obj)
}
}
if obj := d.Get("DR"); obj != nil {
if d, ok := core.GetDict(obj); ok {
resources, err := NewPdfPageResourcesFromDict(d)
if err != nil {
common.Log.Error("Invalid DR: %v", err)
return nil, err
}
acroForm.DR = resources
} else {
common.Log.Debug("ERROR: DR invalid (got %T)", obj)
}
}
if obj := d.Get("DA"); obj != nil {
str, ok := core.GetString(obj)
if ok {
acroForm.DA = str
} else {
common.Log.Debug("ERROR: DA invalid (got %T)", obj)
}
}
if obj := d.Get("Q"); obj != nil {
val, ok := core.GetInt(obj)
if ok {
acroForm.Q = val
} else {
common.Log.Debug("ERROR: Q invalid (got %T)", obj)
}
}
if obj := d.Get("XFA"); obj != nil {
acroForm.XFA = obj
}
return acroForm, nil
}
// GetContainingPdfObject returns the container of the PdfAcroForm (indirect object).
func (form *PdfAcroForm) GetContainingPdfObject() core.PdfObject {
return form.container
}
// ToPdfObject converts PdfAcroForm to a PdfObject, i.e. an indirect object containing the
// AcroForm dictionary.
func (form *PdfAcroForm) ToPdfObject() core.PdfObject {
container := form.container
dict := container.PdfObject.(*core.PdfObjectDictionary)
if form.Fields != nil {
arr := core.PdfObjectArray{}
for _, field := range *form.Fields {
ctx := field.GetContext()
if ctx != nil {
// Call subtype's ToPdfObject directly to get the entire field data.
arr.Append(ctx.ToPdfObject())
} else {
arr.Append(field.ToPdfObject())
}
}
dict.Set("Fields", &arr)
}
if form.NeedAppearances != nil {
dict.Set("NeedAppearances", form.NeedAppearances)
}
if form.SigFlags != nil {
dict.Set("SigFlags", form.SigFlags)
}
if form.CO != nil {
dict.Set("CO", form.CO)
}
if form.DR != nil {
dict.Set("DR", form.DR.ToPdfObject())
}
if form.DA != nil {
dict.Set("DA", form.DA)
}
if form.Q != nil {
dict.Set("Q", form.Q)
}
if form.XFA != nil {
dict.Set("XFA", form.XFA)
}
return container
}
// FieldValueProvider provides field values from a data source such as FDF, JSON or any other.
type FieldValueProvider interface {
FieldValues() (map[string]core.PdfObject, error)
}
// Fill populates `form` with values provided by `provider`.
func (form *PdfAcroForm) Fill(provider FieldValueProvider) error {
return form.fill(provider, nil)
}
// FillWithAppearance populates `form` with values provided by `provider`.
// If not nil, `appGen` is used to generate appearance dictionaries for the
// field annotations, based on the specified settings. Otherwise, appearance
// generation is skipped.
// e.g.: appGen := annotator.FieldAppearance{OnlyIfMissing: true, RegenerateTextFields: true}
// NOTE: In next major version this functionality will be part of Fill. (v4)
func (form *PdfAcroForm) FillWithAppearance(provider FieldValueProvider, appGen FieldAppearanceGenerator) error {
return form.fill(provider, appGen)
}
// fill populates `form` with values provided by `provider`. If `appGen` is
// not nil, field appearances are also generated.
func (form *PdfAcroForm) fill(provider FieldValueProvider, appGen FieldAppearanceGenerator) error {
if form == nil {
return nil
}
objMap, err := provider.FieldValues()
if err != nil {
return err
}
for _, field := range form.AllFields() {
fname := field.PartialName()
if len(fname) == 0 {
continue
}
if valObj, has := objMap[fname]; has {
err := fillFieldValue(field, valObj)
if err != nil {
return err
}
// Generate field appearance based on the specified settings.
if appGen == nil {
continue
}
for _, annot := range field.Annotations {
// appGen generates the appearance based on the form/field/annotation and other settings
// depending on the implementation (for example may only generate appearance if none set).
apDict, err := appGen.GenerateAppearanceDict(form, field, annot)
if err != nil {
return err
}
annot.AP = apDict
annot.ToPdfObject()
}
}
}
return nil
}
// fillFieldValue populates form field `f` with value represented by `v`.
func fillFieldValue(f *PdfField, val core.PdfObject) error {
switch f.GetContext().(type) {
case *PdfFieldText:
switch t := val.(type) {
case *core.PdfObjectName:
name := t
common.Log.Debug("Unexpected: Got V as name -> converting to string '%s'", name.String())
f.V = core.MakeEncodedString(t.String(), true)
case *core.PdfObjectString:
f.V = core.MakeEncodedString(t.String(), true)
default:
common.Log.Debug("ERROR: Unsupported text field V type: %T (%#v)", t, t)
}
case *PdfFieldButton, *PdfFieldChoice:
switch t := val.(type) {
case *core.PdfObjectName:
if len(t.String()) == 0 {
return nil
}
for _, wa := range f.Annotations {
wa.AS = val
}
f.V = val
case *core.PdfObjectString:
if len(t.String()) == 0 {
return nil
}
common.Log.Debug("Unexpected string for button/choice field. Converting to name: '%s'", t.String())
name := core.MakeName(t.String())
for _, wa := range f.Annotations {
wa.AS = name
}
f.V = name
default:
common.Log.Debug("ERROR: UNEXPECTED %s -> %v", f.PartialName(), val)
f.V = val
}
case *PdfFieldSignature:
common.Log.Debug("TODO: Signature appearance not supported yet: %s/%v", f.PartialName(), val)
}
return nil
}