无法将 PDF 从快递发送到浏览器或邮递员

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

以上代码没有向浏览器发送任何响应。

当我在浏览器中加载 API 时,我得到了这个。

但是,当我删除 doc.pipe 代码时,它工作正常。正在发送 PDF。

你可以评论试试

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

调用 doc.end() 时,pdf 将需要一些时间才能写入磁盘。因此,您基本上是在发送一个“写了一半”的 pdf 文件,这会导致文件无效。 所以先等待创建的WriteStream完成:

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