How to return PDF to result of action in MVC

I have a small problem that puzzles over this problem. I have an ajax call that should display an iframe that loads a PDF file. PDF is created using Apache FOP hosted in a different environment. What I still have:

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

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 properly. The stream fills as expected, but the PDF does not display in the iFrame. I get an Http 200 response code (OK).

I would be grateful for any help.

+4
source share
3 answers

You use MVC FileContentResult to return an ActionResult For example:

return File(fileArray, contentType, fileName)

another stack Answer

+7

FileResult :

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);
}

, .

, .

+6

Set MvcPdfActionResult via nuget

PM> Install-Package MvcPdfActionResult

Just use the return type as the PdfActionResult in the controller will output the PDF instead of HTML. It converts HTML to PDF using the iTextXmlWorker library.

  ...
  return PdfActionResult(model);
}

Creates PDFs from your shaving views in an asp.net 5 MVC project. https://www.nuget.org/packages/MvcPdfActionResult/

+2
source

All Articles