Last active
March 21, 2019 21:39
-
-
Save JasonHarrop/4ad92012754c907341b1bf40346ca580 to your computer and use it in GitHub Desktop.
docxtemplater sample code applying invoice data to a docx to create an invoice instance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var JSZip = require('jszip'); | |
var Docxtemplater = require('docxtemplater'); | |
var fs = require('fs'); | |
var path = require('path'); | |
//Load the docx file as a binary | |
var content = fs | |
.readFileSync(path.resolve(__dirname, 'invoice-template.docx'), 'binary'); | |
var zip = new JSZip(content); | |
var doc = new Docxtemplater(); | |
doc.loadZip(zip); | |
//set the templateVariables | |
doc.setData({CustomerName : "Microsoft Corp", | |
AddressLine1: "One Microsoft Way", | |
City: "Redmond", State: "WA", Zip: "98052", | |
Country: "USA", | |
InvoiceDate : "14 March 2019", | |
InvoiceNumber: "INV123", | |
Items: [ | |
{ | |
Item_Description: "Bananas", | |
Item_Price: "5", | |
Item_Qty: "10", | |
Item_SubTotal: "50" | |
}, | |
{ | |
Item_Description: "Mangoes", | |
Item_Price: "10", | |
Item_Qty: "4", | |
Item_SubTotal: "40" | |
} | |
], | |
TotalEx:"90", | |
SalesTax:"9", | |
Shipping:"10", | |
TotalPrice:"$109", | |
DueDate : "28 March 2019" | |
}); | |
try { | |
// render the document ie replace the variables | |
doc.render() | |
} | |
catch (error) { | |
var e = { | |
message: error.message, | |
name: error.name, | |
stack: error.stack, | |
properties: error.properties, | |
} | |
console.log(JSON.stringify({error: e})); | |
throw error; | |
} | |
var buf = doc.getZip() | |
.generate({type: 'nodebuffer'}); | |
// buf is a nodejs buffer, you can either write it to a file or do anything else with it. | |
fs.writeFileSync(path.resolve(__dirname, 'invoice-instance.docx'), buf); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment