-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwwpdf.js
More file actions
executable file
·390 lines (337 loc) · 9.32 KB
/
wwpdf.js
File metadata and controls
executable file
·390 lines (337 loc) · 9.32 KB
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
#!/usr/bin/env node
/**
https://github.com/jjwilly16/node-pdftk
https://github.com/NickNaso/ghostscript4js
*/
const program = require('commander');
const jsonminify=require('jsonminify');
const fs=require('fs');
const path=require('path');
const gs = require('ghostscript4js');
const pdftk = require('node-pdftk');
const mkdirp=require('mkdirp');
const each=require('sync-each');
var execSync = require('child_process').execSync;
var winston = require('winston');
const moment=require('moment');
program
.version('0.1.0')
.option('-s, --schema [schema]', 'specify a specific schema [default is all schemas]')
.option('-c, --crawl', 'crawl all subdirectories and run all pdf.json')
.option('-l, --loglevel [level]','set the log level [error, warn, info, verbose, debug, silly]','info')
.option('-t, --timestamp [true|false]','use timestamps in logs',false)
.parse(process.argv);
const myConsoleFormat = winston.format.printf(function (info) {
if(program.timestamp){
return `${info.level} [${moment().format('YYYY-MM-DDTHH:mm:ss.SSSZZ')}]: ${info.message} `;
}
else return `${info.level}: ${info.message}`;
});
var logger = winston.createLogger({
transports: [
new winston.transports.Console({ format: winston.format.combine( winston.format.colorize(), myConsoleFormat) })
],
level: program.loglevel,
});
program.on('--help', function(){
console.log('\n Examples:');
console.log('');
console.log(' $ pdfpower config.json');
console.log('');
});
const sysCheck=()=>{
let pv=process.version;
logger.log("debug",pv);
// var exe="pdftk "+PDF+" data_dump output "+outfile+";cat "+outfile
// _debug(exe);
metadata=execSync("which node");
logger.log("debug","we gt: "+metadata);
nvminstall="curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash"
}
const writeAbookmarkToFD = (fd,title,level,page,offset)=>{
fs.writeSync(fd,"BookmarkBegin\n");
fs.writeSync(fd,"BookmarkTitle: "+title+"\n");
fs.writeSync(fd,"BookmarkLevel: "+level+"\n");
fs.writeSync(fd,"BookmarkPageNumber: "+(page+offset+"\n"));
}
const writeAbookmarkToRay = (ray,title,level,page,offset)=>{
ray.push("BookmarkBegin");
ray.push("BookmarkTitle: "+title);
ray.push("BookmarkLevel: "+level);
ray.push("BookmarkPageNumber: "+(page+offset));
return ray;
}
const loopTOC = (obj,clevel,offset,fd) => {
Object.entries(obj).forEach(([key, val]) => {
if (val && typeof val === 'object') {
loopTOC(val,(clevel+1),offset,fd);
}
else {
writeAbookmarkToFD(fd,key,clevel,val,offset);
// fs.writeSync(fd,"BookmarkBegin\n");
// fs.writeSync(fd,"BookmarkTitle: "+key+"\n");
// fs.writeSync(fd,"BookmarkLevel: "+clevel+"\n");
// fs.writeSync(fd,"BookmarkPageNumber: "+(val+offset+"\n"));
}
});
};
const buildBookmarkFile = (outfile,TOC) => {
fd=fs.openSync(outfile,'w');
loopTOC(TOC,1,0,fd);
fs.closeSync(fd);
}
const getMetaData=(PDF,outfile) => {
let metadata;
var exe="pdftk "+PDF+" data_dump output "+outfile+";cat "+outfile
_debug(exe);
metadata=execSync(exe);
metaRay=metadata.toString().split(/(?:\r\n|\r|\n)/g);
return metaRay;
}
const getBookmarks=(metadataArray) => {
let bRay=[];
for (var lineno = 0; lineno < metadataArray.length; lineno++) {
var str = metadataArray[lineno];
if(str.startsWith("Book")){
bRay.push(str);
}
}
return bRay;
}
const buildPdfList=(obj) => {
var rtnstring="";
var rtnkeys="";
Object.entries(obj).forEach(([key, val]) => {
logger.log("debug","key:"+key+" val:"+val);
rtnstring+=key+"=\""+val+"\" ";
rtnkeys+=key+" ";
});
return {"pdflist":rtnstring,"po":rtnkeys}
}
const updateJustBookmarks=(metadatafile,newbookmarkfile) => {
var exe="pdftk "+outtemp+" data_dump output"
_debug(exe);
books=execSync(exe);
}
const replaceBookmarksInMetaFile=(metaDataRay,bookRay,newfile) =>{
let firsttime=true;
let bline;
let rRay=[];
outfd=fs.openSync(newfile,'w');
for (var lineno = 0; lineno < metaDataRay.length; lineno++) {
line=metaDataRay[lineno];
if(line.startsWith("Book")){
if(firsttime){
for (var blineno = 0; blineno < bookRay.length; blineno++) {
bline=bookRay[blineno];
fs.writeSync(outfd,bline+"\n");
rRay.push(bline);
_debug("PUSHING -->"+bline);
}
firsttime=false;
}
}
else {
fs.writeSync(outfd,line+"\n");
rRay.push(line);
}
}
return rRay;
}
const insertBookmarkTopLevel=(title,bookMarkRay,newbookmarkfile) => {
var bRay=[];
var books=""
var booklines="";
let regex = /^(BookmarkLevel:\s)+(\d)+/g;
let m;
let matched=false;
let theinc=0;
tbfd=fs.openSync(newbookmarkfile,'w');
writeAbookmarkToFD(tbfd,title,1,1,0);
writeAbookmarkToRay(bRay,title,1,1,0);
for (var line = 0; line < bookMarkRay.length; line++) {
var str = bookMarkRay[line];
regex.lastIndex=0;
_debug("my line: '"+str+"'");
matched=false;
while ((m = regex.exec(str)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
matched=true;
_debug("in here");
_debugDir(m);
theinc=parseInt((m[2]));
_debug("my inc: "+theinc+"vs the m2: "+m[2]);
theinc++;
_debug("my inc: "+theinc+"vs the m2: "+m[2]);
fs.writeSync(tbfd,m[1]+theinc+"\n");
bRay.push(m[1]+theinc);
// m.forEach((match, groupIndex) => {
// _debug(`Found match, group ${groupIndex}: ${match}`);
// });
}
if (! matched){
fs.writeSync(tbfd,str+"\n");
bRay.push(str);
}
}
fs.closeSync(tbfd);
return bRay;
}
const toplevelBookmarks=(text,outtemp,bmkfile)=> {
var books=""
var booklines="";
let regex = /^(BookmarkLevel:\s)+(\d)+/g;
let m;
let matched=false;
let theinc=0;
var exe="pdftk "+outtemp+" data_dump output | grep Book"
_debug(exe);
books=execSync(exe);
booklines=books.toString().split(/(?:\r\n|\r|\n)/g);
tbfd=fs.openSync(bmkfile,'w');
writeAbookmarkToFD(tbfd,text,1,1,0);
for (var line = 0; line < booklines.length; line++) {
var str = booklines[line];
regex.lastIndex=0;
_debug("my line: '"+str+"'");
matched=false;
while ((m = regex.exec(str)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
matched=true;
_debug("in here");
_debugDir(m);
theinc=parseInt((m[2]));
_debug("my inc: "+theinc+"vs the m2: "+m[2]);
theinc++;
_debug("my inc: "+theinc+"vs the m2: "+m[2]);
fs.writeSync(tbfd,m[1]+theinc+"\n");
// m.forEach((match, groupIndex) => {
// _debug(`Found match, group ${groupIndex}: ${match}`);
// });
}
if (! matched){
fs.writeSync(tbfd,str+"\n");
}
}
fs.closeSync(tbfd);
}
const _showRay=(rayname,ray)=>{
_debug("----")
_debug(rayname);
_debugDir(ray);
}
const _debug=(message) => {
if(program.debug){
console.log(message);
}
}
const _debugDir=(message) => {
if(program.debug){
console.dir(message);
}
}
// let asyncForEach = (array, callback) => {
// let result=(async function() {
// for (let index = 0; index < array.length; index++) {
// await callback(array[index], index, array)
// }
// })();
const processSchema = (schema) => {
var counter=0;
schema.pdfs.forEach(function(element) {
counter++;
logger.log
logger.info("building: "+element.outPDF);
mkdirp.sync(path.dirname(path.resolve(element.outPDF)));
var outtemp="/tmp/out_"+counter+".pdf";
var booktemp="/tmp/bmk"+counter+".txt";
if (element.inpdfs){
var inpdfOBJ=buildPdfList(element.inpdfs);
pdflist=inpdfOBJ.pdflist;
po=inpdfOBJ.po;
_debug("MY PO: "+po);
}
else if(element.wildcard){
var pdflist=element.wildcard;
po="";
}
if (element.pageOrder){
po=element.pageOrder;
}
var exe="pdftk "+pdflist+" cat "+po+" output "+outtemp
_debug(exe);
execSync(exe);
// }
// else {
// fs.copyFileSync(element.inpdfs.A,outtemp);
// }
if (element.TOC){
buildBookmarkFile(booktemp,element.TOC);
var exe="/usr/local/bin/pdftk "+outtemp+" update_Info "+booktemp+" output "+element.outPDF
_debug(exe);
execSync(exe);
}
else if (element.TOC_TOPLEVEL){
var oldMetaRay=getMetaData(outtemp,"/tmp/mdfile.txt");
var oldBooksRay=getBookmarks(oldMetaRay);
var newBooksRay=insertBookmarkTopLevel(element.TOC_TOPLEVEL,oldBooksRay,"/tmp/bktmp.txt");
var newMetaRay=replaceBookmarksInMetaFile(oldMetaRay,newBooksRay,"/tmp/newmdfile.txt");
_debug("-------------------------");
_showRay("metaold",oldMetaRay);
_showRay("bookold",oldBooksRay);
_showRay("newbook", newBooksRay);
_showRay("newmeta",newMetaRay);
var exe="pdftk "+outtemp+" update_Info /tmp/newmdfile.txt output "+element.outPDF
_debug(exe);
execSync(exe);
}
else {
fs.copyFileSync(outtemp,element.outPDF);
}
});
}
const start=()=>{
if (program.schema){
processSchema(desc[program.schema]);
}
else {
for (var schema in desc){
processSchema(desc[schema]);
}
}
_debug("all done with start");
}
sysCheck();
if(program.args.length>0){
desc = JSON.parse(jsonminify(fs.readFileSync(program.args[0], 'utf8')));
froot=path.dirname(path.resolve(program.args[0]));
process.chdir(froot);
//_debug(froot);
//process.exit(0);
//_debug(desc);
logger.log({
level: 'info',
message: 'Starting pdfpower parsing: '+program.args[0]
});
logger.log({
level: 'debug',
message: 'Hello debug distributed log files!'
});
start();
}
else {
program.help();
}
// try {
// // Take decision based on Ghostscript version
// const version = gs.version()
// _debug(version)
// // gs.executeSync('-sDEVICE=pngalpha -o my.png -sDEVICE=pngalpha -r144 my.pdf')
// } catch (err) {
// // Handle error
// throw err
// }