简体   繁体   中英

Load page in dynamically created iframe (not in dom) and print it

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM