Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open PDF result in browser tab with MVC 3

I am using ASP.NET MVC 3. I have a controller action that returns a PDF file like this:

Public Class ReportController
    ...
    Function Generate(id As Integer) As ActionResult
        ...
        Return File(output, "application/pdf", "something.pdf")
        ' "output" is a memory stream
    End Function

The code works but Firefox doesn't display the result in a tab, the result is either downloaded or opened with Adobe Reader.

I know that Firefox can display PDF in a tab because I can just google some PDF, click the link, and the PDF will open in a tab.

How do I set up the action so the PDF will open in a tab?

like image 822
Endy Tjahjono Avatar asked May 29 '11 16:05

Endy Tjahjono


People also ask

How do I open a PDF in a new tab or window instead of downloading in C# MVC?

click(function (e) { // if using type="submit", this is mandatory e. preventDefault(); window. open('@Url. Action("PdfInvoice", "ControllerName", new { customerOrderselectedId = selectedId })', '_blank'); });


2 Answers

I got the answer from the related links on the right:

Response.AppendHeader("Content-Disposition", "inline")
Return File(output, "application/pdf")

The PDF opens in a tab, but the filename hint is lost, even if I do it like this:

Response.AppendHeader("Content-Disposition", "inline; filename=something.pdf")
Return File(output, "application/pdf", "something.pdf")

So finally I didn't bother to give filename hint at all.

EDIT

ASP.NET MVC 3's File with 3 parameters:

Return File(output, "application/pdf", "something.pdf")

will add Content-Disposition: attachment; filename="something.pdf" to the response header, even if there is already a Content-Disposition in the response header.

So if you manually added Content-Disposition to the header, and then use File with 3 parameters, you end up with two Content-Disposition headers. Firefox 8 will say that the response is corrupted if the response header is like this.

So best way to do it now is add Content-Disposition manually for 'inline', and then use File with 2 parameters:

Response.AppendHeader("Content-Disposition", "inline; filename=something.pdf")
Return File(output, "application/pdf")
like image 132
Endy Tjahjono Avatar answered Nov 08 '22 00:11

Endy Tjahjono


This is configurable in your browser. You can change the settings to download / open in browser or open in relevant application in tools->options->applications section for all file types. Thi has nothing to do with your code.

like image 34
Jayantha Lal Sirisena Avatar answered Nov 07 '22 22:11

Jayantha Lal Sirisena