How to Open .pdf on a new Tab

前提是你 提交于 2020-05-11 04:15:32

问题


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}")');
}

回答1:


Solved! That works for me

 window.open('/Export/PrintPdf');



回答2:


$("a[target!='_blank'][href$='.pdf']").attr("target", "_blank");



回答3:


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);



回答4:


You can use the following solution

   jQuery('<form target="_blank" action="' + URL + '" method="get"></form>').appendTo('body').submit().remove();

where URL is the pdf url...




回答5:


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.




回答6:


You can try using jQuery.deffered. I prepared sample function for you. It will process getPdf call, and then will resolve promise. Hope this helps

function getPDF() {
    return '';
}

getPdf()
  .then(function(response) {
    console.log('response here' + response);
    window.open(response);
  }).fail(function(){
      console.error('failed reposne');
  });


来源:https://stackoverflow.com/questions/15944245/how-to-open-pdf-on-a-new-tab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!