Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1x 1x | import { saveAs } from 'file-saver'
import Docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import get from 'lodash.get'
export const generateFileFromTemplate = <T extends object>(data: T, templatePath: string, fileName?: string) => {
fetch(templatePath)
.then(response => response.arrayBuffer())
.then(content => {
const zip = new PizZip(content)
const doc = new Docxtemplater(zip, {
paragraphLoop: true,
linebreaks: true,
parser: tag => ({
get(scope, context) {
const arrayLikeIndex = context.scopePathItem
if (tag === '.') {
if (context.scopePathLength[1] - 1 === context.scopePathItem[1]) {
return scope
}
return scope + ', '
}
if (tag === '$index') {
return arrayLikeIndex.at(0)
}
if (tag === '$ordinalNumber') {
return (arrayLikeIndex.at(0) || 0) + 1
}
if (/\./.test(tag)) {
return get(scope, tag, scope[tag])
}
return scope[tag]
},
}),
})
doc.render(data)
saveAs(
doc.getZip().generate({
type: 'blob',
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
}),
fileName || templatePath
)
})
}
|