How do you download a PDF from an API in angular2 RC5?

為{幸葍}努か 提交于 2020-01-13 16:18:28

问题


This previous question had some good work arounds:

Angular 2 download PDF from API and Display it in View

but now that RC5 is out we can use arrayBuffer(). I can't seem to get anywhere with this. How do I go from this to a nice pdf blob:

return this._authHttp.get(this.fileUrl+id)
        .map((res:Response) => res.arrayBuffer())
        .subscribe(
            data => {
                console.log(data);
                var blob = new Blob([data], {type: 'application/pdf'});
                console.log(blob);
                saveAs(blob, "testData.pdf");

        },
            err => console.error(err),
        () => console.log('done')
    );

data ends up being twice the size I would expect. Any ideas what I'm missing?


回答1:


I had same issue while downloading pdf files. I wasted two days to fix this but but got it working finally. U need to set the responseType to blob.

return this._authHttp.get(this.fileUrl+id , 
                         { responseType: ResponseContentType.Blob })
    .map((res:Response) => res.blob())
    .subscribe(
        data => {
            console.log(data);
            var blob = new Blob([data], {type: 'application/pdf'});
            console.log(blob);
            saveAs(blob, "testData.pdf");

    },
        err => console.error(err),
    () => console.log('done')
);

And dont forget to import ResponseContentType

Hope this helps you




回答2:


Thanks man...

This hack, change my life... thanks. But I make an light change.

        this._authHttp.get(URLx, { responseType: ResponseContentType.Blob })
        .map((res:any) => return res) <-- this line change --!>
        .subscribe( 
            data => {
                var mediaType = 'application/pdf';
                var blob = new Blob([data], {type: mediaType});
                var filename = `Veiculo-Eixos-${veiculoDTO.placa}.pdf`;
                // saveAs(blob, filename);
                var fileURL = URL.createObjectURL(blob);
                window.open(fileURL); // if you want to open it in new tab  
            },
            error =>{
                console.log(error);
            });


来源:https://stackoverflow.com/questions/39049260/how-do-you-download-a-pdf-from-an-api-in-angular2-rc5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!