Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a PDF in an action result in MVC

I have a little problem getting my head around this problem. I have an ajax call that should render an iframe which loads a PDF. The PDF is generated using Apache FOP hosted in another environment. What I have so far is:

in the controller action (where the src element of the iFrame points), the code snippet is:

var targetStream = new MemoryStream();    
using (var response = FOPrequest.GetResponse()) // response from FOP
                {
                    using (var stream = response.GetResponseStream())
                    {
                        stream.CopyTo(targetStream);

                    }
                }
 return new FileStreamResult(targetStream, "application/pdf");

However, this does not work as expected. The stream is populated as expected, but the PDF does not render in the iFrame. I get a Http response code of 200 (OK).

I'd be grateful of any help.

like image 243
Faithypop Avatar asked May 08 '15 10:05

Faithypop


People also ask

What is the return type of action result in MVC?

An ActionResult is a return type of a controller method in MVC. Action methods help us to return models to views, file streams, and also redirect to another controller's Action method.

What is return type of action result?

The ActionResult types represent various HTTP status codes. Any non-abstract class deriving from ActionResult qualifies as a valid return type. Some common return types in this category are BadRequestResult (400), NotFoundResult (404), and OkObjectResult (200).


2 Answers

You use MVC FileContentResult to return ActionResult For example:

return File(fileArray, contentType, fileName)

another stack Answer

like image 109
Shawnas Avatar answered Oct 19 '22 16:10

Shawnas


You can make use of the return type as FileResult here like this :

public FileResult getFile(string CsvName)
{
   //Add businees logic here
   byte[] fileBytes = System.IO.File.ReadAllBytes(System.Web.Hosting.HostingEnvironment.MapPath("~/Content/Uploads/records.csv"));
   string fileName = CsvName;
   return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}

Might not be the exact solution, you can manipulate and develop your own.

Hope this helps.

like image 7
Matt Murdock Avatar answered Oct 19 '22 15:10

Matt Murdock