Open PDF File in browser New Tab on Button Click in ASP.Net MVC

Last Reply 23 days ago By dharmendr

Posted 23 days ago

Hello all,

Its exactly like I said. I can open a PDF file in the same tab browser but now when I try to open with target=_blank any way to get a new tab I have not been able to succeed with this.

My button is in a modal. I have a directory with PDF documents. I want to open one of the PDFS in a new tab. That is all.

Here I am looking to see how many PDFs I have, if I have more than 1 I open the folder, otherwise if just 1 I want to open that 1 in a new browser tab.

if (isValid)
{
    ViewBag.AlertSuccess = "The .zip file has been successfully unzipped";
    //OpenPDFs();
    var folderPath = Path.Combine(downloadPath, zipFolder);

    if(Directory.Exists(folderPath))
    {
        var fileCount = Directory.GetFiles(@folderPath, "*.pdf");
        if(fileCount.Length > 1) // more than 1 file
        {
            Process.Start(folderPath);
        }
        else if(fileCount.Length == 1) // exactly only 1 file
        {
            return File(folderPath + "\\" + fileName, "application/pdf");
        }
        else // no files 
        {
            // maybe make alert message says apparently has no files ?!@ ?! !?!?? ??
            Process.Start(folderPath);
        }
    }
}

 

$("#btnUnZip").click(function (e) {
    e.preventDefault();
    window.open('@Url.Action("UnZipDownload", "Service", null, "_blank")');
})

 

Posted 23 days ago

With window.open it is not possible to open only pdf in new tab.

It will open the complete view in new tab.

You need to ues ajax call to the method and based on the condition set the data and open new tab to display the pdf.

Controller

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

    public ActionResult DownloadPDF()
    {
        return View();
    }

    public JsonResult Download()
    {
        var folderPath = Server.MapPath("~/Files");
        var fileCount = Directory.GetFiles(Server.MapPath("~/Files"), "*.pdf");
        if (fileCount.Length == 1) // exactly only 1 file
        {
            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/Test.pdf"));
            return Json("Exist", JsonRequestBehavior.AllowGet);
        }
        else if (fileCount.Length > 1) // more than 1 file
        {
            Process.Start(folderPath);
        }
        else
        {
            Process.Start(folderPath);
        }

        return Json("", JsonRequestBehavior.AllowGet);
    }
}

View

Index

<body>
    <div>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script type="text/javascript">
            $(function () {
                $("#btnDownload").click(function () {
                    $.ajax({
                        type: "POST",
                        url: "/Home/Download",
                        data: {},
                        contentType: "application/json; charset=utf-8",
                        success: function (response) {
                            debugger;
                            if (response == "Exist") {
                                window.open('/Home/DownloadPDF');
                            }
                        },
                        failure: function (response) {
                            alert(response.responseText);
                        },
                        error: function (response) {
                            alert(response.responseText);
                        }
                    });
                });
            });
        </script>
        <input id="btnDownload" type="button" value="Open" />
    </div>
</body>

DownloadPDF

<body>
    <div>
        <%if (TempData["Embed"] != null)
          {%>
        <%:MvcHtmlString.Create(TempData["Embed"].ToString())%>
        <% } %>
    </div>
</body>