Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download PDF file, Angular 6 and Web API

I want to download PDF using Angular 6 and Web API. Here is the code implementation,

mycomponent.ts

download(myObj: any) {
    this.testService.downloadDoc(myObj.id).subscribe(result => {

        var url = window.URL.createObjectURL(result);
        window.open(url);
        console.log("download result ", result);
    });
}

myService.ts

downloadDoc(Id: string): Observable<any> {
    let url = this.apiUrl + "api/myApi/download/" + Id;
    return this.http.get(url, { responseType: "blob" });
}

Web API Service

[HttpGet("download/{DocId}")]
    public async Task<HttpResponseMessage> GetDocument(string docId)
    {
        var docDetails = await _hoaDocs.GetDocumentDetails(docId).ConfigureAwait(false);
        var dataBytes = docDetails.Stream;
        var dataStream = new MemoryStream(dataBytes);

        var response = new HttpResponseMessage
        {
            StatusCode = HttpStatusCode.OK,
            Content = new StreamContent(dataStream)
        };

        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = docDetails.File_Name
        };
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

        return response;
    }

When I execute the above code, it is not downloading the PDF, here is the result object that is logged in the console

download result  
Blob(379) {size: 379, type: "application/json"}
size:379
type:"application/json"
__proto__:Blob
like image 797
Madhu Avatar asked Aug 01 '18 02:08

Madhu


4 Answers

import { Injectable } from "@angular/core";
declare var $;

@Injectable()
export class DownloadFileService {

   save(file, fileName) {
       if (window.navigator.msSaveOrOpenBlob) {
        // IE specific download.
        navigator.msSaveBlob(file, fileName);
    } else {
        const downloadLink = document.createElement("a");
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
        downloadLink.setAttribute("href", window.URL.createObjectURL(file));
        downloadLink.setAttribute("download", fileName);
        downloadLink.click();
        document.body.removeChild(downloadLink);
     }
   }
}
like image 117
anees Avatar answered Nov 12 '22 20:11

anees


I am assuming you are using .Net Core.

You return type is HttpResponseMessage. For .Net Core onward, it should be IActionResult.

So, in your case, you will be returning

return File(<filepath-or-stream>, <content-type>)

Or

You have to make one small change in your Startup.cs file:

services.AddMvc().AddWebApiConventions();

Then, I am not 100% sure here, but you have to change the routing too:

routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
like image 43
r2018 Avatar answered Nov 12 '22 19:11

r2018


In some browser, We need to dynamically create Anchor tag and make it clickable in order to download files. Here is the code .

  const link = document.createElement('a');
  link.href = window.URL.createObjectURL(blob);
  link.download = filename;
  link.click();

Hope, this helps. Thanks.

like image 1
Suresh Kumar Ariya Avatar answered Nov 12 '22 21:11

Suresh Kumar Ariya


dataService.ts

  downloadNoteReceipt(notes_purchased_id: number):Observable<Blob>{    
        return this.httpClient.get(this.baseUrl + `receipt/notespurchasedreceipt/` + notes_purchased_id, { responseType: "blob" } );
      }

component.ts

  download(booking_id: number) {
    this.orderDetailsService.downloadNoteReceipt(booking_id).subscribe(res => {
      console.log(res);
      var newBlob = new Blob([res], { type: "application/pdf" });

      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(newBlob);
        return;
    }
     // For other browsers: 
            // Create a link pointing to the ObjectURL containing the blob.
            const data = window.URL.createObjectURL(newBlob);

            var link = document.createElement('a');
            link.href = data;
            link.download = "receipt.pdf";
            // this is necessary as link.click() does not work on the latest firefox
            link.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));

            setTimeout(function () {
                // For Firefox it is necessary to delay revoking the ObjectURL
                window.URL.revokeObjectURL(data);
            }, 100);

    }, error => {
      console.log(error);
    })
  }

component.html

 <i class="fa fa-download" style="font-size:20px;color:purple" aria-hidden="true" (click)="download(row.booking_id)"></i>
like image 1
Sachin from Pune Avatar answered Nov 12 '22 21:11

Sachin from Pune