jquery.printarea.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. /**
  2. * Version 2.4.0 Copyright (C) 2013
  3. * Tested in IE 11, FF 28.0 and Chrome 33.0.1750.154
  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. var settings = {};//global settings
  45. $.fn.printArea = function( options )
  46. {
  47. $.extend( settings, defaults, options );
  48. counter++;
  49. var idPrefix = "printArea_";
  50. $( "[id^=" + idPrefix + "]" ).remove();
  51. settings.id = idPrefix + counter;
  52. var $printSource = $(this);
  53. var PrintAreaWindow = PrintArea.getPrintWindow();
  54. PrintArea.write( PrintAreaWindow.doc, $printSource );
  55. setTimeout( function () { PrintArea.print( PrintAreaWindow ); }, 1000 );
  56. };
  57. var PrintArea = {
  58. print : function( PAWindow ) {
  59. var paWindow = PAWindow.win;
  60. $(PAWindow.doc).ready(function(){
  61. paWindow.focus();
  62. paWindow.print();
  63. if ( settings.mode == modes.popup && settings.popClose )
  64. setTimeout(function() { paWindow.close(); }, 2000);
  65. });
  66. },
  67. write : function ( PADocument, $ele ) {
  68. PADocument.open();
  69. PADocument.write( PrintArea.docType() + "<html>" + PrintArea.getHead() + PrintArea.getBody( $ele ) + "</html>" );
  70. PADocument.close();
  71. },
  72. docType : function() {
  73. if ( settings.mode == modes.iframe ) return "";
  74. if ( settings.standard == standards.html5 ) return "<!DOCTYPE html>";
  75. var transitional = settings.standard == standards.loose ? " Transitional" : "";
  76. var dtd = settings.standard == standards.loose ? "loose" : "strict";
  77. return '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01' + transitional + '//EN" "http://www.w3.org/TR/html4/' + dtd + '.dtd">';
  78. },
  79. getHead : function() {
  80. var extraHead = "";
  81. var links = "";
  82. if ( settings.extraHead ) settings.extraHead.replace( /([^,]+)/g, function(m){ extraHead += m });
  83. $(document).find("link")
  84. .filter(function(){ // Requirement: <link> element MUST have rel="stylesheet" to be considered in print document
  85. var relAttr = $(this).attr("rel");
  86. return ($.type(relAttr) === 'undefined') == false && relAttr.toLowerCase() == 'stylesheet';
  87. })
  88. .filter(function(){ // Include if media is undefined, empty, print or all
  89. var mediaAttr = $(this).attr("media");
  90. return $.type(mediaAttr) === 'undefined' || mediaAttr == "" || mediaAttr.toLowerCase() == 'print' || mediaAttr.toLowerCase() == 'all'
  91. })
  92. .each(function(){
  93. links += '<link type="text/css" rel="stylesheet" href="' + $(this).attr("href") + '" >';
  94. });
  95. if ( settings.extraCss ) settings.extraCss.replace( /([^,\s]+)/g, function(m){ links += '<link type="text/css" rel="stylesheet" href="' + m + '">' });
  96. return "<head><title>" + settings.popTitle + "</title>" + extraHead + links + "</head>";
  97. },
  98. getBody : function ( elements ) {
  99. var htm = "";
  100. var attrs = settings.retainAttr;
  101. elements.each(function() {
  102. var ele = PrintArea.getFormData( $(this) );
  103. var attributes = ""
  104. for ( var x = 0; x < attrs.length; x++ )
  105. {
  106. var eleAttr = $(ele).attr( attrs[x] );
  107. if ( eleAttr ) attributes += (attributes.length > 0 ? " ":"") + attrs[x] + "='" + eleAttr + "'";
  108. }
  109. htm += '<div ' + attributes + '>' + $(ele).html() + '</div>';
  110. });
  111. return "<body>" + htm + "</body>";
  112. },
  113. getFormData : function ( ele ) {
  114. var copy = ele.clone();
  115. var copiedInputs = $("input,select,textarea", copy);
  116. $("input,select,textarea", ele).each(function( i ){
  117. var typeInput = $(this).attr("type");
  118. if ($.type(typeInput) === 'undefined') typeInput = $(this).is("select") ? "select" : $(this).is("textarea") ? "textarea" : "";
  119. var copiedInput = copiedInputs.eq( i );
  120. if ( typeInput == "radio" || typeInput == "checkbox" ) copiedInput.attr( "checked", $(this).is(":checked") );
  121. else if ( typeInput == "text" ) copiedInput.attr( "value", $(this).val() );
  122. else if ( typeInput == "select" )
  123. $(this).find( "option" ).each( function( i ) {
  124. if ( $(this).is(":selected") ) $("option", copiedInput).eq( i ).attr( "selected", true );
  125. });
  126. else if ( typeInput == "textarea" ) copiedInput.text( $(this).val() );
  127. });
  128. return copy;
  129. },
  130. getPrintWindow : function () {
  131. switch ( settings.mode )
  132. {
  133. case modes.iframe :
  134. var f = new PrintArea.Iframe();
  135. return { win : f.contentWindow || f, doc : f.doc };
  136. case modes.popup :
  137. var p = new PrintArea.Popup();
  138. return { win : p, doc : p.doc };
  139. }
  140. },
  141. Iframe : function () {
  142. var frameId = settings.id;
  143. var iframeStyle = 'border:0;position:absolute;width:0px;height:0px;right:0px;top:0px;';
  144. var iframe;
  145. try
  146. {
  147. iframe = document.createElement('iframe');
  148. document.body.appendChild(iframe);
  149. $(iframe).attr({ style: iframeStyle, id: frameId, src: "#" + new Date().getTime() });
  150. iframe.doc = null;
  151. iframe.doc = iframe.contentDocument ? iframe.contentDocument : ( iframe.contentWindow ? iframe.contentWindow.document : iframe.document);
  152. }
  153. catch( e ) { throw e + ". iframes may not be supported in this browser."; }
  154. if ( iframe.doc == null ) throw "Cannot find document.";
  155. return iframe;
  156. },
  157. Popup : function () {
  158. var windowAttr = "location=yes,statusbar=no,directories=no,menubar=no,titlebar=no,toolbar=no,dependent=no";
  159. windowAttr += ",width=" + settings.popWd + ",height=" + settings.popHt;
  160. windowAttr += ",resizable=yes,screenX=" + settings.popX + ",screenY=" + settings.popY + ",personalbar=no,scrollbars=yes";
  161. var newWin = window.open( "", "_blank", windowAttr );
  162. newWin.doc = newWin.document;
  163. return newWin;
  164. }
  165. };
  166. })(jQuery);