Make any link with .pdf open in new window with jQuery?
To achieve this you can select any a
element which has a href
property ending with .pdf
, and add a target="_blank"
attribute to it. Try this:
$(function() {
$('a[href$=".pdf"]').prop('target', '_blank');
});
One way, assuming you want links not ending in pdf
to open in the same page:
$('a').click(
function(e){
e.preventDefault();
if (this.href.split('.').pop() === 'pdf') {
window.open(this.href);
}
else {
window.location = this.href;
}
});
<a onclick=ViewPdf(test.pdf) href="">
function ViewPdf(FileName) {
var url = '../Home/GetPDF?fileName=' + FileName;
window.open(url, '_blank');
}
Now write ActionResult like below
public ActionResult GetPDF(string fileName)
{
try
{
byte[] fileData = System.IO.File.ReadAllBytes(Functions.GetConfigValue("CDXFilePath") + fileName);
string resultFileName = String.Format("{0}.pdf", fileName);
Response.AppendHeader("Content-Disposition", "inline; filename=" + resultFileName);
return File(fileData, "application/pdf");
}
catch
{
return File(Server.MapPath("/Content/") + "FileNotFound.html", "text/html");
}
}