PDF Blob is not showing content, Angular 2 PDF Blob is not showing content, Angular 2 arrays arrays

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.


ANGULAR 5

I had the same problem which I lost few days on that.

Here my answer may help others, which helped to render pdf.

For me even though if i mention as responseType : 'arraybuffer', it was unable to take it.

For that you need to mention as responseType : 'arraybuffer' as 'json'.(Reference)

Working code

downloadPDF(): any {    return this._http.get(url, {  responseType: 'blob' as 'json' }).subscribe((res) => {        var file = new Blob([res], { type: 'application/pdf' });                    var fileURL = URL.createObjectURL(file);        window.open(fileURL);    }}

Referred from the below link

https://github.com/angular/angular/issues/18586


Amit, You can rename the filename by adding a variable to the end of the stringso saveAs(res, "myPDF.pdf");

Becomes

saveAs(res, "myPDF_"+someVariable+".pdf");

where someVariable might be a counter or my personal favorite a date time string.