使用jquery实现基于browser的打印

来源:互联网 发布:淘宝分销怎么取消 编辑:程序博客网 时间:2024/05/23 13:48

前不久在做项目时,要求要实现对页面中指定内容区域的打印功能,找了很多的资料和方法,经过多次实验,最终选择了如下的方式,实现起来比较简单,对主流浏览器Chrome\Firefox\IE\Safari的支持比较好,对Opera的支持不是很好,不过这个和我的页面内容本身的处理方式有一定的关系。

这个项目类似于Microsoft的MSDN Library,如下图所示。其中左边的内容是从帮助文档html页面读取并嵌入到当前的页面的(不是用iframe)。打印的区域就是右边加载的内容。



实现方式如下:

1. 引入jquery.print.js文件(另外还尝试过jquery.PrintArea.js和jquery.printElement.js,对本项目的支持效果不是太好或是实现较繁琐,就放弃了)

// Create a jquery plugin that prints the given element.jQuery.fn.print = function () {    // NOTE: We are trimming the jQuery collection down to the    // first element in the collection.    if (this.size() > 1) {        this.eq(0).print();        return;    } else if (!this.size()) {        return;    }    // ASSERT: At this point, we know that the current jQuery    // collection (as defined by THIS), contains only one    // printable element.    // Create a random name for the print frame.    var strFrameName = ("printer-" + (new Date()).getTime());    // Create an iFrame with the new name.    var jFrame = $("<iframe name='" + strFrameName + "'>");    // Hide the frame (sort of) and attach to the body.    jFrame    .css("width", "1px")    .css("height", "1px")    .css("position", "absolute")    .css("left", "-9999px")    .appendTo($("body.hc_body"))    //.appendTo($("body:first"));    // Get a FRAMES reference to the new frame.    var objFrame = window.frames[strFrameName];    // Get a reference to the DOM in the new frame.    var objDoc = objFrame.document;    // Grab all the style tags and copy to the new    // document so that we capture look and feel of    // the current document.    // Create a temp document DIV to hold the style tags.    // This is the only way I could find to get the style    // tags into IE.    var jStyleDiv = $("<div>").append(    $("style").clone()    );    // Write the HTML for the document. In this, we will    // write out the HTML of the current element.    objDoc.open();    objDoc.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");    objDoc.write("<html>");    objDoc.write("<body>");    objDoc.write("<head>");    objDoc.write("<title>");    objDoc.write(document.title);    objDoc.write("</title>");    objDoc.write(jStyleDiv.html());    // importing printable style sheet    objDoc.write("<style type=\"text/css\"> @import url(\"./styles/Quiz_print.css\") </style>");    objDoc.write("</head>");    objDoc.write(this.html());    objDoc.write("</body>");    objDoc.write("</html>");    objDoc.close();    //此处经过改进,解决IE\Opera对一个页面中有多个iframe时的支持不友好的问题    // Print the document.    if ($.browser.msie || $.browser.opera) {        jQuery("[name=" + strFrameName + "]").load(            function () {                window.frames[strFrameName].focus();                window.frames[strFrameName].print();            }         );    }    else {        objFrame.focus();        objFrame.print();    }    // Have the frame remove itself in about a minute so that    // we don't build up too many of these frames.    setTimeout(    function () {        jFrame.remove();    },    (60 * 1000)    );}

2. 在打印内容所在的页面引用该js文件,或者在母版页中(我是用ASP.NET MVC开发的,所以加载Layout页面中)

<script src="@Url.Content("~/Scripts/jquery.print.js")" type="text/javascript"></script>
3. 用<div class="printable">包装打印内容(class名称可以任意选取)

<div class="printable">    <!-- print content --></div>
4. 为触发打印的按钮或<a>或其他对象绑定事件

<script type="text/javascript">    $(function () {                $("#btnPrint").bind("click", function (event) { //btnPrint是按钮            $(".printable").print(); //printable是包含打印内容的div,print()是在js中定义的方法        });    });</script>
至此,打印功能就全部实现了。该方法可以应用于基于browser的各种web中。

希望以后有时间能够找到更好的方法,特别是能够较好的支持Opera。


原创粉丝点击