print.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. interface PrintFunction {
  2. extendOptions: Function;
  3. getStyle: Function;
  4. setDomHeight: Function;
  5. toPrint: Function;
  6. }
  7. const Print = function (dom, options?: object): PrintFunction {
  8. options = options || {};
  9. // @ts-expect-error
  10. if (!(this instanceof Print)) return new Print(dom, options);
  11. // @ts-expect-error
  12. this.conf = {
  13. styleStr: "",
  14. // Elements that need to dynamically get and set the height
  15. setDomHeightArr: [],
  16. // Callback before printing
  17. printBeforeFn: null,
  18. // Callback after printing
  19. printDoneCallBack: null
  20. };
  21. // @ts-expect-error
  22. for (const key in this.conf) {
  23. if (key && options.hasOwnProperty(key)) {
  24. // @ts-expect-error
  25. this.conf[key] = options[key];
  26. }
  27. }
  28. if (typeof dom === "string") {
  29. // @ts-expect-error
  30. this.dom = document.querySelector(dom);
  31. } else {
  32. // @ts-expect-error
  33. this.dom = this.isDOM(dom) ? dom : dom.$el;
  34. }
  35. // @ts-expect-error
  36. if (this.conf.setDomHeightArr && this.conf.setDomHeightArr.length) {
  37. // @ts-expect-error
  38. this.setDomHeight(this.conf.setDomHeightArr);
  39. }
  40. // @ts-expect-error
  41. this.init();
  42. };
  43. Print.prototype = {
  44. /**
  45. * init
  46. */
  47. init: function (): void {
  48. const content = this.getStyle() + this.getHtml();
  49. this.writeIframe(content);
  50. },
  51. /**
  52. * Configuration property extension
  53. * @param {Object} obj
  54. * @param {Object} obj2
  55. */
  56. extendOptions: function <T>(obj, obj2: T): T {
  57. for (const k in obj2) {
  58. obj[k] = obj2[k];
  59. }
  60. return obj;
  61. },
  62. /**
  63. Copy all styles of the original page
  64. */
  65. getStyle: function (): string {
  66. let str = "";
  67. const styles: NodeListOf<Element> = document.querySelectorAll("style,link");
  68. for (let i = 0; i < styles.length; i++) {
  69. str += styles[i].outerHTML;
  70. }
  71. str += `<style>.no-print{display:none;}${this.conf.styleStr}</style>`;
  72. return str;
  73. },
  74. // form assignment
  75. getHtml: function (): Element {
  76. const inputs = document.querySelectorAll("input");
  77. const selects = document.querySelectorAll("select");
  78. const textareas = document.querySelectorAll("textarea");
  79. const canvass = document.querySelectorAll("canvas");
  80. for (let k = 0; k < inputs.length; k++) {
  81. if (inputs[k].type == "checkbox" || inputs[k].type == "radio") {
  82. if (inputs[k].checked == true) {
  83. inputs[k].setAttribute("checked", "checked");
  84. } else {
  85. inputs[k].removeAttribute("checked");
  86. }
  87. } else if (inputs[k].type == "text") {
  88. inputs[k].setAttribute("value", inputs[k].value);
  89. } else {
  90. inputs[k].setAttribute("value", inputs[k].value);
  91. }
  92. }
  93. for (let k2 = 0; k2 < textareas.length; k2++) {
  94. if (textareas[k2].type == "textarea") {
  95. textareas[k2].innerHTML = textareas[k2].value;
  96. }
  97. }
  98. for (let k3 = 0; k3 < selects.length; k3++) {
  99. if (selects[k3].type == "select-one") {
  100. const child = selects[k3].children;
  101. for (const i in child) {
  102. if (child[i].tagName == "OPTION") {
  103. if ((child[i] as any).selected == true) {
  104. child[i].setAttribute("selected", "selected");
  105. } else {
  106. child[i].removeAttribute("selected");
  107. }
  108. }
  109. }
  110. }
  111. }
  112. for (let k4 = 0; k4 < canvass.length; k4++) {
  113. const imageURL = canvass[k4].toDataURL("image/png");
  114. const img = document.createElement("img");
  115. img.src = imageURL;
  116. img.setAttribute("style", "max-width: 100%;");
  117. img.className = "isNeedRemove";
  118. canvass[k4].parentNode.insertBefore(img, canvass[k4].nextElementSibling);
  119. }
  120. return this.dom.outerHTML;
  121. },
  122. /**
  123. create iframe
  124. */
  125. writeIframe: function (content) {
  126. let w: Document | Window;
  127. let doc: Document;
  128. const iframe: HTMLIFrameElement = document.createElement("iframe");
  129. const f: HTMLIFrameElement = document.body.appendChild(iframe);
  130. iframe.id = "myIframe";
  131. iframe.setAttribute(
  132. "style",
  133. "position:absolute;width:0;height:0;top:-10px;left:-10px;"
  134. );
  135. // eslint-disable-next-line prefer-const
  136. w = f.contentWindow || f.contentDocument;
  137. // eslint-disable-next-line prefer-const
  138. doc = f.contentDocument || f.contentWindow.document;
  139. doc.open();
  140. doc.write(content);
  141. doc.close();
  142. const removes = document.querySelectorAll(".isNeedRemove");
  143. for (let k = 0; k < removes.length; k++) {
  144. removes[k].parentNode.removeChild(removes[k]);
  145. }
  146. // eslint-disable-next-line @typescript-eslint/no-this-alias
  147. const _this = this;
  148. iframe.onload = function (): void {
  149. // Before popping, callback
  150. if (_this.conf.printBeforeFn) {
  151. _this.conf.printBeforeFn({ doc });
  152. }
  153. _this.toPrint(w);
  154. setTimeout(function () {
  155. document.body.removeChild(iframe);
  156. // After popup, callback
  157. if (_this.conf.printDoneCallBack) {
  158. _this.conf.printDoneCallBack();
  159. }
  160. }, 100);
  161. };
  162. },
  163. /**
  164. Print
  165. */
  166. toPrint: function (frameWindow): void {
  167. try {
  168. setTimeout(function () {
  169. frameWindow.focus();
  170. try {
  171. if (!frameWindow.document.execCommand("print", false, null)) {
  172. frameWindow.print();
  173. }
  174. } catch {
  175. frameWindow.print();
  176. }
  177. frameWindow.close();
  178. }, 10);
  179. } catch (err) {
  180. console.error(err);
  181. }
  182. },
  183. isDOM:
  184. typeof HTMLElement === "object"
  185. ? function (obj) {
  186. return obj instanceof HTMLElement;
  187. }
  188. : function (obj) {
  189. return (
  190. obj &&
  191. typeof obj === "object" &&
  192. obj.nodeType === 1 &&
  193. typeof obj.nodeName === "string"
  194. );
  195. },
  196. /**
  197. * Set the height of the specified dom element by getting the existing height of the dom element and setting
  198. * @param {Array} arr
  199. */
  200. setDomHeight(arr) {
  201. if (arr && arr.length) {
  202. arr.forEach(name => {
  203. const domArr = document.querySelectorAll(name);
  204. domArr.forEach(dom => {
  205. dom.style.height = dom.offsetHeight + "px";
  206. });
  207. });
  208. }
  209. }
  210. };
  211. export default Print;