-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathacroform.js
392 lines (363 loc) · 10.2 KB
/
acroform.js
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
const FIELD_FLAGS = {
readOnly: 1,
required: 2,
noExport: 4,
multiline: 0x1000,
password: 0x2000,
toggleToOffButton: 0x4000,
radioButton: 0x8000,
pushButton: 0x10000,
combo: 0x20000,
edit: 0x40000,
sort: 0x80000,
multiSelect: 0x200000,
noSpell: 0x400000,
};
const FIELD_JUSTIFY = {
left: 0,
center: 1,
right: 2,
};
const VALUE_MAP = { value: 'V', defaultValue: 'DV' };
const FORMAT_SPECIAL = {
zip: '0',
zipPlus4: '1',
zip4: '1',
phone: '2',
ssn: '3',
};
const FORMAT_DEFAULT = {
number: {
nDec: 0,
sepComma: false,
negStyle: 'MinusBlack',
currency: '',
currencyPrepend: true,
},
percent: {
nDec: 0,
sepComma: false,
},
};
export default {
/**
* Must call if adding AcroForms to a document. Must also call font() before
* this method to set the default font.
*/
initForm() {
if (!this._font) {
throw new Error('Must set a font before calling initForm method');
}
this._acroform = {
fonts: {},
defaultFont: this._font.name,
};
this._acroform.fonts[this._font.id] = this._font.ref();
let data = {
Fields: [],
NeedAppearances: true,
DA: new String(`/${this._font.id} 0 Tf 0 g`),
DR: {
Font: {},
},
};
data.DR.Font[this._font.id] = this._font.ref();
const AcroForm = this.ref(data);
this._root.data.AcroForm = AcroForm;
return this;
},
/**
* Called automatically by document.js
*/
endAcroForm() {
if (this._root.data.AcroForm) {
if (
!Object.keys(this._acroform.fonts).length &&
!this._acroform.defaultFont
) {
throw new Error('No fonts specified for PDF form');
}
let fontDict = this._root.data.AcroForm.data.DR.Font;
Object.keys(this._acroform.fonts).forEach((name) => {
fontDict[name] = this._acroform.fonts[name];
});
this._root.data.AcroForm.data.Fields.forEach((fieldRef) => {
this._endChild(fieldRef);
});
this._root.data.AcroForm.end();
}
return this;
},
_endChild(ref) {
if (Array.isArray(ref.data.Kids)) {
ref.data.Kids.forEach((childRef) => {
this._endChild(childRef);
});
ref.end();
}
return this;
},
/**
* Creates and adds a form field to the document. Form fields are intermediate
* nodes in a PDF form that are used to specify form name heirarchy and form
* value defaults.
* @param {string} name - field name (T attribute in field dictionary)
* @param {object} options - other attributes to include in field dictionary
*/
formField(name, options = {}) {
let fieldDict = this._fieldDict(name, null, options);
let fieldRef = this.ref(fieldDict);
this._addToParent(fieldRef);
return fieldRef;
},
/**
* Creates and adds a Form Annotation to the document. Form annotations are
* called Widget annotations internally within a PDF file.
* @param {string} name - form field name (T attribute of widget annotation
* dictionary)
* @param {number} x
* @param {number} y
* @param {number} w
* @param {number} h
* @param {object} options
*/
formAnnotation(name, type, x, y, w, h, options = {}) {
let fieldDict = this._fieldDict(name, type, options);
fieldDict.Subtype = 'Widget';
if (fieldDict.F === undefined) {
fieldDict.F = 4; // print the annotation
}
// Add Field annot to page, and get it's ref
this.annotate(x, y, w, h, fieldDict);
let annotRef = this.page.annotations[this.page.annotations.length - 1];
return this._addToParent(annotRef);
},
formText(name, x, y, w, h, options = {}) {
return this.formAnnotation(name, 'text', x, y, w, h, options);
},
formPushButton(name, x, y, w, h, options = {}) {
return this.formAnnotation(name, 'pushButton', x, y, w, h, options);
},
formCombo(name, x, y, w, h, options = {}) {
return this.formAnnotation(name, 'combo', x, y, w, h, options);
},
formList(name, x, y, w, h, options = {}) {
return this.formAnnotation(name, 'list', x, y, w, h, options);
},
formRadioButton(name, x, y, w, h, options = {}) {
return this.formAnnotation(name, 'radioButton', x, y, w, h, options);
},
formCheckbox(name, x, y, w, h, options = {}) {
return this.formAnnotation(name, 'checkbox', x, y, w, h, options);
},
_addToParent(fieldRef) {
let parent = fieldRef.data.Parent;
if (parent) {
if (!parent.data.Kids) {
parent.data.Kids = [];
}
parent.data.Kids.push(fieldRef);
} else {
this._root.data.AcroForm.data.Fields.push(fieldRef);
}
return this;
},
_fieldDict(name, type, options = {}) {
if (!this._acroform) {
throw new Error(
'Call document.initForm() method before adding form elements to document',
);
}
let opts = Object.assign({}, options);
if (type !== null) {
opts = this._resolveType(type, options);
}
opts = this._resolveFlags(opts);
opts = this._resolveJustify(opts);
opts = this._resolveFont(opts);
opts = this._resolveStrings(opts);
opts = this._resolveColors(opts);
opts = this._resolveFormat(opts);
opts.T = new String(name);
if (opts.parent) {
opts.Parent = opts.parent;
delete opts.parent;
}
return opts;
},
_resolveType(type, opts) {
if (type === 'text') {
opts.FT = 'Tx';
} else if (type === 'pushButton') {
opts.FT = 'Btn';
opts.pushButton = true;
} else if (type === 'radioButton') {
opts.FT = 'Btn';
opts.radioButton = true;
} else if (type === 'checkbox') {
opts.FT = 'Btn';
} else if (type === 'combo') {
opts.FT = 'Ch';
opts.combo = true;
} else if (type === 'list') {
opts.FT = 'Ch';
} else {
throw new Error(`Invalid form annotation type '${type}'`);
}
return opts;
},
_resolveFormat(opts) {
const f = opts.format;
if (f && f.type) {
let fnKeystroke;
let fnFormat;
let params = '';
if (FORMAT_SPECIAL[f.type] !== undefined) {
fnKeystroke = `AFSpecial_Keystroke`;
fnFormat = `AFSpecial_Format`;
params = FORMAT_SPECIAL[f.type];
} else {
let format = f.type.charAt(0).toUpperCase() + f.type.slice(1);
fnKeystroke = `AF${format}_Keystroke`;
fnFormat = `AF${format}_Format`;
if (f.type === 'date') {
fnKeystroke += 'Ex';
params = String(f.param);
} else if (f.type === 'time') {
params = String(f.param);
} else if (f.type === 'number') {
let p = Object.assign({}, FORMAT_DEFAULT.number, f);
params = String(
[
String(p.nDec),
p.sepComma ? '0' : '1',
'"' + p.negStyle + '"',
'null',
'"' + p.currency + '"',
String(p.currencyPrepend),
].join(','),
);
} else if (f.type === 'percent') {
let p = Object.assign({}, FORMAT_DEFAULT.percent, f);
params = String([String(p.nDec), p.sepComma ? '0' : '1'].join(','));
}
}
opts.AA = opts.AA ? opts.AA : {};
opts.AA.K = {
S: 'JavaScript',
JS: new String(`${fnKeystroke}(${params});`),
};
opts.AA.F = {
S: 'JavaScript',
JS: new String(`${fnFormat}(${params});`),
};
}
delete opts.format;
return opts;
},
_resolveColors(opts) {
let color = this._normalizeColor(opts.backgroundColor);
if (color) {
if (!opts.MK) {
opts.MK = {};
}
opts.MK.BG = color;
}
color = this._normalizeColor(opts.borderColor);
if (color) {
if (!opts.MK) {
opts.MK = {};
}
opts.MK.BC = color;
}
delete opts.backgroundColor;
delete opts.borderColor;
return opts;
},
_resolveFlags(options) {
let result = 0;
Object.keys(options).forEach((key) => {
if (FIELD_FLAGS[key]) {
if (options[key]) {
result |= FIELD_FLAGS[key];
}
delete options[key];
}
});
if (result !== 0) {
options.Ff = options.Ff ? options.Ff : 0;
options.Ff |= result;
}
return options;
},
_resolveJustify(options) {
let result = 0;
if (options.align !== undefined) {
if (typeof FIELD_JUSTIFY[options.align] === 'number') {
result = FIELD_JUSTIFY[options.align];
}
delete options.align;
}
if (result !== 0) {
options.Q = result; // default
}
return options;
},
_resolveFont(options) {
// add current font to document-level AcroForm dict if necessary
if (this._acroform.fonts[this._font.id] == null) {
this._acroform.fonts[this._font.id] = this._font.ref();
}
// add current font to field's resource dict (RD) if not the default acroform font
if (this._acroform.defaultFont !== this._font.name) {
options.DR = { Font: {} };
// Get the fontSize option. If not set use auto sizing
const fontSize = options.fontSize || 0;
options.DR.Font[this._font.id] = this._font.ref();
options.DA = new String(`/${this._font.id} ${fontSize} Tf 0 g`);
}
return options;
},
_resolveStrings(options) {
let select = [];
function appendChoices(a) {
if (Array.isArray(a)) {
for (let idx = 0; idx < a.length; idx++) {
if (typeof a[idx] === 'string') {
select.push(new String(a[idx]));
} else {
select.push(a[idx]);
}
}
}
}
appendChoices(options.Opt);
if (options.select) {
appendChoices(options.select);
delete options.select;
}
if (select.length) {
options.Opt = select;
}
Object.keys(VALUE_MAP).forEach((key) => {
if (options[key] !== undefined) {
options[VALUE_MAP[key]] = options[key];
delete options[key];
}
});
['V', 'DV'].forEach((key) => {
if (typeof options[key] === 'string') {
options[key] = new String(options[key]);
}
});
if (options.MK && options.MK.CA) {
options.MK.CA = new String(options.MK.CA);
}
if (options.label) {
options.MK = options.MK ? options.MK : {};
options.MK.CA = new String(options.label);
delete options.label;
}
return options;
},
};