print.js 38 KB

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