在ReactJS/Javascript中将Base64转换为PDF文件时遇到错误
我正在努力将PDF显示为ReactJS中的附件。我已经设法将base64带到前端,但是在我尝试创建blob对象之后,它不起作用,尽管它转到Acrobat阅读器,但显示了错误。如有任何建议,请告知如何将base64正确转换为pdf 我还上传了base64代码,这是我在pastebin登录控制台时得到的 注意: 当我试图修复时,它显示了无效的字符串和字符(数据:application/pdf;),我尝试使用在ReactJS/Javascript中将Base64转换为PDF文件时遇到错误,javascript,reactjs,pdf,pdf-generation,blob,Javascript,Reactjs,Pdf,Pdf Generation,Blob,我正在努力将PDF显示为ReactJS中的附件。我已经设法将base64带到前端,但是在我尝试创建blob对象之后,它不起作用,尽管它转到Acrobat阅读器,但显示了错误。如有任何建议,请告知如何将base64正确转换为pdf 我还上传了base64代码,这是我在pastebin登录控制台时得到的 注意: 当我试图修复时,它显示了无效的字符串和字符(数据:application/pdf;),我尝试使用content.slice(29)因此它将从JVB…(而不是从数据:application/p
content.slice(29)代码>因此它将从JVB…
(而不是从数据:application/pdf;base64,JVBERi0xL…
)开始,但得到相同的错误。
错误:
未正确解码
- NodeJS-baackend代码响应API调用
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")}`);
}
});
- 前端代码API调用
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()函数调用前端-收到响应后
- 打开时出错
一个简单的
console.log(content.slice(29))
可能会暴露您的错误。问题是content1
变量包含一个以“VBE…”开头的字符串,而它必须以“JVBE…”开头。因此,您的错误是slice()
函数丢弃了太多的字符。在我使用.slice方法后,当我使用联机工具时,字符串输出是生成正确的PDF,因此我认为问题是在创建blob对象时出现的,但不确定是否准确。
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();
};