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

梦想的初衷 提交于 2019-12-06 03:53:57

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

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