RSS

Monthly Archives: March 2012

ASP.NET MVC embedded pdf file always downloads and shows a blank page in Google Chrome

The other day I had to create a controller method to return a pdf file for the browser’s embedded viewer to display. On the whole, this was pretty easy, I quickly got the embedded file to display in IE, Opera and Firefox just using the standard File ActionResult method from the controller:

    [HttpGet]
    public ActionResult GetPdfFile()
    {
        return File("Path/To/My/PDF/File", "application/pdf", "MyPdfFile");
    }

However, on Chrome, I just got a blank page and the file was downloaded rather than displayed in the viewer. In the page that renders the viewer html I had this:

    " width="200" height="200"></embed>

After much searching on t’interweb I found the solution. The file was being downloaded because the Content-Disposition header in the response was being set by the File ActionResult method to ‘attachment; filename=MyPdfFile’. It just happened that the viewers in the other browsers weren’t taking much notice of this and the viewer was displaying it anyway. Chrome however, seemed to be handling it to the letter and downloading the file whilst showing the blank page.

The solution was to set the Content-Disposition response header to ‘inline; filename=MyPdfFile’. Therefore I added the following lines to the controller method:

    [HttpGet]
    public ActionResult GetPdfFile()
    {
        Response.Headers.Remove("Content-Disposition");
        Response.Headers.Add("Content-Disposition", "inline; filename=MyPdfFile");
        return File("Path/To/My/PDF/File", "application/pdf", "MyPdfFile");
    }

Much to my frustration, it still wasn’t working though. Turned out this was because the File method was overwriting the Content-Disposition response header with ‘attachment; filename=MyPdfFile’ because I specified the filename in the third input parameter of the method. So I changed it again to:

    [HttpGet]
    public ActionResult GetPdfFile()
    {
        Response.Headers.Remove("Content-Disposition");
        Response.Headers.Add("Content-Disposition", "inline; filename=MyPdfFile");
        return File("Path/To/My/PDF/File", "application/pdf");
    }

And it finally worked. At which point I punched the air and shouted ‘woohoo’. I just hope you found this post before trawling through various different forums trying to find an answer to this problem, to no avail.

 
2 Comments

Posted by on March 19, 2012 in asp.net, asp.net mvc, dotnet