如何正确将服务器端生成的pdf文件发送到前端

问题描述 投票:0回答:1

我有一个快速应用程序,可以提供文章列表。 我的服务器只需单击按钮即可为所选文章生成 pdf 文件。

这是我制作pdf-s的后端代码

app.get("/generate-pdf/:articleHref", async (req, res) => {
  const articleHref = req.params.articleHref;
  const pdfDoc = await PDFDocument.create();
  const page = pdfDoc.addPage();

  const { width, height } = page.getSize();

  page.drawText("HELLO", {
    x: 50,
    y: height - 50,
    size: 20,
    color: rgb(0, 0, 0),
  });
  const pdfBytes = await pdfDoc.save();

  const currentDate = DateTime.now().toFormat('yyyy-MM-dd'); 
  const fileName = `${articleHref}_${currentDate}`; 

  res.setHeader("Content-Type", "application/pdf");
  res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);
  res.send(pdfBytes);
});

在前端,我监听按钮点击并使用此代码启动 pdf 生成

                const response = await fetch(`/generate-pdf/${articleHref}`, {
                    method: 'GET'
                });

                if (response.ok) {
                    const blob = await response.blob();

                    const url = window.URL.createObjectURL(blob);
                    const filename = response.headers.get('Content-Disposition').split('filename=')[1];
                    const link = document.createElement('a');
                    link.href = url;
                    link.download = filename; // Use the filename received from the server

                    document.body.appendChild(link);
                    link.click();

                    document.body.removeChild(link);
                    window.URL.revokeObjectURL(url);

我将文件保存到我的“下载”文件夹中,并使用正确的命名和类型 .pdf 但我打不开它,因为它坏了。

我检查了blob.type(application/pdf),内容类型标头(application/pdf,utf-8) 我使用 fs.writeFileSync(filePath, pdfBytes) 在服务器端本地保存 pdf 文件 - 它打开得很好。 但是,当我尝试从前端生成并获取文件时,文件就损坏了。

可能是什么原因? TIA

node.js pdf pdf-generation
1个回答
0
投票

尝试通过更改以下行来传递您在等待调用中收到的 blob 类型,

const url = window.URL.createObjectURL(blob);

const blobObj = new Blob([blob], { type: blob.type });
const url = window.URL.createObjectURL(blobObj);
© www.soinside.com 2019 - 2024. All rights reserved.