打印DIV内容的最佳方法是什么?


当前回答

打开一个新窗口 打开新窗口的文档对象,并在其中写入一个简单的文档,其中只包含您已经获得的div和必要的html头文件等-您可能还希望将文档拉入样式表,这取决于您的内容是什么 在新页面中放入一个脚本来调用window.print() 触发脚本

其他回答

注意:从下面提到的插件编写到现在已经有13年了,就像评论中提到的那样。它不再工作,因为改变了API在jQuery。随意分叉和添加一个拉请求!

虽然这是@gabe说的, 如果你正在使用jQuery,你可以使用我的printElement插件。

这里有一个示例,以及关于插件的更多信息。

使用方法相当简单,只需用jQuery选择器抓取一个元素并打印它:

$("#myDiv").printElement();

我希望这能有所帮助!

最好的方法是将div的内容提交给服务器,并打开一个新窗口,服务器可以将这些内容放入新窗口中。

如果这不是一个选项,你可以尝试使用客户端语言,如javascript隐藏页面上的所有内容,除了div,然后打印页面…

下面的代码复制了查询选择器目标的所有相关节点,复制了它们在屏幕上看到的样式,因为许多用于css选择器目标的父元素将会丢失。如果有很多带有很多样式的子节点,这将导致一些延迟。

理想情况下,你应该有一个打印样式表,但这是为用例,没有打印样式表插入,你希望打印在屏幕上看到。

如果您在此页的浏览器控制台中复制以下项目,它将打印此页上的所有代码片段。

+function() {
    /**
     * copied from  https://stackoverflow.com/questions/19784064/set-javascript-computed-style-from-one-element-to-another
     * @author Adi Darachi https://stackoverflow.com/users/2318881/adi-darachi
     */
    var copyComputedStyle = function(from,to){
        var computed_style_object = false;
        //trying to figure out which style object we need to use depense on the browser support
        //so we try until we have one
        computed_style_object = from.currentStyle || document.defaultView.getComputedStyle(from,null);

        //if the browser dose not support both methods we will return null
        if(!computed_style_object) return null;

            var stylePropertyValid = function(name,value){
                        //checking that the value is not a undefined
                return typeof value !== 'undefined' &&
                        //checking that the value is not a object
                        typeof value !== 'object' &&
                        //checking that the value is not a function
                        typeof value !== 'function' &&
                        //checking that we dosent have empty string
                        value.length > 0 &&
                        //checking that the property is not int index ( happens on some browser
                        value != parseInt(value)

            };

        //we iterating the computed style object and compy the style props and the values
        for(property in computed_style_object)
        {
            //checking if the property and value we get are valid sinse browser have different implementations
                if(stylePropertyValid(property,computed_style_object[property]))
                {
                    //applying the style property to the target element
                        to.style[property] = computed_style_object[property];

                }   
        }   

    };


    // Copy over all relevant styles to preserve styling, work the way down the children tree.
    var buildChild = function(masterList, childList) {
        for(c=0; c<masterList.length; c++) {
           var master = masterList[c];
           var child = childList[c];
           copyComputedStyle(master, child);
           if(master.children && master.children.length > 0) {
               buildChild(master.children, child.children);
           }
        }
    }

    /** select elements to print with query selector **/
    var printSelection = function(querySelector) {
        // Create an iframe to make sure everything is clean and ordered.
        var iframe = document.createElement('iframe');
        // Give it enough dimension so you can visually check when modifying.
        iframe.width = document.width;
        iframe.height = document.height;
        // Add it to the current document to be sure it has the internal objects set up.
        document.body.append(iframe);

        var nodes = document.querySelectorAll(querySelector);
        if(!nodes || nodes.length == 0) {
           console.error('Printing Faillure: Nothing to print. Please check your querySelector');
           return;
        }

        for(i=0; i < nodes.length; i++) {

            // Get the node you wish to print.
            var origNode = nodes[i];

            // Clone it and all it's children
            var node = origNode.cloneNode(true);

            // Copy the base style.
            copyComputedStyle(origNode, node);

            if(origNode.children && origNode.children.length > 0) {
                buildChild(origNode.children, node.children);
            }

            // Add the styled clone to the iframe. using contentWindow.document since it seems the be the most widely supported version.

            iframe.contentWindow.document.body.append(node);
        }
        // Print the window
        iframe.contentWindow.print();

        // Give the browser a second to gather the data then remove the iframe.
        window.setTimeout(function() {iframe.parentNode.removeChild(iframe)}, 1000);
    }
window.printSelection = printSelection;
}();
printSelection('.default.prettyprint.prettyprinted')

在Opera中,试试:

    print_win.document.write('</body></html>');
    print_win.document.close(); // This bit is important
    print_win.print();
    print_win.close();

注意:这只适用于启用jQuery的站点

这个很酷的技巧非常简单。它在谷歌Chrome浏览器中为我工作。火狐不允许你在没有插件的情况下打印PDF文件。

首先,使用(Ctrl + Shift + I) / (Cmd + Option + I)打开检查器。 在控制台中输入以下代码:


var jqchild = document.createElement('script');
jqchild.src = "https://cdnjs.cloudflare.com/ajax/libs/jQuery.print/1.5.1/jQuery.print.min.js";
document.getElementsByTagName('body')[0].appendChild(jqchild);
$("#myDivWithStyles").print(); // Replace ID with yours

它启动打印对话框。打印出来或者保存成PDF格式(chrome)。完成了!

逻辑很简单。我们正在创建一个新的脚本标记,并将其附加在关闭主体标记的前面。我们在HTML中注入了一个jQuery打印扩展。用你自己的Div标签ID更改myDivWithStyles。现在它负责准备一个可打印的虚拟窗口。

在任何网站上尝试一下。唯一需要注意的是,有时巧妙地编写CSS会导致丢失样式。但大多数时候我们得到的是内容。