Base64 表示 PDF 到 blob - JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36036280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Base64 representing PDF to blob - JavaScript
提问by user3461486
I have a Base64 string representing a PDF file. I want to convert it to a file with the Blob object using javascript. After it's done i want to save the blob as a PDF file using FileSaver.js.
我有一个代表 PDF 文件的 Base64 字符串。我想使用 javascript 将其转换为带有 Blob 对象的文件。完成后,我想使用 FileSaver.js 将 blob 保存为 PDF 文件。
Here is my code:
这是我的代码:
var base64PDF = JVBERi0xLjQNCiW0t..; // This is a huge string.
var blob = new Blob([base64PDF], { type: 'application/pdf' });
saveAs(blob, "test.pdf");
This code doesn't work. It saves a test.pdf that says it can't open this pdf because there was en error in the decoding.
此代码不起作用。它保存了一个 test.pdf,说它无法打开这个 pdf,因为解码中出现错误。
I've also tried to do this:
我也试过这样做:
var base64PDF = JVBERi0xLjQNCiW0t..; // This is a huge string.
var decode = atob(screen.prp_wcfria_ExternalFile.pdfFile);
var blob = new Blob([decode], { type: 'application/pdf' });
saveAs(blob, "test.pdf");
This code also doesn't work. How do i do this?
此代码也不起作用。我该怎么做呢?
回答by Carlos Chaguendo
This javascript converts a base64 string to a blob object:
此 javascript 将 base64 字符串转换为 blob 对象:
// base64 string
var base64str = result.pdf;
// decode base64 string, remove space for IE compatibility
var binary = atob(base64str.replace(/\s/g, ''));
var len = binary.length;
var buffer = new ArrayBuffer(len);
var view = new Uint8Array(buffer);
for (var i = 0; i < len; i++) {
view[i] = binary.charCodeAt(i);
}
// create the blob object with content-type "application/pdf"
var blob = new Blob( [view], { type: "application/pdf" });
var url = URL.createObjectURL(blob);
回答by Musa
You have to convert the base64 string back into the original binary data. Using atob is not sufficient, you'll have to run it through a loop and convert it to an array buffer - Convert base64 string to ArrayBuffer
Then use that to create the blob.
您必须将 base64 字符串转换回原始二进制数据。使用 atob 是不够的,您必须通过循环运行它并将其转换为数组缓冲区 -将 base64 字符串转换为 ArrayBuffer
然后使用它来创建 blob。