DownloadFile.js

const fs = require('fs')
const path = require('path')
const async = require('async')
const officegen = require('officegen')

const DocxGenerator = require('../docx/DocxGenerator')
const RtfGenerator = require('../rtf/RtfGenerator')

function generateDocx(req, res, inputs) {
  var docx = officegen({
    type: 'docx',
    orientation: 'portrait'
  })

  docx.on('error', function (err) {
    console.error(err)
  })

  docx.on('finalize', function (written) {
    console.log('Total bytes created: ' + written + '\n')
  })

  DocxGenerator.generate(docx, inputs)

  docx.generate(res)
}

function generateRtf(req, res, inputs) {
  var content = RtfGenerator.generate(inputs)
  res.json({ content: content })
}

function readAndSendFile(req, res, filename) {
  console.log('Reading file')
  var file = path.resolve(__dirname + '/../../../') + '/' + filename

  fs.stat(file, function (error, stat) {
    if (error) {
      throw error
    }

    res.writeHead(200, {
      'Content-Type':
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'Content-disposition': 'attachment; filename=' + filename,
      'Content-Length': stat.size
    })

    var filestream = fs.createReadStream(file)
    filestream.pipe(res)
  })
}

const DownloadFile = {
  generateDocx,
  generateRtf
}

module.exports = DownloadFile