使用javascript下载时PDF为空白 [英] PDF is blank when downloading using javascript

查看:45
本文介绍了使用javascript下载时PDF为空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Web 服务,它在其响应中返回 PDF 文件内容.当用户单击链接时,我想将其下载为 pdf 文件.我在UI中编写的javascript代码如下:

I have a web service that returns PDF file content in its response. I want to download this as a pdf file when user clicks the link. The javascript code that I have written in UI is as follows:

$http.get('http://MyPdfFileAPIstreamURl').then(function(response){
var blob=new File([response],'myBill.pdf',{type: "text/pdf"});
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="myBill.pdf";
link.click();
});

'response' 包含来自 'MyPdfFileAPIstreamURl' servlet 输出流的 PDF 字节数组.而且流也没有加密.

'response' contains the PDF byte array from servlet outputstream of 'MyPdfFileAPIstreamURl'. And also the stream is not encrypted.

所以当我点击链接时,一个大约 200KB 的 PDF 文件被成功下载.但是当我打开这个文件时,它打开了空白页.下载的pdf文件的起始内容在图片中.

So when I click the link, a PDF file gets downloaded successfully of size around 200KB. But when I open this file, it opens up with blank pages. The starting content of the downloaded pdf file is in the image.

我不明白这里有什么问题.帮助!

I can't understand what is wrong here. Help !

这是下载的pdf文件起始内容:

This is the downloaded pdf file starting contents:

推荐答案

通过 XMLHttpRequest 和 xhr.responseType = 'arraybuffer'; 解决代码:

solved it via XMLHttpRequest and xhr.responseType = 'arraybuffer'; code:

var xhr = new XMLHttpRequest();
    xhr.open('GET', './api/exportdoc/report_'+id, true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function(e) {
       if (this.status == 200) {
          var blob=new Blob([this.response], {type:"application/pdf"});
          var link=document.createElement('a');
          link.href=window.URL.createObjectURL(blob);
          link.download="Report_"+new Date()+".pdf";
          link.click();
       }
    };
xhr.send();

这篇关于使用javascript下载时PDF为空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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