How do you download a PDF from an API in angular2

2019-05-15 20:09发布

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?

2条回答
我命由我不由天
2楼-- · 2019-05-15 20:46

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);
            });
查看更多
不美不萌又怎样
3楼-- · 2019-05-15 21:02

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

查看更多
登录 后发表回答