简体   繁体   English

在动态创建的iframe中加载页面(不在dom中)并打印

[英]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. 我正在尝试在javascript中创建打印功能,它会创建iframe,设置源并等待dom准备打印iframe的内容,但无法正常工作。

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? 我可以在动态创建的iframe中打印页面吗? or do the iframe needs to be attached to the DOM? 还是需要将iframe附加到DOM?

Javascript does not have the ability to print directly. Javascript无法直接打印。 It can only trigger the browser's print functionality. 它只能触发浏览器的打印功能。 So if your element is not in the DOM, it can't be printed. 因此,如果您的元素不在DOM中,则无法打印该元素。 In your code above, the iframe isn't printing because its not technically loaded until inserted in the DOM. 在上面的代码中,iframe无法打印,因为在插入DOM中之前,iframe在技术上并未加载。

I recommend using CSS to hide the iframe with: 我建议使用CSS通过以下方式隐藏iframe:

iframe {
    display: none;
}

Put that in your regular screen stylesheet. 将其放在常规屏幕样式表中。 Then in your print style sheet, show the iframe: 然后在您的打印样式表中,显示iframe:

iframe {
    display: block;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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