forked from pdffillerjs/pdffiller
-
Notifications
You must be signed in to change notification settings - Fork 9
/
fdf.js
72 lines (65 loc) · 1.58 KB
/
fdf.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
var fs = require('fs');
var _ = require('lodash');
// only this sequence in FDF header requires char codes
var headerChars = new Buffer(
(String.fromCharCode(226)) +
(String.fromCharCode(227)) +
(String.fromCharCode(207)) +
(String.fromCharCode(211)) +
"\n"
);
var header = Buffer.concat([
new Buffer("%FDF-1.2\n"),
headerChars,
new Buffer(
"1 0 obj \n" +
"<<\n" +
"/FDF \n" +
"<<\n" +
"/Fields [\n"
)
]);
var footer = new Buffer(
"]\n" +
">>\n" +
">>\n" +
"endobj \n" +
"trailer\n" +
"\n" +
"<<\n" +
"/Root 1 0 R\n" +
">>\n" +
"%%EOF\n"
)
var escapeString = function escapeString(value) {
var out = value.toString();
out = out.replace(/\\/g, "\\\\");
out = out.replace(/\(/g, "\\(");
out = out.replace(/\)/g, "\\)");
out = out.toString("utf8");
return out;
}
exports.createFdf = function (data) {
var body = new Buffer([]);
_.mapKeys(data, function (value, name) {
try {
body = Buffer.concat([
body,
new Buffer(
"<<\n" +
"/T (" +
escapeString(name) +
")\n" +
"/V (" +
escapeString(value) +
")\n" +
">>\n"
)
]);
} catch (err) {
let errMsg = "Cannot escape string: '" + name + ": " + value + "'.";
throw Error(errMsg);
}
});
return Buffer.concat([header, body, footer]);
}