Search code examples
node.jspdfkit

Not able to send PDF from express to browser or postman


const PDF = require("pdfkit");
const fs = require("fs");
const express = require("express");
const app = express();

app.get("/", (req, res) => {
  try {
    const doc = new PDF({ size: "A4" });

    doc.image("/home/rahul/Desktop/projects/test/test/vlogo.png", 10, 0, {
      width: 100,
      height: 100,
      align: "left",
    });

    doc.pipe(
      fs.createWriteStream("/home/rahul/Desktop/projects/test/test/doc.pdf")
    );
    doc.end();
    res.sendFile("/home/rahul/Desktop/projects/test/test/doc.pdf");
  } catch (error) {
    console.log(error);
    res.status(500).sendFile("Rahul");
  }
});

The above code is not sending any response to the browser.

When I am loading the API in the browser, then I am getting this. rahul

But, when I remove the doc.pipe code, then it's working fine. It's sending PDF.

You can try by commenting

    // doc.pipe(
    //   fs.createWriteStream("/home/rahul/Desktop/projects/test/test/doc.pdf")
    // );

Solution

  • When calling doc.end() the pdf will take some time to be written on the disk. So you are basically sending a "half written" pdf file which results in an invalid file. So wait for the created WriteStream to finish first:

    const PDF = require("pdfkit");
    const fs = require("fs");
    const express = require("express");
    const app = express();
    
    app.get("/", (req, res) => {
      try {
        const doc = new PDF({ size: "A4" });
    
        doc.image("/home/rahul/Desktop/projects/test/test/vlogo.png", 10, 0, {
          width: 100,
          height: 100,
          align: "left",
        });
    
        const stream = fs.createWriteStream("/home/rahul/Desktop/projects/test/test/doc.pdf")
    
        stream.on('finish', () => {
            // now, the file is fully written to disk. Let's send it back!.
            res.sendFile("/home/rahul/Desktop/projects/test/test/doc.pdf");
        })
    
        stream.on('error', err => {
            console.error(err)
            res.status(500).send("Failed to send pdf.")
        })
    
        doc.pipe(stream);
    
    
        // start writing to file!.
        doc.end();
        
      } catch (error) {
        console.log(error);
        res.status(500).send("Server error occured.");
      }
    });