Display PDF file embedded in View in MVC

Embed pdf file in View of MVC razor and display pdf file in browser view. If adobe is not installed simply user can download and view file.

Controller

Add below code to View pdf in the post method of Home controller.

// GET: Home
 public ActionResult Index()
 {
     return View();
 }

 [HttpPost]
 public ActionResult ViewPDF()
 {
     string embed = "<object data=\"{0}\" type=\"application/pdf\" width=\"500px\" height=\"300px\">";
     embed += "If you are unable to view file, you can download from <a href = \"{0}\">here</a>";
     embed += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
     embed += "</object>";
     TempData["Embed"] = string.Format(embed, VirtualPathUtility.ToAbsolute("~/Files/Sample.pdf"));

     return RedirectToAction("Index");
 }

View

Add below code in the index view of Home Controller.

@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }
    </style>
</head>
<body>
    <h2>Display PDF file embedded in View in MVC</h2>
    @using (Html.BeginForm("ViewPDF", "Home", FormMethod.Post))
    {
        <a href="javascript:;" onclick="document.forms[0].submit();">View PDF</a>
        <hr/>
        @Html.Raw(TempData["Embed"])
    }
</body>
</html>

Create a new folder names “Files” and add the below pdf sample file to view.

Download sample pdf here

Output

Display pdf file in browser using adobe viewer.

If adobe viewer is not installed then Download pdf file and view same.