This repository has been archived by the owner on Jul 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
181 lines (154 loc) · 5 KB
/
index.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
'use strict';
const CsvParse = require('csv-parse');
const spawn = require('child_process').spawn;
const Joi = require('joi');
const _ = require('lodash');
function quote(val) {
// escape and quote the value if it is a string and this isn't windows
if (typeof val === 'string' && process.platform !== 'win32') {
val = '"' + val.replace(/(["\\$`])/g, '\\$1') + '"';
}
return val;
}
function pdfTools(options, callback) {
Joi.assert(callback, Joi.func());
Joi.assert(options, Joi.object().keys({
nailgun: Joi.bool().description('use nailgun'),
sourcePath: Joi.string().description('path to the source file'),
sourceContent: Joi.any().description('the content of the source file'),
font: Joi.string(),
cert: Joi.string(),
language: Joi.string(),
certpass: Joi.string(),
certformat: Joi.string(),
data: Joi.string(),
spawnOptions: Joi.object().description('options for the spawn command'),
logFile: Joi.string(),
logLevel: Joi.string().only('SEVERE', 'WARNING', 'INFO', 'CONFIG', 'FINE', 'FINER', 'FINEST'),
getFields: Joi.boolean(),
getAttachments: Joi.boolean(),
getSignatures: Joi.boolean(),
watermark: Joi.object().keys({
text: Joi.string().required(),
rotation: Joi.number().integer().min(0).max(360),
opacity: Joi.number().integer().min(0).max(100),
fontSize: Joi.number().integer().min(1)
})
})
.xor('sourcePath', 'sourceContent')
// if certpass or certformat is given than require cert
.with('certpass', 'cert')
.with('certformat', 'cert')
);
if (typeof options.nailgun === 'undefined') {
options.nailgun = true;
}
const args = [];
// either use nailgun client or the JAR directly
if (options.nailgun) {
const ngPath = process.env.TP_PDF_TOOLS_NG_PATH ? quote(process.env.TP_PDF_TOOLS_NG_PATH) : 'ng';
args.push(ngPath, 'pdfTools.Main');
} else {
const jarPath = process.env.TP_PDF_TOOLS_JAR_PATH ? quote(process.env.TP_PDF_TOOLS_JAR_PATH) : 'tepez-pdf-tools.jar';
args.push('java', '-jar', jarPath);
}
args.push('--source');
if (options.sourceContent) {
args.push('-')
} else {
args.push(quote(options.sourcePath));
}
[ 'logFile', 'logLevel' ].forEach((key) => {
const val = options[key];
if (val) {
args.push('--' + _.kebabCase(key));
args.push(quote(val));
}
});
if (options.getFields) {
args.push('--print-fields');
} else if (options.getAttachments) {
args.push('--report-attachments');
} else if (options.getSignatures) {
args.push('--report-signatures');
} else {
args.push('--destination', '-');
[ 'font', 'cert', 'certpass', 'certformat', 'data', 'language' ].forEach((key) => {
const val = options[key];
if (val) {
args.push('--' + _.kebabCase(key));
args.push(quote(val));
}
});
if (options.watermark) {
_.forEach(options.watermark, (value, key) => {
args.push(`--watermark-${_.kebabCase(key)}`, quote(value))
});
}
}
let child;
if (process.platform === 'win32') {
child = spawn(args[0], args.slice(1), options.spawnOptions);
} else {
// this nasty business prevents piping problems on linux
child = spawn('/bin/sh', ['-c', args.join(' ') + ' | cat'], options.spawnOptions);
}
// call the callback with null error when the process exits successfully
if (callback) {
child.on('exit', () => { callback(null); });
}
// setup error handling
const stream = child.stdout;
function handleError(err) {
child.removeAllListeners('exit');
child.kill();
// call the callback if there is one
if (callback) {
callback(err);
}
// if not, or there are listeners for errors, emit the error event
if (!callback || stream.listeners('error').length > 0) {
stream.emit('error', err);
}
}
child.once('error', handleError);
child.stderr.once('data', (err) => {
handleError(new Error((err || '').toString().trim()));
});
if (options.sourceContent) {
child.stdin.end(options.sourceContent);
}
if (options.getFields) {
return new Promise((resolve, reject) => {
const fields = [];
const csvParser = CsvParse({
columns: true,
skip_empty_lines: true
});
csvParser.on('readable', () => {
let record;
while (record = csvParser.read()) {
fields.push(record);
}
});
csvParser.on('error', reject);
csvParser.on('finish', () => {
resolve(fields);
});
stream.pipe(csvParser);
});
} else if (options.getAttachments || options.getSignatures) {
return new Promise((resolve, reject) => {
let json = '';
stream.on('data', (data) => { json += data.toString() });
stream.on('end', () => {
resolve(JSON.parse(json));
});
stream.on('error', reject);
});
} else {
// return stdout stream so we can pipe
return stream;
}
}
module.exports = pdfTools;