Base64代表PDF到blob - JavaScript [英] Base64 representing PDF to blob - JavaScript

查看:414
本文介绍了Base64代表PDF到blob - JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表示PDF文件的Base64字符串。
我想用javascript将它转换为Blob对象的文件。
完成后我想使用FileSaver.js将blob保存为PDF文件。

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.

这是我的代码:

var base64PDF = JVBERi0xLjQNCiW0t..; // This is a huge string.
var blob = new Blob([base64PDF], { type: 'application/pdf' });
saveAs(blob, "test.pdf");

此代码不起作用。它保存了一个test.pdf,说它无法打开这个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.

我也试过这样做:

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?

推荐答案

这个javascript将base64字符串转换为blob对象:

This javascript converts a base64 string to a blob object:

// 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);

这篇关于Base64代表PDF到blob - JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆