Node/Parse docx variables

/* npm install --save docxtemplater pizzip command: node docxtemplater2.js input.docx "<json file or text.json>" output.docx */ const fs = require("fs"); const path = require("path"); if (process.argv.length < 5) { console.error('Expected at least three argument!'); process.exit(1); } if (!fs.existsSync(process.argv[2])) { console.error('File does not exist '+process.argv[2]+'!'); process.exit(1); } const PizZip = require("pizzip"); const Docxtemplater = require("docxtemplater"); // Load the docx file as binary content const content = fs.readFileSync( path.resolve(__dirname, process.argv[2]), "binary" ); const zip = new PizZip(content); var json = process.argv[3]; if (fs.existsSync(json)) { json = fs.readFileSync(json); } json = JSON.parse(json); const doc = new Docxtemplater(zip, { paragraphLoop: true, linebreaks: true, nullGetter: function(part) { // console.log(part); return "{"+part.value+"}"; } }); // Render the document (Replace {first_name} by John, {last_name} by Doe, ...) doc.render(json); const buf = doc.getZip().generate({ type: "nodebuffer", // compression: DEFLATE adds a compression step. // For a 50MB output document, expect 500ms additional CPU time compression: "DEFLATE", }); // buf is a nodejs Buffer, you can either write it to a // file or res.send it with express for example. fs.writeFileSync(path.resolve(__dirname, process.argv[4]), buf);
Replace "{tags}" in docx document from json data:

Ex:

node doctemplater2.js input.docx '{"TITLE": "This is the title for document", "USER": "MyUser"}' output.docx

result file will replace {TITLE} with 'This is the title for document' and {USER} with 'MyUser' in document contents.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.