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

Ruben Valas picture Ruben Valas · Aug 20, 2016 · Viewed 9.3k times · Source

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?

Answer

Kiran Shenoy picture Kiran Shenoy · Sep 30, 2016

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