问题
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