hjg
2023-11-17 3780c5e65b05bf23020810798babc6d20311fa79
提交 | 用户 | 时间
58d006 1 /**
A 2  *  Version 2.3.3 Copyright (C) 2013
3  *  Tested in IE 10, FF 21.0 and Chrome 27.0.1453.110
4  *  No official support for other browsers, but will TRY to accommodate challenges in other browsers.
5  *  Example:
6  *      Print Button: <div id="print_button">Print</div>
7  *      Print Area  : <div class="PrintArea" id="MyId" class="MyClass"> ... html ... </div>
8  *      Javascript  : <script>
9  *                       $("div#print_button").click(function(){
10  *                           $("div.PrintArea").printArea( [OPTIONS] );
11  *                       });
12  *                     </script>
13  *  options are passed as json (example: {mode: "popup", popClose: false})
14  *
15  *  {OPTIONS}   | [type]     | (default), values      | Explanation
16  *  ---------   | ---------  | ---------------------- | -----------
17  *  @mode       | [string]   | (iframe),popup         | printable window is either iframe or browser popup
18  *  @popHt      | [number]   | (500)                  | popup window height
19  *  @popWd      | [number]   | (400)                  | popup window width
20  *  @popX       | [number]   | (500)                  | popup window screen X position
21  *  @popY       | [number]   | (500)                  | popup window screen Y position
22  *  @popTitle   | [string]   | ('')                   | popup window title element
23  *  @popClose   | [boolean]  | (false),true           | popup window close after printing
24  *  @extraCss   | [string]   | ('')                   | comma separated list of extra css to include
25  *  @retainAttr | [string[]] | ["id","class","style"] | string array of attributes to retain for the containment area. (ie: id, style, class)
26  *  @standard   | [string]   | strict, loose, (html5) | Only for popup. For html 4.01, strict or loose document standard, or html 5 standard
27  *  @extraHead  | [string]   | ('')                   | comma separated list of extra elements to be appended to the head tag
28  */
29 (function($) {
30     var counter = 0;
31     var modes = { iframe : "iframe", popup : "popup" };
32     var standards = { strict : "strict", loose : "loose", html5 : "html5" };
33     var defaults = { mode       : modes.iframe,
34                      standard   : standards.html5,
35                      popHt      : 500,
36                      popWd      : 400,
37                      popX       : 200,
38                      popY       : 200,
39                      popTitle   : '',
40                      popClose   : false,
41                      extraCss   : '',
42                      extraHead  : '',
43                      retainAttr : ["id","class","style"] };
44
45     var settings = {};//global settings
46
47     $.fn.printArea = function( options )
48     {
49         $.extend( settings, defaults, options );
50
51         counter++;
52         var idPrefix = "printArea_";
53         $( "[id^=" + idPrefix + "]" ).remove();
54
55         settings.id = idPrefix + counter;
56
57         var writeDoc;
58         var printWindow;
59
60         switch ( settings.mode )
61         {
62             case modes.iframe :
63                 var f = new Iframe();
64                 writeDoc = f.doc;
65                 printWindow = f.contentWindow || f;
66                 break;
67             case modes.popup :
68                 printWindow = new Popup();
69                 writeDoc = printWindow.doc;
70         }
71
72         writeDoc.open();
73         writeDoc.write( docType() + "<html>" + getHead() + getBody( $(this) ) + "</html>" );
74         writeDoc.close();
75
76         $(writeDoc).ready(function(){
77             printWindow.focus();
78             printWindow.print();
79
80             if ( settings.mode == modes.popup && settings.popClose )
81                 setTimeout(function() { printWindow.close(); }, 2000);
82         });
83     }
84
85     function docType()
86     {
87         if ( settings.mode == modes.iframe ) return "";
88
89         if ( settings.standard == standards.html5 ) return "<!DOCTYPE html>";
90
91         var transitional = settings.standard == standards.loose ? " Transitional" : "";
92         var dtd = settings.standard == standards.loose ? "loose" : "strict";
93
94         return '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01' + transitional + '//EN" "http://www.w3.org/TR/html4/' + dtd +  '.dtd">';
95     }
96
97     function getHead()
98     {
99         var extraHead = "";
100         var links = "";
101
102         if ( settings.extraHead ) settings.extraHead.replace( /([^,]+)/g, function(m){ extraHead += m });
103
104         $(document).find("link")
105             .filter(function(){ // Requirement: <link> element MUST have rel="stylesheet" to be considered in print document
106                     var relAttr = $(this).attr("rel");
107                     return ($.type(relAttr) === 'undefined') == false && relAttr.toLowerCase() == 'stylesheet';
108                 })
109             .filter(function(){ // Include if media is undefined, empty, print or all
110                     var mediaAttr = $(this).attr("media");
111                     return $.type(mediaAttr) === 'undefined' || mediaAttr == "" || mediaAttr.toLowerCase() == 'print' || mediaAttr.toLowerCase() == 'all'
112                 })
113             .each(function(){
114                     links += '<link type="text/css" rel="stylesheet" href="' + $(this).attr("href") + '" >';
115                 });
116         if ( settings.extraCss ) settings.extraCss.replace( /([^,\s]+)/g, function(m){ links += '<link type="text/css" rel="stylesheet" href="' + m + '">' });
117
118         return "<head><title>" + settings.popTitle + "</title>" + extraHead + links + "</head>";
119     }
120
121     function getBody( elements )
122     {
123         var htm = "";
124         var attrs = settings.retainAttr;
125         elements.each(function() {
126             var ele = getFormData( $(this) );
127
128             var attributes = ""
129             for ( var x = 0; x < attrs.length; x++ )
130             {
131                 var eleAttr = $(ele).attr( attrs[x] );
132                 if ( eleAttr ) attributes += (attributes.length > 0 ? " ":"") + attrs[x] + "='" + eleAttr + "'";
133             }
134
135             htm += '<div ' + attributes + '>' + $(ele).html() + '</div>';
136         });
137
138         return "<body>" + htm + "</body>";
139     }
140
141     function getFormData( ele )
142     {
143         var copy = ele.clone();
144         var copiedInputs = $("input,select,textarea", copy);
145         $("input,select,textarea", ele).each(function( i ){
146             var typeInput = $(this).attr("type");
147             if ($.type(typeInput) === 'undefined') typeInput = $(this).is("select") ? "select" : $(this).is("textarea") ? "textarea" : "";
148             var copiedInput = copiedInputs.eq( i );
149
150             if ( typeInput == "radio" || typeInput == "checkbox" ) copiedInput.attr( "checked", $(this).is(":checked") );
151             else if ( typeInput == "text" ) copiedInput.attr( "value", $(this).val() );
152             else if ( typeInput == "select" )
153                 $(this).find( "option" ).each( function( i ) {
154                     if ( $(this).is(":selected") ) $("option", copiedInput).eq( i ).attr( "selected", true );
155                 });
156             else if ( typeInput == "textarea" ) copiedInput.text( $(this).val() );
157         });
158         return copy;
159     }
160
161     function Iframe()
162     {
163         var frameId = settings.id;
164         var iframeStyle = 'border:0;position:absolute;width:0px;height:0px;left:0px;top:0px;';
165         var iframe;
166
167         try
168         {
169             iframe = document.createElement('iframe');
170             document.body.appendChild(iframe);
171             $(iframe).attr({ style: iframeStyle, id: frameId, src: "" });
172             iframe.doc = null;
173             iframe.doc = iframe.contentDocument ? iframe.contentDocument : ( iframe.contentWindow ? iframe.contentWindow.document : iframe.document);
174         }
175         catch( e ) { throw e + ". iframes may not be supported in this browser."; }
176
177         if ( iframe.doc == null ) throw "Cannot find document.";
178
179         return iframe;
180     }
181
182     function Popup()
183     {
184         var windowAttr = "location=yes,statusbar=no,directories=no,menubar=no,titlebar=no,toolbar=no,dependent=no";
185         windowAttr += ",width=" + settings.popWd + ",height=" + settings.popHt;
186         windowAttr += ",resizable=yes,screenX=" + settings.popX + ",screenY=" + settings.popY + ",personalbar=no,scrollbars=yes";
187
188         var newWin = window.open( "", "_blank",  windowAttr );
189
190         newWin.doc = newWin.document;
191
192         return newWin;
193     }
194 })(jQuery);