Reputation: 29
Open PDF in a new window, print that PDF and Close the window. How to do this in javascript. This 3 steps should be done in One click.
Upvotes: 1
Views: 4981
Reputation: 580
There are two scenarios: loading the pdf through a get request or through a post (form) request; my scenario addresses them by bringing up the print dialog and when the print dialog is closed, closing the window.
For the get request, this should be sufficient:
function testprint(){
var w = window.open(yourURL)
w.focus()
w.print()
// Don't try to close it until you've give the window time to register the print dialog request
setTimeout(function(){
w.close()
}, 1000)
}
The post is a little more complicated. After battling this issue for a while, this is what I came up with - it uses a hidden iframe; I couldn't get it to work with an extra window. The upshot of that is though you can hide the iframe so the user doesn't even need to see the other window. (Note, you could convert the get solution to use the iframe as well and avoid the extra window all together.) It assumes you've build a form with jQuery, and the result of the post will be the PDF you want.
jQuery(document.body).append(form);
if (doPrint) {
jQuery(document.body).append("<iframe style='display:none' id='doPrintId' name='doPrint'>");
form.submit(function () {
form.attr('target', 'doPrint');
});
var printWindow = document.getElementById('doPrintId');
printWindow.onload = function(){
printWindow.focus();
printWindow.contentWindow.print();
document.body.remove(printWindow);
};
form.submit();
} else {
form.submit();
}
jQuery(document.body).remove(form);
Upvotes: 1
Reputation: 1038830
Sorry to inform you that these steps cannot be done simply using pure javascript. Imagine if web sites were capable of automatically sending print requests directly to users printers. You visit a malicious site and you could run out of toner and/or paper. You will have to install some plugin on the client browser that will perform the actual printing.
Upvotes: 1