elliot-j
elliot-j

Reputation: 12098

MVC - FileContentResult sends corrupted pdf

I have a simple action method that returns a PDF document, that gets shown in an <iframe> with an <embed> tag, and every few calls to this method will return a corrupted PDF. (I've determined its corrupted by using dev tools to save the response from the server)

Action Method:

public FileContentResult GetPdfReport(string Id)
{
    Response.AppendHeader("Content-Disposition", "inline; filename=report.pdf");
    var content = System.IO.File.ReadAllBytes(Server.MapPath("~/Reports/Testfile.pdf"));
    System.IO.File.WriteAllBytes(Server.MapPath("~/Reports/debugReport.pdf"), content);
    return File(content, "application/pdf");
}

View Content:

<embed id="widgetResponsePdf" src="@Url.Action("GetPdfReport", "WidgetResponse", new { Id = "123" })" type="application/pdf" onmouseout="mouseOutHandler();" />

The files TestFile.pdf and debugReport.pdf open just fine when I get a corrupted PDF, and there is no difference in the request and response header between the normal request/response and the corrupted request/response.

Is there some setting in IIS that I am missing that could be causing the inconsistent behavior between requests, or could this be caused solely by a network issue?

Upvotes: 0

Views: 797

Answers (1)

elliot-j
elliot-j

Reputation: 12098

In our case, the IFrame has a src attribute that points to a partial view that loads the <embed> content, which then has a src attribute that points to the actual PDF file instead of a PartialView that returns a FileContentResult. The example below has been simplified from our actual implementation Partial View

<iframe> <!-- iframe is actually loaded from another partial view, it is show here to simplify things -->
    <embed 
         src='@Url.Content(Model.ReportFileName)' 
         type="application/pdf">
    </embed>
</iframe>

Controller

public PartialView GetPdfReport(string Id)
{
    var model = PDFResponseModel 
    {
        ReportFileName = Server.MapPath("~/Reports/Testfile.pdf")
    };
    return PartialView(model);
}

Due to a site restriction for IE support, our users (intranet site) are required to have AdobeAcrobat installed to view PDF's. While this solution works for us, this may not be desirable for internet facing websites.

Upvotes: 1

Related Questions