-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
53 lines (47 loc) · 1.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
const { promisify } = require('util')
const fs = require('fs')
const readFile = promisify(fs.readFile)
const writeFile = promisify(fs.writeFile)
const Docxtemplater = require('docxtemplater')
const JSzip = require('jszip')
const generateDocx = async options => {
if (!options) {
throw Error('Missing required input: options')
}
if (!options.template) {
throw Error('Missing required input: options.template')
}
if (!options.template.filePath) {
throw Error('Missing required input: options.template.filePath')
}
if (!options.template.data) {
throw Error('Missing required input: options.template.data')
}
if (options.save && !options.save.filePath) {
throw Error('Missing required input: options.save.filePath')
}
const template = await readFile(options.template.filePath, 'binary')
const zip = new JSzip(template)
const templateOptions = options.templateOptions || {}
const document = new Docxtemplater()
.loadZip(zip)
.setData(options.template.data)
.setOptions(templateOptions)
.render()
const buf = document
.getZip()
.generate({ type: 'nodebuffer' })
if (options.save) {
await writeFile(options.save.filePath, buf)
return { status: 'File written' }
} else {
return buf
}
}
module.exports = (options, callback) => {
return new Promise((resolve, reject) => {
generateDocx(options)
.then(data => callback ? callback(null, data) : resolve(data))
.catch(error => callback ? callback(error, null) : reject(error))
})
}