print.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. (function webpackUniversalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory();
  4. else if(typeof define === 'function' && define.amd)
  5. define([], factory);
  6. else if(typeof exports === 'object')
  7. exports["printJS"] = factory();
  8. else
  9. root["printJS"] = factory();
  10. })(window, function() {
  11. return /******/ (function(modules) { // webpackBootstrap
  12. /******/ // The module cache
  13. /******/ let installedModules = {};
  14. /******/
  15. /******/ // The require function
  16. /******/ function __webpack_require__(moduleId) {
  17. /******/
  18. /******/ // Check if module is in cache
  19. /******/ if(installedModules[moduleId]) {
  20. /******/ return installedModules[moduleId].exports;
  21. /******/ }
  22. /******/ // Create a new module (and put it into the cache)
  23. /******/ let module = installedModules[moduleId] = {
  24. /******/ i: moduleId,
  25. /******/ l: false,
  26. /******/ exports: {}
  27. /******/ };
  28. /******/
  29. /******/ // Execute the module function
  30. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  31. /******/
  32. /******/ // Flag the module as loaded
  33. /******/ module.l = true;
  34. /******/
  35. /******/ // Return the exports of the module
  36. /******/ return module.exports;
  37. /******/ }
  38. /******/
  39. /******/
  40. /******/ // expose the modules object (__webpack_modules__)
  41. /******/ __webpack_require__.m = modules;
  42. /******/
  43. /******/ // expose the module cache
  44. /******/ __webpack_require__.c = installedModules;
  45. /******/
  46. /******/ // define getter function for harmony exports
  47. /******/ __webpack_require__.d = function(exports, name, getter) {
  48. /******/ if(!__webpack_require__.o(exports, name)) {
  49. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  50. /******/ }
  51. /******/ };
  52. /******/
  53. /******/ // define __esModule on exports
  54. /******/ __webpack_require__.r = function(exports) {
  55. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  56. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  57. /******/ }
  58. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  59. /******/ };
  60. /******/
  61. /******/ // create a fake namespace object
  62. /******/ // mode & 1: value is a module id, require it
  63. /******/ // mode & 2: merge all properties of value into the ns
  64. /******/ // mode & 4: return value when already ns object
  65. /******/ // mode & 8|1: behave like require
  66. /******/ __webpack_require__.t = function(value, mode) {
  67. /******/ if(mode & 1) value = __webpack_require__(value);
  68. /******/ if(mode & 8) return value;
  69. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  70. /******/ let ns = Object.create(null);
  71. /******/ __webpack_require__.r(ns);
  72. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  73. /******/ if(mode & 2 && typeof value !== 'string') for(let key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  74. /******/ return ns;
  75. /******/ };
  76. /******/
  77. /******/ // getDefaultExport function for compatibility with non-harmony modules
  78. /******/ __webpack_require__.n = function(module) {
  79. /******/ let getter = module && module.__esModule ?
  80. /******/ function getDefault() { return module['default']; } :
  81. /******/ function getModuleExports() { return module; };
  82. /******/ __webpack_require__.d(getter, 'a', getter);
  83. /******/ return getter;
  84. /******/ };
  85. /******/
  86. /******/ // Object.prototype.hasOwnProperty.call
  87. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  88. /******/
  89. /******/ // __webpack_public_path__
  90. /******/ __webpack_require__.p = "";
  91. /******/
  92. /******/
  93. /******/ // Load entry module and return exports
  94. /******/ return __webpack_require__(__webpack_require__.s = 0);
  95. /******/ })
  96. /************************************************************************/
  97. /******/ ({
  98. /***/ "./src/index.js":
  99. /*! **********************!*\
  100. !*** ./src/index.js ***!
  101. \**********************/
  102. /*! exports provided: default */
  103. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  104. "use strict";
  105. __webpack_require__.r(__webpack_exports__);
  106. /* harmony import */ let _sass_index_scss__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./sass/index.scss */ "./src/sass/index.scss");
  107. /* harmony import */ let _sass_index_scss__WEBPACK_IMPORTED_MODULE_0___default = /* #__PURE__ */__webpack_require__.n(_sass_index_scss__WEBPACK_IMPORTED_MODULE_0__);
  108. /* harmony import */ let _js_init__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./js/init */ "./src/js/init.js");
  109. let printJS = _js_init__WEBPACK_IMPORTED_MODULE_1__["default"].init;
  110. if (typeof window !== 'undefined') {
  111. window.printJS = printJS;
  112. }
  113. /* harmony default export */ __webpack_exports__["default"] = (printJS);
  114. /***/ }),
  115. /***/ "./src/js/browser.js":
  116. /*! ***************************!*\
  117. !*** ./src/js/browser.js ***!
  118. \***************************/
  119. /*! exports provided: default */
  120. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  121. "use strict";
  122. __webpack_require__.r(__webpack_exports__);
  123. var Browser = {
  124. // Firefox 1.0+
  125. isFirefox: function isFirefox() {
  126. return typeof InstallTrigger !== 'undefined';
  127. },
  128. // Internet Explorer 6-11
  129. isIE: function isIE() {
  130. return navigator.userAgent.indexOf('MSIE') !== -1 || !!document.documentMode;
  131. },
  132. // Edge 20+
  133. isEdge: function isEdge() {
  134. return !Browser.isIE() && !!window.StyleMedia;
  135. },
  136. // Chrome 1+
  137. isChrome: function isChrome() {
  138. let context = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window;
  139. return !!context.chrome;
  140. },
  141. // At least Safari 3+: "[object HTMLElementConstructor]"
  142. isSafari: function isSafari() {
  143. return Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0 || navigator.userAgent.toLowerCase().indexOf('safari') !== -1;
  144. },
  145. // IOS Chrome
  146. isIOSChrome: function isIOSChrome() {
  147. return navigator.userAgent.toLowerCase().indexOf('crios') !== -1;
  148. }
  149. };
  150. /* harmony default export */ __webpack_exports__["default"] = (Browser);
  151. /***/ }),
  152. /***/ "./src/js/functions.js":
  153. /*! *****************************!*\
  154. !*** ./src/js/functions.js ***!
  155. \*****************************/
  156. /*! exports provided: addWrapper, capitalizePrint, collectStyles, addHeader, cleanUp, isRawHTML */
  157. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  158. "use strict";
  159. __webpack_require__.r(__webpack_exports__);
  160. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addWrapper", function() { return addWrapper; });
  161. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "capitalizePrint", function() { return capitalizePrint; });
  162. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "collectStyles", function() { return collectStyles; });
  163. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addHeader", function() { return addHeader; });
  164. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cleanUp", function() { return cleanUp; });
  165. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isRawHTML", function() { return isRawHTML; });
  166. /* harmony import */ let _modal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./modal */ "./src/js/modal.js");
  167. /* harmony import */ let _browser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./browser */ "./src/js/browser.js");
  168. function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  169. function addWrapper(htmlData, params) {
  170. let bodyStyle = 'font-family:' + params.font + ' !important; font-size: ' + params.font_size + ' !important; width:100%;';
  171. return '<div style="' + bodyStyle + '">' + htmlData + '</div>';
  172. }
  173. function capitalizePrint(obj) {
  174. return obj.charAt(0).toUpperCase() + obj.slice(1);
  175. }
  176. function collectStyles(element, params) {
  177. let win = document.defaultView || window; // String variable to hold styling for each element
  178. let elementStyle = ''; // Loop over computed styles
  179. let styles = win.getComputedStyle(element, '');
  180. for (let key = 0; key < styles.length; key++) {
  181. // Check if style should be processed
  182. if (params.targetStyles.indexOf('*') !== -1 || params.targetStyle.indexOf(styles[key]) !== -1 || targetStylesMatch(params.targetStyles, styles[key])) {
  183. if (styles.getPropertyValue(styles[key])) elementStyle += styles[key] + ':' + styles.getPropertyValue(styles[key]) + ';';
  184. }
  185. } // Print friendly defaults (deprecated)
  186. // elementStyle += 'max-width: ' + params.maxWidth + 'px !important; font-size: ' + params.font_size + ' !important;';
  187. elementStyle += 'max-width: ' + params.maxWidth + 'px !important;';
  188. return elementStyle;
  189. }
  190. function targetStylesMatch(styles, value) {
  191. for (let i = 0; i < styles.length; i++) {
  192. if (_typeof(value) === 'object' && value.indexOf(styles[i]) !== -1) return true;
  193. }
  194. return false;
  195. }
  196. function addHeader(printElement, params) {
  197. // Create the header container div
  198. let headerContainer = document.createElement('div'); // Check if the header is text or raw html
  199. if (isRawHTML(params.header)) {
  200. headerContainer.innerHTML = params.header;
  201. } else {
  202. // Create header element
  203. let headerElement = document.createElement('h1'); // Create header text node
  204. let headerNode = document.createTextNode(params.header); // Build and style
  205. headerElement.appendChild(headerNode);
  206. headerElement.setAttribute('style', params.headerStyle);
  207. headerContainer.appendChild(headerElement);
  208. }
  209. printElement.insertBefore(headerContainer, printElement.childNodes[0]);
  210. }
  211. function cleanUp(params) {
  212. // If we are showing a feedback message to user, remove it
  213. if (params.showModal) _modal__WEBPACK_IMPORTED_MODULE_0__["default"].close(); // Check for a finished loading hook function
  214. if (params.onLoadingEnd) params.onLoadingEnd(); // If preloading pdf files, clean blob url
  215. if (params.showModal || params.onLoadingStart) window.URL.revokeObjectURL(params.printable); // Run onPrintDialogClose callback
  216. let event = 'mouseover';
  217. if (_browser__WEBPACK_IMPORTED_MODULE_1__["default"].isChrome() || _browser__WEBPACK_IMPORTED_MODULE_1__["default"].isFirefox()) {
  218. // Ps.: Firefox will require an extra click in the document to fire the focus event.
  219. event = 'focus';
  220. }
  221. let handler = function handler() {
  222. // Make sure the event only happens once.
  223. window.removeEventListener(event, handler);
  224. params.onPrintDialogClose(); // Remove iframe from the DOM
  225. let iframe = document.getElementById(params.frameId);
  226. if (iframe) {
  227. iframe.remove();
  228. }
  229. };
  230. window.addEventListener(event, handler);
  231. }
  232. function isRawHTML(raw) {
  233. let regexHtml = new RegExp('<([A-Za-z][A-Za-z0-9]*)\\b[^>]*>(.*?)</\\1>');
  234. return regexHtml.test(raw);
  235. }
  236. /***/ }),
  237. /***/ "./src/js/html.js":
  238. /*! ************************!*\
  239. !*** ./src/js/html.js ***!
  240. \************************/
  241. /*! exports provided: default */
  242. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  243. "use strict";
  244. __webpack_require__.r(__webpack_exports__);
  245. /* harmony import */ let _functions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./functions */ "./src/js/functions.js");
  246. /* harmony import */ let _print__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./print */ "./src/js/print.js");
  247. function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  248. /* harmony default export */ __webpack_exports__["default"] = ({
  249. print: function print(params, printFrame) {
  250. // Get the DOM printable element
  251. let printElement = isHtmlElement(params.printable) ? params.printable : document.getElementById(params.printable); // Check if the element exists
  252. if (!printElement) {
  253. window.console.error('Invalid HTML element id: ' + params.printable);
  254. return;
  255. } // Clone the target element including its children (if available)
  256. params.printableElement = cloneElement(printElement, params); // Add header
  257. if (params.header) {
  258. Object(_functions__WEBPACK_IMPORTED_MODULE_0__["addHeader"])(params.printableElement, params);
  259. } // Print html element contents
  260. _print__WEBPACK_IMPORTED_MODULE_1__["default"].send(params, printFrame);
  261. }
  262. });
  263. function cloneElement(element, params) {
  264. // Clone the main node (if not already inside the recursion process)
  265. let clone = element.cloneNode(); // Loop over and process the children elements / nodes (including text nodes)
  266. let childNodesArray = Array.prototype.slice.call(element.childNodes);
  267. for (let i = 0; i < childNodesArray.length; i++) {
  268. // Check if we are skipping the current element
  269. if (params.ignoreElements.indexOf(childNodesArray[i].id) !== -1) {
  270. continue;
  271. } // Clone the child element
  272. let clonedChild = cloneElement(childNodesArray[i], params); // Attach the cloned child to the cloned parent node
  273. clone.appendChild(clonedChild);
  274. } // Get all styling for print element (for nodes of type element only)
  275. if (params.scanStyles && element.nodeType === 1) {
  276. clone.setAttribute('style', Object(_functions__WEBPACK_IMPORTED_MODULE_0__["collectStyles"])(element, params));
  277. } // Check if the element needs any state processing (copy user input data)
  278. switch (element.tagName) {
  279. case 'SELECT':
  280. // Copy the current selection value to its clone
  281. clone.value = element.value;
  282. break;
  283. case 'CANVAS':
  284. // Copy the canvas content to its clone
  285. clone.getContext('2d').drawImage(element, 0, 0);
  286. break;
  287. }
  288. return clone;
  289. }
  290. function isHtmlElement(printable) {
  291. // Check if element is instance of HTMLElement or has nodeType === 1 (for elements in iframe)
  292. return _typeof(printable) === 'object' && printable && (printable instanceof HTMLElement || printable.nodeType === 1);
  293. }
  294. /***/ }),
  295. /***/ "./src/js/image.js":
  296. /*! *************************!*\
  297. !*** ./src/js/image.js ***!
  298. \*************************/
  299. /*! exports provided: default */
  300. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  301. "use strict";
  302. __webpack_require__.r(__webpack_exports__);
  303. /* harmony import */ let _functions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./functions */ "./src/js/functions.js");
  304. /* harmony import */ let _print__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./print */ "./src/js/print.js");
  305. /* harmony import */ let _browser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./browser */ "./src/js/browser.js");
  306. /* harmony default export */ __webpack_exports__["default"] = ({
  307. print: function print(params, printFrame) {
  308. // Check if we are printing one image or multiple images
  309. if (params.printable.constructor !== Array) {
  310. // Create array with one image
  311. params.printable = [params.printable];
  312. } // Create printable element (container)
  313. params.printableElement = document.createElement('div'); // Create all image elements and append them to the printable container
  314. params.printable.forEach(function (src) {
  315. // Create the image element
  316. let img = document.createElement('img');
  317. img.setAttribute('style', params.imageStyle); // Set image src with the file url
  318. img.src = src; // The following block is for Firefox, which for some reason requires the image's src to be fully qualified in
  319. // order to print it
  320. if (_browser__WEBPACK_IMPORTED_MODULE_2__["default"].isFirefox()) {
  321. let fullyQualifiedSrc = img.src;
  322. img.src = fullyQualifiedSrc;
  323. } // Create the image wrapper
  324. let imageWrapper = document.createElement('div'); // Append image to the wrapper element
  325. imageWrapper.appendChild(img); // Append wrapper to the printable element
  326. params.printableElement.appendChild(imageWrapper);
  327. }); // Check if we are adding a print header
  328. if (params.header) Object(_functions__WEBPACK_IMPORTED_MODULE_0__["addHeader"])(params.printableElement, params); // Print image
  329. _print__WEBPACK_IMPORTED_MODULE_1__["default"].send(params, printFrame);
  330. }
  331. });
  332. /***/ }),
  333. /***/ "./src/js/init.js":
  334. /*! ************************!*\
  335. !*** ./src/js/init.js ***!
  336. \************************/
  337. /*! exports provided: default */
  338. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  339. "use strict";
  340. __webpack_require__.r(__webpack_exports__);
  341. /* harmony import */ let _browser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./browser */ "./src/js/browser.js");
  342. /* harmony import */ let _modal__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./modal */ "./src/js/modal.js");
  343. /* harmony import */ let _pdf__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./pdf */ "./src/js/pdf.js");
  344. /* harmony import */ let _html__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./html */ "./src/js/html.js");
  345. /* harmony import */ let _raw_html__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./raw-html */ "./src/js/raw-html.js");
  346. /* harmony import */ let _image__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./image */ "./src/js/image.js");
  347. /* harmony import */ let _json__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./json */ "./src/js/json.js");
  348. function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  349. let printTypes = ['pdf', 'html', 'image', 'json', 'raw-html'];
  350. /* harmony default export */ __webpack_exports__["default"] = ({
  351. init: function init() {
  352. let params = {
  353. printable: null,
  354. fallbackPrintable: null,
  355. type: 'pdf',
  356. header: null,
  357. headerStyle: 'font-weight: 300;',
  358. maxWidth: 800,
  359. properties: null,
  360. gridHeaderStyle: 'font-weight: bold; padding: 5px; border: 1px solid #dddddd;',
  361. gridStyle: 'border: 1px solid lightgray; margin-bottom: -1px;',
  362. showModal: false,
  363. onError: function onError(error) {
  364. throw error;
  365. },
  366. onLoadingStart: null,
  367. onLoadingEnd: null,
  368. onPrintDialogClose: function onPrintDialogClose() {},
  369. onIncompatibleBrowser: function onIncompatibleBrowser() {},
  370. modalMessage: 'Retrieving Document...',
  371. frameId: 'printJS',
  372. printableElement: null,
  373. documentTitle: 'Document',
  374. targetStyle: ['clear', 'display', 'width', 'min-width', 'height', 'min-height', 'max-height'],
  375. targetStyles: ['border', 'box', 'break', 'text-decoration'],
  376. ignoreElements: [],
  377. repeatTableHeader: true,
  378. css: null,
  379. style: null,
  380. scanStyles: true,
  381. base64: false,
  382. // Deprecated
  383. onPdfOpen: null,
  384. font: 'TimesNewRoman',
  385. font_size: '12pt',
  386. honorMarginPadding: true,
  387. honorColor: false,
  388. imageStyle: 'max-width: 100%;'
  389. }; // Check if a printable document or object was supplied
  390. let args = arguments[0];
  391. if (args === undefined) {
  392. throw new Error('printJS expects at least 1 attribute.');
  393. } // Process parameters
  394. switch (_typeof(args)) {
  395. case 'string':
  396. params.printable = encodeURI(args);
  397. params.fallbackPrintable = params.printable;
  398. params.type = arguments[1] || params.type;
  399. break;
  400. case 'object':
  401. params.printable = args.printable;
  402. params.fallbackPrintable = typeof args.fallbackPrintable !== 'undefined' ? args.fallbackPrintable : params.printable;
  403. params.fallbackPrintable = params.base64 ? "data:application/pdf;base64,".concat(params.fallbackPrintable) : params.fallbackPrintable;
  404. for (let k in params) {
  405. if (k === 'printable' || k === 'fallbackPrintable') continue;
  406. params[k] = typeof args[k] !== 'undefined' ? args[k] : params[k];
  407. }
  408. break;
  409. default:
  410. throw new Error('Unexpected argument type! Expected "string" or "object", got ' + _typeof(args));
  411. } // Validate printable
  412. if (!params.printable) throw new Error('Missing printable information.'); // Validate type
  413. if (!params.type || typeof params.type !== 'string' || printTypes.indexOf(params.type.toLowerCase()) === -1) {
  414. throw new Error('Invalid print type. Available types are: pdf, html, image and json.');
  415. } // Check if we are showing a feedback message to the user (useful for large files)
  416. if (params.showModal) _modal__WEBPACK_IMPORTED_MODULE_1__["default"].show(params); // Check for a print start hook function
  417. if (params.onLoadingStart) params.onLoadingStart(); // To prevent duplication and issues, remove any used printFrame from the DOM
  418. let usedFrame = document.getElementById(params.frameId);
  419. if (usedFrame) usedFrame.parentNode.removeChild(usedFrame); // Create a new iframe for the print job
  420. let printFrame = document.createElement('iframe');
  421. if (_browser__WEBPACK_IMPORTED_MODULE_0__["default"].isFirefox()) {
  422. // Set the iframe to be is visible on the page (guaranteed by fixed position) but hidden using opacity 0, because
  423. // this works in Firefox. The height needs to be sufficient for some part of the document other than the PDF
  424. // viewer's toolbar to be visible in the page
  425. printFrame.setAttribute('style', 'width: 1px; height: 100px; position: fixed; left: 0; top: 0; opacity: 0; border-width: 0; margin: 0; padding: 0');
  426. } else {
  427. // Hide the iframe in other browsers
  428. printFrame.setAttribute('style', 'visibility: hidden; height: 0; width: 0; position: absolute; border: 0');
  429. } // Set iframe element id
  430. printFrame.setAttribute('id', params.frameId); // For non pdf printing, pass an html document string to srcdoc (force onload callback)
  431. if (params.type !== 'pdf') {
  432. printFrame.srcdoc = '<html><head><title>' + params.documentTitle + '</title>'; // Attach css files
  433. if (params.css) {
  434. // Add support for single file
  435. if (!Array.isArray(params.css)) params.css = [params.css]; // Create link tags for each css file
  436. params.css.forEach(function (file) {
  437. printFrame.srcdoc += '<link rel="stylesheet" href="' + file + '">';
  438. });
  439. }
  440. printFrame.srcdoc += '</head><body></body></html>';
  441. } // Check printable type
  442. switch (params.type) {
  443. case 'pdf':
  444. // Check browser support for pdf and if not supported we will just open the pdf file instead
  445. if (_browser__WEBPACK_IMPORTED_MODULE_0__["default"].isIE()) {
  446. try {
  447. console.info('Print.js doesn\'t support PDF printing in Internet Explorer.');
  448. let win = window.open(params.fallbackPrintable, '_blank');
  449. win.focus();
  450. params.onIncompatibleBrowser();
  451. } catch (error) {
  452. params.onError(error);
  453. } finally {
  454. // Make sure there is no loading modal opened
  455. if (params.showModal) _modal__WEBPACK_IMPORTED_MODULE_1__["default"].close();
  456. if (params.onLoadingEnd) params.onLoadingEnd();
  457. }
  458. } else {
  459. _pdf__WEBPACK_IMPORTED_MODULE_2__["default"].print(params, printFrame);
  460. }
  461. break;
  462. case 'image':
  463. _image__WEBPACK_IMPORTED_MODULE_5__["default"].print(params, printFrame);
  464. break;
  465. case 'html':
  466. _html__WEBPACK_IMPORTED_MODULE_3__["default"].print(params, printFrame);
  467. break;
  468. case 'raw-html':
  469. _raw_html__WEBPACK_IMPORTED_MODULE_4__["default"].print(params, printFrame);
  470. break;
  471. case 'json':
  472. _json__WEBPACK_IMPORTED_MODULE_6__["default"].print(params, printFrame);
  473. break;
  474. }
  475. }
  476. });
  477. /***/ }),
  478. /***/ "./src/js/json.js":
  479. /*! ************************!*\
  480. !*** ./src/js/json.js ***!
  481. \************************/
  482. /*! exports provided: default */
  483. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  484. "use strict";
  485. __webpack_require__.r(__webpack_exports__);
  486. /* harmony import */ let _functions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./functions */ "./src/js/functions.js");
  487. /* harmony import */ let _print__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./print */ "./src/js/print.js");
  488. function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  489. /* harmony default export */ __webpack_exports__["default"] = ({
  490. print: function print(params, printFrame) {
  491. // Check if we received proper data
  492. if (_typeof(params.printable) !== 'object') {
  493. throw new Error('Invalid javascript data object (JSON).');
  494. } // Validate repeatTableHeader
  495. if (typeof params.repeatTableHeader !== 'boolean') {
  496. throw new Error('Invalid value for repeatTableHeader attribute (JSON).');
  497. } // Validate properties
  498. if (!params.properties || !Array.isArray(params.properties)) {
  499. throw new Error('Invalid properties array for your JSON data.');
  500. } // We will format the property objects to keep the JSON api compatible with older releases
  501. params.properties = params.properties.map(function (property) {
  502. return {
  503. field: _typeof(property) === 'object' ? property.field : property,
  504. displayName: _typeof(property) === 'object' ? property.displayName : property,
  505. columnSize: _typeof(property) === 'object' && property.columnSize ? property.columnSize + ';' : 100 / params.properties.length + '%;'
  506. };
  507. }); // Create a print container element
  508. params.printableElement = document.createElement('div'); // Check if we are adding a print header
  509. if (params.header) {
  510. Object(_functions__WEBPACK_IMPORTED_MODULE_0__["addHeader"])(params.printableElement, params);
  511. } // Build the printable html data
  512. params.printableElement.innerHTML += jsonToHTML(params); // Print the json data
  513. _print__WEBPACK_IMPORTED_MODULE_1__["default"].send(params, printFrame);
  514. }
  515. });
  516. function jsonToHTML(params) {
  517. // Get the row and column data
  518. let data = params.printable;
  519. let properties = params.properties; // Create a html table
  520. let htmlData = '<table style="border-collapse: collapse; width: 100%;">'; // Check if the header should be repeated
  521. if (params.repeatTableHeader) {
  522. htmlData += '<thead>';
  523. } // Add the table header row
  524. htmlData += '<tr>'; // Add the table header columns
  525. for (let a = 0; a < properties.length; a++) {
  526. htmlData += '<th style="width:' + properties[a].columnSize + ';' + params.gridHeaderStyle + '">' + Object(_functions__WEBPACK_IMPORTED_MODULE_0__["capitalizePrint"])(properties[a].displayName) + '</th>';
  527. } // Add the closing tag for the table header row
  528. htmlData += '</tr>'; // If the table header is marked as repeated, add the closing tag
  529. if (params.repeatTableHeader) {
  530. htmlData += '</thead>';
  531. } // Create the table body
  532. htmlData += '<tbody>'; // Add the table data rows
  533. for (let i = 0; i < data.length; i++) {
  534. // Add the row starting tag
  535. htmlData += '<tr>'; // Print selected properties only
  536. for (let n = 0; n < properties.length; n++) {
  537. let stringData = data[i]; // Support nested objects
  538. let property = properties[n].field.split('.');
  539. if (property.length > 1) {
  540. for (let p = 0; p < property.length; p++) {
  541. stringData = stringData[property[p]];
  542. }
  543. } else {
  544. stringData = stringData[properties[n].field];
  545. } // Add the row contents and styles
  546. htmlData += '<td style="width:' + properties[n].columnSize + params.gridStyle + '">' + stringData + '</td>';
  547. } // Add the row closing tag
  548. htmlData += '</tr>';
  549. } // Add the table and body closing tags
  550. htmlData += '</tbody></table>';
  551. return htmlData;
  552. }
  553. /***/ }),
  554. /***/ "./src/js/modal.js":
  555. /*! *************************!*\
  556. !*** ./src/js/modal.js ***!
  557. \*************************/
  558. /*! exports provided: default */
  559. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  560. "use strict";
  561. __webpack_require__.r(__webpack_exports__);
  562. var Modal = {
  563. show: function show(params) {
  564. // Build modal
  565. let modalStyle = 'font-family:sans-serif; ' + 'display:table; ' + 'text-align:center; ' + 'font-weight:300; ' + 'font-size:30px; ' + 'left:0; top:0;' + 'position:fixed; ' + 'z-index: 9990;' + 'color: #0460B5; ' + 'width: 100%; ' + 'height: 100%; ' + 'background-color:rgba(255,255,255,.9);' + 'transition: opacity .3s ease;'; // Create wrapper
  566. let printModal = document.createElement('div');
  567. printModal.setAttribute('style', modalStyle);
  568. printModal.setAttribute('id', 'printJS-Modal'); // Create content div
  569. let contentDiv = document.createElement('div');
  570. contentDiv.setAttribute('style', 'display:table-cell; vertical-align:middle; padding-bottom:100px;'); // Add close button (requires print.css)
  571. let closeButton = document.createElement('div');
  572. closeButton.setAttribute('class', 'printClose');
  573. closeButton.setAttribute('id', 'printClose');
  574. contentDiv.appendChild(closeButton); // Add spinner (requires print.css)
  575. let spinner = document.createElement('span');
  576. spinner.setAttribute('class', 'printSpinner');
  577. contentDiv.appendChild(spinner); // Add message
  578. let messageNode = document.createTextNode(params.modalMessage);
  579. contentDiv.appendChild(messageNode); // Add contentDiv to printModal
  580. printModal.appendChild(contentDiv); // Append print modal element to document body
  581. document.getElementsByTagName('body')[0].appendChild(printModal); // Add event listener to close button
  582. document.getElementById('printClose').addEventListener('click', function () {
  583. Modal.close();
  584. });
  585. },
  586. close: function close() {
  587. let printModal = document.getElementById('printJS-Modal');
  588. if (printModal) {
  589. printModal.parentNode.removeChild(printModal);
  590. }
  591. }
  592. };
  593. /* harmony default export */ __webpack_exports__["default"] = (Modal);
  594. /***/ }),
  595. /***/ "./src/js/pdf.js":
  596. /*! ***********************!*\
  597. !*** ./src/js/pdf.js ***!
  598. \***********************/
  599. /*! exports provided: default */
  600. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  601. "use strict";
  602. __webpack_require__.r(__webpack_exports__);
  603. /* harmony import */ let _print__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./print */ "./src/js/print.js");
  604. /* harmony import */ let _functions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./functions */ "./src/js/functions.js");
  605. /* harmony default export */ __webpack_exports__["default"] = ({
  606. print: function print(params, printFrame) {
  607. // Check if we have base64 data
  608. if (params.base64) {
  609. let bytesArray = Uint8Array.from(atob(params.printable), function (c) {
  610. return c.charCodeAt(0);
  611. });
  612. createBlobAndPrint(params, printFrame, bytesArray);
  613. return;
  614. } // Format pdf url
  615. params.printable = /^(blob|http|\/\/)/i.test(params.printable) ? params.printable : window.location.origin + (params.printable.charAt(0) !== '/' ? '/' + params.printable : params.printable); // Get the file through a http request (Preload)
  616. let req = new window.XMLHttpRequest();
  617. req.responseType = 'arraybuffer';
  618. req.addEventListener('error', function () {
  619. Object(_functions__WEBPACK_IMPORTED_MODULE_1__["cleanUp"])(params);
  620. params.onError(req.statusText, req); // Since we don't have a pdf document available, we will stop the print job
  621. });
  622. req.addEventListener('load', function () {
  623. // Check for errors
  624. if ([200, 201].indexOf(req.status) === -1) {
  625. Object(_functions__WEBPACK_IMPORTED_MODULE_1__["cleanUp"])(params);
  626. params.onError(req.statusText, req); // Since we don't have a pdf document available, we will stop the print job
  627. return;
  628. } // Print requested document
  629. createBlobAndPrint(params, printFrame, req.response);
  630. });
  631. req.open('GET', params.printable, true);
  632. req.send();
  633. }
  634. });
  635. function createBlobAndPrint(params, printFrame, data) {
  636. // Pass response or base64 data to a blob and create a local object url
  637. let localPdf = new window.Blob([data], {
  638. type: 'application/pdf'
  639. });
  640. localPdf = window.URL.createObjectURL(localPdf); // Set iframe src with pdf document url
  641. printFrame.setAttribute('src', localPdf);
  642. _print__WEBPACK_IMPORTED_MODULE_0__["default"].send(params, printFrame);
  643. }
  644. /***/ }),
  645. /***/ "./src/js/print.js":
  646. /*! *************************!*\
  647. !*** ./src/js/print.js ***!
  648. \*************************/
  649. /*! exports provided: default */
  650. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  651. "use strict";
  652. __webpack_require__.r(__webpack_exports__);
  653. /* harmony import */ let _browser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./browser */ "./src/js/browser.js");
  654. /* harmony import */ let _functions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./functions */ "./src/js/functions.js");
  655. let Print = {
  656. send: function send(params, printFrame) {
  657. // Append iframe element to document body
  658. document.getElementsByTagName('body')[0].appendChild(printFrame); // Get iframe element
  659. let iframeElement = document.getElementById(params.frameId); // Wait for iframe to load all content
  660. iframeElement.onload = function () {
  661. if (params.type === 'pdf') {
  662. // Add a delay for Firefox. In my tests, 1000ms was sufficient but 100ms was not
  663. if (_browser__WEBPACK_IMPORTED_MODULE_0__["default"].isFirefox()) {
  664. setTimeout(function () {
  665. return performPrint(iframeElement, params);
  666. }, 1000);
  667. } else {
  668. performPrint(iframeElement, params);
  669. }
  670. return;
  671. } // Get iframe element document
  672. let printDocument = iframeElement.contentWindow || iframeElement.contentDocument;
  673. if (printDocument.document) printDocument = printDocument.document; // Append printable element to the iframe body
  674. printDocument.body.appendChild(params.printableElement); // Add custom style
  675. if (params.type !== 'pdf' && params.style) {
  676. // Create style element
  677. let style = document.createElement('style');
  678. style.innerHTML = params.style; // Append style element to iframe's head
  679. printDocument.head.appendChild(style);
  680. } // If printing images, wait for them to load inside the iframe
  681. let images = printDocument.getElementsByTagName('img');
  682. if (images.length > 0) {
  683. loadIframeImages(Array.from(images)).then(function () {
  684. return performPrint(iframeElement, params);
  685. });
  686. } else {
  687. performPrint(iframeElement, params);
  688. }
  689. };
  690. }
  691. };
  692. function performPrint(iframeElement, params) {
  693. try {
  694. iframeElement.focus(); // If Edge or IE, try catch with execCommand
  695. if (_browser__WEBPACK_IMPORTED_MODULE_0__["default"].isEdge() || _browser__WEBPACK_IMPORTED_MODULE_0__["default"].isIE()) {
  696. try {
  697. iframeElement.contentWindow.document.execCommand('print', false, null);
  698. } catch (e) {
  699. iframeElement.contentWindow.print();
  700. }
  701. } else {
  702. // Other browsers
  703. iframeElement.contentWindow.print();
  704. }
  705. } catch (error) {
  706. params.onError(error);
  707. } finally {
  708. if (_browser__WEBPACK_IMPORTED_MODULE_0__["default"].isFirefox()) {
  709. // Move the iframe element off-screen and make it invisible
  710. iframeElement.style.visibility = 'hidden';
  711. iframeElement.style.left = '-1px';
  712. }
  713. Object(_functions__WEBPACK_IMPORTED_MODULE_1__["cleanUp"])(params);
  714. }
  715. }
  716. function loadIframeImages(images) {
  717. let promises = images.map(function (image) {
  718. if (image.src && image.src !== window.location.href) {
  719. return loadIframeImage(image);
  720. }
  721. });
  722. return Promise.all(promises);
  723. }
  724. function loadIframeImage(image) {
  725. return new Promise(function (resolve) {
  726. let pollImage = function pollImage() {
  727. !image || typeof image.naturalWidth === 'undefined' || image.naturalWidth === 0 || !image.complete ? setTimeout(pollImage, 500) : resolve();
  728. };
  729. pollImage();
  730. });
  731. }
  732. /* harmony default export */ __webpack_exports__["default"] = (Print);
  733. /***/ }),
  734. /***/ "./src/js/raw-html.js":
  735. /*! ****************************!*\
  736. !*** ./src/js/raw-html.js ***!
  737. \****************************/
  738. /*! exports provided: default */
  739. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  740. "use strict";
  741. __webpack_require__.r(__webpack_exports__);
  742. /* harmony import */ let _print__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./print */ "./src/js/print.js");
  743. /* harmony default export */ __webpack_exports__["default"] = ({
  744. print: function print(params, printFrame) {
  745. // Create printable element (container)
  746. params.printableElement = document.createElement('div');
  747. params.printableElement.setAttribute('style', 'width:100%'); // Set our raw html as the printable element inner html content
  748. params.printableElement.innerHTML = params.printable; // Print html contents
  749. _print__WEBPACK_IMPORTED_MODULE_0__["default"].send(params, printFrame);
  750. }
  751. });
  752. /***/ }),
  753. /***/ "./src/sass/index.scss":
  754. /*! *****************************!*\
  755. !*** ./src/sass/index.scss ***!
  756. \*****************************/
  757. /*! no static exports found */
  758. /***/ (function(module, exports, __webpack_require__) {
  759. // extracted by mini-css-extract-plugin
  760. /***/ }),
  761. /***/ 0:
  762. /*! ****************************!*\
  763. !*** multi ./src/index.js ***!
  764. \****************************/
  765. /*! no static exports found */
  766. /***/ (function(module, exports, __webpack_require__) {
  767. module.exports = __webpack_require__(/*! ./src/index.js */"./src/index.js");
  768. /***/ })
  769. /******/ })["default"];
  770. });
  771. // # sourceMappingURL=print.map