Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Open .pdf on a new Tab

The Objective:

I have to print a PDF on a new tab after some tasks have finished correctly.

Steps: I want to execute a method that should go to the server, take the PDF and open it on a new Tab, I was trying with these but is not working:

Controller: Export

 public ActionResult PrintPdf()
    {
        Response.AppendHeader("Content-Disposition", "inline; filename= " + MyClassPdfWriter.GetFileName);
        return File(MyClassPdfWriter.GetMemoryStream, "application/pdf");
    }

View:

function TasksSucced(){
      $.get('@Url.Action("PrintPdf", "Export", "new {target = _blank}")');
}
like image 684
user1520494 Avatar asked Apr 11 '13 08:04

user1520494


Video Answer


4 Answers

Solved! That works for me

 window.open('/Export/PrintPdf');
like image 83
user1520494 Avatar answered Oct 11 '22 22:10

user1520494


There several ways to download or view the PDF.

  • View

You can set the content-type as application/pdf in the response header just like Content-Type: application/pdf

And in order to open it to new tab in javascript, please add this code.

window.open("Here Download PDF url", '_blank');
  • Download

You need to set the content-type as application/octet-stream in the response header just like application/octet-stream.

And add download HTML5 attribute to a tag or just target="_blank".

<a href="PDF URL" download="pdf">Download</a>
<a href="PDF URL" target="_blank">Download</a>

So you can use PDF.js or 3rd library to view the PDF in iFrame or inline page.

like image 42
Sergio Reis Avatar answered Oct 11 '22 23:10

Sergio Reis


$("a[target!='_blank'][href$='.pdf']").attr("target", "_blank");
like image 4
Timtech Avatar answered Oct 11 '22 23:10

Timtech


If anyone is having a similar problem, none of the above solutions worked for me in Google Chrome (they did work in Firefox)

This code worked in all major browsers:

var a = document.createElement('A');
var filePath = 'https://pathtopdf.com/file.pdf';
a.href = filePath;
a.download = filePath.substr(filePath.lastIndexOf('/') + 1);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
like image 4
Jordash Avatar answered Oct 11 '22 22:10

Jordash