PDF Blob没有显示内容,Angular 2

Lou*_*cký 15 pdf blob bytearray angular

我的问题非常类似于这个PDF Blob - 弹出窗口没有显示内容,但我使用的是Angular 2.问题的回答是将responseType设置为arrayBuffer,但它在Angular 2中不起作用,错误是reponseType没有存在于RequestOptionsArgs类型中.我也尝试通过BrowserXhr扩展它,但仍然不起作用(https://github.com/angular/http/issues/83).

我的代码是:

createPDF(customerServiceId: string) {
   console.log("Sending GET on " + this.getPDFUrl + "/" + customerServiceId);

   this._http.get(this.getPDFUrl + '/' + customerServiceId).subscribe(
       (data) => {
            this.handleResponse(data);
         });
}
Run Code Online (Sandbox Code Playgroud)

而handleResponse方法:

handleResponse(data: any) {
     console.log("[Receipt service] GET PDF byte array " + JSON.stringify(data));

     var file = new Blob([data._body], { type: 'application/pdf' });            
     var fileURL = URL.createObjectURL(file);
     window.open(fileURL);
 }
Run Code Online (Sandbox Code Playgroud)

我也尝试从FileSaver.js中保存方法,但是同样的问题,pdf打开,但内容不显示.谢谢

Ste*_*ota 60

我在下载和显示PDF内容方面遇到了很多问题,我可能浪费了一两天来修复它,所以我将发布如何成功下载PDF或在新标签中打开它的工作示例:

myService.ts

downloadPDF(): any {
        return this._http.get(url, { responseType: ResponseContentType.Blob }).map(
        (res) => {
            return new Blob([res.blob()], { type: 'application/pdf' })
        }
}
Run Code Online (Sandbox Code Playgroud)

myComponent.ts

this.myService.downloadPDF().subscribe(
        (res) => {
            saveAs(res, "myPDF.pdf"); //if you want to save it - you need file-saver for this : https://www.npmjs.com/package/file-saver

        var fileURL = URL.createObjectURL(res);
        window.open(fileURL); / if you want to open it in new tab

        }
    );
Run Code Online (Sandbox Code Playgroud)

注意

还值得一提的是,如果您要扩展Http类以添加headers所有请求或类似的东西,它也会产生下载PDF的问题,因为您将覆盖RequestOptions,这是我们添加的地方responseType: ResponseContentType.Blob,这将导致The request body isn't either a blob or an array buffer错误.


MPP*_*NBD 5

角度5

我遇到了同样的问题,我为此损失了几天。

在这里我的回答可能对其他人有帮助,这有助于渲染pdf。

对我来说,即使我提到responseType:'arraybuffer',它也无法接受它。

为此,您需要提及为responseType:'arraybuffer'为'json'。(参考

工作代码

downloadPDF(): any {
    return this._http.get(url, {  responseType: 'blob' as 'json' }).subscribe((res) => {
        var file = new Blob([res], { type: 'application/pdf' });            
        var fileURL = URL.createObjectURL(file);
        window.open(fileURL);
    }
}
Run Code Online (Sandbox Code Playgroud)

参考以下链接

https://github.com/angular/angular/issues/18586