add docxtemplater and download route

master
shoaibalmasi 4 years ago
parent 3dc23fd746
commit 97d8d34e12
  1. 4
      package.json
  2. 13
      routes/users.js
  3. 36
      services/user.js
  4. BIN
      template/Hform4.docx
  5. 67
      tools/docxtemp.js

@ -8,12 +8,14 @@
"dependencies": {
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"docxtemplater": "^3.21.1",
"ejs": "~2.6.1",
"express": "~4.16.1",
"http-errors": "~1.6.3",
"mammoth": "^1.4.16",
"jalali-moment": "^3.3.10",
"morgan": "~1.9.1",
"pg": "^8.5.1",
"pizzip": "^3.0.6",
"sequelize": "^6.5.0"
}
}

@ -1,10 +1,11 @@
var express = require('express');
var router = express.Router();
const userServeice = require('../services/user')
const fs = require('fs')
var path = require('path');
/* GET users listing. */
router.post('/add', function(req, res) {
console.log('hereeeeeeeeee');
const userInfo ={
firstName : req.body.firstName,
lastName : req.body.lastName,
@ -76,4 +77,12 @@ router.post('/complete/form', function(req, res) {
})
})
router.get('/download/:fileName', function(req, res){
var file = fs.readFileSync(path.join(__dirname + `/../public/files/${req.params.fileName}`), 'binary');
res.setHeader('Content-Length', file.length);
res.write(file, 'binary');
res.end();
});
module.exports = router;

@ -1,5 +1,7 @@
let models = require('../models')
let mammoth = require("mammoth");
const models = require('../models')
const jalali = require("jalali-moment");
const docxTemp = require('../tools/docxtemp')
let methods = {}
let privates = {
@ -23,31 +25,11 @@ let privates = {
})
})
})
},
replaceInfo : (user)=>{
console.log(user);
return new Promise((resolve, reject) => {
mammoth.convertToHtml({path: "./template/Hform4.docx"})
.then((result)=>{
let text = result.value;
for (const property in user) {
console.log('++++++++++++++++++++++++');
console.log(property);
result.value =result.value.replace(`[${property}]`, `${user[property]}`);
}
resolve(result.value)
}).catch(err => {
reject({
eCode: 500,
eText: err
})
})
})
}
}
methods.addUser = (userInfo) => {
return new Promise((resolve, reject) => {
models.User.create(userInfo).then((user) => {
@ -68,7 +50,13 @@ methods.completeForm =(userId)=>{
return new Promise((resolve, reject) => {
privates.findUser(userId)
.then(user=>{
return privates.replaceInfo(user)
let userInfo = user
userInfo.fullName = user.firstName + ' ' + user.lastName
userInfo.obligationDate = jalali( user.obligationDate, 'YYYY/MM/DD').locale('fa').format('YYYY/MM/DD')
userInfo.requestDate = jalali( user.requestDate, 'YYYY/MM/DD').locale('fa').format('YYYY/MM/DD')
userInfo.writtenOrderDate = jalali( user.writtenOrderDate, 'YYYY/MM/DD').locale('fa').format('YYYY/MM/DD')
return docxTemp(userInfo, 'Hform4.docx')
}).then(text=>{
resolve(text)
}).catch(err => {

Binary file not shown.

@ -0,0 +1,67 @@
const PizZip = require('pizzip');
const Docxtemplater = require('docxtemplater');
const fs = require('fs');
const path = require('path');
// The error object contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors).
function replaceErrors(key, value) {
if (value instanceof Error) {
return Object.getOwnPropertyNames(value).reduce(function (error, key) {
error[key] = value[key];
return error;
}, {});
}
return value;
}
function errorHandler(error) {
console.log(JSON.stringify({
error: error
}, replaceErrors));
if (error.properties && error.properties.errors instanceof Array) {
const errorMessages = error.properties.errors.map(function (error) {
return error.properties.explanation;
}).join("\n");
console.log('errorMessages', errorMessages);
// errorMessages is a humanly readable message looking like this :
// 'The tag beginning with "foobar" is unopened'
}
throw error;
}
module.exports = function (userInfo, fileName) {
return new Promise((resolve, reject) => {
let content = fs.readFileSync(path.resolve(__dirname, `../template/${fileName}`), 'binary');
let zip = new PizZip(content);
let doc;
try {
doc = new Docxtemplater(zip);
} catch (error) {
errorHandler(error);
}
doc.setData(userInfo);
try {
doc.render()
} catch (error) {
errorHandler(error);
}
let buf = doc.getZip().generate({
type: 'nodebuffer'
});
fs.writeFileSync(path.resolve(__dirname, `../public/files/${userInfo.firstName}-${userInfo.lastName}-${fileName}`), buf);
resolve(`http://localhost:3000/users/download/${userInfo.firstName}-${userInfo.lastName}-${fileName}`)
.catch(err => {
reject({
eCode: 500,
eText: err
})
})
})
}
Loading…
Cancel
Save