Neelima Ediga
Neelima Ediga

Reputation: 356

Pdf download in Angular 2 or Angular 4

We have designed a page in Angular4, which has Download PDF files functionality in it. When the user clicks on download, my application makes a call to a web API and get the PDF file data. I have used filesaver package for this. Below is the code snippet of it.

Angular4 code:

    downloadPdf(url: string, body: any, basePage: BaseErrorPage, showSpinner: boolean = false, goBackToMaster: boolean = true) {
    if (showSpinner) {
        basePage.spinner.runningRefCountIncrement();
    }

    let headers = new Headers({ 
        'UserID': this.storage.UserID,
        'ADUserName': this.storage.ADUserName,
        'Content-Type': 'application/json', 
        'Accept': 'application/pdf'
    });        

    let options = new RequestOptions({ headers: headers });
    options.responseType = ResponseContentType.Blob;

    this.http.get(
        url).subscribe(
          (response) => {
            var mediaType = 'application/pdf';
            var blob = new Blob([response.blob], {type: mediaType});
            var filename = 'test.pdf';
            console.log(blob);
            console.log(response);
            saveAs(blob, filename);
          });
}

And this is how my API looks like:

    [Route("download/{invoiceID}")]
    [HttpGet]
    public HttpResponseMessage DownloadInvoice(int invoiceID)
    {
        var result = service.GetPDFByID(invoiceID);
        if (result == null)
        {
            HttpResponseMessage r4 = new HttpResponseMessage(HttpStatusCode.NotFound);
            return r4;
        }

        HttpResponseMessage r = new HttpResponseMessage(HttpStatusCode.OK);
        r.Content = new StreamContent(new MemoryStream(result.Data));
        r.Content.Headers.ContentType = new MediaTypeHeaderValue("application/blob");
        r.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        r.Content.Headers.ContentDisposition.FileName = result.FileName;

        return r;
    }

The code seems to be working fine to some extent. When I click on download, the API call is hit and response is received. Also, a file is downloaded. However, when I try to open it, it says "Failed to load PDF document." I guess I have done some mistake in the content matching and tried various options, but couldn't succeed.

Does anyone has any inputs on this, please!

Thanks in advance.

Upvotes: 1

Views: 2758

Answers (1)

Neelima Ediga
Neelima Ediga

Reputation: 356

After some research, I was able to resolve the issue. The above code would have worked for .Net Framework 4.6 (or other versions too). But, in my case, I was working on .Net core 2.0/web API2. HttpResponseMessage is returned as a json here. We need to write a customized class inorder to return stream object. Below is the new code, that worked.

Hope this helps someone.

API Controller:

    [HttpGet]
    [ProducesResponseType(typeof(byte[]), 200)]
    public IActionResult Get()
    {
        byte[] buffer = new byte[16 * 1024];
        FileStream fs = new FileStream("C:\\Backup\\123.pdf", FileMode.Open);

        string fileName = "FileName.pdf";
        return new FileResultFromStream(fileName, fs, "application/pdf");            
    }

Custom class below:

   public class FileResultFromStream : ActionResult
   {
    public FileResultFromStream(string fileDownloadName, Stream fileStream, string contentType)
    {
        FileDownloadName = fileDownloadName;
        FileStream = fileStream;
        ContentType = contentType;
    }

    public string ContentType { get; private set; }
    public string FileDownloadName { get; private set; }
    public Stream FileStream { get; private set; }

    public async override Task ExecuteResultAsync(ActionContext context)
    {
        var response = context.HttpContext.Response;
        response.ContentType = ContentType;
        context.HttpContext.Response.Headers.Add("Content-Disposition", new[] { "attachment; filename=" + FileDownloadName });
        await FileStream.CopyToAsync(context.HttpContext.Response.Body);
    }
  }

And Angular 4 code :

   downloadPdf(url: string, fileName: string, body: any, basePage: BaseErrorPage, showSpinner: boolean = false, goBackToMaster: boolean = true) 
   {

    if (showSpinner) {
        basePage.spinner.runningRefCountIncrement();
    }

    let headers = new Headers({ 
        'UserID': this.storage.UserID,
        'ADUserName': this.storage.ADUserName,
        'Content-Type': 'application/json', 
        'Accept': 'application/pdf'
    });        

    let options = new RequestOptions({ headers: headers });
    options.responseType = ResponseContentType.ArrayBuffer;

    this.http.get(
        url, options).subscribe(
          (response) => {
            var mediaType = 'application/pdf';
            var blob = new Blob([response.blob()], {type: mediaType});
            saveAs(blob, fileName+'.pdf');
          });
    }

Upvotes: 1

Related Questions