jquery 实现web页面div元素内容打印 2011-2-14

这篇博客介绍了如何使用jQuery的PrintArea插件来实现在web页面上点击按钮打印div元素内容。示例代码展示了如何设置按钮触发打印,并且提供了打印样式和内容的示例,包括表格布局和数据。需要注意的是,为了保证打印效果,表格的宽度和高度需使用绝对单位,如cm,同时要清除不必要的边框和间距。

工作中遇到这种需求,但是需要手动页面设置中设定页边距

代码:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'index.jsp' starting page</title>
   
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">

 <link rel="stylesheet" type="text/css" href="css.css">
 <script type="text/javascript" src="jquery.js"></script>
 <script type="text/javascript" src="print.js"></script>
 <script type="text/javascript">
  $(document).ready(function(){
    $("#dayin").click(function(){
    $(".biaoti").css("color","#FFF");
    $("div#myPrintArea").printArea();
    });
  });
</script>

  </head>
 
  <body>
    <input id="dayin" type="button" value="打印">
<div cellspacing="0" id="myPrintArea" style="height:27.6cm;width:18.91cm;">
  <table cellpadding="0" cellspacing="0">
   <tr  height="27.6cm">
     <td style="width:0.8cm"><div align="center" style=" height:27.6cm; width:0.8cm;background-color:#CCC"></div></td>
        <td  cellspacing="0" style="border:none">
         <div align="center" style="height:27.6cm; width:17.51cm;background-color:#999999;">
          <table cellpadding="0"  cellspacing="0">
                 <tr>
                     <td>
                         <div cellspacing="0" align="center" style=" height:4cm; width:17.51cm;background-color:#0C0;"></div>
                        </td>
                    </tr>
                    <tr >
                     <td >
                         <div  align="center" style="  height:18.6cm; width:17.51cm;background-color:#CFF;">
                             <table cellpadding="0"  cellspacing="0">
                                    <tr  style="background-color:#FFF; height:1.4cm">
                                    <td>
                                     <div align="center">
                                         <table cellpadding="0"  cellspacing="0">
                                             <tr style="height:1.4cm">
                                        <td class="biaoti" style="width:2.5cm">航班号:</td>
                                        <td class="nr" style="width:2.1cm">01001</td>
                                        <td class="biaoti" style="width:2.5cm">飞机号:</td>
                                        <td class="nr" style="width:2.1cm">no.1</td>
                                        <td class="biaoti" style="width:2.5cm">飞行日期:</td>
                                        <td class="nr" style="width:2.1cm">2010.1.6</td>
                                        <td class="biaoti" style="width:2.4cm">出发站:</td>
                                        <td class="nr" style="width:1.3cm">天津</td>
                                                </tr>
                                            </table>
                                        </div>
                                    </td>
                                    </tr>
                                    <tr  style="background-color:#FFF; height:1.5cm">
                                     <td>
                                         <div align="center">
                                             <table cellpadding="0"  cellspacing="0">
                                                 <tr>
                                                     <td class="biaoti" style="width:1.4cm">序号</td>
                                            <td class="biaoti" style="width:3.2cm">运单号</td>
                                            <td class="biaoti" style="width:3.2cm">品名</td>
                                            <td class="biaoti" style="width:1.4cm">件数</td>
                                            <td class="biaoti" style="width:2.2cm">重量</td>
                                            <td class="biaoti" style="width:1.8cm">始发站</td>
                                            <td class="biaoti" style="width:2.2cm">目的地</td>
                                            <td class="biaoti" style="width:2.2cm">备注</td>
                                                    </tr>
                                                </table>
                                            </div>
                                        </td>
          </tr>
                           <%for(int i=0;i<20;i++){ %>        
                                 <tr style="background-color:#FFF; height:0.785cm">
                                     <td>
                                         <div align="center" style="border:none">
                                             <table cellpadding="0"  cellspacing="0">
                                                 <tr>
                                                     <td class="nr" style="width:1.4cm">111</td>
                                            <td class="nr" style="width:3.2cm">222</td>
                                            <td class="nr" style="width:3.2cm">dongxi</td>
                                            <td class="nr" style="width:1.4cm">3</td>
                                            <td class="nr" style="width:2.2cm">4444</td>
                                            <td class="nr" style="width:1.8cm">hebei</td>
                                            <td class="nr" style="width:2.2cm">tianj</td>
                                            <td class="nr" style="width:2.2cm">meiyou</td>
                                                    </tr>
                                                </table>
                                            </div>
                                        </td>
          </tr>
       <%} %>
                                </table>
                            </div>
                        </td>
                    </tr>
                    <tr cellspacing="0">
                     <td cellspacing="0"></td>
                    </tr>
                </table>
         </div>
        </td>
        <td cellspacing="0" style="border:none"><div align="center" style=" height:27.6cm; width:0.6cm;background-color:#CF0;border:none"></div></td>
 </tr>
  </table>
</div>

  </body>
</html>

 

 

 

 

 

 

 

 

导入文件有:

1.print.js ----jquery插件:PrintArea打印插件 http://plugins.jquery.com/project/PrintArea

 

内容:

/**
 *  Version 2.1
 *      -Contributors: "mindinquiring" : filter to exclude any stylesheet other than print.
 *  Tested ONLY in IE 8 and FF 3.6. No official support for other browsers, but will
 *      TRY to accomodate challenges in other browsers.
 *  Example:
 *      Print Button: <div id="print_button">Print</div>
 *      Print Area  : <div class="PrintArea"> ... html ... </div>
 *      Javascript  : <script>
 *                       $("div#print_button").click(function(){
 *                           $("div.PrintArea").printArea( [OPTIONS] );
 *                       });
 *                     </script>
 *  options are passed as json (json example: {mode: "popup", popClose: false})
 *
 *  {OPTIONS} | [type]    | (default), values      | Explanation
 *  --------- | --------- | ---------------------- | -----------
 *  @mode     | [string]  | ("iframe"),"popup"     | printable window is either iframe or browser popup
 *  @popHt    | [number]  | (500)                  | popup window height
 *  @popWd    | [number]  | (400)                  | popup window width
 *  @popX     | [number]  | (500)                  | popup window screen X position
 *  @popY     | [number]  | (500)                  | popup window screen Y position
 *  @popTitle | [string]  | ('')                   | popup window title element
 *  @popClose | [boolean] | (false),true           | popup window close after printing
 *  @strict   | [boolean] | (undefined),true,false | strict or loose(Transitional) html 4.01 document standard or undefined to not include at all (only for popup option)
 */
(function($) {
    var counter = 0;
    var modes = { iframe : "iframe", popup : "popup" };
    var defaults = { mode     : modes.iframe,
                     popHt    : 500,
                     popWd    : 400,
                     popX     : 200,
                     popY     : 200,
                     popTitle : '',
                     popClose : false };

    var settings = {};//global settings

    $.fn.printArea = function( options )
        {
            $.extend( settings, defaults, options );

            counter++;
            var idPrefix = "printArea_";
            $( "[id^=" + idPrefix + "]" ).remove();
            var ele = getFormData( $(this) );

            settings.id = idPrefix + counter;

            var writeDoc;
            var printWindow;

            switch ( settings.mode )
            {
                case modes.iframe :
                    var f = new Iframe();
                    writeDoc = f.doc;
                    printWindow = f.contentWindow || f;
                    break;
                case modes.popup :
                    printWindow = new Popup();
                    writeDoc = printWindow.doc;
            }

            writeDoc.open();
            writeDoc.write( docType() + "<html>" + getHead() + getBody(ele) + "</html>" );
            writeDoc.close();

            printWindow.focus();
            printWindow.print();

            if ( settings.mode == modes.popup && settings.popClose )
                printWindow.close();
        }

    function docType()
    {
        if ( settings.mode == modes.iframe || !settings.strict ) return "";

        var standard = settings.strict == false ? " Trasitional" : "";
        var dtd = settings.strict == false ? "loose" : "strict";

        return '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01' + standard + '//EN" "http://www.w3.org/TR/html4/' + dtd +  '.dtd">';
    }

    function getHead()
    {
        var head = "<head><title>" + settings.popTitle + "</title>";
        $(document).find("link")
            .filter(function(){
                    return $(this).attr("rel").toLowerCase() == "stylesheet";
                })
            .filter(function(){ // this filter contributed by "mindinquiring"
                    var media = $(this).attr("media");
                    return (media.toLowerCase() == "" || media.toLowerCase() == "print")
                })
            .each(function(){
                    head += '<link type="text/css" rel="stylesheet" href="' + $(this).attr("href") + '" >';
                });
        head += "</head>";
        return head;
    }

    function getBody( printElement )
    {
        return '<body><div class="' + $(printElement).attr("class") + '">' + $(printElement).html() + '</div></body>';
    }

    function getFormData( ele )
    {
        $("input,select,textarea", ele).each(function(){
            // In cases where radio, checkboxes and select elements are selected and deselected, and the print
            // button is pressed between select/deselect, the print screen shows incorrectly selected elements.
            // To ensure that the correct inputs are selected, when eventually printed, we must inspect each dom element
            var type = $(this).attr("type");
            if ( type == "radio" || type == "checkbox" )
            {
                if ( $(this).is(":not(:checked)") ) this.removeAttribute("checked");
                else this.setAttribute( "checked", true );
            }
            else if ( type == "text" )
                this.setAttribute( "value", $(this).val() );
            else if ( type == "select-multiple" || type == "select-one" )
                $(this).find( "option" ).each( function() {
                    if ( $(this).is(":not(:selected)") ) this.removeAttribute("selected");
                    else this.setAttribute( "selected", true );
                });
            else if ( type == "textarea" )
            {
                var v = $(this).attr( "value" );
                if ($.browser.mozilla)
                {
                    if (this.firstChild) this.firstChild.textContent = v;
                    else this.textContent = v;
                }
                else this.innerHTML = v;
            }
        });
        return ele;
    }

    function Iframe()
    {
        var frameId = settings.id;
        var iframeStyle = 'border:0;position:absolute;width:0px;height:0px;left:0px;top:0px;';
        var iframe;

        try
        {
            iframe = document.createElement('iframe');
            document.body.appendChild(iframe);
            $(iframe).attr({ style: iframeStyle, id: frameId, src: "" });
            iframe.doc = null;
            iframe.doc = iframe.contentDocument ? iframe.contentDocument : ( iframe.contentWindow ? iframe.contentWindow.document : iframe.document);
        }
        catch( e ) { throw e + ". iframes may not be supported in this browser."; }

        if ( iframe.doc == null ) throw "Cannot find document.";

        return iframe;
    }

    function Popup()
    {
        var windowAttr = "location=yes,statusbar=no,directories=no,menubar=no,titlebar=no,toolbar=no,dependent=no";
        windowAttr += ",width=" + settings.popWd + ",height=" + settings.popHt;
        windowAttr += ",resizable=yes,screenX=" + settings.popX + ",screenY=" + settings.popY + ",personalbar=no,scrollbars=no";

        var newWin = window.open( "", "_blank",  windowAttr );

        newWin.doc = newWin.document;

        return newWin;
    }
})(jQuery);
 2.jquery.js jquery库文件

 

注意:需要打印的话tr,td宽度和高度需要使用绝对距离,如cm,取消各种边框以及边距 table:cellpadding="0"  cellspacing="0"

*{border:none}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值