-
Notifications
You must be signed in to change notification settings - Fork 2
/
import.js
424 lines (388 loc) · 12.7 KB
/
import.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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
'use strict';
let outputDir = 'output'; // default
const path = require('path');
const xslt4node = require('xslt4node');
const extract = require('extract-zip');
const fs = require('fs-extra');
const DOMParser = require('xmldom').DOMParser;
const XMLSerializer = require('xmldom').XMLSerializer;
const async = require('async');
const _ = require('lodash');
const Q = require('q');
const mv = require('mv');
const Datauri = require('datauri');
const md = require('html-md');
const table = require('gfm-table');
const json = require('format-json');
let config = {};
/**
* Constructor
* @param {object} options - config options
* @returns {Convert}
* @constructor
*/
function Convert(options) {
if (!(this instanceof Convert)) {
return new Convert(options);
}
this.init();
config = options;
}
/**
* Set up object: read in XSL for transforms
*/
Convert.prototype.init = function () {
fs.readFile(process.cwd() + "/wordtoxml.xsl", (err, data) => {
if (err) {
return console.error(err);
}
this.XML2HTML = new DOMParser().parseFromString(data.toString());
});
this.WordXML = null;
console.log('Initialized.')
};
/**
* Main import function
* @param {string } sourcePath - path to input docx file.
* @param {string } outDir - output folder
*/
Convert.prototype.import = function (sourcePath, outDir) {
if (outDir) {
outputDir = outDir;
}
this.WordXML = null;
let sourceFile = {
path: sourcePath,
name: path.basename(sourcePath),
dir: path.dirname(sourcePath) + '',
extname: path.extname(sourcePath),
basename: path.basename(sourcePath, path.extname(sourcePath))
};
sourceFile.outDir = outputDir + '/' + sourceFile.basename;
// unzip the docx file, then get the xml files and transform
let _extract = function () {
extract(sourceFile.path, {dir: sourceFile.outDir + '/.tmp'}, function (err) {
if (err) {
return console.error(err);
}
_getXMLAndTransform();
});
};
/**
* Need to read several XML files:
* the main document.xml,
* the rels file (which contains links to the images),
* the core.xml file which has properties like title etc.
* Append one to the other, and then we can call transform.
*
* The next two functions perform these tasks
* @param {string} xmlPath to xml file
* @param {function} callback (so we can use with async library, see _getXML)
* @private
*/
let _addXML = (xmlPath, callback) => {
let filePath = sourceFile.outDir + '/.tmp/' + xmlPath;
fs.readFile(filePath, (err, data) => {
if (err) {
if ('ENOENT' !== err.code) {
console.error("addXML:", err);
}
if ('ENOENT' === err.code) {
console.log('File not found in add XML:', filePath);
}
return callback();
}
let xml = new DOMParser().parseFromString(data.toString());
if (!this.WordXML) {
this.WordXML = xml;
} else {
this.WordXML.documentElement.appendChild(
this.WordXML.importNode(xml.documentElement, true)
);
}
callback();
});
};
/**
* Put together the separate xml files unzipped from the docx file,
* then transform them with XSL.
* @private
*/
let _getXMLAndTransform = function () {
let paths = [
'word/document.xml',
'word/_rels/document.xml.rels',
'docProps/core.xml',
'word/styles.xml',
'word/numbering.xml'
];
let funcs = [];
paths.forEach((path) => {
funcs.push((callback) => {
_addXML(path, callback)
})
});
funcs.push(() => {
_writeWordXML().then(()=> _transform());
});
async.series(funcs);
};
/**
* Once we have all of the doc xml files loaded into a DOM object,
* we will apply the XSL to get the intermediate XML which we can
* easily transform into JSON and other formats
* @private
*/
let _transform = () => {
const xslt = new XMLSerializer().serializeToString(this.XML2HTML);
const xml = new XMLSerializer().serializeToString(this.WordXML);
const config = {
xslt: xslt,
source: xml,
result: String,
props: {
indent: 'yes'
}
};
xslt4node.transform(config, (err, result) => {
_writeXML(result, '/word/output_document.xml')
.then(() => _createJsonOutput(result))
.then(() => _cleanup());
});
};
/**
* Create Json output from xml.
*
* @param {string} xmlString - input xml as String
* @private
*/
let _createJsonOutput = function (xmlString) {
let doc = new DOMParser().parseFromString(xmlString);
let wordJson = {};
let items = wordJson.items = [];
let tocEl = doc.getElementsByTagName("toc")[0];
if (tocEl) {
let toc = {};
let heading = tocEl.getElementsByTagName("heading")[0];
if (heading) {
toc.heading = heading.textContent
}
let linkEls = tocEl.getElementsByTagName("links")[0];
if (linkEls) {
linkEls = linkEls.getElementsByTagName("link");
toc.links = [];
_.each(linkEls, (linkEl)=> {
let link = {};
_attachAttrs(link, linkEl);
toc.links.push(link);
});
}
wordJson.toc = toc;
}
// build JSON for the items
let itemEls = doc.getElementsByTagName("item");
_.forEach(itemEls, (itemEl) => {
let item = {};
_attachAttrs(item, itemEl);
// get the item attributes, put in JSON
let elType = itemEl.getAttribute("type");
// convert the item content to JSON
let contentEl = itemEl.getElementsByTagName("content")[0];
if (contentEl) {
let content = new XMLSerializer().serializeToString(contentEl);
content = content.replace(/^<content>/, '').replace(/<\/content>$/, '').replace(/\n/g, '').replace(/<content\/>/, '');
item.content = content;
if (elType === "table") {
let rowEls = contentEl.getElementsByTagName("tr");
let rows = [];
_.forEach(rowEls, (rowEl) => {
let row = [];
let colEls = rowEl.getElementsByTagName("td");
if (colEls) {
_.forEach(colEls, (colEl) => {
row.push(colEl.textContent);
});
}
rows.push(row);
});
item.rows = rows;
}
if (elType === "list") {
let list = domListToJson(null, contentEl);
item.list = list.list;
}
if (elType === 'image') {
let imgEl = contentEl.getElementsByTagName('img')[0];
if (imgEl) {
let src = imgEl.getAttribute('src');
if (src) {
item.src = src;
item.height = imgEl.getAttribute('height');
item.width = imgEl.getAttribute('width');
if (config.datauri) {
let datauri = new Datauri(sourceFile.outDir + '/.tmp/word/' + src);
item.dataUri = (datauri.content);
}
}
}
}
}
if (item.content) {
items.push(item);
}
});
let headEls = doc.getElementsByTagName("head")[0].childNodes;
if (!headEls) {
headEls = []
}
_.forEach(headEls, (el) => {
if (el.nodeType === 1) {
wordJson[el.tagName] = el.textContent;
}
});
return _writeWordJson(wordJson);
};
// util to take attributes from DOM El and put on object as keys
let _attachAttrs = function (item, el) {
_.forEach(el.attributes, (attr) => {
let v = attr.textContent;
if (v === 'true') {
v = true
}
if (v === 'false') {
v = false
}
item[attr.name] = v;
});
};
let _writeWordXML = () => {
return _writeXML(this.WordXML, 'word/imported_document.xml');
};
let _writeXML = (xml, filePath) => {
let deferred = Q.defer();
let xmlString = new XMLSerializer().serializeToString(xml);
fs.writeFile(sourceFile.outDir + '/.tmp/' + filePath, xmlString, (err) => {
if (err) {
console.log(err);
return deferred.reject(err);
}
return deferred.resolve();
});
return deferred.promise;
};
let _writeWordJson = (wordJson) => {
let deferred = Q.defer();
let outPath = sourceFile.outDir + '/' + sourceFile.basename + ".json";
fs.writeFile(outPath, json.plain(wordJson), (err) => {
if (err) {
console.log(err);
return deferred.reject(err);
}
_writeMarkdown(wordJson).then( ()=> {
console.log('Conversion finished.');
return deferred.resolve();
});
});
return deferred.promise;
};
let _writeMarkdown = (jsonData) => {
if (!config.md){
return Q.when();
}
let deferred = Q.defer();
let outPath = sourceFile.outDir + '/' + sourceFile.basename + ".md";
let md = _jsonToMd(jsonData);
fs.writeFile(outPath, md, (err) => {
if (err) {
console.log(err);
return deferred.reject(err);
}
return deferred.resolve();
});
return deferred.promise;
};
let _jsonToMd = (jsonData) => {
let mdOut = [];
let toc = jsonData.toc;
if (toc){
mdOut.push('#' + toc.heading);
toc.links.forEach((link)=>{
mdOut.push(link.name);
})
}
jsonData.items.forEach((item)=>{
switch (item.type) {
case 'section' :
mdOut.push(md(item.content));
break;
case 'table' :
mdOut.push(table(item.rows));
break;
case 'list' :
mdOut.push(md(item.content));
break;
case 'image' :
if (item.dataUri) {
mdOut.push('![](' + item.dataUri + ')');
} else {
mdOut.push('![](' + item.src + ')');
}
break;
case 'heading' :
let level = item.style.match(/(\d)/)[0]/1;
let hashes = '';
for (let i = 0; i < level; i++){
hashes = hashes + '#';
}
mdOut.push(hashes + item.content);
break;
}
});
return mdOut.join("\n\n");
};
let _cleanup = ()=> {
try {
fs.copySync(sourceFile.outDir + '/.tmp/word/media', sourceFile.outDir + '/media');
} catch(e){
// no media files
}
if (!config.no_cleanup) {
fs.removeSync(sourceFile.outDir + '/.tmp');
}
process.exit(0);
};
// start the import process
_extract(path);
};
/**
* Utility function, takes an array and an element, gets all
* child data from list item nodes. Returns nested arrays
* corresponding to the DOM subtree.
* @param list
* @param el
* @returns {*}
*/
function domListToJson(list, el) {
if (el.tagName === 'li') {
return list.data.push(el.textContent);
}
let children = el.childNodes;
if (!children) {
return;
}
let childList = {};
childList.type = el.tagName;
childList.data = [];
if (list) {
list.list = childList;
} else {
list = childList;
}
_.forEach(children, (child) => {
if (child.nodeType !== 3) {
domListToJson(childList, child);
}
});
return list;
}
module.exports = Convert;