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.

196 lines
6.6 KiB

  1. const Print = function (dom, options) {
  2. if (!(this instanceof Print)) return new Print(dom, options);
  3. this.options = this.extend({
  4. 'noPrint': '.no-print'
  5. }, options);
  6. if ((typeof dom) === "string") {
  7. this.dom = document.querySelector(dom);
  8. } else {
  9. this.isDOM(dom)
  10. this.dom = this.isDOM(dom) ? dom : dom.$el;
  11. }
  12. this.init();
  13. };
  14. Print.prototype = {
  15. init: function () {
  16. var content = this.getStyle() + this.getHtml();
  17. this.writeIframe(content);
  18. },
  19. extend: function (obj, obj2) {
  20. for (var k in obj2) {
  21. obj[k] = obj2[k];
  22. }
  23. return obj;
  24. },
  25. getStyle: function () {
  26. var str = "",
  27. styles = document.querySelectorAll('style,link');
  28. for (var i = 0; i < styles.length; i++) {
  29. str += styles[i].outerHTML;
  30. }
  31. str += "<style>" + (this.options.noPrint ? this.options.noPrint : '.no-print') + "{display:none;}</style>";
  32. // 去除height:100%样式,解决分页下,样式混乱问题
  33. str += "<style>html,body,div{height: auto!important;}";
  34. // 可以控制打印方向,portrait: 纵向打印地, landscape: 横向
  35. str += "@media print { body { display: block !important;-webkit-print-color-adjust:exact;-moz-print-color-adjust:exact;-ms-print-color-adjust:exact;print-color-adjust:exact; } @page {size: auto A4 landscape;margin: 20px auto;}}</style>"
  36. return str;
  37. },
  38. getHtml: function () {
  39. var inputs = document.querySelectorAll('input');
  40. var textareas = document.querySelectorAll('textarea');
  41. var selects = document.querySelectorAll('select');
  42. var canvass = document.querySelectorAll('canvas');
  43. var svgs = document.querySelectorAll('svg');
  44. for (var k = 0; k < inputs.length; k++) {
  45. if (inputs[k].type == "checkbox" || inputs[k].type == "radio") {
  46. if (inputs[k].checked == true) {
  47. inputs[k].setAttribute('checked', "checked")
  48. } else {
  49. inputs[k].removeAttribute('checked')
  50. }
  51. } else if (inputs[k].type == "text") {
  52. inputs[k].setAttribute('value', inputs[k].value)
  53. } else {
  54. inputs[k].setAttribute('value', inputs[k].value)
  55. }
  56. }
  57. for (var k2 = 0; k2 < textareas.length; k2++) {
  58. if (textareas[k2].type == 'textarea') {
  59. textareas[k2].innerHTML = textareas[k2].value
  60. }
  61. }
  62. for (var k3 = 0; k3 < selects.length; k3++) {
  63. if (selects[k3].type == 'select-one') {
  64. var child = selects[k3].children;
  65. for (var i in child) {
  66. if (child[i].tagName == 'OPTION') {
  67. if (child[i].selected == true) {
  68. child[i].setAttribute('selected', "selected")
  69. } else {
  70. child[i].removeAttribute('selected')
  71. }
  72. }
  73. }
  74. }
  75. }
  76. //canvass echars图表转为图片
  77. for (var k4 = 0; k4 < canvass.length; k4++) {
  78. var imageURL = canvass[k4].toDataURL("image/png");
  79. var img = document.createElement("img");
  80. img.src = imageURL;
  81. img.setAttribute('style', 'max-width: 100%;');
  82. img.className = 'isNeedRemove'
  83. // canvass[k4].style.display = 'none'
  84. // canvass[k4].parentNode.style.width = '100%'
  85. // canvass[k4].parentNode.style.textAlign = 'center'
  86. canvass[k4].parentNode.insertBefore(img,canvass[k4].nextElementSibling);
  87. }
  88. // 包裹要打印的元素
  89. // fix: https://github.com/xyl66/vuePlugs_printjs/issues/36
  90. // return this.wrapperRefDom(this.dom).outerHTML;
  91. return this.dom.outerHTML;
  92. },
  93. drawSVGTOCanvas: function(svg){
  94. const { width, height} = svg.getBoundingClientRect();
  95. const serializer = new XMLSerializer();
  96. copy = svg.cloneNode(true);
  97. const data = serializer.serializeToString(copy);
  98. const image = new Image();
  99. const blob = new Blob([data],{
  100. type: 'iamge/svg+xml;charset=utf-8'
  101. });
  102. const url = URL.createObjectURL(blob);
  103. return new Promise(resolve =>{
  104. const canvas = document.createComment('canvas');
  105. const ctx = canvas.getContext('2d');
  106. canvas.width = width;
  107. canvas.height = height;
  108. image.addEventListener('load',()=>{
  109. ctx && ctx.drawImage(image,0,0,width,height);
  110. URL.revokeObjectURL(url);
  111. resolve(canvas);
  112. },{once: true});
  113. image.src = url;
  114. });
  115. },
  116. // 向父级元素循环,包裹当前需要打印的元素
  117. // 防止根级别开头的 css 选择器不生效
  118. wrapperRefDom: function (refDom) {
  119. let prevDom = null
  120. let currDom = refDom
  121. while (currDom && currDom.tagName.toLowerCase() !== 'body') {
  122. if (prevDom) {
  123. let element = currDom.cloneNode(false)
  124. element.appendChild(prevDom)
  125. prevDom = element
  126. } else {
  127. prevDom = currDom.cloneNode(true)
  128. }
  129. currDom = currDom.parentElement
  130. }
  131. return currDom.tagName.toLowerCase() === 'body' ? currDom : prevDom
  132. },
  133. writeIframe: function (content) {
  134. var w, doc, iframe = document.createElement('iframe'),
  135. f = document.body.appendChild(iframe);
  136. iframe.id = "myIframe";
  137. //iframe.style = "position:absolute;width:0;height:0;top:-10px;left:-10px;";
  138. iframe.setAttribute('style', 'position:absolute;width:0;height:0;top:-10px;left:-10px;');
  139. w = f.contentWindow || f.contentDocument;
  140. doc = f.contentDocument || f.contentWindow.document;
  141. doc.open();
  142. doc.write(content);
  143. doc.close();
  144. var _this = this
  145. iframe.onload = function(){
  146. _this.toPrint(w);
  147. setTimeout(function () {
  148. document.body.removeChild(iframe)
  149. }, 100)
  150. }
  151. },
  152. toPrint: function (frameWindow) {
  153. try {
  154. setTimeout(function () {
  155. frameWindow.focus();
  156. try {
  157. if (!frameWindow.document.execCommand('print', false, null)) {
  158. frameWindow.print();
  159. }
  160. } catch (e) {
  161. frameWindow.print();
  162. }
  163. frameWindow.close();
  164. }, 10);
  165. } catch (err) {
  166. console.log('err', err);
  167. }
  168. },
  169. isDOM: (typeof HTMLElement === 'object') ?
  170. function (obj) {
  171. return obj instanceof HTMLElement;
  172. } :
  173. function (obj) {
  174. return obj && typeof obj === 'object' && obj.nodeType === 1 && typeof obj.nodeName === 'string';
  175. }
  176. };
  177. const MyPlugin = {}
  178. MyPlugin.install = function (Vue, options) {
  179. // 4. 添加实例方法
  180. Vue.prototype.$print = Print
  181. }
  182. export default MyPlugin