0

I'm trying to create a printing function in javascript, it creates an iframe, sets the source and waits for the dom to be ready to print the contents of the iframe, but it's not working.

This is my function:

app.addReportPrintButtons = function (parentElement) {
    var parent = parentElement || "body";

    $(parent).on("click", ".print-report", function (e) {
        var url = $(this).attr('href');

        var iframe = document.createElement("IFRAME");
        iframe.setAttribute("src", url);
        iframe.onload = function (e) {
            var win = iframe.contentWindow || iframe;
            win.focus();
            win.print();
        };

        e.preventDefault();
    });
};

Can I print a page in a dynamically created iframe? or do the iframe needs to be attached to the DOM?

Escobar5
  • 3,941
  • 8
  • 39
  • 62
  • Check out this similar question: http://stackoverflow.com/questions/9616426/javascript-print-iframe-contents-only – Josh KG Jul 02 '14 at 14:17
  • I can see a difference between that question, I'm asking if it's possible to do that in a dynamically generated iframe, an iframe not attached to the DOM, that other question is for an iframe in the DOM – Escobar5 Jul 02 '14 at 14:19
  • Also, I don't want to write the contents in the body, I want to specify the SRC of the iframe to another page – Escobar5 Jul 02 '14 at 14:20
  • What about bringing it into the DOM and hide it with CSS display none, and then in your print style sheet, display block? – Josh KG Jul 02 '14 at 14:22

1 Answers1

0

Javascript does not have the ability to print directly. It can only trigger the browser's print functionality. So if your element is not in the DOM, it can't be printed. In your code above, the iframe isn't printing because its not technically loaded until inserted in the DOM.

I recommend using CSS to hide the iframe with:

iframe {
    display: none;
}

Put that in your regular screen stylesheet. Then in your print style sheet, show the iframe:

iframe {
    display: block;
}
Josh KG
  • 5,050
  • 3
  • 20
  • 24