webpage print to PDF

剪裁网页的内容,打印成PDF

当前为 2017-12-08 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name webpage print to PDF
  3. // @description 剪裁网页的内容,打印成PDF
  4. // @namespace jjjj
  5. // @author amormaid
  6. // @version 0.1
  7. // @include *
  8. // @run-at document-end
  9. // @grant GM_xmlhttpRequest
  10. // @require https://greasyfork.org/scripts/15924-jspdf/code/jsPDF.js
  11. // ==/UserScript==
  12.  
  13. !
  14. function(e) {
  15. if ("object" == typeof exports && "undefined" != typeof module) module.exports = e();
  16. else if ("function" == typeof define && define.amd) define([], e);
  17. else {
  18. var f;
  19. "undefined" != typeof window ? f = window : "undefined" != typeof global ? f = global : "undefined" != typeof self && (f = self), f.html2canvas = e()
  20. }
  21. }(function() {
  22. var define, module, exports;
  23. return (function e(t, n, r) {
  24. function s(o, u) {
  25. if (!n[o]) {
  26. if (!t[o]) {
  27. var a = typeof require == "function" && require;
  28. if (!u && a) return a(o, !0);
  29. if (i) return i(o, !0);
  30. var f = new Error("Cannot find module '" + o + "'");
  31. throw f.code = "MODULE_NOT_FOUND", f
  32. }
  33. var l = n[o] = {
  34. exports: {}
  35. };
  36. t[o][0].call(l.exports, function(e) {
  37. var n = t[o][1][e];
  38. return s(n ? n : e)
  39. }, l, l.exports, e, t, n, r)
  40. }
  41. return n[o].exports
  42. }
  43. var i = typeof require == "function" && require;
  44. for (var o = 0; o < r.length; o++) s(r[o]);
  45. return s
  46. })({
  47. 1: [function(_dereq_, module, exports) {
  48. (function(global) {;
  49. (function(root) {
  50. var freeExports = typeof exports == 'object' && exports;
  51. var freeModule = typeof module == 'object' && module && module.exports == freeExports && module;
  52. var freeGlobal = typeof global == 'object' && global;
  53. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  54. root = freeGlobal
  55. }
  56. var punycode, maxInt = 2147483647,
  57. base = 36,
  58. tMin = 1,
  59. tMax = 26,
  60. skew = 38,
  61. damp = 700,
  62. initialBias = 72,
  63. initialN = 128,
  64. delimiter = '-',
  65. regexPunycode = /^xn--/,
  66. regexNonASCII = /[^ -~]/,
  67. regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g,
  68. errors = {
  69. 'overflow': 'Overflow: input needs wider integers to process',
  70. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  71. 'invalid-input': 'Invalid input'
  72. },
  73. baseMinusTMin = base - tMin,
  74. floor = Math.floor,
  75. stringFromCharCode = String.fromCharCode,
  76. key;
  77.  
  78. function error(type) {
  79. throw RangeError(errors[type]);
  80. }
  81. function map(array, fn) {
  82. var length = array.length;
  83. while (length--) {
  84. array[length] = fn(array[length])
  85. }
  86. return array
  87. }
  88. function mapDomain(string, fn) {
  89. return map(string.split(regexSeparators), fn).join('.')
  90. }
  91. function ucs2decode(string) {
  92. var output = [],
  93. counter = 0,
  94. length = string.length,
  95. value, extra;
  96. while (counter < length) {
  97. value = string.charCodeAt(counter++);
  98. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  99. extra = string.charCodeAt(counter++);
  100. if ((extra & 0xFC00) == 0xDC00) {
  101. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000)
  102. } else {
  103. output.push(value);
  104. counter--
  105. }
  106. } else {
  107. output.push(value)
  108. }
  109. }
  110. return output
  111. }
  112. function ucs2encode(array) {
  113. return map(array, function(value) {
  114. var output = '';
  115. if (value > 0xFFFF) {
  116. value -= 0x10000;
  117. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  118. value = 0xDC00 | value & 0x3FF
  119. }
  120. output += stringFromCharCode(value);
  121. return output
  122. }).join('')
  123. }
  124. function basicToDigit(codePoint) {
  125. if (codePoint - 48 < 10) {
  126. return codePoint - 22
  127. }
  128. if (codePoint - 65 < 26) {
  129. return codePoint - 65
  130. }
  131. if (codePoint - 97 < 26) {
  132. return codePoint - 97
  133. }
  134. return base
  135. }
  136. function digitToBasic(digit, flag) {
  137. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5)
  138. }
  139. function adapt(delta, numPoints, firstTime) {
  140. var k = 0;
  141. delta = firstTime ? floor(delta / damp) : delta >> 1;
  142. delta += floor(delta / numPoints);
  143. for (; delta > baseMinusTMin * tMax >> 1; k += base) {
  144. delta = floor(delta / baseMinusTMin)
  145. }
  146. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew))
  147. }
  148. function decode(input) {
  149. var output = [],
  150. inputLength = input.length,
  151. out, i = 0,
  152. n = initialN,
  153. bias = initialBias,
  154. basic, j, index, oldi, w, k, digit, t, baseMinusT;
  155. basic = input.lastIndexOf(delimiter);
  156. if (basic < 0) {
  157. basic = 0
  158. }
  159. for (j = 0; j < basic; ++j) {
  160. if (input.charCodeAt(j) >= 0x80) {
  161. error('not-basic')
  162. }
  163. output.push(input.charCodeAt(j))
  164. }
  165. for (index = basic > 0 ? basic + 1 : 0; index < inputLength;) {
  166. for (oldi = i, w = 1, k = base; k += base) {
  167. if (index >= inputLength) {
  168. error('invalid-input')
  169. }
  170. digit = basicToDigit(input.charCodeAt(index++));
  171. if (digit >= base || digit > floor((maxInt - i) / w)) {
  172. error('overflow')
  173. }
  174. i += digit * w;
  175. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  176. if (digit < t) {
  177. break
  178. }
  179. baseMinusT = base - t;
  180. if (w > floor(maxInt / baseMinusT)) {
  181. error('overflow')
  182. }
  183. w *= baseMinusT
  184. }
  185. out = output.length + 1;
  186. bias = adapt(i - oldi, out, oldi == 0);
  187. if (floor(i / out) > maxInt - n) {
  188. error('overflow')
  189. }
  190. n += floor(i / out);
  191. i %= out;
  192. output.splice(i++, 0, n)
  193. }
  194. return ucs2encode(output)
  195. }
  196. function encode(input) {
  197. var n, delta, handledCPCount, basicLength, bias, j, m, q, k, t, currentValue, output = [],
  198. inputLength, handledCPCountPlusOne, baseMinusT, qMinusT;
  199. input = ucs2decode(input);
  200. inputLength = input.length;
  201. n = initialN;
  202. delta = 0;
  203. bias = initialBias;
  204. for (j = 0; j < inputLength; ++j) {
  205. currentValue = input[j];
  206. if (currentValue < 0x80) {
  207. output.push(stringFromCharCode(currentValue))
  208. }
  209. }
  210. handledCPCount = basicLength = output.length;
  211. if (basicLength) {
  212. output.push(delimiter)
  213. }
  214. while (handledCPCount < inputLength) {
  215. for (m = maxInt, j = 0; j < inputLength; ++j) {
  216. currentValue = input[j];
  217. if (currentValue >= n && currentValue < m) {
  218. m = currentValue
  219. }
  220. }
  221. handledCPCountPlusOne = handledCPCount + 1;
  222. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  223. error('overflow')
  224. }
  225. delta += (m - n) * handledCPCountPlusOne;
  226. n = m;
  227. for (j = 0; j < inputLength; ++j) {
  228. currentValue = input[j];
  229. if (currentValue < n && ++delta > maxInt) {
  230. error('overflow')
  231. }
  232. if (currentValue == n) {
  233. for (q = delta, k = base; k += base) {
  234. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  235. if (q < t) {
  236. break
  237. }
  238. qMinusT = q - t;
  239. baseMinusT = base - t;
  240. output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)));
  241. q = floor(qMinusT / baseMinusT)
  242. }
  243. output.push(stringFromCharCode(digitToBasic(q, 0)));
  244. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  245. delta = 0;
  246. ++handledCPCount
  247. }
  248. }++delta;
  249. ++n
  250. }
  251. return output.join('')
  252. }
  253. function toUnicode(domain) {
  254. return mapDomain(domain, function(string) {
  255. return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string
  256. })
  257. }
  258. function toASCII(domain) {
  259. return mapDomain(domain, function(string) {
  260. return regexNonASCII.test(string) ? 'xn--' + encode(string) : string
  261. })
  262. }
  263. punycode = {
  264. 'version': '1.2.4',
  265. 'ucs2': {
  266. 'decode': ucs2decode,
  267. 'encode': ucs2encode
  268. },
  269. 'decode': decode,
  270. 'encode': encode,
  271. 'toASCII': toASCII,
  272. 'toUnicode': toUnicode
  273. };
  274. if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
  275. define('punycode', function() {
  276. return punycode
  277. })
  278. } else if (freeExports && !freeExports.nodeType) {
  279. if (freeModule) {
  280. freeModule.exports = punycode
  281. } else {
  282. for (key in punycode) {
  283. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key])
  284. }
  285. }
  286. } else {
  287. root.punycode = punycode
  288. }
  289. }(this))
  290. }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  291. }, {}],
  292. 2: [function(_dereq_, module, exports) {
  293. var log = _dereq_('./log');
  294.  
  295. function restoreOwnerScroll(ownerDocument, x, y) {
  296. if (ownerDocument.defaultView && (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) {
  297. ownerDocument.defaultView.scrollTo(x, y)
  298. }
  299. }
  300. function cloneCanvasContents(canvas, clonedCanvas) {
  301. try {
  302. if (clonedCanvas) {
  303. clonedCanvas.width = canvas.width;
  304. clonedCanvas.height = canvas.height;
  305. clonedCanvas.getContext("2d").putImageData(canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height), 0, 0)
  306. }
  307. } catch (e) {
  308. log("Unable to copy canvas content from", canvas, e)
  309. }
  310. }
  311. function cloneNode(node, javascriptEnabled) {
  312. var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
  313. var child = node.firstChild;
  314. while (child) {
  315. if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') {
  316. clone.appendChild(cloneNode(child, javascriptEnabled))
  317. }
  318. child = child.nextSibling
  319. }
  320. if (node.nodeType === 1) {
  321. clone._scrollTop = node.scrollTop;
  322. clone._scrollLeft = node.scrollLeft;
  323. if (node.nodeName === "CANVAS") {
  324. cloneCanvasContents(node, clone)
  325. } else if (node.nodeName === "TEXTAREA" || node.nodeName === "SELECT") {
  326. clone.value = node.value
  327. }
  328. }
  329. return clone
  330. }
  331. function initNode(node) {
  332. if (node.nodeType === 1) {
  333. node.scrollTop = node._scrollTop;
  334. node.scrollLeft = node._scrollLeft;
  335. var child = node.firstChild;
  336. while (child) {
  337. initNode(child);
  338. child = child.nextSibling
  339. }
  340. }
  341. }
  342. module.exports = function(ownerDocument, containerDocument, width, height, options, x, y) {
  343. var documentElement = cloneNode(ownerDocument.documentElement, options.javascriptEnabled);
  344. var container = containerDocument.createElement("iframe");
  345. container.className = "html2canvas-container";
  346. container.style.visibility = "hidden";
  347. container.style.position = "fixed";
  348. container.style.left = "-10000px";
  349. container.style.top = "0px";
  350. container.style.border = "0";
  351. container.width = width;
  352. container.height = height;
  353. container.scrolling = "no";
  354. containerDocument.body.appendChild(container);
  355. return new Promise(function(resolve) {
  356. var documentClone = container.contentWindow.document;
  357. container.contentWindow.onload = container.onload = function() {
  358. var interval = setInterval(function() {
  359. if (documentClone.body.childNodes.length > 0) {
  360. initNode(documentClone.documentElement);
  361. clearInterval(interval);
  362. if (options.type === "view") {
  363. container.contentWindow.scrollTo(x, y);
  364. if ((/(iPad|iPhone|iPod)/g).test(navigator.userAgent) && (container.contentWindow.scrollY !== y || container.contentWindow.scrollX !== x)) {
  365. documentClone.documentElement.style.top = (-y) + "px";
  366. documentClone.documentElement.style.left = (-x) + "px";
  367. documentClone.documentElement.style.position = 'absolute'
  368. }
  369. }
  370. resolve(container)
  371. }
  372. }, 50)
  373. };
  374. documentClone.open();
  375. documentClone.write("<!DOCTYPE html><html></html>");
  376. restoreOwnerScroll(ownerDocument, x, y);
  377. documentClone.replaceChild(documentClone.adoptNode(documentElement), documentClone.documentElement);
  378. documentClone.close()
  379. })
  380. }
  381. }, {
  382. "./log": 13
  383. }],
  384. 3: [function(_dereq_, module, exports) {
  385. function Color(value) {
  386. this.r = 0;
  387. this.g = 0;
  388. this.b = 0;
  389. this.a = null;
  390. var result = this.fromArray(value) || this.namedColor(value) || this.rgb(value) || this.rgba(value) || this.hex6(value) || this.hex3(value)
  391. }
  392. Color.prototype.darken = function(amount) {
  393. var a = 1 - amount;
  394. return new Color([Math.round(this.r * a), Math.round(this.g * a), Math.round(this.b * a), this.a])
  395. };
  396. Color.prototype.isTransparent = function() {
  397. return this.a === 0
  398. };
  399. Color.prototype.isBlack = function() {
  400. return this.r === 0 && this.g === 0 && this.b === 0
  401. };
  402. Color.prototype.fromArray = function(array) {
  403. if (Array.isArray(array)) {
  404. this.r = Math.min(array[0], 255);
  405. this.g = Math.min(array[1], 255);
  406. this.b = Math.min(array[2], 255);
  407. if (array.length > 3) {
  408. this.a = array[3]
  409. }
  410. }
  411. return (Array.isArray(array))
  412. };
  413. var _hex3 = /^#([a-f0-9]{3})$/i;
  414. Color.prototype.hex3 = function(value) {
  415. var match = null;
  416. if ((match = value.match(_hex3)) !== null) {
  417. this.r = parseInt(match[1][0] + match[1][0], 16);
  418. this.g = parseInt(match[1][1] + match[1][1], 16);
  419. this.b = parseInt(match[1][2] + match[1][2], 16)
  420. }
  421. return match !== null
  422. };
  423. var _hex6 = /^#([a-f0-9]{6})$/i;
  424. Color.prototype.hex6 = function(value) {
  425. var match = null;
  426. if ((match = value.match(_hex6)) !== null) {
  427. this.r = parseInt(match[1].substring(0, 2), 16);
  428. this.g = parseInt(match[1].substring(2, 4), 16);
  429. this.b = parseInt(match[1].substring(4, 6), 16)
  430. }
  431. return match !== null
  432. };
  433. var _rgb = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/;
  434. Color.prototype.rgb = function(value) {
  435. var match = null;
  436. if ((match = value.match(_rgb)) !== null) {
  437. this.r = Number(match[1]);
  438. this.g = Number(match[2]);
  439. this.b = Number(match[3])
  440. }
  441. return match !== null
  442. };
  443. var _rgba = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d?\.?\d+)\s*\)$/;
  444. Color.prototype.rgba = function(value) {
  445. var match = null;
  446. if ((match = value.match(_rgba)) !== null) {
  447. this.r = Number(match[1]);
  448. this.g = Number(match[2]);
  449. this.b = Number(match[3]);
  450. this.a = Number(match[4])
  451. }
  452. return match !== null
  453. };
  454. Color.prototype.toString = function() {
  455. return this.a !== null && this.a !== 1 ? "rgba(" + [this.r, this.g, this.b, this.a].join(",") + ")" : "rgb(" + [this.r, this.g, this.b].join(",") + ")"
  456. };
  457. Color.prototype.namedColor = function(value) {
  458. value = value.toLowerCase();
  459. var color = colors[value];
  460. if (color) {
  461. this.r = color[0];
  462. this.g = color[1];
  463. this.b = color[2]
  464. } else if (value === "transparent") {
  465. this.r = this.g = this.b = this.a = 0;
  466. return true
  467. }
  468. return !!color
  469. };
  470. Color.prototype.isColor = true;
  471. var colors = {
  472. "aliceblue": [240, 248, 255],
  473. "antiquewhite": [250, 235, 215],
  474. "aqua": [0, 255, 255],
  475. "aquamarine": [127, 255, 212],
  476. "azure": [240, 255, 255],
  477. "beige": [245, 245, 220],
  478. "bisque": [255, 228, 196],
  479. "black": [0, 0, 0],
  480. "blanchedalmond": [255, 235, 205],
  481. "blue": [0, 0, 255],
  482. "blueviolet": [138, 43, 226],
  483. "brown": [165, 42, 42],
  484. "burlywood": [222, 184, 135],
  485. "cadetblue": [95, 158, 160],
  486. "chartreuse": [127, 255, 0],
  487. "chocolate": [210, 105, 30],
  488. "coral": [255, 127, 80],
  489. "cornflowerblue": [100, 149, 237],
  490. "cornsilk": [255, 248, 220],
  491. "crimson": [220, 20, 60],
  492. "cyan": [0, 255, 255],
  493. "darkblue": [0, 0, 139],
  494. "darkcyan": [0, 139, 139],
  495. "darkgoldenrod": [184, 134, 11],
  496. "darkgray": [169, 169, 169],
  497. "darkgreen": [0, 100, 0],
  498. "darkgrey": [169, 169, 169],
  499. "darkkhaki": [189, 183, 107],
  500. "darkmagenta": [139, 0, 139],
  501. "darkolivegreen": [85, 107, 47],
  502. "darkorange": [255, 140, 0],
  503. "darkorchid": [153, 50, 204],
  504. "darkred": [139, 0, 0],
  505. "darksalmon": [233, 150, 122],
  506. "darkseagreen": [143, 188, 143],
  507. "darkslateblue": [72, 61, 139],
  508. "darkslategray": [47, 79, 79],
  509. "darkslategrey": [47, 79, 79],
  510. "darkturquoise": [0, 206, 209],
  511. "darkviolet": [148, 0, 211],
  512. "deeppink": [255, 20, 147],
  513. "deepskyblue": [0, 191, 255],
  514. "dimgray": [105, 105, 105],
  515. "dimgrey": [105, 105, 105],
  516. "dodgerblue": [30, 144, 255],
  517. "firebrick": [178, 34, 34],
  518. "floralwhite": [255, 250, 240],
  519. "forestgreen": [34, 139, 34],
  520. "fuchsia": [255, 0, 255],
  521. "gainsboro": [220, 220, 220],
  522. "ghostwhite": [248, 248, 255],
  523. "gold": [255, 215, 0],
  524. "goldenrod": [218, 165, 32],
  525. "gray": [128, 128, 128],
  526. "green": [0, 128, 0],
  527. "greenyellow": [173, 255, 47],
  528. "grey": [128, 128, 128],
  529. "honeydew": [240, 255, 240],
  530. "hotpink": [255, 105, 180],
  531. "indianred": [205, 92, 92],
  532. "indigo": [75, 0, 130],
  533. "ivory": [255, 255, 240],
  534. "khaki": [240, 230, 140],
  535. "lavender": [230, 230, 250],
  536. "lavenderblush": [255, 240, 245],
  537. "lawngreen": [124, 252, 0],
  538. "lemonchiffon": [255, 250, 205],
  539. "lightblue": [173, 216, 230],
  540. "lightcoral": [240, 128, 128],
  541. "lightcyan": [224, 255, 255],
  542. "lightgoldenrodyellow": [250, 250, 210],
  543. "lightgray": [211, 211, 211],
  544. "lightgreen": [144, 238, 144],
  545. "lightgrey": [211, 211, 211],
  546. "lightpink": [255, 182, 193],
  547. "lightsalmon": [255, 160, 122],
  548. "lightseagreen": [32, 178, 170],
  549. "lightskyblue": [135, 206, 250],
  550. "lightslategray": [119, 136, 153],
  551. "lightslategrey": [119, 136, 153],
  552. "lightsteelblue": [176, 196, 222],
  553. "lightyellow": [255, 255, 224],
  554. "lime": [0, 255, 0],
  555. "limegreen": [50, 205, 50],
  556. "linen": [250, 240, 230],
  557. "magenta": [255, 0, 255],
  558. "maroon": [128, 0, 0],
  559. "mediumaquamarine": [102, 205, 170],
  560. "mediumblue": [0, 0, 205],
  561. "mediumorchid": [186, 85, 211],
  562. "mediumpurple": [147, 112, 219],
  563. "mediumseagreen": [60, 179, 113],
  564. "mediumslateblue": [123, 104, 238],
  565. "mediumspringgreen": [0, 250, 154],
  566. "mediumturquoise": [72, 209, 204],
  567. "mediumvioletred": [199, 21, 133],
  568. "midnightblue": [25, 25, 112],
  569. "mintcream": [245, 255, 250],
  570. "mistyrose": [255, 228, 225],
  571. "moccasin": [255, 228, 181],
  572. "navajowhite": [255, 222, 173],
  573. "navy": [0, 0, 128],
  574. "oldlace": [253, 245, 230],
  575. "olive": [128, 128, 0],
  576. "olivedrab": [107, 142, 35],
  577. "orange": [255, 165, 0],
  578. "orangered": [255, 69, 0],
  579. "orchid": [218, 112, 214],
  580. "palegoldenrod": [238, 232, 170],
  581. "palegreen": [152, 251, 152],
  582. "paleturquoise": [175, 238, 238],
  583. "palevioletred": [219, 112, 147],
  584. "papayawhip": [255, 239, 213],
  585. "peachpuff": [255, 218, 185],
  586. "peru": [205, 133, 63],
  587. "pink": [255, 192, 203],
  588. "plum": [221, 160, 221],
  589. "powderblue": [176, 224, 230],
  590. "purple": [128, 0, 128],
  591. "rebeccapurple": [102, 51, 153],
  592. "red": [255, 0, 0],
  593. "rosybrown": [188, 143, 143],
  594. "royalblue": [65, 105, 225],
  595. "saddlebrown": [139, 69, 19],
  596. "salmon": [250, 128, 114],
  597. "sandybrown": [244, 164, 96],
  598. "seagreen": [46, 139, 87],
  599. "seashell": [255, 245, 238],
  600. "sienna": [160, 82, 45],
  601. "silver": [192, 192, 192],
  602. "skyblue": [135, 206, 235],
  603. "slateblue": [106, 90, 205],
  604. "slategray": [112, 128, 144],
  605. "slategrey": [112, 128, 144],
  606. "snow": [255, 250, 250],
  607. "springgreen": [0, 255, 127],
  608. "steelblue": [70, 130, 180],
  609. "tan": [210, 180, 140],
  610. "teal": [0, 128, 128],
  611. "thistle": [216, 191, 216],
  612. "tomato": [255, 99, 71],
  613. "turquoise": [64, 224, 208],
  614. "violet": [238, 130, 238],
  615. "wheat": [245, 222, 179],
  616. "white": [255, 255, 255],
  617. "whitesmoke": [245, 245, 245],
  618. "yellow": [255, 255, 0],
  619. "yellowgreen": [154, 205, 50]
  620. };
  621. module.exports = Color
  622. }, {}],
  623. 4: [function(_dereq_, module, exports) {
  624. var Support = _dereq_('./support');
  625. var CanvasRenderer = _dereq_('./renderers/canvas');
  626. var ImageLoader = _dereq_('./imageloader');
  627. var NodeParser = _dereq_('./nodeparser');
  628. var NodeContainer = _dereq_('./nodecontainer');
  629. var log = _dereq_('./log');
  630. var utils = _dereq_('./utils');
  631. var createWindowClone = _dereq_('./clone');
  632. var loadUrlDocument = _dereq_('./proxy').loadUrlDocument;
  633. var getBounds = utils.getBounds;
  634. var html2canvasNodeAttribute = "data-html2canvas-node";
  635. var html2canvasCloneIndex = 0;
  636.  
  637. function html2canvas(nodeList, options) {
  638. var index = html2canvasCloneIndex++;
  639. options = options || {};
  640. if (options.logging) {
  641. log.options.logging = true;
  642. log.options.start = Date.now()
  643. }
  644. options.async = typeof(options.async) === "undefined" ? true : options.async;
  645. options.allowTaint = typeof(options.allowTaint) === "undefined" ? false : options.allowTaint;
  646. options.removeContainer = typeof(options.removeContainer) === "undefined" ? true : options.removeContainer;
  647. options.javascriptEnabled = typeof(options.javascriptEnabled) === "undefined" ? false : options.javascriptEnabled;
  648. options.imageTimeout = typeof(options.imageTimeout) === "undefined" ? 10000 : options.imageTimeout;
  649. options.renderer = typeof(options.renderer) === "function" ? options.renderer : CanvasRenderer;
  650. options.strict = !! options.strict;
  651. if (typeof(nodeList) === "string") {
  652. if (typeof(options.proxy) !== "string") {
  653. return Promise.reject("Proxy must be used when rendering url")
  654. }
  655. var width = options.width != null ? options.width : window.innerWidth;
  656. var height = options.height != null ? options.height : window.innerHeight;
  657. return loadUrlDocument(absoluteUrl(nodeList), options.proxy, document, width, height, options).then(function(container) {
  658. return renderWindow(container.contentWindow.document.documentElement, container, options, width, height)
  659. })
  660. }
  661. var node = ((nodeList === undefined) ? [document.documentElement] : ((nodeList.length) ? nodeList : [nodeList]))[0];
  662. node.setAttribute(html2canvasNodeAttribute + index, index);
  663. return renderDocument(node.ownerDocument, options, node.ownerDocument.defaultView.innerWidth, node.ownerDocument.defaultView.innerHeight, index).then(function(canvas) {
  664. if (typeof(options.onrendered) === "function") {
  665. log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas");
  666. options.onrendered(canvas)
  667. }
  668. return canvas
  669. })
  670. }
  671. html2canvas.CanvasRenderer = CanvasRenderer;
  672. html2canvas.NodeContainer = NodeContainer;
  673. html2canvas.log = log;
  674. html2canvas.utils = utils;
  675. var html2canvasExport = (typeof(document) === "undefined" || typeof(Object.create) !== "function" || typeof(document.createElement("canvas").getContext) !== "function") ?
  676. function() {
  677. return Promise.reject("No canvas support")
  678. } : html2canvas;
  679. module.exports = html2canvasExport;
  680. if (typeof(define) === 'function' && define.amd) {
  681. define('html2canvas', [], function() {
  682. return html2canvasExport
  683. })
  684. }
  685. function renderDocument(document, options, windowWidth, windowHeight, html2canvasIndex) {
  686. return createWindowClone(document, document, windowWidth, windowHeight, options, document.defaultView.pageXOffset, document.defaultView.pageYOffset).then(function(container) {
  687. log("Document cloned");
  688. var attributeName = html2canvasNodeAttribute + html2canvasIndex;
  689. var selector = "[" + attributeName + "='" + html2canvasIndex + "']";
  690. document.querySelector(selector).removeAttribute(attributeName);
  691. var clonedWindow = container.contentWindow;
  692. var node = clonedWindow.document.querySelector(selector);
  693. var oncloneHandler = (typeof(options.onclone) === "function") ? Promise.resolve(options.onclone(clonedWindow.document)) : Promise.resolve(true);
  694. return oncloneHandler.then(function() {
  695. return renderWindow(node, container, options, windowWidth, windowHeight)
  696. })
  697. })
  698. }
  699. function renderWindow(node, container, options, windowWidth, windowHeight) {
  700. var clonedWindow = container.contentWindow;
  701. var support = new Support(clonedWindow.document);
  702. var imageLoader = new ImageLoader(options, support);
  703. var bounds = getBounds(node);
  704. var width = options.type === "view" ? windowWidth : documentWidth(clonedWindow.document);
  705. var height = options.type === "view" ? windowHeight : documentHeight(clonedWindow.document);
  706. var renderer = new options.renderer(width, height, imageLoader, options, document);
  707. var parser = new NodeParser(node, renderer, support, imageLoader, options);
  708. return parser.ready.then(function() {
  709. log("Finished rendering");
  710. var canvas;
  711. if (options.type === "view") {
  712. canvas = crop(renderer.canvas, {
  713. width: renderer.canvas.width,
  714. height: renderer.canvas.height,
  715. top: 0,
  716. left: 0,
  717. x: 0,
  718. y: 0
  719. })
  720. } else if (node === clonedWindow.document.body || node === clonedWindow.document.documentElement || options.canvas != null) {
  721. canvas = renderer.canvas
  722. } else {
  723. canvas = crop(renderer.canvas, {
  724. width: options.width != null ? options.width : bounds.width,
  725. height: options.height != null ? options.height : bounds.height,
  726. top: bounds.top,
  727. left: bounds.left,
  728. x: 0,
  729. y: 0
  730. })
  731. }
  732. cleanupContainer(container, options);
  733. return canvas
  734. })
  735. }
  736. function cleanupContainer(container, options) {
  737. if (options.removeContainer) {
  738. container.parentNode.removeChild(container);
  739. log("Cleaned up container")
  740. }
  741. }
  742. function crop(canvas, bounds) {
  743. var croppedCanvas = document.createElement("canvas");
  744. var x1 = Math.min(canvas.width - 1, Math.max(0, bounds.left));
  745. var x2 = Math.min(canvas.width, Math.max(1, bounds.left + bounds.width));
  746. var y1 = Math.min(canvas.height - 1, Math.max(0, bounds.top));
  747. var y2 = Math.min(canvas.height, Math.max(1, bounds.top + bounds.height));
  748. croppedCanvas.width = bounds.width;
  749. croppedCanvas.height = bounds.height;
  750. var width = x2 - x1;
  751. var height = y2 - y1;
  752. log("Cropping canvas at:", "left:", bounds.left, "top:", bounds.top, "width:", width, "height:", height);
  753. log("Resulting crop with width", bounds.width, "and height", bounds.height, "with x", x1, "and y", y1);
  754. croppedCanvas.getContext("2d").drawImage(canvas, x1, y1, width, height, bounds.x, bounds.y, width, height);
  755. return croppedCanvas
  756. }
  757. function documentWidth(doc) {
  758. return Math.max(Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth), Math.max(doc.body.offsetWidth, doc.documentElement.offsetWidth), Math.max(doc.body.clientWidth, doc.documentElement.clientWidth))
  759. }
  760. function documentHeight(doc) {
  761. return Math.max(Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight), Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight), Math.max(doc.body.clientHeight, doc.documentElement.clientHeight))
  762. }
  763. function absoluteUrl(url) {
  764. var link = document.createElement("a");
  765. link.href = url;
  766. link.href = link.href;
  767. return link
  768. }
  769. }, {
  770. "./clone": 2,
  771. "./imageloader": 11,
  772. "./log": 13,
  773. "./nodecontainer": 14,
  774. "./nodeparser": 15,
  775. "./proxy": 16,
  776. "./renderers/canvas": 20,
  777. "./support": 22,
  778. "./utils": 26
  779. }],
  780. 5: [function(_dereq_, module, exports) {
  781. var log = _dereq_('./log');
  782. var smallImage = _dereq_('./utils').smallImage;
  783.  
  784. function DummyImageContainer(src) {
  785. this.src = src;
  786. log("DummyImageContainer for", src);
  787. if (!this.promise || !this.image) {
  788. log("Initiating DummyImageContainer");
  789. DummyImageContainer.prototype.image = new Image();
  790. var image = this.image;
  791. DummyImageContainer.prototype.promise = new Promise(function(resolve, reject) {
  792. image.onload = resolve;
  793. image.onerror = reject;
  794. image.src = smallImage();
  795. if (image.complete === true) {
  796. resolve(image)
  797. }
  798. })
  799. }
  800. }
  801. module.exports = DummyImageContainer
  802. }, {
  803. "./log": 13,
  804. "./utils": 26
  805. }],
  806. 6: [function(_dereq_, module, exports) {
  807. var smallImage = _dereq_('./utils').smallImage;
  808.  
  809. function Font(family, size) {
  810. var container = document.createElement('div'),
  811. img = document.createElement('img'),
  812. span = document.createElement('span'),
  813. sampleText = 'Hidden Text',
  814. baseline, middle;
  815. container.style.visibility = "hidden";
  816. container.style.fontFamily = family;
  817. container.style.fontSize = size;
  818. container.style.margin = 0;
  819. container.style.padding = 0;
  820. document.body.appendChild(container);
  821. img.src = smallImage();
  822. img.width = 1;
  823. img.height = 1;
  824. img.style.margin = 0;
  825. img.style.padding = 0;
  826. img.style.verticalAlign = "baseline";
  827. span.style.fontFamily = family;
  828. span.style.fontSize = size;
  829. span.style.margin = 0;
  830. span.style.padding = 0;
  831. span.appendChild(document.createTextNode(sampleText));
  832. container.appendChild(span);
  833. container.appendChild(img);
  834. baseline = (img.offsetTop - span.offsetTop) + 1;
  835. container.removeChild(span);
  836. container.appendChild(document.createTextNode(sampleText));
  837. container.style.lineHeight = "normal";
  838. img.style.verticalAlign = "super";
  839. middle = (img.offsetTop - container.offsetTop) + 1;
  840. document.body.removeChild(container);
  841. this.baseline = baseline;
  842. this.lineWidth = 1;
  843. this.middle = middle
  844. }
  845. module.exports = Font
  846. }, {
  847. "./utils": 26
  848. }],
  849. 7: [function(_dereq_, module, exports) {
  850. var Font = _dereq_('./font');
  851.  
  852. function FontMetrics() {
  853. this.data = {}
  854. }
  855. FontMetrics.prototype.getMetrics = function(family, size) {
  856. if (this.data[family + "-" + size] === undefined) {
  857. this.data[family + "-" + size] = new Font(family, size)
  858. }
  859. return this.data[family + "-" + size]
  860. };
  861. module.exports = FontMetrics
  862. }, {
  863. "./font": 6
  864. }],
  865. 8: [function(_dereq_, module, exports) {
  866. var utils = _dereq_('./utils');
  867. var getBounds = utils.getBounds;
  868. var loadUrlDocument = _dereq_('./proxy').loadUrlDocument;
  869.  
  870. function FrameContainer(container, sameOrigin, options) {
  871. this.image = null;
  872. this.src = container;
  873. var self = this;
  874. var bounds = getBounds(container);
  875. this.promise = (!sameOrigin ? this.proxyLoad(options.proxy, bounds, options) : new Promise(function(resolve) {
  876. if (container.contentWindow.document.URL === "about:blank" || container.contentWindow.document.documentElement == null) {
  877. container.contentWindow.onload = container.onload = function() {
  878. resolve(container)
  879. }
  880. } else {
  881. resolve(container)
  882. }
  883. })).then(function(container) {
  884. var html2canvas = _dereq_('./core');
  885. return html2canvas(container.contentWindow.document.documentElement, {
  886. type: 'view',
  887. width: container.width,
  888. height: container.height,
  889. proxy: options.proxy,
  890. javascriptEnabled: options.javascriptEnabled,
  891. removeContainer: options.removeContainer,
  892. allowTaint: options.allowTaint,
  893. imageTimeout: options.imageTimeout / 2
  894. })
  895. }).then(function(canvas) {
  896. return self.image = canvas
  897. })
  898. }
  899. FrameContainer.prototype.proxyLoad = function(proxy, bounds, options) {
  900. var container = this.src;
  901. return loadUrlDocument(container.src, proxy, container.ownerDocument, bounds.width, bounds.height, options)
  902. };
  903. module.exports = FrameContainer
  904. }, {
  905. "./core": 4,
  906. "./proxy": 16,
  907. "./utils": 26
  908. }],
  909. 9: [function(_dereq_, module, exports) {
  910. function GradientContainer(imageData) {
  911. this.src = imageData.value;
  912. this.colorStops = [];
  913. this.type = null;
  914. this.x0 = 0.5;
  915. this.y0 = 0.5;
  916. this.x1 = 0.5;
  917. this.y1 = 0.5;
  918. this.promise = Promise.resolve(true)
  919. }
  920. GradientContainer.TYPES = {
  921. LINEAR: 1,
  922. RADIAL: 2
  923. };
  924. GradientContainer.REGEXP_COLORSTOP = /^\s*(rgba?\(\s*\d{1,3},\s*\d{1,3},\s*\d{1,3}(?:,\s*[0-9\.]+)?\s*\)|[a-z]{3,20}|#[a-f0-9]{3,6})(?:\s+(\d{1,3}(?:\.\d+)?)(%|px)?)?(?:\s|$)/i;
  925. module.exports = GradientContainer
  926. }, {}],
  927. 10: [function(_dereq_, module, exports) {
  928. function ImageContainer(src, cors) {
  929. this.src = src;
  930. this.image = new Image();
  931. var self = this;
  932. this.tainted = null;
  933. this.promise = new Promise(function(resolve, reject) {
  934. self.image.onload = resolve;
  935. self.image.onerror = reject;
  936. if (cors) {
  937. self.image.crossOrigin = "anonymous"
  938. }
  939. self.image.src = src;
  940. if (self.image.complete === true) {
  941. resolve(self.image)
  942. }
  943. })
  944. }
  945. module.exports = ImageContainer
  946. }, {}],
  947. 11: [function(_dereq_, module, exports) {
  948. var log = _dereq_('./log');
  949. var ImageContainer = _dereq_('./imagecontainer');
  950. var DummyImageContainer = _dereq_('./dummyimagecontainer');
  951. var ProxyImageContainer = _dereq_('./proxyimagecontainer');
  952. var FrameContainer = _dereq_('./framecontainer');
  953. var SVGContainer = _dereq_('./svgcontainer');
  954. var SVGNodeContainer = _dereq_('./svgnodecontainer');
  955. var LinearGradientContainer = _dereq_('./lineargradientcontainer');
  956. var WebkitGradientContainer = _dereq_('./webkitgradientcontainer');
  957. var bind = _dereq_('./utils').bind;
  958.  
  959. function ImageLoader(options, support) {
  960. this.link = null;
  961. this.options = options;
  962. this.support = support;
  963. this.origin = this.getOrigin(window.location.href)
  964. }
  965. ImageLoader.prototype.findImages = function(nodes) {
  966. var images = [];
  967. nodes.reduce(function(imageNodes, container) {
  968. switch (container.node.nodeName) {
  969. case "IMG":
  970. return imageNodes.concat([{
  971. args: [container.node.src],
  972. method: "url"
  973. }]);
  974. case "svg":
  975. case "IFRAME":
  976. return imageNodes.concat([{
  977. args: [container.node],
  978. method: container.node.nodeName
  979. }])
  980. }
  981. return imageNodes
  982. }, []).forEach(this.addImage(images, this.loadImage), this);
  983. return images
  984. };
  985. ImageLoader.prototype.findBackgroundImage = function(images, container) {
  986. container.parseBackgroundImages().filter(this.hasImageBackground).forEach(this.addImage(images, this.loadImage), this);
  987. return images
  988. };
  989. ImageLoader.prototype.addImage = function(images, callback) {
  990. return function(newImage) {
  991. newImage.args.forEach(function(image) {
  992. if (!this.imageExists(images, image)) {
  993. images.splice(0, 0, callback.call(this, newImage));
  994. log('Added image #' + (images.length), typeof(image) === "string" ? image.substring(0, 100) : image)
  995. }
  996. }, this)
  997. }
  998. };
  999. ImageLoader.prototype.hasImageBackground = function(imageData) {
  1000. return imageData.method !== "none"
  1001. };
  1002. ImageLoader.prototype.loadImage = function(imageData) {
  1003. if (imageData.method === "url") {
  1004. var src = imageData.args[0];
  1005. if (this.isSVG(src) && !this.support.svg && !this.options.allowTaint) {
  1006. return new SVGContainer(src)
  1007. } else if (src.match(/data:image\/.*;base64,/i)) {
  1008. return new ImageContainer(src.replace(/url\(['"]{0,}|['"]{0,}\)$/ig, ''), false)
  1009. } else if (this.isSameOrigin(src) || this.options.allowTaint === true || this.isSVG(src)) {
  1010. return new ImageContainer(src, false)
  1011. } else if (this.support.cors && !this.options.allowTaint && this.options.useCORS) {
  1012. return new ImageContainer(src, true)
  1013. } else if (this.options.proxy) {
  1014. return new ProxyImageContainer(src, this.options.proxy)
  1015. } else {
  1016. return new DummyImageContainer(src)
  1017. }
  1018. } else if (imageData.method === "linear-gradient") {
  1019. return new LinearGradientContainer(imageData)
  1020. } else if (imageData.method === "gradient") {
  1021. return new WebkitGradientContainer(imageData)
  1022. } else if (imageData.method === "svg") {
  1023. return new SVGNodeContainer(imageData.args[0], this.support.svg)
  1024. } else if (imageData.method === "IFRAME") {
  1025. return new FrameContainer(imageData.args[0], this.isSameOrigin(imageData.args[0].src), this.options)
  1026. } else {
  1027. return new DummyImageContainer(imageData)
  1028. }
  1029. };
  1030. ImageLoader.prototype.isSVG = function(src) {
  1031. return src.substring(src.length - 3).toLowerCase() === "svg" || SVGContainer.prototype.isInline(src)
  1032. };
  1033. ImageLoader.prototype.imageExists = function(images, src) {
  1034. return images.some(function(image) {
  1035. return image.src === src
  1036. })
  1037. };
  1038. ImageLoader.prototype.isSameOrigin = function(url) {
  1039. return (this.getOrigin(url) === this.origin)
  1040. };
  1041. ImageLoader.prototype.getOrigin = function(url) {
  1042. var link = this.link || (this.link = document.createElement("a"));
  1043. link.href = url;
  1044. link.href = link.href;
  1045. return link.protocol + link.hostname + link.port
  1046. };
  1047. ImageLoader.prototype.getPromise = function(container) {
  1048. return this.timeout(container, this.options.imageTimeout)['catch'](function() {
  1049. var dummy = new DummyImageContainer(container.src);
  1050. return dummy.promise.then(function(image) {
  1051. container.image = image
  1052. })
  1053. })
  1054. };
  1055. ImageLoader.prototype.get = function(src) {
  1056. var found = null;
  1057. return this.images.some(function(img) {
  1058. return (found = img).src === src
  1059. }) ? found : null
  1060. };
  1061. ImageLoader.prototype.fetch = function(nodes) {
  1062. this.images = nodes.reduce(bind(this.findBackgroundImage, this), this.findImages(nodes));
  1063. this.images.forEach(function(image, index) {
  1064. image.promise.then(function() {
  1065. log("Succesfully loaded image #" + (index + 1), image)
  1066. }, function(e) {
  1067. log("Failed loading image #" + (index + 1), image, e)
  1068. })
  1069. });
  1070. this.ready = Promise.all(this.images.map(this.getPromise, this));
  1071. log("Finished searching images");
  1072. return this
  1073. };
  1074. ImageLoader.prototype.timeout = function(container, timeout) {
  1075. var timer;
  1076. var promise = Promise.race([container.promise, new Promise(function(res, reject) {
  1077. timer = setTimeout(function() {
  1078. log("Timed out loading image", container);
  1079. reject(container)
  1080. }, timeout)
  1081. })]).then(function(container) {
  1082. clearTimeout(timer);
  1083. return container
  1084. });
  1085. promise['catch'](function() {
  1086. clearTimeout(timer)
  1087. });
  1088. return promise
  1089. };
  1090. module.exports = ImageLoader
  1091. }, {
  1092. "./dummyimagecontainer": 5,
  1093. "./framecontainer": 8,
  1094. "./imagecontainer": 10,
  1095. "./lineargradientcontainer": 12,
  1096. "./log": 13,
  1097. "./proxyimagecontainer": 17,
  1098. "./svgcontainer": 23,
  1099. "./svgnodecontainer": 24,
  1100. "./utils": 26,
  1101. "./webkitgradientcontainer": 27
  1102. }],
  1103. 12: [function(_dereq_, module, exports) {
  1104. var GradientContainer = _dereq_('./gradientcontainer');
  1105. var Color = _dereq_('./color');
  1106.  
  1107. function LinearGradientContainer(imageData) {
  1108. GradientContainer.apply(this, arguments);
  1109. this.type = GradientContainer.TYPES.LINEAR;
  1110. var hasDirection = LinearGradientContainer.REGEXP_DIRECTION.test(imageData.args[0]) || !GradientContainer.REGEXP_COLORSTOP.test(imageData.args[0]);
  1111. if (hasDirection) {
  1112. imageData.args[0].split(/\s+/).reverse().forEach(function(position, index) {
  1113. switch (position) {
  1114. case "left":
  1115. this.x0 = 0;
  1116. this.x1 = 1;
  1117. break;
  1118. case "top":
  1119. this.y0 = 0;
  1120. this.y1 = 1;
  1121. break;
  1122. case "right":
  1123. this.x0 = 1;
  1124. this.x1 = 0;
  1125. break;
  1126. case "bottom":
  1127. this.y0 = 1;
  1128. this.y1 = 0;
  1129. break;
  1130. case "to":
  1131. var y0 = this.y0;
  1132. var x0 = this.x0;
  1133. this.y0 = this.y1;
  1134. this.x0 = this.x1;
  1135. this.x1 = x0;
  1136. this.y1 = y0;
  1137. break;
  1138. case "center":
  1139. break;
  1140. default:
  1141. var ratio = parseFloat(position, 10) * 1e-2;
  1142. if (isNaN(ratio)) {
  1143. break
  1144. }
  1145. if (index === 0) {
  1146. this.y0 = ratio;
  1147. this.y1 = 1 - this.y0
  1148. } else {
  1149. this.x0 = ratio;
  1150. this.x1 = 1 - this.x0
  1151. }
  1152. break
  1153. }
  1154. }, this)
  1155. } else {
  1156. this.y0 = 0;
  1157. this.y1 = 1
  1158. }
  1159. this.colorStops = imageData.args.slice(hasDirection ? 1 : 0).map(function(colorStop) {
  1160. var colorStopMatch = colorStop.match(GradientContainer.REGEXP_COLORSTOP);
  1161. var value = +colorStopMatch[2];
  1162. var unit = value === 0 ? "%" : colorStopMatch[3];
  1163. return {
  1164. color: new Color(colorStopMatch[1]),
  1165. stop: unit === "%" ? value / 100 : null
  1166. }
  1167. });
  1168. if (this.colorStops[0].stop === null) {
  1169. this.colorStops[0].stop = 0
  1170. }
  1171. if (this.colorStops[this.colorStops.length - 1].stop === null) {
  1172. this.colorStops[this.colorStops.length - 1].stop = 1
  1173. }
  1174. this.colorStops.forEach(function(colorStop, index) {
  1175. if (colorStop.stop === null) {
  1176. this.colorStops.slice(index).some(function(find, count) {
  1177. if (find.stop !== null) {
  1178. colorStop.stop = ((find.stop - this.colorStops[index - 1].stop) / (count + 1)) + this.colorStops[index - 1].stop;
  1179. return true
  1180. } else {
  1181. return false
  1182. }
  1183. }, this)
  1184. }
  1185. }, this)
  1186. }
  1187. LinearGradientContainer.prototype = Object.create(GradientContainer.prototype);
  1188. LinearGradientContainer.REGEXP_DIRECTION = /^\s*(?:to|left|right|top|bottom|center|\d{1,3}(?:\.\d+)?%?)(?:\s|$)/i;
  1189. module.exports = LinearGradientContainer
  1190. }, {
  1191. "./color": 3,
  1192. "./gradientcontainer": 9
  1193. }],
  1194. 13: [function(_dereq_, module, exports) {
  1195. var logger = function() {
  1196. if (logger.options.logging && window.console && window.console.log) {
  1197. Function.prototype.bind.call(window.console.log, (window.console)).apply(window.console, [(Date.now() - logger.options.start) + "ms", "html2canvas:"].concat([].slice.call(arguments, 0)))
  1198. }
  1199. };
  1200. logger.options = {
  1201. logging: false
  1202. };
  1203. module.exports = logger
  1204. }, {}],
  1205. 14: [function(_dereq_, module, exports) {
  1206. var Color = _dereq_('./color');
  1207. var utils = _dereq_('./utils');
  1208. var getBounds = utils.getBounds;
  1209. var parseBackgrounds = utils.parseBackgrounds;
  1210. var offsetBounds = utils.offsetBounds;
  1211.  
  1212. function NodeContainer(node, parent) {
  1213. this.node = node;
  1214. this.parent = parent;
  1215. this.stack = null;
  1216. this.bounds = null;
  1217. this.borders = null;
  1218. this.clip = [];
  1219. this.backgroundClip = [];
  1220. this.offsetBounds = null;
  1221. this.visible = null;
  1222. this.computedStyles = null;
  1223. this.colors = {};
  1224. this.styles = {};
  1225. this.backgroundImages = null;
  1226. this.transformData = null;
  1227. this.transformMatrix = null;
  1228. this.isPseudoElement = false;
  1229. this.opacity = null
  1230. }
  1231. NodeContainer.prototype.cloneTo = function(stack) {
  1232. stack.visible = this.visible;
  1233. stack.borders = this.borders;
  1234. stack.bounds = this.bounds;
  1235. stack.clip = this.clip;
  1236. stack.backgroundClip = this.backgroundClip;
  1237. stack.computedStyles = this.computedStyles;
  1238. stack.styles = this.styles;
  1239. stack.backgroundImages = this.backgroundImages;
  1240. stack.opacity = this.opacity
  1241. };
  1242. NodeContainer.prototype.getOpacity = function() {
  1243. return this.opacity === null ? (this.opacity = this.cssFloat('opacity')) : this.opacity
  1244. };
  1245. NodeContainer.prototype.assignStack = function(stack) {
  1246. this.stack = stack;
  1247. stack.children.push(this)
  1248. };
  1249. NodeContainer.prototype.isElementVisible = function() {
  1250. return this.node.nodeType === Node.TEXT_NODE ? this.parent.visible : (this.css('display') !== "none" && this.css('visibility') !== "hidden" && !this.node.hasAttribute("data-html2canvas-ignore") && (this.node.nodeName !== "INPUT" || this.node.getAttribute("type") !== "hidden"))
  1251. };
  1252. NodeContainer.prototype.css = function(attribute) {
  1253. if (!this.computedStyles) {
  1254. this.computedStyles = this.isPseudoElement ? this.parent.computedStyle(this.before ? ":before" : ":after") : this.computedStyle(null)
  1255. }
  1256. return this.styles[attribute] || (this.styles[attribute] = this.computedStyles[attribute])
  1257. };
  1258. NodeContainer.prototype.prefixedCss = function(attribute) {
  1259. var prefixes = ["webkit", "moz", "ms", "o"];
  1260. var value = this.css(attribute);
  1261. if (value === undefined) {
  1262. prefixes.some(function(prefix) {
  1263. value = this.css(prefix + attribute.substr(0, 1).toUpperCase() + attribute.substr(1));
  1264. return value !== undefined
  1265. }, this)
  1266. }
  1267. return value === undefined ? null : value
  1268. };
  1269. NodeContainer.prototype.computedStyle = function(type) {
  1270. return this.node.ownerDocument.defaultView.getComputedStyle(this.node, type)
  1271. };
  1272. NodeContainer.prototype.cssInt = function(attribute) {
  1273. var value = parseInt(this.css(attribute), 10);
  1274. return (isNaN(value)) ? 0 : value
  1275. };
  1276. NodeContainer.prototype.color = function(attribute) {
  1277. return this.colors[attribute] || (this.colors[attribute] = new Color(this.css(attribute)))
  1278. };
  1279. NodeContainer.prototype.cssFloat = function(attribute) {
  1280. var value = parseFloat(this.css(attribute));
  1281. return (isNaN(value)) ? 0 : value
  1282. };
  1283. NodeContainer.prototype.fontWeight = function() {
  1284. var weight = this.css("fontWeight");
  1285. switch (parseInt(weight, 10)) {
  1286. case 401:
  1287. weight = "bold";
  1288. break;
  1289. case 400:
  1290. weight = "normal";
  1291. break
  1292. }
  1293. return weight
  1294. };
  1295. NodeContainer.prototype.parseClip = function() {
  1296. var matches = this.css('clip').match(this.CLIP);
  1297. if (matches) {
  1298. return {
  1299. top: parseInt(matches[1], 10),
  1300. right: parseInt(matches[2], 10),
  1301. bottom: parseInt(matches[3], 10),
  1302. left: parseInt(matches[4], 10)
  1303. }
  1304. }
  1305. return null
  1306. };
  1307. NodeContainer.prototype.parseBackgroundImages = function() {
  1308. return this.backgroundImages || (this.backgroundImages = parseBackgrounds(this.css("backgroundImage")))
  1309. };
  1310. NodeContainer.prototype.cssList = function(property, index) {
  1311. var value = (this.css(property) || '').split(',');
  1312. value = value[index || 0] || value[0] || 'auto';
  1313. value = value.trim().split(' ');
  1314. if (value.length === 1) {
  1315. value = [value[0], isPercentage(value[0]) ? 'auto' : value[0]]
  1316. }
  1317. return value
  1318. };
  1319. NodeContainer.prototype.parseBackgroundSize = function(bounds, image, index) {
  1320. var size = this.cssList("backgroundSize", index);
  1321. var width, height;
  1322. if (isPercentage(size[0])) {
  1323. width = bounds.width * parseFloat(size[0]) / 100
  1324. } else if (/contain|cover/.test(size[0])) {
  1325. var targetRatio = bounds.width / bounds.height,
  1326. currentRatio = image.width / image.height;
  1327. return (targetRatio < currentRatio ^ size[0] === 'contain') ? {
  1328. width: bounds.height * currentRatio,
  1329. height: bounds.height
  1330. } : {
  1331. width: bounds.width,
  1332. height: bounds.width / currentRatio
  1333. }
  1334. } else {
  1335. width = parseInt(size[0], 10)
  1336. }
  1337. if (size[0] === 'auto' && size[1] === 'auto') {
  1338. height = image.height
  1339. } else if (size[1] === 'auto') {
  1340. height = width / image.width * image.height
  1341. } else if (isPercentage(size[1])) {
  1342. height = bounds.height * parseFloat(size[1]) / 100
  1343. } else {
  1344. height = parseInt(size[1], 10)
  1345. }
  1346. if (size[0] === 'auto') {
  1347. width = height / image.height * image.width
  1348. }
  1349. return {
  1350. width: width,
  1351. height: height
  1352. }
  1353. };
  1354. NodeContainer.prototype.parseBackgroundPosition = function(bounds, image, index, backgroundSize) {
  1355. var position = this.cssList('backgroundPosition', index);
  1356. var left, top;
  1357. if (isPercentage(position[0])) {
  1358. left = (bounds.width - (backgroundSize || image).width) * (parseFloat(position[0]) / 100)
  1359. } else {
  1360. left = parseInt(position[0], 10)
  1361. }
  1362. if (position[1] === 'auto') {
  1363. top = left / image.width * image.height
  1364. } else if (isPercentage(position[1])) {
  1365. top = (bounds.height - (backgroundSize || image).height) * parseFloat(position[1]) / 100
  1366. } else {
  1367. top = parseInt(position[1], 10)
  1368. }
  1369. if (position[0] === 'auto') {
  1370. left = top / image.height * image.width
  1371. }
  1372. return {
  1373. left: left,
  1374. top: top
  1375. }
  1376. };
  1377. NodeContainer.prototype.parseBackgroundRepeat = function(index) {
  1378. return this.cssList("backgroundRepeat", index)[0]
  1379. };
  1380. NodeContainer.prototype.parseTextShadows = function() {
  1381. var textShadow = this.css("textShadow");
  1382. var results = [];
  1383. if (textShadow && textShadow !== 'none') {
  1384. var shadows = textShadow.match(this.TEXT_SHADOW_PROPERTY);
  1385. for (var i = 0; shadows && (i < shadows.length); i++) {
  1386. var s = shadows[i].match(this.TEXT_SHADOW_VALUES);
  1387. results.push({
  1388. color: new Color(s[0]),
  1389. offsetX: s[1] ? parseFloat(s[1].replace('px', '')) : 0,
  1390. offsetY: s[2] ? parseFloat(s[2].replace('px', '')) : 0,
  1391. blur: s[3] ? s[3].replace('px', '') : 0
  1392. })
  1393. }
  1394. }
  1395. return results
  1396. };
  1397. NodeContainer.prototype.parseTransform = function() {
  1398. if (!this.transformData) {
  1399. if (this.hasTransform()) {
  1400. var offset = this.parseBounds();
  1401. var origin = this.prefixedCss("transformOrigin").split(" ").map(removePx).map(asFloat);
  1402. origin[0] += offset.left;
  1403. origin[1] += offset.top;
  1404. this.transformData = {
  1405. origin: origin,
  1406. matrix: this.parseTransformMatrix()
  1407. }
  1408. } else {
  1409. this.transformData = {
  1410. origin: [0, 0],
  1411. matrix: [1, 0, 0, 1, 0, 0]
  1412. }
  1413. }
  1414. }
  1415. return this.transformData
  1416. };
  1417. NodeContainer.prototype.parseTransformMatrix = function() {
  1418. if (!this.transformMatrix) {
  1419. var transform = this.prefixedCss("transform");
  1420. var matrix = transform ? parseMatrix(transform.match(this.MATRIX_PROPERTY)) : null;
  1421. this.transformMatrix = matrix ? matrix : [1, 0, 0, 1, 0, 0]
  1422. }
  1423. return this.transformMatrix
  1424. };
  1425. NodeContainer.prototype.parseBounds = function() {
  1426. return this.bounds || (this.bounds = this.hasTransform() ? offsetBounds(this.node) : getBounds(this.node))
  1427. };
  1428. NodeContainer.prototype.hasTransform = function() {
  1429. return this.parseTransformMatrix().join(",") !== "1,0,0,1,0,0" || (this.parent && this.parent.hasTransform())
  1430. };
  1431. NodeContainer.prototype.getValue = function() {
  1432. var value = this.node.value || "";
  1433. if (this.node.tagName === "SELECT") {
  1434. value = selectionValue(this.node)
  1435. } else if (this.node.type === "password") {
  1436. value = Array(value.length + 1).join('\u2022')
  1437. }
  1438. return value.length === 0 ? (this.node.placeholder || "") : value
  1439. };
  1440. NodeContainer.prototype.MATRIX_PROPERTY = /(matrix|matrix3d)\((.+)\)/;
  1441. NodeContainer.prototype.TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g;
  1442. NodeContainer.prototype.TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g;
  1443. NodeContainer.prototype.CLIP = /^rect\((\d+)px,? (\d+)px,? (\d+)px,? (\d+)px\)$/;
  1444.  
  1445. function selectionValue(node) {
  1446. var option = node.options[node.selectedIndex || 0];
  1447. return option ? (option.text || "") : ""
  1448. }
  1449. function parseMatrix(match) {
  1450. if (match && match[1] === "matrix") {
  1451. return match[2].split(",").map(function(s) {
  1452. return parseFloat(s.trim())
  1453. })
  1454. } else if (match && match[1] === "matrix3d") {
  1455. var matrix3d = match[2].split(",").map(function(s) {
  1456. return parseFloat(s.trim())
  1457. });
  1458. return [matrix3d[0], matrix3d[1], matrix3d[4], matrix3d[5], matrix3d[12], matrix3d[13]]
  1459. }
  1460. }
  1461. function isPercentage(value) {
  1462. return value.toString().indexOf("%") !== -1
  1463. }
  1464. function removePx(str) {
  1465. return str.replace("px", "")
  1466. }
  1467. function asFloat(str) {
  1468. return parseFloat(str)
  1469. }
  1470. module.exports = NodeContainer
  1471. }, {
  1472. "./color": 3,
  1473. "./utils": 26
  1474. }],
  1475. 15: [function(_dereq_, module, exports) {
  1476. var log = _dereq_('./log');
  1477. var punycode = _dereq_('punycode');
  1478. var NodeContainer = _dereq_('./nodecontainer');
  1479. var TextContainer = _dereq_('./textcontainer');
  1480. var PseudoElementContainer = _dereq_('./pseudoelementcontainer');
  1481. var FontMetrics = _dereq_('./fontmetrics');
  1482. var Color = _dereq_('./color');
  1483. var StackingContext = _dereq_('./stackingcontext');
  1484. var utils = _dereq_('./utils');
  1485. var bind = utils.bind;
  1486. var getBounds = utils.getBounds;
  1487. var parseBackgrounds = utils.parseBackgrounds;
  1488. var offsetBounds = utils.offsetBounds;
  1489.  
  1490. function NodeParser(element, renderer, support, imageLoader, options) {
  1491. log("Starting NodeParser");
  1492. this.renderer = renderer;
  1493. this.options = options;
  1494. this.range = null;
  1495. this.support = support;
  1496. this.renderQueue = [];
  1497. this.stack = new StackingContext(true, 1, element.ownerDocument, null);
  1498. var parent = new NodeContainer(element, null);
  1499. if (options.background) {
  1500. renderer.rectangle(0, 0, renderer.width, renderer.height, new Color(options.background))
  1501. }
  1502. if (element === element.ownerDocument.documentElement) {
  1503. var canvasBackground = new NodeContainer(parent.color('backgroundColor').isTransparent() ? element.ownerDocument.body : element.ownerDocument.documentElement, null);
  1504. renderer.rectangle(0, 0, renderer.width, renderer.height, canvasBackground.color('backgroundColor'))
  1505. }
  1506. parent.visibile = parent.isElementVisible();
  1507. this.createPseudoHideStyles(element.ownerDocument);
  1508. this.disableAnimations(element.ownerDocument);
  1509. this.nodes = flatten([parent].concat(this.getChildren(parent)).filter(function(container) {
  1510. return container.visible = container.isElementVisible()
  1511. }).map(this.getPseudoElements, this));
  1512. this.fontMetrics = new FontMetrics();
  1513. log("Fetched nodes, total:", this.nodes.length);
  1514. log("Calculate overflow clips");
  1515. this.calculateOverflowClips();
  1516. log("Start fetching images");
  1517. this.images = imageLoader.fetch(this.nodes.filter(isElement));
  1518. this.ready = this.images.ready.then(bind(function() {
  1519. log("Images loaded, starting parsing");
  1520. log("Creating stacking contexts");
  1521. this.createStackingContexts();
  1522. log("Sorting stacking contexts");
  1523. this.sortStackingContexts(this.stack);
  1524. this.parse(this.stack);
  1525. log("Render queue created with " + this.renderQueue.length + " items");
  1526. return new Promise(bind(function(resolve) {
  1527. if (!options.async) {
  1528. this.renderQueue.forEach(this.paint, this);
  1529. resolve()
  1530. } else if (typeof(options.async) === "function") {
  1531. options.async.call(this, this.renderQueue, resolve)
  1532. } else if (this.renderQueue.length > 0) {
  1533. this.renderIndex = 0;
  1534. this.asyncRenderer(this.renderQueue, resolve)
  1535. } else {
  1536. resolve()
  1537. }
  1538. }, this))
  1539. }, this))
  1540. }
  1541. NodeParser.prototype.calculateOverflowClips = function() {
  1542. this.nodes.forEach(function(container) {
  1543. if (isElement(container)) {
  1544. if (isPseudoElement(container)) {
  1545. container.appendToDOM()
  1546. }
  1547. container.borders = this.parseBorders(container);
  1548. var clip = (container.css('overflow') === "hidden") ? [container.borders.clip] : [];
  1549. var cssClip = container.parseClip();
  1550. if (cssClip && ["absolute", "fixed"].indexOf(container.css('position')) !== -1) {
  1551. clip.push([
  1552. ["rect", container.bounds.left + cssClip.left, container.bounds.top + cssClip.top, cssClip.right - cssClip.left, cssClip.bottom - cssClip.top]
  1553. ])
  1554. }
  1555. container.clip = hasParentClip(container) ? container.parent.clip.concat(clip) : clip;
  1556. container.backgroundClip = (container.css('overflow') !== "hidden") ? container.clip.concat([container.borders.clip]) : container.clip;
  1557. if (isPseudoElement(container)) {
  1558. container.cleanDOM()
  1559. }
  1560. } else if (isTextNode(container)) {
  1561. container.clip = hasParentClip(container) ? container.parent.clip : []
  1562. }
  1563. if (!isPseudoElement(container)) {
  1564. container.bounds = null
  1565. }
  1566. }, this)
  1567. };
  1568.  
  1569. function hasParentClip(container) {
  1570. return container.parent && container.parent.clip.length
  1571. }
  1572. NodeParser.prototype.asyncRenderer = function(queue, resolve, asyncTimer) {
  1573. asyncTimer = asyncTimer || Date.now();
  1574. this.paint(queue[this.renderIndex++]);
  1575. if (queue.length === this.renderIndex) {
  1576. resolve()
  1577. } else if (asyncTimer + 20 > Date.now()) {
  1578. this.asyncRenderer(queue, resolve, asyncTimer)
  1579. } else {
  1580. setTimeout(bind(function() {
  1581. this.asyncRenderer(queue, resolve)
  1582. }, this), 0)
  1583. }
  1584. };
  1585. NodeParser.prototype.createPseudoHideStyles = function(document) {
  1586. this.createStyles(document, '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + ':before { content: "" !important; display: none !important; }' + '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER + ':after { content: "" !important; display: none !important; }')
  1587. };
  1588. NodeParser.prototype.disableAnimations = function(document) {
  1589. this.createStyles(document, '* { -webkit-animation: none !important; -moz-animation: none !important; -o-animation: none !important; animation: none !important; ' + '-webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; transition: none !important;}')
  1590. };
  1591. NodeParser.prototype.createStyles = function(document, styles) {
  1592. var hidePseudoElements = document.createElement('style');
  1593. hidePseudoElements.innerHTML = styles;
  1594. document.body.appendChild(hidePseudoElements)
  1595. };
  1596. NodeParser.prototype.getPseudoElements = function(container) {
  1597. var nodes = [
  1598. [container]
  1599. ];
  1600. if (container.node.nodeType === Node.ELEMENT_NODE) {
  1601. var before = this.getPseudoElement(container, ":before");
  1602. var after = this.getPseudoElement(container, ":after");
  1603. if (before) {
  1604. nodes.push(before)
  1605. }
  1606. if (after) {
  1607. nodes.push(after)
  1608. }
  1609. }
  1610. return flatten(nodes)
  1611. };
  1612.  
  1613. function toCamelCase(str) {
  1614. return str.replace(/(\-[a-z])/g, function(match) {
  1615. return match.toUpperCase().replace('-', '')
  1616. })
  1617. }
  1618. NodeParser.prototype.getPseudoElement = function(container, type) {
  1619. var style = container.computedStyle(type);
  1620. if (!style || !style.content || style.content === "none" || style.content === "-moz-alt-content" || style.display === "none") {
  1621. return null
  1622. }
  1623. var content = stripQuotes(style.content);
  1624. var isImage = content.substr(0, 3) === 'url';
  1625. var pseudoNode = document.createElement(isImage ? 'img' : 'html2canvaspseudoelement');
  1626. var pseudoContainer = new PseudoElementContainer(pseudoNode, container, type);
  1627. for (var i = style.length - 1; i >= 0; i--) {
  1628. var property = toCamelCase(style.item(i));
  1629. pseudoNode.style[property] = style[property]
  1630. }
  1631. pseudoNode.className = PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
  1632. if (isImage) {
  1633. pseudoNode.src = parseBackgrounds(content)[0].args[0];
  1634. return [pseudoContainer]
  1635. } else {
  1636. var text = document.createTextNode(content);
  1637. pseudoNode.appendChild(text);
  1638. return [pseudoContainer, new TextContainer(text, pseudoContainer)]
  1639. }
  1640. };
  1641. NodeParser.prototype.getChildren = function(parentContainer) {
  1642. return flatten([].filter.call(parentContainer.node.childNodes, renderableNode).map(function(node) {
  1643. var container = [node.nodeType === Node.TEXT_NODE ? new TextContainer(node, parentContainer) : new NodeContainer(node, parentContainer)].filter(nonIgnoredElement);
  1644. return node.nodeType === Node.ELEMENT_NODE && container.length && node.tagName !== "TEXTAREA" ? (container[0].isElementVisible() ? container.concat(this.getChildren(container[0])) : []) : container
  1645. }, this))
  1646. };
  1647. NodeParser.prototype.newStackingContext = function(container, hasOwnStacking) {
  1648. var stack = new StackingContext(hasOwnStacking, container.getOpacity(), container.node, container.parent);
  1649. container.cloneTo(stack);
  1650. var parentStack = hasOwnStacking ? stack.getParentStack(this) : stack.parent.stack;
  1651. parentStack.contexts.push(stack);
  1652. container.stack = stack
  1653. };
  1654. NodeParser.prototype.createStackingContexts = function() {
  1655. this.nodes.forEach(function(container) {
  1656. if (isElement(container) && (this.isRootElement(container) || hasOpacity(container) || isPositionedForStacking(container) || this.isBodyWithTransparentRoot(container) || container.hasTransform())) {
  1657. this.newStackingContext(container, true)
  1658. } else if (isElement(container) && ((isPositioned(container) && zIndex0(container)) || isInlineBlock(container) || isFloating(container))) {
  1659. this.newStackingContext(container, false)
  1660. } else {
  1661. container.assignStack(container.parent.stack)
  1662. }
  1663. }, this)
  1664. };
  1665. NodeParser.prototype.isBodyWithTransparentRoot = function(container) {
  1666. return container.node.nodeName === "BODY" && container.parent.color('backgroundColor').isTransparent()
  1667. };
  1668. NodeParser.prototype.isRootElement = function(container) {
  1669. return container.parent === null
  1670. };
  1671. NodeParser.prototype.sortStackingContexts = function(stack) {
  1672. stack.contexts.sort(zIndexSort(stack.contexts.slice(0)));
  1673. stack.contexts.forEach(this.sortStackingContexts, this)
  1674. };
  1675. NodeParser.prototype.parseTextBounds = function(container) {
  1676. return function(text, index, textList) {
  1677. if (container.parent.css("textDecoration").substr(0, 4) !== "none" || text.trim().length !== 0) {
  1678. if (this.support.rangeBounds && !container.parent.hasTransform()) {
  1679. var offset = textList.slice(0, index).join("").length;
  1680. return this.getRangeBounds(container.node, offset, text.length)
  1681. } else if (container.node && typeof(container.node.data) === "string") {
  1682. var replacementNode = container.node.splitText(text.length);
  1683. var bounds = this.getWrapperBounds(container.node, container.parent.hasTransform());
  1684. container.node = replacementNode;
  1685. return bounds
  1686. }
  1687. } else if (!this.support.rangeBounds || container.parent.hasTransform()) {
  1688. container.node = container.node.splitText(text.length)
  1689. }
  1690. return {}
  1691. }
  1692. };
  1693. NodeParser.prototype.getWrapperBounds = function(node, transform) {
  1694. var wrapper = node.ownerDocument.createElement('html2canvaswrapper');
  1695. var parent = node.parentNode,
  1696. backupText = node.cloneNode(true);
  1697. wrapper.appendChild(node.cloneNode(true));
  1698. parent.replaceChild(wrapper, node);
  1699. var bounds = transform ? offsetBounds(wrapper) : getBounds(wrapper);
  1700. parent.replaceChild(backupText, wrapper);
  1701. return bounds
  1702. };
  1703. NodeParser.prototype.getRangeBounds = function(node, offset, length) {
  1704. var range = this.range || (this.range = node.ownerDocument.createRange());
  1705. range.setStart(node, offset);
  1706. range.setEnd(node, offset + length);
  1707. return range.getBoundingClientRect()
  1708. };
  1709.  
  1710. function ClearTransform() {}
  1711. NodeParser.prototype.parse = function(stack) {
  1712. var negativeZindex = stack.contexts.filter(negativeZIndex);
  1713. var descendantElements = stack.children.filter(isElement);
  1714. var descendantNonFloats = descendantElements.filter(not(isFloating));
  1715. var nonInlineNonPositionedDescendants = descendantNonFloats.filter(not(isPositioned)).filter(not(inlineLevel));
  1716. var nonPositionedFloats = descendantElements.filter(not(isPositioned)).filter(isFloating);
  1717. var inFlow = descendantNonFloats.filter(not(isPositioned)).filter(inlineLevel);
  1718. var stackLevel0 = stack.contexts.concat(descendantNonFloats.filter(isPositioned)).filter(zIndex0);
  1719. var text = stack.children.filter(isTextNode).filter(hasText);
  1720. var positiveZindex = stack.contexts.filter(positiveZIndex);
  1721. negativeZindex.concat(nonInlineNonPositionedDescendants).concat(nonPositionedFloats).concat(inFlow).concat(stackLevel0).concat(text).concat(positiveZindex).forEach(function(container) {
  1722. this.renderQueue.push(container);
  1723. if (isStackingContext(container)) {
  1724. this.parse(container);
  1725. this.renderQueue.push(new ClearTransform())
  1726. }
  1727. }, this)
  1728. };
  1729. NodeParser.prototype.paint = function(container) {
  1730. try {
  1731. if (container instanceof ClearTransform) {
  1732. this.renderer.ctx.restore()
  1733. } else if (isTextNode(container)) {
  1734. if (isPseudoElement(container.parent)) {
  1735. container.parent.appendToDOM()
  1736. }
  1737. this.paintText(container);
  1738. if (isPseudoElement(container.parent)) {
  1739. container.parent.cleanDOM()
  1740. }
  1741. } else {
  1742. this.paintNode(container)
  1743. }
  1744. } catch (e) {
  1745. log(e);
  1746. if (this.options.strict) {
  1747. throw e;
  1748. }
  1749. }
  1750. };
  1751. NodeParser.prototype.paintNode = function(container) {
  1752. if (isStackingContext(container)) {
  1753. this.renderer.setOpacity(container.opacity);
  1754. this.renderer.ctx.save();
  1755. if (container.hasTransform()) {
  1756. this.renderer.setTransform(container.parseTransform())
  1757. }
  1758. }
  1759. if (container.node.nodeName === "INPUT" && container.node.type === "checkbox") {
  1760. this.paintCheckbox(container)
  1761. } else if (container.node.nodeName === "INPUT" && container.node.type === "radio") {
  1762. this.paintRadio(container)
  1763. } else {
  1764. this.paintElement(container)
  1765. }
  1766. };
  1767. NodeParser.prototype.paintElement = function(container) {
  1768. var bounds = container.parseBounds();
  1769. this.renderer.clip(container.backgroundClip, function() {
  1770. this.renderer.renderBackground(container, bounds, container.borders.borders.map(getWidth))
  1771. }, this);
  1772. this.renderer.clip(container.clip, function() {
  1773. this.renderer.renderBorders(container.borders.borders)
  1774. }, this);
  1775. this.renderer.clip(container.backgroundClip, function() {
  1776. switch (container.node.nodeName) {
  1777. case "svg":
  1778. case "IFRAME":
  1779. var imgContainer = this.images.get(container.node);
  1780. if (imgContainer) {
  1781. this.renderer.renderImage(container, bounds, container.borders, imgContainer)
  1782. } else {
  1783. log("Error loading <" + container.node.nodeName + ">", container.node)
  1784. }
  1785. break;
  1786. case "IMG":
  1787. var imageContainer = this.images.get(container.node.src);
  1788. if (imageContainer) {
  1789. this.renderer.renderImage(container, bounds, container.borders, imageContainer)
  1790. } else {
  1791. log("Error loading <img>", container.node.src)
  1792. }
  1793. break;
  1794. case "CANVAS":
  1795. this.renderer.renderImage(container, bounds, container.borders, {
  1796. image: container.node
  1797. });
  1798. break;
  1799. case "SELECT":
  1800. case "INPUT":
  1801. case "TEXTAREA":
  1802. this.paintFormValue(container);
  1803. break
  1804. }
  1805. }, this)
  1806. };
  1807. NodeParser.prototype.paintCheckbox = function(container) {
  1808. var b = container.parseBounds();
  1809. var size = Math.min(b.width, b.height);
  1810. var bounds = {
  1811. width: size - 1,
  1812. height: size - 1,
  1813. top: b.top,
  1814. left: b.left
  1815. };
  1816. var r = [3, 3];
  1817. var radius = [r, r, r, r];
  1818. var borders = [1, 1, 1, 1].map(function(w) {
  1819. return {
  1820. color: new Color('#A5A5A5'),
  1821. width: w
  1822. }
  1823. });
  1824. var borderPoints = calculateCurvePoints(bounds, radius, borders);
  1825. this.renderer.clip(container.backgroundClip, function() {
  1826. this.renderer.rectangle(bounds.left + 1, bounds.top + 1, bounds.width - 2, bounds.height - 2, new Color("#DEDEDE"));
  1827. this.renderer.renderBorders(calculateBorders(borders, bounds, borderPoints, radius));
  1828. if (container.node.checked) {
  1829. this.renderer.font(new Color('#424242'), 'normal', 'normal', 'bold', (size - 3) + "px", 'arial');
  1830. this.renderer.text("\u2714", bounds.left + size / 6, bounds.top + size - 1)
  1831. }
  1832. }, this)
  1833. };
  1834. NodeParser.prototype.paintRadio = function(container) {
  1835. var bounds = container.parseBounds();
  1836. var size = Math.min(bounds.width, bounds.height) - 2;
  1837. this.renderer.clip(container.backgroundClip, function() {
  1838. this.renderer.circleStroke(bounds.left + 1, bounds.top + 1, size, new Color('#DEDEDE'), 1, new Color('#A5A5A5'));
  1839. if (container.node.checked) {
  1840. this.renderer.circle(Math.ceil(bounds.left + size / 4) + 1, Math.ceil(bounds.top + size / 4) + 1, Math.floor(size / 2), new Color('#424242'))
  1841. }
  1842. }, this)
  1843. };
  1844. NodeParser.prototype.paintFormValue = function(container) {
  1845. var value = container.getValue();
  1846. if (value.length > 0) {
  1847. var document = container.node.ownerDocument;
  1848. var wrapper = document.createElement('html2canvaswrapper');
  1849. var properties = ['lineHeight', 'textAlign', 'fontFamily', 'fontWeight', 'fontSize', 'color', 'paddingLeft', 'paddingTop', 'paddingRight', 'paddingBottom', 'width', 'height', 'borderLeftStyle', 'borderTopStyle', 'borderLeftWidth', 'borderTopWidth', 'boxSizing', 'whiteSpace', 'wordWrap'];
  1850. properties.forEach(function(property) {
  1851. try {
  1852. wrapper.style[property] = container.css(property)
  1853. } catch (e) {
  1854. log("html2canvas: Parse: Exception caught in renderFormValue: " + e.message)
  1855. }
  1856. });
  1857. var bounds = container.parseBounds();
  1858. wrapper.style.position = "fixed";
  1859. wrapper.style.left = bounds.left + "px";
  1860. wrapper.style.top = bounds.top + "px";
  1861. wrapper.textContent = value;
  1862. document.body.appendChild(wrapper);
  1863. this.paintText(new TextContainer(wrapper.firstChild, container));
  1864. document.body.removeChild(wrapper)
  1865. }
  1866. };
  1867. NodeParser.prototype.paintText = function(container) {
  1868. container.applyTextTransform();
  1869. var characters = punycode.ucs2.decode(container.node.data);
  1870. var textList = (!this.options.letterRendering || noLetterSpacing(container)) && !hasUnicode(container.node.data) ? getWords(characters) : characters.map(function(character) {
  1871. return punycode.ucs2.encode([character])
  1872. });
  1873. var weight = container.parent.fontWeight();
  1874. var size = container.parent.css('fontSize');
  1875. var family = container.parent.css('fontFamily');
  1876. var shadows = container.parent.parseTextShadows();
  1877. this.renderer.font(container.parent.color('color'), container.parent.css('fontStyle'), container.parent.css('fontVariant'), weight, size, family);
  1878. if (shadows.length) {
  1879. this.renderer.fontShadow(shadows[0].color, shadows[0].offsetX, shadows[0].offsetY, shadows[0].blur)
  1880. } else {
  1881. this.renderer.clearShadow()
  1882. }
  1883. this.renderer.clip(container.parent.clip, function() {
  1884. textList.map(this.parseTextBounds(container), this).forEach(function(bounds, index) {
  1885. if (bounds) {
  1886. this.renderer.text(textList[index], bounds.left, bounds.bottom);
  1887. this.renderTextDecoration(container.parent, bounds, this.fontMetrics.getMetrics(family, size))
  1888. }
  1889. }, this)
  1890. }, this)
  1891. };
  1892. NodeParser.prototype.renderTextDecoration = function(container, bounds, metrics) {
  1893. switch (container.css("textDecoration").split(" ")[0]) {
  1894. case "underline":
  1895. this.renderer.rectangle(bounds.left, Math.round(bounds.top + metrics.baseline + metrics.lineWidth), bounds.width, 1, container.color("color"));
  1896. break;
  1897. case "overline":
  1898. this.renderer.rectangle(bounds.left, Math.round(bounds.top), bounds.width, 1, container.color("color"));
  1899. break;
  1900. case "line-through":
  1901. this.renderer.rectangle(bounds.left, Math.ceil(bounds.top + metrics.middle + metrics.lineWidth), bounds.width, 1, container.color("color"));
  1902. break
  1903. }
  1904. };
  1905. var borderColorTransforms = {
  1906. inset: [
  1907. ["darken", 0.60],
  1908. ["darken", 0.10],
  1909. ["darken", 0.10],
  1910. ["darken", 0.60]
  1911. ]
  1912. };
  1913. NodeParser.prototype.parseBorders = function(container) {
  1914. var nodeBounds = container.parseBounds();
  1915. var radius = getBorderRadiusData(container);
  1916. var borders = ["Top", "Right", "Bottom", "Left"].map(function(side, index) {
  1917. var style = container.css('border' + side + 'Style');
  1918. var color = container.color('border' + side + 'Color');
  1919. if (style === "inset" && color.isBlack()) {
  1920. color = new Color([255, 255, 255, color.a])
  1921. }
  1922. var colorTransform = borderColorTransforms[style] ? borderColorTransforms[style][index] : null;
  1923. return {
  1924. width: container.cssInt('border' + side + 'Width'),
  1925. color: colorTransform ? color[colorTransform[0]](colorTransform[1]) : color,
  1926. args: null
  1927. }
  1928. });
  1929. var borderPoints = calculateCurvePoints(nodeBounds, radius, borders);
  1930. return {
  1931. clip: this.parseBackgroundClip(container, borderPoints, borders, radius, nodeBounds),
  1932. borders: calculateBorders(borders, nodeBounds, borderPoints, radius)
  1933. }
  1934. };
  1935.  
  1936. function calculateBorders(borders, nodeBounds, borderPoints, radius) {
  1937. return borders.map(function(border, borderSide) {
  1938. if (border.width > 0) {
  1939. var bx = nodeBounds.left;
  1940. var by = nodeBounds.top;
  1941. var bw = nodeBounds.width;
  1942. var bh = nodeBounds.height - (borders[2].width);
  1943. switch (borderSide) {
  1944. case 0:
  1945. bh = borders[0].width;
  1946. border.args = drawSide({
  1947. c1: [bx, by],
  1948. c2: [bx + bw, by],
  1949. c3: [bx + bw - borders[1].width, by + bh],
  1950. c4: [bx + borders[3].width, by + bh]
  1951. }, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topLeftInner, borderPoints.topRightOuter, borderPoints.topRightInner);
  1952. break;
  1953. case 1:
  1954. bx = nodeBounds.left + nodeBounds.width - (borders[1].width);
  1955. bw = borders[1].width;
  1956. border.args = drawSide({
  1957. c1: [bx + bw, by],
  1958. c2: [bx + bw, by + bh + borders[2].width],
  1959. c3: [bx, by + bh],
  1960. c4: [bx, by + borders[0].width]
  1961. }, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.topRightInner, borderPoints.bottomRightOuter, borderPoints.bottomRightInner);
  1962. break;
  1963. case 2:
  1964. by = (by + nodeBounds.height) - (borders[2].width);
  1965. bh = borders[2].width;
  1966. border.args = drawSide({
  1967. c1: [bx + bw, by + bh],
  1968. c2: [bx, by + bh],
  1969. c3: [bx + borders[3].width, by],
  1970. c4: [bx + bw - borders[3].width, by]
  1971. }, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomRightInner, borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner);
  1972. break;
  1973. case 3:
  1974. bw = borders[3].width;
  1975. border.args = drawSide({
  1976. c1: [bx, by + bh + borders[2].width],
  1977. c2: [bx, by],
  1978. c3: [bx + bw, by + borders[0].width],
  1979. c4: [bx + bw, by + bh]
  1980. }, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner, borderPoints.topLeftOuter, borderPoints.topLeftInner);
  1981. break
  1982. }
  1983. }
  1984. return border
  1985. })
  1986. }
  1987. NodeParser.prototype.parseBackgroundClip = function(container, borderPoints, borders, radius, bounds) {
  1988. var backgroundClip = container.css('backgroundClip'),
  1989. borderArgs = [];
  1990. switch (backgroundClip) {
  1991. case "content-box":
  1992. case "padding-box":
  1993. parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftInner, borderPoints.topRightInner, bounds.left + borders[3].width, bounds.top + borders[0].width);
  1994. parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightInner, borderPoints.bottomRightInner, bounds.left + bounds.width - borders[1].width, bounds.top + borders[0].width);
  1995. parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightInner, borderPoints.bottomLeftInner, bounds.left + bounds.width - borders[1].width, bounds.top + bounds.height - borders[2].width);
  1996. parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftInner, borderPoints.topLeftInner, bounds.left + borders[3].width, bounds.top + bounds.height - borders[2].width);
  1997. break;
  1998. default:
  1999. parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topRightOuter, bounds.left, bounds.top);
  2000. parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.bottomRightOuter, bounds.left + bounds.width, bounds.top);
  2001. parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomLeftOuter, bounds.left + bounds.width, bounds.top + bounds.height);
  2002. parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.topLeftOuter, bounds.left, bounds.top + bounds.height);
  2003. break
  2004. }
  2005. return borderArgs
  2006. };
  2007.  
  2008. function getCurvePoints(x, y, r1, r2) {
  2009. var kappa = 4 * ((Math.sqrt(2) - 1) / 3);
  2010. var ox = (r1) * kappa,
  2011. oy = (r2) * kappa,
  2012. xm = x + r1,
  2013. ym = y + r2;
  2014. return {
  2015. topLeft: bezierCurve({
  2016. x: x,
  2017. y: ym
  2018. }, {
  2019. x: x,
  2020. y: ym - oy
  2021. }, {
  2022. x: xm - ox,
  2023. y: y
  2024. }, {
  2025. x: xm,
  2026. y: y
  2027. }),
  2028. topRight: bezierCurve({
  2029. x: x,
  2030. y: y
  2031. }, {
  2032. x: x + ox,
  2033. y: y
  2034. }, {
  2035. x: xm,
  2036. y: ym - oy
  2037. }, {
  2038. x: xm,
  2039. y: ym
  2040. }),
  2041. bottomRight: bezierCurve({
  2042. x: xm,
  2043. y: y
  2044. }, {
  2045. x: xm,
  2046. y: y + oy
  2047. }, {
  2048. x: x + ox,
  2049. y: ym
  2050. }, {
  2051. x: x,
  2052. y: ym
  2053. }),
  2054. bottomLeft: bezierCurve({
  2055. x: xm,
  2056. y: ym
  2057. }, {
  2058. x: xm - ox,
  2059. y: ym
  2060. }, {
  2061. x: x,
  2062. y: y + oy
  2063. }, {
  2064. x: x,
  2065. y: y
  2066. })
  2067. }
  2068. }
  2069. function calculateCurvePoints(bounds, borderRadius, borders) {
  2070. var x = bounds.left,
  2071. y = bounds.top,
  2072. width = bounds.width,
  2073. height = bounds.height,
  2074. tlh = borderRadius[0][0] < width / 2 ? borderRadius[0][0] : width / 2,
  2075. tlv = borderRadius[0][1] < height / 2 ? borderRadius[0][1] : height / 2,
  2076. trh = borderRadius[1][0] < width / 2 ? borderRadius[1][0] : width / 2,
  2077. trv = borderRadius[1][1] < height / 2 ? borderRadius[1][1] : height / 2,
  2078. brh = borderRadius[2][0] < width / 2 ? borderRadius[2][0] : width / 2,
  2079. brv = borderRadius[2][1] < height / 2 ? borderRadius[2][1] : height / 2,
  2080. blh = borderRadius[3][0] < width / 2 ? borderRadius[3][0] : width / 2,
  2081. blv = borderRadius[3][1] < height / 2 ? borderRadius[3][1] : height / 2;
  2082. var topWidth = width - trh,
  2083. rightHeight = height - brv,
  2084. bottomWidth = width - brh,
  2085. leftHeight = height - blv;
  2086. return {
  2087. topLeftOuter: getCurvePoints(x, y, tlh, tlv).topLeft.subdivide(0.5),
  2088. topLeftInner: getCurvePoints(x + borders[3].width, y + borders[0].width, Math.max(0, tlh - borders[3].width), Math.max(0, tlv - borders[0].width)).topLeft.subdivide(0.5),
  2089. topRightOuter: getCurvePoints(x + topWidth, y, trh, trv).topRight.subdivide(0.5),
  2090. topRightInner: getCurvePoints(x + Math.min(topWidth, width + borders[3].width), y + borders[0].width, (topWidth > width + borders[3].width) ? 0 : trh - borders[3].width, trv - borders[0].width).topRight.subdivide(0.5),
  2091. bottomRightOuter: getCurvePoints(x + bottomWidth, y + rightHeight, brh, brv).bottomRight.subdivide(0.5),
  2092. bottomRightInner: getCurvePoints(x + Math.min(bottomWidth, width - borders[3].width), y + Math.min(rightHeight, height + borders[0].width), Math.max(0, brh - borders[1].width), brv - borders[2].width).bottomRight.subdivide(0.5),
  2093. bottomLeftOuter: getCurvePoints(x, y + leftHeight, blh, blv).bottomLeft.subdivide(0.5),
  2094. bottomLeftInner: getCurvePoints(x + borders[3].width, y + leftHeight, Math.max(0, blh - borders[3].width), blv - borders[2].width).bottomLeft.subdivide(0.5)
  2095. }
  2096. }
  2097. function bezierCurve(start, startControl, endControl, end) {
  2098. var lerp = function(a, b, t) {
  2099. return {
  2100. x: a.x + (b.x - a.x) * t,
  2101. y: a.y + (b.y - a.y) * t
  2102. }
  2103. };
  2104. return {
  2105. start: start,
  2106. startControl: startControl,
  2107. endControl: endControl,
  2108. end: end,
  2109. subdivide: function(t) {
  2110. var ab = lerp(start, startControl, t),
  2111. bc = lerp(startControl, endControl, t),
  2112. cd = lerp(endControl, end, t),
  2113. abbc = lerp(ab, bc, t),
  2114. bccd = lerp(bc, cd, t),
  2115. dest = lerp(abbc, bccd, t);
  2116. return [bezierCurve(start, ab, abbc, dest), bezierCurve(dest, bccd, cd, end)]
  2117. },
  2118. curveTo: function(borderArgs) {
  2119. borderArgs.push(["bezierCurve", startControl.x, startControl.y, endControl.x, endControl.y, end.x, end.y])
  2120. },
  2121. curveToReversed: function(borderArgs) {
  2122. borderArgs.push(["bezierCurve", endControl.x, endControl.y, startControl.x, startControl.y, start.x, start.y])
  2123. }
  2124. }
  2125. }
  2126. function drawSide(borderData, radius1, radius2, outer1, inner1, outer2, inner2) {
  2127. var borderArgs = [];
  2128. if (radius1[0] > 0 || radius1[1] > 0) {
  2129. borderArgs.push(["line", outer1[1].start.x, outer1[1].start.y]);
  2130. outer1[1].curveTo(borderArgs)
  2131. } else {
  2132. borderArgs.push(["line", borderData.c1[0], borderData.c1[1]])
  2133. }
  2134. if (radius2[0] > 0 || radius2[1] > 0) {
  2135. borderArgs.push(["line", outer2[0].start.x, outer2[0].start.y]);
  2136. outer2[0].curveTo(borderArgs);
  2137. borderArgs.push(["line", inner2[0].end.x, inner2[0].end.y]);
  2138. inner2[0].curveToReversed(borderArgs)
  2139. } else {
  2140. borderArgs.push(["line", borderData.c2[0], borderData.c2[1]]);
  2141. borderArgs.push(["line", borderData.c3[0], borderData.c3[1]])
  2142. }
  2143. if (radius1[0] > 0 || radius1[1] > 0) {
  2144. borderArgs.push(["line", inner1[1].end.x, inner1[1].end.y]);
  2145. inner1[1].curveToReversed(borderArgs)
  2146. } else {
  2147. borderArgs.push(["line", borderData.c4[0], borderData.c4[1]])
  2148. }
  2149. return borderArgs
  2150. }
  2151. function parseCorner(borderArgs, radius1, radius2, corner1, corner2, x, y) {
  2152. if (radius1[0] > 0 || radius1[1] > 0) {
  2153. borderArgs.push(["line", corner1[0].start.x, corner1[0].start.y]);
  2154. corner1[0].curveTo(borderArgs);
  2155. corner1[1].curveTo(borderArgs)
  2156. } else {
  2157. borderArgs.push(["line", x, y])
  2158. }
  2159. if (radius2[0] > 0 || radius2[1] > 0) {
  2160. borderArgs.push(["line", corner2[0].start.x, corner2[0].start.y])
  2161. }
  2162. }
  2163. function negativeZIndex(container) {
  2164. return container.cssInt("zIndex") < 0
  2165. }
  2166. function positiveZIndex(container) {
  2167. return container.cssInt("zIndex") > 0
  2168. }
  2169. function zIndex0(container) {
  2170. return container.cssInt("zIndex") === 0
  2171. }
  2172. function inlineLevel(container) {
  2173. return ["inline", "inline-block", "inline-table"].indexOf(container.css("display")) !== -1
  2174. }
  2175. function isStackingContext(container) {
  2176. return (container instanceof StackingContext)
  2177. }
  2178. function hasText(container) {
  2179. return container.node.data.trim().length > 0
  2180. }
  2181. function noLetterSpacing(container) {
  2182. return (/^(normal|none|0px)$/.test(container.parent.css("letterSpacing")))
  2183. }
  2184. function getBorderRadiusData(container) {
  2185. return ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].map(function(side) {
  2186. var value = container.css('border' + side + 'Radius');
  2187. var arr = value.split(" ");
  2188. if (arr.length <= 1) {
  2189. arr[1] = arr[0]
  2190. }
  2191. return arr.map(asInt)
  2192. })
  2193. }
  2194. function renderableNode(node) {
  2195. return (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.ELEMENT_NODE)
  2196. }
  2197. function isPositionedForStacking(container) {
  2198. var position = container.css("position");
  2199. var zIndex = (["absolute", "relative", "fixed"].indexOf(position) !== -1) ? container.css("zIndex") : "auto";
  2200. return zIndex !== "auto"
  2201. }
  2202. function isPositioned(container) {
  2203. return container.css("position") !== "static"
  2204. }
  2205. function isFloating(container) {
  2206. return container.css("float") !== "none"
  2207. }
  2208. function isInlineBlock(container) {
  2209. return ["inline-block", "inline-table"].indexOf(container.css("display")) !== -1
  2210. }
  2211. function not(callback) {
  2212. var context = this;
  2213. return function() {
  2214. return !callback.apply(context, arguments)
  2215. }
  2216. }
  2217. function isElement(container) {
  2218. return container.node.nodeType === Node.ELEMENT_NODE
  2219. }
  2220. function isPseudoElement(container) {
  2221. return container.isPseudoElement === true
  2222. }
  2223. function isTextNode(container) {
  2224. return container.node.nodeType === Node.TEXT_NODE
  2225. }
  2226. function zIndexSort(contexts) {
  2227. return function(a, b) {
  2228. return (a.cssInt("zIndex") + (contexts.indexOf(a) / contexts.length)) - (b.cssInt("zIndex") + (contexts.indexOf(b) / contexts.length))
  2229. }
  2230. }
  2231. function hasOpacity(container) {
  2232. return container.getOpacity() < 1
  2233. }
  2234. function asInt(value) {
  2235. return parseInt(value, 10)
  2236. }
  2237. function getWidth(border) {
  2238. return border.width
  2239. }
  2240. function nonIgnoredElement(nodeContainer) {
  2241. return (nodeContainer.node.nodeType !== Node.ELEMENT_NODE || ["SCRIPT", "HEAD", "TITLE", "OBJECT", "BR", "OPTION"].indexOf(nodeContainer.node.nodeName) === -1)
  2242. }
  2243. function flatten(arrays) {
  2244. return [].concat.apply([], arrays)
  2245. }
  2246. function stripQuotes(content) {
  2247. var first = content.substr(0, 1);
  2248. return (first === content.substr(content.length - 1) && first.match(/'|"/)) ? content.substr(1, content.length - 2) : content
  2249. }
  2250. function getWords(characters) {
  2251. var words = [],
  2252. i = 0,
  2253. onWordBoundary = false,
  2254. word;
  2255. while (characters.length) {
  2256. if (isWordBoundary(characters[i]) === onWordBoundary) {
  2257. word = characters.splice(0, i);
  2258. if (word.length) {
  2259. words.push(punycode.ucs2.encode(word))
  2260. }
  2261. onWordBoundary = !onWordBoundary;
  2262. i = 0
  2263. } else {
  2264. i++
  2265. }
  2266. if (i >= characters.length) {
  2267. word = characters.splice(0, i);
  2268. if (word.length) {
  2269. words.push(punycode.ucs2.encode(word))
  2270. }
  2271. }
  2272. }
  2273. return words
  2274. }
  2275. function isWordBoundary(characterCode) {
  2276. return [32, 13, 10, 9, 45].indexOf(characterCode) !== -1
  2277. }
  2278. function hasUnicode(string) {
  2279. return (/[^\u0000-\u00ff]/).test(string)
  2280. }
  2281. module.exports = NodeParser
  2282. }, {
  2283. "./color": 3,
  2284. "./fontmetrics": 7,
  2285. "./log": 13,
  2286. "./nodecontainer": 14,
  2287. "./pseudoelementcontainer": 18,
  2288. "./stackingcontext": 21,
  2289. "./textcontainer": 25,
  2290. "./utils": 26,
  2291. "punycode": 1
  2292. }],
  2293. 16: [function(_dereq_, module, exports) {
  2294. var XHR = _dereq_('./xhr');
  2295. var utils = _dereq_('./utils');
  2296. var log = _dereq_('./log');
  2297. var createWindowClone = _dereq_('./clone');
  2298. var decode64 = utils.decode64;
  2299.  
  2300. function Proxy(src, proxyUrl, document) {
  2301. var supportsCORS = ('withCredentials' in new XMLHttpRequest());
  2302. if (!proxyUrl) {
  2303. return Promise.reject("No proxy configured")
  2304. }
  2305. var callback = createCallback(supportsCORS);
  2306. var url = createProxyUrl(proxyUrl, src, callback);
  2307. return supportsCORS ? XHR(url) : (jsonp(document, url, callback).then(function(response) {
  2308. return decode64(response.content)
  2309. }))
  2310. }
  2311. var proxyCount = 0;
  2312.  
  2313. function ProxyURL(src, proxyUrl, document) {
  2314. var supportsCORSImage = ('crossOrigin' in new Image());
  2315. var callback = createCallback(supportsCORSImage);
  2316. var url = createProxyUrl(proxyUrl, src, callback);
  2317. return (supportsCORSImage ? Promise.resolve(url) : jsonp(document, url, callback).then(function(response) {
  2318. return "data:" + response.type + ";base64," + response.content
  2319. }))
  2320. }
  2321. function jsonp(document, url, callback) {
  2322. return new Promise(function(resolve, reject) {
  2323. var s = document.createElement("script");
  2324. var cleanup = function() {
  2325. delete window.html2canvas.proxy[callback];
  2326. document.body.removeChild(s)
  2327. };
  2328. window.html2canvas.proxy[callback] = function(response) {
  2329. cleanup();
  2330. resolve(response)
  2331. };
  2332. s.src = url;
  2333. s.onerror = function(e) {
  2334. cleanup();
  2335. reject(e)
  2336. };
  2337. document.body.appendChild(s)
  2338. })
  2339. }
  2340. function createCallback(useCORS) {
  2341. return !useCORS ? "html2canvas_" + Date.now() + "_" + (++proxyCount) + "_" + Math.round(Math.random() * 100000) : ""
  2342. }
  2343. function createProxyUrl(proxyUrl, src, callback) {
  2344. return proxyUrl + "?url=" + encodeURIComponent(src) + (callback.length ? "&callback=html2canvas.proxy." + callback : "")
  2345. }
  2346. function documentFromHTML(src) {
  2347. return function(html) {
  2348. var parser = new DOMParser(),
  2349. doc;
  2350. try {
  2351. doc = parser.parseFromString(html, "text/html")
  2352. } catch (e) {
  2353. log("DOMParser not supported, falling back to createHTMLDocument");
  2354. doc = document.implementation.createHTMLDocument("");
  2355. try {
  2356. doc.open();
  2357. doc.write(html);
  2358. doc.close()
  2359. } catch (ee) {
  2360. log("createHTMLDocument write not supported, falling back to document.body.innerHTML");
  2361. doc.body.innerHTML = html
  2362. }
  2363. }
  2364. var b = doc.querySelector("base");
  2365. if (!b || !b.href.host) {
  2366. var base = doc.createElement("base");
  2367. base.href = src;
  2368. doc.head.insertBefore(base, doc.head.firstChild)
  2369. }
  2370. return doc
  2371. }
  2372. }
  2373. function loadUrlDocument(src, proxy, document, width, height, options) {
  2374. return new Proxy(src, proxy, window.document).then(documentFromHTML(src)).then(function(doc) {
  2375. return createWindowClone(doc, document, width, height, options, 0, 0)
  2376. })
  2377. }
  2378. exports.Proxy = Proxy;
  2379. exports.ProxyURL = ProxyURL;
  2380. exports.loadUrlDocument = loadUrlDocument
  2381. }, {
  2382. "./clone": 2,
  2383. "./log": 13,
  2384. "./utils": 26,
  2385. "./xhr": 28
  2386. }],
  2387. 17: [function(_dereq_, module, exports) {
  2388. var ProxyURL = _dereq_('./proxy').ProxyURL;
  2389.  
  2390. function ProxyImageContainer(src, proxy) {
  2391. var link = document.createElement("a");
  2392. link.href = src;
  2393. src = link.href;
  2394. this.src = src;
  2395. this.image = new Image();
  2396. var self = this;
  2397. this.promise = new Promise(function(resolve, reject) {
  2398. self.image.crossOrigin = "Anonymous";
  2399. self.image.onload = resolve;
  2400. self.image.onerror = reject;
  2401. new ProxyURL(src, proxy, document).then(function(url) {
  2402. self.image.src = url
  2403. })['catch'](reject)
  2404. })
  2405. }
  2406. module.exports = ProxyImageContainer
  2407. }, {
  2408. "./proxy": 16
  2409. }],
  2410. 18: [function(_dereq_, module, exports) {
  2411. var NodeContainer = _dereq_('./nodecontainer');
  2412.  
  2413. function PseudoElementContainer(node, parent, type) {
  2414. NodeContainer.call(this, node, parent);
  2415. this.isPseudoElement = true;
  2416. this.before = type === ":before"
  2417. }
  2418. PseudoElementContainer.prototype.cloneTo = function(stack) {
  2419. PseudoElementContainer.prototype.cloneTo.call(this, stack);
  2420. stack.isPseudoElement = true;
  2421. stack.before = this.before
  2422. };
  2423. PseudoElementContainer.prototype = Object.create(NodeContainer.prototype);
  2424. PseudoElementContainer.prototype.appendToDOM = function() {
  2425. if (this.before) {
  2426. this.parent.node.insertBefore(this.node, this.parent.node.firstChild)
  2427. } else {
  2428. this.parent.node.appendChild(this.node)
  2429. }
  2430. this.parent.node.className += " " + this.getHideClass()
  2431. };
  2432. PseudoElementContainer.prototype.cleanDOM = function() {
  2433. this.node.parentNode.removeChild(this.node);
  2434. this.parent.node.className = this.parent.node.className.replace(this.getHideClass(), "")
  2435. };
  2436. PseudoElementContainer.prototype.getHideClass = function() {
  2437. return this["PSEUDO_HIDE_ELEMENT_CLASS_" + (this.before ? "BEFORE" : "AFTER")]
  2438. };
  2439. PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = "___html2canvas___pseudoelement_before";
  2440. PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER = "___html2canvas___pseudoelement_after";
  2441. module.exports = PseudoElementContainer
  2442. }, {
  2443. "./nodecontainer": 14
  2444. }],
  2445. 19: [function(_dereq_, module, exports) {
  2446. var log = _dereq_('./log');
  2447.  
  2448. function Renderer(width, height, images, options, document) {
  2449. this.width = width;
  2450. this.height = height;
  2451. this.images = images;
  2452. this.options = options;
  2453. this.document = document
  2454. }
  2455. Renderer.prototype.renderImage = function(container, bounds, borderData, imageContainer) {
  2456. var paddingLeft = container.cssInt('paddingLeft'),
  2457. paddingTop = container.cssInt('paddingTop'),
  2458. paddingRight = container.cssInt('paddingRight'),
  2459. paddingBottom = container.cssInt('paddingBottom'),
  2460. borders = borderData.borders;
  2461. var width = bounds.width - (borders[1].width + borders[3].width + paddingLeft + paddingRight);
  2462. var height = bounds.height - (borders[0].width + borders[2].width + paddingTop + paddingBottom);
  2463. this.drawImage(imageContainer, 0, 0, imageContainer.image.width || width, imageContainer.image.height || height, bounds.left + paddingLeft + borders[3].width, bounds.top + paddingTop + borders[0].width, width, height)
  2464. };
  2465. Renderer.prototype.renderBackground = function(container, bounds, borderData) {
  2466. if (bounds.height > 0 && bounds.width > 0) {
  2467. this.renderBackgroundColor(container, bounds);
  2468. this.renderBackgroundImage(container, bounds, borderData)
  2469. }
  2470. };
  2471. Renderer.prototype.renderBackgroundColor = function(container, bounds) {
  2472. var color = container.color("backgroundColor");
  2473. if (!color.isTransparent()) {
  2474. this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, color)
  2475. }
  2476. };
  2477. Renderer.prototype.renderBorders = function(borders) {
  2478. borders.forEach(this.renderBorder, this)
  2479. };
  2480. Renderer.prototype.renderBorder = function(data) {
  2481. if (!data.color.isTransparent() && data.args !== null) {
  2482. this.drawShape(data.args, data.color)
  2483. }
  2484. };
  2485. Renderer.prototype.renderBackgroundImage = function(container, bounds, borderData) {
  2486. var backgroundImages = container.parseBackgroundImages();
  2487. backgroundImages.reverse().forEach(function(backgroundImage, index, arr) {
  2488. switch (backgroundImage.method) {
  2489. case "url":
  2490. var image = this.images.get(backgroundImage.args[0]);
  2491. if (image) {
  2492. this.renderBackgroundRepeating(container, bounds, image, arr.length - (index + 1), borderData)
  2493. } else {
  2494. log("Error loading background-image", backgroundImage.args[0])
  2495. }
  2496. break;
  2497. case "linear-gradient":
  2498. case "gradient":
  2499. var gradientImage = this.images.get(backgroundImage.value);
  2500. if (gradientImage) {
  2501. this.renderBackgroundGradient(gradientImage, bounds, borderData)
  2502. } else {
  2503. log("Error loading background-image", backgroundImage.args[0])
  2504. }
  2505. break;
  2506. case "none":
  2507. break;
  2508. default:
  2509. log("Unknown background-image type", backgroundImage.args[0])
  2510. }
  2511. }, this)
  2512. };
  2513. Renderer.prototype.renderBackgroundRepeating = function(container, bounds, imageContainer, index, borderData) {
  2514. var size = container.parseBackgroundSize(bounds, imageContainer.image, index);
  2515. var position = container.parseBackgroundPosition(bounds, imageContainer.image, index, size);
  2516. var repeat = container.parseBackgroundRepeat(index);
  2517. switch (repeat) {
  2518. case "repeat-x":
  2519. case "repeat no-repeat":
  2520. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + borderData[3], bounds.top + position.top + borderData[0], 99999, size.height, borderData);
  2521. break;
  2522. case "repeat-y":
  2523. case "no-repeat repeat":
  2524. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + borderData[0], size.width, 99999, borderData);
  2525. break;
  2526. case "no-repeat":
  2527. this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + position.top + borderData[0], size.width, size.height, borderData);
  2528. break;
  2529. default:
  2530. this.renderBackgroundRepeat(imageContainer, position, size, {
  2531. top: bounds.top,
  2532. left: bounds.left
  2533. }, borderData[3], borderData[0]);
  2534. break
  2535. }
  2536. };
  2537. module.exports = Renderer
  2538. }, {
  2539. "./log": 13
  2540. }],
  2541. 20: [function(_dereq_, module, exports) {
  2542. var Renderer = _dereq_('../renderer');
  2543. var LinearGradientContainer = _dereq_('../lineargradientcontainer');
  2544. var log = _dereq_('../log');
  2545.  
  2546. function CanvasRenderer(width, height) {
  2547. Renderer.apply(this, arguments);
  2548. this.canvas = this.options.canvas || this.document.createElement("canvas");
  2549. if (!this.options.canvas) {
  2550. this.canvas.width = width;
  2551. this.canvas.height = height
  2552. }
  2553. this.ctx = this.canvas.getContext("2d");
  2554. this.taintCtx = this.document.createElement("canvas").getContext("2d");
  2555. this.ctx.textBaseline = "bottom";
  2556. this.variables = {};
  2557. log("Initialized CanvasRenderer with size", width, "x", height)
  2558. }
  2559. CanvasRenderer.prototype = Object.create(Renderer.prototype);
  2560. CanvasRenderer.prototype.setFillStyle = function(fillStyle) {
  2561. this.ctx.fillStyle = typeof(fillStyle) === "object" && !! fillStyle.isColor ? fillStyle.toString() : fillStyle;
  2562. return this.ctx
  2563. };
  2564. CanvasRenderer.prototype.rectangle = function(left, top, width, height, color) {
  2565. this.setFillStyle(color).fillRect(left, top, width, height)
  2566. };
  2567. CanvasRenderer.prototype.circle = function(left, top, size, color) {
  2568. this.setFillStyle(color);
  2569. this.ctx.beginPath();
  2570. this.ctx.arc(left + size / 2, top + size / 2, size / 2, 0, Math.PI * 2, true);
  2571. this.ctx.closePath();
  2572. this.ctx.fill()
  2573. };
  2574. CanvasRenderer.prototype.circleStroke = function(left, top, size, color, stroke, strokeColor) {
  2575. this.circle(left, top, size, color);
  2576. this.ctx.strokeStyle = strokeColor.toString();
  2577. this.ctx.stroke()
  2578. };
  2579. CanvasRenderer.prototype.drawShape = function(shape, color) {
  2580. this.shape(shape);
  2581. this.setFillStyle(color).fill()
  2582. };
  2583. CanvasRenderer.prototype.taints = function(imageContainer) {
  2584. if (imageContainer.tainted === null) {
  2585. this.taintCtx.drawImage(imageContainer.image, 0, 0);
  2586. try {
  2587. this.taintCtx.getImageData(0, 0, 1, 1);
  2588. imageContainer.tainted = false
  2589. } catch (e) {
  2590. this.taintCtx = document.createElement("canvas").getContext("2d");
  2591. imageContainer.tainted = true
  2592. }
  2593. }
  2594. return imageContainer.tainted
  2595. };
  2596. CanvasRenderer.prototype.drawImage = function(imageContainer, sx, sy, sw, sh, dx, dy, dw, dh) {
  2597. if (!this.taints(imageContainer) || this.options.allowTaint) {
  2598. this.ctx.drawImage(imageContainer.image, sx, sy, sw, sh, dx, dy, dw, dh)
  2599. }
  2600. };
  2601. CanvasRenderer.prototype.clip = function(shapes, callback, context) {
  2602. this.ctx.save();
  2603. shapes.filter(hasEntries).forEach(function(shape) {
  2604. this.shape(shape).clip()
  2605. }, this);
  2606. callback.call(context);
  2607. this.ctx.restore()
  2608. };
  2609. CanvasRenderer.prototype.shape = function(shape) {
  2610. this.ctx.beginPath();
  2611. shape.forEach(function(point, index) {
  2612. if (point[0] === "rect") {
  2613. this.ctx.rect.apply(this.ctx, point.slice(1))
  2614. } else {
  2615. this.ctx[(index === 0) ? "moveTo" : point[0] + "To"].apply(this.ctx, point.slice(1))
  2616. }
  2617. }, this);
  2618. this.ctx.closePath();
  2619. return this.ctx
  2620. };
  2621. CanvasRenderer.prototype.font = function(color, style, variant, weight, size, family) {
  2622. this.setFillStyle(color).font = [style, variant, weight, size, family].join(" ").split(",")[0]
  2623. };
  2624. CanvasRenderer.prototype.fontShadow = function(color, offsetX, offsetY, blur) {
  2625. this.setVariable("shadowColor", color.toString()).setVariable("shadowOffsetY", offsetX).setVariable("shadowOffsetX", offsetY).setVariable("shadowBlur", blur)
  2626. };
  2627. CanvasRenderer.prototype.clearShadow = function() {
  2628. this.setVariable("shadowColor", "rgba(0,0,0,0)")
  2629. };
  2630. CanvasRenderer.prototype.setOpacity = function(opacity) {
  2631. this.ctx.globalAlpha = opacity
  2632. };
  2633. CanvasRenderer.prototype.setTransform = function(transform) {
  2634. this.ctx.translate(transform.origin[0], transform.origin[1]);
  2635. this.ctx.transform.apply(this.ctx, transform.matrix);
  2636. this.ctx.translate(-transform.origin[0], -transform.origin[1])
  2637. };
  2638. CanvasRenderer.prototype.setVariable = function(property, value) {
  2639. if (this.variables[property] !== value) {
  2640. this.variables[property] = this.ctx[property] = value
  2641. }
  2642. return this
  2643. };
  2644. CanvasRenderer.prototype.text = function(text, left, bottom) {
  2645. this.ctx.fillText(text, left, bottom)
  2646. };
  2647. CanvasRenderer.prototype.backgroundRepeatShape = function(imageContainer, backgroundPosition, size, bounds, left, top, width, height, borderData) {
  2648. var shape = [
  2649. ["line", Math.round(left), Math.round(top)],
  2650. ["line", Math.round(left + width), Math.round(top)],
  2651. ["line", Math.round(left + width), Math.round(height + top)],
  2652. ["line", Math.round(left), Math.round(height + top)]
  2653. ];
  2654. this.clip([shape], function() {
  2655. this.renderBackgroundRepeat(imageContainer, backgroundPosition, size, bounds, borderData[3], borderData[0])
  2656. }, this)
  2657. };
  2658. CanvasRenderer.prototype.renderBackgroundRepeat = function(imageContainer, backgroundPosition, size, bounds, borderLeft, borderTop) {
  2659. var offsetX = Math.round(bounds.left + backgroundPosition.left + borderLeft),
  2660. offsetY = Math.round(bounds.top + backgroundPosition.top + borderTop);
  2661. this.setFillStyle(this.ctx.createPattern(this.resizeImage(imageContainer, size), "repeat"));
  2662. this.ctx.translate(offsetX, offsetY);
  2663. this.ctx.fill();
  2664. this.ctx.translate(-offsetX, -offsetY)
  2665. };
  2666. CanvasRenderer.prototype.renderBackgroundGradient = function(gradientImage, bounds) {
  2667. if (gradientImage instanceof LinearGradientContainer) {
  2668. var gradient = this.ctx.createLinearGradient(bounds.left + bounds.width * gradientImage.x0, bounds.top + bounds.height * gradientImage.y0, bounds.left + bounds.width * gradientImage.x1, bounds.top + bounds.height * gradientImage.y1);
  2669. gradientImage.colorStops.forEach(function(colorStop) {
  2670. gradient.addColorStop(colorStop.stop, colorStop.color.toString())
  2671. });
  2672. this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, gradient)
  2673. }
  2674. };
  2675. CanvasRenderer.prototype.resizeImage = function(imageContainer, size) {
  2676. var image = imageContainer.image;
  2677. if (image.width === size.width && image.height === size.height) {
  2678. return image
  2679. }
  2680. var ctx, canvas = document.createElement('canvas');
  2681. canvas.width = size.width;
  2682. canvas.height = size.height;
  2683. ctx = canvas.getContext("2d");
  2684. ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, size.width, size.height);
  2685. return canvas
  2686. };
  2687.  
  2688. function hasEntries(array) {
  2689. return array.length > 0
  2690. }
  2691. module.exports = CanvasRenderer
  2692. }, {
  2693. "../lineargradientcontainer": 12,
  2694. "../log": 13,
  2695. "../renderer": 19
  2696. }],
  2697. 21: [function(_dereq_, module, exports) {
  2698. var NodeContainer = _dereq_('./nodecontainer');
  2699.  
  2700. function StackingContext(hasOwnStacking, opacity, element, parent) {
  2701. NodeContainer.call(this, element, parent);
  2702. this.ownStacking = hasOwnStacking;
  2703. this.contexts = [];
  2704. this.children = [];
  2705. this.opacity = (this.parent ? this.parent.stack.opacity : 1) * opacity
  2706. }
  2707. StackingContext.prototype = Object.create(NodeContainer.prototype);
  2708. StackingContext.prototype.getParentStack = function(context) {
  2709. var parentStack = (this.parent) ? this.parent.stack : null;
  2710. return parentStack ? (parentStack.ownStacking ? parentStack : parentStack.getParentStack(context)) : context.stack
  2711. };
  2712. module.exports = StackingContext
  2713. }, {
  2714. "./nodecontainer": 14
  2715. }],
  2716. 22: [function(_dereq_, module, exports) {
  2717. function Support(document) {
  2718. this.rangeBounds = this.testRangeBounds(document);
  2719. this.cors = this.testCORS();
  2720. this.svg = this.testSVG()
  2721. }
  2722. Support.prototype.testRangeBounds = function(document) {
  2723. var range, testElement, rangeBounds, rangeHeight, support = false;
  2724. if (document.createRange) {
  2725. range = document.createRange();
  2726. if (range.getBoundingClientRect) {
  2727. testElement = document.createElement('boundtest');
  2728. testElement.style.height = "123px";
  2729. testElement.style.display = "block";
  2730. document.body.appendChild(testElement);
  2731. range.selectNode(testElement);
  2732. rangeBounds = range.getBoundingClientRect();
  2733. rangeHeight = rangeBounds.height;
  2734. if (rangeHeight === 123) {
  2735. support = true
  2736. }
  2737. document.body.removeChild(testElement)
  2738. }
  2739. }
  2740. return support
  2741. };
  2742. Support.prototype.testCORS = function() {
  2743. return typeof((new Image()).crossOrigin) !== "undefined"
  2744. };
  2745. Support.prototype.testSVG = function() {
  2746. var img = new Image();
  2747. var canvas = document.createElement("canvas");
  2748. var ctx = canvas.getContext("2d");
  2749. img.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";
  2750. try {
  2751. ctx.drawImage(img, 0, 0);
  2752. canvas.toDataURL()
  2753. } catch (e) {
  2754. return false
  2755. }
  2756. return true
  2757. };
  2758. module.exports = Support
  2759. }, {}],
  2760. 23: [function(_dereq_, module, exports) {
  2761. var XHR = _dereq_('./xhr');
  2762. var decode64 = _dereq_('./utils').decode64;
  2763.  
  2764. function SVGContainer(src) {
  2765. this.src = src;
  2766. this.image = null;
  2767. var self = this;
  2768. this.promise = this.hasFabric().then(function() {
  2769. return (self.isInline(src) ? Promise.resolve(self.inlineFormatting(src)) : XHR(src))
  2770. }).then(function(svg) {
  2771. return new Promise(function(resolve) {
  2772. window.html2canvas.svg.fabric.loadSVGFromString(svg, self.createCanvas.call(self, resolve))
  2773. })
  2774. })
  2775. }
  2776. SVGContainer.prototype.hasFabric = function() {
  2777. return !window.html2canvas.svg || !window.html2canvas.svg.fabric ? Promise.reject(new Error("html2canvas.svg.js is not loaded, cannot render svg")) : Promise.resolve()
  2778. };
  2779. SVGContainer.prototype.inlineFormatting = function(src) {
  2780. return (/^data:image\/svg\+xml;base64,/.test(src)) ? this.decode64(this.removeContentType(src)) : this.removeContentType(src)
  2781. };
  2782. SVGContainer.prototype.removeContentType = function(src) {
  2783. return src.replace(/^data:image\/svg\+xml(;base64)?,/, '')
  2784. };
  2785. SVGContainer.prototype.isInline = function(src) {
  2786. return (/^data:image\/svg\+xml/i.test(src))
  2787. };
  2788. SVGContainer.prototype.createCanvas = function(resolve) {
  2789. var self = this;
  2790. return function(objects, options) {
  2791. var canvas = new window.html2canvas.svg.fabric.StaticCanvas('c');
  2792. self.image = canvas.lowerCanvasEl;
  2793. canvas.setWidth(options.width).setHeight(options.height).add(window.html2canvas.svg.fabric.util.groupSVGElements(objects, options)).renderAll();
  2794. resolve(canvas.lowerCanvasEl)
  2795. }
  2796. };
  2797. SVGContainer.prototype.decode64 = function(str) {
  2798. return (typeof(window.atob) === "function") ? window.atob(str) : decode64(str)
  2799. };
  2800. module.exports = SVGContainer
  2801. }, {
  2802. "./utils": 26,
  2803. "./xhr": 28
  2804. }],
  2805. 24: [function(_dereq_, module, exports) {
  2806. var SVGContainer = _dereq_('./svgcontainer');
  2807.  
  2808. function SVGNodeContainer(node, _native) {
  2809. this.src = node;
  2810. this.image = null;
  2811. var self = this;
  2812. this.promise = _native ? new Promise(function(resolve, reject) {
  2813. self.image = new Image();
  2814. self.image.onload = resolve;
  2815. self.image.onerror = reject;
  2816. self.image.src = "data:image/svg+xml," + (new XMLSerializer()).serializeToString(node);
  2817. if (self.image.complete === true) {
  2818. resolve(self.image)
  2819. }
  2820. }) : this.hasFabric().then(function() {
  2821. return new Promise(function(resolve) {
  2822. window.html2canvas.svg.fabric.parseSVGDocument(node, self.createCanvas.call(self, resolve))
  2823. })
  2824. })
  2825. }
  2826. SVGNodeContainer.prototype = Object.create(SVGContainer.prototype);
  2827. module.exports = SVGNodeContainer
  2828. }, {
  2829. "./svgcontainer": 23
  2830. }],
  2831. 25: [function(_dereq_, module, exports) {
  2832. var NodeContainer = _dereq_('./nodecontainer');
  2833.  
  2834. function TextContainer(node, parent) {
  2835. NodeContainer.call(this, node, parent)
  2836. }
  2837. TextContainer.prototype = Object.create(NodeContainer.prototype);
  2838. TextContainer.prototype.applyTextTransform = function() {
  2839. this.node.data = this.transform(this.parent.css("textTransform"))
  2840. };
  2841. TextContainer.prototype.transform = function(transform) {
  2842. var text = this.node.data;
  2843. switch (transform) {
  2844. case "lowercase":
  2845. return text.toLowerCase();
  2846. case "capitalize":
  2847. return text.replace(/(^|\s|:|-|\(|\))([a-z])/g, capitalize);
  2848. case "uppercase":
  2849. return text.toUpperCase();
  2850. default:
  2851. return text
  2852. }
  2853. };
  2854.  
  2855. function capitalize(m, p1, p2) {
  2856. if (m.length > 0) {
  2857. return p1 + p2.toUpperCase()
  2858. }
  2859. }
  2860. module.exports = TextContainer
  2861. }, {
  2862. "./nodecontainer": 14
  2863. }],
  2864. 26: [function(_dereq_, module, exports) {
  2865. exports.smallImage = function smallImage() {
  2866. return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
  2867. };
  2868. exports.bind = function(callback, context) {
  2869. return function() {
  2870. return callback.apply(context, arguments)
  2871. }
  2872. };
  2873. exports.decode64 = function(base64) {
  2874. var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  2875. var len = base64.length,
  2876. i, encoded1, encoded2, encoded3, encoded4, byte1, byte2, byte3;
  2877. var output = "";
  2878. for (i = 0; i < len; i += 4) {
  2879. encoded1 = chars.indexOf(base64[i]);
  2880. encoded2 = chars.indexOf(base64[i + 1]);
  2881. encoded3 = chars.indexOf(base64[i + 2]);
  2882. encoded4 = chars.indexOf(base64[i + 3]);
  2883. byte1 = (encoded1 << 2) | (encoded2 >> 4);
  2884. byte2 = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  2885. byte3 = ((encoded3 & 3) << 6) | encoded4;
  2886. if (encoded3 === 64) {
  2887. output += String.fromCharCode(byte1)
  2888. } else if (encoded4 === 64 || encoded4 === -1) {
  2889. output += String.fromCharCode(byte1, byte2)
  2890. } else {
  2891. output += String.fromCharCode(byte1, byte2, byte3)
  2892. }
  2893. }
  2894. return output
  2895. };
  2896. exports.getBounds = function(node) {
  2897. if (node.getBoundingClientRect) {
  2898. var clientRect = node.getBoundingClientRect();
  2899. var width = node.offsetWidth == null ? clientRect.width : node.offsetWidth;
  2900. return {
  2901. top: clientRect.top,
  2902. bottom: clientRect.bottom || (clientRect.top + clientRect.height),
  2903. right: clientRect.left + width,
  2904. left: clientRect.left,
  2905. width: width,
  2906. height: node.offsetHeight == null ? clientRect.height : node.offsetHeight
  2907. }
  2908. }
  2909. return {}
  2910. };
  2911. exports.offsetBounds = function(node) {
  2912. var parent = node.offsetParent ? exports.offsetBounds(node.offsetParent) : {
  2913. top: 0,
  2914. left: 0
  2915. };
  2916. return {
  2917. top: node.offsetTop + parent.top,
  2918. bottom: node.offsetTop + node.offsetHeight + parent.top,
  2919. right: node.offsetLeft + parent.left + node.offsetWidth,
  2920. left: node.offsetLeft + parent.left,
  2921. width: node.offsetWidth,
  2922. height: node.offsetHeight
  2923. }
  2924. };
  2925. exports.parseBackgrounds = function(backgroundImage) {
  2926. var whitespace = ' \r\n\t',
  2927. method, definition, prefix, prefix_i, block, results = [],
  2928. mode = 0,
  2929. numParen = 0,
  2930. quote, args;
  2931. var appendResult = function() {
  2932. if (method) {
  2933. if (definition.substr(0, 1) === '"') {
  2934. definition = definition.substr(1, definition.length - 2)
  2935. }
  2936. if (definition) {
  2937. args.push(definition)
  2938. }
  2939. if (method.substr(0, 1) === '-' && (prefix_i = method.indexOf('-', 1) + 1) > 0) {
  2940. prefix = method.substr(0, prefix_i);
  2941. method = method.substr(prefix_i)
  2942. }
  2943. results.push({
  2944. prefix: prefix,
  2945. method: method.toLowerCase(),
  2946. value: block,
  2947. args: args,
  2948. image: null
  2949. })
  2950. }
  2951. args = [];
  2952. method = prefix = definition = block = ''
  2953. };
  2954. args = [];
  2955. method = prefix = definition = block = '';
  2956. backgroundImage.split("").forEach(function(c) {
  2957. if (mode === 0 && whitespace.indexOf(c) > -1) {
  2958. return
  2959. }
  2960. switch (c) {
  2961. case '"':
  2962. if (!quote) {
  2963. quote = c
  2964. } else if (quote === c) {
  2965. quote = null
  2966. }
  2967. break;
  2968. case '(':
  2969. if (quote) {
  2970. break
  2971. } else if (mode === 0) {
  2972. mode = 1;
  2973. block += c;
  2974. return
  2975. } else {
  2976. numParen++
  2977. }
  2978. break;
  2979. case ')':
  2980. if (quote) {
  2981. break
  2982. } else if (mode === 1) {
  2983. if (numParen === 0) {
  2984. mode = 0;
  2985. block += c;
  2986. appendResult();
  2987. return
  2988. } else {
  2989. numParen--
  2990. }
  2991. }
  2992. break;
  2993. case ',':
  2994. if (quote) {
  2995. break
  2996. } else if (mode === 0) {
  2997. appendResult();
  2998. return
  2999. } else if (mode === 1) {
  3000. if (numParen === 0 && !method.match(/^url$/i)) {
  3001. args.push(definition);
  3002. definition = '';
  3003. block += c;
  3004. return
  3005. }
  3006. }
  3007. break
  3008. }
  3009. block += c;
  3010. if (mode === 0) {
  3011. method += c
  3012. } else {
  3013. definition += c
  3014. }
  3015. });
  3016. appendResult();
  3017. return results
  3018. }
  3019. }, {}],
  3020. 27: [function(_dereq_, module, exports) {
  3021. var GradientContainer = _dereq_('./gradientcontainer');
  3022.  
  3023. function WebkitGradientContainer(imageData) {
  3024. GradientContainer.apply(this, arguments);
  3025. this.type = imageData.args[0] === "linear" ? GradientContainer.TYPES.LINEAR : GradientContainer.TYPES.RADIAL
  3026. }
  3027. WebkitGradientContainer.prototype = Object.create(GradientContainer.prototype);
  3028. module.exports = WebkitGradientContainer
  3029. }, {
  3030. "./gradientcontainer": 9
  3031. }],
  3032. 28: [function(_dereq_, module, exports) {
  3033. function XHR(url) {
  3034. return new Promise(function(resolve, reject) {
  3035. var xhr = new XMLHttpRequest();
  3036. xhr.open('GET', url);
  3037. xhr.onload = function() {
  3038. if (xhr.status === 200) {
  3039. resolve(xhr.responseText)
  3040. } else {
  3041. reject(new Error(xhr.statusText))
  3042. }
  3043. };
  3044. xhr.onerror = function() {
  3045. reject(new Error("Network Error"))
  3046. };
  3047. xhr.send()
  3048. })
  3049. }
  3050. module.exports = XHR
  3051. }, {}]
  3052. }, {}, [4])(4)
  3053. });
  3054.  
  3055. function main_searcher(father) {
  3056. var ele = father.getElementsByTagName("div");
  3057. var div_arr = [];
  3058. var div_arr_area = [];
  3059. var main_index;
  3060. var area;
  3061. for (var i = 0, ele_length = ele.length; i < ele_length; i++) {
  3062. if (ele[i].nodeName == "DIV" && ele[i].clientWidth && ele[i].clientHeight) {
  3063. div_arr.push(ele[i]);
  3064. div_arr_area.push(ele[i].clientWidth * ele[i].clientHeight)
  3065. }
  3066. }
  3067. main_index = div_arr_area.indexOf(Math.max.apply(Math, div_arr_area));
  3068. var son = div_arr[main_index];
  3069. var son_area = son.clientWidth * son.clientHeight;
  3070. var father_area = father.clientWidth * father.clientHeight;
  3071. if (son_area > 0.5 * father_area) {
  3072. main_searcher(son)
  3073. } else {
  3074. return son
  3075. }
  3076. }
  3077. function main_div_searcher() {
  3078. var ele = document.getElementsByTagName("div");
  3079. var div_arr = [];
  3080. var div_arr_area = [];
  3081. var main_index;
  3082. var area;
  3083. for (var i = 0, ele_length = ele.length; i < ele_length; i++) {
  3084. if (ele[i].nodeName == "DIV" && ele[i].clientWidth && ele[i].clientHeight) {
  3085. div_arr.push(ele[i]);
  3086. div_arr_area.push(ele[i].clientWidth * ele[i].clientHeight)
  3087. }
  3088. }
  3089. main_index = div_arr_area.indexOf(Math.max.apply(Math, div_arr_area));
  3090. return div_arr[main_index]
  3091. }
  3092. function content_div_searcher(father_div, ratio) {
  3093. var sons = father_div.childNodes;
  3094. for (var i = 0, len = sons.length; i < len; i++) {
  3095. if (sons[i].nodeName == 'DIV' && sons[i].clientWidth && sons[i].clientHeight) {
  3096. if (sons[i].clientWidth * sons[i].clientHeight > ratio * father_div.clientWidth && father_div.clientHeight) {
  3097. content_div_searcher(sons[i], ratio)
  3098. } else {
  3099. return sons[i]
  3100. }
  3101. } else {
  3102. return father_div
  3103. }
  3104. }
  3105. }
  3106. function PDF_button() {
  3107. var btn = document.createElement("input");
  3108. btn.type = "button";
  3109. btn.value = "PDF";
  3110. btn.style = "position:fixed;top:0px;right:0px;";
  3111. btn.onclick = downloadPdf;
  3112. document.body.appendChild(btn)
  3113. }
  3114. function title_searcher() {
  3115. if (document.title) return document.title;
  3116. var title = document.querySelector('h1').innerText || document.querySelector('h2').innerText || document.querySelector('h1').innerText || document.querySelector('h3').innerText || document.querySelector('h4').innerText || document.querySelector('h5').innerText;
  3117. if (title) return title;
  3118. return Math.random().toString(32).slice(2)
  3119. }
  3120. function downloadPdf() {
  3121. html2canvas(document.body, {
  3122. onrendered: function(canvas) {
  3123. var contentWidth = canvas.width;
  3124. var contentHeight = canvas.height;
  3125. var pageHeight = contentWidth / 595.28 * 841.89;
  3126. var leftHeight = contentHeight;
  3127. var position = 20;
  3128. var imgWidth = 595.28;
  3129. var imgHeight = 595.28 / contentWidth * contentHeight;
  3130. var pageData = canvas.toDataURL('image/jpeg', 1.0);
  3131. var pdf = new jsPDF('', 'pt', 'a4');
  3132. if (leftHeight < pageHeight) {
  3133. pdf.addImage(pageData, 'JPEG', 10, 20, imgWidth, imgHeight)
  3134. } else {
  3135. while (leftHeight > 0) {
  3136. pdf.addImage(pageData, 'JPEG', 10, position, imgWidth, imgHeight) leftHeight -= pageHeight;
  3137. position -= 841.89;
  3138. if (leftHeight > 0) {
  3139. pdf.addPage()
  3140. }
  3141. }
  3142. }
  3143. pdf.save('' + title_searcher() + '.pdf')
  3144. }
  3145. })
  3146. }
  3147. PDF_button();