Javascript:在字节数组的新选项卡中打开 PDF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28197179/
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
Javascript: Open PDF in new tab from byte array
提问by Jeremy Wagner
I'm using AngularJS with an HTTP resource to call an external API and my response is a byte array. I need to turn this byte array into a PDF in a new window. I haven't seen any very good solutions on here that work cross browser or that are pure javascript. Is there a way to do this?
我使用带有 HTTP 资源的 AngularJS 来调用外部 API,我的响应是一个字节数组。我需要在新窗口中将此字节数组转换为 PDF。我还没有在这里看到任何非常好的解决方案,可以跨浏览器工作或纯 javascript。有没有办法做到这一点?
Here is my code:
这是我的代码:
Javascript
Javascript
Document.preview({id: $scope.order.id}, function(data){
// Open PDF Here
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
});
回答by aniltilanthe
You would need to pass the responseType in your service call
您需要在服务调用中传递 responseType
$http.post('/Service-URL', dataTO, {responseType: 'arraybuffer'});
then in the success of your data call this should open up pdf in a new window:-
然后在您的数据调用成功后,这应该在新窗口中打开 pdf:-
getDocument()
.success(function(data) {
var file = new Blob([data], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
})
From this answer :- https://stackoverflow.com/a/21730535/3645957by https://stackoverflow.com/users/2688545/michael
从这个答案:- https://stackoverflow.com/a/21730535/3645957by https://stackoverflow.com/users/2688545/michael
回答by Gonnarule
If anyone still looks for that, here is what I'm doing (and working) :
如果有人仍然在寻找,这就是我正在做的(和工作的):
var pdfAsDataUri = "data:application/pdf;base64,"+byteArray;
window.open(pdfAsDataUri);
Where byteArray is the data you receive. It's maybe not a nice solution (byte array is visible in the URL), but it works...
其中 byteArray 是您收到的数据。这可能不是一个好的解决方案(字节数组在 URL 中可见),但它有效......

