Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I open a pdf file directly in my browser?

Tags:

I would like to view a PDF file directly in my browser. I know this question is already asked but I haven't found a solution that works for me.

Here is my action's controller code so far:

public ActionResult GetPdf(string fileName)
{
    string filePath = "~/Content/files/" + fileName;
    return File(filePath, "application/pdf", fileName);
}

Here is my view:

@{
   doc = "Mode_d'emploi.pdf";
} 

<p>@Html.ActionLink(UserResource.DocumentationLink, "GetPdf", "General", new { fileName = doc }, null)</p>

When I mouse hover the link here is the link:

enter image description here

The problem with my code is that the pdf file is not viewed in the browser but I get a message asking me if I wand to open or save the file.

enter image description here

I know it is possible and my browser support it because I already test it with another website allowing me to view pdf directly in my browser.

For example, here is the link when I mouse hover a link (on another website):

enter image description here

As you can see there is a difference in the generated link. I don't know if this is useful.

Any idea how can I view my pdf directly in the browser?

like image 659
Bronzato Avatar asked Feb 05 '13 18:02

Bronzato


2 Answers

The reason you're getting a message asking you to open or save the file is that you're specifying a filename. If you don't specify the filename the PDF file will be opened in your browser.

So, all you need to do is to change your action to this:

public ActionResult GetPdf(string fileName)
{
    string filePath = "~/Content/files/" + fileName;
    return File(filePath, "application/pdf");
}

Or, if you need to specify a filename you'll have to do it this way:

public ActionResult GetPdf(string fileName)
{
    string filePath = "~/Content/files/" + fileName;
    Response.AddHeader("Content-Disposition", "inline; filename=" + fileName);        

    return File(filePath, "application/pdf");
}
like image 76
ataravati Avatar answered Sep 24 '22 23:09

ataravati


Instead of returning a File, try returning a FileStreamResult

public ActionResult GetPdf(string fileName)
{
    var fileStream = new FileStream("~/Content/files/" + fileName, 
                                     FileMode.Open,
                                     FileAccess.Read
                                   );
    var fsResult = new FileStreamResult(fileStream, "application/pdf");
    return fsResult;
}
like image 34
Forty-Two Avatar answered Sep 23 '22 23:09

Forty-Two