Generate pdf file using pdfkit and send it to browser in nodejs-expressjs

前端 未结 2 1458
日久生厌
日久生厌 2021-02-07 04:02

I am using pdfkit to generate pdf file and i want to send this pdf file to browser.

But i am getting message \"TypeError: listener must be a function\",

2条回答
  •  梦如初夏
    2021-02-07 04:17

    doc.write is the line causing the trouble, which is also a deprecated method so don't use it. Instead, use pipe to tell your doc where to stream the information, and remember to close it using doc.end(), i.e., like so:

    doc = new PDFDocument();
    doc.pipe( fs.createWriteStream('out.pdf') );
    
    // rest of the code goes here...
    
    doc.end();
    

    Note that it's not important that doc.pipe() be at the top, it just makes sense to me (you can put it before or after doc.end(). It doesn't matter, it'll work just fine). Finally, note that you can use pipe to stream directly to a response, there's no need to create the file first and then download it, i.e.:

    doc.pipe( fs.createWriteStream(res) )
    

提交回复
热议问题