pdfGenerator.js 924 Bytes
/**
 * Created by Tommy Huang on 18/04/26.
 */

 const fs = require('fs')
 const path = require('path')
 const util = require('util')
 const pdf = require('html-pdf')

class PDFGenerator {
  constructor(type, data) {
    this.src = type === 'loan' ? path.join(__dirname, '/template/loanAgreement.html') : path.join(__dirname, 'template/serviceAgreement.html')
    this.data = data
    this.file = undefined
    this.parsedStr = ''
    this.load()
  }
  load() {
    this.file = fs.readFileSync(this.src).toString('utf-8')
    this.parse(this.file)  
  }
  parse(rawStr) {
    const search = /\{\{([a-zA-Z]+)\}\}/g
    this.parsedStr = rawStr.replace(search, (match, key) => {
      return this.data[key]
    })
  }
  async generate() {
    const newPDF = pdf.create(this.parsedStr)
    const asyncToBuffer = util.promisify(newPDF.toBuffer).bind(newPDF)
    return await asyncToBuffer()
  }
}

module.exports = PDFGenerator