jquery.printarea.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. /**
  2. * Version 2.4.1 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 = {
  34. mode: modes.iframe,
  35. standard: standards.html5,
  36. popHt: 500,
  37. popWd: 400,
  38. popX: 200,
  39. popY: 200,
  40. popTitle: '',
  41. popClose: false,
  42. extraCss: '',
  43. extraHead: '',
  44. retainAttr: ["id", "class", "style"]
  45. };
  46. var settings = {};//global settings
  47. $.fn.printArea = function (options) {
  48. $.extend(settings, defaults, options);
  49. counter++;
  50. var idPrefix = "printArea_";
  51. $("[id^=" + idPrefix + "]").remove();
  52. settings.id = idPrefix + counter;
  53. var $printSource = $(this);
  54. var PrintAreaWindow = PrintArea.getPrintWindow();
  55. PrintArea.write(PrintAreaWindow.doc, $printSource);
  56. setTimeout(function () { PrintArea.print(PrintAreaWindow); }, 1000);
  57. };
  58. var PrintArea = {
  59. print: function (PAWindow) {
  60. var paWindow = PAWindow.win;
  61. $(PAWindow.doc).ready(function () {
  62. paWindow.focus();
  63. paWindow.print();
  64. if (settings.mode == modes.popup && settings.popClose)
  65. setTimeout(function () { paWindow.close(); }, 2000);
  66. });
  67. },
  68. write: function (PADocument, $ele) {
  69. PADocument.open();
  70. PADocument.write(PrintArea.docType() + "<html>" + PrintArea.getHead() + PrintArea.getBody($ele) + "</html>");
  71. PADocument.close();
  72. },
  73. docType: function () {
  74. if (settings.mode == modes.iframe) return "";
  75. if (settings.standard == standards.html5) return "<!DOCTYPE html>";
  76. var transitional = settings.standard == standards.loose ? " Transitional" : "";
  77. var dtd = settings.standard == standards.loose ? "loose" : "strict";
  78. return '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01' + transitional + '//EN" "http://www.w3.org/TR/html4/' + dtd + '.dtd">';
  79. },
  80. getHead: function () {
  81. var extraHead = "";
  82. var links = "";
  83. if (settings.extraHead) settings.extraHead.replace(/([^,]+)/g, function (m) { extraHead += m });
  84. $(document).find("link")
  85. .filter(function () { // Requirement: <link> element MUST have rel="stylesheet" to be considered in print document
  86. var relAttr = $(this).attr("rel");
  87. return ($.type(relAttr) === 'undefined') == false && relAttr.toLowerCase() == 'stylesheet';
  88. })
  89. .filter(function () { // Include if media is undefined, empty, print or all
  90. var mediaAttr = $(this).attr("media");
  91. return $.type(mediaAttr) === 'undefined' || mediaAttr == "" || mediaAttr.toLowerCase() == 'print' || mediaAttr.toLowerCase() == 'all'
  92. })
  93. .each(function () {
  94. links += '<link type="text/css" rel="stylesheet" href="' + $(this).attr("href") + '" >';
  95. });
  96. if (settings.extraCss) settings.extraCss.replace(/([^,\s]+)/g, function (m) { links += '<link type="text/css" rel="stylesheet" href="' + m + '">' });
  97. return "<head><title>" + settings.popTitle + "</title>" + extraHead + links + "</head>";
  98. },
  99. getBody: function (elements) {
  100. var htm = "";
  101. var attrs = settings.retainAttr;
  102. elements.each(function () {
  103. var ele = PrintArea.getFormData($(this));
  104. var attributes = ""
  105. for (var x = 0; x < attrs.length; x++) {
  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" || typeInput == "") 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. case modes.iframe:
  133. var f = new PrintArea.Iframe();
  134. return { win: f.contentWindow || f, doc: f.doc };
  135. case modes.popup:
  136. var p = new PrintArea.Popup();
  137. return { win: p, doc: p.doc };
  138. }
  139. },
  140. Iframe: function () {
  141. var frameId = settings.id;
  142. var iframeStyle = 'border:0;position:absolute;width:0px;height:0px;right:0px;top:0px;';
  143. var iframe;
  144. try {
  145. iframe = document.createElement('iframe');
  146. document.body.appendChild(iframe);
  147. $(iframe).attr({ style: iframeStyle, id: frameId, src: "#" + new Date().getTime() });
  148. iframe.doc = null;
  149. iframe.doc = iframe.contentDocument ? iframe.contentDocument : (iframe.contentWindow ? iframe.contentWindow.document : iframe.document);
  150. }
  151. catch (e) { throw e + ". iframes may not be supported in this browser."; }
  152. if (iframe.doc == null) throw "Cannot find document.";
  153. return iframe;
  154. },
  155. Popup: function () {
  156. var windowAttr = "location=yes,statusbar=no,directories=no,menubar=no,titlebar=no,toolbar=no,dependent=no";
  157. windowAttr += ",width=" + settings.popWd + ",height=" + settings.popHt;
  158. windowAttr += ",resizable=yes,screenX=" + settings.popX + ",screenY=" + settings.popY + ",personalbar=no,scrollbars=yes";
  159. var newWin = window.open("", "_blank", windowAttr);
  160. newWin.doc = newWin.document;
  161. return newWin;
  162. }
  163. };
  164. })(jQuery);