簡體   English   中英

使用 html-pdf 創建 pdf 時出錯

[英]Getting error While Creating pdf using html-pdf

嘗試在節點 js 中使用 html-pdf 生成 pdf,但在某些記錄后出現以下錯誤:

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

代碼:

    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;
    });

const ejsData = ejs.render(htmlString, data); , ejs.render()異步的 因此,要么您必須將您的函數轉換為async並添加如下所示的await

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;
    });
}

或者,做這樣的事情:

    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;
            }););
        });
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM