使用 API 调用在 ReactJS 中将 base64 转换为 PDF

base64 to PDF in ReactJS using API call

我很难在浏览器中显示 PDF,尽管我正在获取 Base64 代码并使用在线工具 (https://base64.guru/converter/decode/pdf),但我可以看到代码转换为存储在后台的正确 PDF 文件。 之后我转换为 blob 对象,然后当我单击按钮时它似乎没有在 adobe reader 中打开。

// when the button is pressed, it will call the API to get the PDF document 

 const headers = new Headers();
        headers.append("content-type", "application/json");
        headers.append("responseType", "arraybuffer");

        const options = {
          method: "POST",
          headers,
          credentials: "include",
          body: JSON.stringify(invoice_Object),
          // body: "My HTML String",
        };

        const newRequest = new Request("http://localhost:5000/api/invoice-only", options);

        (async () => {
          const invoice_Call = await fetch(newRequest)
            .then((res) => {
              return text1 = res.text();
            })
            .then((data) => {
             generateFile(data, invoice_Name);// here data is the actual item that i am looking to display as PDF document
            });
        })();
      };

   let generateFile = (content, fileName) => {
       console.log("content", content); // here at console if i copy the code and use online tool(https://base64.guru/converter/decode/pdf) it shows the correct pdf
       const blob = new Blob([content], { type: "application/pdf" });
       console.log(blob);
       const link = document.createElement("a");
       link.href = window.URL.createObjectURL(blob);
       link.download = fileName;
       link.click();
       };

     fs.readFile(`${__dirname}\` + `${Invoice_No_Actual}` + `.pdf`, (err, data) => {
          if (err) res.status(500).send(err);
          else {
                   res.contentType("application/pdf");
                 res.send(`data:application/pdf;base64,${new Buffer.from(data).toString("base64")}`);
          }
        });
      }

您的响应类型必须是 arraybuffer 才能从中创建一个 blob。保持 blob 的内容类型不变 (application/pdf):

const headers = new Headers();
    headers.append("content-type", "application/json");
    headers.append("responseType", "arraybuffer");

编辑:请看下面我的评论,你似乎在解析无效的 base64