You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

181 lines
8.2 KiB

  1. /// <reference path="http://code.jquery.com/jquery-1.4.1-vsdoc.js" />
  2. /*
  3. * Print Element Plugin 1.2
  4. *
  5. * Copyright (c) 2010 Erik Zaadi
  6. *
  7. * Inspired by PrintArea (http://plugins.jquery.com/project/PrintArea) and
  8. * http://stackoverflow.com/questions/472951/how-do-i-print-an-iframe-from-javascript-in-safari-chrome
  9. *
  10. * Home Page : http://projects.erikzaadi/jQueryPlugins/jQuery.printElement
  11. * Issues (bug reporting) : http://github.com/erikzaadi/jQueryPlugins/issues/labels/printElement
  12. * jQuery plugin page : http://plugins.jquery.com/project/printElement
  13. *
  14. * Thanks to David B (http://github.com/ungenio) and icgJohn (http://www.blogger.com/profile/11881116857076484100)
  15. * For their great contributions!
  16. *
  17. * Dual licensed under the MIT and GPL licenses:
  18. * http://www.opensource.org/licenses/mit-license.php
  19. * http://www.gnu.org/licenses/gpl.html
  20. *
  21. * Note, Iframe Printing is not supported in Opera and Chrome 3.0, a popup window will be shown instead
  22. */
  23. ; (function (window, undefined) {
  24. var document = window["document"];
  25. var $ = window["jQuery"];
  26. $.fn["printElement"] = function (options) {
  27. var mainOptions = $.extend({}, $.fn["printElement"]["defaults"], options);
  28. //iframe mode is not supported for opera and chrome 3.0 (it prints the entire page).
  29. //http://www.google.com/support/forum/p/Webmasters/thread?tid=2cb0f08dce8821c3&hl=en
  30. if (mainOptions["printMode"] == 'iframe') {
  31. if ($.browser.opera || (/chrome/.test(navigator.userAgent.toLowerCase())))
  32. mainOptions["printMode"] = 'popup';
  33. }
  34. //Remove previously printed iframe if exists
  35. $("[id^='printElement_']").remove();
  36. return this.each(function () {
  37. //Support Metadata Plug-in if available
  38. var opts = $.meta ? $.extend({}, mainOptions, $(this).data()) : mainOptions;
  39. _printElement($(this), opts);
  40. });
  41. };
  42. $.fn["printElement"]["defaults"] = {
  43. "printMode": 'iframe', //Usage : iframe / popup
  44. "pageTitle": '', //Print Page Title
  45. "overrideElementCSS": null,
  46. /* Can be one of the following 3 options:
  47. * 1 : boolean (pass true for stripping all css linked)
  48. * 2 : array of $.fn.printElement.cssElement (s)
  49. * 3 : array of strings with paths to alternate css files (optimized for print)
  50. */
  51. "printBodyOptions": {
  52. "styleToAdd": 'padding:10px;margin:10px;', //style attributes to add to the body of print document
  53. "classNameToAdd": '' //css class to add to the body of print document
  54. },
  55. "leaveOpen": false, // in case of popup, leave the print page open or not
  56. "iframeElementOptions": {
  57. "styleToAdd": 'border:none;position:absolute;width:0px;height:0px;bottom:0px;left:0px;', //style attributes to add to the iframe element
  58. "classNameToAdd": '' //css class to add to the iframe element
  59. }
  60. };
  61. $.fn["printElement"]["cssElement"] = {
  62. "href": '',
  63. "media": ''
  64. };
  65. function _printElement(element, opts) {
  66. //Create markup to be printed
  67. var html = _getMarkup(element, opts);
  68. var popupOrIframe = null;
  69. var documentToWriteTo = null;
  70. if (opts["printMode"].toLowerCase() == 'popup') {
  71. popupOrIframe = window.open('about:blank', 'printElementWindow', 'width=650,height=440,scrollbars=yes');
  72. documentToWriteTo = popupOrIframe.document;
  73. }
  74. else {
  75. //The random ID is to overcome a safari bug http://www.cjboco.com.sharedcopy.com/post.cfm/442dc92cd1c0ca10a5c35210b8166882.html
  76. var printElementID = "printElement_" + (Math.round(Math.random() * 99999)).toString();
  77. //Native creation of the element is faster..
  78. var iframe = document.createElement('IFRAME');
  79. $(iframe).attr({
  80. style: opts["iframeElementOptions"]["styleToAdd"],
  81. id: printElementID,
  82. className: opts["iframeElementOptions"]["classNameToAdd"],
  83. frameBorder: 0,
  84. scrolling: 'no',
  85. src: 'about:blank'
  86. });
  87. document.body.appendChild(iframe);
  88. documentToWriteTo = (iframe.contentWindow || iframe.contentDocument);
  89. if (documentToWriteTo.document)
  90. documentToWriteTo = documentToWriteTo.document;
  91. iframe = document.frames ? document.frames[printElementID] : document.getElementById(printElementID);
  92. popupOrIframe = iframe.contentWindow || iframe;
  93. }
  94. focus();
  95. documentToWriteTo.open();
  96. documentToWriteTo.write(html);
  97. documentToWriteTo.close();
  98. _callPrint(popupOrIframe);
  99. };
  100. function _callPrint(element) {
  101. if (element && element["printPage"])
  102. element["printPage"]();
  103. else
  104. setTimeout(function () {
  105. _callPrint(element);
  106. }, 50);
  107. }
  108. function _getElementHTMLIncludingFormElements(element) {
  109. var $element = $(element);
  110. //Radiobuttons and checkboxes
  111. /*$(":checked", $element).each(function () {
  112. this.setAttribute('checked', 'checked');
  113. });
  114. //simple text inputs
  115. $("input[type='text']", $element).each(function () {
  116. this.setAttribute('value', $(this).val());
  117. });
  118. $("select", $element).each(function () {
  119. var $select = $(this);
  120. $("option", $select).each(function () {
  121. if ($select.val() == $(this).val())
  122. this.setAttribute('selected', 'selected');
  123. });
  124. });
  125. $("textarea", $element).each(function () {
  126. //Thanks http://blog.ekini.net/2009/02/24/jquery-getting-the-latest-textvalue-inside-a-textarea/
  127. var value = $(this).attr('value');
  128. //fix for issue 7 (http://plugins.jquery.com/node/13503 and http://github.com/erikzaadi/jQueryPlugins/issues#issue/7)
  129. if ($.browser.mozilla && this.firstChild)
  130. this.firstChild.textContent = value;
  131. else
  132. this.innerHTML = value;
  133. });*/
  134. //http://dbj.org/dbj/?p=91
  135. var elementHtml = $('<div></div>').append($element.clone()).html();
  136. return elementHtml;
  137. }
  138. function _getBaseHref() {
  139. var port = (window.location.port) ? ':' + window.location.port : '';
  140. return window.location.protocol + '//' + window.location.hostname + port + window.location.pathname;
  141. }
  142. function _getMarkup(element, opts) {
  143. var $element = $(element);
  144. var elementHtml = _getElementHTMLIncludingFormElements(element);
  145. var html = new Array();
  146. html.push('<html><head><title>' + opts["pageTitle"] + '</title>');
  147. if (opts["overrideElementCSS"]) {
  148. if (opts["overrideElementCSS"].length > 0) {
  149. for (var x = 0; x < opts["overrideElementCSS"].length; x++) {
  150. var current = opts["overrideElementCSS"][x];
  151. if (typeof (current) == 'string')
  152. html.push('<link type="text/css" rel="stylesheet" href="' + current + '" >');
  153. else
  154. html.push('<link type="text/css" rel="stylesheet" href="' + current["href"] + '" media="' + current["media"] + '" >');
  155. }
  156. }
  157. }
  158. else {
  159. $("link", document).filter(function () {
  160. return $(this).attr("rel").toLowerCase() == "stylesheet";
  161. }).each(function () {
  162. html.push('<link type="text/css" rel="stylesheet" href="' + $(this).attr("href") + '" media="' + $(this).attr('media') + '" >');
  163. });
  164. }
  165. //Ensure that relative links work
  166. html.push('<base href="' + _getBaseHref() + '" />');
  167. html.push('</head><body style="' + opts["printBodyOptions"]["styleToAdd"] + '" class="' + opts["printBodyOptions"]["classNameToAdd"] + '">');
  168. html.push('<div class="' + $element.attr('class') + '">' + elementHtml + '</div>');
  169. html.push('<script type="text/javascript">function printPage(){focus();print();' + ((!$.browser.opera && !opts["leaveOpen"] && opts["printMode"].toLowerCase() == 'popup') ? 'close();' : '') + '}</script>');
  170. html.push('</body></html>');
  171. return html.join('');
  172. };
  173. })(window);