简体   繁体   中英

How can i download the pdf directly from the API (Angular)?

I need to download a PDF from an API in Angular.

So, I've written a service to call the API:

 getPDF(id:any) {
    return this.http.get(
       `url?=${id}`,
        { responseType: 'blob' as 'json', observe: 'response' }
    );
 }

In my component file, I'm calling the service to download the PDF.

  onGeneratepdf() {
    this.service
  .getPDF(
    123
  )
  .subscribe((res: any) => {
    let filename = res.header
    ?.get('content-disposition')
    ?.split(';')[1]
    .split('=')[1];
  let blob: Blob = res.body as Blob;
  var a = document.createElement('a');
  a.download = filename;
  a.href = window.URL.createObjectURL(blob);
  a.click();
  });

}

after hitting onGeneratePDF, the pdf is downloading but the problem is....it is downloading the file name as undefined.pdf ...it should download as name like user.pdf and also i am getting the response headers as

access-control-allow-origin: *

cache-control: no-cache, no-store, max-age=0, must-revalidate

content-disposition: attachment; filename=user.pdf

content-type: application/pdf

Please help me on these issue.

Thanks in advance.

onGeneratepdf() {
        this.service
      .getPDF(
        123
      )
      .subscribe((res: any) => {
        let filename = res.headers
        ?.get('content-disposition')
        ?.split(';')[1]
        .split('=')[1];
      let blob: Blob = res.body as Blob;
      var a = document.createElement('a');
      a.download = filename;
      a.href = window.URL.createObjectURL(blob);
      a.click();
      });

Please try above code, you wrote res.header that should be res.headers

if above code not works for you, then take look at below link you will find your solution there Here .

Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM