webpage print to PDF

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

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

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