1

In my Angular 7 application, I have the following code for downloading PDF on various platforms.

this.http.get('/api/url', {responseType: 'blob'}).pipe(map(res => {
      return {
        filename: 'filename.pdf',
        data: res
      };
    }))
      .subscribe(
        res => {
          const fileBlob = new Blob([res.data], {type: 'application/pdf'});

          if (navigator && navigator.msSaveBlob) { // IE10+
            navigator.msSaveBlob(fileBlob, res.filename);
          } else if (navigator.userAgent.match('CriOS')) { // iOS Chrome
            const reader = new FileReader();
            reader.onloadend = () => {
              window.location.href = reader.result.toString();
            };
            reader.readAsDataURL(fileBlob);
          } else if (navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPhone/i)) { // iOS Safari and Opera
            const url: string = URL.createObjectURL(fileBlob);
            window.location.href = url;
          } else {
            const url: string = URL.createObjectURL(fileBlob);
            const a: any = document.createElement('a');
            document.body.appendChild(a);
            a.setAttribute('style', 'display: none');
            a.href = url;
            a.download = res.filename;
            a.click();
            URL.revokeObjectURL(url);
            a.remove();
          }
        }
      );

The download works fine on all platforms except Chrome iOS. I mainly followed this link and a few other similar links.

I have also tried the following cases for Chrome iOS

const reader = new FileReader();
reader.onloadend = () => {
    window.open(reader.result.toString());
};
reader.readAsDataURL(fileBlob);

Also replaced onloadend with onload above and tried both ways. Plus I tried also with the code for Safari, but that failed as well.

Any idea what I maybe missing here?

Philip John
  • 5,275
  • 10
  • 43
  • 68

1 Answers1

-2

removing the custom chrome ios check worked for me:

        ...subscribe(response => {
            const file = new Blob([response.body], {type: 'application/pdf'});
            const fileURL = (window.URL || window['webkitURL']).createObjectURL(file);
            const fileName = 'Whatever.pdf';

            const downloadLink = document.createElement('a');
            downloadLink.href = fileURL;
            downloadLink.download = fileName;
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
        })
jm__
  • 112
  • 1
  • 4