PDF Blob is not showing content, Angular 2

I had a lot of problems with downloading and showing content of PDF, I probably wasted a day or two to fix it, so I’ll post working example of how to successfully download PDF or open it in new tab:

myService.ts

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

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

        }
    );

NOTE

It is also worth mentioning that if you are extending Http class to add headers to all your requests or something like that, it can also create problems for downloading PDF because you will override RequestOptions, which is where we add responseType: ResponseContentType.Blob and this will get you The request body isn't either a blob or an array buffer error.

Leave a Comment