Search code examples
.netasp.net-web-api2

Pdf from web api service not opening


Below is my code, actually it downloads pdf file but it might be corrupt or something wrong with it. Can you please help me with this?

public Task<HttpResponseMessage> ExportPDF()
    {
        HttpResponseMessage response =
           Request.CreateResponse(System.Net.HttpStatusCode.BadRequest, "No data to export.");
        MemoryStream _stream = new MemoryStream();
        try
        {
            _stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("da adasdasd adasd"));
            //if file the dowload
            if (_stream.Length > 0)
            {
                response = Request.CreateResponse(HttpStatusCode.OK);
                response.Content = new StreamContent(_stream);
                response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("inline");
                response.Content.Headers.ContentLength = _stream.Length;
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
                response.Content.Headers.ContentDisposition.FileName = "Responses.pdf";
            }
            return Task.FromResult(response);
        }
        catch (Exception ex)
        {
            return Task.FromResult(response); 
        }
    }

And Below is result: enter image description here


Solution

  • Thanks All, I have used "SelectPDF" library and it is working fine now!