5

Trying to generate pdf using html-pdf in node js but getting the below error after certain records:

TypeError: Cannot read property 'on' of undefined`

events.js:183
      throw er; // Unhandled 'error' event
      ^
Error: spawn /usr/local/lib/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs EAGAIN

Code:

    const filePathName = path.join(__dirname, '../../../views/', "invoice.ejs");
    const htmlString = fs.readFileSync(filePathName).toString();
    let options = { format: 'Letter',"timeout": 600000 };
    const ejsData = ejs.render(htmlString, data);

    return pdf.create(ejsData, options).toFile(path.join(__dirname, '../../../tmp/', data.filename), (err, response) => {
      if (err) return console.log('err',err);
      return response;
    });
Ultrasaurus
  • 3,031
  • 2
  • 33
  • 52

1 Answers1

0

In the line of const ejsData = ejs.render(htmlString, data);, ejs.render() is asynchrounous. So either you have to convert your function to an async and add await like below,

const yourFunction = async () => {
    const filePathName = path.join(__dirname, '../../../views/', "invoice.ejs");
    const htmlString = fs.readFileSync(filePathName).toString();
    let options = { format: 'Letter',"timeout": 600000 };
    const ejsData = await ejs.render(htmlString, data); //adding await

    return pdf.create(ejsData, options).toFile(path.join(__dirname, '../../../tmp/', data.filename), (err, response) => {
      if (err) return console.log('err',err);
      return response;
    });
}

Or, do something like this:

    const filePathName = path.join(__dirname, '../../../views/', "invoice.ejs");
    const htmlString = fs.readFileSync(filePathName).toString();
    let options = { format: 'Letter',"timeout": 600000 };
    ejs.renderFile(htmlString, data, (err, ejsData) => {
    if (err) {
          res.send(err);
    } else {
        pdf.create(ejsData, options).toFile((path.join(__dirname, '../../../tmp/', data.filename), (err, response) => {
                if (err) return console.log('err',err);
                return response;
            }););
        });
    }
Rukshan Jayasekara
  • 1,945
  • 1
  • 6
  • 26