在ReactJS/Javascript中将Base64转换为PDF文件时出现错误

3
我正在努力在ReactJS中将PDF作为附件显示。我已经成功将base64带到前端,但在尝试创建blob对象后,它无法工作,并且虽然它进入了Acrobat阅读器,但显示错误。请问有什么建议可以正确地将base64转换为PDF吗?
我还上传了当我在pastebin上记录控制台日志时获得的base64代码,https://pastebin.com/W4zEXyPy 注意:当我尝试在https://base64.guru/修复时,它显示无效的字符串和字符(data:application/pdf;),我已经尝试使用content.slice(29);,所以它将从JVB...开始(而不是从data:application/pdf;base64,JVBERi0xL........),但是仍然出现相同的错误。 链接到在base64guru中修复Base64的图片 错误:未正确解码。
  • NodeJS baackend code responding to API call

         let token = req.cookies.access_token;
             if (token) {
               let Invoice_No_Actual = req.body.invoice_Name;
               res.set("Content-disposition", "attachment; filename=" + `${__dirname}\\` + `${Invoice_No_Actual}` + `.pdf`);
               res.contentType("application/pdf");
               res.send(`data:application/pdf;base64,${new Buffer.from(data).toString("base64")}`);
             }
           });
    
  • Frontend code API call

     const headers = new Headers();
            headers.append("content-type", "application/json");
            headers.append("responseType", "application/pdf");
    
            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);
                });
            })();
          };
    
  • generateFile() function call Front End- after receiving the response


    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

        let content1= content.slice(29);// content1 is correct base64 as if i use it online tool it correctly generate the PDF document
        const blob = new Blob([content1], { type: "application/pdf" });
        console.log(blob);
        const link = document.createElement("a");
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
      };


使用 .slice 方法后,当我使用在线工具生成正确的 PDF 时,字符串输出是正确的,因此我认为问题出现在创建 blob 对象之后,但不确定确切原因。 - umair
1个回答

1
一个简单的console.log(content.slice(29))可以揭示你的错误。问题在于content1变量包含以"VBE..."开头的字符串,而它必须以"JVBE..."开头。因此,你的错误在于slice()函数丢弃了太多字符。

@umair,你能否分享一下你的最终工作代码?我遇到了完全相同的问题。我的PDF文件已经生成并下载,但是我无法打开它。我得到了你报告的相同错误。我也使用了content.slice(0)并将整个内容放入blob中。 - exlnt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接