How do we download a pdf from external url in angular?

Viewed 1296

I tried to use file-saver module but it is opening the URL in the new page instead of getting downloaded. Here is the snippet I used. Can anyone help me with this?

this.pdfurl = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
const blob = new Blob([this.pdfurl],{type:'applicaton/pdf'})
fileSaver.saveAs(this.pdfurl,"download.pdf");
1 Answers

This works for me:

rest.service.ts

@Injectable()
export class RestService {

  constructor(private httpClient: HttpClient) {
  }

  public downloadPdf() {
    return this.httpClient.get(`https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf`, {
      responseType: 'arraybuffer',
      headers: new HttpHeaders().append('Content-Type', 'application/pdf'),
    });
  }
}

usage of Service (eg. inside TS of component):

this.restService.downloadPdf().subscribe((response: ArrayBuffer) => download(response, 'application/pdf', 'download.pdf'))

download.function.ts

export function download(binaryData: ArrayBuffer, fileType: string, fileName: string): void {
  const file: Blob = new Blob([binaryData], {type: fileType});
  const url: string = window.URL.createObjectURL(file);
  const anchorElement: HTMLAnchorElement = document.createElement('a');
  anchorElement.download = fileName;
  anchorElement.href = url;
  anchorElement.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));
}
Related