nr.iras.sk
nr.iras.sk

Reputation: 8498

Window.print() does not work

Why this does not works? Only loading the page. Not getting printed. Here I take the src of an iframe and open that url in new window.

var myDivObj = document.getElementById('resumedocument').src;
var someXml = '<html><title>Resume</title><body onload="window.print();"><iframe style="height: 1000px; width: 1260px;" src="' + myDivObj + '"/></body></html>';
var printwindow = window.open('', '_blank','fullscreen=yes');
printwindow.document.write(someXml);
printwindow.onload = function() {                               
   printwindow.self.focus();
   printwindow.self.print();
};

Upvotes: 1

Views: 9969

Answers (5)

user982671
user982671

Reputation: 1073

Note https://developer.mozilla.org/en-US/docs/Web/API/Window/print#Notes :

Starting with Chrome 46.0 this method is blocked inside an <iframe> unless its sandbox attribute has the value allow-modals.

Upvotes: 0

The Alpha
The Alpha

Reputation: 146191

var url = document.getElementById('resumedocument').src;
var printwindow = window.open('', '', 'fullscreen=yes');
printwindow.document.write('<iframe width="100%" height="100%" onload="window.print()" src='+url+'></iframe>');

Upvotes: 1

Michael
Michael

Reputation: 9044

You don't need to do it in onload as you are doing your own document.write. The following code works as an example:

    var someXml = '<html><body>Stuff</body></html>';
    var printwindow = window.open('', '_blank','fullscreen=yes');
    printwindow.document.write(someXml);
    printwindow.print();

I think your problem is the onload would fire during the window.open method when the document has been loaded. At this point of time your document is '', so there is no handler.

To wait for the IFRAME to load you need to move the onload handler there. For example:

    var someXml = '<html><body><iframe id=Frame width="800" height="800" src="http://jsfiddle.net" /></body></html>';
    var printwindow = window.open('', '_blank','fullscreen=yes');
    printwindow.document.write(someXml);
    printwindow.document.getElementById('Frame').onload = function () {
        printwindow.self.focus();
        printwindow.print();
    };​

Upvotes: 2

Daedalus
Daedalus

Reputation: 7722

Replace this line:

printwindow.onload = function() {                               
    printwindow.self.focus();
    printwindow.self.print();
};

With this line:

printwindow.document.getElementsByTagName('iframe')[0].onload = function () {
    printwindow.self.focus();
    printwindow.print();
};

Upvotes: 2

Tanzeeb Khalili
Tanzeeb Khalili

Reputation: 7344

Did you try without the self, as in printwindow.print()?

Upvotes: 1

Related Questions