tags:

views:

542

answers:

3

Hi

How do I (in my controller) send a pdf that opens in the browser. I have tried this but it only downloads the file (both ie and firefox) without asking.

public ActionResult GetIt()
{
    var filename = @"C:\path\to\pdf\test.pdf";
    // Edit start
    ControllerContext.HttpContext.Response.AddHeader("Content-Disposition", String.Format("inline;filename=\"{0}\"", "test.pdf"));
    // Edit stop
    return File(filename, "application/pdf", Server.HtmlEncode(filename));
}

After adding the edit above it works as it should, thanks.

+1  A: 

I think this relies on how the client handles PDF files. If it has setup to let Adobe Reader open the files in the browser plugin it will do that, but maybe you have set it up to download the file rather than opening it. In any case, there is no way of controlling how PDF files will be opened on the user's machine.

tomlog
No, my client works as expected on other websites. Sometimes it downloads, sometimes it opens in adobe plug-in. It's probably got something to do with the headers sent.
Nifle
Yeah, it's the headers - see comments below.
Steve Claridge
+2  A: 

This (in addition to the other headers) does the trick for me in a plain .net web app:

Response.AddHeader("Content-Disposition", String.Format("attachment;filename=""{0}""", FileName))

I'm not familiar with MVC, but hopefully this helps.

ScottE
I think you need to set the disposition to inline rather than attachment. Using attachment forces it to save the file to disk.
Steve Claridge
Yes, sorry, quick on my copy / paste. That would open it in a new window, this will attempt to open it in the same window: Response.AddHeader("Content-Disposition", String.Format("inline;filename=""{0}""", FileName))
ScottE
+4  A: 

You need to set the Content disposition HTTP header to inline to indicate to the browser that it should try to use a PDF plugin if it is available.

Something like: Content-Disposition: inline; filename=test.pdf

Note that you cannot force the use of the plugin, it is a decision made by the browser.

Steve Claridge