Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 

22474 righe
713 KiB

  1. 'use strict';
  2. /** @license
  3. * jsPDF - PDF Document creation from JavaScript
  4. * Version 1.5.3 Built on 2018-12-27T14:11:50.068Z
  5. * CommitID d93d28db14
  6. *
  7. * Copyright (c) 2010-2016 James Hall <james@parall.ax>, https://github.com/MrRio/jsPDF
  8. * 2010 Aaron Spike, https://github.com/acspike
  9. * 2012 Willow Systems Corporation, willow-systems.com
  10. * 2012 Pablo Hess, https://github.com/pablohess
  11. * 2012 Florian Jenett, https://github.com/fjenett
  12. * 2013 Warren Weckesser, https://github.com/warrenweckesser
  13. * 2013 Youssef Beddad, https://github.com/lifof
  14. * 2013 Lee Driscoll, https://github.com/lsdriscoll
  15. * 2013 Stefan Slonevskiy, https://github.com/stefslon
  16. * 2013 Jeremy Morel, https://github.com/jmorel
  17. * 2013 Christoph Hartmann, https://github.com/chris-rock
  18. * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
  19. * 2014 James Makes, https://github.com/dollaruw
  20. * 2014 Diego Casorran, https://github.com/diegocr
  21. * 2014 Steven Spungin, https://github.com/Flamenco
  22. * 2014 Kenneth Glassey, https://github.com/Gavvers
  23. *
  24. * Licensed under the MIT License
  25. *
  26. * Contributor(s):
  27. * siefkenj, ahwolf, rickygu, Midnith, saintclair, eaparango,
  28. * kim3er, mfo, alnorth, Flamenco
  29. */
  30. function _typeof(obj) {
  31. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  32. _typeof = function (obj) {
  33. return typeof obj;
  34. };
  35. } else {
  36. _typeof = function (obj) {
  37. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  38. };
  39. }
  40. return _typeof(obj);
  41. }
  42. /**
  43. * Creates new jsPDF document object instance.
  44. * @name jsPDF
  45. * @class
  46. * @param orientation {string/Object} Orientation of the first page. Possible values are "portrait" or "landscape" (or shortcuts "p" (Default), "l").<br />
  47. * Can also be an options object.
  48. * @param unit {string} Measurement unit to be used when coordinates are specified.<br />
  49. * Possible values are "pt" (points), "mm" (Default), "cm", "in" or "px".
  50. * @param format {string/Array} The format of the first page. Can be:<ul><li>a0 - a10</li><li>b0 - b10</li><li>c0 - c10</li><li>dl</li><li>letter</li><li>government-letter</li><li>legal</li><li>junior-legal</li><li>ledger</li><li>tabloid</li><li>credit-card</li></ul><br />
  51. * Default is "a4". If you want to use your own format just pass instead of one of the above predefined formats the size as an number-array, e.g. [595.28, 841.89]
  52. * @returns {jsPDF} jsPDF-instance
  53. * @description
  54. * If the first parameter (orientation) is an object, it will be interpreted as an object of named parameters
  55. * ```
  56. * {
  57. * orientation: 'p',
  58. * unit: 'mm',
  59. * format: 'a4',
  60. * hotfixes: [] // an array of hotfix strings to enable
  61. * }
  62. * ```
  63. */
  64. var jsPDF = function (global) {
  65. /**
  66. * jsPDF's Internal PubSub Implementation.
  67. * Backward compatible rewritten on 2014 by
  68. * Diego Casorran, https://github.com/diegocr
  69. *
  70. * @class
  71. * @name PubSub
  72. * @ignore
  73. */
  74. function PubSub(context) {
  75. if (_typeof(context) !== 'object') {
  76. throw new Error('Invalid Context passed to initialize PubSub (jsPDF-module)');
  77. }
  78. var topics = {};
  79. this.subscribe = function (topic, callback, once) {
  80. once = once || false;
  81. if (typeof topic !== 'string' || typeof callback !== 'function' || typeof once !== 'boolean') {
  82. throw new Error('Invalid arguments passed to PubSub.subscribe (jsPDF-module)');
  83. }
  84. if (!topics.hasOwnProperty(topic)) {
  85. topics[topic] = {};
  86. }
  87. var token = Math.random().toString(35);
  88. topics[topic][token] = [callback, !!once];
  89. return token;
  90. };
  91. this.unsubscribe = function (token) {
  92. for (var topic in topics) {
  93. if (topics[topic][token]) {
  94. delete topics[topic][token];
  95. if (Object.keys(topics[topic]).length === 0) {
  96. delete topics[topic];
  97. }
  98. return true;
  99. }
  100. }
  101. return false;
  102. };
  103. this.publish = function (topic) {
  104. if (topics.hasOwnProperty(topic)) {
  105. var args = Array.prototype.slice.call(arguments, 1),
  106. tokens = [];
  107. for (var token in topics[topic]) {
  108. var sub = topics[topic][token];
  109. try {
  110. sub[0].apply(context, args);
  111. } catch (ex) {
  112. if (global.console) {
  113. console.error('jsPDF PubSub Error', ex.message, ex);
  114. }
  115. }
  116. if (sub[1]) tokens.push(token);
  117. }
  118. if (tokens.length) tokens.forEach(this.unsubscribe);
  119. }
  120. };
  121. this.getTopics = function () {
  122. return topics;
  123. };
  124. }
  125. /**
  126. * @constructor
  127. * @private
  128. */
  129. function jsPDF(orientation, unit, format, compressPdf) {
  130. var options = {};
  131. var filters = [];
  132. var userUnit = 1.0;
  133. if (_typeof(orientation) === 'object') {
  134. options = orientation;
  135. orientation = options.orientation;
  136. unit = options.unit || unit;
  137. format = options.format || format;
  138. compressPdf = options.compress || options.compressPdf || compressPdf;
  139. filters = options.filters || (compressPdf === true ? ['FlateEncode'] : filters);
  140. userUnit = typeof options.userUnit === "number" ? Math.abs(options.userUnit) : 1.0;
  141. }
  142. unit = unit || 'mm';
  143. orientation = ('' + (orientation || 'P')).toLowerCase();
  144. var putOnlyUsedFonts = options.putOnlyUsedFonts || true;
  145. var usedFonts = {};
  146. var API = {
  147. internal: {},
  148. __private__: {}
  149. };
  150. API.__private__.PubSub = PubSub;
  151. var pdfVersion = '1.3';
  152. var getPdfVersion = API.__private__.getPdfVersion = function () {
  153. return pdfVersion;
  154. };
  155. var setPdfVersion = API.__private__.setPdfVersion = function (value) {
  156. pdfVersion = value;
  157. }; // Size in pt of various paper formats
  158. var pageFormats = {
  159. 'a0': [2383.94, 3370.39],
  160. 'a1': [1683.78, 2383.94],
  161. 'a2': [1190.55, 1683.78],
  162. 'a3': [841.89, 1190.55],
  163. 'a4': [595.28, 841.89],
  164. 'a5': [419.53, 595.28],
  165. 'a6': [297.64, 419.53],
  166. 'a7': [209.76, 297.64],
  167. 'a8': [147.40, 209.76],
  168. 'a9': [104.88, 147.40],
  169. 'a10': [73.70, 104.88],
  170. 'b0': [2834.65, 4008.19],
  171. 'b1': [2004.09, 2834.65],
  172. 'b2': [1417.32, 2004.09],
  173. 'b3': [1000.63, 1417.32],
  174. 'b4': [708.66, 1000.63],
  175. 'b5': [498.90, 708.66],
  176. 'b6': [354.33, 498.90],
  177. 'b7': [249.45, 354.33],
  178. 'b8': [175.75, 249.45],
  179. 'b9': [124.72, 175.75],
  180. 'b10': [87.87, 124.72],
  181. 'c0': [2599.37, 3676.54],
  182. 'c1': [1836.85, 2599.37],
  183. 'c2': [1298.27, 1836.85],
  184. 'c3': [918.43, 1298.27],
  185. 'c4': [649.13, 918.43],
  186. 'c5': [459.21, 649.13],
  187. 'c6': [323.15, 459.21],
  188. 'c7': [229.61, 323.15],
  189. 'c8': [161.57, 229.61],
  190. 'c9': [113.39, 161.57],
  191. 'c10': [79.37, 113.39],
  192. 'dl': [311.81, 623.62],
  193. 'letter': [612, 792],
  194. 'government-letter': [576, 756],
  195. 'legal': [612, 1008],
  196. 'junior-legal': [576, 360],
  197. 'ledger': [1224, 792],
  198. 'tabloid': [792, 1224],
  199. 'credit-card': [153, 243]
  200. };
  201. var getPageFormats = API.__private__.getPageFormats = function () {
  202. return pageFormats;
  203. };
  204. var getPageFormat = API.__private__.getPageFormat = function (value) {
  205. return pageFormats[value];
  206. };
  207. if (typeof format === "string") {
  208. format = getPageFormat(format);
  209. }
  210. format = format || getPageFormat('a4');
  211. var f2 = API.f2 = API.__private__.f2 = function (number) {
  212. if (isNaN(number)) {
  213. throw new Error('Invalid argument passed to jsPDF.f2');
  214. }
  215. return number.toFixed(2); // Ie, %.2f
  216. };
  217. var f3 = API.__private__.f3 = function (number) {
  218. if (isNaN(number)) {
  219. throw new Error('Invalid argument passed to jsPDF.f3');
  220. }
  221. return number.toFixed(3); // Ie, %.3f
  222. };
  223. var fileId = '00000000000000000000000000000000';
  224. var getFileId = API.__private__.getFileId = function () {
  225. return fileId;
  226. };
  227. var setFileId = API.__private__.setFileId = function (value) {
  228. value = value || "12345678901234567890123456789012".split('').map(function () {
  229. return "ABCDEF0123456789".charAt(Math.floor(Math.random() * 16));
  230. }).join('');
  231. fileId = value;
  232. return fileId;
  233. };
  234. /**
  235. * @name setFileId
  236. * @memberOf jsPDF
  237. * @function
  238. * @instance
  239. * @param {string} value GUID.
  240. * @returns {jsPDF}
  241. */
  242. API.setFileId = function (value) {
  243. setFileId(value);
  244. return this;
  245. };
  246. /**
  247. * @name getFileId
  248. * @memberOf jsPDF
  249. * @function
  250. * @instance
  251. *
  252. * @returns {string} GUID.
  253. */
  254. API.getFileId = function () {
  255. return getFileId();
  256. };
  257. var creationDate;
  258. var convertDateToPDFDate = API.__private__.convertDateToPDFDate = function (parmDate) {
  259. var result = '';
  260. var tzoffset = parmDate.getTimezoneOffset(),
  261. tzsign = tzoffset < 0 ? '+' : '-',
  262. tzhour = Math.floor(Math.abs(tzoffset / 60)),
  263. tzmin = Math.abs(tzoffset % 60),
  264. timeZoneString = [tzsign, padd2(tzhour), "'", padd2(tzmin), "'"].join('');
  265. result = ['D:', parmDate.getFullYear(), padd2(parmDate.getMonth() + 1), padd2(parmDate.getDate()), padd2(parmDate.getHours()), padd2(parmDate.getMinutes()), padd2(parmDate.getSeconds()), timeZoneString].join('');
  266. return result;
  267. };
  268. var convertPDFDateToDate = API.__private__.convertPDFDateToDate = function (parmPDFDate) {
  269. var year = parseInt(parmPDFDate.substr(2, 4), 10);
  270. var month = parseInt(parmPDFDate.substr(6, 2), 10) - 1;
  271. var date = parseInt(parmPDFDate.substr(8, 2), 10);
  272. var hour = parseInt(parmPDFDate.substr(10, 2), 10);
  273. var minutes = parseInt(parmPDFDate.substr(12, 2), 10);
  274. var seconds = parseInt(parmPDFDate.substr(14, 2), 10);
  275. var timeZoneHour = parseInt(parmPDFDate.substr(16, 2), 10);
  276. var timeZoneMinutes = parseInt(parmPDFDate.substr(20, 2), 10);
  277. var resultingDate = new Date(year, month, date, hour, minutes, seconds, 0);
  278. return resultingDate;
  279. };
  280. var setCreationDate = API.__private__.setCreationDate = function (date) {
  281. var tmpCreationDateString;
  282. var regexPDFCreationDate = /^D:(20[0-2][0-9]|203[0-7]|19[7-9][0-9])(0[0-9]|1[0-2])([0-2][0-9]|3[0-1])(0[0-9]|1[0-9]|2[0-3])(0[0-9]|[1-5][0-9])(0[0-9]|[1-5][0-9])(\+0[0-9]|\+1[0-4]|\-0[0-9]|\-1[0-1])\'(0[0-9]|[1-5][0-9])\'?$/;
  283. if (typeof date === "undefined") {
  284. date = new Date();
  285. }
  286. if (_typeof(date) === "object" && Object.prototype.toString.call(date) === "[object Date]") {
  287. tmpCreationDateString = convertDateToPDFDate(date);
  288. } else if (regexPDFCreationDate.test(date)) {
  289. tmpCreationDateString = date;
  290. } else {
  291. throw new Error('Invalid argument passed to jsPDF.setCreationDate');
  292. }
  293. creationDate = tmpCreationDateString;
  294. return creationDate;
  295. };
  296. var getCreationDate = API.__private__.getCreationDate = function (type) {
  297. var result = creationDate;
  298. if (type === "jsDate") {
  299. result = convertPDFDateToDate(creationDate);
  300. }
  301. return result;
  302. };
  303. /**
  304. * @name setCreationDate
  305. * @memberOf jsPDF
  306. * @function
  307. * @instance
  308. * @param {Object} date
  309. * @returns {jsPDF}
  310. */
  311. API.setCreationDate = function (date) {
  312. setCreationDate(date);
  313. return this;
  314. };
  315. /**
  316. * @name getCreationDate
  317. * @memberOf jsPDF
  318. * @function
  319. * @instance
  320. * @param {Object} type
  321. * @returns {Object}
  322. */
  323. API.getCreationDate = function (type) {
  324. return getCreationDate(type);
  325. };
  326. var padd2 = API.__private__.padd2 = function (number) {
  327. return ('0' + parseInt(number)).slice(-2);
  328. };
  329. var outToPages = !1; // switches where out() prints. outToPages true = push to pages obj. outToPages false = doc builder content
  330. var pages = [];
  331. var content = [];
  332. var currentPage;
  333. var content_length = 0;
  334. var customOutputDestination;
  335. var setOutputDestination = API.__private__.setCustomOutputDestination = function (destination) {
  336. customOutputDestination = destination;
  337. };
  338. var resetOutputDestination = API.__private__.resetCustomOutputDestination = function (destination) {
  339. customOutputDestination = undefined;
  340. };
  341. var out = API.__private__.out = function (string) {
  342. var writeArray;
  343. string = typeof string === "string" ? string : string.toString();
  344. if (typeof customOutputDestination === "undefined") {
  345. writeArray = outToPages ? pages[currentPage] : content;
  346. } else {
  347. writeArray = customOutputDestination;
  348. }
  349. writeArray.push(string);
  350. if (!outToPages) {
  351. content_length += string.length + 1;
  352. }
  353. return writeArray;
  354. };
  355. var write = API.__private__.write = function (value) {
  356. return out(arguments.length === 1 ? value.toString() : Array.prototype.join.call(arguments, ' '));
  357. };
  358. var getArrayBuffer = API.__private__.getArrayBuffer = function (data) {
  359. var len = data.length,
  360. ab = new ArrayBuffer(len),
  361. u8 = new Uint8Array(ab);
  362. while (len--) {
  363. u8[len] = data.charCodeAt(len);
  364. }
  365. return ab;
  366. };
  367. var standardFonts = [['Helvetica', "helvetica", "normal", 'WinAnsiEncoding'], ['Helvetica-Bold', "helvetica", "bold", 'WinAnsiEncoding'], ['Helvetica-Oblique', "helvetica", "italic", 'WinAnsiEncoding'], ['Helvetica-BoldOblique', "helvetica", "bolditalic", 'WinAnsiEncoding'], ['Courier', "courier", "normal", 'WinAnsiEncoding'], ['Courier-Bold', "courier", "bold", 'WinAnsiEncoding'], ['Courier-Oblique', "courier", "italic", 'WinAnsiEncoding'], ['Courier-BoldOblique', "courier", "bolditalic", 'WinAnsiEncoding'], ['Times-Roman', "times", "normal", 'WinAnsiEncoding'], ['Times-Bold', "times", "bold", 'WinAnsiEncoding'], ['Times-Italic', "times", "italic", 'WinAnsiEncoding'], ['Times-BoldItalic', "times", "bolditalic", 'WinAnsiEncoding'], ['ZapfDingbats', "zapfdingbats", "normal", null], ['Symbol', "symbol", "normal", null]];
  368. var getStandardFonts = API.__private__.getStandardFonts = function (data) {
  369. return standardFonts;
  370. };
  371. var activeFontSize = options.fontSize || 16;
  372. /**
  373. * Sets font size for upcoming text elements.
  374. *
  375. * @param {number} size Font size in points.
  376. * @function
  377. * @instance
  378. * @returns {jsPDF}
  379. * @memberOf jsPDF
  380. * @name setFontSize
  381. */
  382. var setFontSize = API.__private__.setFontSize = API.setFontSize = function (size) {
  383. activeFontSize = size;
  384. return this;
  385. };
  386. /**
  387. * Gets the fontsize for upcoming text elements.
  388. *
  389. * @function
  390. * @instance
  391. * @returns {number}
  392. * @memberOf jsPDF
  393. * @name getFontSize
  394. */
  395. var getFontSize = API.__private__.getFontSize = API.getFontSize = function () {
  396. return activeFontSize;
  397. };
  398. var R2L = options.R2L || false;
  399. /**
  400. * Set value of R2L functionality.
  401. *
  402. * @param {boolean} value
  403. * @function
  404. * @instance
  405. * @returns {jsPDF} jsPDF-instance
  406. * @memberOf jsPDF
  407. * @name setR2L
  408. */
  409. var setR2L = API.__private__.setR2L = API.setR2L = function (value) {
  410. R2L = value;
  411. return this;
  412. };
  413. /**
  414. * Get value of R2L functionality.
  415. *
  416. * @function
  417. * @instance
  418. * @returns {boolean} jsPDF-instance
  419. * @memberOf jsPDF
  420. * @name getR2L
  421. */
  422. var getR2L = API.__private__.getR2L = API.getR2L = function (value) {
  423. return R2L;
  424. };
  425. var zoomMode; // default: 1;
  426. var setZoomMode = API.__private__.setZoomMode = function (zoom) {
  427. var validZoomModes = [undefined, null, 'fullwidth', 'fullheight', 'fullpage', 'original'];
  428. if (/^\d*\.?\d*\%$/.test(zoom)) {
  429. zoomMode = zoom;
  430. } else if (!isNaN(zoom)) {
  431. zoomMode = parseInt(zoom, 10);
  432. } else if (validZoomModes.indexOf(zoom) !== -1) {
  433. zoomMode = zoom;
  434. } else {
  435. throw new Error('zoom must be Integer (e.g. 2), a percentage Value (e.g. 300%) or fullwidth, fullheight, fullpage, original. "' + zoom + '" is not recognized.');
  436. }
  437. };
  438. var getZoomMode = API.__private__.getZoomMode = function () {
  439. return zoomMode;
  440. };
  441. var pageMode; // default: 'UseOutlines';
  442. var setPageMode = API.__private__.setPageMode = function (pmode) {
  443. var validPageModes = [undefined, null, 'UseNone', 'UseOutlines', 'UseThumbs', 'FullScreen'];
  444. if (validPageModes.indexOf(pmode) == -1) {
  445. throw new Error('Page mode must be one of UseNone, UseOutlines, UseThumbs, or FullScreen. "' + pmode + '" is not recognized.');
  446. }
  447. pageMode = pmode;
  448. };
  449. var getPageMode = API.__private__.getPageMode = function () {
  450. return pageMode;
  451. };
  452. var layoutMode; // default: 'continuous';
  453. var setLayoutMode = API.__private__.setLayoutMode = function (layout) {
  454. var validLayoutModes = [undefined, null, 'continuous', 'single', 'twoleft', 'tworight', 'two'];
  455. if (validLayoutModes.indexOf(layout) == -1) {
  456. throw new Error('Layout mode must be one of continuous, single, twoleft, tworight. "' + layout + '" is not recognized.');
  457. }
  458. layoutMode = layout;
  459. };
  460. var getLayoutMode = API.__private__.getLayoutMode = function () {
  461. return layoutMode;
  462. };
  463. /**
  464. * Set the display mode options of the page like zoom and layout.
  465. *
  466. * @name setDisplayMode
  467. * @memberOf jsPDF
  468. * @function
  469. * @instance
  470. * @param {integer|String} zoom You can pass an integer or percentage as
  471. * a string. 2 will scale the document up 2x, '200%' will scale up by the
  472. * same amount. You can also set it to 'fullwidth', 'fullheight',
  473. * 'fullpage', or 'original'.
  474. *
  475. * Only certain PDF readers support this, such as Adobe Acrobat.
  476. *
  477. * @param {string} layout Layout mode can be: 'continuous' - this is the
  478. * default continuous scroll. 'single' - the single page mode only shows one
  479. * page at a time. 'twoleft' - two column left mode, first page starts on
  480. * the left, and 'tworight' - pages are laid out in two columns, with the
  481. * first page on the right. This would be used for books.
  482. * @param {string} pmode 'UseOutlines' - it shows the
  483. * outline of the document on the left. 'UseThumbs' - shows thumbnails along
  484. * the left. 'FullScreen' - prompts the user to enter fullscreen mode.
  485. *
  486. * @returns {jsPDF}
  487. */
  488. var setDisplayMode = API.__private__.setDisplayMode = API.setDisplayMode = function (zoom, layout, pmode) {
  489. setZoomMode(zoom);
  490. setLayoutMode(layout);
  491. setPageMode(pmode);
  492. return this;
  493. };
  494. var documentProperties = {
  495. 'title': '',
  496. 'subject': '',
  497. 'author': '',
  498. 'keywords': '',
  499. 'creator': ''
  500. };
  501. var getDocumentProperty = API.__private__.getDocumentProperty = function (key) {
  502. if (Object.keys(documentProperties).indexOf(key) === -1) {
  503. throw new Error('Invalid argument passed to jsPDF.getDocumentProperty');
  504. }
  505. return documentProperties[key];
  506. };
  507. var getDocumentProperties = API.__private__.getDocumentProperties = function (properties) {
  508. return documentProperties;
  509. };
  510. /**
  511. * Adds a properties to the PDF document.
  512. *
  513. * @param {Object} A property_name-to-property_value object structure.
  514. * @function
  515. * @instance
  516. * @returns {jsPDF}
  517. * @memberOf jsPDF
  518. * @name setDocumentProperties
  519. */
  520. var setDocumentProperties = API.__private__.setDocumentProperties = API.setProperties = API.setDocumentProperties = function (properties) {
  521. // copying only those properties we can render.
  522. for (var property in documentProperties) {
  523. if (documentProperties.hasOwnProperty(property) && properties[property]) {
  524. documentProperties[property] = properties[property];
  525. }
  526. }
  527. return this;
  528. };
  529. var setDocumentProperty = API.__private__.setDocumentProperty = function (key, value) {
  530. if (Object.keys(documentProperties).indexOf(key) === -1) {
  531. throw new Error('Invalid arguments passed to jsPDF.setDocumentProperty');
  532. }
  533. return documentProperties[key] = value;
  534. };
  535. var objectNumber = 0; // 'n' Current object number
  536. var offsets = []; // List of offsets. Activated and reset by buildDocument(). Pupulated by various calls buildDocument makes.
  537. var fonts = {}; // collection of font objects, where key is fontKey - a dynamically created label for a given font.
  538. var fontmap = {}; // mapping structure fontName > fontStyle > font key - performance layer. See addFont()
  539. var activeFontKey; // will be string representing the KEY of the font as combination of fontName + fontStyle
  540. var k; // Scale factor
  541. var page = 0;
  542. var pagesContext = [];
  543. var additionalObjects = [];
  544. var events = new PubSub(API);
  545. var hotfixes = options.hotfixes || [];
  546. var newObject = API.__private__.newObject = function () {
  547. var oid = newObjectDeferred();
  548. newObjectDeferredBegin(oid, true);
  549. return oid;
  550. }; // Does not output the object. The caller must call newObjectDeferredBegin(oid) before outputing any data
  551. var newObjectDeferred = API.__private__.newObjectDeferred = function () {
  552. objectNumber++;
  553. offsets[objectNumber] = function () {
  554. return content_length;
  555. };
  556. return objectNumber;
  557. };
  558. var newObjectDeferredBegin = function newObjectDeferredBegin(oid, doOutput) {
  559. doOutput = typeof doOutput === 'boolean' ? doOutput : false;
  560. offsets[oid] = content_length;
  561. if (doOutput) {
  562. out(oid + ' 0 obj');
  563. }
  564. return oid;
  565. }; // Does not output the object until after the pages have been output.
  566. // Returns an object containing the objectId and content.
  567. // All pages have been added so the object ID can be estimated to start right after.
  568. // This does not modify the current objectNumber; It must be updated after the newObjects are output.
  569. var newAdditionalObject = API.__private__.newAdditionalObject = function () {
  570. var objId = newObjectDeferred();
  571. var obj = {
  572. objId: objId,
  573. content: ''
  574. };
  575. additionalObjects.push(obj);
  576. return obj;
  577. };
  578. var rootDictionaryObjId = newObjectDeferred();
  579. var resourceDictionaryObjId = newObjectDeferred(); /////////////////////
  580. // Private functions
  581. /////////////////////
  582. var decodeColorString = API.__private__.decodeColorString = function (color) {
  583. var colorEncoded = color.split(' ');
  584. if (colorEncoded.length === 2 && (colorEncoded[1] === 'g' || colorEncoded[1] === 'G')) {
  585. // convert grayscale value to rgb so that it can be converted to hex for consistency
  586. var floatVal = parseFloat(colorEncoded[0]);
  587. colorEncoded = [floatVal, floatVal, floatVal, 'r'];
  588. }
  589. var colorAsRGB = '#';
  590. for (var i = 0; i < 3; i++) {
  591. colorAsRGB += ('0' + Math.floor(parseFloat(colorEncoded[i]) * 255).toString(16)).slice(-2);
  592. }
  593. return colorAsRGB;
  594. };
  595. var encodeColorString = API.__private__.encodeColorString = function (options) {
  596. var color;
  597. if (typeof options === "string") {
  598. options = {
  599. ch1: options
  600. };
  601. }
  602. var ch1 = options.ch1;
  603. var ch2 = options.ch2;
  604. var ch3 = options.ch3;
  605. var ch4 = options.ch4;
  606. var precision = options.precision;
  607. var letterArray = options.pdfColorType === "draw" ? ['G', 'RG', 'K'] : ['g', 'rg', 'k'];
  608. if (typeof ch1 === "string" && ch1.charAt(0) !== '#') {
  609. var rgbColor = new RGBColor(ch1);
  610. if (rgbColor.ok) {
  611. ch1 = rgbColor.toHex();
  612. } else if (!/^\d*\.?\d*$/.test(ch1)) {
  613. throw new Error('Invalid color "' + ch1 + '" passed to jsPDF.encodeColorString.');
  614. }
  615. } //convert short rgb to long form
  616. if (typeof ch1 === "string" && /^#[0-9A-Fa-f]{3}$/.test(ch1)) {
  617. ch1 = '#' + ch1[1] + ch1[1] + ch1[2] + ch1[2] + ch1[3] + ch1[3];
  618. }
  619. if (typeof ch1 === "string" && /^#[0-9A-Fa-f]{6}$/.test(ch1)) {
  620. var hex = parseInt(ch1.substr(1), 16);
  621. ch1 = hex >> 16 & 255;
  622. ch2 = hex >> 8 & 255;
  623. ch3 = hex & 255;
  624. }
  625. if (typeof ch2 === "undefined" || typeof ch4 === "undefined" && ch1 === ch2 && ch2 === ch3) {
  626. // Gray color space.
  627. if (typeof ch1 === "string") {
  628. color = ch1 + " " + letterArray[0];
  629. } else {
  630. switch (options.precision) {
  631. case 2:
  632. color = f2(ch1 / 255) + " " + letterArray[0];
  633. break;
  634. case 3:
  635. default:
  636. color = f3(ch1 / 255) + " " + letterArray[0];
  637. }
  638. }
  639. } else if (typeof ch4 === "undefined" || _typeof(ch4) === "object") {
  640. // assume RGBA
  641. if (ch4 && !isNaN(ch4.a)) {
  642. //TODO Implement transparency.
  643. //WORKAROUND use white for now, if transparent, otherwise handle as rgb
  644. if (ch4.a === 0) {
  645. color = ['1.000', '1.000', '1.000', letterArray[1]].join(" ");
  646. return color;
  647. }
  648. } // assume RGB
  649. if (typeof ch1 === "string") {
  650. color = [ch1, ch2, ch3, letterArray[1]].join(" ");
  651. } else {
  652. switch (options.precision) {
  653. case 2:
  654. color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), letterArray[1]].join(" ");
  655. break;
  656. default:
  657. case 3:
  658. color = [f3(ch1 / 255), f3(ch2 / 255), f3(ch3 / 255), letterArray[1]].join(" ");
  659. }
  660. }
  661. } else {
  662. // assume CMYK
  663. if (typeof ch1 === 'string') {
  664. color = [ch1, ch2, ch3, ch4, letterArray[2]].join(" ");
  665. } else {
  666. switch (options.precision) {
  667. case 2:
  668. color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), f2(ch4 / 255), letterArray[2]].join(" ");
  669. break;
  670. case 3:
  671. default:
  672. color = [f3(ch1 / 255), f3(ch2 / 255), f3(ch3 / 255), f3(ch4 / 255), letterArray[2]].join(" ");
  673. }
  674. }
  675. }
  676. return color;
  677. };
  678. var getFilters = API.__private__.getFilters = function () {
  679. return filters;
  680. };
  681. var putStream = API.__private__.putStream = function (options) {
  682. options = options || {};
  683. var data = options.data || '';
  684. var filters = options.filters || getFilters();
  685. var alreadyAppliedFilters = options.alreadyAppliedFilters || [];
  686. var addLength1 = options.addLength1 || false;
  687. var valueOfLength1 = data.length;
  688. var processedData = {};
  689. if (filters === true) {
  690. filters = ['FlateEncode'];
  691. }
  692. var keyValues = options.additionalKeyValues || [];
  693. if (typeof jsPDF.API.processDataByFilters !== 'undefined') {
  694. processedData = jsPDF.API.processDataByFilters(data, filters);
  695. } else {
  696. processedData = {
  697. data: data,
  698. reverseChain: []
  699. };
  700. }
  701. var filterAsString = processedData.reverseChain + (Array.isArray(alreadyAppliedFilters) ? alreadyAppliedFilters.join(' ') : alreadyAppliedFilters.toString());
  702. if (processedData.data.length !== 0) {
  703. keyValues.push({
  704. key: 'Length',
  705. value: processedData.data.length
  706. });
  707. if (addLength1 === true) {
  708. keyValues.push({
  709. key: 'Length1',
  710. value: valueOfLength1
  711. });
  712. }
  713. }
  714. if (filterAsString.length != 0) {
  715. //if (filters.length === 0 && alreadyAppliedFilters.length === 1 && typeof alreadyAppliedFilters !== "undefined") {
  716. if (filterAsString.split('/').length - 1 === 1) {
  717. keyValues.push({
  718. key: 'Filter',
  719. value: filterAsString
  720. });
  721. } else {
  722. keyValues.push({
  723. key: 'Filter',
  724. value: '[' + filterAsString + ']'
  725. });
  726. }
  727. }
  728. out('<<');
  729. for (var i = 0; i < keyValues.length; i++) {
  730. out('/' + keyValues[i].key + ' ' + keyValues[i].value);
  731. }
  732. out('>>');
  733. if (processedData.data.length !== 0) {
  734. out('stream');
  735. out(processedData.data);
  736. out('endstream');
  737. }
  738. };
  739. var putPage = API.__private__.putPage = function (page) {
  740. var mediaBox = page.mediaBox;
  741. var pageNumber = page.number;
  742. var data = page.data;
  743. var pageObjectNumber = page.objId;
  744. var pageContentsObjId = page.contentsObjId;
  745. newObjectDeferredBegin(pageObjectNumber, true);
  746. var wPt = pagesContext[currentPage].mediaBox.topRightX - pagesContext[currentPage].mediaBox.bottomLeftX;
  747. var hPt = pagesContext[currentPage].mediaBox.topRightY - pagesContext[currentPage].mediaBox.bottomLeftY;
  748. out('<</Type /Page');
  749. out('/Parent ' + page.rootDictionaryObjId + ' 0 R');
  750. out('/Resources ' + page.resourceDictionaryObjId + ' 0 R');
  751. out('/MediaBox [' + parseFloat(f2(page.mediaBox.bottomLeftX)) + ' ' + parseFloat(f2(page.mediaBox.bottomLeftY)) + ' ' + f2(page.mediaBox.topRightX) + ' ' + f2(page.mediaBox.topRightY) + ']');
  752. if (page.cropBox !== null) {
  753. out('/CropBox [' + f2(page.cropBox.bottomLeftX) + ' ' + f2(page.cropBox.bottomLeftY) + ' ' + f2(page.cropBox.topRightX) + ' ' + f2(page.cropBox.topRightY) + ']');
  754. }
  755. if (page.bleedBox !== null) {
  756. out('/BleedBox [' + f2(page.bleedBox.bottomLeftX) + ' ' + f2(page.bleedBox.bottomLeftY) + ' ' + f2(page.bleedBox.topRightX) + ' ' + f2(page.bleedBox.topRightY) + ']');
  757. }
  758. if (page.trimBox !== null) {
  759. out('/TrimBox [' + f2(page.trimBox.bottomLeftX) + ' ' + f2(page.trimBox.bottomLeftY) + ' ' + f2(page.trimBox.topRightX) + ' ' + f2(page.trimBox.topRightY) + ']');
  760. }
  761. if (page.artBox !== null) {
  762. out('/ArtBox [' + f2(page.artBox.bottomLeftX) + ' ' + f2(page.artBox.bottomLeftY) + ' ' + f2(page.artBox.topRightX) + ' ' + f2(page.artBox.topRightY) + ']');
  763. }
  764. if (typeof page.userUnit === "number" && page.userUnit !== 1.0) {
  765. out('/UserUnit ' + page.userUnit);
  766. }
  767. events.publish('putPage', {
  768. objId: pageObjectNumber,
  769. pageContext: pagesContext[pageNumber],
  770. pageNumber: pageNumber,
  771. page: data
  772. });
  773. out('/Contents ' + pageContentsObjId + ' 0 R');
  774. out('>>');
  775. out('endobj'); // Page content
  776. var pageContent = data.join('\n');
  777. newObjectDeferredBegin(pageContentsObjId, true);
  778. putStream({
  779. data: pageContent,
  780. filters: getFilters()
  781. });
  782. out('endobj');
  783. return pageObjectNumber;
  784. };
  785. var putPages = API.__private__.putPages = function () {
  786. var n,
  787. i,
  788. pageObjectNumbers = [];
  789. for (n = 1; n <= page; n++) {
  790. pagesContext[n].objId = newObjectDeferred();
  791. pagesContext[n].contentsObjId = newObjectDeferred();
  792. }
  793. for (n = 1; n <= page; n++) {
  794. pageObjectNumbers.push(putPage({
  795. number: n,
  796. data: pages[n],
  797. objId: pagesContext[n].objId,
  798. contentsObjId: pagesContext[n].contentsObjId,
  799. mediaBox: pagesContext[n].mediaBox,
  800. cropBox: pagesContext[n].cropBox,
  801. bleedBox: pagesContext[n].bleedBox,
  802. trimBox: pagesContext[n].trimBox,
  803. artBox: pagesContext[n].artBox,
  804. userUnit: pagesContext[n].userUnit,
  805. rootDictionaryObjId: rootDictionaryObjId,
  806. resourceDictionaryObjId: resourceDictionaryObjId
  807. }));
  808. }
  809. newObjectDeferredBegin(rootDictionaryObjId, true);
  810. out('<</Type /Pages');
  811. var kids = '/Kids [';
  812. for (i = 0; i < page; i++) {
  813. kids += pageObjectNumbers[i] + ' 0 R ';
  814. }
  815. out(kids + ']');
  816. out('/Count ' + page);
  817. out('>>');
  818. out('endobj');
  819. events.publish('postPutPages');
  820. };
  821. var putFont = function putFont(font) {
  822. events.publish('putFont', {
  823. font: font,
  824. out: out,
  825. newObject: newObject,
  826. putStream: putStream
  827. });
  828. if (font.isAlreadyPutted !== true) {
  829. font.objectNumber = newObject();
  830. out('<<');
  831. out('/Type /Font');
  832. out('/BaseFont /' + font.postScriptName);
  833. out('/Subtype /Type1');
  834. if (typeof font.encoding === 'string') {
  835. out('/Encoding /' + font.encoding);
  836. }
  837. out('/FirstChar 32');
  838. out('/LastChar 255');
  839. out('>>');
  840. out('endobj');
  841. }
  842. };
  843. var putFonts = function putFonts() {
  844. for (var fontKey in fonts) {
  845. if (fonts.hasOwnProperty(fontKey)) {
  846. if (putOnlyUsedFonts === false || putOnlyUsedFonts === true && usedFonts.hasOwnProperty(fontKey)) {
  847. putFont(fonts[fontKey]);
  848. }
  849. }
  850. }
  851. };
  852. var putResourceDictionary = function putResourceDictionary() {
  853. out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
  854. out('/Font <<'); // Do this for each font, the '1' bit is the index of the font
  855. for (var fontKey in fonts) {
  856. if (fonts.hasOwnProperty(fontKey)) {
  857. if (putOnlyUsedFonts === false || putOnlyUsedFonts === true && usedFonts.hasOwnProperty(fontKey)) {
  858. out('/' + fontKey + ' ' + fonts[fontKey].objectNumber + ' 0 R');
  859. }
  860. }
  861. }
  862. out('>>');
  863. out('/XObject <<');
  864. events.publish('putXobjectDict');
  865. out('>>');
  866. };
  867. var putResources = function putResources() {
  868. putFonts();
  869. events.publish('putResources');
  870. newObjectDeferredBegin(resourceDictionaryObjId, true);
  871. out('<<');
  872. putResourceDictionary();
  873. out('>>');
  874. out('endobj');
  875. events.publish('postPutResources');
  876. };
  877. var putAdditionalObjects = function putAdditionalObjects() {
  878. events.publish('putAdditionalObjects');
  879. for (var i = 0; i < additionalObjects.length; i++) {
  880. var obj = additionalObjects[i];
  881. newObjectDeferredBegin(obj.objId, true);
  882. out(obj.content);
  883. out('endobj');
  884. }
  885. events.publish('postPutAdditionalObjects');
  886. };
  887. var addToFontDictionary = function addToFontDictionary(fontKey, fontName, fontStyle) {
  888. // this is mapping structure for quick font key lookup.
  889. // returns the KEY of the font (ex: "F1") for a given
  890. // pair of font name and type (ex: "Arial". "Italic")
  891. if (!fontmap.hasOwnProperty(fontName)) {
  892. fontmap[fontName] = {};
  893. }
  894. fontmap[fontName][fontStyle] = fontKey;
  895. };
  896. var addFont = function addFont(postScriptName, fontName, fontStyle, encoding, isStandardFont) {
  897. isStandardFont = isStandardFont || false;
  898. var fontKey = 'F' + (Object.keys(fonts).length + 1).toString(10),
  899. // This is FontObject
  900. font = {
  901. 'id': fontKey,
  902. 'postScriptName': postScriptName,
  903. 'fontName': fontName,
  904. 'fontStyle': fontStyle,
  905. 'encoding': encoding,
  906. 'isStandardFont': isStandardFont,
  907. 'metadata': {}
  908. };
  909. var instance = this;
  910. events.publish('addFont', {
  911. font: font,
  912. instance: instance
  913. });
  914. if (fontKey !== undefined) {
  915. fonts[fontKey] = font;
  916. addToFontDictionary(fontKey, fontName, fontStyle);
  917. }
  918. return fontKey;
  919. };
  920. var addFonts = function addFonts(arrayOfFonts) {
  921. for (var i = 0, l = standardFonts.length; i < l; i++) {
  922. var fontKey = addFont(arrayOfFonts[i][0], arrayOfFonts[i][1], arrayOfFonts[i][2], standardFonts[i][3], true);
  923. usedFonts[fontKey] = true; // adding aliases for standard fonts, this time matching the capitalization
  924. var parts = arrayOfFonts[i][0].split('-');
  925. addToFontDictionary(fontKey, parts[0], parts[1] || '');
  926. }
  927. events.publish('addFonts', {
  928. fonts: fonts,
  929. dictionary: fontmap
  930. });
  931. };
  932. var SAFE = function __safeCall(fn) {
  933. fn.foo = function __safeCallWrapper() {
  934. try {
  935. return fn.apply(this, arguments);
  936. } catch (e) {
  937. var stack = e.stack || '';
  938. if (~stack.indexOf(' at ')) stack = stack.split(" at ")[1];
  939. var m = "Error in function " + stack.split("\n")[0].split('<')[0] + ": " + e.message;
  940. if (global.console) {
  941. global.console.error(m, e);
  942. if (global.alert) alert(m);
  943. } else {
  944. throw new Error(m);
  945. }
  946. }
  947. };
  948. fn.foo.bar = fn;
  949. return fn.foo;
  950. };
  951. var to8bitStream = function to8bitStream(text, flags) {
  952. /**
  953. * PDF 1.3 spec:
  954. * "For text strings encoded in Unicode, the first two bytes must be 254 followed by
  955. * 255, representing the Unicode byte order marker, U+FEFF. (This sequence conflicts
  956. * with the PDFDocEncoding character sequence thorn ydieresis, which is unlikely
  957. * to be a meaningful beginning of a word or phrase.) The remainder of the
  958. * string consists of Unicode character codes, according to the UTF-16 encoding
  959. * specified in the Unicode standard, version 2.0. Commonly used Unicode values
  960. * are represented as 2 bytes per character, with the high-order byte appearing first
  961. * in the string."
  962. *
  963. * In other words, if there are chars in a string with char code above 255, we
  964. * recode the string to UCS2 BE - string doubles in length and BOM is prepended.
  965. *
  966. * HOWEVER!
  967. * Actual *content* (body) text (as opposed to strings used in document properties etc)
  968. * does NOT expect BOM. There, it is treated as a literal GID (Glyph ID)
  969. *
  970. * Because of Adobe's focus on "you subset your fonts!" you are not supposed to have
  971. * a font that maps directly Unicode (UCS2 / UTF16BE) code to font GID, but you could
  972. * fudge it with "Identity-H" encoding and custom CIDtoGID map that mimics Unicode
  973. * code page. There, however, all characters in the stream are treated as GIDs,
  974. * including BOM, which is the reason we need to skip BOM in content text (i.e. that
  975. * that is tied to a font).
  976. *
  977. * To signal this "special" PDFEscape / to8bitStream handling mode,
  978. * API.text() function sets (unless you overwrite it with manual values
  979. * given to API.text(.., flags) )
  980. * flags.autoencode = true
  981. * flags.noBOM = true
  982. *
  983. * ===================================================================================
  984. * `flags` properties relied upon:
  985. * .sourceEncoding = string with encoding label.
  986. * "Unicode" by default. = encoding of the incoming text.
  987. * pass some non-existing encoding name
  988. * (ex: 'Do not touch my strings! I know what I am doing.')
  989. * to make encoding code skip the encoding step.
  990. * .outputEncoding = Either valid PDF encoding name
  991. * (must be supported by jsPDF font metrics, otherwise no encoding)
  992. * or a JS object, where key = sourceCharCode, value = outputCharCode
  993. * missing keys will be treated as: sourceCharCode === outputCharCode
  994. * .noBOM
  995. * See comment higher above for explanation for why this is important
  996. * .autoencode
  997. * See comment higher above for explanation for why this is important
  998. */
  999. var i, l, sourceEncoding, encodingBlock, outputEncoding, newtext, isUnicode, ch, bch;
  1000. flags = flags || {};
  1001. sourceEncoding = flags.sourceEncoding || 'Unicode';
  1002. outputEncoding = flags.outputEncoding; // This 'encoding' section relies on font metrics format
  1003. // attached to font objects by, among others,
  1004. // "Willow Systems' standard_font_metrics plugin"
  1005. // see jspdf.plugin.standard_font_metrics.js for format
  1006. // of the font.metadata.encoding Object.
  1007. // It should be something like
  1008. // .encoding = {'codePages':['WinANSI....'], 'WinANSI...':{code:code, ...}}
  1009. // .widths = {0:width, code:width, ..., 'fof':divisor}
  1010. // .kerning = {code:{previous_char_code:shift, ..., 'fof':-divisor},...}
  1011. if ((flags.autoencode || outputEncoding) && fonts[activeFontKey].metadata && fonts[activeFontKey].metadata[sourceEncoding] && fonts[activeFontKey].metadata[sourceEncoding].encoding) {
  1012. encodingBlock = fonts[activeFontKey].metadata[sourceEncoding].encoding; // each font has default encoding. Some have it clearly defined.
  1013. if (!outputEncoding && fonts[activeFontKey].encoding) {
  1014. outputEncoding = fonts[activeFontKey].encoding;
  1015. } // Hmmm, the above did not work? Let's try again, in different place.
  1016. if (!outputEncoding && encodingBlock.codePages) {
  1017. outputEncoding = encodingBlock.codePages[0]; // let's say, first one is the default
  1018. }
  1019. if (typeof outputEncoding === 'string') {
  1020. outputEncoding = encodingBlock[outputEncoding];
  1021. } // we want output encoding to be a JS Object, where
  1022. // key = sourceEncoding's character code and
  1023. // value = outputEncoding's character code.
  1024. if (outputEncoding) {
  1025. isUnicode = false;
  1026. newtext = [];
  1027. for (i = 0, l = text.length; i < l; i++) {
  1028. ch = outputEncoding[text.charCodeAt(i)];
  1029. if (ch) {
  1030. newtext.push(String.fromCharCode(ch));
  1031. } else {
  1032. newtext.push(text[i]);
  1033. } // since we are looping over chars anyway, might as well
  1034. // check for residual unicodeness
  1035. if (newtext[i].charCodeAt(0) >> 8) {
  1036. /* more than 255 */
  1037. isUnicode = true;
  1038. }
  1039. }
  1040. text = newtext.join('');
  1041. }
  1042. }
  1043. i = text.length; // isUnicode may be set to false above. Hence the triple-equal to undefined
  1044. while (isUnicode === undefined && i !== 0) {
  1045. if (text.charCodeAt(i - 1) >> 8) {
  1046. /* more than 255 */
  1047. isUnicode = true;
  1048. }
  1049. i--;
  1050. }
  1051. if (!isUnicode) {
  1052. return text;
  1053. }
  1054. newtext = flags.noBOM ? [] : [254, 255];
  1055. for (i = 0, l = text.length; i < l; i++) {
  1056. ch = text.charCodeAt(i);
  1057. bch = ch >> 8; // divide by 256
  1058. if (bch >> 8) {
  1059. /* something left after dividing by 256 second time */
  1060. throw new Error("Character at position " + i + " of string '" + text + "' exceeds 16bits. Cannot be encoded into UCS-2 BE");
  1061. }
  1062. newtext.push(bch);
  1063. newtext.push(ch - (bch << 8));
  1064. }
  1065. return String.fromCharCode.apply(undefined, newtext);
  1066. };
  1067. var pdfEscape = API.__private__.pdfEscape = API.pdfEscape = function (text, flags) {
  1068. /**
  1069. * Replace '/', '(', and ')' with pdf-safe versions
  1070. *
  1071. * Doing to8bitStream does NOT make this PDF display unicode text. For that
  1072. * we also need to reference a unicode font and embed it - royal pain in the rear.
  1073. *
  1074. * There is still a benefit to to8bitStream - PDF simply cannot handle 16bit chars,
  1075. * which JavaScript Strings are happy to provide. So, while we still cannot display
  1076. * 2-byte characters property, at least CONDITIONALLY converting (entire string containing)
  1077. * 16bit chars to (USC-2-BE) 2-bytes per char + BOM streams we ensure that entire PDF
  1078. * is still parseable.
  1079. * This will allow immediate support for unicode in document properties strings.
  1080. */
  1081. return to8bitStream(text, flags).replace(/\\/g, '\\\\').replace(/\(/g, '\\(').replace(/\)/g, '\\)');
  1082. };
  1083. var beginPage = API.__private__.beginPage = function (width, height) {
  1084. var tmp; // Dimensions are stored as user units and converted to points on output
  1085. var orientation = typeof height === 'string' && height.toLowerCase();
  1086. if (typeof width === 'string') {
  1087. if (tmp = getPageFormat(width.toLowerCase())) {
  1088. width = tmp[0];
  1089. height = tmp[1];
  1090. }
  1091. }
  1092. if (Array.isArray(width)) {
  1093. height = width[1];
  1094. width = width[0];
  1095. }
  1096. if (isNaN(width) || isNaN(height)) {
  1097. width = format[0];
  1098. height = format[1];
  1099. }
  1100. if (orientation) {
  1101. switch (orientation.substr(0, 1)) {
  1102. case 'l':
  1103. if (height > width) orientation = 's';
  1104. break;
  1105. case 'p':
  1106. if (width > height) orientation = 's';
  1107. break;
  1108. }
  1109. if (orientation === 's') {
  1110. tmp = width;
  1111. width = height;
  1112. height = tmp;
  1113. }
  1114. }
  1115. if (width > 14400 || height > 14400) {
  1116. console.warn('A page in a PDF can not be wider or taller than 14400 userUnit. jsPDF limits the width/height to 14400');
  1117. width = Math.min(14400, width);
  1118. height = Math.min(14400, height);
  1119. }
  1120. format = [width, height];
  1121. outToPages = true;
  1122. pages[++page] = [];
  1123. pagesContext[page] = {
  1124. objId: 0,
  1125. contentsObjId: 0,
  1126. userUnit: Number(userUnit),
  1127. artBox: null,
  1128. bleedBox: null,
  1129. cropBox: null,
  1130. trimBox: null,
  1131. mediaBox: {
  1132. bottomLeftX: 0,
  1133. bottomLeftY: 0,
  1134. topRightX: Number(width),
  1135. topRightY: Number(height)
  1136. }
  1137. };
  1138. _setPage(page);
  1139. };
  1140. var _addPage = function _addPage() {
  1141. beginPage.apply(this, arguments); // Set line width
  1142. setLineWidth(lineWidth); // Set draw color
  1143. out(strokeColor); // resurrecting non-default line caps, joins
  1144. if (lineCapID !== 0) {
  1145. out(lineCapID + ' J');
  1146. }
  1147. if (lineJoinID !== 0) {
  1148. out(lineJoinID + ' j');
  1149. }
  1150. events.publish('addPage', {
  1151. pageNumber: page
  1152. });
  1153. };
  1154. var _deletePage = function _deletePage(n) {
  1155. if (n > 0 && n <= page) {
  1156. pages.splice(n, 1);
  1157. page--;
  1158. if (currentPage > page) {
  1159. currentPage = page;
  1160. }
  1161. this.setPage(currentPage);
  1162. }
  1163. };
  1164. var _setPage = function _setPage(n) {
  1165. if (n > 0 && n <= page) {
  1166. currentPage = n;
  1167. }
  1168. };
  1169. var getNumberOfPages = API.__private__.getNumberOfPages = API.getNumberOfPages = function () {
  1170. return pages.length - 1;
  1171. };
  1172. /**
  1173. * Returns a document-specific font key - a label assigned to a
  1174. * font name + font type combination at the time the font was added
  1175. * to the font inventory.
  1176. *
  1177. * Font key is used as label for the desired font for a block of text
  1178. * to be added to the PDF document stream.
  1179. * @private
  1180. * @function
  1181. * @param fontName {string} can be undefined on "falthy" to indicate "use current"
  1182. * @param fontStyle {string} can be undefined on "falthy" to indicate "use current"
  1183. * @returns {string} Font key.
  1184. * @ignore
  1185. */
  1186. var _getFont = function getFont(fontName, fontStyle, options) {
  1187. var key = undefined,
  1188. fontNameLowerCase;
  1189. options = options || {};
  1190. fontName = fontName !== undefined ? fontName : fonts[activeFontKey].fontName;
  1191. fontStyle = fontStyle !== undefined ? fontStyle : fonts[activeFontKey].fontStyle;
  1192. fontNameLowerCase = fontName.toLowerCase();
  1193. if (fontmap[fontNameLowerCase] !== undefined && fontmap[fontNameLowerCase][fontStyle] !== undefined) {
  1194. key = fontmap[fontNameLowerCase][fontStyle];
  1195. } else if (fontmap[fontName] !== undefined && fontmap[fontName][fontStyle] !== undefined) {
  1196. key = fontmap[fontName][fontStyle];
  1197. } else {
  1198. if (options.disableWarning === false) {
  1199. console.warn("Unable to look up font label for font '" + fontName + "', '" + fontStyle + "'. Refer to getFontList() for available fonts.");
  1200. }
  1201. }
  1202. if (!key && !options.noFallback) {
  1203. key = fontmap['times'][fontStyle];
  1204. if (key == null) {
  1205. key = fontmap['times']['normal'];
  1206. }
  1207. }
  1208. return key;
  1209. };
  1210. var putInfo = API.__private__.putInfo = function () {
  1211. newObject();
  1212. out('<<');
  1213. out('/Producer (jsPDF ' + jsPDF.version + ')');
  1214. for (var key in documentProperties) {
  1215. if (documentProperties.hasOwnProperty(key) && documentProperties[key]) {
  1216. out('/' + key.substr(0, 1).toUpperCase() + key.substr(1) + ' (' + pdfEscape(documentProperties[key]) + ')');
  1217. }
  1218. }
  1219. out('/CreationDate (' + creationDate + ')');
  1220. out('>>');
  1221. out('endobj');
  1222. };
  1223. var putCatalog = API.__private__.putCatalog = function (options) {
  1224. options = options || {};
  1225. var tmpRootDictionaryObjId = options.rootDictionaryObjId || rootDictionaryObjId;
  1226. newObject();
  1227. out('<<');
  1228. out('/Type /Catalog');
  1229. out('/Pages ' + tmpRootDictionaryObjId + ' 0 R'); // PDF13ref Section 7.2.1
  1230. if (!zoomMode) zoomMode = 'fullwidth';
  1231. switch (zoomMode) {
  1232. case 'fullwidth':
  1233. out('/OpenAction [3 0 R /FitH null]');
  1234. break;
  1235. case 'fullheight':
  1236. out('/OpenAction [3 0 R /FitV null]');
  1237. break;
  1238. case 'fullpage':
  1239. out('/OpenAction [3 0 R /Fit]');
  1240. break;
  1241. case 'original':
  1242. out('/OpenAction [3 0 R /XYZ null null 1]');
  1243. break;
  1244. default:
  1245. var pcn = '' + zoomMode;
  1246. if (pcn.substr(pcn.length - 1) === '%') zoomMode = parseInt(zoomMode) / 100;
  1247. if (typeof zoomMode === 'number') {
  1248. out('/OpenAction [3 0 R /XYZ null null ' + f2(zoomMode) + ']');
  1249. }
  1250. }
  1251. if (!layoutMode) layoutMode = 'continuous';
  1252. switch (layoutMode) {
  1253. case 'continuous':
  1254. out('/PageLayout /OneColumn');
  1255. break;
  1256. case 'single':
  1257. out('/PageLayout /SinglePage');
  1258. break;
  1259. case 'two':
  1260. case 'twoleft':
  1261. out('/PageLayout /TwoColumnLeft');
  1262. break;
  1263. case 'tworight':
  1264. out('/PageLayout /TwoColumnRight');
  1265. break;
  1266. }
  1267. if (pageMode) {
  1268. /**
  1269. * A name object specifying how the document should be displayed when opened:
  1270. * UseNone : Neither document outline nor thumbnail images visible -- DEFAULT
  1271. * UseOutlines : Document outline visible
  1272. * UseThumbs : Thumbnail images visible
  1273. * FullScreen : Full-screen mode, with no menu bar, window controls, or any other window visible
  1274. */
  1275. out('/PageMode /' + pageMode);
  1276. }
  1277. events.publish('putCatalog');
  1278. out('>>');
  1279. out('endobj');
  1280. };
  1281. var putTrailer = API.__private__.putTrailer = function () {
  1282. out('trailer');
  1283. out('<<');
  1284. out('/Size ' + (objectNumber + 1));
  1285. out('/Root ' + objectNumber + ' 0 R');
  1286. out('/Info ' + (objectNumber - 1) + ' 0 R');
  1287. out("/ID [ <" + fileId + "> <" + fileId + "> ]");
  1288. out('>>');
  1289. };
  1290. var putHeader = API.__private__.putHeader = function () {
  1291. out('%PDF-' + pdfVersion);
  1292. out("%\xBA\xDF\xAC\xE0");
  1293. };
  1294. var putXRef = API.__private__.putXRef = function () {
  1295. var i = 1;
  1296. var p = "0000000000";
  1297. out('xref');
  1298. out('0 ' + (objectNumber + 1));
  1299. out('0000000000 65535 f ');
  1300. for (i = 1; i <= objectNumber; i++) {
  1301. var offset = offsets[i];
  1302. if (typeof offset === 'function') {
  1303. out((p + offsets[i]()).slice(-10) + ' 00000 n ');
  1304. } else {
  1305. if (typeof offsets[i] !== "undefined") {
  1306. out((p + offsets[i]).slice(-10) + ' 00000 n ');
  1307. } else {
  1308. out('0000000000 00000 n ');
  1309. }
  1310. }
  1311. }
  1312. };
  1313. var buildDocument = API.__private__.buildDocument = function () {
  1314. outToPages = false; // switches out() to content
  1315. //reset fields relevant for objectNumber generation and xref.
  1316. objectNumber = 0;
  1317. content_length = 0;
  1318. content = [];
  1319. offsets = [];
  1320. additionalObjects = [];
  1321. rootDictionaryObjId = newObjectDeferred();
  1322. resourceDictionaryObjId = newObjectDeferred();
  1323. events.publish('buildDocument');
  1324. putHeader();
  1325. putPages();
  1326. putAdditionalObjects();
  1327. putResources();
  1328. putInfo();
  1329. putCatalog();
  1330. var offsetOfXRef = content_length;
  1331. putXRef();
  1332. putTrailer();
  1333. out('startxref');
  1334. out('' + offsetOfXRef);
  1335. out('%%EOF');
  1336. outToPages = true;
  1337. return content.join('\n');
  1338. };
  1339. var getBlob = API.__private__.getBlob = function (data) {
  1340. return new Blob([getArrayBuffer(data)], {
  1341. type: "application/pdf"
  1342. });
  1343. };
  1344. /**
  1345. * Generates the PDF document.
  1346. *
  1347. * If `type` argument is undefined, output is raw body of resulting PDF returned as a string.
  1348. *
  1349. * @param {string} type A string identifying one of the possible output types. Possible values are 'arraybuffer', 'blob', 'bloburi'/'bloburl', 'datauristring'/'dataurlstring', 'datauri'/'dataurl', 'dataurlnewwindow'.
  1350. * @param {Object} options An object providing some additional signalling to PDF generator. Possible options are 'filename'.
  1351. *
  1352. * @function
  1353. * @instance
  1354. * @returns {jsPDF}
  1355. * @memberOf jsPDF
  1356. * @name output
  1357. */
  1358. var output = API.output = API.__private__.output = SAFE(function output(type, options) {
  1359. options = options || {};
  1360. var pdfDocument = buildDocument();
  1361. if (typeof options === "string") {
  1362. options = {
  1363. filename: options
  1364. };
  1365. } else {
  1366. options.filename = options.filename || 'generated.pdf';
  1367. }
  1368. switch (type) {
  1369. case undefined:
  1370. return pdfDocument;
  1371. case 'save':
  1372. API.save(options.filename);
  1373. break;
  1374. case 'arraybuffer':
  1375. return getArrayBuffer(pdfDocument);
  1376. case 'blob':
  1377. return getBlob(pdfDocument);
  1378. case 'bloburi':
  1379. case 'bloburl':
  1380. // Developer is responsible of calling revokeObjectURL
  1381. if (typeof global.URL !== "undefined" && typeof global.URL.createObjectURL === "function") {
  1382. return global.URL && global.URL.createObjectURL(getBlob(pdfDocument)) || void 0;
  1383. } else {
  1384. console.warn('bloburl is not supported by your system, because URL.createObjectURL is not supported by your browser.');
  1385. }
  1386. break;
  1387. case 'datauristring':
  1388. case 'dataurlstring':
  1389. return 'data:application/pdf;filename=' + options.filename + ';base64,' + btoa(pdfDocument);
  1390. case 'dataurlnewwindow':
  1391. var htmlForNewWindow = '<html>' + '<style>html, body { padding: 0; margin: 0; } iframe { width: 100%; height: 100%; border: 0;} </style>' + '<body>' + '<iframe src="' + this.output('datauristring') + '"></iframe>' + '</body></html>';
  1392. var nW = global.open();
  1393. if (nW !== null) {
  1394. nW.document.write(htmlForNewWindow);
  1395. }
  1396. if (nW || typeof safari === "undefined") return nW;
  1397. /* pass through */
  1398. case 'datauri':
  1399. case 'dataurl':
  1400. return global.document.location.href = 'data:application/pdf;filename=' + options.filename + ';base64,' + btoa(pdfDocument);
  1401. default:
  1402. return null;
  1403. }
  1404. });
  1405. /**
  1406. * Used to see if a supplied hotfix was requested when the pdf instance was created.
  1407. * @param {string} hotfixName - The name of the hotfix to check.
  1408. * @returns {boolean}
  1409. */
  1410. var hasHotfix = function hasHotfix(hotfixName) {
  1411. return Array.isArray(hotfixes) === true && hotfixes.indexOf(hotfixName) > -1;
  1412. };
  1413. switch (unit) {
  1414. case 'pt':
  1415. k = 1;
  1416. break;
  1417. case 'mm':
  1418. k = 72 / 25.4;
  1419. break;
  1420. case 'cm':
  1421. k = 72 / 2.54;
  1422. break;
  1423. case 'in':
  1424. k = 72;
  1425. break;
  1426. case 'px':
  1427. if (hasHotfix('px_scaling') == true) {
  1428. k = 72 / 96;
  1429. } else {
  1430. k = 96 / 72;
  1431. }
  1432. break;
  1433. case 'pc':
  1434. k = 12;
  1435. break;
  1436. case 'em':
  1437. k = 12;
  1438. break;
  1439. case 'ex':
  1440. k = 6;
  1441. break;
  1442. default:
  1443. throw new Error('Invalid unit: ' + unit);
  1444. }
  1445. setCreationDate();
  1446. setFileId(); //---------------------------------------
  1447. // Public API
  1448. var getPageInfo = API.__private__.getPageInfo = function (pageNumberOneBased) {
  1449. if (isNaN(pageNumberOneBased) || pageNumberOneBased % 1 !== 0) {
  1450. throw new Error('Invalid argument passed to jsPDF.getPageInfo');
  1451. }
  1452. var objId = pagesContext[pageNumberOneBased].objId;
  1453. return {
  1454. objId: objId,
  1455. pageNumber: pageNumberOneBased,
  1456. pageContext: pagesContext[pageNumberOneBased]
  1457. };
  1458. };
  1459. var getPageInfoByObjId = API.__private__.getPageInfoByObjId = function (objId) {
  1460. for (var pageNumber in pagesContext) {
  1461. if (pagesContext[pageNumber].objId === objId) {
  1462. break;
  1463. }
  1464. }
  1465. if (isNaN(objId) || objId % 1 !== 0) {
  1466. throw new Error('Invalid argument passed to jsPDF.getPageInfoByObjId');
  1467. }
  1468. return getPageInfo(pageNumber);
  1469. };
  1470. var getCurrentPageInfo = API.__private__.getCurrentPageInfo = function () {
  1471. return {
  1472. objId: pagesContext[currentPage].objId,
  1473. pageNumber: currentPage,
  1474. pageContext: pagesContext[currentPage]
  1475. };
  1476. };
  1477. /**
  1478. * Adds (and transfers the focus to) new page to the PDF document.
  1479. * @param format {String/Array} The format of the new page. Can be: <ul><li>a0 - a10</li><li>b0 - b10</li><li>c0 - c10</li><li>dl</li><li>letter</li><li>government-letter</li><li>legal</li><li>junior-legal</li><li>ledger</li><li>tabloid</li><li>credit-card</li></ul><br />
  1480. * Default is "a4". If you want to use your own format just pass instead of one of the above predefined formats the size as an number-array, e.g. [595.28, 841.89]
  1481. * @param orientation {string} Orientation of the new page. Possible values are "portrait" or "landscape" (or shortcuts "p" (Default), "l").
  1482. * @function
  1483. * @instance
  1484. * @returns {jsPDF}
  1485. *
  1486. * @memberOf jsPDF
  1487. * @name addPage
  1488. */
  1489. API.addPage = function () {
  1490. _addPage.apply(this, arguments);
  1491. return this;
  1492. };
  1493. /**
  1494. * Adds (and transfers the focus to) new page to the PDF document.
  1495. * @function
  1496. * @instance
  1497. * @returns {jsPDF}
  1498. *
  1499. * @memberOf jsPDF
  1500. * @name setPage
  1501. * @param {number} page Switch the active page to the page number specified.
  1502. * @example
  1503. * doc = jsPDF()
  1504. * doc.addPage()
  1505. * doc.addPage()
  1506. * doc.text('I am on page 3', 10, 10)
  1507. * doc.setPage(1)
  1508. * doc.text('I am on page 1', 10, 10)
  1509. */
  1510. API.setPage = function () {
  1511. _setPage.apply(this, arguments);
  1512. return this;
  1513. };
  1514. /**
  1515. * @name insertPage
  1516. * @memberOf jsPDF
  1517. *
  1518. * @function
  1519. * @instance
  1520. * @param {Object} beforePage
  1521. * @returns {jsPDF}
  1522. */
  1523. API.insertPage = function (beforePage) {
  1524. this.addPage();
  1525. this.movePage(currentPage, beforePage);
  1526. return this;
  1527. };
  1528. /**
  1529. * @name movePage
  1530. * @memberOf jsPDF
  1531. * @function
  1532. * @instance
  1533. * @param {Object} targetPage
  1534. * @param {Object} beforePage
  1535. * @returns {jsPDF}
  1536. */
  1537. API.movePage = function (targetPage, beforePage) {
  1538. if (targetPage > beforePage) {
  1539. var tmpPages = pages[targetPage];
  1540. var tmpPagesContext = pagesContext[targetPage];
  1541. for (var i = targetPage; i > beforePage; i--) {
  1542. pages[i] = pages[i - 1];
  1543. pagesContext[i] = pagesContext[i - 1];
  1544. }
  1545. pages[beforePage] = tmpPages;
  1546. pagesContext[beforePage] = tmpPagesContext;
  1547. this.setPage(beforePage);
  1548. } else if (targetPage < beforePage) {
  1549. var tmpPages = pages[targetPage];
  1550. var tmpPagesContext = pagesContext[targetPage];
  1551. for (var i = targetPage; i < beforePage; i++) {
  1552. pages[i] = pages[i + 1];
  1553. pagesContext[i] = pagesContext[i + 1];
  1554. }
  1555. pages[beforePage] = tmpPages;
  1556. pagesContext[beforePage] = tmpPagesContext;
  1557. this.setPage(beforePage);
  1558. }
  1559. return this;
  1560. };
  1561. /**
  1562. * Deletes a page from the PDF.
  1563. * @name deletePage
  1564. * @memberOf jsPDF
  1565. * @function
  1566. * @instance
  1567. * @returns {jsPDF}
  1568. */
  1569. API.deletePage = function () {
  1570. _deletePage.apply(this, arguments);
  1571. return this;
  1572. };
  1573. /**
  1574. * Adds text to page. Supports adding multiline text when 'text' argument is an Array of Strings.
  1575. *
  1576. * @function
  1577. * @instance
  1578. * @param {String|Array} text String or array of strings to be added to the page. Each line is shifted one line down per font, spacing settings declared before this call.
  1579. * @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page.
  1580. * @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page.
  1581. * @param {Object} [options] - Collection of settings signaling how the text must be encoded.
  1582. * @param {string} [options.align=left] - The alignment of the text, possible values: left, center, right, justify.
  1583. * @param {string} [options.baseline=alphabetic] - Sets text baseline used when drawing the text, possible values: alphabetic, ideographic, bottom, top, middle.
  1584. * @param {string} [options.angle=0] - Rotate the text counterclockwise. Expects the angle in degree.
  1585. * @param {string} [options.charSpace=0] - The space between each letter.
  1586. * @param {string} [options.lineHeightFactor=1.15] - The lineheight of each line.
  1587. * @param {string} [options.flags] - Flags for to8bitStream.
  1588. * @param {string} [options.flags.noBOM=true] - Don't add BOM to Unicode-text.
  1589. * @param {string} [options.flags.autoencode=true] - Autoencode the Text.
  1590. * @param {string} [options.maxWidth=0] - Split the text by given width, 0 = no split.
  1591. * @param {string} [options.renderingMode=fill] - Set how the text should be rendered, possible values: fill, stroke, fillThenStroke, invisible, fillAndAddForClipping, strokeAndAddPathForClipping, fillThenStrokeAndAddToPathForClipping, addToPathForClipping.
  1592. * @returns {jsPDF}
  1593. * @memberOf jsPDF
  1594. * @name text
  1595. */
  1596. var text = API.__private__.text = API.text = function (text, x, y, options) {
  1597. /**
  1598. * Inserts something like this into PDF
  1599. * BT
  1600. * /F1 16 Tf % Font name + size
  1601. * 16 TL % How many units down for next line in multiline text
  1602. * 0 g % color
  1603. * 28.35 813.54 Td % position
  1604. * (line one) Tj
  1605. * T* (line two) Tj
  1606. * T* (line three) Tj
  1607. * ET
  1608. */
  1609. //backwardsCompatibility
  1610. var tmp; // Pre-August-2012 the order of arguments was function(x, y, text, flags)
  1611. // in effort to make all calls have similar signature like
  1612. // function(data, coordinates... , miscellaneous)
  1613. // this method had its args flipped.
  1614. // code below allows backward compatibility with old arg order.
  1615. if (typeof text === 'number' && typeof x === 'number' && (typeof y === 'string' || Array.isArray(y))) {
  1616. tmp = y;
  1617. y = x;
  1618. x = text;
  1619. text = tmp;
  1620. }
  1621. var flags = arguments[3];
  1622. var angle = arguments[4];
  1623. var align = arguments[5];
  1624. if (_typeof(flags) !== "object" || flags === null) {
  1625. if (typeof angle === 'string') {
  1626. align = angle;
  1627. angle = null;
  1628. }
  1629. if (typeof flags === 'string') {
  1630. align = flags;
  1631. flags = null;
  1632. }
  1633. if (typeof flags === 'number') {
  1634. angle = flags;
  1635. flags = null;
  1636. }
  1637. options = {
  1638. flags: flags,
  1639. angle: angle,
  1640. align: align
  1641. };
  1642. }
  1643. flags = flags || {};
  1644. flags.noBOM = flags.noBOM || true;
  1645. flags.autoencode = flags.autoencode || true;
  1646. if (isNaN(x) || isNaN(y) || typeof text === "undefined" || text === null) {
  1647. throw new Error('Invalid arguments passed to jsPDF.text');
  1648. }
  1649. if (text.length === 0) {
  1650. return scope;
  1651. }
  1652. var xtra = '';
  1653. var isHex = false;
  1654. var lineHeight = typeof options.lineHeightFactor === 'number' ? options.lineHeightFactor : lineHeightFactor;
  1655. var scope = options.scope || this;
  1656. function ESC(s) {
  1657. s = s.split("\t").join(Array(options.TabLen || 9).join(" "));
  1658. return pdfEscape(s, flags);
  1659. }
  1660. function transformTextToSpecialArray(text) {
  1661. //we don't want to destroy original text array, so cloning it
  1662. var sa = text.concat();
  1663. var da = [];
  1664. var len = sa.length;
  1665. var curDa; //we do array.join('text that must not be PDFescaped")
  1666. //thus, pdfEscape each component separately
  1667. while (len--) {
  1668. curDa = sa.shift();
  1669. if (typeof curDa === "string") {
  1670. da.push(curDa);
  1671. } else {
  1672. if (Array.isArray(text) && curDa.length === 1) {
  1673. da.push(curDa[0]);
  1674. } else {
  1675. da.push([curDa[0], curDa[1], curDa[2]]);
  1676. }
  1677. }
  1678. }
  1679. return da;
  1680. }
  1681. function processTextByFunction(text, processingFunction) {
  1682. var result;
  1683. if (typeof text === 'string') {
  1684. result = processingFunction(text)[0];
  1685. } else if (Array.isArray(text)) {
  1686. //we don't want to destroy original text array, so cloning it
  1687. var sa = text.concat();
  1688. var da = [];
  1689. var len = sa.length;
  1690. var curDa;
  1691. var tmpResult; //we do array.join('text that must not be PDFescaped")
  1692. //thus, pdfEscape each component separately
  1693. while (len--) {
  1694. curDa = sa.shift();
  1695. if (typeof curDa === "string") {
  1696. da.push(processingFunction(curDa)[0]);
  1697. } else if (Array.isArray(curDa) && curDa[0] === "string") {
  1698. tmpResult = processingFunction(curDa[0], curDa[1], curDa[2]);
  1699. da.push([tmpResult[0], tmpResult[1], tmpResult[2]]);
  1700. }
  1701. }
  1702. result = da;
  1703. }
  1704. return result;
  1705. } //Check if text is of type String
  1706. var textIsOfTypeString = false;
  1707. var tmpTextIsOfTypeString = true;
  1708. if (typeof text === 'string') {
  1709. textIsOfTypeString = true;
  1710. } else if (Array.isArray(text)) {
  1711. //we don't want to destroy original text array, so cloning it
  1712. var sa = text.concat();
  1713. var da = [];
  1714. var len = sa.length;
  1715. var curDa; //we do array.join('text that must not be PDFescaped")
  1716. //thus, pdfEscape each component separately
  1717. while (len--) {
  1718. curDa = sa.shift();
  1719. if (typeof curDa !== "string" || Array.isArray(curDa) && typeof curDa[0] !== "string") {
  1720. tmpTextIsOfTypeString = false;
  1721. }
  1722. }
  1723. textIsOfTypeString = tmpTextIsOfTypeString;
  1724. }
  1725. if (textIsOfTypeString === false) {
  1726. throw new Error('Type of text must be string or Array. "' + text + '" is not recognized.');
  1727. } //Escaping
  1728. var activeFontEncoding = fonts[activeFontKey].encoding;
  1729. if (activeFontEncoding === "WinAnsiEncoding" || activeFontEncoding === "StandardEncoding") {
  1730. text = processTextByFunction(text, function (text, posX, posY) {
  1731. return [ESC(text), posX, posY];
  1732. });
  1733. } //If there are any newlines in text, we assume
  1734. //the user wanted to print multiple lines, so break the
  1735. //text up into an array. If the text is already an array,
  1736. //we assume the user knows what they are doing.
  1737. //Convert text into an array anyway to simplify
  1738. //later code.
  1739. if (typeof text === 'string') {
  1740. if (text.match(/[\r?\n]/)) {
  1741. text = text.split(/\r\n|\r|\n/g);
  1742. } else {
  1743. text = [text];
  1744. }
  1745. } //baseline
  1746. var height = activeFontSize / scope.internal.scaleFactor;
  1747. var descent = height * (lineHeightFactor - 1);
  1748. switch (options.baseline) {
  1749. case 'bottom':
  1750. y -= descent;
  1751. break;
  1752. case 'top':
  1753. y += height - descent;
  1754. break;
  1755. case 'hanging':
  1756. y += height - 2 * descent;
  1757. break;
  1758. case 'middle':
  1759. y += height / 2 - descent;
  1760. break;
  1761. case 'ideographic':
  1762. case 'alphabetic':
  1763. default:
  1764. // do nothing, everything is fine
  1765. break;
  1766. } //multiline
  1767. var maxWidth = options.maxWidth || 0;
  1768. if (maxWidth > 0) {
  1769. if (typeof text === 'string') {
  1770. text = scope.splitTextToSize(text, maxWidth);
  1771. } else if (Object.prototype.toString.call(text) === '[object Array]') {
  1772. text = scope.splitTextToSize(text.join(" "), maxWidth);
  1773. }
  1774. } //creating Payload-Object to make text byRef
  1775. var payload = {
  1776. text: text,
  1777. x: x,
  1778. y: y,
  1779. options: options,
  1780. mutex: {
  1781. pdfEscape: pdfEscape,
  1782. activeFontKey: activeFontKey,
  1783. fonts: fonts,
  1784. activeFontSize: activeFontSize
  1785. }
  1786. };
  1787. events.publish('preProcessText', payload);
  1788. text = payload.text;
  1789. options = payload.options; //angle
  1790. var angle = options.angle;
  1791. var k = scope.internal.scaleFactor;
  1792. var transformationMatrix = [];
  1793. if (angle) {
  1794. angle *= Math.PI / 180;
  1795. var c = Math.cos(angle),
  1796. s = Math.sin(angle);
  1797. transformationMatrix = [f2(c), f2(s), f2(s * -1), f2(c)];
  1798. } //charSpace
  1799. var charSpace = options.charSpace;
  1800. if (typeof charSpace !== 'undefined') {
  1801. xtra += f3(charSpace * k) + " Tc\n";
  1802. } //lang
  1803. var lang = options.lang;
  1804. var tmpRenderingMode = -1;
  1805. var parmRenderingMode = typeof options.renderingMode !== "undefined" ? options.renderingMode : options.stroke;
  1806. var pageContext = scope.internal.getCurrentPageInfo().pageContext;
  1807. switch (parmRenderingMode) {
  1808. case 0:
  1809. case false:
  1810. case 'fill':
  1811. tmpRenderingMode = 0;
  1812. break;
  1813. case 1:
  1814. case true:
  1815. case 'stroke':
  1816. tmpRenderingMode = 1;
  1817. break;
  1818. case 2:
  1819. case 'fillThenStroke':
  1820. tmpRenderingMode = 2;
  1821. break;
  1822. case 3:
  1823. case 'invisible':
  1824. tmpRenderingMode = 3;
  1825. break;
  1826. case 4:
  1827. case 'fillAndAddForClipping':
  1828. tmpRenderingMode = 4;
  1829. break;
  1830. case 5:
  1831. case 'strokeAndAddPathForClipping':
  1832. tmpRenderingMode = 5;
  1833. break;
  1834. case 6:
  1835. case 'fillThenStrokeAndAddToPathForClipping':
  1836. tmpRenderingMode = 6;
  1837. break;
  1838. case 7:
  1839. case 'addToPathForClipping':
  1840. tmpRenderingMode = 7;
  1841. break;
  1842. }
  1843. var usedRenderingMode = typeof pageContext.usedRenderingMode !== 'undefined' ? pageContext.usedRenderingMode : -1; //if the coder wrote it explicitly to use a specific
  1844. //renderingMode, then use it
  1845. if (tmpRenderingMode !== -1) {
  1846. xtra += tmpRenderingMode + " Tr\n"; //otherwise check if we used the rendering Mode already
  1847. //if so then set the rendering Mode...
  1848. } else if (usedRenderingMode !== -1) {
  1849. xtra += "0 Tr\n";
  1850. }
  1851. if (tmpRenderingMode !== -1) {
  1852. pageContext.usedRenderingMode = tmpRenderingMode;
  1853. } //align
  1854. var align = options.align || 'left';
  1855. var leading = activeFontSize * lineHeight;
  1856. var pageWidth = scope.internal.pageSize.getWidth();
  1857. var k = scope.internal.scaleFactor;
  1858. var activeFont = fonts[activeFontKey];
  1859. var charSpace = options.charSpace || activeCharSpace;
  1860. var maxWidth = options.maxWidth || 0;
  1861. var lineWidths;
  1862. var flags = {};
  1863. var wordSpacingPerLine = [];
  1864. if (Object.prototype.toString.call(text) === '[object Array]') {
  1865. var da = transformTextToSpecialArray(text);
  1866. var newY;
  1867. var maxLineLength;
  1868. var lineWidths;
  1869. if (align !== "left") {
  1870. lineWidths = da.map(function (v) {
  1871. return scope.getStringUnitWidth(v, {
  1872. font: activeFont,
  1873. charSpace: charSpace,
  1874. fontSize: activeFontSize
  1875. }) * activeFontSize / k;
  1876. });
  1877. }
  1878. var maxLineLength = Math.max.apply(Math, lineWidths); //The first line uses the "main" Td setting,
  1879. //and the subsequent lines are offset by the
  1880. //previous line's x coordinate.
  1881. var prevWidth = 0;
  1882. var delta;
  1883. var newX;
  1884. if (align === "right") {
  1885. x -= lineWidths[0];
  1886. text = [];
  1887. for (var i = 0, len = da.length; i < len; i++) {
  1888. delta = maxLineLength - lineWidths[i];
  1889. if (i === 0) {
  1890. newX = getHorizontalCoordinate(x);
  1891. newY = getVerticalCoordinate(y);
  1892. } else {
  1893. newX = (prevWidth - lineWidths[i]) * k;
  1894. newY = -leading;
  1895. }
  1896. text.push([da[i], newX, newY]);
  1897. prevWidth = lineWidths[i];
  1898. }
  1899. } else if (align === "center") {
  1900. x -= lineWidths[0] / 2;
  1901. text = [];
  1902. for (var i = 0, len = da.length; i < len; i++) {
  1903. delta = (maxLineLength - lineWidths[i]) / 2;
  1904. if (i === 0) {
  1905. newX = getHorizontalCoordinate(x);
  1906. newY = getVerticalCoordinate(y);
  1907. } else {
  1908. newX = (prevWidth - lineWidths[i]) / 2 * k;
  1909. newY = -leading;
  1910. }
  1911. text.push([da[i], newX, newY]);
  1912. prevWidth = lineWidths[i];
  1913. }
  1914. } else if (align === "left") {
  1915. text = [];
  1916. for (var i = 0, len = da.length; i < len; i++) {
  1917. newY = i === 0 ? getVerticalCoordinate(y) : -leading;
  1918. newX = i === 0 ? getHorizontalCoordinate(x) : 0; //text.push([da[i], newX, newY]);
  1919. text.push(da[i]);
  1920. }
  1921. } else if (align === "justify") {
  1922. text = [];
  1923. var maxWidth = maxWidth !== 0 ? maxWidth : pageWidth;
  1924. for (var i = 0, len = da.length; i < len; i++) {
  1925. newY = i === 0 ? getVerticalCoordinate(y) : -leading;
  1926. newX = i === 0 ? getHorizontalCoordinate(x) : 0;
  1927. if (i < len - 1) {
  1928. wordSpacingPerLine.push(((maxWidth - lineWidths[i]) / (da[i].split(" ").length - 1) * k).toFixed(2));
  1929. }
  1930. text.push([da[i], newX, newY]);
  1931. }
  1932. } else {
  1933. throw new Error('Unrecognized alignment option, use "left", "center", "right" or "justify".');
  1934. }
  1935. } //R2L
  1936. var doReversing = typeof options.R2L === "boolean" ? options.R2L : R2L;
  1937. if (doReversing === true) {
  1938. text = processTextByFunction(text, function (text, posX, posY) {
  1939. return [text.split("").reverse().join(""), posX, posY];
  1940. });
  1941. } //creating Payload-Object to make text byRef
  1942. var payload = {
  1943. text: text,
  1944. x: x,
  1945. y: y,
  1946. options: options,
  1947. mutex: {
  1948. pdfEscape: pdfEscape,
  1949. activeFontKey: activeFontKey,
  1950. fonts: fonts,
  1951. activeFontSize: activeFontSize
  1952. }
  1953. };
  1954. events.publish('postProcessText', payload);
  1955. text = payload.text;
  1956. isHex = payload.mutex.isHex;
  1957. var da = transformTextToSpecialArray(text);
  1958. text = [];
  1959. var variant = 0;
  1960. var len = da.length;
  1961. var posX;
  1962. var posY;
  1963. var content;
  1964. var wordSpacing = '';
  1965. for (var i = 0; i < len; i++) {
  1966. wordSpacing = '';
  1967. if (!Array.isArray(da[i])) {
  1968. posX = getHorizontalCoordinate(x);
  1969. posY = getVerticalCoordinate(y);
  1970. content = (isHex ? "<" : "(") + da[i] + (isHex ? ">" : ")");
  1971. } else {
  1972. posX = parseFloat(da[i][1]);
  1973. posY = parseFloat(da[i][2]);
  1974. content = (isHex ? "<" : "(") + da[i][0] + (isHex ? ">" : ")");
  1975. variant = 1;
  1976. }
  1977. if (wordSpacingPerLine !== undefined && wordSpacingPerLine[i] !== undefined) {
  1978. wordSpacing = wordSpacingPerLine[i] + " Tw\n";
  1979. }
  1980. if (transformationMatrix.length !== 0 && i === 0) {
  1981. text.push(wordSpacing + transformationMatrix.join(" ") + " " + posX.toFixed(2) + " " + posY.toFixed(2) + " Tm\n" + content);
  1982. } else if (variant === 1 || variant === 0 && i === 0) {
  1983. text.push(wordSpacing + posX.toFixed(2) + " " + posY.toFixed(2) + " Td\n" + content);
  1984. } else {
  1985. text.push(wordSpacing + content);
  1986. }
  1987. }
  1988. if (variant === 0) {
  1989. text = text.join(" Tj\nT* ");
  1990. } else {
  1991. text = text.join(" Tj\n");
  1992. }
  1993. text += " Tj\n";
  1994. var result = 'BT\n/' + activeFontKey + ' ' + activeFontSize + ' Tf\n' + // font face, style, size
  1995. (activeFontSize * lineHeight).toFixed(2) + ' TL\n' + // line spacing
  1996. textColor + '\n';
  1997. result += xtra;
  1998. result += text;
  1999. result += "ET";
  2000. out(result);
  2001. usedFonts[activeFontKey] = true;
  2002. return scope;
  2003. };
  2004. /**
  2005. * Letter spacing method to print text with gaps
  2006. *
  2007. * @function
  2008. * @instance
  2009. * @param {String|Array} text String to be added to the page.
  2010. * @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  2011. * @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  2012. * @param {number} spacing Spacing (in units declared at inception)
  2013. * @returns {jsPDF}
  2014. * @memberOf jsPDF
  2015. * @name lstext
  2016. * @deprecated We'll be removing this function. It doesn't take character width into account.
  2017. */
  2018. var lstext = API.__private__.lstext = API.lstext = function (text, x, y, charSpace) {
  2019. console.warn('jsPDF.lstext is deprecated');
  2020. return this.text(text, x, y, {
  2021. charSpace: charSpace
  2022. });
  2023. };
  2024. /**
  2025. *
  2026. * @name clip
  2027. * @function
  2028. * @instance
  2029. * @param {string} rule
  2030. * @returns {jsPDF}
  2031. * @memberOf jsPDF
  2032. * @description All .clip() after calling drawing ops with a style argument of null.
  2033. */
  2034. var clip = API.__private__.clip = API.clip = function (rule) {
  2035. // Call .clip() after calling drawing ops with a style argument of null
  2036. // W is the PDF clipping op
  2037. if ('evenodd' === rule) {
  2038. out('W*');
  2039. } else {
  2040. out('W');
  2041. } // End the path object without filling or stroking it.
  2042. // This operator is a path-painting no-op, used primarily for the side effect of changing the current clipping path
  2043. // (see Section 4.4.3, “Clipping Path Operators”)
  2044. out('n');
  2045. };
  2046. /**
  2047. * This fixes the previous function clip(). Perhaps the 'stroke path' hack was due to the missing 'n' instruction?
  2048. * We introduce the fixed version so as to not break API.
  2049. * @param fillRule
  2050. * @ignore
  2051. */
  2052. var clip_fixed = API.__private__.clip_fixed = API.clip_fixed = function (rule) {
  2053. console.log("clip_fixed is deprecated");
  2054. API.clip(rule);
  2055. };
  2056. var isValidStyle = API.__private__.isValidStyle = function (style) {
  2057. var validStyleVariants = [undefined, null, 'S', 'F', 'DF', 'FD', 'f', 'f*', 'B', 'B*'];
  2058. var result = false;
  2059. if (validStyleVariants.indexOf(style) !== -1) {
  2060. result = true;
  2061. }
  2062. return result;
  2063. };
  2064. var getStyle = API.__private__.getStyle = function (style) {
  2065. // see path-painting operators in PDF spec
  2066. var op = 'S'; // stroke
  2067. if (style === 'F') {
  2068. op = 'f'; // fill
  2069. } else if (style === 'FD' || style === 'DF') {
  2070. op = 'B'; // both
  2071. } else if (style === 'f' || style === 'f*' || style === 'B' || style === 'B*') {
  2072. /*
  2073. Allow direct use of these PDF path-painting operators:
  2074. - f fill using nonzero winding number rule
  2075. - f* fill using even-odd rule
  2076. - B fill then stroke with fill using non-zero winding number rule
  2077. - B* fill then stroke with fill using even-odd rule
  2078. */
  2079. op = style;
  2080. }
  2081. return op;
  2082. };
  2083. /**
  2084. * Draw a line on the current page.
  2085. *
  2086. * @name line
  2087. * @function
  2088. * @instance
  2089. * @param {number} x1
  2090. * @param {number} y1
  2091. * @param {number} x2
  2092. * @param {number} y2
  2093. * @returns {jsPDF}
  2094. * @memberOf jsPDF
  2095. */
  2096. var line = API.__private__.line = API.line = function (x1, y1, x2, y2) {
  2097. if (isNaN(x1) || isNaN(y1) || isNaN(x2) || isNaN(y2)) {
  2098. throw new Error('Invalid arguments passed to jsPDF.line');
  2099. }
  2100. return this.lines([[x2 - x1, y2 - y1]], x1, y1);
  2101. };
  2102. /**
  2103. * Adds series of curves (straight lines or cubic bezier curves) to canvas, starting at `x`, `y` coordinates.
  2104. * All data points in `lines` are relative to last line origin.
  2105. * `x`, `y` become x1,y1 for first line / curve in the set.
  2106. * For lines you only need to specify [x2, y2] - (ending point) vector against x1, y1 starting point.
  2107. * For bezier curves you need to specify [x2,y2,x3,y3,x4,y4] - vectors to control points 1, 2, ending point. All vectors are against the start of the curve - x1,y1.
  2108. *
  2109. * @example .lines([[2,2],[-2,2],[1,1,2,2,3,3],[2,1]], 212,110, [1,1], 'F', false) // line, line, bezier curve, line
  2110. * @param {Array} lines Array of *vector* shifts as pairs (lines) or sextets (cubic bezier curves).
  2111. * @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page.
  2112. * @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page.
  2113. * @param {number} scale (Defaults to [1.0,1.0]) x,y Scaling factor for all vectors. Elements can be any floating number Sub-one makes drawing smaller. Over-one grows the drawing. Negative flips the direction.
  2114. * @param {string} style A string specifying the painting style or null. Valid styles include: 'S' [default] - stroke, 'F' - fill, and 'DF' (or 'FD') - fill then stroke. A null value postpones setting the style so that a shape may be composed using multiple method calls. The last drawing method call used to define the shape should not have a null style argument.
  2115. * @param {boolean} closed If true, the path is closed with a straight line from the end of the last curve to the starting point.
  2116. * @function
  2117. * @instance
  2118. * @returns {jsPDF}
  2119. * @memberOf jsPDF
  2120. * @name lines
  2121. */
  2122. var lines = API.__private__.lines = API.lines = function (lines, x, y, scale, style, closed) {
  2123. var scalex, scaley, i, l, leg, x2, y2, x3, y3, x4, y4, tmp; // Pre-August-2012 the order of arguments was function(x, y, lines, scale, style)
  2124. // in effort to make all calls have similar signature like
  2125. // function(content, coordinateX, coordinateY , miscellaneous)
  2126. // this method had its args flipped.
  2127. // code below allows backward compatibility with old arg order.
  2128. if (typeof lines === 'number') {
  2129. tmp = y;
  2130. y = x;
  2131. x = lines;
  2132. lines = tmp;
  2133. }
  2134. scale = scale || [1, 1];
  2135. closed = closed || false;
  2136. if (isNaN(x) || isNaN(y) || !Array.isArray(lines) || !Array.isArray(scale) || !isValidStyle(style) || typeof closed !== 'boolean') {
  2137. throw new Error('Invalid arguments passed to jsPDF.lines');
  2138. } // starting point
  2139. out(f3(getHorizontalCoordinate(x)) + ' ' + f3(getVerticalCoordinate(y)) + ' m ');
  2140. scalex = scale[0];
  2141. scaley = scale[1];
  2142. l = lines.length; //, x2, y2 // bezier only. In page default measurement "units", *after* scaling
  2143. //, x3, y3 // bezier only. In page default measurement "units", *after* scaling
  2144. // ending point for all, lines and bezier. . In page default measurement "units", *after* scaling
  2145. x4 = x; // last / ending point = starting point for first item.
  2146. y4 = y; // last / ending point = starting point for first item.
  2147. for (i = 0; i < l; i++) {
  2148. leg = lines[i];
  2149. if (leg.length === 2) {
  2150. // simple line
  2151. x4 = leg[0] * scalex + x4; // here last x4 was prior ending point
  2152. y4 = leg[1] * scaley + y4; // here last y4 was prior ending point
  2153. out(f3(getHorizontalCoordinate(x4)) + ' ' + f3(getVerticalCoordinate(y4)) + ' l');
  2154. } else {
  2155. // bezier curve
  2156. x2 = leg[0] * scalex + x4; // here last x4 is prior ending point
  2157. y2 = leg[1] * scaley + y4; // here last y4 is prior ending point
  2158. x3 = leg[2] * scalex + x4; // here last x4 is prior ending point
  2159. y3 = leg[3] * scaley + y4; // here last y4 is prior ending point
  2160. x4 = leg[4] * scalex + x4; // here last x4 was prior ending point
  2161. y4 = leg[5] * scaley + y4; // here last y4 was prior ending point
  2162. out(f3(getHorizontalCoordinate(x2)) + ' ' + f3(getVerticalCoordinate(y2)) + ' ' + f3(getHorizontalCoordinate(x3)) + ' ' + f3(getVerticalCoordinate(y3)) + ' ' + f3(getHorizontalCoordinate(x4)) + ' ' + f3(getVerticalCoordinate(y4)) + ' c');
  2163. }
  2164. }
  2165. if (closed) {
  2166. out(' h');
  2167. } // stroking / filling / both the path
  2168. if (style !== null) {
  2169. out(getStyle(style));
  2170. }
  2171. return this;
  2172. };
  2173. /**
  2174. * Adds a rectangle to PDF.
  2175. *
  2176. * @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page.
  2177. * @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page.
  2178. * @param {number} w Width (in units declared at inception of PDF document).
  2179. * @param {number} h Height (in units declared at inception of PDF document).
  2180. * @param {string} style A string specifying the painting style or null. Valid styles include: 'S' [default] - stroke, 'F' - fill, and 'DF' (or 'FD') - fill then stroke. A null value postpones setting the style so that a shape may be composed using multiple method calls. The last drawing method call used to define the shape should not have a null style argument.
  2181. * @function
  2182. * @instance
  2183. * @returns {jsPDF}
  2184. * @memberOf jsPDF
  2185. * @name rect
  2186. */
  2187. var rect = API.__private__.rect = API.rect = function (x, y, w, h, style) {
  2188. if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h) || !isValidStyle(style)) {
  2189. throw new Error('Invalid arguments passed to jsPDF.rect');
  2190. }
  2191. out([f2(getHorizontalCoordinate(x)), f2(getVerticalCoordinate(y)), f2(w * k), f2(-h * k), 're'].join(' '));
  2192. if (style !== null) {
  2193. out(getStyle(style));
  2194. }
  2195. return this;
  2196. };
  2197. /**
  2198. * Adds a triangle to PDF.
  2199. *
  2200. * @param {number} x1 Coordinate (in units declared at inception of PDF document) against left edge of the page.
  2201. * @param {number} y1 Coordinate (in units declared at inception of PDF document) against upper edge of the page.
  2202. * @param {number} x2 Coordinate (in units declared at inception of PDF document) against left edge of the page.
  2203. * @param {number} y2 Coordinate (in units declared at inception of PDF document) against upper edge of the page.
  2204. * @param {number} x3 Coordinate (in units declared at inception of PDF document) against left edge of the page.
  2205. * @param {number} y3 Coordinate (in units declared at inception of PDF document) against upper edge of the page.
  2206. * @param {string} style A string specifying the painting style or null. Valid styles include: 'S' [default] - stroke, 'F' - fill, and 'DF' (or 'FD') - fill then stroke. A null value postpones setting the style so that a shape may be composed using multiple method calls. The last drawing method call used to define the shape should not have a null style argument.
  2207. * @function
  2208. * @instance
  2209. * @returns {jsPDF}
  2210. * @memberOf jsPDF
  2211. * @name triangle
  2212. */
  2213. var triangle = API.__private__.triangle = API.triangle = function (x1, y1, x2, y2, x3, y3, style) {
  2214. if (isNaN(x1) || isNaN(y1) || isNaN(x2) || isNaN(y2) || isNaN(x3) || isNaN(y3) || !isValidStyle(style)) {
  2215. throw new Error('Invalid arguments passed to jsPDF.triangle');
  2216. }
  2217. this.lines([[x2 - x1, y2 - y1], // vector to point 2
  2218. [x3 - x2, y3 - y2], // vector to point 3
  2219. [x1 - x3, y1 - y3] // closing vector back to point 1
  2220. ], x1, y1, // start of path
  2221. [1, 1], style, true);
  2222. return this;
  2223. };
  2224. /**
  2225. * Adds a rectangle with rounded corners to PDF.
  2226. *
  2227. * @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page.
  2228. * @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page.
  2229. * @param {number} w Width (in units declared at inception of PDF document).
  2230. * @param {number} h Height (in units declared at inception of PDF document).
  2231. * @param {number} rx Radius along x axis (in units declared at inception of PDF document).
  2232. * @param {number} ry Radius along y axis (in units declared at inception of PDF document).
  2233. * @param {string} style A string specifying the painting style or null. Valid styles include: 'S' [default] - stroke, 'F' - fill, and 'DF' (or 'FD') - fill then stroke. A null value postpones setting the style so that a shape may be composed using multiple method calls. The last drawing method call used to define the shape should not have a null style argument.
  2234. * @function
  2235. * @instance
  2236. * @returns {jsPDF}
  2237. * @memberOf jsPDF
  2238. * @name roundedRect
  2239. */
  2240. var roundedRect = API.__private__.roundedRect = API.roundedRect = function (x, y, w, h, rx, ry, style) {
  2241. if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h) || isNaN(rx) || isNaN(ry) || !isValidStyle(style)) {
  2242. throw new Error('Invalid arguments passed to jsPDF.roundedRect');
  2243. }
  2244. var MyArc = 4 / 3 * (Math.SQRT2 - 1);
  2245. this.lines([[w - 2 * rx, 0], [rx * MyArc, 0, rx, ry - ry * MyArc, rx, ry], [0, h - 2 * ry], [0, ry * MyArc, -(rx * MyArc), ry, -rx, ry], [-w + 2 * rx, 0], [-(rx * MyArc), 0, -rx, -(ry * MyArc), -rx, -ry], [0, -h + 2 * ry], [0, -(ry * MyArc), rx * MyArc, -ry, rx, -ry]], x + rx, y, // start of path
  2246. [1, 1], style);
  2247. return this;
  2248. };
  2249. /**
  2250. * Adds an ellipse to PDF.
  2251. *
  2252. * @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page.
  2253. * @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page.
  2254. * @param {number} rx Radius along x axis (in units declared at inception of PDF document).
  2255. * @param {number} ry Radius along y axis (in units declared at inception of PDF document).
  2256. * @param {string} style A string specifying the painting style or null. Valid styles include: 'S' [default] - stroke, 'F' - fill, and 'DF' (or 'FD') - fill then stroke. A null value postpones setting the style so that a shape may be composed using multiple method calls. The last drawing method call used to define the shape should not have a null style argument.
  2257. * @function
  2258. * @instance
  2259. * @returns {jsPDF}
  2260. * @memberOf jsPDF
  2261. * @name ellipse
  2262. */
  2263. var ellise = API.__private__.ellipse = API.ellipse = function (x, y, rx, ry, style) {
  2264. if (isNaN(x) || isNaN(y) || isNaN(rx) || isNaN(ry) || !isValidStyle(style)) {
  2265. throw new Error('Invalid arguments passed to jsPDF.ellipse');
  2266. }
  2267. var lx = 4 / 3 * (Math.SQRT2 - 1) * rx,
  2268. ly = 4 / 3 * (Math.SQRT2 - 1) * ry;
  2269. out([f2(getHorizontalCoordinate(x + rx)), f2(getVerticalCoordinate(y)), 'm', f2(getHorizontalCoordinate(x + rx)), f2(getVerticalCoordinate(y - ly)), f2(getHorizontalCoordinate(x + lx)), f2(getVerticalCoordinate(y - ry)), f2(getHorizontalCoordinate(x)), f2(getVerticalCoordinate(y - ry)), 'c'].join(' '));
  2270. out([f2(getHorizontalCoordinate(x - lx)), f2(getVerticalCoordinate(y - ry)), f2(getHorizontalCoordinate(x - rx)), f2(getVerticalCoordinate(y - ly)), f2(getHorizontalCoordinate(x - rx)), f2(getVerticalCoordinate(y)), 'c'].join(' '));
  2271. out([f2(getHorizontalCoordinate(x - rx)), f2(getVerticalCoordinate(y + ly)), f2(getHorizontalCoordinate(x - lx)), f2(getVerticalCoordinate(y + ry)), f2(getHorizontalCoordinate(x)), f2(getVerticalCoordinate(y + ry)), 'c'].join(' '));
  2272. out([f2(getHorizontalCoordinate(x + lx)), f2(getVerticalCoordinate(y + ry)), f2(getHorizontalCoordinate(x + rx)), f2(getVerticalCoordinate(y + ly)), f2(getHorizontalCoordinate(x + rx)), f2(getVerticalCoordinate(y)), 'c'].join(' '));
  2273. if (style !== null) {
  2274. out(getStyle(style));
  2275. }
  2276. return this;
  2277. };
  2278. /**
  2279. * Adds an circle to PDF.
  2280. *
  2281. * @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page.
  2282. * @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page.
  2283. * @param {number} r Radius (in units declared at inception of PDF document).
  2284. * @param {string} style A string specifying the painting style or null. Valid styles include: 'S' [default] - stroke, 'F' - fill, and 'DF' (or 'FD') - fill then stroke. A null value postpones setting the style so that a shape may be composed using multiple method calls. The last drawing method call used to define the shape should not have a null style argument.
  2285. * @function
  2286. * @instance
  2287. * @returns {jsPDF}
  2288. * @memberOf jsPDF
  2289. * @name circle
  2290. */
  2291. var circle = API.__private__.circle = API.circle = function (x, y, r, style) {
  2292. if (isNaN(x) || isNaN(y) || isNaN(r) || !isValidStyle(style)) {
  2293. throw new Error('Invalid arguments passed to jsPDF.circle');
  2294. }
  2295. return this.ellipse(x, y, r, r, style);
  2296. };
  2297. /**
  2298. * Sets text font face, variant for upcoming text elements.
  2299. * See output of jsPDF.getFontList() for possible font names, styles.
  2300. *
  2301. * @param {string} fontName Font name or family. Example: "times".
  2302. * @param {string} fontStyle Font style or variant. Example: "italic".
  2303. * @function
  2304. * @instance
  2305. * @returns {jsPDF}
  2306. * @memberOf jsPDF
  2307. * @name setFont
  2308. */
  2309. API.setFont = function (fontName, fontStyle) {
  2310. activeFontKey = _getFont(fontName, fontStyle, {
  2311. disableWarning: false
  2312. });
  2313. return this;
  2314. };
  2315. /**
  2316. * Switches font style or variant for upcoming text elements,
  2317. * while keeping the font face or family same.
  2318. * See output of jsPDF.getFontList() for possible font names, styles.
  2319. *
  2320. * @param {string} style Font style or variant. Example: "italic".
  2321. * @function
  2322. * @instance
  2323. * @returns {jsPDF}
  2324. * @memberOf jsPDF
  2325. * @name setFontStyle
  2326. */
  2327. API.setFontStyle = API.setFontType = function (style) {
  2328. activeFontKey = _getFont(undefined, style); // if font is not found, the above line blows up and we never go further
  2329. return this;
  2330. };
  2331. /**
  2332. * Returns an object - a tree of fontName to fontStyle relationships available to
  2333. * active PDF document.
  2334. *
  2335. * @public
  2336. * @function
  2337. * @instance
  2338. * @returns {Object} Like {'times':['normal', 'italic', ... ], 'arial':['normal', 'bold', ... ], ... }
  2339. * @memberOf jsPDF
  2340. * @name getFontList
  2341. */
  2342. var getFontList = API.__private__.getFontList = API.getFontList = function () {
  2343. // TODO: iterate over fonts array or return copy of fontmap instead in case more are ever added.
  2344. var list = {},
  2345. fontName,
  2346. fontStyle,
  2347. tmp;
  2348. for (fontName in fontmap) {
  2349. if (fontmap.hasOwnProperty(fontName)) {
  2350. list[fontName] = tmp = [];
  2351. for (fontStyle in fontmap[fontName]) {
  2352. if (fontmap[fontName].hasOwnProperty(fontStyle)) {
  2353. tmp.push(fontStyle);
  2354. }
  2355. }
  2356. }
  2357. }
  2358. return list;
  2359. };
  2360. /**
  2361. * Add a custom font to the current instance.
  2362. *
  2363. * @property {string} postScriptName PDF specification full name for the font.
  2364. * @property {string} id PDF-document-instance-specific label assinged to the font.
  2365. * @property {string} fontStyle Style of the Font.
  2366. * @property {Object} encoding Encoding_name-to-Font_metrics_object mapping.
  2367. * @function
  2368. * @instance
  2369. * @memberOf jsPDF
  2370. * @name addFont
  2371. */
  2372. API.addFont = function (postScriptName, fontName, fontStyle, encoding) {
  2373. encoding = encoding || 'Identity-H';
  2374. addFont.call(this, postScriptName, fontName, fontStyle, encoding);
  2375. };
  2376. var lineWidth = options.lineWidth || 0.200025; // 2mm
  2377. /**
  2378. * Sets line width for upcoming lines.
  2379. *
  2380. * @param {number} width Line width (in units declared at inception of PDF document).
  2381. * @function
  2382. * @instance
  2383. * @returns {jsPDF}
  2384. * @memberOf jsPDF
  2385. * @name setLineWidth
  2386. */
  2387. var setLineWidth = API.__private__.setLineWidth = API.setLineWidth = function (width) {
  2388. out((width * k).toFixed(2) + ' w');
  2389. return this;
  2390. };
  2391. /**
  2392. * Sets the dash pattern for upcoming lines.
  2393. *
  2394. * To reset the settings simply call the method without any parameters.
  2395. * @param {array} dashArray The pattern of the line, expects numbers.
  2396. * @param {number} dashPhase The phase at which the dash pattern starts.
  2397. * @function
  2398. * @instance
  2399. * @returns {jsPDF}
  2400. * @memberOf jsPDF
  2401. * @name setLineDash
  2402. */
  2403. var setLineDash = API.__private__.setLineDash = jsPDF.API.setLineDash = function (dashArray, dashPhase) {
  2404. dashArray = dashArray || [];
  2405. dashPhase = dashPhase || 0;
  2406. if (isNaN(dashPhase) || !Array.isArray(dashArray)) {
  2407. throw new Error('Invalid arguments passed to jsPDF.setLineDash');
  2408. }
  2409. dashArray = dashArray.map(function (x) {
  2410. return (x * k).toFixed(3);
  2411. }).join(' ');
  2412. dashPhase = parseFloat((dashPhase * k).toFixed(3));
  2413. out('[' + dashArray + '] ' + dashPhase + ' d');
  2414. return this;
  2415. };
  2416. var lineHeightFactor;
  2417. var getLineHeight = API.__private__.getLineHeight = API.getLineHeight = function () {
  2418. return activeFontSize * lineHeightFactor;
  2419. };
  2420. var lineHeightFactor;
  2421. var getLineHeight = API.__private__.getLineHeight = API.getLineHeight = function () {
  2422. return activeFontSize * lineHeightFactor;
  2423. };
  2424. /**
  2425. * Sets the LineHeightFactor of proportion.
  2426. *
  2427. * @param {number} value LineHeightFactor value. Default: 1.15.
  2428. * @function
  2429. * @instance
  2430. * @returns {jsPDF}
  2431. * @memberOf jsPDF
  2432. * @name setLineHeightFactor
  2433. */
  2434. var setLineHeightFactor = API.__private__.setLineHeightFactor = API.setLineHeightFactor = function (value) {
  2435. value = value || 1.15;
  2436. if (typeof value === "number") {
  2437. lineHeightFactor = value;
  2438. }
  2439. return this;
  2440. };
  2441. /**
  2442. * Gets the LineHeightFactor, default: 1.15.
  2443. *
  2444. * @function
  2445. * @instance
  2446. * @returns {number} lineHeightFactor
  2447. * @memberOf jsPDF
  2448. * @name getLineHeightFactor
  2449. */
  2450. var getLineHeightFactor = API.__private__.getLineHeightFactor = API.getLineHeightFactor = function () {
  2451. return lineHeightFactor;
  2452. };
  2453. setLineHeightFactor(options.lineHeight);
  2454. var getHorizontalCoordinate = API.__private__.getHorizontalCoordinate = function (value) {
  2455. return value * k;
  2456. };
  2457. var getVerticalCoordinate = API.__private__.getVerticalCoordinate = function (value) {
  2458. return pagesContext[currentPage].mediaBox.topRightY - pagesContext[currentPage].mediaBox.bottomLeftY - value * k;
  2459. };
  2460. var getHorizontalCoordinateString = API.__private__.getHorizontalCoordinateString = function (value) {
  2461. return f2(value * k);
  2462. };
  2463. var getVerticalCoordinateString = API.__private__.getVerticalCoordinateString = function (value) {
  2464. return f2(pagesContext[currentPage].mediaBox.topRightY - pagesContext[currentPage].mediaBox.bottomLeftY - value * k);
  2465. };
  2466. var strokeColor = options.strokeColor || '0 G';
  2467. /**
  2468. * Gets the stroke color for upcoming elements.
  2469. *
  2470. * @function
  2471. * @instance
  2472. * @returns {string} colorAsHex
  2473. * @memberOf jsPDF
  2474. * @name getDrawColor
  2475. */
  2476. var getStrokeColor = API.__private__.getStrokeColor = API.getDrawColor = function () {
  2477. return decodeColorString(strokeColor);
  2478. };
  2479. /**
  2480. * Sets the stroke color for upcoming elements.
  2481. *
  2482. * Depending on the number of arguments given, Gray, RGB, or CMYK
  2483. * color space is implied.
  2484. *
  2485. * When only ch1 is given, "Gray" color space is implied and it
  2486. * must be a value in the range from 0.00 (solid black) to to 1.00 (white)
  2487. * if values are communicated as String types, or in range from 0 (black)
  2488. * to 255 (white) if communicated as Number type.
  2489. * The RGB-like 0-255 range is provided for backward compatibility.
  2490. *
  2491. * When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
  2492. * value must be in the range from 0.00 (minimum intensity) to to 1.00
  2493. * (max intensity) if values are communicated as String types, or
  2494. * from 0 (min intensity) to to 255 (max intensity) if values are communicated
  2495. * as Number types.
  2496. * The RGB-like 0-255 range is provided for backward compatibility.
  2497. *
  2498. * When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
  2499. * value must be a in the range from 0.00 (0% concentration) to to
  2500. * 1.00 (100% concentration)
  2501. *
  2502. * Because JavaScript treats fixed point numbers badly (rounds to
  2503. * floating point nearest to binary representation) it is highly advised to
  2504. * communicate the fractional numbers as String types, not JavaScript Number type.
  2505. *
  2506. * @param {Number|String} ch1 Color channel value or {string} ch1 color value in hexadecimal, example: '#FFFFFF'.
  2507. * @param {Number|String} ch2 Color channel value.
  2508. * @param {Number|String} ch3 Color channel value.
  2509. * @param {Number|String} ch4 Color channel value.
  2510. *
  2511. * @function
  2512. * @instance
  2513. * @returns {jsPDF}
  2514. * @memberOf jsPDF
  2515. * @name setDrawColor
  2516. */
  2517. var setStrokeColor = API.__private__.setStrokeColor = API.setDrawColor = function (ch1, ch2, ch3, ch4) {
  2518. var options = {
  2519. "ch1": ch1,
  2520. "ch2": ch2,
  2521. "ch3": ch3,
  2522. "ch4": ch4,
  2523. "pdfColorType": "draw",
  2524. "precision": 2
  2525. };
  2526. strokeColor = encodeColorString(options);
  2527. out(strokeColor);
  2528. return this;
  2529. };
  2530. var fillColor = options.fillColor || '0 g';
  2531. /**
  2532. * Gets the fill color for upcoming elements.
  2533. *
  2534. * @function
  2535. * @instance
  2536. * @returns {string} colorAsHex
  2537. * @memberOf jsPDF
  2538. * @name getFillColor
  2539. */
  2540. var getFillColor = API.__private__.getFillColor = API.getFillColor = function () {
  2541. return decodeColorString(fillColor);
  2542. };
  2543. /**
  2544. * Sets the fill color for upcoming elements.
  2545. *
  2546. * Depending on the number of arguments given, Gray, RGB, or CMYK
  2547. * color space is implied.
  2548. *
  2549. * When only ch1 is given, "Gray" color space is implied and it
  2550. * must be a value in the range from 0.00 (solid black) to to 1.00 (white)
  2551. * if values are communicated as String types, or in range from 0 (black)
  2552. * to 255 (white) if communicated as Number type.
  2553. * The RGB-like 0-255 range is provided for backward compatibility.
  2554. *
  2555. * When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
  2556. * value must be in the range from 0.00 (minimum intensity) to to 1.00
  2557. * (max intensity) if values are communicated as String types, or
  2558. * from 0 (min intensity) to to 255 (max intensity) if values are communicated
  2559. * as Number types.
  2560. * The RGB-like 0-255 range is provided for backward compatibility.
  2561. *
  2562. * When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
  2563. * value must be a in the range from 0.00 (0% concentration) to to
  2564. * 1.00 (100% concentration)
  2565. *
  2566. * Because JavaScript treats fixed point numbers badly (rounds to
  2567. * floating point nearest to binary representation) it is highly advised to
  2568. * communicate the fractional numbers as String types, not JavaScript Number type.
  2569. *
  2570. * @param {Number|String} ch1 Color channel value or {string} ch1 color value in hexadecimal, example: '#FFFFFF'.
  2571. * @param {Number|String} ch2 Color channel value.
  2572. * @param {Number|String} ch3 Color channel value.
  2573. * @param {Number|String} ch4 Color channel value.
  2574. *
  2575. * @function
  2576. * @instance
  2577. * @returns {jsPDF}
  2578. * @memberOf jsPDF
  2579. * @name setFillColor
  2580. */
  2581. var setFillColor = API.__private__.setFillColor = API.setFillColor = function (ch1, ch2, ch3, ch4) {
  2582. var options = {
  2583. "ch1": ch1,
  2584. "ch2": ch2,
  2585. "ch3": ch3,
  2586. "ch4": ch4,
  2587. "pdfColorType": "fill",
  2588. "precision": 2
  2589. };
  2590. fillColor = encodeColorString(options);
  2591. out(fillColor);
  2592. return this;
  2593. };
  2594. var textColor = options.textColor || '0 g';
  2595. /**
  2596. * Gets the text color for upcoming elements.
  2597. *
  2598. * @function
  2599. * @instance
  2600. * @returns {string} colorAsHex
  2601. * @memberOf jsPDF
  2602. * @name getTextColor
  2603. */
  2604. var getTextColor = API.__private__.getTextColor = API.getTextColor = function () {
  2605. return decodeColorString(textColor);
  2606. };
  2607. /**
  2608. * Sets the text color for upcoming elements.
  2609. *
  2610. * Depending on the number of arguments given, Gray, RGB, or CMYK
  2611. * color space is implied.
  2612. *
  2613. * When only ch1 is given, "Gray" color space is implied and it
  2614. * must be a value in the range from 0.00 (solid black) to to 1.00 (white)
  2615. * if values are communicated as String types, or in range from 0 (black)
  2616. * to 255 (white) if communicated as Number type.
  2617. * The RGB-like 0-255 range is provided for backward compatibility.
  2618. *
  2619. * When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
  2620. * value must be in the range from 0.00 (minimum intensity) to to 1.00
  2621. * (max intensity) if values are communicated as String types, or
  2622. * from 0 (min intensity) to to 255 (max intensity) if values are communicated
  2623. * as Number types.
  2624. * The RGB-like 0-255 range is provided for backward compatibility.
  2625. *
  2626. * When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
  2627. * value must be a in the range from 0.00 (0% concentration) to to
  2628. * 1.00 (100% concentration)
  2629. *
  2630. * Because JavaScript treats fixed point numbers badly (rounds to
  2631. * floating point nearest to binary representation) it is highly advised to
  2632. * communicate the fractional numbers as String types, not JavaScript Number type.
  2633. *
  2634. * @param {Number|String} ch1 Color channel value or {string} ch1 color value in hexadecimal, example: '#FFFFFF'.
  2635. * @param {Number|String} ch2 Color channel value.
  2636. * @param {Number|String} ch3 Color channel value.
  2637. * @param {Number|String} ch4 Color channel value.
  2638. *
  2639. * @function
  2640. * @instance
  2641. * @returns {jsPDF}
  2642. * @memberOf jsPDF
  2643. * @name setTextColor
  2644. */
  2645. var setTextColor = API.__private__.setTextColor = API.setTextColor = function (ch1, ch2, ch3, ch4) {
  2646. var options = {
  2647. "ch1": ch1,
  2648. "ch2": ch2,
  2649. "ch3": ch3,
  2650. "ch4": ch4,
  2651. "pdfColorType": "text",
  2652. "precision": 3
  2653. };
  2654. textColor = encodeColorString(options);
  2655. return this;
  2656. };
  2657. var activeCharSpace = options.charSpace || 0;
  2658. /**
  2659. * Get global value of CharSpace.
  2660. *
  2661. * @function
  2662. * @instance
  2663. * @returns {number} charSpace
  2664. * @memberOf jsPDF
  2665. * @name getCharSpace
  2666. */
  2667. var getCharSpace = API.__private__.getCharSpace = API.getCharSpace = function () {
  2668. return activeCharSpace;
  2669. };
  2670. /**
  2671. * Set global value of CharSpace.
  2672. *
  2673. * @param {number} charSpace
  2674. * @function
  2675. * @instance
  2676. * @returns {jsPDF} jsPDF-instance
  2677. * @memberOf jsPDF
  2678. * @name setCharSpace
  2679. */
  2680. var setCharSpace = API.__private__.setCharSpace = API.setCharSpace = function (charSpace) {
  2681. if (isNaN(charSpace)) {
  2682. throw new Error('Invalid argument passed to jsPDF.setCharSpace');
  2683. }
  2684. activeCharSpace = charSpace;
  2685. return this;
  2686. };
  2687. var lineCapID = 0;
  2688. /**
  2689. * Is an Object providing a mapping from human-readable to
  2690. * integer flag values designating the varieties of line cap
  2691. * and join styles.
  2692. *
  2693. * @memberOf jsPDF
  2694. * @name CapJoinStyles
  2695. */
  2696. API.CapJoinStyles = {
  2697. 0: 0,
  2698. 'butt': 0,
  2699. 'but': 0,
  2700. 'miter': 0,
  2701. 1: 1,
  2702. 'round': 1,
  2703. 'rounded': 1,
  2704. 'circle': 1,
  2705. 2: 2,
  2706. 'projecting': 2,
  2707. 'project': 2,
  2708. 'square': 2,
  2709. 'bevel': 2
  2710. };
  2711. /**
  2712. * Sets the line cap styles.
  2713. * See {jsPDF.CapJoinStyles} for variants.
  2714. *
  2715. * @param {String|Number} style A string or number identifying the type of line cap.
  2716. * @function
  2717. * @instance
  2718. * @returns {jsPDF}
  2719. * @memberOf jsPDF
  2720. * @name setLineCap
  2721. */
  2722. var setLineCap = API.__private__.setLineCap = API.setLineCap = function (style) {
  2723. var id = API.CapJoinStyles[style];
  2724. if (id === undefined) {
  2725. throw new Error("Line cap style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
  2726. }
  2727. lineCapID = id;
  2728. out(id + ' J');
  2729. return this;
  2730. };
  2731. var lineJoinID = 0;
  2732. /**
  2733. * Sets the line join styles.
  2734. * See {jsPDF.CapJoinStyles} for variants.
  2735. *
  2736. * @param {String|Number} style A string or number identifying the type of line join.
  2737. * @function
  2738. * @instance
  2739. * @returns {jsPDF}
  2740. * @memberOf jsPDF
  2741. * @name setLineJoin
  2742. */
  2743. var setLineJoin = API.__private__.setLineJoin = API.setLineJoin = function (style) {
  2744. var id = API.CapJoinStyles[style];
  2745. if (id === undefined) {
  2746. throw new Error("Line join style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
  2747. }
  2748. lineJoinID = id;
  2749. out(id + ' j');
  2750. return this;
  2751. };
  2752. var miterLimit;
  2753. /**
  2754. * Sets the miterLimit property, which effects the maximum miter length.
  2755. *
  2756. * @param {number} length The length of the miter
  2757. * @function
  2758. * @instance
  2759. * @returns {jsPDF}
  2760. * @memberOf jsPDF
  2761. * @name setMiterLimit
  2762. */
  2763. var setMiterLimit = API.__private__.setMiterLimit = API.setMiterLimit = function (length) {
  2764. length = length || 0;
  2765. if (isNaN(length)) {
  2766. throw new Error('Invalid argument passed to jsPDF.setMiterLimit');
  2767. }
  2768. miterLimit = parseFloat(f2(length * k));
  2769. out(miterLimit + ' M');
  2770. return this;
  2771. };
  2772. /**
  2773. * Saves as PDF document. An alias of jsPDF.output('save', 'filename.pdf').
  2774. * Uses FileSaver.js-method saveAs.
  2775. *
  2776. * @memberOf jsPDF
  2777. * @name save
  2778. * @function
  2779. * @instance
  2780. * @param {string} filename The filename including extension.
  2781. * @param {Object} options An Object with additional options, possible options: 'returnPromise'.
  2782. * @returns {jsPDF} jsPDF-instance
  2783. */
  2784. API.save = function (filename, options) {
  2785. filename = filename || 'generated.pdf';
  2786. options = options || {};
  2787. options.returnPromise = options.returnPromise || false;
  2788. if (options.returnPromise === false) {
  2789. saveAs(getBlob(buildDocument()), filename);
  2790. if (typeof saveAs.unload === 'function') {
  2791. if (global.setTimeout) {
  2792. setTimeout(saveAs.unload, 911);
  2793. }
  2794. }
  2795. } else {
  2796. return new Promise(function (resolve, reject) {
  2797. try {
  2798. var result = saveAs(getBlob(buildDocument()), filename);
  2799. if (typeof saveAs.unload === 'function') {
  2800. if (global.setTimeout) {
  2801. setTimeout(saveAs.unload, 911);
  2802. }
  2803. }
  2804. resolve(result);
  2805. } catch (e) {
  2806. reject(e.message);
  2807. }
  2808. });
  2809. }
  2810. }; // applying plugins (more methods) ON TOP of built-in API.
  2811. // this is intentional as we allow plugins to override
  2812. // built-ins
  2813. for (var plugin in jsPDF.API) {
  2814. if (jsPDF.API.hasOwnProperty(plugin)) {
  2815. if (plugin === 'events' && jsPDF.API.events.length) {
  2816. (function (events, newEvents) {
  2817. // jsPDF.API.events is a JS Array of Arrays
  2818. // where each Array is a pair of event name, handler
  2819. // Events were added by plugins to the jsPDF instantiator.
  2820. // These are always added to the new instance and some ran
  2821. // during instantiation.
  2822. var eventname, handler_and_args, i;
  2823. for (i = newEvents.length - 1; i !== -1; i--) {
  2824. // subscribe takes 3 args: 'topic', function, runonce_flag
  2825. // if undefined, runonce is false.
  2826. // users can attach callback directly,
  2827. // or they can attach an array with [callback, runonce_flag]
  2828. // that's what the "apply" magic is for below.
  2829. eventname = newEvents[i][0];
  2830. handler_and_args = newEvents[i][1];
  2831. events.subscribe.apply(events, [eventname].concat(typeof handler_and_args === 'function' ? [handler_and_args] : handler_and_args));
  2832. }
  2833. })(events, jsPDF.API.events);
  2834. } else {
  2835. API[plugin] = jsPDF.API[plugin];
  2836. }
  2837. }
  2838. }
  2839. /**
  2840. * Object exposing internal API to plugins
  2841. * @public
  2842. * @ignore
  2843. */
  2844. API.internal = {
  2845. 'pdfEscape': pdfEscape,
  2846. 'getStyle': getStyle,
  2847. 'getFont': function getFont() {
  2848. return fonts[_getFont.apply(API, arguments)];
  2849. },
  2850. 'getFontSize': getFontSize,
  2851. 'getCharSpace': getCharSpace,
  2852. 'getTextColor': getTextColor,
  2853. 'getLineHeight': getLineHeight,
  2854. 'getLineHeightFactor': getLineHeightFactor,
  2855. 'write': write,
  2856. 'getHorizontalCoordinate': getHorizontalCoordinate,
  2857. 'getVerticalCoordinate': getVerticalCoordinate,
  2858. 'getCoordinateString': getHorizontalCoordinateString,
  2859. 'getVerticalCoordinateString': getVerticalCoordinateString,
  2860. 'collections': {},
  2861. 'newObject': newObject,
  2862. 'newAdditionalObject': newAdditionalObject,
  2863. 'newObjectDeferred': newObjectDeferred,
  2864. 'newObjectDeferredBegin': newObjectDeferredBegin,
  2865. 'getFilters': getFilters,
  2866. 'putStream': putStream,
  2867. 'events': events,
  2868. // ratio that you use in multiplication of a given "size" number to arrive to 'point'
  2869. // units of measurement.
  2870. // scaleFactor is set at initialization of the document and calculated against the stated
  2871. // default measurement units for the document.
  2872. // If default is "mm", k is the number that will turn number in 'mm' into 'points' number.
  2873. // through multiplication.
  2874. 'scaleFactor': k,
  2875. 'pageSize': {
  2876. getWidth: function getWidth() {
  2877. return (pagesContext[currentPage].mediaBox.topRightX - pagesContext[currentPage].mediaBox.bottomLeftX) / k;
  2878. },
  2879. setWidth: function setWidth(value) {
  2880. pagesContext[currentPage].mediaBox.topRightX = value * k + pagesContext[currentPage].mediaBox.bottomLeftX;
  2881. },
  2882. getHeight: function getHeight() {
  2883. return (pagesContext[currentPage].mediaBox.topRightY - pagesContext[currentPage].mediaBox.bottomLeftY) / k;
  2884. },
  2885. setHeight: function setHeight(value) {
  2886. pagesContext[currentPage].mediaBox.topRightY = value * k + pagesContext[currentPage].mediaBox.bottomLeftY;
  2887. }
  2888. },
  2889. 'output': output,
  2890. 'getNumberOfPages': getNumberOfPages,
  2891. 'pages': pages,
  2892. 'out': out,
  2893. 'f2': f2,
  2894. 'f3': f3,
  2895. 'getPageInfo': getPageInfo,
  2896. 'getPageInfoByObjId': getPageInfoByObjId,
  2897. 'getCurrentPageInfo': getCurrentPageInfo,
  2898. 'getPDFVersion': getPdfVersion,
  2899. 'hasHotfix': hasHotfix //Expose the hasHotfix check so plugins can also check them.
  2900. };
  2901. Object.defineProperty(API.internal.pageSize, 'width', {
  2902. get: function get() {
  2903. return (pagesContext[currentPage].mediaBox.topRightX - pagesContext[currentPage].mediaBox.bottomLeftX) / k;
  2904. },
  2905. set: function set(value) {
  2906. pagesContext[currentPage].mediaBox.topRightX = value * k + pagesContext[currentPage].mediaBox.bottomLeftX;
  2907. },
  2908. enumerable: true,
  2909. configurable: true
  2910. });
  2911. Object.defineProperty(API.internal.pageSize, 'height', {
  2912. get: function get() {
  2913. return (pagesContext[currentPage].mediaBox.topRightY - pagesContext[currentPage].mediaBox.bottomLeftY) / k;
  2914. },
  2915. set: function set(value) {
  2916. pagesContext[currentPage].mediaBox.topRightY = value * k + pagesContext[currentPage].mediaBox.bottomLeftY;
  2917. },
  2918. enumerable: true,
  2919. configurable: true
  2920. }); //////////////////////////////////////////////////////
  2921. // continuing initialization of jsPDF Document object
  2922. //////////////////////////////////////////////////////
  2923. // Add the first page automatically
  2924. addFonts(standardFonts);
  2925. activeFontKey = 'F1';
  2926. _addPage(format, orientation);
  2927. events.publish('initialized');
  2928. return API;
  2929. }
  2930. /**
  2931. * jsPDF.API is a STATIC property of jsPDF class.
  2932. * jsPDF.API is an object you can add methods and properties to.
  2933. * The methods / properties you add will show up in new jsPDF objects.
  2934. *
  2935. * One property is prepopulated. It is the 'events' Object. Plugin authors can add topics,
  2936. * callbacks to this object. These will be reassigned to all new instances of jsPDF.
  2937. *
  2938. * @static
  2939. * @public
  2940. * @memberOf jsPDF
  2941. * @name API
  2942. *
  2943. * @example
  2944. * jsPDF.API.mymethod = function(){
  2945. * // 'this' will be ref to internal API object. see jsPDF source
  2946. * // , so you can refer to built-in methods like so:
  2947. * // this.line(....)
  2948. * // this.text(....)
  2949. * }
  2950. * var pdfdoc = new jsPDF()
  2951. * pdfdoc.mymethod() // <- !!!!!!
  2952. */
  2953. jsPDF.API = {
  2954. events: []
  2955. };
  2956. /**
  2957. * The version of jsPDF.
  2958. * @name version
  2959. * @type {string}
  2960. * @memberOf jsPDF
  2961. */
  2962. jsPDF.version = '1.5.3';
  2963. if (typeof define === 'function' && define.amd) {
  2964. define('jsPDF', function () {
  2965. return jsPDF;
  2966. });
  2967. } else if (typeof module !== 'undefined' && module.exports) {
  2968. module.exports = jsPDF;
  2969. module.exports.jsPDF = jsPDF;
  2970. } else {
  2971. global.jsPDF = jsPDF;
  2972. }
  2973. return jsPDF;
  2974. }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || typeof global !== "undefined" && global || Function('return typeof this === "object" && this.content')() || Function('return this')()); // `self` is undefined in Firefox for Android content script context
  2975. // while `this` is nsIContentFrameMessageManager
  2976. // with an attribute `content` that corresponds to the window
  2977. /*rollup-keeper-start*/
  2978. window.tmp = jsPDF;
  2979. /*rollup-keeper-end*/
  2980. /**
  2981. * @license
  2982. * Copyright (c) 2016 Alexander Weidt,
  2983. * https://github.com/BiggA94
  2984. *
  2985. * Licensed under the MIT License. http://opensource.org/licenses/mit-license
  2986. */
  2987. /**
  2988. * jsPDF AcroForm Plugin
  2989. * @module AcroForm
  2990. */
  2991. (function (jsPDFAPI, globalObj) {
  2992. var scope;
  2993. var scaleFactor = 1;
  2994. var pdfEscape = function pdfEscape(value) {
  2995. return value.replace(/\\/g, '\\\\').replace(/\(/g, '\\(').replace(/\)/g, '\\)');
  2996. };
  2997. var pdfUnescape = function pdfUnescape(value) {
  2998. return value.replace(/\\\\/g, '\\').replace(/\\\(/g, '(').replace(/\\\)/g, ')');
  2999. };
  3000. var f2 = function f2(number) {
  3001. if (isNaN(number)) {
  3002. throw new Error('Invalid argument passed to jsPDF.f2');
  3003. }
  3004. return number.toFixed(2); // Ie, %.2f
  3005. };
  3006. var f5 = function f5(number) {
  3007. if (isNaN(number)) {
  3008. throw new Error('Invalid argument passed to jsPDF.f2');
  3009. }
  3010. return number.toFixed(5); // Ie, %.2f
  3011. };
  3012. jsPDFAPI.__acroform__ = {};
  3013. var inherit = function inherit(child, parent) {
  3014. child.prototype = Object.create(parent.prototype);
  3015. child.prototype.constructor = child;
  3016. };
  3017. var scale = function scale(x) {
  3018. return x * scaleFactor;
  3019. };
  3020. var antiScale = function antiScale(x) {
  3021. return x / scaleFactor;
  3022. };
  3023. var createFormXObject = function createFormXObject(formObject) {
  3024. var xobj = new AcroFormXObject();
  3025. var height = AcroFormAppearance.internal.getHeight(formObject) || 0;
  3026. var width = AcroFormAppearance.internal.getWidth(formObject) || 0;
  3027. xobj.BBox = [0, 0, Number(f2(width)), Number(f2(height))];
  3028. return xobj;
  3029. };
  3030. /**
  3031. * Bit-Operations
  3032. */
  3033. var setBit = jsPDFAPI.__acroform__.setBit = function (number, bitPosition) {
  3034. number = number || 0;
  3035. bitPosition = bitPosition || 0;
  3036. if (isNaN(number) || isNaN(bitPosition)) {
  3037. throw new Error('Invalid arguments passed to jsPDF.API.__acroform__.setBit');
  3038. }
  3039. var bitMask = 1 << bitPosition;
  3040. number |= bitMask;
  3041. return number;
  3042. };
  3043. var clearBit = jsPDFAPI.__acroform__.clearBit = function (number, bitPosition) {
  3044. number = number || 0;
  3045. bitPosition = bitPosition || 0;
  3046. if (isNaN(number) || isNaN(bitPosition)) {
  3047. throw new Error('Invalid arguments passed to jsPDF.API.__acroform__.clearBit');
  3048. }
  3049. var bitMask = 1 << bitPosition;
  3050. number &= ~bitMask;
  3051. return number;
  3052. };
  3053. var getBit = jsPDFAPI.__acroform__.getBit = function (number, bitPosition) {
  3054. if (isNaN(number) || isNaN(bitPosition)) {
  3055. throw new Error('Invalid arguments passed to jsPDF.API.__acroform__.getBit');
  3056. }
  3057. return (number & 1 << bitPosition) === 0 ? 0 : 1;
  3058. };
  3059. /*
  3060. * Ff starts counting the bit position at 1 and not like javascript at 0
  3061. */
  3062. var getBitForPdf = jsPDFAPI.__acroform__.getBitForPdf = function (number, bitPosition) {
  3063. if (isNaN(number) || isNaN(bitPosition)) {
  3064. throw new Error('Invalid arguments passed to jsPDF.API.__acroform__.getBitForPdf');
  3065. }
  3066. return getBit(number, bitPosition - 1);
  3067. };
  3068. var setBitForPdf = jsPDFAPI.__acroform__.setBitForPdf = function (number, bitPosition) {
  3069. if (isNaN(number) || isNaN(bitPosition)) {
  3070. throw new Error('Invalid arguments passed to jsPDF.API.__acroform__.setBitForPdf');
  3071. }
  3072. return setBit(number, bitPosition - 1);
  3073. };
  3074. var clearBitForPdf = jsPDFAPI.__acroform__.clearBitForPdf = function (number, bitPosition, value) {
  3075. if (isNaN(number) || isNaN(bitPosition)) {
  3076. throw new Error('Invalid arguments passed to jsPDF.API.__acroform__.clearBitForPdf');
  3077. }
  3078. return clearBit(number, bitPosition - 1);
  3079. };
  3080. var calculateCoordinates = jsPDFAPI.__acroform__.calculateCoordinates = function (args) {
  3081. var getHorizontalCoordinate = this.internal.getHorizontalCoordinate;
  3082. var getVerticalCoordinate = this.internal.getVerticalCoordinate;
  3083. var x = args[0];
  3084. var y = args[1];
  3085. var w = args[2];
  3086. var h = args[3];
  3087. var coordinates = {};
  3088. coordinates.lowerLeft_X = getHorizontalCoordinate(x) || 0;
  3089. coordinates.lowerLeft_Y = getVerticalCoordinate(y + h) || 0;
  3090. coordinates.upperRight_X = getHorizontalCoordinate(x + w) || 0;
  3091. coordinates.upperRight_Y = getVerticalCoordinate(y) || 0;
  3092. return [Number(f2(coordinates.lowerLeft_X)), Number(f2(coordinates.lowerLeft_Y)), Number(f2(coordinates.upperRight_X)), Number(f2(coordinates.upperRight_Y))];
  3093. };
  3094. var calculateAppearanceStream = function calculateAppearanceStream(formObject) {
  3095. if (formObject.appearanceStreamContent) {
  3096. return formObject.appearanceStreamContent;
  3097. }
  3098. if (!formObject.V && !formObject.DV) {
  3099. return;
  3100. } // else calculate it
  3101. var stream = [];
  3102. var text = formObject.V || formObject.DV;
  3103. var calcRes = calculateX(formObject, text);
  3104. var fontKey = scope.internal.getFont(formObject.fontName, formObject.fontStyle).id; //PDF 32000-1:2008, page 444
  3105. stream.push('/Tx BMC');
  3106. stream.push('q');
  3107. stream.push('BT'); // Begin Text
  3108. stream.push(scope.__private__.encodeColorString(formObject.color));
  3109. stream.push('/' + fontKey + ' ' + f2(calcRes.fontSize) + ' Tf');
  3110. stream.push('1 0 0 1 0 0 Tm'); // Transformation Matrix
  3111. stream.push(calcRes.text);
  3112. stream.push('ET'); // End Text
  3113. stream.push('Q');
  3114. stream.push('EMC');
  3115. var appearanceStreamContent = new createFormXObject(formObject);
  3116. appearanceStreamContent.stream = stream.join("\n");
  3117. return appearanceStreamContent;
  3118. };
  3119. var calculateX = function calculateX(formObject, text) {
  3120. var maxFontSize = formObject.maxFontSize || 12;
  3121. var font = formObject.fontName;
  3122. var returnValue = {
  3123. text: "",
  3124. fontSize: ""
  3125. }; // Remove Brackets
  3126. text = text.substr(0, 1) == '(' ? text.substr(1) : text;
  3127. text = text.substr(text.length - 1) == ')' ? text.substr(0, text.length - 1) : text; // split into array of words
  3128. var textSplit = text.split(' ');
  3129. var color = scope.__private__.encodeColorString(formObject.color);
  3130. var fontSize = maxFontSize; // The Starting fontSize (The Maximum)
  3131. var lineSpacing = 2;
  3132. var borderPadding = 2;
  3133. var height = AcroFormAppearance.internal.getHeight(formObject) || 0;
  3134. height = height < 0 ? -height : height;
  3135. var width = AcroFormAppearance.internal.getWidth(formObject) || 0;
  3136. width = width < 0 ? -width : width;
  3137. var isSmallerThanWidth = function isSmallerThanWidth(i, lastLine, fontSize) {
  3138. if (i + 1 < textSplit.length) {
  3139. var tmp = lastLine + " " + textSplit[i + 1];
  3140. var TextWidth = calculateFontSpace(tmp, formObject, fontSize).width;
  3141. var FieldWidth = width - 2 * borderPadding;
  3142. return TextWidth <= FieldWidth;
  3143. } else {
  3144. return false;
  3145. }
  3146. };
  3147. fontSize++;
  3148. FontSize: while (true) {
  3149. var text = "";
  3150. fontSize--;
  3151. var textHeight = calculateFontSpace("3", formObject, fontSize).height;
  3152. var startY = formObject.multiline ? height - fontSize : (height - textHeight) / 2;
  3153. startY += lineSpacing;
  3154. var startX = -borderPadding;
  3155. var lastY = startY;
  3156. var firstWordInLine = 0,
  3157. lastWordInLine = 0;
  3158. var lastLength = 0;
  3159. if (fontSize <= 0) {
  3160. // In case, the Text doesn't fit at all
  3161. fontSize = 12;
  3162. text = "(...) Tj\n";
  3163. text += "% Width of Text: " + calculateFontSpace(text, formObject, fontSize).width + ", FieldWidth:" + width + "\n";
  3164. break;
  3165. }
  3166. lastLength = calculateFontSpace(textSplit[0] + " ", formObject, fontSize).width;
  3167. var lastLine = "";
  3168. var lineCount = 0;
  3169. Line: for (var i in textSplit) {
  3170. if (textSplit.hasOwnProperty(i)) {
  3171. lastLine += textSplit[i] + " "; // Remove last blank
  3172. lastLine = lastLine.substr(lastLine.length - 1) == " " ? lastLine.substr(0, lastLine.length - 1) : lastLine;
  3173. var key = parseInt(i);
  3174. lastLength = calculateFontSpace(lastLine + " ", formObject, fontSize).width;
  3175. var nextLineIsSmaller = isSmallerThanWidth(key, lastLine, fontSize);
  3176. var isLastWord = i >= textSplit.length - 1;
  3177. if (nextLineIsSmaller && !isLastWord) {
  3178. lastLine += " ";
  3179. continue; // Line
  3180. } else if (!nextLineIsSmaller && !isLastWord) {
  3181. if (!formObject.multiline) {
  3182. continue FontSize;
  3183. } else {
  3184. if ((textHeight + lineSpacing) * (lineCount + 2) + lineSpacing > height) {
  3185. // If the Text is higher than the
  3186. // FieldObject
  3187. continue FontSize;
  3188. }
  3189. lastWordInLine = key; // go on
  3190. }
  3191. } else if (isLastWord) {
  3192. lastWordInLine = key;
  3193. } else {
  3194. if (formObject.multiline && (textHeight + lineSpacing) * (lineCount + 2) + lineSpacing > height) {
  3195. // If the Text is higher than the FieldObject
  3196. continue FontSize;
  3197. }
  3198. }
  3199. var line = '';
  3200. for (var x = firstWordInLine; x <= lastWordInLine; x++) {
  3201. line += textSplit[x] + ' ';
  3202. } // Remove last blank
  3203. line = line.substr(line.length - 1) == " " ? line.substr(0, line.length - 1) : line; // lastLength -= blankSpace.width;
  3204. lastLength = calculateFontSpace(line, formObject, fontSize).width; // Calculate startX
  3205. switch (formObject.textAlign) {
  3206. case 'right':
  3207. startX = width - lastLength - borderPadding;
  3208. break;
  3209. case 'center':
  3210. startX = (width - lastLength) / 2;
  3211. break;
  3212. case 'left':
  3213. default:
  3214. startX = borderPadding;
  3215. break;
  3216. }
  3217. text += f2(startX) + ' ' + f2(lastY) + ' Td\n';
  3218. text += '(' + pdfEscape(line) + ') Tj\n'; // reset X in PDF
  3219. text += -f2(startX) + ' 0 Td\n'; // After a Line, adjust y position
  3220. lastY = -(fontSize + lineSpacing);
  3221. lastLength = 0;
  3222. firstWordInLine = lastWordInLine + 1;
  3223. lineCount++;
  3224. lastLine = "";
  3225. continue Line;
  3226. }
  3227. }
  3228. break;
  3229. }
  3230. returnValue.text = text;
  3231. returnValue.fontSize = fontSize;
  3232. return returnValue;
  3233. };
  3234. /**
  3235. * Small workaround for calculating the TextMetric approximately.
  3236. *
  3237. * @param text
  3238. * @param fontsize
  3239. * @returns {TextMetrics} (Has Height and Width)
  3240. */
  3241. var calculateFontSpace = function calculateFontSpace(text, formObject, fontSize) {
  3242. var font = scope.internal.getFont(formObject.fontName, formObject.fontStyle);
  3243. var width = scope.getStringUnitWidth(text, {
  3244. font: font,
  3245. fontSize: parseFloat(fontSize),
  3246. charSpace: 0
  3247. }) * parseFloat(fontSize);
  3248. var height = scope.getStringUnitWidth("3", {
  3249. font: font,
  3250. fontSize: parseFloat(fontSize),
  3251. charSpace: 0
  3252. }) * parseFloat(fontSize) * 1.5;
  3253. return {
  3254. height: height,
  3255. width: width
  3256. };
  3257. };
  3258. var acroformPluginTemplate = {
  3259. fields: [],
  3260. xForms: [],
  3261. /**
  3262. * acroFormDictionaryRoot contains information about the AcroForm
  3263. * Dictionary 0: The Event-Token, the AcroFormDictionaryCallback has
  3264. * 1: The Object ID of the Root
  3265. */
  3266. acroFormDictionaryRoot: null,
  3267. /**
  3268. * After the PDF gets evaluated, the reference to the root has to be
  3269. * reset, this indicates, whether the root has already been printed
  3270. * out
  3271. */
  3272. printedOut: false,
  3273. internal: null,
  3274. isInitialized: false
  3275. };
  3276. var annotReferenceCallback = function annotReferenceCallback() {
  3277. //set objId to undefined and force it to get a new objId on buildDocument
  3278. scope.internal.acroformPlugin.acroFormDictionaryRoot.objId = undefined;
  3279. var fields = scope.internal.acroformPlugin.acroFormDictionaryRoot.Fields;
  3280. for (var i in fields) {
  3281. if (fields.hasOwnProperty(i)) {
  3282. var formObject = fields[i]; //set objId to undefined and force it to get a new objId on buildDocument
  3283. formObject.objId = undefined; // add Annot Reference!
  3284. if (formObject.hasAnnotation) {
  3285. // If theres an Annotation Widget in the Form Object, put the
  3286. // Reference in the /Annot array
  3287. createAnnotationReference.call(scope, formObject);
  3288. }
  3289. }
  3290. }
  3291. };
  3292. var putForm = function putForm(formObject) {
  3293. if (scope.internal.acroformPlugin.printedOut) {
  3294. scope.internal.acroformPlugin.printedOut = false;
  3295. scope.internal.acroformPlugin.acroFormDictionaryRoot = null;
  3296. }
  3297. if (!scope.internal.acroformPlugin.acroFormDictionaryRoot) {
  3298. initializeAcroForm.call(scope);
  3299. }
  3300. scope.internal.acroformPlugin.acroFormDictionaryRoot.Fields.push(formObject);
  3301. };
  3302. /**
  3303. * Create the Reference to the widgetAnnotation, so that it gets referenced
  3304. * in the Annot[] int the+ (Requires the Annotation Plugin)
  3305. */
  3306. var createAnnotationReference = function createAnnotationReference(object) {
  3307. var options = {
  3308. type: 'reference',
  3309. object: object
  3310. };
  3311. var findEntry = function findEntry(entry) {
  3312. return entry.type === options.type && entry.object === options.object;
  3313. };
  3314. if (scope.internal.getPageInfo(object.page).pageContext.annotations.find(findEntry) === undefined) {
  3315. scope.internal.getPageInfo(object.page).pageContext.annotations.push(options);
  3316. }
  3317. }; // Callbacks
  3318. var putCatalogCallback = function putCatalogCallback() {
  3319. // Put reference to AcroForm to DocumentCatalog
  3320. if (typeof scope.internal.acroformPlugin.acroFormDictionaryRoot != 'undefined') {
  3321. // for safety, shouldn't normally be the case
  3322. scope.internal.write('/AcroForm ' + scope.internal.acroformPlugin.acroFormDictionaryRoot.objId + ' ' + 0 + ' R');
  3323. } else {
  3324. throw new Error('putCatalogCallback: Root missing.');
  3325. }
  3326. };
  3327. /**
  3328. * Adds /Acroform X 0 R to Document Catalog, and creates the AcroForm
  3329. * Dictionary
  3330. */
  3331. var AcroFormDictionaryCallback = function AcroFormDictionaryCallback() {
  3332. // Remove event
  3333. scope.internal.events.unsubscribe(scope.internal.acroformPlugin.acroFormDictionaryRoot._eventID);
  3334. delete scope.internal.acroformPlugin.acroFormDictionaryRoot._eventID;
  3335. scope.internal.acroformPlugin.printedOut = true;
  3336. };
  3337. /**
  3338. * Creates the single Fields and writes them into the Document
  3339. *
  3340. * If fieldArray is set, use the fields that are inside it instead of the
  3341. * fields from the AcroRoot (for the FormXObjects...)
  3342. */
  3343. var createFieldCallback = function createFieldCallback(fieldArray) {
  3344. var standardFields = !fieldArray;
  3345. if (!fieldArray) {
  3346. // in case there is no fieldArray specified, we want to print out
  3347. // the Fields of the AcroForm
  3348. // Print out Root
  3349. scope.internal.newObjectDeferredBegin(scope.internal.acroformPlugin.acroFormDictionaryRoot.objId, true);
  3350. scope.internal.acroformPlugin.acroFormDictionaryRoot.putStream();
  3351. }
  3352. var fieldArray = fieldArray || scope.internal.acroformPlugin.acroFormDictionaryRoot.Kids;
  3353. for (var i in fieldArray) {
  3354. if (fieldArray.hasOwnProperty(i)) {
  3355. var fieldObject = fieldArray[i];
  3356. var keyValueList = [];
  3357. var oldRect = fieldObject.Rect;
  3358. if (fieldObject.Rect) {
  3359. fieldObject.Rect = calculateCoordinates.call(this, fieldObject.Rect);
  3360. } // Start Writing the Object
  3361. scope.internal.newObjectDeferredBegin(fieldObject.objId, true);
  3362. fieldObject.DA = AcroFormAppearance.createDefaultAppearanceStream(fieldObject);
  3363. if (_typeof(fieldObject) === "object" && typeof fieldObject.getKeyValueListForStream === "function") {
  3364. keyValueList = fieldObject.getKeyValueListForStream();
  3365. }
  3366. fieldObject.Rect = oldRect;
  3367. if (fieldObject.hasAppearanceStream && !fieldObject.appearanceStreamContent) {
  3368. // Calculate Appearance
  3369. var appearance = calculateAppearanceStream.call(this, fieldObject);
  3370. keyValueList.push({
  3371. key: 'AP',
  3372. value: "<</N " + appearance + ">>"
  3373. });
  3374. scope.internal.acroformPlugin.xForms.push(appearance);
  3375. } // Assume AppearanceStreamContent is a Array with N,R,D (at least
  3376. // one of them!)
  3377. if (fieldObject.appearanceStreamContent) {
  3378. var appearanceStreamString = ""; // Iterate over N,R and D
  3379. for (var k in fieldObject.appearanceStreamContent) {
  3380. if (fieldObject.appearanceStreamContent.hasOwnProperty(k)) {
  3381. var value = fieldObject.appearanceStreamContent[k];
  3382. appearanceStreamString += "/" + k + " ";
  3383. appearanceStreamString += "<<";
  3384. if (Object.keys(value).length >= 1 || Array.isArray(value)) {
  3385. // appearanceStream is an Array or Object!
  3386. for (var i in value) {
  3387. if (value.hasOwnProperty(i)) {
  3388. var obj = value[i];
  3389. if (typeof obj === 'function') {
  3390. // if Function is referenced, call it in order
  3391. // to get the FormXObject
  3392. obj = obj.call(this, fieldObject);
  3393. }
  3394. appearanceStreamString += "/" + i + " " + obj + " "; // In case the XForm is already used, e.g. OffState
  3395. // of CheckBoxes, don't add it
  3396. if (!(scope.internal.acroformPlugin.xForms.indexOf(obj) >= 0)) scope.internal.acroformPlugin.xForms.push(obj);
  3397. }
  3398. }
  3399. } else {
  3400. var obj = value;
  3401. if (typeof obj === 'function') {
  3402. // if Function is referenced, call it in order to
  3403. // get the FormXObject
  3404. obj = obj.call(this, fieldObject);
  3405. }
  3406. appearanceStreamString += "/" + i + " " + obj;
  3407. if (!(scope.internal.acroformPlugin.xForms.indexOf(obj) >= 0)) scope.internal.acroformPlugin.xForms.push(obj);
  3408. }
  3409. appearanceStreamString += ">>";
  3410. }
  3411. } // appearance stream is a normal Object..
  3412. keyValueList.push({
  3413. key: 'AP',
  3414. value: "<<\n" + appearanceStreamString + ">>"
  3415. });
  3416. }
  3417. scope.internal.putStream({
  3418. additionalKeyValues: keyValueList
  3419. });
  3420. scope.internal.out("endobj");
  3421. }
  3422. }
  3423. if (standardFields) {
  3424. createXFormObjectCallback.call(this, scope.internal.acroformPlugin.xForms);
  3425. }
  3426. };
  3427. var createXFormObjectCallback = function createXFormObjectCallback(fieldArray) {
  3428. for (var i in fieldArray) {
  3429. if (fieldArray.hasOwnProperty(i)) {
  3430. var key = i;
  3431. var fieldObject = fieldArray[i]; // Start Writing the Object
  3432. scope.internal.newObjectDeferredBegin(fieldObject && fieldObject.objId, true);
  3433. if (_typeof(fieldObject) === "object" && typeof fieldObject.putStream === "function") {
  3434. fieldObject.putStream();
  3435. }
  3436. delete fieldArray[key];
  3437. }
  3438. }
  3439. };
  3440. var initializeAcroForm = function initializeAcroForm() {
  3441. if (this.internal !== undefined && (this.internal.acroformPlugin === undefined || this.internal.acroformPlugin.isInitialized === false)) {
  3442. scope = this;
  3443. AcroFormField.FieldNum = 0;
  3444. this.internal.acroformPlugin = JSON.parse(JSON.stringify(acroformPluginTemplate));
  3445. if (this.internal.acroformPlugin.acroFormDictionaryRoot) {
  3446. throw new Error("Exception while creating AcroformDictionary");
  3447. }
  3448. scaleFactor = scope.internal.scaleFactor; // The Object Number of the AcroForm Dictionary
  3449. scope.internal.acroformPlugin.acroFormDictionaryRoot = new AcroFormDictionary(); // add Callback for creating the AcroForm Dictionary
  3450. scope.internal.acroformPlugin.acroFormDictionaryRoot._eventID = scope.internal.events.subscribe('postPutResources', AcroFormDictionaryCallback);
  3451. scope.internal.events.subscribe('buildDocument', annotReferenceCallback); // buildDocument
  3452. // Register event, that is triggered when the DocumentCatalog is
  3453. // written, in order to add /AcroForm
  3454. scope.internal.events.subscribe('putCatalog', putCatalogCallback); // Register event, that creates all Fields
  3455. scope.internal.events.subscribe('postPutPages', createFieldCallback);
  3456. scope.internal.acroformPlugin.isInitialized = true;
  3457. }
  3458. }; //PDF 32000-1:2008, page 26, 7.3.6
  3459. var arrayToPdfArray = jsPDFAPI.__acroform__.arrayToPdfArray = function (array) {
  3460. if (Array.isArray(array)) {
  3461. var content = '[';
  3462. for (var i = 0; i < array.length; i++) {
  3463. if (i !== 0) {
  3464. content += ' ';
  3465. }
  3466. switch (_typeof(array[i])) {
  3467. case 'boolean':
  3468. case 'number':
  3469. case 'object':
  3470. content += array[i].toString();
  3471. break;
  3472. case 'string':
  3473. if (array[i].substr(0, 1) !== '/') {
  3474. content += '(' + pdfEscape(array[i].toString()) + ')';
  3475. } else {
  3476. content += array[i].toString();
  3477. }
  3478. break;
  3479. }
  3480. }
  3481. content += ']';
  3482. return content;
  3483. }
  3484. throw new Error('Invalid argument passed to jsPDF.__acroform__.arrayToPdfArray');
  3485. };
  3486. function getMatches(string, regex, index) {
  3487. index || (index = 1); // default to the first capturing group
  3488. var matches = [];
  3489. var match;
  3490. while (match = regex.exec(string)) {
  3491. matches.push(match[index]);
  3492. }
  3493. return matches;
  3494. }
  3495. var pdfArrayToStringArray = function pdfArrayToStringArray(array) {
  3496. var result = [];
  3497. if (typeof array === "string") {
  3498. result = getMatches(array, /\((.*?)\)/g);
  3499. }
  3500. return result;
  3501. };
  3502. var toPdfString = function toPdfString(string) {
  3503. string = string || "";
  3504. string.toString();
  3505. string = '(' + pdfEscape(string) + ')';
  3506. return string;
  3507. }; // ##########################
  3508. // Classes
  3509. // ##########################
  3510. /**
  3511. * @class AcroFormPDFObject
  3512. * @classdesc A AcroFormPDFObject
  3513. */
  3514. var AcroFormPDFObject = function AcroFormPDFObject() {
  3515. var _objId;
  3516. /** *
  3517. * @name AcroFormPDFObject#objId
  3518. * @type {any}
  3519. */
  3520. Object.defineProperty(this, 'objId', {
  3521. configurable: true,
  3522. get: function get() {
  3523. if (!_objId) {
  3524. _objId = scope.internal.newObjectDeferred();
  3525. }
  3526. if (!_objId) {
  3527. throw new Error("AcroFormPDFObject: Couldn't create Object ID");
  3528. }
  3529. return _objId;
  3530. },
  3531. set: function set(value) {
  3532. _objId = value;
  3533. }
  3534. });
  3535. };
  3536. /**
  3537. * @function AcroFormPDFObject.toString
  3538. */
  3539. AcroFormPDFObject.prototype.toString = function () {
  3540. return this.objId + " 0 R";
  3541. };
  3542. AcroFormPDFObject.prototype.putStream = function () {
  3543. var keyValueList = this.getKeyValueListForStream();
  3544. scope.internal.putStream({
  3545. data: this.stream,
  3546. additionalKeyValues: keyValueList
  3547. });
  3548. scope.internal.out("endobj");
  3549. };
  3550. /**
  3551. * Returns an key-value-List of all non-configurable Variables from the Object
  3552. *
  3553. * @name getKeyValueListForStream
  3554. * @returns {string}
  3555. */
  3556. AcroFormPDFObject.prototype.getKeyValueListForStream = function () {
  3557. var createKeyValueListFromFieldObject = function createKeyValueListFromFieldObject(fieldObject) {
  3558. var keyValueList = [];
  3559. var keys = Object.getOwnPropertyNames(fieldObject).filter(function (key) {
  3560. return key != 'content' && key != 'appearanceStreamContent' && key.substring(0, 1) != "_";
  3561. });
  3562. for (var i in keys) {
  3563. if (Object.getOwnPropertyDescriptor(fieldObject, keys[i]).configurable === false) {
  3564. var key = keys[i];
  3565. var value = fieldObject[key];
  3566. if (value) {
  3567. if (Array.isArray(value)) {
  3568. keyValueList.push({
  3569. key: key,
  3570. value: arrayToPdfArray(value)
  3571. });
  3572. } else if (value instanceof AcroFormPDFObject) {
  3573. // In case it is a reference to another PDFObject,
  3574. // take the reference number
  3575. keyValueList.push({
  3576. key: key,
  3577. value: value.objId + " 0 R"
  3578. });
  3579. } else if (typeof value !== "function") {
  3580. keyValueList.push({
  3581. key: key,
  3582. value: value
  3583. });
  3584. }
  3585. }
  3586. }
  3587. }
  3588. return keyValueList;
  3589. };
  3590. return createKeyValueListFromFieldObject(this);
  3591. };
  3592. var AcroFormXObject = function AcroFormXObject() {
  3593. AcroFormPDFObject.call(this);
  3594. Object.defineProperty(this, 'Type', {
  3595. value: "/XObject",
  3596. configurable: false,
  3597. writeable: true
  3598. });
  3599. Object.defineProperty(this, 'Subtype', {
  3600. value: "/Form",
  3601. configurable: false,
  3602. writeable: true
  3603. });
  3604. Object.defineProperty(this, 'FormType', {
  3605. value: 1,
  3606. configurable: false,
  3607. writeable: true
  3608. });
  3609. var _BBox = [];
  3610. Object.defineProperty(this, 'BBox', {
  3611. configurable: false,
  3612. writeable: true,
  3613. get: function get() {
  3614. return _BBox;
  3615. },
  3616. set: function set(value) {
  3617. _BBox = value;
  3618. }
  3619. });
  3620. Object.defineProperty(this, 'Resources', {
  3621. value: "2 0 R",
  3622. configurable: false,
  3623. writeable: true
  3624. });
  3625. var _stream;
  3626. Object.defineProperty(this, 'stream', {
  3627. enumerable: false,
  3628. configurable: true,
  3629. set: function set(value) {
  3630. _stream = value.trim();
  3631. },
  3632. get: function get() {
  3633. if (_stream) {
  3634. return _stream;
  3635. } else {
  3636. return null;
  3637. }
  3638. }
  3639. });
  3640. };
  3641. inherit(AcroFormXObject, AcroFormPDFObject);
  3642. var AcroFormDictionary = function AcroFormDictionary() {
  3643. AcroFormPDFObject.call(this);
  3644. var _Kids = [];
  3645. Object.defineProperty(this, 'Kids', {
  3646. enumerable: false,
  3647. configurable: true,
  3648. get: function get() {
  3649. if (_Kids.length > 0) {
  3650. return _Kids;
  3651. } else {
  3652. return;
  3653. }
  3654. }
  3655. });
  3656. Object.defineProperty(this, 'Fields', {
  3657. enumerable: false,
  3658. configurable: false,
  3659. get: function get() {
  3660. return _Kids;
  3661. }
  3662. }); // Default Appearance
  3663. var _DA;
  3664. Object.defineProperty(this, 'DA', {
  3665. enumerable: false,
  3666. configurable: false,
  3667. get: function get() {
  3668. if (!_DA) {
  3669. return;
  3670. }
  3671. return '(' + _DA + ')';
  3672. },
  3673. set: function set(value) {
  3674. _DA = value;
  3675. }
  3676. });
  3677. };
  3678. inherit(AcroFormDictionary, AcroFormPDFObject);
  3679. /**
  3680. * The Field Object contains the Variables, that every Field needs
  3681. *
  3682. * @class AcroFormField
  3683. * @classdesc An AcroForm FieldObject
  3684. */
  3685. var AcroFormField = function AcroFormField() {
  3686. AcroFormPDFObject.call(this); //Annotation-Flag See Table 165
  3687. var _F = 4;
  3688. Object.defineProperty(this, 'F', {
  3689. enumerable: false,
  3690. configurable: false,
  3691. get: function get() {
  3692. return _F;
  3693. },
  3694. set: function set(value) {
  3695. if (!isNaN(value)) {
  3696. _F = value;
  3697. } else {
  3698. throw new Error('Invalid value "' + value + '" for attribute F supplied.');
  3699. }
  3700. }
  3701. });
  3702. /**
  3703. * (PDF 1.2) If set, print the annotation when the page is printed. If clear, never print the annotation, regardless of wether is is displayed on the screen.
  3704. * NOTE 2 This can be useful for annotations representing interactive pushbuttons, which would serve no meaningful purpose on the printed page.
  3705. *
  3706. * @name AcroFormField#showWhenPrinted
  3707. * @default true
  3708. * @type {boolean}
  3709. */
  3710. Object.defineProperty(this, 'showWhenPrinted', {
  3711. enumerable: true,
  3712. configurable: true,
  3713. get: function get() {
  3714. return Boolean(getBitForPdf(_F, 3));
  3715. },
  3716. set: function set(value) {
  3717. if (Boolean(value) === true) {
  3718. this.F = setBitForPdf(_F, 3);
  3719. } else {
  3720. this.F = clearBitForPdf(_F, 3);
  3721. }
  3722. }
  3723. });
  3724. var _Ff = 0;
  3725. Object.defineProperty(this, 'Ff', {
  3726. enumerable: false,
  3727. configurable: false,
  3728. get: function get() {
  3729. return _Ff;
  3730. },
  3731. set: function set(value) {
  3732. if (!isNaN(value)) {
  3733. _Ff = value;
  3734. } else {
  3735. throw new Error('Invalid value "' + value + '" for attribute Ff supplied.');
  3736. }
  3737. }
  3738. });
  3739. var _Rect = [];
  3740. Object.defineProperty(this, 'Rect', {
  3741. enumerable: false,
  3742. configurable: false,
  3743. get: function get() {
  3744. if (_Rect.length === 0) {
  3745. return;
  3746. }
  3747. return _Rect;
  3748. },
  3749. set: function set(value) {
  3750. if (typeof value !== "undefined") {
  3751. _Rect = value;
  3752. } else {
  3753. _Rect = [];
  3754. }
  3755. }
  3756. });
  3757. /**
  3758. * The x-position of the field.
  3759. *
  3760. * @name AcroFormField#x
  3761. * @default null
  3762. * @type {number}
  3763. */
  3764. Object.defineProperty(this, 'x', {
  3765. enumerable: true,
  3766. configurable: true,
  3767. get: function get() {
  3768. if (!_Rect || isNaN(_Rect[0])) {
  3769. return 0;
  3770. }
  3771. return antiScale(_Rect[0]);
  3772. },
  3773. set: function set(value) {
  3774. _Rect[0] = scale(value);
  3775. }
  3776. });
  3777. /**
  3778. * The y-position of the field.
  3779. *
  3780. * @name AcroFormField#y
  3781. * @default null
  3782. * @type {number}
  3783. */
  3784. Object.defineProperty(this, 'y', {
  3785. enumerable: true,
  3786. configurable: true,
  3787. get: function get() {
  3788. if (!_Rect || isNaN(_Rect[1])) {
  3789. return 0;
  3790. }
  3791. return antiScale(_Rect[1]);
  3792. },
  3793. set: function set(value) {
  3794. _Rect[1] = scale(value);
  3795. }
  3796. });
  3797. /**
  3798. * The width of the field.
  3799. *
  3800. * @name AcroFormField#width
  3801. * @default null
  3802. * @type {number}
  3803. */
  3804. Object.defineProperty(this, 'width', {
  3805. enumerable: true,
  3806. configurable: true,
  3807. get: function get() {
  3808. if (!_Rect || isNaN(_Rect[2])) {
  3809. return 0;
  3810. }
  3811. return antiScale(_Rect[2]);
  3812. },
  3813. set: function set(value) {
  3814. _Rect[2] = scale(value);
  3815. }
  3816. });
  3817. /**
  3818. * The height of the field.
  3819. *
  3820. * @name AcroFormField#height
  3821. * @default null
  3822. * @type {number}
  3823. */
  3824. Object.defineProperty(this, 'height', {
  3825. enumerable: true,
  3826. configurable: true,
  3827. get: function get() {
  3828. if (!_Rect || isNaN(_Rect[3])) {
  3829. return 0;
  3830. }
  3831. return antiScale(_Rect[3]);
  3832. },
  3833. set: function set(value) {
  3834. _Rect[3] = scale(value);
  3835. }
  3836. });
  3837. var _FT = "";
  3838. Object.defineProperty(this, 'FT', {
  3839. enumerable: true,
  3840. configurable: false,
  3841. get: function get() {
  3842. return _FT;
  3843. },
  3844. set: function set(value) {
  3845. switch (value) {
  3846. case '/Btn':
  3847. case '/Tx':
  3848. case '/Ch':
  3849. case '/Sig':
  3850. _FT = value;
  3851. break;
  3852. default:
  3853. throw new Error('Invalid value "' + value + '" for attribute FT supplied.');
  3854. }
  3855. }
  3856. });
  3857. var _T = null;
  3858. Object.defineProperty(this, 'T', {
  3859. enumerable: true,
  3860. configurable: false,
  3861. get: function get() {
  3862. if (!_T || _T.length < 1) {
  3863. // In case of a Child from a Radio´Group, you don't need a FieldName
  3864. if (this instanceof AcroFormChildClass) {
  3865. return;
  3866. }
  3867. _T = "FieldObject" + AcroFormField.FieldNum++;
  3868. }
  3869. return '(' + pdfEscape(_T) + ')';
  3870. },
  3871. set: function set(value) {
  3872. _T = value.toString();
  3873. }
  3874. });
  3875. /**
  3876. * (Optional) The partial field name (see 12.7.3.2, “Field Names”).
  3877. *
  3878. * @name AcroFormField#fieldName
  3879. * @default null
  3880. * @type {string}
  3881. */
  3882. Object.defineProperty(this, 'fieldName', {
  3883. configurable: true,
  3884. enumerable: true,
  3885. get: function get() {
  3886. return _T;
  3887. },
  3888. set: function set(value) {
  3889. _T = value;
  3890. }
  3891. });
  3892. var _fontName = 'helvetica';
  3893. /**
  3894. * The fontName of the font to be used.
  3895. *
  3896. * @name AcroFormField#fontName
  3897. * @default 'helvetica'
  3898. * @type {string}
  3899. */
  3900. Object.defineProperty(this, 'fontName', {
  3901. enumerable: true,
  3902. configurable: true,
  3903. get: function get() {
  3904. return _fontName;
  3905. },
  3906. set: function set(value) {
  3907. _fontName = value;
  3908. }
  3909. });
  3910. var _fontStyle = 'normal';
  3911. /**
  3912. * The fontStyle of the font to be used.
  3913. *
  3914. * @name AcroFormField#fontStyle
  3915. * @default 'normal'
  3916. * @type {string}
  3917. */
  3918. Object.defineProperty(this, 'fontStyle', {
  3919. enumerable: true,
  3920. configurable: true,
  3921. get: function get() {
  3922. return _fontStyle;
  3923. },
  3924. set: function set(value) {
  3925. _fontStyle = value;
  3926. }
  3927. });
  3928. var _fontSize = 0;
  3929. /**
  3930. * The fontSize of the font to be used.
  3931. *
  3932. * @name AcroFormField#fontSize
  3933. * @default 0 (for auto)
  3934. * @type {number}
  3935. */
  3936. Object.defineProperty(this, 'fontSize', {
  3937. enumerable: true,
  3938. configurable: true,
  3939. get: function get() {
  3940. return antiScale(_fontSize);
  3941. },
  3942. set: function set(value) {
  3943. _fontSize = scale(value);
  3944. }
  3945. });
  3946. var _maxFontSize = 50;
  3947. /**
  3948. * The maximum fontSize of the font to be used.
  3949. *
  3950. * @name AcroFormField#maxFontSize
  3951. * @default 0 (for auto)
  3952. * @type {number}
  3953. */
  3954. Object.defineProperty(this, 'maxFontSize', {
  3955. enumerable: true,
  3956. configurable: true,
  3957. get: function get() {
  3958. return antiScale(_maxFontSize);
  3959. },
  3960. set: function set(value) {
  3961. _maxFontSize = scale(value);
  3962. }
  3963. });
  3964. var _color = 'black';
  3965. /**
  3966. * The color of the text
  3967. *
  3968. * @name AcroFormField#color
  3969. * @default 'black'
  3970. * @type {string|rgba}
  3971. */
  3972. Object.defineProperty(this, 'color', {
  3973. enumerable: true,
  3974. configurable: true,
  3975. get: function get() {
  3976. return _color;
  3977. },
  3978. set: function set(value) {
  3979. _color = value;
  3980. }
  3981. });
  3982. var _DA = '/F1 0 Tf 0 g'; // Defines the default appearance (Needed for variable Text)
  3983. Object.defineProperty(this, 'DA', {
  3984. enumerable: true,
  3985. configurable: false,
  3986. get: function get() {
  3987. if (!_DA || this instanceof AcroFormChildClass || this instanceof AcroFormTextField) {
  3988. return;
  3989. }
  3990. return toPdfString(_DA);
  3991. },
  3992. set: function set(value) {
  3993. value = value.toString();
  3994. _DA = value;
  3995. }
  3996. });
  3997. var _DV = null;
  3998. Object.defineProperty(this, 'DV', {
  3999. enumerable: false,
  4000. configurable: false,
  4001. get: function get() {
  4002. if (!_DV) {
  4003. return;
  4004. }
  4005. if (this instanceof AcroFormButton === false) {
  4006. return toPdfString(_DV);
  4007. }
  4008. return _DV;
  4009. },
  4010. set: function set(value) {
  4011. value = value.toString();
  4012. if (this instanceof AcroFormButton === false) {
  4013. if (value.substr(0, 1) === '(') {
  4014. _DV = pdfUnescape(value.substr(1, value.length - 2));
  4015. } else {
  4016. _DV = pdfUnescape(value);
  4017. }
  4018. } else {
  4019. _DV = value;
  4020. }
  4021. }
  4022. });
  4023. /**
  4024. * (Optional; inheritable) The default value to which the field reverts when a reset-form action is executed (see 12.7.5.3, “Reset-Form Action”). The format of this value is the same as that of value.
  4025. *
  4026. * @name AcroFormField#defaultValue
  4027. * @default null
  4028. * @type {any}
  4029. */
  4030. Object.defineProperty(this, 'defaultValue', {
  4031. enumerable: true,
  4032. configurable: true,
  4033. get: function get() {
  4034. if (this instanceof AcroFormButton === true) {
  4035. return pdfUnescape(_DV.substr(1, _DV.length - 1));
  4036. } else {
  4037. return _DV;
  4038. }
  4039. },
  4040. set: function set(value) {
  4041. value = value.toString();
  4042. if (this instanceof AcroFormButton === true) {
  4043. _DV = '/' + value;
  4044. } else {
  4045. _DV = value;
  4046. }
  4047. }
  4048. });
  4049. var _V = null;
  4050. Object.defineProperty(this, 'V', {
  4051. enumerable: false,
  4052. configurable: false,
  4053. get: function get() {
  4054. if (!_V) {
  4055. return;
  4056. }
  4057. if (this instanceof AcroFormButton === false) {
  4058. return toPdfString(_V);
  4059. }
  4060. return _V;
  4061. },
  4062. set: function set(value) {
  4063. value = value.toString();
  4064. if (this instanceof AcroFormButton === false) {
  4065. if (value.substr(0, 1) === '(') {
  4066. _V = pdfUnescape(value.substr(1, value.length - 2));
  4067. } else {
  4068. _V = pdfUnescape(value);
  4069. }
  4070. } else {
  4071. _V = value;
  4072. }
  4073. }
  4074. });
  4075. /**
  4076. * (Optional; inheritable) The field’s value, whose format varies depending on the field type. See the descriptions of individual field types for further information.
  4077. *
  4078. * @name AcroFormField#value
  4079. * @default null
  4080. * @type {any}
  4081. */
  4082. Object.defineProperty(this, 'value', {
  4083. enumerable: true,
  4084. configurable: true,
  4085. get: function get() {
  4086. if (this instanceof AcroFormButton === true) {
  4087. return pdfUnescape(_V.substr(1, _V.length - 1));
  4088. } else {
  4089. return _V;
  4090. }
  4091. },
  4092. set: function set(value) {
  4093. value = value.toString();
  4094. if (this instanceof AcroFormButton === true) {
  4095. _V = '/' + value;
  4096. } else {
  4097. _V = value;
  4098. }
  4099. }
  4100. });
  4101. /**
  4102. * Check if field has annotations
  4103. *
  4104. * @name AcroFormField#hasAnnotation
  4105. * @readonly
  4106. * @type {boolean}
  4107. */
  4108. Object.defineProperty(this, 'hasAnnotation', {
  4109. enumerable: true,
  4110. configurable: true,
  4111. get: function get() {
  4112. return this.Rect;
  4113. }
  4114. });
  4115. Object.defineProperty(this, 'Type', {
  4116. enumerable: true,
  4117. configurable: false,
  4118. get: function get() {
  4119. return this.hasAnnotation ? "/Annot" : null;
  4120. }
  4121. });
  4122. Object.defineProperty(this, 'Subtype', {
  4123. enumerable: true,
  4124. configurable: false,
  4125. get: function get() {
  4126. return this.hasAnnotation ? "/Widget" : null;
  4127. }
  4128. });
  4129. var _hasAppearanceStream = false;
  4130. /**
  4131. * true if field has an appearanceStream
  4132. *
  4133. * @name AcroFormField#hasAppearanceStream
  4134. * @readonly
  4135. * @type {boolean}
  4136. */
  4137. Object.defineProperty(this, 'hasAppearanceStream', {
  4138. enumerable: true,
  4139. configurable: true,
  4140. writeable: true,
  4141. get: function get() {
  4142. return _hasAppearanceStream;
  4143. },
  4144. set: function set(value) {
  4145. value = Boolean(value);
  4146. _hasAppearanceStream = value;
  4147. }
  4148. });
  4149. /**
  4150. * The page on which the AcroFormField is placed
  4151. *
  4152. * @name AcroFormField#page
  4153. * @type {number}
  4154. */
  4155. var _page;
  4156. Object.defineProperty(this, 'page', {
  4157. enumerable: true,
  4158. configurable: true,
  4159. writeable: true,
  4160. get: function get() {
  4161. if (!_page) {
  4162. return;
  4163. }
  4164. return _page;
  4165. },
  4166. set: function set(value) {
  4167. _page = value;
  4168. }
  4169. });
  4170. /**
  4171. * If set, the user may not change the value of the field. Any associated widget annotations will not interact with the user; that is, they will not respond to mouse clicks or change their appearance in response to mouse motions. This flag is useful for fields whose values are computed or imported from a database.
  4172. *
  4173. * @name AcroFormField#readOnly
  4174. * @default false
  4175. * @type {boolean}
  4176. */
  4177. Object.defineProperty(this, 'readOnly', {
  4178. enumerable: true,
  4179. configurable: true,
  4180. get: function get() {
  4181. return Boolean(getBitForPdf(this.Ff, 1));
  4182. },
  4183. set: function set(value) {
  4184. if (Boolean(value) === true) {
  4185. this.Ff = setBitForPdf(this.Ff, 1);
  4186. } else {
  4187. this.Ff = clearBitForPdf(this.Ff, 1);
  4188. }
  4189. }
  4190. });
  4191. /**
  4192. * If set, the field shall have a value at the time it is exported by a submitform action (see 12.7.5.2, “Submit-Form Action”).
  4193. *
  4194. * @name AcroFormField#required
  4195. * @default false
  4196. * @type {boolean}
  4197. */
  4198. Object.defineProperty(this, 'required', {
  4199. enumerable: true,
  4200. configurable: true,
  4201. get: function get() {
  4202. return Boolean(getBitForPdf(this.Ff, 2));
  4203. },
  4204. set: function set(value) {
  4205. if (Boolean(value) === true) {
  4206. this.Ff = setBitForPdf(this.Ff, 2);
  4207. } else {
  4208. this.Ff = clearBitForPdf(this.Ff, 2);
  4209. }
  4210. }
  4211. });
  4212. /**
  4213. * If set, the field shall not be exported by a submit-form action (see 12.7.5.2, “Submit-Form Action”)
  4214. *
  4215. * @name AcroFormField#noExport
  4216. * @default false
  4217. * @type {boolean}
  4218. */
  4219. Object.defineProperty(this, 'noExport', {
  4220. enumerable: true,
  4221. configurable: true,
  4222. get: function get() {
  4223. return Boolean(getBitForPdf(this.Ff, 3));
  4224. },
  4225. set: function set(value) {
  4226. if (Boolean(value) === true) {
  4227. this.Ff = setBitForPdf(this.Ff, 3);
  4228. } else {
  4229. this.Ff = clearBitForPdf(this.Ff, 3);
  4230. }
  4231. }
  4232. });
  4233. var _Q = null;
  4234. Object.defineProperty(this, 'Q', {
  4235. enumerable: true,
  4236. configurable: false,
  4237. get: function get() {
  4238. if (_Q === null) {
  4239. return;
  4240. }
  4241. return _Q;
  4242. },
  4243. set: function set(value) {
  4244. if ([0, 1, 2].indexOf(value) !== -1) {
  4245. _Q = value;
  4246. } else {
  4247. throw new Error('Invalid value "' + value + '" for attribute Q supplied.');
  4248. }
  4249. }
  4250. });
  4251. /**
  4252. * (Optional; inheritable) A code specifying the form of quadding (justification) that shall be used in displaying the text:
  4253. * 'left', 'center', 'right'
  4254. *
  4255. * @name AcroFormField#textAlign
  4256. * @default 'left'
  4257. * @type {string}
  4258. */
  4259. Object.defineProperty(this, 'textAlign', {
  4260. get: function get() {
  4261. var result = 'left';
  4262. switch (_Q) {
  4263. case 0:
  4264. default:
  4265. result = 'left';
  4266. break;
  4267. case 1:
  4268. result = 'center';
  4269. break;
  4270. case 2:
  4271. result = 'right';
  4272. break;
  4273. }
  4274. return result;
  4275. },
  4276. configurable: true,
  4277. enumerable: true,
  4278. set: function set(value) {
  4279. switch (value) {
  4280. case 'right':
  4281. case 2:
  4282. _Q = 2;
  4283. break;
  4284. case 'center':
  4285. case 1:
  4286. _Q = 1;
  4287. break;
  4288. case 'left':
  4289. case 0:
  4290. default:
  4291. _Q = 0;
  4292. }
  4293. }
  4294. });
  4295. };
  4296. inherit(AcroFormField, AcroFormPDFObject);
  4297. /**
  4298. * @class AcroFormChoiceField
  4299. * @extends AcroFormField
  4300. */
  4301. var AcroFormChoiceField = function AcroFormChoiceField() {
  4302. AcroFormField.call(this); // Field Type = Choice Field
  4303. this.FT = "/Ch"; // options
  4304. this.V = '()';
  4305. this.fontName = 'zapfdingbats'; // Top Index
  4306. var _TI = 0;
  4307. Object.defineProperty(this, 'TI', {
  4308. enumerable: true,
  4309. configurable: false,
  4310. get: function get() {
  4311. return _TI;
  4312. },
  4313. set: function set(value) {
  4314. _TI = value;
  4315. }
  4316. });
  4317. /**
  4318. * (Optional) For scrollable list boxes, the top index (the index in the Opt array of the first option visible in the list). Default value: 0.
  4319. *
  4320. * @name AcroFormChoiceField#topIndex
  4321. * @default 0
  4322. * @type {number}
  4323. */
  4324. Object.defineProperty(this, 'topIndex', {
  4325. enumerable: true,
  4326. configurable: true,
  4327. get: function get() {
  4328. return _TI;
  4329. },
  4330. set: function set(value) {
  4331. _TI = value;
  4332. }
  4333. });
  4334. var _Opt = [];
  4335. Object.defineProperty(this, 'Opt', {
  4336. enumerable: true,
  4337. configurable: false,
  4338. get: function get() {
  4339. return arrayToPdfArray(_Opt);
  4340. },
  4341. set: function set(value) {
  4342. _Opt = pdfArrayToStringArray(value);
  4343. }
  4344. });
  4345. /**
  4346. * @memberof AcroFormChoiceField
  4347. * @name getOptions
  4348. * @function
  4349. * @instance
  4350. * @returns {array} array of Options
  4351. */
  4352. this.getOptions = function () {
  4353. return _Opt;
  4354. };
  4355. /**
  4356. * @memberof AcroFormChoiceField
  4357. * @name setOptions
  4358. * @function
  4359. * @instance
  4360. * @param {array} value
  4361. */
  4362. this.setOptions = function (value) {
  4363. _Opt = value;
  4364. if (this.sort) {
  4365. _Opt.sort();
  4366. }
  4367. };
  4368. /**
  4369. * @memberof AcroFormChoiceField
  4370. * @name addOption
  4371. * @function
  4372. * @instance
  4373. * @param {string} value
  4374. */
  4375. this.addOption = function (value) {
  4376. value = value || "";
  4377. value = value.toString();
  4378. _Opt.push(value);
  4379. if (this.sort) {
  4380. _Opt.sort();
  4381. }
  4382. };
  4383. /**
  4384. * @memberof AcroFormChoiceField
  4385. * @name removeOption
  4386. * @function
  4387. * @instance
  4388. * @param {string} value
  4389. * @param {boolean} allEntries (default: false)
  4390. */
  4391. this.removeOption = function (value, allEntries) {
  4392. allEntries = allEntries || false;
  4393. value = value || "";
  4394. value = value.toString();
  4395. while (_Opt.indexOf(value) !== -1) {
  4396. _Opt.splice(_Opt.indexOf(value), 1);
  4397. if (allEntries === false) {
  4398. break;
  4399. }
  4400. }
  4401. };
  4402. /**
  4403. * If set, the field is a combo box; if clear, the field is a list box.
  4404. *
  4405. * @name AcroFormChoiceField#combo
  4406. * @default false
  4407. * @type {boolean}
  4408. */
  4409. Object.defineProperty(this, 'combo', {
  4410. enumerable: true,
  4411. configurable: true,
  4412. get: function get() {
  4413. return Boolean(getBitForPdf(this.Ff, 18));
  4414. },
  4415. set: function set(value) {
  4416. if (Boolean(value) === true) {
  4417. this.Ff = setBitForPdf(this.Ff, 18);
  4418. } else {
  4419. this.Ff = clearBitForPdf(this.Ff, 18);
  4420. }
  4421. }
  4422. });
  4423. /**
  4424. * If set, the combo box shall include an editable text box as well as a drop-down list; if clear, it shall include only a drop-down list. This flag shall be used only if the Combo flag is set.
  4425. *
  4426. * @name AcroFormChoiceField#edit
  4427. * @default false
  4428. * @type {boolean}
  4429. */
  4430. Object.defineProperty(this, 'edit', {
  4431. enumerable: true,
  4432. configurable: true,
  4433. get: function get() {
  4434. return Boolean(getBitForPdf(this.Ff, 19));
  4435. },
  4436. set: function set(value) {
  4437. //PDF 32000-1:2008, page 444
  4438. if (this.combo === true) {
  4439. if (Boolean(value) === true) {
  4440. this.Ff = setBitForPdf(this.Ff, 19);
  4441. } else {
  4442. this.Ff = clearBitForPdf(this.Ff, 19);
  4443. }
  4444. }
  4445. }
  4446. });
  4447. /**
  4448. * If set, the field’s option items shall be sorted alphabetically. This flag is intended for use by writers, not by readers. Conforming readers shall display the options in the order in which they occur in the Opt array (see Table 231).
  4449. *
  4450. * @name AcroFormChoiceField#sort
  4451. * @default false
  4452. * @type {boolean}
  4453. */
  4454. Object.defineProperty(this, 'sort', {
  4455. enumerable: true,
  4456. configurable: true,
  4457. get: function get() {
  4458. return Boolean(getBitForPdf(this.Ff, 20));
  4459. },
  4460. set: function set(value) {
  4461. if (Boolean(value) === true) {
  4462. this.Ff = setBitForPdf(this.Ff, 20);
  4463. _Opt.sort();
  4464. } else {
  4465. this.Ff = clearBitForPdf(this.Ff, 20);
  4466. }
  4467. }
  4468. });
  4469. /**
  4470. * (PDF 1.4) If set, more than one of the field’s option items may be selected simultaneously; if clear, at most one item shall be selected
  4471. *
  4472. * @name AcroFormChoiceField#multiSelect
  4473. * @default false
  4474. * @type {boolean}
  4475. */
  4476. Object.defineProperty(this, 'multiSelect', {
  4477. enumerable: true,
  4478. configurable: true,
  4479. get: function get() {
  4480. return Boolean(getBitForPdf(this.Ff, 22));
  4481. },
  4482. set: function set(value) {
  4483. if (Boolean(value) === true) {
  4484. this.Ff = setBitForPdf(this.Ff, 22);
  4485. } else {
  4486. this.Ff = clearBitForPdf(this.Ff, 22);
  4487. }
  4488. }
  4489. });
  4490. /**
  4491. * (PDF 1.4) If set, text entered in the field shall not be spellchecked. This flag shall not be used unless the Combo and Edit flags are both set.
  4492. *
  4493. * @name AcroFormChoiceField#doNotSpellCheck
  4494. * @default false
  4495. * @type {boolean}
  4496. */
  4497. Object.defineProperty(this, 'doNotSpellCheck', {
  4498. enumerable: true,
  4499. configurable: true,
  4500. get: function get() {
  4501. return Boolean(getBitForPdf(this.Ff, 23));
  4502. },
  4503. set: function set(value) {
  4504. if (Boolean(value) === true) {
  4505. this.Ff = setBitForPdf(this.Ff, 23);
  4506. } else {
  4507. this.Ff = clearBitForPdf(this.Ff, 23);
  4508. }
  4509. }
  4510. });
  4511. /**
  4512. * (PDF 1.5) If set, the new value shall be committed as soon as a selection is made (commonly with the pointing device). In this case, supplying a value for a field involves three actions: selecting the field for fill-in, selecting a choice for the fill-in value, and leaving that field, which finalizes or “commits” the data choice and triggers any actions associated with the entry or changing of this data. If this flag is on, then processing does not wait for leaving the field action to occur, but immediately proceeds to the third step.
  4513. * This option enables applications to perform an action once a selection is made, without requiring the user to exit the field. If clear, the new value is not committed until the user exits the field.
  4514. *
  4515. * @name AcroFormChoiceField#commitOnSelChange
  4516. * @default false
  4517. * @type {boolean}
  4518. */
  4519. Object.defineProperty(this, 'commitOnSelChange', {
  4520. enumerable: true,
  4521. configurable: true,
  4522. get: function get() {
  4523. return Boolean(getBitForPdf(this.Ff, 27));
  4524. },
  4525. set: function set(value) {
  4526. if (Boolean(value) === true) {
  4527. this.Ff = setBitForPdf(this.Ff, 27);
  4528. } else {
  4529. this.Ff = clearBitForPdf(this.Ff, 27);
  4530. }
  4531. }
  4532. });
  4533. this.hasAppearanceStream = false;
  4534. };
  4535. inherit(AcroFormChoiceField, AcroFormField);
  4536. /**
  4537. * @class AcroFormListBox
  4538. * @extends AcroFormChoiceField
  4539. * @extends AcroFormField
  4540. */
  4541. var AcroFormListBox = function AcroFormListBox() {
  4542. AcroFormChoiceField.call(this);
  4543. this.fontName = 'helvetica'; //PDF 32000-1:2008, page 444
  4544. this.combo = false;
  4545. };
  4546. inherit(AcroFormListBox, AcroFormChoiceField);
  4547. /**
  4548. * @class AcroFormComboBox
  4549. * @extends AcroFormListBox
  4550. * @extends AcroFormChoiceField
  4551. * @extends AcroFormField
  4552. */
  4553. var AcroFormComboBox = function AcroFormComboBox() {
  4554. AcroFormListBox.call(this);
  4555. this.combo = true;
  4556. };
  4557. inherit(AcroFormComboBox, AcroFormListBox);
  4558. /**
  4559. * @class AcroFormEditBox
  4560. * @extends AcroFormComboBox
  4561. * @extends AcroFormListBox
  4562. * @extends AcroFormChoiceField
  4563. * @extends AcroFormField
  4564. */
  4565. var AcroFormEditBox = function AcroFormEditBox() {
  4566. AcroFormComboBox.call(this);
  4567. this.edit = true;
  4568. };
  4569. inherit(AcroFormEditBox, AcroFormComboBox);
  4570. /**
  4571. * @class AcroFormButton
  4572. * @extends AcroFormField
  4573. */
  4574. var AcroFormButton = function AcroFormButton() {
  4575. AcroFormField.call(this);
  4576. this.FT = "/Btn";
  4577. /**
  4578. * (Radio buttons only) If set, exactly one radio button shall be selected at all times; selecting the currently selected button has no effect. If clear, clicking the selected button deselects it, leaving no button selected.
  4579. *
  4580. * @name AcroFormButton#noToggleToOff
  4581. * @type {boolean}
  4582. */
  4583. Object.defineProperty(this, 'noToggleToOff', {
  4584. enumerable: true,
  4585. configurable: true,
  4586. get: function get() {
  4587. return Boolean(getBitForPdf(this.Ff, 15));
  4588. },
  4589. set: function set(value) {
  4590. if (Boolean(value) === true) {
  4591. this.Ff = setBitForPdf(this.Ff, 15);
  4592. } else {
  4593. this.Ff = clearBitForPdf(this.Ff, 15);
  4594. }
  4595. }
  4596. });
  4597. /**
  4598. * If set, the field is a set of radio buttons; if clear, the field is a checkbox. This flag may be set only if the Pushbutton flag is clear.
  4599. *
  4600. * @name AcroFormButton#radio
  4601. * @type {boolean}
  4602. */
  4603. Object.defineProperty(this, 'radio', {
  4604. enumerable: true,
  4605. configurable: true,
  4606. get: function get() {
  4607. return Boolean(getBitForPdf(this.Ff, 16));
  4608. },
  4609. set: function set(value) {
  4610. if (Boolean(value) === true) {
  4611. this.Ff = setBitForPdf(this.Ff, 16);
  4612. } else {
  4613. this.Ff = clearBitForPdf(this.Ff, 16);
  4614. }
  4615. }
  4616. });
  4617. /**
  4618. * If set, the field is a pushbutton that does not retain a permanent value.
  4619. *
  4620. * @name AcroFormButton#pushButton
  4621. * @type {boolean}
  4622. */
  4623. Object.defineProperty(this, 'pushButton', {
  4624. enumerable: true,
  4625. configurable: true,
  4626. get: function get() {
  4627. return Boolean(getBitForPdf(this.Ff, 17));
  4628. },
  4629. set: function set(value) {
  4630. if (Boolean(value) === true) {
  4631. this.Ff = setBitForPdf(this.Ff, 17);
  4632. } else {
  4633. this.Ff = clearBitForPdf(this.Ff, 17);
  4634. }
  4635. }
  4636. });
  4637. /**
  4638. * (PDF 1.5) If set, a group of radio buttons within a radio button field that use the same value for the on state will turn on and off in unison; that is if one is checked, they are all checked. If clear, the buttons are mutually exclusive (the same behavior as HTML radio buttons).
  4639. *
  4640. * @name AcroFormButton#radioIsUnison
  4641. * @type {boolean}
  4642. */
  4643. Object.defineProperty(this, 'radioIsUnison', {
  4644. enumerable: true,
  4645. configurable: true,
  4646. get: function get() {
  4647. return Boolean(getBitForPdf(this.Ff, 26));
  4648. },
  4649. set: function set(value) {
  4650. if (Boolean(value) === true) {
  4651. this.Ff = setBitForPdf(this.Ff, 26);
  4652. } else {
  4653. this.Ff = clearBitForPdf(this.Ff, 26);
  4654. }
  4655. }
  4656. });
  4657. var _MK = {};
  4658. Object.defineProperty(this, 'MK', {
  4659. enumerable: false,
  4660. configurable: false,
  4661. get: function get() {
  4662. if (Object.keys(_MK).length !== 0) {
  4663. var result = [];
  4664. result.push('<<');
  4665. var key;
  4666. for (key in _MK) {
  4667. result.push('/' + key + ' (' + _MK[key] + ')');
  4668. }
  4669. result.push('>>');
  4670. return result.join('\n');
  4671. }
  4672. return;
  4673. },
  4674. set: function set(value) {
  4675. if (_typeof(value) === "object") {
  4676. _MK = value;
  4677. }
  4678. }
  4679. });
  4680. /**
  4681. * From the PDF reference:
  4682. * (Optional, button fields only) The widget annotation's normal caption which shall be displayed when it is not interacting with the user.
  4683. * Unlike the remaining entries listed in this Table which apply only to widget annotations associated with pushbutton fields (see Pushbuttons in 12.7.4.2, "Button Fields"), the CA entry may be used with any type of button field, including check boxes (see Check Boxes in 12.7.4.2, "Button Fields") and radio buttons (Radio Buttons in 12.7.4.2, "Button Fields").
  4684. *
  4685. * - '8' = Cross,
  4686. * - 'l' = Circle,
  4687. * - '' = nothing
  4688. * @name AcroFormButton#caption
  4689. * @type {string}
  4690. */
  4691. Object.defineProperty(this, 'caption', {
  4692. enumerable: true,
  4693. configurable: true,
  4694. get: function get() {
  4695. return _MK.CA || '';
  4696. },
  4697. set: function set(value) {
  4698. if (typeof value === "string") {
  4699. _MK.CA = value;
  4700. }
  4701. }
  4702. });
  4703. var _AS;
  4704. Object.defineProperty(this, 'AS', {
  4705. enumerable: false,
  4706. configurable: false,
  4707. get: function get() {
  4708. return _AS;
  4709. },
  4710. set: function set(value) {
  4711. _AS = value;
  4712. }
  4713. });
  4714. /**
  4715. * (Required if the appearance dictionary AP contains one or more subdictionaries; PDF 1.2) The annotation's appearance state, which selects the applicable appearance stream from an appearance subdictionary (see Section 12.5.5, "Appearance Streams")
  4716. *
  4717. * @name AcroFormButton#appearanceState
  4718. * @type {any}
  4719. */
  4720. Object.defineProperty(this, 'appearanceState', {
  4721. enumerable: true,
  4722. configurable: true,
  4723. get: function get() {
  4724. return _AS.substr(1, _AS.length - 1);
  4725. },
  4726. set: function set(value) {
  4727. _AS = '/' + value;
  4728. }
  4729. });
  4730. };
  4731. inherit(AcroFormButton, AcroFormField);
  4732. /**
  4733. * @class AcroFormPushButton
  4734. * @extends AcroFormButton
  4735. * @extends AcroFormField
  4736. */
  4737. var AcroFormPushButton = function AcroFormPushButton() {
  4738. AcroFormButton.call(this);
  4739. this.pushButton = true;
  4740. };
  4741. inherit(AcroFormPushButton, AcroFormButton);
  4742. /**
  4743. * @class AcroFormRadioButton
  4744. * @extends AcroFormButton
  4745. * @extends AcroFormField
  4746. */
  4747. var AcroFormRadioButton = function AcroFormRadioButton() {
  4748. AcroFormButton.call(this);
  4749. this.radio = true;
  4750. this.pushButton = false;
  4751. var _Kids = [];
  4752. Object.defineProperty(this, 'Kids', {
  4753. enumerable: true,
  4754. configurable: false,
  4755. get: function get() {
  4756. return _Kids;
  4757. },
  4758. set: function set(value) {
  4759. if (typeof value !== "undefined") {
  4760. _Kids = value;
  4761. } else {
  4762. _Kids = [];
  4763. }
  4764. }
  4765. });
  4766. };
  4767. inherit(AcroFormRadioButton, AcroFormButton);
  4768. /**
  4769. * The Child class of a RadioButton (the radioGroup) -> The single Buttons
  4770. *
  4771. * @class AcroFormChildClass
  4772. * @extends AcroFormField
  4773. * @ignore
  4774. */
  4775. var AcroFormChildClass = function AcroFormChildClass() {
  4776. AcroFormField.call(this);
  4777. var _parent;
  4778. Object.defineProperty(this, 'Parent', {
  4779. enumerable: false,
  4780. configurable: false,
  4781. get: function get() {
  4782. return _parent;
  4783. },
  4784. set: function set(value) {
  4785. _parent = value;
  4786. }
  4787. });
  4788. var _optionName;
  4789. Object.defineProperty(this, 'optionName', {
  4790. enumerable: false,
  4791. configurable: true,
  4792. get: function get() {
  4793. return _optionName;
  4794. },
  4795. set: function set(value) {
  4796. _optionName = value;
  4797. }
  4798. });
  4799. var _MK = {};
  4800. Object.defineProperty(this, 'MK', {
  4801. enumerable: false,
  4802. configurable: false,
  4803. get: function get() {
  4804. var result = [];
  4805. result.push('<<');
  4806. var key;
  4807. for (key in _MK) {
  4808. result.push('/' + key + ' (' + _MK[key] + ')');
  4809. }
  4810. result.push('>>');
  4811. return result.join('\n');
  4812. },
  4813. set: function set(value) {
  4814. if (_typeof(value) === "object") {
  4815. _MK = value;
  4816. }
  4817. }
  4818. });
  4819. /**
  4820. * From the PDF reference:
  4821. * (Optional, button fields only) The widget annotation's normal caption which shall be displayed when it is not interacting with the user.
  4822. * Unlike the remaining entries listed in this Table which apply only to widget annotations associated with pushbutton fields (see Pushbuttons in 12.7.4.2, "Button Fields"), the CA entry may be used with any type of button field, including check boxes (see Check Boxes in 12.7.4.2, "Button Fields") and radio buttons (Radio Buttons in 12.7.4.2, "Button Fields").
  4823. *
  4824. * - '8' = Cross,
  4825. * - 'l' = Circle,
  4826. * - '' = nothing
  4827. * @name AcroFormButton#caption
  4828. * @type {string}
  4829. */
  4830. Object.defineProperty(this, 'caption', {
  4831. enumerable: true,
  4832. configurable: true,
  4833. get: function get() {
  4834. return _MK.CA || '';
  4835. },
  4836. set: function set(value) {
  4837. if (typeof value === "string") {
  4838. _MK.CA = value;
  4839. }
  4840. }
  4841. });
  4842. var _AS;
  4843. Object.defineProperty(this, 'AS', {
  4844. enumerable: false,
  4845. configurable: false,
  4846. get: function get() {
  4847. return _AS;
  4848. },
  4849. set: function set(value) {
  4850. _AS = value;
  4851. }
  4852. });
  4853. /**
  4854. * (Required if the appearance dictionary AP contains one or more subdictionaries; PDF 1.2) The annotation's appearance state, which selects the applicable appearance stream from an appearance subdictionary (see Section 12.5.5, "Appearance Streams")
  4855. *
  4856. * @name AcroFormButton#appearanceState
  4857. * @type {any}
  4858. */
  4859. Object.defineProperty(this, 'appearanceState', {
  4860. enumerable: true,
  4861. configurable: true,
  4862. get: function get() {
  4863. return _AS.substr(1, _AS.length - 1);
  4864. },
  4865. set: function set(value) {
  4866. _AS = '/' + value;
  4867. }
  4868. });
  4869. this.optionName = name;
  4870. this.caption = 'l';
  4871. this.appearanceState = 'Off'; // todo: set AppearanceType as variable that can be set from the
  4872. // outside...
  4873. this._AppearanceType = AcroFormAppearance.RadioButton.Circle; // The Default appearanceType is the Circle
  4874. this.appearanceStreamContent = this._AppearanceType.createAppearanceStream(name);
  4875. };
  4876. inherit(AcroFormChildClass, AcroFormField);
  4877. AcroFormRadioButton.prototype.setAppearance = function (appearance) {
  4878. if (!('createAppearanceStream' in appearance && 'getCA' in appearance)) {
  4879. throw new Error("Couldn't assign Appearance to RadioButton. Appearance was Invalid!");
  4880. return;
  4881. }
  4882. for (var objId in this.Kids) {
  4883. if (this.Kids.hasOwnProperty(objId)) {
  4884. var child = this.Kids[objId];
  4885. child.appearanceStreamContent = appearance.createAppearanceStream(child.optionName);
  4886. child.caption = appearance.getCA();
  4887. }
  4888. }
  4889. };
  4890. AcroFormRadioButton.prototype.createOption = function (name) {
  4891. var kidCount = this.Kids.length; // Create new Child for RadioGroup
  4892. var child = new AcroFormChildClass();
  4893. child.Parent = this;
  4894. child.optionName = name; // Add to Parent
  4895. this.Kids.push(child);
  4896. addField.call(this, child);
  4897. return child;
  4898. };
  4899. /**
  4900. * @class AcroFormCheckBox
  4901. * @extends AcroFormButton
  4902. * @extends AcroFormField
  4903. */
  4904. var AcroFormCheckBox = function AcroFormCheckBox() {
  4905. AcroFormButton.call(this);
  4906. this.fontName = 'zapfdingbats';
  4907. this.caption = '3';
  4908. this.appearanceState = 'On';
  4909. this.value = "On";
  4910. this.textAlign = 'center';
  4911. this.appearanceStreamContent = AcroFormAppearance.CheckBox.createAppearanceStream();
  4912. };
  4913. inherit(AcroFormCheckBox, AcroFormButton);
  4914. /**
  4915. * @class AcroFormTextField
  4916. * @extends AcroFormField
  4917. */
  4918. var AcroFormTextField = function AcroFormTextField() {
  4919. AcroFormField.call(this);
  4920. this.FT = '/Tx';
  4921. /**
  4922. * If set, the field may contain multiple lines of text; if clear, the field’s text shall be restricted to a single line.
  4923. *
  4924. * @name AcroFormTextField#multiline
  4925. * @type {boolean}
  4926. */
  4927. Object.defineProperty(this, 'multiline', {
  4928. enumerable: true,
  4929. configurable: true,
  4930. get: function get() {
  4931. return Boolean(getBitForPdf(this.Ff, 13));
  4932. },
  4933. set: function set(value) {
  4934. if (Boolean(value) === true) {
  4935. this.Ff = setBitForPdf(this.Ff, 13);
  4936. } else {
  4937. this.Ff = clearBitForPdf(this.Ff, 13);
  4938. }
  4939. }
  4940. });
  4941. /**
  4942. * (PDF 1.4) If set, the text entered in the field represents the pathname of a file whose contents shall be submitted as the value of the field.
  4943. *
  4944. * @name AcroFormTextField#fileSelect
  4945. * @type {boolean}
  4946. */
  4947. Object.defineProperty(this, 'fileSelect', {
  4948. enumerable: true,
  4949. configurable: true,
  4950. get: function get() {
  4951. return Boolean(getBitForPdf(this.Ff, 21));
  4952. },
  4953. set: function set(value) {
  4954. if (Boolean(value) === true) {
  4955. this.Ff = setBitForPdf(this.Ff, 21);
  4956. } else {
  4957. this.Ff = clearBitForPdf(this.Ff, 21);
  4958. }
  4959. }
  4960. });
  4961. /**
  4962. * (PDF 1.4) If set, text entered in the field shall not be spell-checked.
  4963. *
  4964. * @name AcroFormTextField#doNotSpellCheck
  4965. * @type {boolean}
  4966. */
  4967. Object.defineProperty(this, 'doNotSpellCheck', {
  4968. enumerable: true,
  4969. configurable: true,
  4970. get: function get() {
  4971. return Boolean(getBitForPdf(this.Ff, 23));
  4972. },
  4973. set: function set(value) {
  4974. if (Boolean(value) === true) {
  4975. this.Ff = setBitForPdf(this.Ff, 23);
  4976. } else {
  4977. this.Ff = clearBitForPdf(this.Ff, 23);
  4978. }
  4979. }
  4980. });
  4981. /**
  4982. * (PDF 1.4) If set, the field shall not scroll (horizontally for single-line fields, vertically for multiple-line fields) to accommodate more text than fits within its annotation rectangle. Once the field is full, no further text shall be accepted for interactive form filling; for noninteractive form filling, the filler should take care not to add more character than will visibly fit in the defined area.
  4983. *
  4984. * @name AcroFormTextField#doNotScroll
  4985. * @type {boolean}
  4986. */
  4987. Object.defineProperty(this, 'doNotScroll', {
  4988. enumerable: true,
  4989. configurable: true,
  4990. get: function get() {
  4991. return Boolean(getBitForPdf(this.Ff, 24));
  4992. },
  4993. set: function set(value) {
  4994. if (Boolean(value) === true) {
  4995. this.Ff = setBitForPdf(this.Ff, 24);
  4996. } else {
  4997. this.Ff = clearBitForPdf(this.Ff, 24);
  4998. }
  4999. }
  5000. });
  5001. /**
  5002. * (PDF 1.5) May be set only if the MaxLen entry is present in the text field dictionary (see Table 229) and if the Multiline, Password, and FileSelect flags are clear. If set, the field shall be automatically divided into as many equally spaced positions, or combs, as the value of MaxLen, and the text is laid out into those combs.
  5003. *
  5004. * @name AcroFormTextField#comb
  5005. * @type {boolean}
  5006. */
  5007. Object.defineProperty(this, 'comb', {
  5008. enumerable: true,
  5009. configurable: true,
  5010. get: function get() {
  5011. return Boolean(getBitForPdf(this.Ff, 25));
  5012. },
  5013. set: function set(value) {
  5014. if (Boolean(value) === true) {
  5015. this.Ff = setBitForPdf(this.Ff, 25);
  5016. } else {
  5017. this.Ff = clearBitForPdf(this.Ff, 25);
  5018. }
  5019. }
  5020. });
  5021. /**
  5022. * (PDF 1.5) If set, the value of this field shall be a rich text string (see 12.7.3.4, “Rich Text Strings”). If the field has a value, the RV entry of the field dictionary (Table 222) shall specify the rich text string.
  5023. *
  5024. * @name AcroFormTextField#richText
  5025. * @type {boolean}
  5026. */
  5027. Object.defineProperty(this, 'richText', {
  5028. enumerable: true,
  5029. configurable: true,
  5030. get: function get() {
  5031. return Boolean(getBitForPdf(this.Ff, 26));
  5032. },
  5033. set: function set(value) {
  5034. if (Boolean(value) === true) {
  5035. this.Ff = setBitForPdf(this.Ff, 26);
  5036. } else {
  5037. this.Ff = clearBitForPdf(this.Ff, 26);
  5038. }
  5039. }
  5040. });
  5041. var _MaxLen = null;
  5042. Object.defineProperty(this, 'MaxLen', {
  5043. enumerable: true,
  5044. configurable: false,
  5045. get: function get() {
  5046. return _MaxLen;
  5047. },
  5048. set: function set(value) {
  5049. _MaxLen = value;
  5050. }
  5051. });
  5052. /**
  5053. * (Optional; inheritable) The maximum length of the field’s text, in characters.
  5054. *
  5055. * @name AcroFormTextField#maxLength
  5056. * @type {number}
  5057. */
  5058. Object.defineProperty(this, 'maxLength', {
  5059. enumerable: true,
  5060. configurable: true,
  5061. get: function get() {
  5062. return _MaxLen;
  5063. },
  5064. set: function set(value) {
  5065. if (Number.isInteger(value)) {
  5066. _MaxLen = value;
  5067. }
  5068. }
  5069. });
  5070. Object.defineProperty(this, 'hasAppearanceStream', {
  5071. enumerable: true,
  5072. configurable: true,
  5073. get: function get() {
  5074. return this.V || this.DV;
  5075. }
  5076. });
  5077. };
  5078. inherit(AcroFormTextField, AcroFormField);
  5079. /**
  5080. * @class AcroFormPasswordField
  5081. * @extends AcroFormTextField
  5082. * @extends AcroFormField
  5083. */
  5084. var AcroFormPasswordField = function AcroFormPasswordField() {
  5085. AcroFormTextField.call(this);
  5086. /**
  5087. * If set, the field is intended for entering a secure password that should not be echoed visibly to the screen. Characters typed from the keyboard shall instead be echoed in some unreadable form, such as asterisks or bullet characters.
  5088. * NOTE To protect password confidentiality, readers should never store the value of the text field in the PDF file if this flag is set.
  5089. *
  5090. * @name AcroFormTextField#password
  5091. * @type {boolean}
  5092. */
  5093. Object.defineProperty(this, 'password', {
  5094. enumerable: true,
  5095. configurable: true,
  5096. get: function get() {
  5097. return Boolean(getBitForPdf(this.Ff, 14));
  5098. },
  5099. set: function set(value) {
  5100. if (Boolean(value) === true) {
  5101. this.Ff = setBitForPdf(this.Ff, 14);
  5102. } else {
  5103. this.Ff = clearBitForPdf(this.Ff, 14);
  5104. }
  5105. }
  5106. });
  5107. this.password = true;
  5108. };
  5109. inherit(AcroFormPasswordField, AcroFormTextField); // Contains Methods for creating standard appearances
  5110. var AcroFormAppearance = {
  5111. CheckBox: {
  5112. createAppearanceStream: function createAppearanceStream() {
  5113. var appearance = {
  5114. N: {
  5115. On: AcroFormAppearance.CheckBox.YesNormal
  5116. },
  5117. D: {
  5118. On: AcroFormAppearance.CheckBox.YesPushDown,
  5119. Off: AcroFormAppearance.CheckBox.OffPushDown
  5120. }
  5121. };
  5122. return appearance;
  5123. },
  5124. /**
  5125. * Returns the standard On Appearance for a CheckBox
  5126. *
  5127. * @returns {AcroFormXObject}
  5128. */
  5129. YesPushDown: function YesPushDown(formObject) {
  5130. var xobj = createFormXObject(formObject);
  5131. var stream = [];
  5132. var fontKey = scope.internal.getFont(formObject.fontName, formObject.fontStyle).id;
  5133. var encodedColor = scope.__private__.encodeColorString(formObject.color);
  5134. var calcRes = calculateX(formObject, formObject.caption);
  5135. stream.push("0.749023 g");
  5136. stream.push("0 0 " + f2(AcroFormAppearance.internal.getWidth(formObject)) + " " + f2(AcroFormAppearance.internal.getHeight(formObject)) + " re");
  5137. stream.push("f");
  5138. stream.push("BMC");
  5139. stream.push("q");
  5140. stream.push("0 0 1 rg");
  5141. stream.push("/" + fontKey + " " + f2(calcRes.fontSize) + " Tf " + encodedColor);
  5142. stream.push("BT");
  5143. stream.push(calcRes.text);
  5144. stream.push("ET");
  5145. stream.push("Q");
  5146. stream.push("EMC");
  5147. xobj.stream = stream.join("\n");
  5148. return xobj;
  5149. },
  5150. YesNormal: function YesNormal(formObject) {
  5151. var xobj = createFormXObject(formObject);
  5152. var fontKey = scope.internal.getFont(formObject.fontName, formObject.fontStyle).id;
  5153. var encodedColor = scope.__private__.encodeColorString(formObject.color);
  5154. var stream = [];
  5155. var height = AcroFormAppearance.internal.getHeight(formObject);
  5156. var width = AcroFormAppearance.internal.getWidth(formObject);
  5157. var calcRes = calculateX(formObject, formObject.caption);
  5158. stream.push("1 g");
  5159. stream.push("0 0 " + f2(width) + " " + f2(height) + " re");
  5160. stream.push("f");
  5161. stream.push("q");
  5162. stream.push("0 0 1 rg");
  5163. stream.push("0 0 " + f2(width - 1) + " " + f2(height - 1) + " re");
  5164. stream.push("W");
  5165. stream.push("n");
  5166. stream.push("0 g");
  5167. stream.push("BT");
  5168. stream.push("/" + fontKey + " " + f2(calcRes.fontSize) + " Tf " + encodedColor);
  5169. stream.push(calcRes.text);
  5170. stream.push("ET");
  5171. stream.push("Q");
  5172. xobj.stream = stream.join("\n");
  5173. return xobj;
  5174. },
  5175. /**
  5176. * Returns the standard Off Appearance for a CheckBox
  5177. *
  5178. * @returns {AcroFormXObject}
  5179. */
  5180. OffPushDown: function OffPushDown(formObject) {
  5181. var xobj = createFormXObject(formObject);
  5182. var stream = [];
  5183. stream.push("0.749023 g");
  5184. stream.push("0 0 " + f2(AcroFormAppearance.internal.getWidth(formObject)) + " " + f2(AcroFormAppearance.internal.getHeight(formObject)) + " re");
  5185. stream.push("f");
  5186. xobj.stream = stream.join("\n");
  5187. return xobj;
  5188. }
  5189. },
  5190. RadioButton: {
  5191. Circle: {
  5192. createAppearanceStream: function createAppearanceStream(name) {
  5193. var appearanceStreamContent = {
  5194. D: {
  5195. 'Off': AcroFormAppearance.RadioButton.Circle.OffPushDown
  5196. },
  5197. N: {}
  5198. };
  5199. appearanceStreamContent.N[name] = AcroFormAppearance.RadioButton.Circle.YesNormal;
  5200. appearanceStreamContent.D[name] = AcroFormAppearance.RadioButton.Circle.YesPushDown;
  5201. return appearanceStreamContent;
  5202. },
  5203. getCA: function getCA() {
  5204. return 'l';
  5205. },
  5206. YesNormal: function YesNormal(formObject) {
  5207. var xobj = createFormXObject(formObject);
  5208. var stream = []; // Make the Radius of the Circle relative to min(height, width) of formObject
  5209. var DotRadius = AcroFormAppearance.internal.getWidth(formObject) <= AcroFormAppearance.internal.getHeight(formObject) ? AcroFormAppearance.internal.getWidth(formObject) / 4 : AcroFormAppearance.internal.getHeight(formObject) / 4; // The Borderpadding...
  5210. DotRadius = Number((DotRadius * 0.9).toFixed(5));
  5211. var c = AcroFormAppearance.internal.Bezier_C;
  5212. var DotRadiusBezier = Number((DotRadius * c).toFixed(5));
  5213. /*
  5214. * The Following is a Circle created with Bezier-Curves.
  5215. */
  5216. stream.push("q");
  5217. stream.push("1 0 0 1 " + f5(AcroFormAppearance.internal.getWidth(formObject) / 2) + " " + f5(AcroFormAppearance.internal.getHeight(formObject) / 2) + " cm");
  5218. stream.push(DotRadius + " 0 m");
  5219. stream.push(DotRadius + " " + DotRadiusBezier + " " + DotRadiusBezier + " " + DotRadius + " 0 " + DotRadius + " c");
  5220. stream.push("-" + DotRadiusBezier + " " + DotRadius + " -" + DotRadius + " " + DotRadiusBezier + " -" + DotRadius + " 0 c");
  5221. stream.push("-" + DotRadius + " -" + DotRadiusBezier + " -" + DotRadiusBezier + " -" + DotRadius + " 0 -" + DotRadius + " c");
  5222. stream.push(DotRadiusBezier + " -" + DotRadius + " " + DotRadius + " -" + DotRadiusBezier + " " + DotRadius + " 0 c");
  5223. stream.push("f");
  5224. stream.push("Q");
  5225. xobj.stream = stream.join("\n");
  5226. return xobj;
  5227. },
  5228. YesPushDown: function YesPushDown(formObject) {
  5229. var xobj = createFormXObject(formObject);
  5230. var stream = [];
  5231. var DotRadius = AcroFormAppearance.internal.getWidth(formObject) <= AcroFormAppearance.internal.getHeight(formObject) ? AcroFormAppearance.internal.getWidth(formObject) / 4 : AcroFormAppearance.internal.getHeight(formObject) / 4; // The Borderpadding...
  5232. var DotRadius = Number((DotRadius * 0.9).toFixed(5)); // Save results for later use; no need to waste
  5233. // processor ticks on doing math
  5234. var k = Number((DotRadius * 2).toFixed(5));
  5235. var kc = Number((k * AcroFormAppearance.internal.Bezier_C).toFixed(5));
  5236. var dc = Number((DotRadius * AcroFormAppearance.internal.Bezier_C).toFixed(5));
  5237. stream.push("0.749023 g");
  5238. stream.push("q");
  5239. stream.push("1 0 0 1 " + f5(AcroFormAppearance.internal.getWidth(formObject) / 2) + " " + f5(AcroFormAppearance.internal.getHeight(formObject) / 2) + " cm");
  5240. stream.push(k + " 0 m");
  5241. stream.push(k + " " + kc + " " + kc + " " + k + " 0 " + k + " c");
  5242. stream.push("-" + kc + " " + k + " -" + k + " " + kc + " -" + k + " 0 c");
  5243. stream.push("-" + k + " -" + kc + " -" + kc + " -" + k + " 0 -" + k + " c");
  5244. stream.push(kc + " -" + k + " " + k + " -" + kc + " " + k + " 0 c");
  5245. stream.push("f");
  5246. stream.push("Q");
  5247. stream.push("0 g");
  5248. stream.push("q");
  5249. stream.push("1 0 0 1 " + f5(AcroFormAppearance.internal.getWidth(formObject) / 2) + " " + f5(AcroFormAppearance.internal.getHeight(formObject) / 2) + " cm");
  5250. stream.push(DotRadius + " 0 m");
  5251. stream.push("" + DotRadius + " " + dc + " " + dc + " " + DotRadius + " 0 " + DotRadius + " c");
  5252. stream.push("-" + dc + " " + DotRadius + " -" + DotRadius + " " + dc + " -" + DotRadius + " 0 c");
  5253. stream.push("-" + DotRadius + " -" + dc + " -" + dc + " -" + DotRadius + " 0 -" + DotRadius + " c");
  5254. stream.push(dc + " -" + DotRadius + " " + DotRadius + " -" + dc + " " + DotRadius + " 0 c");
  5255. stream.push("f");
  5256. stream.push("Q");
  5257. xobj.stream = stream.join("\n");
  5258. return xobj;
  5259. },
  5260. OffPushDown: function OffPushDown(formObject) {
  5261. var xobj = createFormXObject(formObject);
  5262. var stream = [];
  5263. var DotRadius = AcroFormAppearance.internal.getWidth(formObject) <= AcroFormAppearance.internal.getHeight(formObject) ? AcroFormAppearance.internal.getWidth(formObject) / 4 : AcroFormAppearance.internal.getHeight(formObject) / 4; // The Borderpadding...
  5264. var DotRadius = Number((DotRadius * 0.9).toFixed(5)); // Save results for later use; no need to waste
  5265. // processor ticks on doing math
  5266. var k = Number((DotRadius * 2).toFixed(5));
  5267. var kc = Number((k * AcroFormAppearance.internal.Bezier_C).toFixed(5));
  5268. stream.push("0.749023 g");
  5269. stream.push("q");
  5270. stream.push("1 0 0 1 " + f5(AcroFormAppearance.internal.getWidth(formObject) / 2) + " " + f5(AcroFormAppearance.internal.getHeight(formObject) / 2) + " cm");
  5271. stream.push(k + " 0 m");
  5272. stream.push(k + " " + kc + " " + kc + " " + k + " 0 " + k + " c");
  5273. stream.push("-" + kc + " " + k + " -" + k + " " + kc + " -" + k + " 0 c");
  5274. stream.push("-" + k + " -" + kc + " -" + kc + " -" + k + " 0 -" + k + " c");
  5275. stream.push(kc + " -" + k + " " + k + " -" + kc + " " + k + " 0 c");
  5276. stream.push("f");
  5277. stream.push("Q");
  5278. xobj.stream = stream.join("\n");
  5279. return xobj;
  5280. }
  5281. },
  5282. Cross: {
  5283. /**
  5284. * Creates the Actual AppearanceDictionary-References
  5285. *
  5286. * @param {string} name
  5287. * @returns {Object}
  5288. * @ignore
  5289. */
  5290. createAppearanceStream: function createAppearanceStream(name) {
  5291. var appearanceStreamContent = {
  5292. D: {
  5293. 'Off': AcroFormAppearance.RadioButton.Cross.OffPushDown
  5294. },
  5295. N: {}
  5296. };
  5297. appearanceStreamContent.N[name] = AcroFormAppearance.RadioButton.Cross.YesNormal;
  5298. appearanceStreamContent.D[name] = AcroFormAppearance.RadioButton.Cross.YesPushDown;
  5299. return appearanceStreamContent;
  5300. },
  5301. getCA: function getCA() {
  5302. return '8';
  5303. },
  5304. YesNormal: function YesNormal(formObject) {
  5305. var xobj = createFormXObject(formObject);
  5306. var stream = [];
  5307. var cross = AcroFormAppearance.internal.calculateCross(formObject);
  5308. stream.push("q");
  5309. stream.push("1 1 " + f2(AcroFormAppearance.internal.getWidth(formObject) - 2) + " " + f2(AcroFormAppearance.internal.getHeight(formObject) - 2) + " re");
  5310. stream.push("W");
  5311. stream.push("n");
  5312. stream.push(f2(cross.x1.x) + " " + f2(cross.x1.y) + " m");
  5313. stream.push(f2(cross.x2.x) + " " + f2(cross.x2.y) + " l");
  5314. stream.push(f2(cross.x4.x) + " " + f2(cross.x4.y) + " m");
  5315. stream.push(f2(cross.x3.x) + " " + f2(cross.x3.y) + " l");
  5316. stream.push("s");
  5317. stream.push("Q");
  5318. xobj.stream = stream.join("\n");
  5319. return xobj;
  5320. },
  5321. YesPushDown: function YesPushDown(formObject) {
  5322. var xobj = createFormXObject(formObject);
  5323. var cross = AcroFormAppearance.internal.calculateCross(formObject);
  5324. var stream = [];
  5325. stream.push("0.749023 g");
  5326. stream.push("0 0 " + f2(AcroFormAppearance.internal.getWidth(formObject)) + " " + f2(AcroFormAppearance.internal.getHeight(formObject)) + " re");
  5327. stream.push("f");
  5328. stream.push("q");
  5329. stream.push("1 1 " + f2(AcroFormAppearance.internal.getWidth(formObject) - 2) + " " + f2(AcroFormAppearance.internal.getHeight(formObject) - 2) + " re");
  5330. stream.push("W");
  5331. stream.push("n");
  5332. stream.push(f2(cross.x1.x) + " " + f2(cross.x1.y) + " m");
  5333. stream.push(f2(cross.x2.x) + " " + f2(cross.x2.y) + " l");
  5334. stream.push(f2(cross.x4.x) + " " + f2(cross.x4.y) + " m");
  5335. stream.push(f2(cross.x3.x) + " " + f2(cross.x3.y) + " l");
  5336. stream.push("s");
  5337. stream.push("Q");
  5338. xobj.stream = stream.join("\n");
  5339. return xobj;
  5340. },
  5341. OffPushDown: function OffPushDown(formObject) {
  5342. var xobj = createFormXObject(formObject);
  5343. var stream = [];
  5344. stream.push("0.749023 g");
  5345. stream.push("0 0 " + f2(AcroFormAppearance.internal.getWidth(formObject)) + " " + f2(AcroFormAppearance.internal.getHeight(formObject)) + " re");
  5346. stream.push("f");
  5347. xobj.stream = stream.join("\n");
  5348. return xobj;
  5349. }
  5350. }
  5351. },
  5352. /**
  5353. * Returns the standard Appearance
  5354. *
  5355. * @returns {AcroFormXObject}
  5356. */
  5357. createDefaultAppearanceStream: function createDefaultAppearanceStream(formObject) {
  5358. // Set Helvetica to Standard Font (size: auto)
  5359. // Color: Black
  5360. var fontKey = scope.internal.getFont(formObject.fontName, formObject.fontStyle).id;
  5361. var encodedColor = scope.__private__.encodeColorString(formObject.color);
  5362. var fontSize = formObject.fontSize;
  5363. var result = '/' + fontKey + ' ' + fontSize + ' Tf ' + encodedColor;
  5364. return result;
  5365. }
  5366. };
  5367. AcroFormAppearance.internal = {
  5368. Bezier_C: 0.551915024494,
  5369. calculateCross: function calculateCross(formObject) {
  5370. var width = AcroFormAppearance.internal.getWidth(formObject);
  5371. var height = AcroFormAppearance.internal.getHeight(formObject);
  5372. var a = Math.min(width, height);
  5373. var cross = {
  5374. x1: {
  5375. // upperLeft
  5376. x: (width - a) / 2,
  5377. y: (height - a) / 2 + a // height - borderPadding
  5378. },
  5379. x2: {
  5380. // lowerRight
  5381. x: (width - a) / 2 + a,
  5382. y: (height - a) / 2 // borderPadding
  5383. },
  5384. x3: {
  5385. // lowerLeft
  5386. x: (width - a) / 2,
  5387. y: (height - a) / 2 // borderPadding
  5388. },
  5389. x4: {
  5390. // upperRight
  5391. x: (width - a) / 2 + a,
  5392. y: (height - a) / 2 + a // height - borderPadding
  5393. }
  5394. };
  5395. return cross;
  5396. }
  5397. };
  5398. AcroFormAppearance.internal.getWidth = function (formObject) {
  5399. var result = 0;
  5400. if (_typeof(formObject) === "object") {
  5401. result = scale(formObject.Rect[2]);
  5402. }
  5403. return result;
  5404. };
  5405. AcroFormAppearance.internal.getHeight = function (formObject) {
  5406. var result = 0;
  5407. if (_typeof(formObject) === "object") {
  5408. result = scale(formObject.Rect[3]);
  5409. }
  5410. return result;
  5411. }; // Public:
  5412. /**
  5413. * Add an AcroForm-Field to the jsPDF-instance
  5414. *
  5415. * @name addField
  5416. * @function
  5417. * @instance
  5418. * @param {Object} fieldObject
  5419. * @returns {jsPDF}
  5420. */
  5421. var addField = jsPDFAPI.addField = function (fieldObject) {
  5422. initializeAcroForm.call(this);
  5423. if (fieldObject instanceof AcroFormField) {
  5424. putForm.call(this, fieldObject);
  5425. } else {
  5426. throw new Error('Invalid argument passed to jsPDF.addField.');
  5427. }
  5428. fieldObject.page = scope.internal.getCurrentPageInfo().pageNumber;
  5429. return this;
  5430. };
  5431. /**
  5432. * @name addButton
  5433. * @function
  5434. * @instance
  5435. * @param {AcroFormButton} options
  5436. * @returns {jsPDF}
  5437. * @deprecated
  5438. */
  5439. var addButton = jsPDFAPI.addButton = function (button) {
  5440. if (button instanceof AcroFormButton === false) {
  5441. throw new Error('Invalid argument passed to jsPDF.addButton.');
  5442. }
  5443. return addField.call(this, button);
  5444. };
  5445. /**
  5446. * @name addTextField
  5447. * @function
  5448. * @instance
  5449. * @param {AcroFormTextField} textField
  5450. * @returns {jsPDF}
  5451. * @deprecated
  5452. */
  5453. var addTextField = jsPDFAPI.addTextField = function (textField) {
  5454. if (textField instanceof AcroFormTextField === false) {
  5455. throw new Error('Invalid argument passed to jsPDF.addTextField.');
  5456. }
  5457. return addField.call(this, textField);
  5458. };
  5459. /**
  5460. * @name addChoiceField
  5461. * @function
  5462. * @instance
  5463. * @param {AcroFormChoiceField}
  5464. * @returns {jsPDF}
  5465. * @deprecated
  5466. */
  5467. var addChoiceField = jsPDFAPI.addChoiceField = function (choiceField) {
  5468. if (choiceField instanceof AcroFormChoiceField === false) {
  5469. throw new Error('Invalid argument passed to jsPDF.addChoiceField.');
  5470. }
  5471. return addField.call(this, choiceField);
  5472. };
  5473. if (_typeof(globalObj) == "object" && typeof globalObj["ChoiceField"] === "undefined" && typeof globalObj["ListBox"] === "undefined" && typeof globalObj["ComboBox"] === "undefined" && typeof globalObj["EditBox"] === "undefined" && typeof globalObj["Button"] === "undefined" && typeof globalObj["PushButton"] === "undefined" && typeof globalObj["RadioButton"] === "undefined" && typeof globalObj["CheckBox"] === "undefined" && typeof globalObj["TextField"] === "undefined" && typeof globalObj["PasswordField"] === "undefined") {
  5474. globalObj["ChoiceField"] = AcroFormChoiceField;
  5475. globalObj["ListBox"] = AcroFormListBox;
  5476. globalObj["ComboBox"] = AcroFormComboBox;
  5477. globalObj["EditBox"] = AcroFormEditBox;
  5478. globalObj["Button"] = AcroFormButton;
  5479. globalObj["PushButton"] = AcroFormPushButton;
  5480. globalObj["RadioButton"] = AcroFormRadioButton;
  5481. globalObj["CheckBox"] = AcroFormCheckBox;
  5482. globalObj["TextField"] = AcroFormTextField;
  5483. globalObj["PasswordField"] = AcroFormPasswordField; // backwardsCompatibility
  5484. globalObj["AcroForm"] = {
  5485. Appearance: AcroFormAppearance
  5486. };
  5487. } else {
  5488. console.warn("AcroForm-Classes are not populated into global-namespace, because the class-Names exist already.");
  5489. }
  5490. jsPDFAPI.AcroFormChoiceField = AcroFormChoiceField;
  5491. jsPDFAPI.AcroFormListBox = AcroFormListBox;
  5492. jsPDFAPI.AcroFormComboBox = AcroFormComboBox;
  5493. jsPDFAPI.AcroFormEditBox = AcroFormEditBox;
  5494. jsPDFAPI.AcroFormButton = AcroFormButton;
  5495. jsPDFAPI.AcroFormPushButton = AcroFormPushButton;
  5496. jsPDFAPI.AcroFormRadioButton = AcroFormRadioButton;
  5497. jsPDFAPI.AcroFormCheckBox = AcroFormCheckBox;
  5498. jsPDFAPI.AcroFormTextField = AcroFormTextField;
  5499. jsPDFAPI.AcroFormPasswordField = AcroFormPasswordField;
  5500. jsPDFAPI.AcroFormAppearance = AcroFormAppearance;
  5501. jsPDFAPI.AcroForm = {
  5502. ChoiceField: AcroFormChoiceField,
  5503. ListBox: AcroFormListBox,
  5504. ComboBox: AcroFormComboBox,
  5505. EditBox: AcroFormEditBox,
  5506. Button: AcroFormButton,
  5507. PushButton: AcroFormPushButton,
  5508. RadioButton: AcroFormRadioButton,
  5509. CheckBox: AcroFormCheckBox,
  5510. TextField: AcroFormTextField,
  5511. PasswordField: AcroFormPasswordField,
  5512. Appearance: AcroFormAppearance
  5513. };
  5514. })(jsPDF.API, typeof window !== "undefined" && window || typeof global !== "undefined" && global);
  5515. /** @license
  5516. * jsPDF addImage plugin
  5517. * Copyright (c) 2012 Jason Siefken, https://github.com/siefkenj/
  5518. * 2013 Chris Dowling, https://github.com/gingerchris
  5519. * 2013 Trinh Ho, https://github.com/ineedfat
  5520. * 2013 Edwin Alejandro Perez, https://github.com/eaparango
  5521. * 2013 Norah Smith, https://github.com/burnburnrocket
  5522. * 2014 Diego Casorran, https://github.com/diegocr
  5523. * 2014 James Robb, https://github.com/jamesbrobb
  5524. *
  5525. *
  5526. */
  5527. /**
  5528. * @name addImage
  5529. * @module
  5530. */
  5531. (function (jsPDFAPI) {
  5532. var namespace = 'addImage_';
  5533. var imageFileTypeHeaders = {
  5534. PNG: [[0x89, 0x50, 0x4e, 0x47]],
  5535. TIFF: [[0x4D, 0x4D, 0x00, 0x2A], //Motorola
  5536. [0x49, 0x49, 0x2A, 0x00] //Intel
  5537. ],
  5538. JPEG: [[0xFF, 0xD8, 0xFF, 0xE0, undefined, undefined, 0x4A, 0x46, 0x49, 0x46, 0x00], //JFIF
  5539. [0xFF, 0xD8, 0xFF, 0xE1, undefined, undefined, 0x45, 0x78, 0x69, 0x66, 0x00, 0x00] //Exif
  5540. ],
  5541. JPEG2000: [[0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20]],
  5542. GIF87a: [[0x47, 0x49, 0x46, 0x38, 0x37, 0x61]],
  5543. GIF89a: [[0x47, 0x49, 0x46, 0x38, 0x39, 0x61]],
  5544. BMP: [[0x42, 0x4D], //BM - Windows 3.1x, 95, NT, ... etc.
  5545. [0x42, 0x41], //BA - OS/2 struct bitmap array
  5546. [0x43, 0x49], //CI - OS/2 struct color icon
  5547. [0x43, 0x50], //CP - OS/2 const color pointer
  5548. [0x49, 0x43], //IC - OS/2 struct icon
  5549. [0x50, 0x54] //PT - OS/2 pointer
  5550. ]
  5551. };
  5552. /**
  5553. * Recognize filetype of Image by magic-bytes
  5554. *
  5555. * https://en.wikipedia.org/wiki/List_of_file_signatures
  5556. *
  5557. * @name getImageFileTypeByImageData
  5558. * @public
  5559. * @function
  5560. * @param {string|arraybuffer} imageData imageData as binary String or arraybuffer
  5561. * @param {string} format format of file if filetype-recognition fails, e.g. 'JPEG'
  5562. *
  5563. * @returns {string} filetype of Image
  5564. */
  5565. var getImageFileTypeByImageData = jsPDFAPI.getImageFileTypeByImageData = function (imageData, fallbackFormat) {
  5566. fallbackFormat = fallbackFormat || 'UNKNOWN';
  5567. var i;
  5568. var j;
  5569. var result = 'UNKNOWN';
  5570. var headerSchemata;
  5571. var compareResult;
  5572. var fileType;
  5573. if (jsPDFAPI.isArrayBufferView(imageData)) {
  5574. imageData = jsPDFAPI.arrayBufferToBinaryString(imageData);
  5575. }
  5576. for (fileType in imageFileTypeHeaders) {
  5577. headerSchemata = imageFileTypeHeaders[fileType];
  5578. for (i = 0; i < headerSchemata.length; i += 1) {
  5579. compareResult = true;
  5580. for (j = 0; j < headerSchemata[i].length; j += 1) {
  5581. if (headerSchemata[i][j] === undefined) {
  5582. continue;
  5583. }
  5584. if (headerSchemata[i][j] !== imageData.charCodeAt(j)) {
  5585. compareResult = false;
  5586. break;
  5587. }
  5588. }
  5589. if (compareResult === true) {
  5590. result = fileType;
  5591. break;
  5592. }
  5593. }
  5594. }
  5595. if (result === 'UNKNOWN' && fallbackFormat !== 'UNKNOWN') {
  5596. console.warn('FileType of Image not recognized. Processing image as "' + fallbackFormat + '".');
  5597. result = fallbackFormat;
  5598. }
  5599. return result;
  5600. }; // Image functionality ported from pdf.js
  5601. var putImage = function putImage(img) {
  5602. var objectNumber = this.internal.newObject(),
  5603. out = this.internal.write,
  5604. putStream = this.internal.putStream,
  5605. getFilters = this.internal.getFilters;
  5606. var filters = getFilters();
  5607. while (filters.indexOf('FlateEncode') !== -1) {
  5608. filters.splice(filters.indexOf('FlateEncode'), 1);
  5609. }
  5610. img['n'] = objectNumber;
  5611. var additionalKeyValues = [];
  5612. additionalKeyValues.push({
  5613. key: 'Type',
  5614. value: '/XObject'
  5615. });
  5616. additionalKeyValues.push({
  5617. key: 'Subtype',
  5618. value: '/Image'
  5619. });
  5620. additionalKeyValues.push({
  5621. key: 'Width',
  5622. value: img['w']
  5623. });
  5624. additionalKeyValues.push({
  5625. key: 'Height',
  5626. value: img['h']
  5627. });
  5628. if (img['cs'] === this.color_spaces.INDEXED) {
  5629. additionalKeyValues.push({
  5630. key: 'ColorSpace',
  5631. value: '[/Indexed /DeviceRGB ' // if an indexed png defines more than one colour with transparency, we've created a smask
  5632. + (img['pal'].length / 3 - 1) + ' ' + ('smask' in img ? objectNumber + 2 : objectNumber + 1) + ' 0 R]'
  5633. });
  5634. } else {
  5635. additionalKeyValues.push({
  5636. key: 'ColorSpace',
  5637. value: '/' + img['cs']
  5638. });
  5639. if (img['cs'] === this.color_spaces.DEVICE_CMYK) {
  5640. additionalKeyValues.push({
  5641. key: 'Decode',
  5642. value: '[1 0 1 0 1 0 1 0]'
  5643. });
  5644. }
  5645. }
  5646. additionalKeyValues.push({
  5647. key: 'BitsPerComponent',
  5648. value: img['bpc']
  5649. });
  5650. if ('dp' in img) {
  5651. additionalKeyValues.push({
  5652. key: 'DecodeParms',
  5653. value: '<<' + img['dp'] + '>>'
  5654. });
  5655. }
  5656. if ('trns' in img && img['trns'].constructor == Array) {
  5657. var trns = '',
  5658. i = 0,
  5659. len = img['trns'].length;
  5660. for (; i < len; i++) {
  5661. trns += img['trns'][i] + ' ' + img['trns'][i] + ' ';
  5662. }
  5663. additionalKeyValues.push({
  5664. key: 'Mask',
  5665. value: '[' + trns + ']'
  5666. });
  5667. }
  5668. if ('smask' in img) {
  5669. additionalKeyValues.push({
  5670. key: 'SMask',
  5671. value: objectNumber + 1 + ' 0 R'
  5672. });
  5673. }
  5674. var alreadyAppliedFilters = typeof img['f'] !== "undefined" ? ['/' + img['f']] : undefined;
  5675. putStream({
  5676. data: img['data'],
  5677. additionalKeyValues: additionalKeyValues,
  5678. alreadyAppliedFilters: alreadyAppliedFilters
  5679. });
  5680. out('endobj'); // Soft mask
  5681. if ('smask' in img) {
  5682. var dp = '/Predictor ' + img['p'] + ' /Colors 1 /BitsPerComponent ' + img['bpc'] + ' /Columns ' + img['w'];
  5683. var smask = {
  5684. 'w': img['w'],
  5685. 'h': img['h'],
  5686. 'cs': 'DeviceGray',
  5687. 'bpc': img['bpc'],
  5688. 'dp': dp,
  5689. 'data': img['smask']
  5690. };
  5691. if ('f' in img) smask.f = img['f'];
  5692. putImage.call(this, smask);
  5693. } //Palette
  5694. if (img['cs'] === this.color_spaces.INDEXED) {
  5695. this.internal.newObject(); //out('<< /Filter / ' + img['f'] +' /Length ' + img['pal'].length + '>>');
  5696. //putStream(zlib.compress(img['pal']));
  5697. putStream({
  5698. data: this.arrayBufferToBinaryString(new Uint8Array(img['pal']))
  5699. });
  5700. out('endobj');
  5701. }
  5702. },
  5703. putResourcesCallback = function putResourcesCallback() {
  5704. var images = this.internal.collections[namespace + 'images'];
  5705. for (var i in images) {
  5706. putImage.call(this, images[i]);
  5707. }
  5708. },
  5709. putXObjectsDictCallback = function putXObjectsDictCallback() {
  5710. var images = this.internal.collections[namespace + 'images'],
  5711. out = this.internal.write,
  5712. image;
  5713. for (var i in images) {
  5714. image = images[i];
  5715. out('/I' + image['i'], image['n'], '0', 'R');
  5716. }
  5717. },
  5718. checkCompressValue = function checkCompressValue(value) {
  5719. if (value && typeof value === 'string') value = value.toUpperCase();
  5720. return value in jsPDFAPI.image_compression ? value : jsPDFAPI.image_compression.NONE;
  5721. },
  5722. getImages = function getImages() {
  5723. var images = this.internal.collections[namespace + 'images']; //first run, so initialise stuff
  5724. if (!images) {
  5725. this.internal.collections[namespace + 'images'] = images = {};
  5726. this.internal.events.subscribe('putResources', putResourcesCallback);
  5727. this.internal.events.subscribe('putXobjectDict', putXObjectsDictCallback);
  5728. }
  5729. return images;
  5730. },
  5731. getImageIndex = function getImageIndex(images) {
  5732. var imageIndex = 0;
  5733. if (images) {
  5734. // this is NOT the first time this method is ran on this instance of jsPDF object.
  5735. imageIndex = Object.keys ? Object.keys(images).length : function (o) {
  5736. var i = 0;
  5737. for (var e in o) {
  5738. if (o.hasOwnProperty(e)) {
  5739. i++;
  5740. }
  5741. }
  5742. return i;
  5743. }(images);
  5744. }
  5745. return imageIndex;
  5746. },
  5747. notDefined = function notDefined(value) {
  5748. return typeof value === 'undefined' || value === null || value.length === 0;
  5749. },
  5750. generateAliasFromImageData = function generateAliasFromImageData(imageData) {
  5751. if (typeof imageData === 'string') {
  5752. return jsPDFAPI.sHashCode(imageData);
  5753. }
  5754. if (jsPDFAPI.isArrayBufferView(imageData)) {
  5755. return jsPDFAPI.sHashCode(jsPDFAPI.arrayBufferToBinaryString(imageData));
  5756. }
  5757. return null;
  5758. },
  5759. isImageTypeSupported = function isImageTypeSupported(type) {
  5760. return typeof jsPDFAPI["process" + type.toUpperCase()] === "function";
  5761. },
  5762. isDOMElement = function isDOMElement(object) {
  5763. return _typeof(object) === 'object' && object.nodeType === 1;
  5764. },
  5765. createDataURIFromElement = function createDataURIFromElement(element, format) {
  5766. //if element is an image which uses data url definition, just return the dataurl
  5767. if (element.nodeName === 'IMG' && element.hasAttribute('src')) {
  5768. var src = '' + element.getAttribute('src'); //is base64 encoded dataUrl, directly process it
  5769. if (src.indexOf('data:image/') === 0) {
  5770. return unescape(src);
  5771. } //it is probably an url, try to load it
  5772. var tmpImageData = jsPDFAPI.loadFile(src);
  5773. if (tmpImageData !== undefined) {
  5774. return btoa(tmpImageData);
  5775. }
  5776. }
  5777. if (element.nodeName === 'CANVAS') {
  5778. var canvas = element;
  5779. return element.toDataURL('image/jpeg', 1.0);
  5780. } //absolute fallback method
  5781. var canvas = document.createElement('canvas');
  5782. canvas.width = element.clientWidth || element.width;
  5783. canvas.height = element.clientHeight || element.height;
  5784. var ctx = canvas.getContext('2d');
  5785. if (!ctx) {
  5786. throw 'addImage requires canvas to be supported by browser.';
  5787. }
  5788. ctx.drawImage(element, 0, 0, canvas.width, canvas.height);
  5789. return canvas.toDataURL(('' + format).toLowerCase() == 'png' ? 'image/png' : 'image/jpeg');
  5790. },
  5791. checkImagesForAlias = function checkImagesForAlias(alias, images) {
  5792. var cached_info;
  5793. if (images) {
  5794. for (var e in images) {
  5795. if (alias === images[e].alias) {
  5796. cached_info = images[e];
  5797. break;
  5798. }
  5799. }
  5800. }
  5801. return cached_info;
  5802. },
  5803. determineWidthAndHeight = function determineWidthAndHeight(w, h, info) {
  5804. if (!w && !h) {
  5805. w = -96;
  5806. h = -96;
  5807. }
  5808. if (w < 0) {
  5809. w = -1 * info['w'] * 72 / w / this.internal.scaleFactor;
  5810. }
  5811. if (h < 0) {
  5812. h = -1 * info['h'] * 72 / h / this.internal.scaleFactor;
  5813. }
  5814. if (w === 0) {
  5815. w = h * info['w'] / info['h'];
  5816. }
  5817. if (h === 0) {
  5818. h = w * info['h'] / info['w'];
  5819. }
  5820. return [w, h];
  5821. },
  5822. writeImageToPDF = function writeImageToPDF(x, y, w, h, info, index, images, rotation) {
  5823. var dims = determineWidthAndHeight.call(this, w, h, info),
  5824. coord = this.internal.getCoordinateString,
  5825. vcoord = this.internal.getVerticalCoordinateString;
  5826. w = dims[0];
  5827. h = dims[1];
  5828. images[index] = info;
  5829. if (rotation) {
  5830. rotation *= Math.PI / 180;
  5831. var c = Math.cos(rotation);
  5832. var s = Math.sin(rotation); //like in pdf Reference do it 4 digits instead of 2
  5833. var f4 = function f4(number) {
  5834. return number.toFixed(4);
  5835. };
  5836. var rotationTransformationMatrix = [f4(c), f4(s), f4(s * -1), f4(c), 0, 0, 'cm'];
  5837. }
  5838. this.internal.write('q'); //Save graphics state
  5839. if (rotation) {
  5840. this.internal.write([1, '0', '0', 1, coord(x), vcoord(y + h), 'cm'].join(' ')); //Translate
  5841. this.internal.write(rotationTransformationMatrix.join(' ')); //Rotate
  5842. this.internal.write([coord(w), '0', '0', coord(h), '0', '0', 'cm'].join(' ')); //Scale
  5843. } else {
  5844. this.internal.write([coord(w), '0', '0', coord(h), coord(x), vcoord(y + h), 'cm'].join(' ')); //Translate and Scale
  5845. }
  5846. this.internal.write('/I' + info['i'] + ' Do'); //Paint Image
  5847. this.internal.write('Q'); //Restore graphics state
  5848. };
  5849. /**
  5850. * COLOR SPACES
  5851. */
  5852. jsPDFAPI.color_spaces = {
  5853. DEVICE_RGB: 'DeviceRGB',
  5854. DEVICE_GRAY: 'DeviceGray',
  5855. DEVICE_CMYK: 'DeviceCMYK',
  5856. CAL_GREY: 'CalGray',
  5857. CAL_RGB: 'CalRGB',
  5858. LAB: 'Lab',
  5859. ICC_BASED: 'ICCBased',
  5860. INDEXED: 'Indexed',
  5861. PATTERN: 'Pattern',
  5862. SEPARATION: 'Separation',
  5863. DEVICE_N: 'DeviceN'
  5864. };
  5865. /**
  5866. * DECODE METHODS
  5867. */
  5868. jsPDFAPI.decode = {
  5869. DCT_DECODE: 'DCTDecode',
  5870. FLATE_DECODE: 'FlateDecode',
  5871. LZW_DECODE: 'LZWDecode',
  5872. JPX_DECODE: 'JPXDecode',
  5873. JBIG2_DECODE: 'JBIG2Decode',
  5874. ASCII85_DECODE: 'ASCII85Decode',
  5875. ASCII_HEX_DECODE: 'ASCIIHexDecode',
  5876. RUN_LENGTH_DECODE: 'RunLengthDecode',
  5877. CCITT_FAX_DECODE: 'CCITTFaxDecode'
  5878. };
  5879. /**
  5880. * IMAGE COMPRESSION TYPES
  5881. */
  5882. jsPDFAPI.image_compression = {
  5883. NONE: 'NONE',
  5884. FAST: 'FAST',
  5885. MEDIUM: 'MEDIUM',
  5886. SLOW: 'SLOW'
  5887. };
  5888. /**
  5889. * @name sHashCode
  5890. * @function
  5891. * @param {string} str
  5892. * @returns {string}
  5893. */
  5894. jsPDFAPI.sHashCode = function (str) {
  5895. str = str || "";
  5896. var hash = 0,
  5897. i,
  5898. chr;
  5899. if (str.length === 0) return hash;
  5900. for (i = 0; i < str.length; i++) {
  5901. chr = str.charCodeAt(i);
  5902. hash = (hash << 5) - hash + chr;
  5903. hash |= 0; // Convert to 32bit integer
  5904. }
  5905. return hash;
  5906. };
  5907. /**
  5908. * @name isString
  5909. * @function
  5910. * @param {any} object
  5911. * @returns {boolean}
  5912. */
  5913. jsPDFAPI.isString = function (object) {
  5914. return typeof object === 'string';
  5915. };
  5916. /**
  5917. * Validates if given String is a valid Base64-String
  5918. *
  5919. * @name validateStringAsBase64
  5920. * @public
  5921. * @function
  5922. * @param {String} possible Base64-String
  5923. *
  5924. * @returns {boolean}
  5925. */
  5926. jsPDFAPI.validateStringAsBase64 = function (possibleBase64String) {
  5927. possibleBase64String = possibleBase64String || '';
  5928. possibleBase64String.toString().trim();
  5929. var result = true;
  5930. if (possibleBase64String.length === 0) {
  5931. result = false;
  5932. }
  5933. if (possibleBase64String.length % 4 !== 0) {
  5934. result = false;
  5935. }
  5936. if (/^[A-Za-z0-9+\/]+$/.test(possibleBase64String.substr(0, possibleBase64String.length - 2)) === false) {
  5937. result = false;
  5938. }
  5939. if (/^[A-Za-z0-9\/][A-Za-z0-9+\/]|[A-Za-z0-9+\/]=|==$/.test(possibleBase64String.substr(-2)) === false) {
  5940. result = false;
  5941. }
  5942. return result;
  5943. };
  5944. /**
  5945. * Strips out and returns info from a valid base64 data URI
  5946. *
  5947. * @name extractInfoFromBase64DataURI
  5948. * @function
  5949. * @param {string} dataUrl a valid data URI of format 'data:[<MIME-type>][;base64],<data>'
  5950. * @returns {Array}an Array containing the following
  5951. * [0] the complete data URI
  5952. * [1] <MIME-type>
  5953. * [2] format - the second part of the mime-type i.e 'png' in 'image/png'
  5954. * [4] <data>
  5955. */
  5956. jsPDFAPI.extractInfoFromBase64DataURI = function (dataURI) {
  5957. return /^data:([\w]+?\/([\w]+?));\S*;*base64,(.+)$/g.exec(dataURI);
  5958. };
  5959. /**
  5960. * Strips out and returns info from a valid base64 data URI
  5961. *
  5962. * @name extractImageFromDataUrl
  5963. * @function
  5964. * @param {string} dataUrl a valid data URI of format 'data:[<MIME-type>][;base64],<data>'
  5965. * @returns {Array}an Array containing the following
  5966. * [0] the complete data URI
  5967. * [1] <MIME-type>
  5968. * [2] format - the second part of the mime-type i.e 'png' in 'image/png'
  5969. * [4] <data>
  5970. */
  5971. jsPDFAPI.extractImageFromDataUrl = function (dataUrl) {
  5972. dataUrl = dataUrl || '';
  5973. var dataUrlParts = dataUrl.split('base64,');
  5974. var result = null;
  5975. if (dataUrlParts.length === 2) {
  5976. var extractedInfo = /^data:(\w*\/\w*);*(charset=[\w=-]*)*;*$/.exec(dataUrlParts[0]);
  5977. if (Array.isArray(extractedInfo)) {
  5978. result = {
  5979. mimeType: extractedInfo[1],
  5980. charset: extractedInfo[2],
  5981. data: dataUrlParts[1]
  5982. };
  5983. }
  5984. }
  5985. return result;
  5986. };
  5987. /**
  5988. * Check to see if ArrayBuffer is supported
  5989. *
  5990. * @name supportsArrayBuffer
  5991. * @function
  5992. * @returns {boolean}
  5993. */
  5994. jsPDFAPI.supportsArrayBuffer = function () {
  5995. return typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined';
  5996. };
  5997. /**
  5998. * Tests supplied object to determine if ArrayBuffer
  5999. *
  6000. * @name isArrayBuffer
  6001. * @function
  6002. * @param {Object} object an Object
  6003. *
  6004. * @returns {boolean}
  6005. */
  6006. jsPDFAPI.isArrayBuffer = function (object) {
  6007. if (!this.supportsArrayBuffer()) return false;
  6008. return object instanceof ArrayBuffer;
  6009. };
  6010. /**
  6011. * Tests supplied object to determine if it implements the ArrayBufferView (TypedArray) interface
  6012. *
  6013. * @name isArrayBufferView
  6014. * @function
  6015. * @param {Object} object an Object
  6016. * @returns {boolean}
  6017. */
  6018. jsPDFAPI.isArrayBufferView = function (object) {
  6019. if (!this.supportsArrayBuffer()) return false;
  6020. if (typeof Uint32Array === 'undefined') return false;
  6021. return object instanceof Int8Array || object instanceof Uint8Array || typeof Uint8ClampedArray !== 'undefined' && object instanceof Uint8ClampedArray || object instanceof Int16Array || object instanceof Uint16Array || object instanceof Int32Array || object instanceof Uint32Array || object instanceof Float32Array || object instanceof Float64Array;
  6022. };
  6023. /**
  6024. * Convert the Buffer to a Binary String
  6025. *
  6026. * @name binaryStringToUint8Array
  6027. * @public
  6028. * @function
  6029. * @param {ArrayBuffer} BinaryString with ImageData
  6030. *
  6031. * @returns {Uint8Array}
  6032. */
  6033. jsPDFAPI.binaryStringToUint8Array = function (binary_string) {
  6034. /*
  6035. * not sure how efficient this will be will bigger files. Is there a native method?
  6036. */
  6037. var len = binary_string.length;
  6038. var bytes = new Uint8Array(len);
  6039. for (var i = 0; i < len; i++) {
  6040. bytes[i] = binary_string.charCodeAt(i);
  6041. }
  6042. return bytes;
  6043. };
  6044. /**
  6045. * Convert the Buffer to a Binary String
  6046. *
  6047. * @name arrayBufferToBinaryString
  6048. * @public
  6049. * @function
  6050. * @param {ArrayBuffer} ArrayBuffer with ImageData
  6051. *
  6052. * @returns {String}
  6053. */
  6054. jsPDFAPI.arrayBufferToBinaryString = function (buffer) {
  6055. // if (typeof Uint8Array !== 'undefined' && typeof Uint8Array.prototype.reduce !== 'undefined') {
  6056. // return new Uint8Array(buffer).reduce(function (data, byte) {
  6057. // return data.push(String.fromCharCode(byte)), data;
  6058. // }, []).join('');
  6059. // }
  6060. if (typeof atob === "function") {
  6061. return atob(this.arrayBufferToBase64(buffer));
  6062. }
  6063. };
  6064. /**
  6065. * Converts an ArrayBuffer directly to base64
  6066. *
  6067. * Taken from http://jsperf.com/encoding-xhr-image-data/31
  6068. *
  6069. * Need to test if this is a better solution for larger files
  6070. *
  6071. * @name arrayBufferToBase64
  6072. * @param {arraybuffer} arrayBuffer
  6073. * @public
  6074. * @function
  6075. *
  6076. * @returns {string}
  6077. */
  6078. jsPDFAPI.arrayBufferToBase64 = function (arrayBuffer) {
  6079. var base64 = '';
  6080. var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  6081. var bytes = new Uint8Array(arrayBuffer);
  6082. var byteLength = bytes.byteLength;
  6083. var byteRemainder = byteLength % 3;
  6084. var mainLength = byteLength - byteRemainder;
  6085. var a, b, c, d;
  6086. var chunk; // Main loop deals with bytes in chunks of 3
  6087. for (var i = 0; i < mainLength; i = i + 3) {
  6088. // Combine the three bytes into a single integer
  6089. chunk = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2]; // Use bitmasks to extract 6-bit segments from the triplet
  6090. a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18
  6091. b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12
  6092. c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6
  6093. d = chunk & 63; // 63 = 2^6 - 1
  6094. // Convert the raw binary segments to the appropriate ASCII encoding
  6095. base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d];
  6096. } // Deal with the remaining bytes and padding
  6097. if (byteRemainder == 1) {
  6098. chunk = bytes[mainLength];
  6099. a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2
  6100. // Set the 4 least significant bits to zero
  6101. b = (chunk & 3) << 4; // 3 = 2^2 - 1
  6102. base64 += encodings[a] + encodings[b] + '==';
  6103. } else if (byteRemainder == 2) {
  6104. chunk = bytes[mainLength] << 8 | bytes[mainLength + 1];
  6105. a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10
  6106. b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4
  6107. // Set the 2 least significant bits to zero
  6108. c = (chunk & 15) << 2; // 15 = 2^4 - 1
  6109. base64 += encodings[a] + encodings[b] + encodings[c] + '=';
  6110. }
  6111. return base64;
  6112. };
  6113. /**
  6114. *
  6115. * @name createImageInfo
  6116. * @param {Object} data
  6117. * @param {number} wd width
  6118. * @param {number} ht height
  6119. * @param {Object} cs colorSpace
  6120. * @param {number} bpc bits per channel
  6121. * @param {any} f
  6122. * @param {number} imageIndex
  6123. * @param {string} alias
  6124. * @param {any} dp
  6125. * @param {any} trns
  6126. * @param {any} pal
  6127. * @param {any} smask
  6128. * @param {any} p
  6129. * @public
  6130. * @function
  6131. *
  6132. * @returns {Object}
  6133. */
  6134. jsPDFAPI.createImageInfo = function (data, wd, ht, cs, bpc, f, imageIndex, alias, dp, trns, pal, smask, p) {
  6135. var info = {
  6136. alias: alias,
  6137. w: wd,
  6138. h: ht,
  6139. cs: cs,
  6140. bpc: bpc,
  6141. i: imageIndex,
  6142. data: data // n: objectNumber will be added by putImage code
  6143. };
  6144. if (f) info.f = f;
  6145. if (dp) info.dp = dp;
  6146. if (trns) info.trns = trns;
  6147. if (pal) info.pal = pal;
  6148. if (smask) info.smask = smask;
  6149. if (p) info.p = p; // predictor parameter for PNG compression
  6150. return info;
  6151. };
  6152. /**
  6153. * Adds an Image to the PDF.
  6154. *
  6155. * @name addImage
  6156. * @public
  6157. * @function
  6158. * @param {string/Image-Element/Canvas-Element/Uint8Array} imageData imageData as base64 encoded DataUrl or Image-HTMLElement or Canvas-HTMLElement
  6159. * @param {string} format format of file if filetype-recognition fails, e.g. 'JPEG'
  6160. * @param {number} x x Coordinate (in units declared at inception of PDF document) against left edge of the page
  6161. * @param {number} y y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  6162. * @param {number} width width of the image (in units declared at inception of PDF document)
  6163. * @param {number} height height of the Image (in units declared at inception of PDF document)
  6164. * @param {string} alias alias of the image (if used multiple times)
  6165. * @param {string} compression compression of the generated JPEG, can have the values 'NONE', 'FAST', 'MEDIUM' and 'SLOW'
  6166. * @param {number} rotation rotation of the image in degrees (0-359)
  6167. *
  6168. * @returns jsPDF
  6169. */
  6170. jsPDFAPI.addImage = function (imageData, format, x, y, w, h, alias, compression, rotation) {
  6171. var tmpImageData = '';
  6172. if (typeof format !== 'string') {
  6173. var tmp = h;
  6174. h = w;
  6175. w = y;
  6176. y = x;
  6177. x = format;
  6178. format = tmp;
  6179. }
  6180. if (_typeof(imageData) === 'object' && !isDOMElement(imageData) && "imageData" in imageData) {
  6181. var options = imageData;
  6182. imageData = options.imageData;
  6183. format = options.format || format || 'UNKNOWN';
  6184. x = options.x || x || 0;
  6185. y = options.y || y || 0;
  6186. w = options.w || w;
  6187. h = options.h || h;
  6188. alias = options.alias || alias;
  6189. compression = options.compression || compression;
  6190. rotation = options.rotation || options.angle || rotation;
  6191. } //If compression is not explicitly set, determine if we should use compression
  6192. var filters = this.internal.getFilters();
  6193. if (compression === undefined && filters.indexOf('FlateEncode') !== -1) {
  6194. compression = 'SLOW';
  6195. }
  6196. if (typeof imageData === "string") {
  6197. imageData = unescape(imageData);
  6198. }
  6199. if (isNaN(x) || isNaN(y)) {
  6200. console.error('jsPDF.addImage: Invalid coordinates', arguments);
  6201. throw new Error('Invalid coordinates passed to jsPDF.addImage');
  6202. }
  6203. var images = getImages.call(this),
  6204. info,
  6205. dataAsBinaryString;
  6206. if (!(info = checkImagesForAlias(imageData, images))) {
  6207. if (isDOMElement(imageData)) imageData = createDataURIFromElement(imageData, format);
  6208. if (notDefined(alias)) alias = generateAliasFromImageData(imageData);
  6209. if (!(info = checkImagesForAlias(alias, images))) {
  6210. if (this.isString(imageData)) {
  6211. tmpImageData = this.convertStringToImageData(imageData);
  6212. if (tmpImageData !== '') {
  6213. imageData = tmpImageData;
  6214. } else {
  6215. tmpImageData = jsPDFAPI.loadFile(imageData);
  6216. if (tmpImageData !== undefined) {
  6217. imageData = tmpImageData;
  6218. }
  6219. }
  6220. }
  6221. format = this.getImageFileTypeByImageData(imageData, format);
  6222. if (!isImageTypeSupported(format)) throw new Error('addImage does not support files of type \'' + format + '\', please ensure that a plugin for \'' + format + '\' support is added.');
  6223. /**
  6224. * need to test if it's more efficient to convert all binary strings
  6225. * to TypedArray - or should we just leave and process as string?
  6226. */
  6227. if (this.supportsArrayBuffer()) {
  6228. // no need to convert if imageData is already uint8array
  6229. if (!(imageData instanceof Uint8Array)) {
  6230. dataAsBinaryString = imageData;
  6231. imageData = this.binaryStringToUint8Array(imageData);
  6232. }
  6233. }
  6234. info = this['process' + format.toUpperCase()](imageData, getImageIndex(images), alias, checkCompressValue(compression), dataAsBinaryString);
  6235. if (!info) {
  6236. throw new Error('An unknown error occurred whilst processing the image');
  6237. }
  6238. }
  6239. }
  6240. writeImageToPDF.call(this, x, y, w, h, info, info.i, images, rotation);
  6241. return this;
  6242. };
  6243. /**
  6244. * @name convertStringToImageData
  6245. * @function
  6246. * @param {string} stringData
  6247. * @returns {string} binary data
  6248. */
  6249. jsPDFAPI.convertStringToImageData = function (stringData) {
  6250. var base64Info;
  6251. var imageData = '';
  6252. var rawData;
  6253. if (this.isString(stringData)) {
  6254. var base64Info = this.extractImageFromDataUrl(stringData);
  6255. rawData = base64Info !== null ? base64Info.data : stringData;
  6256. try {
  6257. imageData = atob(rawData);
  6258. } catch (e) {
  6259. if (!jsPDFAPI.validateStringAsBase64(rawData)) {
  6260. throw new Error('Supplied Data is not a valid base64-String jsPDF.convertStringToImageData ');
  6261. } else {
  6262. throw new Error('atob-Error in jsPDF.convertStringToImageData ' + e.message);
  6263. }
  6264. }
  6265. }
  6266. return imageData;
  6267. };
  6268. /**
  6269. * JPEG SUPPORT
  6270. **/
  6271. //takes a string imgData containing the raw bytes of
  6272. //a jpeg image and returns [width, height]
  6273. //Algorithm from: http://www.64lines.com/jpeg-width-height
  6274. var getJpegSize = function getJpegSize(imgData) {
  6275. var width, height, numcomponents; // Verify we have a valid jpeg header 0xff,0xd8,0xff,0xe0,?,?,'J','F','I','F',0x00
  6276. if (getImageFileTypeByImageData(imgData) !== 'JPEG') {
  6277. throw new Error('getJpegSize requires a binary string jpeg file');
  6278. }
  6279. var blockLength = imgData.charCodeAt(4) * 256 + imgData.charCodeAt(5);
  6280. var i = 4,
  6281. len = imgData.length;
  6282. while (i < len) {
  6283. i += blockLength;
  6284. if (imgData.charCodeAt(i) !== 0xff) {
  6285. throw new Error('getJpegSize could not find the size of the image');
  6286. }
  6287. if (imgData.charCodeAt(i + 1) === 0xc0 || //(SOF) Huffman - Baseline DCT
  6288. imgData.charCodeAt(i + 1) === 0xc1 || //(SOF) Huffman - Extended sequential DCT
  6289. imgData.charCodeAt(i + 1) === 0xc2 || // Progressive DCT (SOF2)
  6290. imgData.charCodeAt(i + 1) === 0xc3 || // Spatial (sequential) lossless (SOF3)
  6291. imgData.charCodeAt(i + 1) === 0xc4 || // Differential sequential DCT (SOF5)
  6292. imgData.charCodeAt(i + 1) === 0xc5 || // Differential progressive DCT (SOF6)
  6293. imgData.charCodeAt(i + 1) === 0xc6 || // Differential spatial (SOF7)
  6294. imgData.charCodeAt(i + 1) === 0xc7) {
  6295. height = imgData.charCodeAt(i + 5) * 256 + imgData.charCodeAt(i + 6);
  6296. width = imgData.charCodeAt(i + 7) * 256 + imgData.charCodeAt(i + 8);
  6297. numcomponents = imgData.charCodeAt(i + 9);
  6298. return [width, height, numcomponents];
  6299. } else {
  6300. i += 2;
  6301. blockLength = imgData.charCodeAt(i) * 256 + imgData.charCodeAt(i + 1);
  6302. }
  6303. }
  6304. },
  6305. getJpegSizeFromBytes = function getJpegSizeFromBytes(data) {
  6306. var hdr = data[0] << 8 | data[1];
  6307. if (hdr !== 0xFFD8) throw new Error('Supplied data is not a JPEG');
  6308. var len = data.length,
  6309. block = (data[4] << 8) + data[5],
  6310. pos = 4,
  6311. bytes,
  6312. width,
  6313. height,
  6314. numcomponents;
  6315. while (pos < len) {
  6316. pos += block;
  6317. bytes = readBytes(data, pos);
  6318. block = (bytes[2] << 8) + bytes[3];
  6319. if ((bytes[1] === 0xC0 || bytes[1] === 0xC2) && bytes[0] === 0xFF && block > 7) {
  6320. bytes = readBytes(data, pos + 5);
  6321. width = (bytes[2] << 8) + bytes[3];
  6322. height = (bytes[0] << 8) + bytes[1];
  6323. numcomponents = bytes[4];
  6324. return {
  6325. width: width,
  6326. height: height,
  6327. numcomponents: numcomponents
  6328. };
  6329. }
  6330. pos += 2;
  6331. }
  6332. throw new Error('getJpegSizeFromBytes could not find the size of the image');
  6333. },
  6334. readBytes = function readBytes(data, offset) {
  6335. return data.subarray(offset, offset + 5);
  6336. };
  6337. /**
  6338. * @ignore
  6339. */
  6340. jsPDFAPI.processJPEG = function (data, index, alias, compression, dataAsBinaryString, colorSpace) {
  6341. var filter = this.decode.DCT_DECODE,
  6342. bpc = 8,
  6343. dims;
  6344. if (!this.isString(data) && !this.isArrayBuffer(data) && !this.isArrayBufferView(data)) {
  6345. return null;
  6346. }
  6347. if (this.isString(data)) {
  6348. dims = getJpegSize(data);
  6349. }
  6350. if (this.isArrayBuffer(data)) {
  6351. data = new Uint8Array(data);
  6352. }
  6353. if (this.isArrayBufferView(data)) {
  6354. dims = getJpegSizeFromBytes(data); // if we already have a stored binary string rep use that
  6355. data = dataAsBinaryString || this.arrayBufferToBinaryString(data);
  6356. }
  6357. if (colorSpace === undefined) {
  6358. switch (dims.numcomponents) {
  6359. case 1:
  6360. colorSpace = this.color_spaces.DEVICE_GRAY;
  6361. break;
  6362. case 4:
  6363. colorSpace = this.color_spaces.DEVICE_CMYK;
  6364. break;
  6365. default:
  6366. case 3:
  6367. colorSpace = this.color_spaces.DEVICE_RGB;
  6368. break;
  6369. }
  6370. }
  6371. return this.createImageInfo(data, dims.width, dims.height, colorSpace, bpc, filter, index, alias);
  6372. };
  6373. /**
  6374. * @ignore
  6375. */
  6376. jsPDFAPI.processJPG = function ()
  6377. /*data, index, alias, compression, dataAsBinaryString*/
  6378. {
  6379. return this.processJPEG.apply(this, arguments);
  6380. };
  6381. /**
  6382. * @name getImageProperties
  6383. * @function
  6384. * @param {Object} imageData
  6385. * @returns {Object}
  6386. */
  6387. jsPDFAPI.getImageProperties = function (imageData) {
  6388. var info;
  6389. var tmpImageData = '';
  6390. var format;
  6391. if (isDOMElement(imageData)) {
  6392. imageData = createDataURIFromElement(imageData);
  6393. }
  6394. if (this.isString(imageData)) {
  6395. tmpImageData = this.convertStringToImageData(imageData);
  6396. if (tmpImageData !== '') {
  6397. imageData = tmpImageData;
  6398. } else {
  6399. tmpImageData = jsPDFAPI.loadFile(imageData);
  6400. if (tmpImageData !== undefined) {
  6401. imageData = tmpImageData;
  6402. }
  6403. }
  6404. }
  6405. format = this.getImageFileTypeByImageData(imageData);
  6406. if (!isImageTypeSupported(format)) {
  6407. throw new Error('addImage does not support files of type \'' + format + '\', please ensure that a plugin for \'' + format + '\' support is added.');
  6408. }
  6409. /**
  6410. * need to test if it's more efficient to convert all binary strings
  6411. * to TypedArray - or should we just leave and process as string?
  6412. */
  6413. if (this.supportsArrayBuffer()) {
  6414. // no need to convert if imageData is already uint8array
  6415. if (!(imageData instanceof Uint8Array)) {
  6416. imageData = this.binaryStringToUint8Array(imageData);
  6417. }
  6418. }
  6419. info = this['process' + format.toUpperCase()](imageData);
  6420. if (!info) {
  6421. throw new Error('An unknown error occurred whilst processing the image');
  6422. }
  6423. return {
  6424. fileType: format,
  6425. width: info.w,
  6426. height: info.h,
  6427. colorSpace: info.cs,
  6428. compressionMode: info.f,
  6429. bitsPerComponent: info.bpc
  6430. };
  6431. };
  6432. })(jsPDF.API);
  6433. /**
  6434. * @license
  6435. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  6436. *
  6437. * Licensed under the MIT License.
  6438. * http://opensource.org/licenses/mit-license
  6439. */
  6440. /**
  6441. * jsPDF Annotations PlugIn
  6442. *
  6443. * There are many types of annotations in a PDF document. Annotations are placed
  6444. * on a page at a particular location. They are not 'attached' to an object.
  6445. * <br />
  6446. * This plugin current supports <br />
  6447. * <li> Goto Page (set pageNumber and top in options)
  6448. * <li> Goto Name (set name and top in options)
  6449. * <li> Goto URL (set url in options)
  6450. * <p>
  6451. * The destination magnification factor can also be specified when goto is a page number or a named destination. (see documentation below)
  6452. * (set magFactor in options). XYZ is the default.
  6453. * </p>
  6454. * <p>
  6455. * Links, Text, Popup, and FreeText are supported.
  6456. * </p>
  6457. * <p>
  6458. * Options In PDF spec Not Implemented Yet
  6459. * <li> link border
  6460. * <li> named target
  6461. * <li> page coordinates
  6462. * <li> destination page scaling and layout
  6463. * <li> actions other than URL and GotoPage
  6464. * <li> background / hover actions
  6465. * </p>
  6466. * @name annotations
  6467. * @module
  6468. */
  6469. /*
  6470. Destination Magnification Factors
  6471. See PDF 1.3 Page 386 for meanings and options
  6472. [supported]
  6473. XYZ (options; left top zoom)
  6474. Fit (no options)
  6475. FitH (options: top)
  6476. FitV (options: left)
  6477. [not supported]
  6478. FitR
  6479. FitB
  6480. FitBH
  6481. FitBV
  6482. */
  6483. (function (jsPDFAPI) {
  6484. jsPDF.API.events.push(['addPage', function (addPageData) {
  6485. var pageInfo = this.internal.getPageInfo(addPageData.pageNumber);
  6486. pageInfo.pageContext.annotations = [];
  6487. }]);
  6488. jsPDFAPI.events.push(['putPage', function (putPageData) {
  6489. var pageInfo = this.internal.getPageInfoByObjId(putPageData.objId);
  6490. var pageAnnos = putPageData.pageContext.annotations;
  6491. var notEmpty = function notEmpty(obj) {
  6492. if (typeof obj != 'undefined') {
  6493. if (obj != '') {
  6494. return true;
  6495. }
  6496. }
  6497. };
  6498. var found = false;
  6499. for (var a = 0; a < pageAnnos.length && !found; a++) {
  6500. var anno = pageAnnos[a];
  6501. switch (anno.type) {
  6502. case 'link':
  6503. if (notEmpty(anno.options.url) || notEmpty(anno.options.pageNumber)) {
  6504. found = true;
  6505. break;
  6506. }
  6507. case 'reference':
  6508. case 'text':
  6509. case 'freetext':
  6510. found = true;
  6511. break;
  6512. }
  6513. }
  6514. if (found == false) {
  6515. return;
  6516. }
  6517. this.internal.write("/Annots [");
  6518. var pageHeight = this.internal.pageSize.height;
  6519. var getHorizontalCoordinateString = this.internal.getCoordinateString;
  6520. var getVerticalCoordinateString = this.internal.getVerticalCoordinateString;
  6521. for (var a = 0; a < pageAnnos.length; a++) {
  6522. var anno = pageAnnos[a];
  6523. switch (anno.type) {
  6524. case 'reference':
  6525. // References to Widget Annotations (for AcroForm Fields)
  6526. this.internal.write(' ' + anno.object.objId + ' 0 R ');
  6527. break;
  6528. case 'text':
  6529. // Create a an object for both the text and the popup
  6530. var objText = this.internal.newAdditionalObject();
  6531. var objPopup = this.internal.newAdditionalObject();
  6532. var title = anno.title || 'Note';
  6533. var rect = "/Rect [" + getHorizontalCoordinateString(anno.bounds.x) + " " + getVerticalCoordinateString(anno.bounds.y + anno.bounds.h) + " " + getHorizontalCoordinateString(anno.bounds.x + anno.bounds.w) + " " + getVerticalCoordinateString(anno.bounds.y) + "] ";
  6534. line = '<</Type /Annot /Subtype /' + 'Text' + ' ' + rect + '/Contents (' + anno.contents + ')';
  6535. line += ' /Popup ' + objPopup.objId + " 0 R";
  6536. line += ' /P ' + pageInfo.objId + " 0 R";
  6537. line += ' /T (' + title + ') >>';
  6538. objText.content = line;
  6539. var parent = objText.objId + ' 0 R';
  6540. var popoff = 30;
  6541. var rect = "/Rect [" + getHorizontalCoordinateString(anno.bounds.x + popoff) + " " + getVerticalCoordinateString(anno.bounds.y + anno.bounds.h) + " " + getHorizontalCoordinateString(anno.bounds.x + anno.bounds.w + popoff) + " " + getVerticalCoordinateString(anno.bounds.y) + "] ";
  6542. line = '<</Type /Annot /Subtype /' + 'Popup' + ' ' + rect + ' /Parent ' + parent;
  6543. if (anno.open) {
  6544. line += ' /Open true';
  6545. }
  6546. line += ' >>';
  6547. objPopup.content = line;
  6548. this.internal.write(objText.objId, '0 R', objPopup.objId, '0 R');
  6549. break;
  6550. case 'freetext':
  6551. var rect = "/Rect [" + getHorizontalCoordinateString(anno.bounds.x) + " " + getVerticalCoordinateString(anno.bounds.y) + " " + getHorizontalCoordinateString(anno.bounds.x + anno.bounds.w) + " " + getVerticalCoordinateString(anno.bounds.y + anno.bounds.h) + "] ";
  6552. var color = anno.color || '#000000';
  6553. line = '<</Type /Annot /Subtype /' + 'FreeText' + ' ' + rect + '/Contents (' + anno.contents + ')';
  6554. line += ' /DS(font: Helvetica,sans-serif 12.0pt; text-align:left; color:#' + color + ')';
  6555. line += ' /Border [0 0 0]';
  6556. line += ' >>';
  6557. this.internal.write(line);
  6558. break;
  6559. case 'link':
  6560. if (anno.options.name) {
  6561. var loc = this.annotations._nameMap[anno.options.name];
  6562. anno.options.pageNumber = loc.page;
  6563. anno.options.top = loc.y;
  6564. } else {
  6565. if (!anno.options.top) {
  6566. anno.options.top = 0;
  6567. }
  6568. }
  6569. var rect = "/Rect [" + getHorizontalCoordinateString(anno.x) + " " + getVerticalCoordinateString(anno.y) + " " + getHorizontalCoordinateString(anno.x + anno.w) + " " + getVerticalCoordinateString(anno.y + anno.h) + "] ";
  6570. var line = '';
  6571. if (anno.options.url) {
  6572. line = '<</Type /Annot /Subtype /Link ' + rect + '/Border [0 0 0] /A <</S /URI /URI (' + anno.options.url + ') >>';
  6573. } else if (anno.options.pageNumber) {
  6574. // first page is 0
  6575. var info = this.internal.getPageInfo(anno.options.pageNumber);
  6576. line = '<</Type /Annot /Subtype /Link ' + rect + '/Border [0 0 0] /Dest [' + info.objId + " 0 R";
  6577. anno.options.magFactor = anno.options.magFactor || "XYZ";
  6578. switch (anno.options.magFactor) {
  6579. case 'Fit':
  6580. line += ' /Fit]';
  6581. break;
  6582. case 'FitH':
  6583. line += ' /FitH ' + anno.options.top + ']';
  6584. break;
  6585. case 'FitV':
  6586. anno.options.left = anno.options.left || 0;
  6587. line += ' /FitV ' + anno.options.left + ']';
  6588. break;
  6589. case 'XYZ':
  6590. default:
  6591. var top = getVerticalCoordinateString(anno.options.top);
  6592. anno.options.left = anno.options.left || 0; // 0 or null zoom will not change zoom factor
  6593. if (typeof anno.options.zoom === 'undefined') {
  6594. anno.options.zoom = 0;
  6595. }
  6596. line += ' /XYZ ' + anno.options.left + ' ' + top + ' ' + anno.options.zoom + ']';
  6597. break;
  6598. }
  6599. }
  6600. if (line != '') {
  6601. line += " >>";
  6602. this.internal.write(line);
  6603. }
  6604. break;
  6605. }
  6606. }
  6607. this.internal.write("]");
  6608. }]);
  6609. /**
  6610. * @name createAnnotation
  6611. * @function
  6612. * @param {Object} options
  6613. */
  6614. jsPDFAPI.createAnnotation = function (options) {
  6615. var pageInfo = this.internal.getCurrentPageInfo();
  6616. switch (options.type) {
  6617. case 'link':
  6618. this.link(options.bounds.x, options.bounds.y, options.bounds.w, options.bounds.h, options);
  6619. break;
  6620. case 'text':
  6621. case 'freetext':
  6622. pageInfo.pageContext.annotations.push(options);
  6623. break;
  6624. }
  6625. };
  6626. /**
  6627. * Create a link
  6628. *
  6629. * valid options
  6630. * <li> pageNumber or url [required]
  6631. * <p>If pageNumber is specified, top and zoom may also be specified</p>
  6632. * @name link
  6633. * @function
  6634. * @param {number} x
  6635. * @param {number} y
  6636. * @param {number} w
  6637. * @param {number} h
  6638. * @param {Object} options
  6639. */
  6640. jsPDFAPI.link = function (x, y, w, h, options) {
  6641. var pageInfo = this.internal.getCurrentPageInfo();
  6642. pageInfo.pageContext.annotations.push({
  6643. x: x,
  6644. y: y,
  6645. w: w,
  6646. h: h,
  6647. options: options,
  6648. type: 'link'
  6649. });
  6650. };
  6651. /**
  6652. * Currently only supports single line text.
  6653. * Returns the width of the text/link
  6654. *
  6655. * @name textWithLink
  6656. * @function
  6657. * @param {string} text
  6658. * @param {number} x
  6659. * @param {number} y
  6660. * @param {Object} options
  6661. * @returns {number} width the width of the text/link
  6662. */
  6663. jsPDFAPI.textWithLink = function (text, x, y, options) {
  6664. var width = this.getTextWidth(text);
  6665. var height = this.internal.getLineHeight() / this.internal.scaleFactor;
  6666. this.text(text, x, y); //TODO We really need the text baseline height to do this correctly.
  6667. // Or ability to draw text on top, bottom, center, or baseline.
  6668. y += height * .2;
  6669. this.link(x, y - height, width, height, options);
  6670. return width;
  6671. }; //TODO move into external library
  6672. /**
  6673. * @name getTextWidth
  6674. * @function
  6675. * @param {string} text
  6676. * @returns {number} txtWidth
  6677. */
  6678. jsPDFAPI.getTextWidth = function (text) {
  6679. var fontSize = this.internal.getFontSize();
  6680. var txtWidth = this.getStringUnitWidth(text) * fontSize / this.internal.scaleFactor;
  6681. return txtWidth;
  6682. };
  6683. return this;
  6684. })(jsPDF.API);
  6685. /**
  6686. * @license
  6687. * Copyright (c) 2017 Aras Abbasi
  6688. *
  6689. * Licensed under the MIT License.
  6690. * http://opensource.org/licenses/mit-license
  6691. */
  6692. /**
  6693. * jsPDF arabic parser PlugIn
  6694. *
  6695. * @name arabic
  6696. * @module
  6697. */
  6698. (function (jsPDFAPI) {
  6699. /**
  6700. * Arabic shape substitutions: char code => (isolated, final, initial, medial).
  6701. * Arabic Substition A
  6702. */
  6703. var arabicSubstitionA = {
  6704. 0x0621: [0xFE80],
  6705. // ARABIC LETTER HAMZA
  6706. 0x0622: [0xFE81, 0xFE82],
  6707. // ARABIC LETTER ALEF WITH MADDA ABOVE
  6708. 0x0623: [0xFE83, 0xFE84],
  6709. // ARABIC LETTER ALEF WITH HAMZA ABOVE
  6710. 0x0624: [0xFE85, 0xFE86],
  6711. // ARABIC LETTER WAW WITH HAMZA ABOVE
  6712. 0x0625: [0xFE87, 0xFE88],
  6713. // ARABIC LETTER ALEF WITH HAMZA BELOW
  6714. 0x0626: [0xFE89, 0xFE8A, 0xFE8B, 0xFE8C],
  6715. // ARABIC LETTER YEH WITH HAMZA ABOVE
  6716. 0x0627: [0xFE8D, 0xFE8E],
  6717. // ARABIC LETTER ALEF
  6718. 0x0628: [0xFE8F, 0xFE90, 0xFE91, 0xFE92],
  6719. // ARABIC LETTER BEH
  6720. 0x0629: [0xFE93, 0xFE94],
  6721. // ARABIC LETTER TEH MARBUTA
  6722. 0x062A: [0xFE95, 0xFE96, 0xFE97, 0xFE98],
  6723. // ARABIC LETTER TEH
  6724. 0x062B: [0xFE99, 0xFE9A, 0xFE9B, 0xFE9C],
  6725. // ARABIC LETTER THEH
  6726. 0x062C: [0xFE9D, 0xFE9E, 0xFE9F, 0xFEA0],
  6727. // ARABIC LETTER JEEM
  6728. 0x062D: [0xFEA1, 0xFEA2, 0xFEA3, 0xFEA4],
  6729. // ARABIC LETTER HAH
  6730. 0x062E: [0xFEA5, 0xFEA6, 0xFEA7, 0xFEA8],
  6731. // ARABIC LETTER KHAH
  6732. 0x062F: [0xFEA9, 0xFEAA],
  6733. // ARABIC LETTER DAL
  6734. 0x0630: [0xFEAB, 0xFEAC],
  6735. // ARABIC LETTER THAL
  6736. 0x0631: [0xFEAD, 0xFEAE],
  6737. // ARABIC LETTER REH
  6738. 0x0632: [0xFEAF, 0xFEB0],
  6739. // ARABIC LETTER ZAIN
  6740. 0x0633: [0xFEB1, 0xFEB2, 0xFEB3, 0xFEB4],
  6741. // ARABIC LETTER SEEN
  6742. 0x0634: [0xFEB5, 0xFEB6, 0xFEB7, 0xFEB8],
  6743. // ARABIC LETTER SHEEN
  6744. 0x0635: [0xFEB9, 0xFEBA, 0xFEBB, 0xFEBC],
  6745. // ARABIC LETTER SAD
  6746. 0x0636: [0xFEBD, 0xFEBE, 0xFEBF, 0xFEC0],
  6747. // ARABIC LETTER DAD
  6748. 0x0637: [0xFEC1, 0xFEC2, 0xFEC3, 0xFEC4],
  6749. // ARABIC LETTER TAH
  6750. 0x0638: [0xFEC5, 0xFEC6, 0xFEC7, 0xFEC8],
  6751. // ARABIC LETTER ZAH
  6752. 0x0639: [0xFEC9, 0xFECA, 0xFECB, 0xFECC],
  6753. // ARABIC LETTER AIN
  6754. 0x063A: [0xFECD, 0xFECE, 0xFECF, 0xFED0],
  6755. // ARABIC LETTER GHAIN
  6756. 0x0641: [0xFED1, 0xFED2, 0xFED3, 0xFED4],
  6757. // ARABIC LETTER FEH
  6758. 0x0642: [0xFED5, 0xFED6, 0xFED7, 0xFED8],
  6759. // ARABIC LETTER QAF
  6760. 0x0643: [0xFED9, 0xFEDA, 0xFEDB, 0xFEDC],
  6761. // ARABIC LETTER KAF
  6762. 0x0644: [0xFEDD, 0xFEDE, 0xFEDF, 0xFEE0],
  6763. // ARABIC LETTER LAM
  6764. 0x0645: [0xFEE1, 0xFEE2, 0xFEE3, 0xFEE4],
  6765. // ARABIC LETTER MEEM
  6766. 0x0646: [0xFEE5, 0xFEE6, 0xFEE7, 0xFEE8],
  6767. // ARABIC LETTER NOON
  6768. 0x0647: [0xFEE9, 0xFEEA, 0xFEEB, 0xFEEC],
  6769. // ARABIC LETTER HEH
  6770. 0x0648: [0xFEED, 0xFEEE],
  6771. // ARABIC LETTER WAW
  6772. 0x0649: [0xFEEF, 0xFEF0, 64488, 64489],
  6773. // ARABIC LETTER ALEF MAKSURA
  6774. 0x064A: [0xFEF1, 0xFEF2, 0xFEF3, 0xFEF4],
  6775. // ARABIC LETTER YEH
  6776. 0x0671: [0xFB50, 0xFB51],
  6777. // ARABIC LETTER ALEF WASLA
  6778. 0x0677: [0xFBDD],
  6779. // ARABIC LETTER U WITH HAMZA ABOVE
  6780. 0x0679: [0xFB66, 0xFB67, 0xFB68, 0xFB69],
  6781. // ARABIC LETTER TTEH
  6782. 0x067A: [0xFB5E, 0xFB5F, 0xFB60, 0xFB61],
  6783. // ARABIC LETTER TTEHEH
  6784. 0x067B: [0xFB52, 0xFB53, 0xFB54, 0xFB55],
  6785. // ARABIC LETTER BEEH
  6786. 0x067E: [0xFB56, 0xFB57, 0xFB58, 0xFB59],
  6787. // ARABIC LETTER PEH
  6788. 0x067F: [0xFB62, 0xFB63, 0xFB64, 0xFB65],
  6789. // ARABIC LETTER TEHEH
  6790. 0x0680: [0xFB5A, 0xFB5B, 0xFB5C, 0xFB5D],
  6791. // ARABIC LETTER BEHEH
  6792. 0x0683: [0xFB76, 0xFB77, 0xFB78, 0xFB79],
  6793. // ARABIC LETTER NYEH
  6794. 0x0684: [0xFB72, 0xFB73, 0xFB74, 0xFB75],
  6795. // ARABIC LETTER DYEH
  6796. 0x0686: [0xFB7A, 0xFB7B, 0xFB7C, 0xFB7D],
  6797. // ARABIC LETTER TCHEH
  6798. 0x0687: [0xFB7E, 0xFB7F, 0xFB80, 0xFB81],
  6799. // ARABIC LETTER TCHEHEH
  6800. 0x0688: [0xFB88, 0xFB89],
  6801. // ARABIC LETTER DDAL
  6802. 0x068C: [0xFB84, 0xFB85],
  6803. // ARABIC LETTER DAHAL
  6804. 0x068D: [0xFB82, 0xFB83],
  6805. // ARABIC LETTER DDAHAL
  6806. 0x068E: [0xFB86, 0xFB87],
  6807. // ARABIC LETTER DUL
  6808. 0x0691: [0xFB8C, 0xFB8D],
  6809. // ARABIC LETTER RREH
  6810. 0x0698: [0xFB8A, 0xFB8B],
  6811. // ARABIC LETTER JEH
  6812. 0x06A4: [0xFB6A, 0xFB6B, 0xFB6C, 0xFB6D],
  6813. // ARABIC LETTER VEH
  6814. 0x06A6: [0xFB6E, 0xFB6F, 0xFB70, 0xFB71],
  6815. // ARABIC LETTER PEHEH
  6816. 0x06A9: [0xFB8E, 0xFB8F, 0xFB90, 0xFB91],
  6817. // ARABIC LETTER KEHEH
  6818. 0x06AD: [0xFBD3, 0xFBD4, 0xFBD5, 0xFBD6],
  6819. // ARABIC LETTER NG
  6820. 0x06AF: [0xFB92, 0xFB93, 0xFB94, 0xFB95],
  6821. // ARABIC LETTER GAF
  6822. 0x06B1: [0xFB9A, 0xFB9B, 0xFB9C, 0xFB9D],
  6823. // ARABIC LETTER NGOEH
  6824. 0x06B3: [0xFB96, 0xFB97, 0xFB98, 0xFB99],
  6825. // ARABIC LETTER GUEH
  6826. 0x06BA: [0xFB9E, 0xFB9F],
  6827. // ARABIC LETTER NOON GHUNNA
  6828. 0x06BB: [0xFBA0, 0xFBA1, 0xFBA2, 0xFBA3],
  6829. // ARABIC LETTER RNOON
  6830. 0x06BE: [0xFBAA, 0xFBAB, 0xFBAC, 0xFBAD],
  6831. // ARABIC LETTER HEH DOACHASHMEE
  6832. 0x06C0: [0xFBA4, 0xFBA5],
  6833. // ARABIC LETTER HEH WITH YEH ABOVE
  6834. 0x06C1: [0xFBA6, 0xFBA7, 0xFBA8, 0xFBA9],
  6835. // ARABIC LETTER HEH GOAL
  6836. 0x06C5: [0xFBE0, 0xFBE1],
  6837. // ARABIC LETTER KIRGHIZ OE
  6838. 0x06C6: [0xFBD9, 0xFBDA],
  6839. // ARABIC LETTER OE
  6840. 0x06C7: [0xFBD7, 0xFBD8],
  6841. // ARABIC LETTER U
  6842. 0x06C8: [0xFBDB, 0xFBDC],
  6843. // ARABIC LETTER YU
  6844. 0x06C9: [0xFBE2, 0xFBE3],
  6845. // ARABIC LETTER KIRGHIZ YU
  6846. 0x06CB: [0xFBDE, 0xFBDF],
  6847. // ARABIC LETTER VE
  6848. 0x06CC: [0xFBFC, 0xFBFD, 0xFBFE, 0xFBFF],
  6849. // ARABIC LETTER FARSI YEH
  6850. 0x06D0: [0xFBE4, 0xFBE5, 0xFBE6, 0xFBE7],
  6851. //ARABIC LETTER E
  6852. 0x06D2: [0xFBAE, 0xFBAF],
  6853. // ARABIC LETTER YEH BARREE
  6854. 0x06D3: [0xFBB0, 0xFBB1] // ARABIC LETTER YEH BARREE WITH HAMZA ABOVE
  6855. };
  6856. var ligatures = {
  6857. 0xFEDF: {
  6858. 0xFE82: 0xFEF5,
  6859. // ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE ISOLATED FORM
  6860. 0xFE84: 0xFEF7,
  6861. // ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE ISOLATED FORM
  6862. 0xFE88: 0xFEF9,
  6863. // ARABIC LIGATURE LAM WITH ALEF WITH HAMZA BELOW ISOLATED FORM
  6864. 0xFE8E: 0xFEFB // ARABIC LIGATURE LAM WITH ALEF ISOLATED FORM
  6865. },
  6866. 0xFEE0: {
  6867. 0xFE82: 0xFEF6,
  6868. // ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE FINAL FORM
  6869. 0xFE84: 0xFEF8,
  6870. // ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE FINAL FORM
  6871. 0xFE88: 0xFEFA,
  6872. // ARABIC LIGATURE LAM WITH ALEF WITH HAMZA BELOW FINAL FORM
  6873. 0xFE8E: 0xFEFC // ARABIC LIGATURE LAM WITH ALEF FINAL FORM
  6874. },
  6875. 0xFE8D: {
  6876. 0xFEDF: {
  6877. 0xFEE0: {
  6878. 0xFEEA: 0xFDF2
  6879. }
  6880. }
  6881. },
  6882. // ALLAH
  6883. 0x0651: {
  6884. 0x064C: 0xFC5E,
  6885. // Shadda + Dammatan
  6886. 0x064D: 0xFC5F,
  6887. // Shadda + Kasratan
  6888. 0x064E: 0xFC60,
  6889. // Shadda + Fatha
  6890. 0x064F: 0xFC61,
  6891. // Shadda + Damma
  6892. 0x0650: 0xFC62 // Shadda + Kasra
  6893. }
  6894. };
  6895. var arabic_diacritics = {
  6896. 1612: 64606,
  6897. // Shadda + Dammatan
  6898. 1613: 64607,
  6899. // Shadda + Kasratan
  6900. 1614: 64608,
  6901. // Shadda + Fatha
  6902. 1615: 64609,
  6903. // Shadda + Damma
  6904. 1616: 64610 // Shadda + Kasra
  6905. };
  6906. var alfletter = [1570, 1571, 1573, 1575];
  6907. var noChangeInForm = -1;
  6908. var isolatedForm = 0;
  6909. var finalForm = 1;
  6910. var initialForm = 2;
  6911. var medialForm = 3;
  6912. jsPDFAPI.__arabicParser__ = {}; //private
  6913. var isInArabicSubstitutionA = jsPDFAPI.__arabicParser__.isInArabicSubstitutionA = function (letter) {
  6914. return typeof arabicSubstitionA[letter.charCodeAt(0)] !== "undefined";
  6915. };
  6916. var isArabicLetter = jsPDFAPI.__arabicParser__.isArabicLetter = function (letter) {
  6917. return typeof letter === "string" && /^[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]+$/.test(letter);
  6918. };
  6919. var isArabicEndLetter = jsPDFAPI.__arabicParser__.isArabicEndLetter = function (letter) {
  6920. return isArabicLetter(letter) && isInArabicSubstitutionA(letter) && arabicSubstitionA[letter.charCodeAt(0)].length <= 2;
  6921. };
  6922. var isArabicAlfLetter = jsPDFAPI.__arabicParser__.isArabicAlfLetter = function (letter) {
  6923. return isArabicLetter(letter) && alfletter.indexOf(letter.charCodeAt(0)) >= 0;
  6924. };
  6925. var arabicLetterHasIsolatedForm = jsPDFAPI.__arabicParser__.arabicLetterHasIsolatedForm = function (letter) {
  6926. return isArabicLetter(letter) && isInArabicSubstitutionA(letter) && arabicSubstitionA[letter.charCodeAt(0)].length >= 1;
  6927. };
  6928. var arabicLetterHasFinalForm = jsPDFAPI.__arabicParser__.arabicLetterHasFinalForm = function (letter) {
  6929. return isArabicLetter(letter) && isInArabicSubstitutionA(letter) && arabicSubstitionA[letter.charCodeAt(0)].length >= 2;
  6930. };
  6931. var arabicLetterHasInitialForm = jsPDFAPI.__arabicParser__.arabicLetterHasInitialForm = function (letter) {
  6932. return isArabicLetter(letter) && isInArabicSubstitutionA(letter) && arabicSubstitionA[letter.charCodeAt(0)].length >= 3;
  6933. };
  6934. var arabicLetterHasMedialForm = jsPDFAPI.__arabicParser__.arabicLetterHasMedialForm = function (letter) {
  6935. return isArabicLetter(letter) && isInArabicSubstitutionA(letter) && arabicSubstitionA[letter.charCodeAt(0)].length == 4;
  6936. };
  6937. var resolveLigatures = jsPDFAPI.__arabicParser__.resolveLigatures = function (letters) {
  6938. var i = 0;
  6939. var tmpLigatures = ligatures;
  6940. var position = isolatedForm;
  6941. var result = '';
  6942. var effectedLetters = 0;
  6943. for (i = 0; i < letters.length; i += 1) {
  6944. if (typeof tmpLigatures[letters.charCodeAt(i)] !== "undefined") {
  6945. effectedLetters++;
  6946. tmpLigatures = tmpLigatures[letters.charCodeAt(i)];
  6947. if (typeof tmpLigatures === "number") {
  6948. position = getCorrectForm(letters.charAt(i), letters.charAt(i - effectedLetters), letters.charAt(i + 1));
  6949. position = position !== -1 ? position : 0;
  6950. result += String.fromCharCode(tmpLigatures);
  6951. tmpLigatures = ligatures;
  6952. effectedLetters = 0;
  6953. }
  6954. if (i === letters.length - 1) {
  6955. tmpLigatures = ligatures;
  6956. result += letters.charAt(i - (effectedLetters - 1));
  6957. i = i - (effectedLetters - 1);
  6958. effectedLetters = 0;
  6959. }
  6960. } else {
  6961. tmpLigatures = ligatures;
  6962. result += letters.charAt(i - effectedLetters);
  6963. i = i - effectedLetters;
  6964. effectedLetters = 0;
  6965. }
  6966. }
  6967. return result;
  6968. };
  6969. var isArabicDiacritic = jsPDFAPI.__arabicParser__.isArabicDiacritic = function (letter) {
  6970. return letter !== undefined && arabic_diacritics[letter.charCodeAt(0)] !== undefined;
  6971. };
  6972. var getCorrectForm = jsPDFAPI.__arabicParser__.getCorrectForm = function (currentChar, beforeChar, nextChar) {
  6973. if (!isArabicLetter(currentChar)) {
  6974. return -1;
  6975. }
  6976. if (isInArabicSubstitutionA(currentChar) === false) {
  6977. return noChangeInForm;
  6978. }
  6979. if (!arabicLetterHasFinalForm(currentChar) || !isArabicLetter(beforeChar) && !isArabicLetter(nextChar) || !isArabicLetter(nextChar) && isArabicEndLetter(beforeChar) || isArabicEndLetter(currentChar) && !isArabicLetter(beforeChar) || isArabicEndLetter(currentChar) && isArabicAlfLetter(beforeChar) || isArabicEndLetter(currentChar) && isArabicEndLetter(beforeChar)) {
  6980. return isolatedForm;
  6981. }
  6982. if (arabicLetterHasMedialForm(currentChar) && isArabicLetter(beforeChar) && !isArabicEndLetter(beforeChar) && isArabicLetter(nextChar) && arabicLetterHasFinalForm(nextChar)) {
  6983. return medialForm;
  6984. }
  6985. if (isArabicEndLetter(currentChar) || !isArabicLetter(nextChar)) {
  6986. return finalForm;
  6987. }
  6988. return initialForm;
  6989. };
  6990. /**
  6991. * @name processArabic
  6992. * @function
  6993. * @param {string} text
  6994. * @param {boolean} reverse
  6995. * @returns {string}
  6996. */
  6997. var processArabic = jsPDFAPI.__arabicParser__.processArabic = jsPDFAPI.processArabic = function (text) {
  6998. text = text || "";
  6999. var result = "";
  7000. var i = 0;
  7001. var j = 0;
  7002. var position = 0;
  7003. var currentLetter = "";
  7004. var prevLetter = "";
  7005. var nextLetter = "";
  7006. var words = text.split("\\s+");
  7007. var newWords = [];
  7008. for (i = 0; i < words.length; i += 1) {
  7009. newWords.push('');
  7010. for (j = 0; j < words[i].length; j += 1) {
  7011. currentLetter = words[i][j];
  7012. prevLetter = words[i][j - 1];
  7013. nextLetter = words[i][j + 1];
  7014. if (isArabicLetter(currentLetter)) {
  7015. position = getCorrectForm(currentLetter, prevLetter, nextLetter);
  7016. if (position !== -1) {
  7017. newWords[i] += String.fromCharCode(arabicSubstitionA[currentLetter.charCodeAt(0)][position]);
  7018. } else {
  7019. newWords[i] += currentLetter;
  7020. }
  7021. } else {
  7022. newWords[i] += currentLetter;
  7023. }
  7024. }
  7025. newWords[i] = resolveLigatures(newWords[i]);
  7026. }
  7027. result = newWords.join(' ');
  7028. return result;
  7029. };
  7030. var arabicParserFunction = function arabicParserFunction(args) {
  7031. var text = args.text;
  7032. var x = args.x;
  7033. var y = args.y;
  7034. var options = args.options || {};
  7035. var mutex = args.mutex || {};
  7036. var lang = options.lang;
  7037. var tmpText = [];
  7038. if (Object.prototype.toString.call(text) === '[object Array]') {
  7039. var i = 0;
  7040. tmpText = [];
  7041. for (i = 0; i < text.length; i += 1) {
  7042. if (Object.prototype.toString.call(text[i]) === '[object Array]') {
  7043. tmpText.push([processArabic(text[i][0]), text[i][1], text[i][2]]);
  7044. } else {
  7045. tmpText.push([processArabic(text[i])]);
  7046. }
  7047. }
  7048. args.text = tmpText;
  7049. } else {
  7050. args.text = processArabic(text);
  7051. }
  7052. };
  7053. jsPDFAPI.events.push(['preProcessText', arabicParserFunction]);
  7054. })(jsPDF.API);
  7055. /** @license
  7056. * jsPDF Autoprint Plugin
  7057. *
  7058. * Licensed under the MIT License.
  7059. * http://opensource.org/licenses/mit-license
  7060. */
  7061. /**
  7062. * @name autoprint
  7063. * @module
  7064. */
  7065. (function (jsPDFAPI) {
  7066. /**
  7067. * Makes the PDF automatically print. This works in Chrome, Firefox, Acrobat
  7068. * Reader.
  7069. *
  7070. * @name autoPrint
  7071. * @function
  7072. * @param {Object} options (optional) Set the attribute variant to 'non-conform' (default) or 'javascript' to activate different methods of automatic printing when opening in a PDF-viewer .
  7073. * @returns {jsPDF}
  7074. * @example
  7075. * var doc = new jsPDF();
  7076. * doc.text(10, 10, 'This is a test');
  7077. * doc.autoPrint({variant: 'non-conform'});
  7078. * doc.save('autoprint.pdf');
  7079. */
  7080. jsPDFAPI.autoPrint = function (options) {
  7081. var refAutoPrintTag;
  7082. options = options || {};
  7083. options.variant = options.variant || 'non-conform';
  7084. switch (options.variant) {
  7085. case 'javascript':
  7086. //https://github.com/Rob--W/pdf.js/commit/c676ecb5a0f54677b9f3340c3ef2cf42225453bb
  7087. this.addJS('print({});');
  7088. break;
  7089. case 'non-conform':
  7090. default:
  7091. this.internal.events.subscribe('postPutResources', function () {
  7092. refAutoPrintTag = this.internal.newObject();
  7093. this.internal.out("<<");
  7094. this.internal.out("/S /Named");
  7095. this.internal.out("/Type /Action");
  7096. this.internal.out("/N /Print");
  7097. this.internal.out(">>");
  7098. this.internal.out("endobj");
  7099. });
  7100. this.internal.events.subscribe("putCatalog", function () {
  7101. this.internal.out("/OpenAction " + refAutoPrintTag + " 0 R");
  7102. });
  7103. break;
  7104. }
  7105. return this;
  7106. };
  7107. })(jsPDF.API);
  7108. /**
  7109. * @license
  7110. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  7111. *
  7112. * Licensed under the MIT License.
  7113. * http://opensource.org/licenses/mit-license
  7114. */
  7115. /**
  7116. * jsPDF Canvas PlugIn
  7117. * This plugin mimics the HTML5 Canvas
  7118. *
  7119. * The goal is to provide a way for current canvas users to print directly to a PDF.
  7120. * @name canvas
  7121. * @module
  7122. */
  7123. (function (jsPDFAPI) {
  7124. /**
  7125. * @class Canvas
  7126. * @classdesc A Canvas Wrapper for jsPDF
  7127. */
  7128. var Canvas = function Canvas() {
  7129. var jsPdfInstance = undefined;
  7130. Object.defineProperty(this, 'pdf', {
  7131. get: function get() {
  7132. return jsPdfInstance;
  7133. },
  7134. set: function set(value) {
  7135. jsPdfInstance = value;
  7136. }
  7137. });
  7138. var _width = 150;
  7139. /**
  7140. * The height property is a positive integer reflecting the height HTML attribute of the <canvas> element interpreted in CSS pixels. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of 150 is used.
  7141. * This is one of the two properties, the other being width, that controls the size of the canvas.
  7142. *
  7143. * @name width
  7144. */
  7145. Object.defineProperty(this, 'width', {
  7146. get: function get() {
  7147. return _width;
  7148. },
  7149. set: function set(value) {
  7150. if (isNaN(value) || Number.isInteger(value) === false || value < 0) {
  7151. _width = 150;
  7152. } else {
  7153. _width = value;
  7154. }
  7155. if (this.getContext('2d').pageWrapXEnabled) {
  7156. this.getContext('2d').pageWrapX = _width + 1;
  7157. }
  7158. }
  7159. });
  7160. var _height = 300;
  7161. /**
  7162. * The width property is a positive integer reflecting the width HTML attribute of the <canvas> element interpreted in CSS pixels. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of 300 is used.
  7163. * This is one of the two properties, the other being height, that controls the size of the canvas.
  7164. *
  7165. * @name height
  7166. */
  7167. Object.defineProperty(this, 'height', {
  7168. get: function get() {
  7169. return _height;
  7170. },
  7171. set: function set(value) {
  7172. if (isNaN(value) || Number.isInteger(value) === false || value < 0) {
  7173. _height = 300;
  7174. } else {
  7175. _height = value;
  7176. }
  7177. if (this.getContext('2d').pageWrapYEnabled) {
  7178. this.getContext('2d').pageWrapY = _height + 1;
  7179. }
  7180. }
  7181. });
  7182. var _childNodes = [];
  7183. Object.defineProperty(this, 'childNodes', {
  7184. get: function get() {
  7185. return _childNodes;
  7186. },
  7187. set: function set(value) {
  7188. _childNodes = value;
  7189. }
  7190. });
  7191. var _style = {};
  7192. Object.defineProperty(this, 'style', {
  7193. get: function get() {
  7194. return _style;
  7195. },
  7196. set: function set(value) {
  7197. _style = value;
  7198. }
  7199. });
  7200. Object.defineProperty(this, 'parentNode', {
  7201. get: function get() {
  7202. return false;
  7203. }
  7204. });
  7205. };
  7206. /**
  7207. * The getContext() method returns a drawing context on the canvas, or null if the context identifier is not supported.
  7208. *
  7209. * @name getContext
  7210. * @function
  7211. * @param {string} contextType Is a String containing the context identifier defining the drawing context associated to the canvas. Possible value is "2d", leading to the creation of a Context2D object representing a two-dimensional rendering context.
  7212. * @param {object} contextAttributes
  7213. */
  7214. Canvas.prototype.getContext = function (contextType, contextAttributes) {
  7215. contextType = contextType || '2d';
  7216. var key;
  7217. if (contextType !== '2d') {
  7218. return null;
  7219. }
  7220. for (key in contextAttributes) {
  7221. if (this.pdf.context2d.hasOwnProperty(key)) {
  7222. this.pdf.context2d[key] = contextAttributes[key];
  7223. }
  7224. }
  7225. this.pdf.context2d._canvas = this;
  7226. return this.pdf.context2d;
  7227. };
  7228. /**
  7229. * The toDataURL() method is just a stub to throw an error if accidently called.
  7230. *
  7231. * @name toDataURL
  7232. * @function
  7233. */
  7234. Canvas.prototype.toDataURL = function () {
  7235. throw new Error('toDataURL is not implemented.');
  7236. };
  7237. jsPDFAPI.events.push(['initialized', function () {
  7238. this.canvas = new Canvas();
  7239. this.canvas.pdf = this;
  7240. }]);
  7241. return this;
  7242. })(jsPDF.API);
  7243. /**
  7244. * @license
  7245. * ====================================================================
  7246. * Copyright (c) 2013 Youssef Beddad, youssef.beddad@gmail.com
  7247. * 2013 Eduardo Menezes de Morais, eduardo.morais@usp.br
  7248. * 2013 Lee Driscoll, https://github.com/lsdriscoll
  7249. * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
  7250. * 2014 James Hall, james@parall.ax
  7251. * 2014 Diego Casorran, https://github.com/diegocr
  7252. *
  7253. *
  7254. * ====================================================================
  7255. */
  7256. /**
  7257. * @name cell
  7258. * @module
  7259. */
  7260. (function (jsPDFAPI) {
  7261. /*jslint browser:true */
  7262. /*global document: false, jsPDF */
  7263. var padding = 3,
  7264. margin = 13,
  7265. headerFunction,
  7266. lastCellPos = {
  7267. x: undefined,
  7268. y: undefined,
  7269. w: undefined,
  7270. h: undefined,
  7271. ln: undefined
  7272. },
  7273. pages = 1,
  7274. setLastCellPosition = function setLastCellPosition(x, y, w, h, ln) {
  7275. lastCellPos = {
  7276. 'x': x,
  7277. 'y': y,
  7278. 'w': w,
  7279. 'h': h,
  7280. 'ln': ln
  7281. };
  7282. },
  7283. getLastCellPosition = function getLastCellPosition() {
  7284. return lastCellPos;
  7285. },
  7286. NO_MARGINS = {
  7287. left: 0,
  7288. top: 0,
  7289. bottom: 0
  7290. };
  7291. /**
  7292. * @name setHeaderFunction
  7293. * @function
  7294. * @param {function} func
  7295. */
  7296. jsPDFAPI.setHeaderFunction = function (func) {
  7297. headerFunction = func;
  7298. };
  7299. /**
  7300. * @name getTextDimensions
  7301. * @function
  7302. * @param {string} txt
  7303. * @returns {Object} dimensions
  7304. */
  7305. jsPDFAPI.getTextDimensions = function (text, options) {
  7306. var fontSize = this.table_font_size || this.internal.getFontSize();
  7307. var fontStyle = this.internal.getFont().fontStyle;
  7308. options = options || {};
  7309. var scaleFactor = options.scaleFactor || this.internal.scaleFactor;
  7310. var width = 0;
  7311. var amountOfLines = 0;
  7312. var height = 0;
  7313. var tempWidth = 0;
  7314. if (typeof text === 'string') {
  7315. width = this.getStringUnitWidth(text) * fontSize;
  7316. if (width !== 0) {
  7317. amountOfLines = 1;
  7318. }
  7319. } else if (Object.prototype.toString.call(text) === '[object Array]') {
  7320. for (var i = 0; i < text.length; i++) {
  7321. tempWidth = this.getStringUnitWidth(text[i]) * fontSize;
  7322. if (width < tempWidth) {
  7323. width = tempWidth;
  7324. }
  7325. }
  7326. if (width !== 0) {
  7327. amountOfLines = text.length;
  7328. }
  7329. } else {
  7330. throw new Error('getTextDimensions expects text-parameter to be of type String or an Array of Strings.');
  7331. }
  7332. width = width / scaleFactor;
  7333. height = Math.max((amountOfLines * fontSize * this.getLineHeightFactor() - fontSize * (this.getLineHeightFactor() - 1)) / scaleFactor, 0);
  7334. return {
  7335. w: width,
  7336. h: height
  7337. };
  7338. };
  7339. /**
  7340. * @name cellAddPage
  7341. * @function
  7342. */
  7343. jsPDFAPI.cellAddPage = function () {
  7344. var margins = this.margins || NO_MARGINS;
  7345. this.addPage();
  7346. setLastCellPosition(margins.left, margins.top, undefined, undefined); //setLastCellPosition(undefined, undefined, undefined, undefined, undefined);
  7347. pages += 1;
  7348. };
  7349. /**
  7350. * @name cellInitialize
  7351. * @function
  7352. */
  7353. jsPDFAPI.cellInitialize = function () {
  7354. lastCellPos = {
  7355. x: undefined,
  7356. y: undefined,
  7357. w: undefined,
  7358. h: undefined,
  7359. ln: undefined
  7360. };
  7361. pages = 1;
  7362. };
  7363. /**
  7364. * @name cell
  7365. * @function
  7366. * @param {number} x
  7367. * @param {number} y
  7368. * @param {number} w
  7369. * @param {number} h
  7370. * @param {string} txt
  7371. * @param {number} ln lineNumber
  7372. * @param {string} align
  7373. * @return {jsPDF} jsPDF-instance
  7374. */
  7375. jsPDFAPI.cell = function (x, y, w, h, txt, ln, align) {
  7376. var curCell = getLastCellPosition();
  7377. var pgAdded = false; // If this is not the first cell, we must change its position
  7378. if (curCell.ln !== undefined) {
  7379. if (curCell.ln === ln) {
  7380. //Same line
  7381. x = curCell.x + curCell.w;
  7382. y = curCell.y;
  7383. } else {
  7384. //New line
  7385. var margins = this.margins || NO_MARGINS;
  7386. if (curCell.y + curCell.h + h + margin >= this.internal.pageSize.getHeight() - margins.bottom) {
  7387. this.cellAddPage();
  7388. pgAdded = true;
  7389. if (this.printHeaders && this.tableHeaderRow) {
  7390. this.printHeaderRow(ln, true);
  7391. }
  7392. } //We ignore the passed y: the lines may have different heights
  7393. y = getLastCellPosition().y + getLastCellPosition().h;
  7394. if (pgAdded) y = margin + 10;
  7395. }
  7396. }
  7397. if (txt[0] !== undefined) {
  7398. if (this.printingHeaderRow) {
  7399. this.rect(x, y, w, h, 'FD');
  7400. } else {
  7401. this.rect(x, y, w, h);
  7402. }
  7403. if (align === 'right') {
  7404. if (!(txt instanceof Array)) {
  7405. txt = [txt];
  7406. }
  7407. for (var i = 0; i < txt.length; i++) {
  7408. var currentLine = txt[i];
  7409. var textSize = this.getStringUnitWidth(currentLine) * this.internal.getFontSize() / this.internal.scaleFactor;
  7410. this.text(currentLine, x + w - textSize - padding, y + this.internal.getLineHeight() * (i + 1));
  7411. }
  7412. } else {
  7413. this.text(txt, x + padding, y + this.internal.getLineHeight());
  7414. }
  7415. }
  7416. setLastCellPosition(x, y, w, h, ln);
  7417. return this;
  7418. };
  7419. /**
  7420. * Return the maximum value from an array
  7421. *
  7422. * @name arrayMax
  7423. * @function
  7424. * @param {Array} array
  7425. * @param comparisonFn
  7426. * @returns {number}
  7427. */
  7428. jsPDFAPI.arrayMax = function (array, comparisonFn) {
  7429. var max = array[0],
  7430. i,
  7431. ln,
  7432. item;
  7433. for (i = 0, ln = array.length; i < ln; i += 1) {
  7434. item = array[i];
  7435. if (comparisonFn) {
  7436. if (comparisonFn(max, item) === -1) {
  7437. max = item;
  7438. }
  7439. } else {
  7440. if (item > max) {
  7441. max = item;
  7442. }
  7443. }
  7444. }
  7445. return max;
  7446. };
  7447. /**
  7448. * Create a table from a set of data.
  7449. * @name table
  7450. * @function
  7451. * @param {Integer} [x] : left-position for top-left corner of table
  7452. * @param {Integer} [y] top-position for top-left corner of table
  7453. * @param {Object[]} [data] As array of objects containing key-value pairs corresponding to a row of data.
  7454. * @param {String[]} [headers] Omit or null to auto-generate headers at a performance cost
  7455. * @param {Object} [config.printHeaders] True to print column headers at the top of every page
  7456. * @param {Object} [config.autoSize] True to dynamically set the column widths to match the widest cell value
  7457. * @param {Object} [config.margins] margin values for left, top, bottom, and width
  7458. * @param {Object} [config.fontSize] Integer fontSize to use (optional)
  7459. * @returns {jsPDF} jsPDF-instance
  7460. */
  7461. jsPDFAPI.table = function (x, y, data, headers, config) {
  7462. if (!data) {
  7463. throw 'No data for PDF table';
  7464. }
  7465. var headerNames = [],
  7466. headerPrompts = [],
  7467. header,
  7468. i,
  7469. ln,
  7470. cln,
  7471. columnMatrix = {},
  7472. columnWidths = {},
  7473. columnData,
  7474. column,
  7475. columnMinWidths = [],
  7476. j,
  7477. tableHeaderConfigs = [],
  7478. model,
  7479. jln,
  7480. func,
  7481. //set up defaults. If a value is provided in config, defaults will be overwritten:
  7482. autoSize = false,
  7483. printHeaders = true,
  7484. fontSize = 12,
  7485. margins = NO_MARGINS;
  7486. margins.width = this.internal.pageSize.getWidth();
  7487. if (config) {
  7488. //override config defaults if the user has specified non-default behavior:
  7489. if (config.autoSize === true) {
  7490. autoSize = true;
  7491. }
  7492. if (config.printHeaders === false) {
  7493. printHeaders = false;
  7494. }
  7495. if (config.fontSize) {
  7496. fontSize = config.fontSize;
  7497. }
  7498. if (config.css && typeof config.css['font-size'] !== "undefined") {
  7499. fontSize = config.css['font-size'] * 16;
  7500. }
  7501. if (config.margins) {
  7502. margins = config.margins;
  7503. }
  7504. }
  7505. /**
  7506. * @property {Number} lnMod
  7507. * Keep track of the current line number modifier used when creating cells
  7508. */
  7509. this.lnMod = 0;
  7510. lastCellPos = {
  7511. x: undefined,
  7512. y: undefined,
  7513. w: undefined,
  7514. h: undefined,
  7515. ln: undefined
  7516. }, pages = 1;
  7517. this.printHeaders = printHeaders;
  7518. this.margins = margins;
  7519. this.setFontSize(fontSize);
  7520. this.table_font_size = fontSize; // Set header values
  7521. if (headers === undefined || headers === null) {
  7522. // No headers defined so we derive from data
  7523. headerNames = Object.keys(data[0]);
  7524. } else if (headers[0] && typeof headers[0] !== 'string') {
  7525. var px2pt = 0.264583 * 72 / 25.4; // Split header configs into names and prompts
  7526. for (i = 0, ln = headers.length; i < ln; i += 1) {
  7527. header = headers[i];
  7528. headerNames.push(header.name);
  7529. headerPrompts.push(header.prompt);
  7530. columnWidths[header.name] = header.width * px2pt;
  7531. }
  7532. } else {
  7533. headerNames = headers;
  7534. }
  7535. if (autoSize) {
  7536. // Create a matrix of columns e.g., {column_title: [row1_Record, row2_Record]}
  7537. func = function func(rec) {
  7538. return rec[header];
  7539. };
  7540. for (i = 0, ln = headerNames.length; i < ln; i += 1) {
  7541. header = headerNames[i];
  7542. columnMatrix[header] = data.map(func); // get header width
  7543. columnMinWidths.push(this.getTextDimensions(headerPrompts[i] || header, {
  7544. scaleFactor: 1
  7545. }).w);
  7546. column = columnMatrix[header]; // get cell widths
  7547. for (j = 0, cln = column.length; j < cln; j += 1) {
  7548. columnData = column[j];
  7549. columnMinWidths.push(this.getTextDimensions(columnData, {
  7550. scaleFactor: 1
  7551. }).w);
  7552. } // get final column width
  7553. columnWidths[header] = jsPDFAPI.arrayMax(columnMinWidths); //have to reset
  7554. columnMinWidths = [];
  7555. }
  7556. } // -- Construct the table
  7557. if (printHeaders) {
  7558. var lineHeight = this.calculateLineHeight(headerNames, columnWidths, headerPrompts.length ? headerPrompts : headerNames); // Construct the header row
  7559. for (i = 0, ln = headerNames.length; i < ln; i += 1) {
  7560. header = headerNames[i];
  7561. tableHeaderConfigs.push([x, y, columnWidths[header], lineHeight, String(headerPrompts.length ? headerPrompts[i] : header)]);
  7562. } // Store the table header config
  7563. this.setTableHeaderRow(tableHeaderConfigs); // Print the header for the start of the table
  7564. this.printHeaderRow(1, false);
  7565. } // Construct the data rows
  7566. for (i = 0, ln = data.length; i < ln; i += 1) {
  7567. var lineHeight;
  7568. model = data[i];
  7569. lineHeight = this.calculateLineHeight(headerNames, columnWidths, model);
  7570. for (j = 0, jln = headerNames.length; j < jln; j += 1) {
  7571. header = headerNames[j];
  7572. this.cell(x, y, columnWidths[header], lineHeight, model[header], i + 2, header.align);
  7573. }
  7574. }
  7575. this.lastCellPos = lastCellPos;
  7576. this.table_x = x;
  7577. this.table_y = y;
  7578. return this;
  7579. };
  7580. /**
  7581. * Calculate the height for containing the highest column
  7582. *
  7583. * @name calculateLineHeight
  7584. * @function
  7585. * @param {String[]} headerNames is the header, used as keys to the data
  7586. * @param {Integer[]} columnWidths is size of each column
  7587. * @param {Object[]} model is the line of data we want to calculate the height of
  7588. * @returns {number} lineHeight
  7589. */
  7590. jsPDFAPI.calculateLineHeight = function (headerNames, columnWidths, model) {
  7591. var header,
  7592. lineHeight = 0;
  7593. for (var j = 0; j < headerNames.length; j++) {
  7594. header = headerNames[j];
  7595. model[header] = this.splitTextToSize(String(model[header]), columnWidths[header] - padding);
  7596. var h = this.internal.getLineHeight() * model[header].length + padding;
  7597. if (h > lineHeight) lineHeight = h;
  7598. }
  7599. return lineHeight;
  7600. };
  7601. /**
  7602. * Store the config for outputting a table header
  7603. *
  7604. * @name setTableHeaderRow
  7605. * @function
  7606. * @param {Object[]} config
  7607. * An array of cell configs that would define a header row: Each config matches the config used by jsPDFAPI.cell
  7608. * except the ln parameter is excluded
  7609. */
  7610. jsPDFAPI.setTableHeaderRow = function (config) {
  7611. this.tableHeaderRow = config;
  7612. };
  7613. /**
  7614. * Output the store header row
  7615. *
  7616. * @name printHeaderRow
  7617. * @function
  7618. * @param {number} lineNumber The line number to output the header at
  7619. * @param {boolean} new_page
  7620. */
  7621. jsPDFAPI.printHeaderRow = function (lineNumber, new_page) {
  7622. if (!this.tableHeaderRow) {
  7623. throw 'Property tableHeaderRow does not exist.';
  7624. }
  7625. var tableHeaderCell, tmpArray, i, ln;
  7626. this.printingHeaderRow = true;
  7627. if (headerFunction !== undefined) {
  7628. var position = headerFunction(this, pages);
  7629. setLastCellPosition(position[0], position[1], position[2], position[3], -1);
  7630. }
  7631. this.setFontStyle('bold');
  7632. var tempHeaderConf = [];
  7633. for (i = 0, ln = this.tableHeaderRow.length; i < ln; i += 1) {
  7634. this.setFillColor(200, 200, 200);
  7635. tableHeaderCell = this.tableHeaderRow[i];
  7636. if (new_page) {
  7637. this.margins.top = margin;
  7638. tableHeaderCell[1] = this.margins && this.margins.top || 0;
  7639. tempHeaderConf.push(tableHeaderCell);
  7640. }
  7641. tmpArray = [].concat(tableHeaderCell);
  7642. this.cell.apply(this, tmpArray.concat(lineNumber));
  7643. }
  7644. if (tempHeaderConf.length > 0) {
  7645. this.setTableHeaderRow(tempHeaderConf);
  7646. }
  7647. this.setFontStyle('normal');
  7648. this.printingHeaderRow = false;
  7649. };
  7650. })(jsPDF.API);
  7651. /**
  7652. * jsPDF Context2D PlugIn Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  7653. *
  7654. * Licensed under the MIT License. http://opensource.org/licenses/mit-license
  7655. */
  7656. /**
  7657. * This plugin mimics the HTML5 CanvasRenderingContext2D.
  7658. *
  7659. * The goal is to provide a way for current canvas implementations to print directly to a PDF.
  7660. *
  7661. * @name context2d
  7662. * @module
  7663. */
  7664. (function (jsPDFAPI, globalObj) {
  7665. var ContextLayer = function ContextLayer(ctx) {
  7666. ctx = ctx || {};
  7667. this.isStrokeTransparent = ctx.isStrokeTransparent || false;
  7668. this.strokeOpacity = ctx.strokeOpacity || 1;
  7669. this.strokeStyle = ctx.strokeStyle || '#000000';
  7670. this.fillStyle = ctx.fillStyle || '#000000';
  7671. this.isFillTransparent = ctx.isFillTransparent || false;
  7672. this.fillOpacity = ctx.fillOpacity || 1;
  7673. this.font = ctx.font || '10px sans-serif';
  7674. this.textBaseline = ctx.textBaseline || 'alphabetic';
  7675. this.textAlign = ctx.textAlign || 'left';
  7676. this.lineWidth = ctx.lineWidth || 1;
  7677. this.lineJoin = ctx.lineJoin || 'miter';
  7678. this.lineCap = ctx.lineCap || 'butt';
  7679. this.path = ctx.path || [];
  7680. this.transform = typeof ctx.transform !== 'undefined' ? ctx.transform.clone() : new Matrix();
  7681. this.globalCompositeOperation = ctx.globalCompositeOperation || 'normal';
  7682. this.globalAlpha = ctx.globalAlpha || 1.0;
  7683. this.clip_path = ctx.clip_path || [];
  7684. this.currentPoint = ctx.currentPoint || new Point();
  7685. this.miterLimit = ctx.miterLimit || 10.0;
  7686. this.lastPoint = ctx.lastPoint || new Point();
  7687. this.ignoreClearRect = typeof ctx.ignoreClearRect === "boolean" ? ctx.ignoreClearRect : true;
  7688. return this;
  7689. }; //stub
  7690. var f2, f3, getHorizontalCoordinateString, getVerticalCoordinateString, getHorizontalCoordinate, getVerticalCoordinate;
  7691. jsPDFAPI.events.push(['initialized', function () {
  7692. this.context2d = new Context2D(this);
  7693. f2 = this.internal.f2;
  7694. f3 = this.internal.f3;
  7695. getHorizontalCoordinateString = this.internal.getCoordinateString;
  7696. getVerticalCoordinateString = this.internal.getVerticalCoordinateString;
  7697. getHorizontalCoordinate = this.internal.getHorizontalCoordinate;
  7698. getVerticalCoordinate = this.internal.getVerticalCoordinate;
  7699. }]);
  7700. var Context2D = function Context2D(pdf) {
  7701. Object.defineProperty(this, 'canvas', {
  7702. get: function get() {
  7703. return {
  7704. parentNode: false,
  7705. style: false
  7706. };
  7707. }
  7708. });
  7709. Object.defineProperty(this, 'pdf', {
  7710. get: function get() {
  7711. return pdf;
  7712. }
  7713. });
  7714. var _pageWrapXEnabled = false;
  7715. /**
  7716. * @name pageWrapXEnabled
  7717. * @type {boolean}
  7718. * @default false
  7719. */
  7720. Object.defineProperty(this, 'pageWrapXEnabled', {
  7721. get: function get() {
  7722. return _pageWrapXEnabled;
  7723. },
  7724. set: function set(value) {
  7725. _pageWrapXEnabled = Boolean(value);
  7726. }
  7727. });
  7728. var _pageWrapYEnabled = false;
  7729. /**
  7730. * @name pageWrapYEnabled
  7731. * @type {boolean}
  7732. * @default true
  7733. */
  7734. Object.defineProperty(this, 'pageWrapYEnabled', {
  7735. get: function get() {
  7736. return _pageWrapYEnabled;
  7737. },
  7738. set: function set(value) {
  7739. _pageWrapYEnabled = Boolean(value);
  7740. }
  7741. });
  7742. var _posX = 0;
  7743. /**
  7744. * @name posX
  7745. * @type {number}
  7746. * @default 0
  7747. */
  7748. Object.defineProperty(this, 'posX', {
  7749. get: function get() {
  7750. return _posX;
  7751. },
  7752. set: function set(value) {
  7753. if (!isNaN(value)) {
  7754. _posX = value;
  7755. }
  7756. }
  7757. });
  7758. var _posY = 0;
  7759. /**
  7760. * @name posY
  7761. * @type {number}
  7762. * @default 0
  7763. */
  7764. Object.defineProperty(this, 'posY', {
  7765. get: function get() {
  7766. return _posY;
  7767. },
  7768. set: function set(value) {
  7769. if (!isNaN(value)) {
  7770. _posY = value;
  7771. }
  7772. }
  7773. });
  7774. var _autoPaging = false;
  7775. /**
  7776. * @name autoPaging
  7777. * @type {boolean}
  7778. * @default true
  7779. */
  7780. Object.defineProperty(this, 'autoPaging', {
  7781. get: function get() {
  7782. return _autoPaging;
  7783. },
  7784. set: function set(value) {
  7785. _autoPaging = Boolean(value);
  7786. }
  7787. });
  7788. var lastBreak = 0;
  7789. /**
  7790. * @name lastBreak
  7791. * @type {number}
  7792. * @default 0
  7793. */
  7794. Object.defineProperty(this, 'lastBreak', {
  7795. get: function get() {
  7796. return lastBreak;
  7797. },
  7798. set: function set(value) {
  7799. lastBreak = value;
  7800. }
  7801. });
  7802. var pageBreaks = [];
  7803. /**
  7804. * Y Position of page breaks.
  7805. * @name pageBreaks
  7806. * @type {number}
  7807. * @default 0
  7808. */
  7809. Object.defineProperty(this, 'pageBreaks', {
  7810. get: function get() {
  7811. return pageBreaks;
  7812. },
  7813. set: function set(value) {
  7814. pageBreaks = value;
  7815. }
  7816. });
  7817. var _ctx = new ContextLayer();
  7818. /**
  7819. * @name ctx
  7820. * @type {object}
  7821. * @default {}
  7822. */
  7823. Object.defineProperty(this, 'ctx', {
  7824. get: function get() {
  7825. return _ctx;
  7826. },
  7827. set: function set(value) {
  7828. if (value instanceof ContextLayer) {
  7829. _ctx = value;
  7830. }
  7831. }
  7832. });
  7833. /**
  7834. * @name path
  7835. * @type {array}
  7836. * @default []
  7837. */
  7838. Object.defineProperty(this, 'path', {
  7839. get: function get() {
  7840. return _ctx.path;
  7841. },
  7842. set: function set(value) {
  7843. _ctx.path = value;
  7844. }
  7845. });
  7846. /**
  7847. * @name ctxStack
  7848. * @type {array}
  7849. * @default []
  7850. */
  7851. var _ctxStack = [];
  7852. Object.defineProperty(this, 'ctxStack', {
  7853. get: function get() {
  7854. return _ctxStack;
  7855. },
  7856. set: function set(value) {
  7857. _ctxStack = value;
  7858. }
  7859. });
  7860. /**
  7861. * Sets or returns the color, gradient, or pattern used to fill the drawing
  7862. *
  7863. * @name fillStyle
  7864. * @default #000000
  7865. * @property {(color|gradient|pattern)} value The color of the drawing. Default value is #000000<br />
  7866. * A gradient object (linear or radial) used to fill the drawing (not supported by context2d)<br />
  7867. * A pattern object to use to fill the drawing (not supported by context2d)
  7868. */
  7869. Object.defineProperty(this, 'fillStyle', {
  7870. get: function get() {
  7871. return this.ctx.fillStyle;
  7872. },
  7873. set: function set(value) {
  7874. var rgba;
  7875. rgba = getRGBA(value);
  7876. this.ctx.fillStyle = rgba.style;
  7877. this.ctx.isFillTransparent = rgba.a === 0;
  7878. this.ctx.fillOpacity = rgba.a;
  7879. this.pdf.setFillColor(rgba.r, rgba.g, rgba.b, {
  7880. a: rgba.a
  7881. });
  7882. this.pdf.setTextColor(rgba.r, rgba.g, rgba.b, {
  7883. a: rgba.a
  7884. });
  7885. }
  7886. });
  7887. /**
  7888. * Sets or returns the color, gradient, or pattern used for strokes
  7889. *
  7890. * @name strokeStyle
  7891. * @default #000000
  7892. * @property {color} color A CSS color value that indicates the stroke color of the drawing. Default value is #000000 (not supported by context2d)
  7893. * @property {gradient} gradient A gradient object (linear or radial) used to create a gradient stroke (not supported by context2d)
  7894. * @property {pattern} pattern A pattern object used to create a pattern stroke (not supported by context2d)
  7895. */
  7896. Object.defineProperty(this, 'strokeStyle', {
  7897. get: function get() {
  7898. return this.ctx.strokeStyle;
  7899. },
  7900. set: function set(value) {
  7901. var rgba = getRGBA(value);
  7902. this.ctx.strokeStyle = rgba.style;
  7903. this.ctx.isStrokeTransparent = rgba.a === 0;
  7904. this.ctx.strokeOpacity = rgba.a;
  7905. if (rgba.a === 0) {
  7906. this.pdf.setDrawColor(255, 255, 255);
  7907. } else if (rgba.a === 1) {
  7908. this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b);
  7909. } else {
  7910. this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b);
  7911. }
  7912. }
  7913. });
  7914. /**
  7915. * Sets or returns the style of the end caps for a line
  7916. *
  7917. * @name lineCap
  7918. * @default butt
  7919. * @property {(butt|round|square)} lineCap butt A flat edge is added to each end of the line <br/>
  7920. * round A rounded end cap is added to each end of the line<br/>
  7921. * square A square end cap is added to each end of the line<br/>
  7922. */
  7923. Object.defineProperty(this, 'lineCap', {
  7924. get: function get() {
  7925. return this.ctx.lineCap;
  7926. },
  7927. set: function set(value) {
  7928. if (['butt', 'round', 'square'].indexOf(value) !== -1) {
  7929. this.ctx.lineCap = value;
  7930. this.pdf.setLineCap(value);
  7931. }
  7932. }
  7933. });
  7934. /**
  7935. * Sets or returns the current line width
  7936. *
  7937. * @name lineWidth
  7938. * @default 1
  7939. * @property {number} lineWidth The current line width, in pixels
  7940. */
  7941. Object.defineProperty(this, 'lineWidth', {
  7942. get: function get() {
  7943. return this.ctx.lineWidth;
  7944. },
  7945. set: function set(value) {
  7946. if (!isNaN(value)) {
  7947. this.ctx.lineWidth = value;
  7948. this.pdf.setLineWidth(value);
  7949. }
  7950. }
  7951. });
  7952. /**
  7953. * Sets or returns the type of corner created, when two lines meet
  7954. */
  7955. Object.defineProperty(this, 'lineJoin', {
  7956. get: function get() {
  7957. return this.ctx.lineJoin;
  7958. },
  7959. set: function set(value) {
  7960. if (['bevel', 'round', 'miter'].indexOf(value) !== -1) {
  7961. this.ctx.lineJoin = value;
  7962. this.pdf.setLineJoin(value);
  7963. }
  7964. }
  7965. });
  7966. /**
  7967. * A number specifying the miter limit ratio in coordinate space units. Zero, negative, Infinity, and NaN values are ignored. The default value is 10.0.
  7968. *
  7969. * @name miterLimit
  7970. * @default 10
  7971. */
  7972. Object.defineProperty(this, 'miterLimit', {
  7973. get: function get() {
  7974. return this.ctx.miterLimit;
  7975. },
  7976. set: function set(value) {
  7977. if (!isNaN(value)) {
  7978. this.ctx.miterLimit = value;
  7979. this.pdf.setMiterLimit(value);
  7980. }
  7981. }
  7982. });
  7983. Object.defineProperty(this, 'textBaseline', {
  7984. get: function get() {
  7985. return this.ctx.textBaseline;
  7986. },
  7987. set: function set(value) {
  7988. this.ctx.textBaseline = value;
  7989. }
  7990. });
  7991. Object.defineProperty(this, 'textAlign', {
  7992. get: function get() {
  7993. return this.ctx.textAlign;
  7994. },
  7995. set: function set(value) {
  7996. if (['right', 'end', 'center', 'left', 'start'].indexOf(value) !== -1) {
  7997. this.ctx.textAlign = value;
  7998. }
  7999. }
  8000. });
  8001. Object.defineProperty(this, 'font', {
  8002. get: function get() {
  8003. return this.ctx.font;
  8004. },
  8005. set: function set(value) {
  8006. this.ctx.font = value;
  8007. var rx, matches; //source: https://stackoverflow.com/a/10136041
  8008. rx = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-_,\"\'\sa-z]+?)\s*$/i;
  8009. matches = rx.exec(value);
  8010. if (matches !== null) {
  8011. var fontStyle = matches[1];
  8012. var fontVariant = matches[2];
  8013. var fontWeight = matches[3];
  8014. var fontSize = matches[4];
  8015. var fontSizeUnit = matches[5];
  8016. var fontFamily = matches[6];
  8017. } else {
  8018. return;
  8019. }
  8020. if ('px' === fontSizeUnit) {
  8021. fontSize = Math.floor(parseFloat(fontSize));
  8022. } else if ('em' === fontSizeUnit) {
  8023. fontSize = Math.floor(parseFloat(fontSize) * this.pdf.getFontSize());
  8024. } else {
  8025. fontSize = Math.floor(parseFloat(fontSize));
  8026. }
  8027. this.pdf.setFontSize(fontSize);
  8028. var style = '';
  8029. if (fontWeight === 'bold' || parseInt(fontWeight, 10) >= 700 || fontStyle === 'bold') {
  8030. style = 'bold';
  8031. }
  8032. if (fontStyle === 'italic') {
  8033. style += 'italic';
  8034. }
  8035. if (style.length === 0) {
  8036. style = 'normal';
  8037. }
  8038. var jsPdfFontName = '';
  8039. var parts = fontFamily.toLowerCase().replace(/"|'/g, '').split(/\s*,\s*/);
  8040. var fallbackFonts = {
  8041. arial: 'Helvetica',
  8042. verdana: 'Helvetica',
  8043. helvetica: 'Helvetica',
  8044. 'sans-serif': 'Helvetica',
  8045. fixed: 'Courier',
  8046. monospace: 'Courier',
  8047. terminal: 'Courier',
  8048. courier: 'Courier',
  8049. times: 'Times',
  8050. cursive: 'Times',
  8051. fantasy: 'Times',
  8052. serif: 'Times'
  8053. };
  8054. for (var i = 0; i < parts.length; i++) {
  8055. if (this.pdf.internal.getFont(parts[i], style, {
  8056. noFallback: true,
  8057. disableWarning: true
  8058. }) !== undefined) {
  8059. jsPdfFontName = parts[i];
  8060. break;
  8061. } else if (style === 'bolditalic' && this.pdf.internal.getFont(parts[i], 'bold', {
  8062. noFallback: true,
  8063. disableWarning: true
  8064. }) !== undefined) {
  8065. jsPdfFontName = parts[i];
  8066. style = 'bold';
  8067. } else if (this.pdf.internal.getFont(parts[i], 'normal', {
  8068. noFallback: true,
  8069. disableWarning: true
  8070. }) !== undefined) {
  8071. jsPdfFontName = parts[i];
  8072. style = 'normal';
  8073. break;
  8074. }
  8075. }
  8076. if (jsPdfFontName === '') {
  8077. for (var i = 0; i < parts.length; i++) {
  8078. if (fallbackFonts[parts[i]]) {
  8079. jsPdfFontName = fallbackFonts[parts[i]];
  8080. break;
  8081. }
  8082. }
  8083. }
  8084. jsPdfFontName = jsPdfFontName === '' ? 'Times' : jsPdfFontName;
  8085. this.pdf.setFont(jsPdfFontName, style);
  8086. }
  8087. });
  8088. Object.defineProperty(this, 'globalCompositeOperation', {
  8089. get: function get() {
  8090. return this.ctx.globalCompositeOperation;
  8091. },
  8092. set: function set(value) {
  8093. this.ctx.globalCompositeOperation = value;
  8094. }
  8095. });
  8096. Object.defineProperty(this, 'globalAlpha', {
  8097. get: function get() {
  8098. return this.ctx.globalAlpha;
  8099. },
  8100. set: function set(value) {
  8101. this.ctx.globalAlpha = value;
  8102. }
  8103. }); // Not HTML API
  8104. Object.defineProperty(this, 'ignoreClearRect', {
  8105. get: function get() {
  8106. return this.ctx.ignoreClearRect;
  8107. },
  8108. set: function set(value) {
  8109. this.ctx.ignoreClearRect = Boolean(value);
  8110. }
  8111. });
  8112. };
  8113. Context2D.prototype.fill = function () {
  8114. pathPreProcess.call(this, 'fill', false);
  8115. };
  8116. /**
  8117. * Actually draws the path you have defined
  8118. *
  8119. * @name stroke
  8120. * @function
  8121. * @description The stroke() method actually draws the path you have defined with all those moveTo() and lineTo() methods. The default color is black.
  8122. */
  8123. Context2D.prototype.stroke = function () {
  8124. pathPreProcess.call(this, 'stroke', false);
  8125. };
  8126. /**
  8127. * Begins a path, or resets the current
  8128. *
  8129. * @name beginPath
  8130. * @function
  8131. * @description The beginPath() method begins a path, or resets the current path.
  8132. */
  8133. Context2D.prototype.beginPath = function () {
  8134. this.path = [{
  8135. type: 'begin'
  8136. }];
  8137. };
  8138. /**
  8139. * Moves the path to the specified point in the canvas, without creating a line
  8140. *
  8141. * @name moveTo
  8142. * @function
  8143. * @param x {Number} The x-coordinate of where to move the path to
  8144. * @param y {Number} The y-coordinate of where to move the path to
  8145. */
  8146. Context2D.prototype.moveTo = function (x, y) {
  8147. if (isNaN(x) || isNaN(y)) {
  8148. console.error('jsPDF.context2d.moveTo: Invalid arguments', arguments);
  8149. throw new Error('Invalid arguments passed to jsPDF.context2d.moveTo');
  8150. }
  8151. var pt = this.ctx.transform.applyToPoint(new Point(x, y));
  8152. this.path.push({
  8153. type: 'mt',
  8154. x: pt.x,
  8155. y: pt.y
  8156. });
  8157. this.ctx.lastPoint = new Point(x, y);
  8158. };
  8159. /**
  8160. * Creates a path from the current point back to the starting point
  8161. *
  8162. * @name closePath
  8163. * @function
  8164. * @description The closePath() method creates a path from the current point back to the starting point.
  8165. */
  8166. Context2D.prototype.closePath = function () {
  8167. var pathBegin = new Point(0, 0);
  8168. var i = 0;
  8169. for (i = this.path.length - 1; i !== -1; i--) {
  8170. if (this.path[i].type === 'begin') {
  8171. if (_typeof(this.path[i + 1]) === 'object' && typeof this.path[i + 1].x === 'number') {
  8172. pathBegin = new Point(this.path[i + 1].x, this.path[i + 1].y);
  8173. this.path.push({
  8174. type: 'lt',
  8175. x: pathBegin.x,
  8176. y: pathBegin.y
  8177. });
  8178. break;
  8179. }
  8180. }
  8181. }
  8182. if (_typeof(this.path[i + 2]) === 'object' && typeof this.path[i + 2].x === 'number') {
  8183. this.path.push(JSON.parse(JSON.stringify(this.path[i + 2])));
  8184. }
  8185. this.path.push({
  8186. type: 'close'
  8187. });
  8188. this.ctx.lastPoint = new Point(pathBegin.x, pathBegin.y);
  8189. };
  8190. /**
  8191. * Adds a new point and creates a line to that point from the last specified point in the canvas
  8192. *
  8193. * @name lineTo
  8194. * @function
  8195. * @param x The x-coordinate of where to create the line to
  8196. * @param y The y-coordinate of where to create the line to
  8197. * @description The lineTo() method adds a new point and creates a line TO that point FROM the last specified point in the canvas (this method does not draw the line).
  8198. */
  8199. Context2D.prototype.lineTo = function (x, y) {
  8200. if (isNaN(x) || isNaN(y)) {
  8201. console.error('jsPDF.context2d.lineTo: Invalid arguments', arguments);
  8202. throw new Error('Invalid arguments passed to jsPDF.context2d.lineTo');
  8203. }
  8204. var pt = this.ctx.transform.applyToPoint(new Point(x, y));
  8205. this.path.push({
  8206. type: 'lt',
  8207. x: pt.x,
  8208. y: pt.y
  8209. });
  8210. this.ctx.lastPoint = new Point(pt.x, pt.y);
  8211. };
  8212. /**
  8213. * Clips a region of any shape and size from the original canvas
  8214. *
  8215. * @name clip
  8216. * @function
  8217. * @description The clip() method clips a region of any shape and size from the original canvas.
  8218. */
  8219. Context2D.prototype.clip = function () {
  8220. this.ctx.clip_path = JSON.parse(JSON.stringify(this.path));
  8221. pathPreProcess.call(this, null, true);
  8222. };
  8223. /**
  8224. * Creates a cubic Bézier curve
  8225. *
  8226. * @name quadraticCurveTo
  8227. * @function
  8228. * @param cpx {Number} The x-coordinate of the Bézier control point
  8229. * @param cpy {Number} The y-coordinate of the Bézier control point
  8230. * @param x {Number} The x-coordinate of the ending point
  8231. * @param y {Number} The y-coordinate of the ending point
  8232. * @description The quadraticCurveTo() method adds a point to the current path by using the specified control points that represent a quadratic Bézier curve.<br /><br /> A quadratic Bézier curve requires two points. The first point is a control point that is used in the quadratic Bézier calculation and the second point is the ending point for the curve. The starting point for the curve is the last point in the current path. If a path does not exist, use the beginPath() and moveTo() methods to define a starting point.
  8233. */
  8234. Context2D.prototype.quadraticCurveTo = function (cpx, cpy, x, y) {
  8235. if (isNaN(x) || isNaN(y) || isNaN(cpx) || isNaN(cpy)) {
  8236. console.error('jsPDF.context2d.quadraticCurveTo: Invalid arguments', arguments);
  8237. throw new Error('Invalid arguments passed to jsPDF.context2d.quadraticCurveTo');
  8238. }
  8239. var pt0 = this.ctx.transform.applyToPoint(new Point(x, y));
  8240. var pt1 = this.ctx.transform.applyToPoint(new Point(cpx, cpy));
  8241. this.path.push({
  8242. type: 'qct',
  8243. x1: pt1.x,
  8244. y1: pt1.y,
  8245. x: pt0.x,
  8246. y: pt0.y
  8247. });
  8248. this.ctx.lastPoint = new Point(pt0.x, pt0.y);
  8249. };
  8250. /**
  8251. * Creates a cubic Bézier curve
  8252. *
  8253. * @name bezierCurveTo
  8254. * @function
  8255. * @param cp1x {Number} The x-coordinate of the first Bézier control point
  8256. * @param cp1y {Number} The y-coordinate of the first Bézier control point
  8257. * @param cp2x {Number} The x-coordinate of the second Bézier control point
  8258. * @param cp2y {Number} The y-coordinate of the second Bézier control point
  8259. * @param x {Number} The x-coordinate of the ending point
  8260. * @param y {Number} The y-coordinate of the ending point
  8261. * @description The bezierCurveTo() method adds a point to the current path by using the specified control points that represent a cubic Bézier curve. <br /><br />A cubic bezier curve requires three points. The first two points are control points that are used in the cubic Bézier calculation and the last point is the ending point for the curve. The starting point for the curve is the last point in the current path. If a path does not exist, use the beginPath() and moveTo() methods to define a starting point.
  8262. */
  8263. Context2D.prototype.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
  8264. if (isNaN(x) || isNaN(y) || isNaN(cp1x) || isNaN(cp1y) || isNaN(cp2x) || isNaN(cp2y)) {
  8265. console.error('jsPDF.context2d.bezierCurveTo: Invalid arguments', arguments);
  8266. throw new Error('Invalid arguments passed to jsPDF.context2d.bezierCurveTo');
  8267. }
  8268. var pt0 = this.ctx.transform.applyToPoint(new Point(x, y));
  8269. var pt1 = this.ctx.transform.applyToPoint(new Point(cp1x, cp1y));
  8270. var pt2 = this.ctx.transform.applyToPoint(new Point(cp2x, cp2y));
  8271. this.path.push({
  8272. type: 'bct',
  8273. x1: pt1.x,
  8274. y1: pt1.y,
  8275. x2: pt2.x,
  8276. y2: pt2.y,
  8277. x: pt0.x,
  8278. y: pt0.y
  8279. });
  8280. this.ctx.lastPoint = new Point(pt0.x, pt0.y);
  8281. };
  8282. /**
  8283. * Creates an arc/curve (used to create circles, or parts of circles)
  8284. *
  8285. * @name arc
  8286. * @function
  8287. * @param x {Number} The x-coordinate of the center of the circle
  8288. * @param y {Number} The y-coordinate of the center of the circle
  8289. * @param radius {Number} The radius of the circle
  8290. * @param startAngle {Number} The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle)
  8291. * @param endAngle {Number} The ending angle, in radians
  8292. * @param counterclockwise {Boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise.
  8293. * @description The arc() method creates an arc/curve (used to create circles, or parts of circles).
  8294. */
  8295. Context2D.prototype.arc = function (x, y, radius, startAngle, endAngle, counterclockwise) {
  8296. if (isNaN(x) || isNaN(y) || isNaN(radius) || isNaN(startAngle) || isNaN(endAngle)) {
  8297. console.error('jsPDF.context2d.arc: Invalid arguments', arguments);
  8298. throw new Error('Invalid arguments passed to jsPDF.context2d.arc');
  8299. }
  8300. counterclockwise = Boolean(counterclockwise);
  8301. if (!this.ctx.transform.isIdentity) {
  8302. var xpt = this.ctx.transform.applyToPoint(new Point(x, y));
  8303. x = xpt.x;
  8304. y = xpt.y;
  8305. var x_radPt = this.ctx.transform.applyToPoint(new Point(0, radius));
  8306. var x_radPt0 = this.ctx.transform.applyToPoint(new Point(0, 0));
  8307. radius = Math.sqrt(Math.pow(x_radPt.x - x_radPt0.x, 2) + Math.pow(x_radPt.y - x_radPt0.y, 2));
  8308. }
  8309. if (Math.abs(endAngle - startAngle) >= 2 * Math.PI) {
  8310. startAngle = 0;
  8311. endAngle = 2 * Math.PI;
  8312. }
  8313. this.path.push({
  8314. type: 'arc',
  8315. x: x,
  8316. y: y,
  8317. radius: radius,
  8318. startAngle: startAngle,
  8319. endAngle: endAngle,
  8320. counterclockwise: counterclockwise
  8321. }); // this.ctx.lastPoint(new Point(pt.x,pt.y));
  8322. };
  8323. /**
  8324. * Creates an arc/curve between two tangents
  8325. *
  8326. * @name arcTo
  8327. * @function
  8328. * @param x1 {Number} The x-coordinate of the first tangent
  8329. * @param y1 {Number} The y-coordinate of the first tangent
  8330. * @param x2 {Number} The x-coordinate of the second tangent
  8331. * @param y2 {Number} The y-coordinate of the second tangent
  8332. * @param radius The radius of the arc
  8333. * @description The arcTo() method creates an arc/curve between two tangents on the canvas.
  8334. */
  8335. Context2D.prototype.arcTo = function (x1, y1, x2, y2, radius) {
  8336. throw new Error('arcTo not implemented.');
  8337. };
  8338. /**
  8339. * Creates a rectangle
  8340. *
  8341. * @name rect
  8342. * @function
  8343. * @param x {Number} The x-coordinate of the upper-left corner of the rectangle
  8344. * @param y {Number} The y-coordinate of the upper-left corner of the rectangle
  8345. * @param w {Number} The width of the rectangle, in pixels
  8346. * @param h {Number} The height of the rectangle, in pixels
  8347. * @description The rect() method creates a rectangle.
  8348. */
  8349. Context2D.prototype.rect = function (x, y, w, h) {
  8350. if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h)) {
  8351. console.error('jsPDF.context2d.rect: Invalid arguments', arguments);
  8352. throw new Error('Invalid arguments passed to jsPDF.context2d.rect');
  8353. }
  8354. this.moveTo(x, y);
  8355. this.lineTo(x + w, y);
  8356. this.lineTo(x + w, y + h);
  8357. this.lineTo(x, y + h);
  8358. this.lineTo(x, y);
  8359. this.lineTo(x + w, y);
  8360. this.lineTo(x, y);
  8361. };
  8362. /**
  8363. * Draws a "filled" rectangle
  8364. *
  8365. * @name fillRect
  8366. * @function
  8367. * @param x {Number} The x-coordinate of the upper-left corner of the rectangle
  8368. * @param y {Number} The y-coordinate of the upper-left corner of the rectangle
  8369. * @param w {Number} The width of the rectangle, in pixels
  8370. * @param h {Number} The height of the rectangle, in pixels
  8371. * @description The fillRect() method draws a "filled" rectangle. The default color of the fill is black.
  8372. */
  8373. Context2D.prototype.fillRect = function (x, y, w, h) {
  8374. if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h)) {
  8375. console.error('jsPDF.context2d.fillRect: Invalid arguments', arguments);
  8376. throw new Error('Invalid arguments passed to jsPDF.context2d.fillRect');
  8377. }
  8378. if (isFillTransparent.call(this)) {
  8379. return;
  8380. }
  8381. var tmp = {};
  8382. if (this.lineCap !== 'butt') {
  8383. tmp.lineCap = this.lineCap;
  8384. this.lineCap = 'butt';
  8385. }
  8386. if (this.lineJoin !== 'miter') {
  8387. tmp.lineJoin = this.lineJoin;
  8388. this.lineJoin = 'miter';
  8389. }
  8390. this.beginPath();
  8391. this.rect(x, y, w, h);
  8392. this.fill();
  8393. if (tmp.hasOwnProperty('lineCap')) {
  8394. this.lineCap = tmp.lineCap;
  8395. }
  8396. if (tmp.hasOwnProperty('lineJoin')) {
  8397. this.lineJoin = tmp.lineJoin;
  8398. }
  8399. };
  8400. /**
  8401. * Draws a rectangle (no fill)
  8402. *
  8403. * @name strokeRect
  8404. * @function
  8405. * @param x {Number} The x-coordinate of the upper-left corner of the rectangle
  8406. * @param y {Number} The y-coordinate of the upper-left corner of the rectangle
  8407. * @param w {Number} The width of the rectangle, in pixels
  8408. * @param h {Number} The height of the rectangle, in pixels
  8409. * @description The strokeRect() method draws a rectangle (no fill). The default color of the stroke is black.
  8410. */
  8411. Context2D.prototype.strokeRect = function strokeRect(x, y, w, h) {
  8412. if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h)) {
  8413. console.error('jsPDF.context2d.strokeRect: Invalid arguments', arguments);
  8414. throw new Error('Invalid arguments passed to jsPDF.context2d.strokeRect');
  8415. }
  8416. if (isStrokeTransparent.call(this)) {
  8417. return;
  8418. }
  8419. this.beginPath();
  8420. this.rect(x, y, w, h);
  8421. this.stroke();
  8422. };
  8423. /**
  8424. * Clears the specified pixels within a given rectangle
  8425. *
  8426. * @name clearRect
  8427. * @function
  8428. * @param x {Number} The x-coordinate of the upper-left corner of the rectangle
  8429. * @param y {Number} The y-coordinate of the upper-left corner of the rectangle
  8430. * @param w {Number} The width of the rectangle to clear, in pixels
  8431. * @param h {Number} The height of the rectangle to clear, in pixels
  8432. * @description We cannot clear PDF commands that were already written to PDF, so we use white instead. <br />
  8433. * As a special case, read a special flag (ignoreClearRect) and do nothing if it is set.
  8434. * This results in all calls to clearRect() to do nothing, and keep the canvas transparent.
  8435. * This flag is stored in the save/restore context and is managed the same way as other drawing states.
  8436. *
  8437. */
  8438. Context2D.prototype.clearRect = function (x, y, w, h) {
  8439. if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h)) {
  8440. console.error('jsPDF.context2d.clearRect: Invalid arguments', arguments);
  8441. throw new Error('Invalid arguments passed to jsPDF.context2d.clearRect');
  8442. }
  8443. if (this.ignoreClearRect) {
  8444. return;
  8445. }
  8446. this.fillStyle = '#ffffff';
  8447. this.fillRect(x, y, w, h);
  8448. };
  8449. /**
  8450. * Saves the state of the current context
  8451. *
  8452. * @name save
  8453. * @function
  8454. */
  8455. Context2D.prototype.save = function (doStackPush) {
  8456. doStackPush = typeof doStackPush === 'boolean' ? doStackPush : true;
  8457. var tmpPageNumber = this.pdf.internal.getCurrentPageInfo().pageNumber;
  8458. for (var i = 0; i < this.pdf.internal.getNumberOfPages(); i++) {
  8459. this.pdf.setPage(i + 1);
  8460. this.pdf.internal.out('q');
  8461. }
  8462. this.pdf.setPage(tmpPageNumber);
  8463. if (doStackPush) {
  8464. this.ctx.fontSize = this.pdf.internal.getFontSize();
  8465. var ctx = new ContextLayer(this.ctx);
  8466. this.ctxStack.push(this.ctx);
  8467. this.ctx = ctx;
  8468. }
  8469. };
  8470. /**
  8471. * Returns previously saved path state and attributes
  8472. *
  8473. * @name restore
  8474. * @function
  8475. */
  8476. Context2D.prototype.restore = function (doStackPop) {
  8477. doStackPop = typeof doStackPop === 'boolean' ? doStackPop : true;
  8478. var tmpPageNumber = this.pdf.internal.getCurrentPageInfo().pageNumber;
  8479. for (var i = 0; i < this.pdf.internal.getNumberOfPages(); i++) {
  8480. this.pdf.setPage(i + 1);
  8481. this.pdf.internal.out('Q');
  8482. }
  8483. this.pdf.setPage(tmpPageNumber);
  8484. if (doStackPop && this.ctxStack.length !== 0) {
  8485. this.ctx = this.ctxStack.pop();
  8486. this.fillStyle = this.ctx.fillStyle;
  8487. this.strokeStyle = this.ctx.strokeStyle;
  8488. this.font = this.ctx.font;
  8489. this.lineCap = this.ctx.lineCap;
  8490. this.lineWidth = this.ctx.lineWidth;
  8491. this.lineJoin = this.ctx.lineJoin;
  8492. }
  8493. };
  8494. /**
  8495. * @name toDataURL
  8496. * @function
  8497. */
  8498. Context2D.prototype.toDataURL = function () {
  8499. throw new Error('toDataUrl not implemented.');
  8500. }; //helper functions
  8501. /**
  8502. * Get the decimal values of r, g, b and a
  8503. *
  8504. * @name getRGBA
  8505. * @function
  8506. * @private
  8507. * @ignore
  8508. */
  8509. var getRGBA = function getRGBA(style) {
  8510. var rxRgb = /rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/;
  8511. var rxRgba = /rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d\.]+)\s*\)/;
  8512. var rxTransparent = /transparent|rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*0+\s*\)/;
  8513. var r, g, b, a;
  8514. if (style.isCanvasGradient === true) {
  8515. style = style.getColor();
  8516. }
  8517. if (!style) {
  8518. return {
  8519. r: 0,
  8520. g: 0,
  8521. b: 0,
  8522. a: 0,
  8523. style: style
  8524. };
  8525. }
  8526. if (rxTransparent.test(style)) {
  8527. r = 0;
  8528. g = 0;
  8529. b = 0;
  8530. a = 0;
  8531. } else {
  8532. var matches = rxRgb.exec(style);
  8533. if (matches !== null) {
  8534. r = parseInt(matches[1]);
  8535. g = parseInt(matches[2]);
  8536. b = parseInt(matches[3]);
  8537. a = 1;
  8538. } else {
  8539. matches = rxRgba.exec(style);
  8540. if (matches !== null) {
  8541. r = parseInt(matches[1]);
  8542. g = parseInt(matches[2]);
  8543. b = parseInt(matches[3]);
  8544. a = parseFloat(matches[4]);
  8545. } else {
  8546. a = 1;
  8547. if (typeof style === "string" && style.charAt(0) !== '#') {
  8548. var rgbColor = new RGBColor(style);
  8549. if (rgbColor.ok) {
  8550. style = rgbColor.toHex();
  8551. } else {
  8552. style = '#000000';
  8553. }
  8554. }
  8555. if (style.length === 4) {
  8556. r = style.substring(1, 2);
  8557. r += r;
  8558. g = style.substring(2, 3);
  8559. g += g;
  8560. b = style.substring(3, 4);
  8561. b += b;
  8562. } else {
  8563. r = style.substring(1, 3);
  8564. g = style.substring(3, 5);
  8565. b = style.substring(5, 7);
  8566. }
  8567. r = parseInt(r, 16);
  8568. g = parseInt(g, 16);
  8569. b = parseInt(b, 16);
  8570. }
  8571. }
  8572. }
  8573. return {
  8574. r: r,
  8575. g: g,
  8576. b: b,
  8577. a: a,
  8578. style: style
  8579. };
  8580. };
  8581. /**
  8582. * @name isFillTransparent
  8583. * @function
  8584. * @private
  8585. * @ignore
  8586. * @returns {Boolean}
  8587. */
  8588. var isFillTransparent = function isFillTransparent() {
  8589. return this.ctx.isFillTransparent || this.globalAlpha == 0;
  8590. };
  8591. /**
  8592. * @name isStrokeTransparent
  8593. * @function
  8594. * @private
  8595. * @ignore
  8596. * @returns {Boolean}
  8597. */
  8598. var isStrokeTransparent = function isStrokeTransparent() {
  8599. return Boolean(this.ctx.isStrokeTransparent || this.globalAlpha == 0);
  8600. };
  8601. /**
  8602. * Draws "filled" text on the canvas
  8603. *
  8604. * @name fillText
  8605. * @function
  8606. * @param text {String} Specifies the text that will be written on the canvas
  8607. * @param x {Number} The x coordinate where to start painting the text (relative to the canvas)
  8608. * @param y {Number} The y coordinate where to start painting the text (relative to the canvas)
  8609. * @param maxWidth {Number} Optional. The maximum allowed width of the text, in pixels
  8610. * @description The fillText() method draws filled text on the canvas. The default color of the text is black.
  8611. */
  8612. Context2D.prototype.fillText = function (text, x, y, maxWidth) {
  8613. if (isNaN(x) || isNaN(y) || typeof text !== 'string') {
  8614. console.error('jsPDF.context2d.fillText: Invalid arguments', arguments);
  8615. throw new Error('Invalid arguments passed to jsPDF.context2d.fillText');
  8616. }
  8617. maxWidth = isNaN(maxWidth) ? undefined : maxWidth;
  8618. if (isFillTransparent.call(this)) {
  8619. return;
  8620. }
  8621. y = getBaseline.call(this, y);
  8622. var degs = rad2deg(this.ctx.transform.rotation); // We only use X axis as scale hint
  8623. var scale = this.ctx.transform.scaleX;
  8624. putText.call(this, {
  8625. text: text,
  8626. x: x,
  8627. y: y,
  8628. scale: scale,
  8629. angle: degs,
  8630. align: this.textAlign,
  8631. maxWidth: maxWidth
  8632. });
  8633. };
  8634. /**
  8635. * Draws text on the canvas (no fill)
  8636. *
  8637. * @name strokeText
  8638. * @function
  8639. * @param text {String} Specifies the text that will be written on the canvas
  8640. * @param x {Number} The x coordinate where to start painting the text (relative to the canvas)
  8641. * @param y {Number} The y coordinate where to start painting the text (relative to the canvas)
  8642. * @param maxWidth {Number} Optional. The maximum allowed width of the text, in pixels
  8643. * @description The strokeText() method draws text (with no fill) on the canvas. The default color of the text is black.
  8644. */
  8645. Context2D.prototype.strokeText = function (text, x, y, maxWidth) {
  8646. if (isNaN(x) || isNaN(y) || typeof text !== 'string') {
  8647. console.error('jsPDF.context2d.strokeText: Invalid arguments', arguments);
  8648. throw new Error('Invalid arguments passed to jsPDF.context2d.strokeText');
  8649. }
  8650. if (isStrokeTransparent.call(this)) {
  8651. return;
  8652. }
  8653. maxWidth = isNaN(maxWidth) ? undefined : maxWidth;
  8654. y = getBaseline.call(this, y);
  8655. var degs = rad2deg(this.ctx.transform.rotation);
  8656. var scale = this.ctx.transform.scaleX;
  8657. putText.call(this, {
  8658. text: text,
  8659. x: x,
  8660. y: y,
  8661. scale: scale,
  8662. renderingMode: 'stroke',
  8663. angle: degs,
  8664. align: this.textAlign,
  8665. maxWidth: maxWidth
  8666. });
  8667. };
  8668. /**
  8669. * Returns an object that contains the width of the specified text
  8670. *
  8671. * @name measureText
  8672. * @function
  8673. * @param text {String} The text to be measured
  8674. * @description The measureText() method returns an object that contains the width of the specified text, in pixels.
  8675. * @returns {Number}
  8676. */
  8677. Context2D.prototype.measureText = function (text) {
  8678. if (typeof text !== 'string') {
  8679. console.error('jsPDF.context2d.measureText: Invalid arguments', arguments);
  8680. throw new Error('Invalid arguments passed to jsPDF.context2d.measureText');
  8681. }
  8682. var pdf = this.pdf;
  8683. var k = this.pdf.internal.scaleFactor;
  8684. var fontSize = pdf.internal.getFontSize();
  8685. var txtWidth = pdf.getStringUnitWidth(text) * fontSize / pdf.internal.scaleFactor;
  8686. txtWidth *= Math.round(k * 96 / 72 * 10000) / 10000;
  8687. var TextMetrics = function TextMetrics(options) {
  8688. options = options || {};
  8689. var _width = options.width || 0;
  8690. Object.defineProperty(this, 'width', {
  8691. get: function get() {
  8692. return _width;
  8693. }
  8694. });
  8695. return this;
  8696. };
  8697. return new TextMetrics({
  8698. width: txtWidth
  8699. });
  8700. }; //Transformations
  8701. /**
  8702. * Scales the current drawing bigger or smaller
  8703. *
  8704. * @name scale
  8705. * @function
  8706. * @param scalewidth {Number} Scales the width of the current drawing (1=100%, 0.5=50%, 2=200%, etc.)
  8707. * @param scaleheight {Number} Scales the height of the current drawing (1=100%, 0.5=50%, 2=200%, etc.)
  8708. * @description The scale() method scales the current drawing, bigger or smaller.
  8709. */
  8710. Context2D.prototype.scale = function (scalewidth, scaleheight) {
  8711. if (isNaN(scalewidth) || isNaN(scaleheight)) {
  8712. console.error('jsPDF.context2d.scale: Invalid arguments', arguments);
  8713. throw new Error('Invalid arguments passed to jsPDF.context2d.scale');
  8714. }
  8715. var matrix = new Matrix(scalewidth, 0.0, 0.0, scaleheight, 0.0, 0.0);
  8716. this.ctx.transform = this.ctx.transform.multiply(matrix);
  8717. };
  8718. /**
  8719. * Rotates the current drawing
  8720. *
  8721. * @name rotate
  8722. * @function
  8723. * @param angle {Number} The rotation angle, in radians.
  8724. * @description To calculate from degrees to radians: degrees*Math.PI/180. <br />
  8725. * Example: to rotate 5 degrees, specify the following: 5*Math.PI/180
  8726. */
  8727. Context2D.prototype.rotate = function (angle) {
  8728. if (isNaN(angle)) {
  8729. console.error('jsPDF.context2d.rotate: Invalid arguments', arguments);
  8730. throw new Error('Invalid arguments passed to jsPDF.context2d.rotate');
  8731. }
  8732. var matrix = new Matrix(Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle), 0.0, 0.0);
  8733. this.ctx.transform = this.ctx.transform.multiply(matrix);
  8734. };
  8735. /**
  8736. * Remaps the (0,0) position on the canvas
  8737. *
  8738. * @name translate
  8739. * @function
  8740. * @param x {Number} The value to add to horizontal (x) coordinates
  8741. * @param y {Number} The value to add to vertical (y) coordinates
  8742. * @description The translate() method remaps the (0,0) position on the canvas.
  8743. */
  8744. Context2D.prototype.translate = function (x, y) {
  8745. if (isNaN(x) || isNaN(y)) {
  8746. console.error('jsPDF.context2d.translate: Invalid arguments', arguments);
  8747. throw new Error('Invalid arguments passed to jsPDF.context2d.translate');
  8748. }
  8749. var matrix = new Matrix(1.0, 0.0, 0.0, 1.0, x, y);
  8750. this.ctx.transform = this.ctx.transform.multiply(matrix);
  8751. };
  8752. /**
  8753. * Replaces the current transformation matrix for the drawing
  8754. *
  8755. * @name transform
  8756. * @function
  8757. * @param a {Number} Horizontal scaling
  8758. * @param b {Number} Horizontal skewing
  8759. * @param c {Number} Vertical skewing
  8760. * @param d {Number} Vertical scaling
  8761. * @param e {Number} Horizontal moving
  8762. * @param f {Number} Vertical moving
  8763. * @description Each object on the canvas has a current transformation matrix.<br /><br />The transform() method replaces the current transformation matrix. It multiplies the current transformation matrix with the matrix described by:<br /><br /><br /><br />a c e<br /><br />b d f<br /><br />0 0 1<br /><br />In other words, the transform() method lets you scale, rotate, move, and skew the current context.
  8764. */
  8765. Context2D.prototype.transform = function (a, b, c, d, e, f) {
  8766. if (isNaN(a) || isNaN(b) || isNaN(c) || isNaN(d) || isNaN(e) || isNaN(f)) {
  8767. console.error('jsPDF.context2d.transform: Invalid arguments', arguments);
  8768. throw new Error('Invalid arguments passed to jsPDF.context2d.transform');
  8769. }
  8770. var matrix = new Matrix(a, b, c, d, e, f);
  8771. this.ctx.transform = this.ctx.transform.multiply(matrix);
  8772. };
  8773. /**
  8774. * Resets the current transform to the identity matrix. Then runs transform()
  8775. *
  8776. * @name setTransform
  8777. * @function
  8778. * @param a {Number} Horizontal scaling
  8779. * @param b {Number} Horizontal skewing
  8780. * @param c {Number} Vertical skewing
  8781. * @param d {Number} Vertical scaling
  8782. * @param e {Number} Horizontal moving
  8783. * @param f {Number} Vertical moving
  8784. * @description Each object on the canvas has a current transformation matrix. <br /><br />The setTransform() method resets the current transform to the identity matrix, and then runs transform() with the same arguments.<br /><br />In other words, the setTransform() method lets you scale, rotate, move, and skew the current context.
  8785. */
  8786. Context2D.prototype.setTransform = function (a, b, c, d, e, f) {
  8787. a = isNaN(a) ? 1 : a;
  8788. b = isNaN(b) ? 0 : b;
  8789. c = isNaN(c) ? 0 : c;
  8790. d = isNaN(d) ? 1 : d;
  8791. e = isNaN(e) ? 0 : e;
  8792. f = isNaN(f) ? 0 : f;
  8793. this.ctx.transform = new Matrix(a, b, c, d, e, f);
  8794. };
  8795. /**
  8796. * Draws an image, canvas, or video onto the canvas
  8797. *
  8798. * @function
  8799. * @param img {} Specifies the image, canvas, or video element to use
  8800. * @param sx {Number} Optional. The x coordinate where to start clipping
  8801. * @param sy {Number} Optional. The y coordinate where to start clipping
  8802. * @param swidth {Number} Optional. The width of the clipped image
  8803. * @param sheight {Number} Optional. The height of the clipped image
  8804. * @param x {Number} The x coordinate where to place the image on the canvas
  8805. * @param y {Number} The y coordinate where to place the image on the canvas
  8806. * @param width {Number} Optional. The width of the image to use (stretch or reduce the image)
  8807. * @param height {Number} Optional. The height of the image to use (stretch or reduce the image)
  8808. */
  8809. Context2D.prototype.drawImage = function (img, sx, sy, swidth, sheight, x, y, width, height) {
  8810. var imageProperties = this.pdf.getImageProperties(img);
  8811. var factorX = 1;
  8812. var factorY = 1;
  8813. var clipFactorX = 1;
  8814. var clipFactorY = 1;
  8815. var scaleFactorX = 1;
  8816. if (typeof swidth !== 'undefined' && typeof width !== 'undefined') {
  8817. clipFactorX = width / swidth;
  8818. clipFactorY = height / sheight;
  8819. factorX = imageProperties.width / swidth * width / swidth;
  8820. factorY = imageProperties.height / sheight * height / sheight;
  8821. } //is sx and sy are set and x and y not, set x and y with values of sx and sy
  8822. if (typeof x === 'undefined') {
  8823. x = sx;
  8824. y = sy;
  8825. sx = 0;
  8826. sy = 0;
  8827. }
  8828. if (typeof swidth !== 'undefined' && typeof width === 'undefined') {
  8829. width = swidth;
  8830. height = sheight;
  8831. }
  8832. if (typeof swidth === 'undefined' && typeof width === 'undefined') {
  8833. width = imageProperties.width;
  8834. height = imageProperties.height;
  8835. }
  8836. var decomposedTransformationMatrix = this.ctx.transform.decompose();
  8837. var angle = rad2deg(decomposedTransformationMatrix.rotate.shx);
  8838. scaleFactorX = decomposedTransformationMatrix.scale.sx;
  8839. scaleFactorX = decomposedTransformationMatrix.scale.sy;
  8840. var matrix = new Matrix();
  8841. matrix = matrix.multiply(decomposedTransformationMatrix.translate);
  8842. matrix = matrix.multiply(decomposedTransformationMatrix.skew);
  8843. matrix = matrix.multiply(decomposedTransformationMatrix.scale);
  8844. var mP = matrix.applyToPoint(new Point(width, height));
  8845. var xRect = matrix.applyToRectangle(new Rectangle(x - sx * clipFactorX, y - sy * clipFactorY, swidth * factorX, sheight * factorY));
  8846. var pageArray = getPagesByPath.call(this, xRect);
  8847. var pages = [];
  8848. for (var ii = 0; ii < pageArray.length; ii += 1) {
  8849. if (pages.indexOf(pageArray[ii]) === -1) {
  8850. pages.push(pageArray[ii]);
  8851. }
  8852. }
  8853. pages.sort();
  8854. var clipPath;
  8855. if (this.autoPaging) {
  8856. var min = pages[0];
  8857. var max = pages[pages.length - 1];
  8858. for (var i = min; i < max + 1; i++) {
  8859. this.pdf.setPage(i);
  8860. if (this.ctx.clip_path.length !== 0) {
  8861. var tmpPaths = this.path;
  8862. clipPath = JSON.parse(JSON.stringify(this.ctx.clip_path));
  8863. this.path = pathPositionRedo(clipPath, this.posX, -1 * this.pdf.internal.pageSize.height * (i - 1) + this.posY);
  8864. drawPaths.call(this, 'fill', true);
  8865. this.path = tmpPaths;
  8866. }
  8867. var tmpRect = JSON.parse(JSON.stringify(xRect));
  8868. tmpRect = pathPositionRedo([tmpRect], this.posX, -1 * this.pdf.internal.pageSize.height * (i - 1) + this.posY)[0];
  8869. this.pdf.addImage(img, 'jpg', tmpRect.x, tmpRect.y, tmpRect.w, tmpRect.h, null, null, angle);
  8870. }
  8871. } else {
  8872. this.pdf.addImage(img, 'jpg', xRect.x, xRect.y, xRect.w, xRect.h, null, null, angle);
  8873. }
  8874. };
  8875. var getPagesByPath = function getPagesByPath(path, pageWrapX, pageWrapY) {
  8876. var result = [];
  8877. pageWrapX = pageWrapX || this.pdf.internal.pageSize.width;
  8878. pageWrapY = pageWrapY || this.pdf.internal.pageSize.height;
  8879. switch (path.type) {
  8880. default:
  8881. case 'mt':
  8882. case 'lt':
  8883. result.push(Math.floor((path.y + this.posY) / pageWrapY) + 1);
  8884. break;
  8885. case 'arc':
  8886. result.push(Math.floor((path.y + this.posY - path.radius) / pageWrapY) + 1);
  8887. result.push(Math.floor((path.y + this.posY + path.radius) / pageWrapY) + 1);
  8888. break;
  8889. case 'qct':
  8890. var rectOfQuadraticCurve = getQuadraticCurveBoundary(this.ctx.lastPoint.x, this.ctx.lastPoint.y, path.x1, path.y1, path.x, path.y);
  8891. result.push(Math.floor(rectOfQuadraticCurve.y / pageWrapY) + 1);
  8892. result.push(Math.floor((rectOfQuadraticCurve.y + rectOfQuadraticCurve.h) / pageWrapY) + 1);
  8893. break;
  8894. case 'bct':
  8895. var rectOfBezierCurve = getBezierCurveBoundary(this.ctx.lastPoint.x, this.ctx.lastPoint.y, path.x1, path.y1, path.x2, path.y2, path.x, path.y);
  8896. result.push(Math.floor(rectOfBezierCurve.y / pageWrapY) + 1);
  8897. result.push(Math.floor((rectOfBezierCurve.y + rectOfBezierCurve.h) / pageWrapY) + 1);
  8898. break;
  8899. case 'rect':
  8900. result.push(Math.floor((path.y + this.posY) / pageWrapY) + 1);
  8901. result.push(Math.floor((path.y + path.h + this.posY) / pageWrapY) + 1);
  8902. }
  8903. for (var i = 0; i < result.length; i += 1) {
  8904. while (this.pdf.internal.getNumberOfPages() < result[i]) {
  8905. addPage.call(this);
  8906. }
  8907. }
  8908. return result;
  8909. };
  8910. var addPage = function addPage() {
  8911. var fillStyle = this.fillStyle;
  8912. var strokeStyle = this.strokeStyle;
  8913. var font = this.font;
  8914. var lineCap = this.lineCap;
  8915. var lineWidth = this.lineWidth;
  8916. var lineJoin = this.lineJoin;
  8917. this.pdf.addPage();
  8918. this.fillStyle = fillStyle;
  8919. this.strokeStyle = strokeStyle;
  8920. this.font = font;
  8921. this.lineCap = lineCap;
  8922. this.lineWidth = lineWidth;
  8923. this.lineJoin = lineJoin;
  8924. };
  8925. var pathPositionRedo = function pathPositionRedo(paths, x, y) {
  8926. for (var i = 0; i < paths.length; i++) {
  8927. switch (paths[i].type) {
  8928. case 'bct':
  8929. paths[i].x2 += x;
  8930. paths[i].y2 += y;
  8931. case 'qct':
  8932. paths[i].x1 += x;
  8933. paths[i].y1 += y;
  8934. case 'mt':
  8935. case 'lt':
  8936. case 'arc':
  8937. default:
  8938. paths[i].x += x;
  8939. paths[i].y += y;
  8940. }
  8941. }
  8942. return paths;
  8943. };
  8944. var pathPreProcess = function pathPreProcess(rule, isClip) {
  8945. var fillStyle = this.fillStyle;
  8946. var strokeStyle = this.strokeStyle;
  8947. var font = this.font;
  8948. var lineCap = this.lineCap;
  8949. var lineWidth = this.lineWidth;
  8950. var lineJoin = this.lineJoin;
  8951. var origPath = JSON.parse(JSON.stringify(this.path));
  8952. var xPath = JSON.parse(JSON.stringify(this.path));
  8953. var clipPath;
  8954. var tmpPath;
  8955. var pages = [];
  8956. for (var i = 0; i < xPath.length; i++) {
  8957. if (typeof xPath[i].x !== "undefined") {
  8958. var page = getPagesByPath.call(this, xPath[i]);
  8959. for (var ii = 0; ii < page.length; ii += 1) {
  8960. if (pages.indexOf(page[ii]) === -1) {
  8961. pages.push(page[ii]);
  8962. }
  8963. }
  8964. }
  8965. }
  8966. for (var i = 0; i < pages.length; i++) {
  8967. while (this.pdf.internal.getNumberOfPages() < pages[i]) {
  8968. addPage.call(this);
  8969. }
  8970. }
  8971. pages.sort();
  8972. if (this.autoPaging) {
  8973. var min = pages[0];
  8974. var max = pages[pages.length - 1];
  8975. for (var i = min; i < max + 1; i++) {
  8976. this.pdf.setPage(i);
  8977. this.fillStyle = fillStyle;
  8978. this.strokeStyle = strokeStyle;
  8979. this.lineCap = lineCap;
  8980. this.lineWidth = lineWidth;
  8981. this.lineJoin = lineJoin;
  8982. if (this.ctx.clip_path.length !== 0) {
  8983. var tmpPaths = this.path;
  8984. clipPath = JSON.parse(JSON.stringify(this.ctx.clip_path));
  8985. this.path = pathPositionRedo(clipPath, this.posX, -1 * this.pdf.internal.pageSize.height * (i - 1) + this.posY);
  8986. drawPaths.call(this, rule, true);
  8987. this.path = tmpPaths;
  8988. }
  8989. tmpPath = JSON.parse(JSON.stringify(origPath));
  8990. this.path = pathPositionRedo(tmpPath, this.posX, -1 * this.pdf.internal.pageSize.height * (i - 1) + this.posY);
  8991. if (isClip === false || i === 0) {
  8992. drawPaths.call(this, rule, isClip);
  8993. }
  8994. }
  8995. } else {
  8996. drawPaths.call(this, rule, isClip);
  8997. }
  8998. this.path = origPath;
  8999. };
  9000. /**
  9001. * Processes the paths
  9002. *
  9003. * @function
  9004. * @param rule {String}
  9005. * @param isClip {Boolean}
  9006. * @private
  9007. * @ignore
  9008. */
  9009. var drawPaths = function drawPaths(rule, isClip) {
  9010. if (rule === 'stroke' && !isClip && isStrokeTransparent.call(this)) {
  9011. return;
  9012. }
  9013. if (rule !== 'stroke' && !isClip && isFillTransparent.call(this)) {
  9014. return;
  9015. }
  9016. var moves = [];
  9017. var alpha = this.ctx.globalAlpha;
  9018. if (this.ctx.fillOpacity < 1) {
  9019. alpha = this.ctx.fillOpacity;
  9020. }
  9021. var xPath = this.path;
  9022. for (var i = 0; i < xPath.length; i++) {
  9023. var pt = xPath[i];
  9024. switch (pt.type) {
  9025. case 'begin':
  9026. moves.push({
  9027. begin: true
  9028. });
  9029. break;
  9030. case 'close':
  9031. moves.push({
  9032. close: true
  9033. });
  9034. break;
  9035. case 'mt':
  9036. moves.push({
  9037. start: pt,
  9038. deltas: [],
  9039. abs: []
  9040. });
  9041. break;
  9042. case 'lt':
  9043. var iii = moves.length;
  9044. if (!isNaN(xPath[i - 1].x)) {
  9045. var delta = [pt.x - xPath[i - 1].x, pt.y - xPath[i - 1].y];
  9046. if (iii > 0) {
  9047. for (iii; iii >= 0; iii--) {
  9048. if (moves[iii - 1].close !== true && moves[iii - 1].begin !== true) {
  9049. moves[iii - 1].deltas.push(delta);
  9050. moves[iii - 1].abs.push(pt);
  9051. break;
  9052. }
  9053. }
  9054. }
  9055. }
  9056. break;
  9057. case 'bct':
  9058. var delta = [pt.x1 - xPath[i - 1].x, pt.y1 - xPath[i - 1].y, pt.x2 - xPath[i - 1].x, pt.y2 - xPath[i - 1].y, pt.x - xPath[i - 1].x, pt.y - xPath[i - 1].y];
  9059. moves[moves.length - 1].deltas.push(delta);
  9060. break;
  9061. case 'qct':
  9062. var x1 = xPath[i - 1].x + 2.0 / 3.0 * (pt.x1 - xPath[i - 1].x);
  9063. var y1 = xPath[i - 1].y + 2.0 / 3.0 * (pt.y1 - xPath[i - 1].y);
  9064. var x2 = pt.x + 2.0 / 3.0 * (pt.x1 - pt.x);
  9065. var y2 = pt.y + 2.0 / 3.0 * (pt.y1 - pt.y);
  9066. var x3 = pt.x;
  9067. var y3 = pt.y;
  9068. var delta = [x1 - xPath[i - 1].x, y1 - xPath[i - 1].y, x2 - xPath[i - 1].x, y2 - xPath[i - 1].y, x3 - xPath[i - 1].x, y3 - xPath[i - 1].y];
  9069. moves[moves.length - 1].deltas.push(delta);
  9070. break;
  9071. case 'arc':
  9072. moves.push({
  9073. deltas: [],
  9074. abs: [],
  9075. arc: true
  9076. });
  9077. if (Array.isArray(moves[moves.length - 1].abs)) {
  9078. moves[moves.length - 1].abs.push(pt);
  9079. }
  9080. break;
  9081. }
  9082. }
  9083. var style;
  9084. if (!isClip) {
  9085. if (rule === 'stroke') {
  9086. style = 'stroke';
  9087. } else {
  9088. style = 'fill';
  9089. }
  9090. } else {
  9091. style = null;
  9092. }
  9093. for (var i = 0; i < moves.length; i++) {
  9094. if (moves[i].arc) {
  9095. var arcs = moves[i].abs;
  9096. for (var ii = 0; ii < arcs.length; ii++) {
  9097. var arc = arcs[ii];
  9098. if (typeof arc.startAngle !== 'undefined') {
  9099. var start = rad2deg(arc.startAngle);
  9100. var end = rad2deg(arc.endAngle);
  9101. var x = arc.x;
  9102. var y = arc.y;
  9103. drawArc.call(this, x, y, arc.radius, start, end, arc.counterclockwise, style, isClip);
  9104. } else {
  9105. drawLine.call(this, arc.x, arc.y);
  9106. }
  9107. }
  9108. }
  9109. if (!moves[i].arc) {
  9110. if (moves[i].close !== true && moves[i].begin !== true) {
  9111. var x = moves[i].start.x;
  9112. var y = moves[i].start.y;
  9113. drawLines.call(this, moves[i].deltas, x, y, null, null);
  9114. }
  9115. }
  9116. }
  9117. if (style) {
  9118. putStyle.call(this, style);
  9119. }
  9120. if (isClip) {
  9121. doClip.call(this);
  9122. }
  9123. };
  9124. var getBaseline = function getBaseline(y) {
  9125. var height = this.pdf.internal.getFontSize() / this.pdf.internal.scaleFactor;
  9126. var descent = height * (this.pdf.internal.getLineHeightFactor() - 1);
  9127. switch (this.ctx.textBaseline) {
  9128. case 'bottom':
  9129. return y - descent;
  9130. case 'top':
  9131. return y + height - descent;
  9132. case 'hanging':
  9133. return y + height - 2 * descent;
  9134. case 'middle':
  9135. return y + height / 2 - descent;
  9136. case 'ideographic':
  9137. // TODO not implemented
  9138. return y;
  9139. case 'alphabetic':
  9140. default:
  9141. return y;
  9142. }
  9143. };
  9144. Context2D.prototype.createLinearGradient = function createLinearGradient() {
  9145. var canvasGradient = function canvasGradient() {};
  9146. canvasGradient.colorStops = [];
  9147. canvasGradient.addColorStop = function (offset, color) {
  9148. this.colorStops.push([offset, color]);
  9149. };
  9150. canvasGradient.getColor = function () {
  9151. if (this.colorStops.length === 0) {
  9152. return '#000000';
  9153. }
  9154. return this.colorStops[0][1];
  9155. };
  9156. canvasGradient.isCanvasGradient = true;
  9157. return canvasGradient;
  9158. };
  9159. Context2D.prototype.createPattern = function createPattern() {
  9160. return this.createLinearGradient();
  9161. };
  9162. Context2D.prototype.createRadialGradient = function createRadialGradient() {
  9163. return this.createLinearGradient();
  9164. };
  9165. /**
  9166. *
  9167. * @param x Edge point X
  9168. * @param y Edge point Y
  9169. * @param r Radius
  9170. * @param a1 start angle
  9171. * @param a2 end angle
  9172. * @param counterclockwise
  9173. * @param style
  9174. * @param isClip
  9175. */
  9176. var drawArc = function drawArc(x, y, r, a1, a2, counterclockwise, style, isClip) {
  9177. var k = this.pdf.internal.scaleFactor;
  9178. var a1r = deg2rad(a1);
  9179. var a2r = deg2rad(a2);
  9180. var curves = createArc.call(this, r, a1r, a2r, counterclockwise);
  9181. for (var i = 0; i < curves.length; i++) {
  9182. var curve = curves[i];
  9183. if (i === 0) {
  9184. doMove.call(this, curve.x1 + x, curve.y1 + y);
  9185. }
  9186. drawCurve.call(this, x, y, curve.x2, curve.y2, curve.x3, curve.y3, curve.x4, curve.y4);
  9187. }
  9188. if (!isClip) {
  9189. putStyle.call(this, style);
  9190. } else {
  9191. doClip.call(this);
  9192. }
  9193. };
  9194. var putStyle = function putStyle(style) {
  9195. switch (style) {
  9196. case 'stroke':
  9197. this.pdf.internal.out('S');
  9198. break;
  9199. case 'fill':
  9200. this.pdf.internal.out('f');
  9201. break;
  9202. }
  9203. };
  9204. var doClip = function doClip() {
  9205. this.pdf.clip();
  9206. };
  9207. var doMove = function doMove(x, y) {
  9208. this.pdf.internal.out(getHorizontalCoordinateString(x) + ' ' + getVerticalCoordinateString(y) + ' m');
  9209. };
  9210. var putText = function putText(options) {
  9211. var textAlign;
  9212. switch (options.align) {
  9213. case 'right':
  9214. case 'end':
  9215. textAlign = 'right';
  9216. break;
  9217. case 'center':
  9218. textAlign = 'center';
  9219. break;
  9220. case 'left':
  9221. case 'start':
  9222. default:
  9223. textAlign = 'left';
  9224. break;
  9225. }
  9226. var pt = this.ctx.transform.applyToPoint(new Point(options.x, options.y));
  9227. var decomposedTransformationMatrix = this.ctx.transform.decompose();
  9228. var matrix = new Matrix();
  9229. matrix = matrix.multiply(decomposedTransformationMatrix.translate);
  9230. matrix = matrix.multiply(decomposedTransformationMatrix.skew);
  9231. matrix = matrix.multiply(decomposedTransformationMatrix.scale);
  9232. var textDimensions = this.pdf.getTextDimensions(options.text);
  9233. var textRect = this.ctx.transform.applyToRectangle(new Rectangle(options.x, options.y, textDimensions.w, textDimensions.h));
  9234. var textXRect = matrix.applyToRectangle(new Rectangle(options.x, options.y - textDimensions.h, textDimensions.w, textDimensions.h));
  9235. var pageArray = getPagesByPath.call(this, textXRect);
  9236. var pages = [];
  9237. for (var ii = 0; ii < pageArray.length; ii += 1) {
  9238. if (pages.indexOf(pageArray[ii]) === -1) {
  9239. pages.push(pageArray[ii]);
  9240. }
  9241. }
  9242. pages.sort();
  9243. var clipPath;
  9244. if (this.autoPaging === true) {
  9245. var min = pages[0];
  9246. var max = pages[pages.length - 1];
  9247. for (var i = min; i < max + 1; i++) {
  9248. this.pdf.setPage(i);
  9249. if (this.ctx.clip_path.length !== 0) {
  9250. var tmpPaths = this.path;
  9251. clipPath = JSON.parse(JSON.stringify(this.ctx.clip_path));
  9252. this.path = pathPositionRedo(clipPath, this.posX, -1 * this.pdf.internal.pageSize.height * (i - 1) + this.posY);
  9253. drawPaths.call(this, 'fill', true);
  9254. this.path = tmpPaths;
  9255. }
  9256. var tmpRect = JSON.parse(JSON.stringify(textRect));
  9257. tmpRect = pathPositionRedo([tmpRect], this.posX, -1 * this.pdf.internal.pageSize.height * (i - 1) + this.posY)[0];
  9258. if (options.scale >= 0.01) {
  9259. var oldSize = this.pdf.internal.getFontSize();
  9260. this.pdf.setFontSize(oldSize * options.scale);
  9261. }
  9262. this.pdf.text(options.text, tmpRect.x, tmpRect.y, {
  9263. angle: options.angle,
  9264. align: textAlign,
  9265. renderingMode: options.renderingMode,
  9266. maxWidth: options.maxWidth
  9267. });
  9268. if (options.scale >= 0.01) {
  9269. this.pdf.setFontSize(oldSize);
  9270. }
  9271. }
  9272. } else {
  9273. if (options.scale >= 0.01) {
  9274. var oldSize = this.pdf.internal.getFontSize();
  9275. this.pdf.setFontSize(oldSize * options.scale);
  9276. }
  9277. this.pdf.text(options.text, pt.x + this.posX, pt.y + this.posY, {
  9278. angle: options.angle,
  9279. align: textAlign,
  9280. renderingMode: options.renderingMode,
  9281. maxWidth: options.maxWidth
  9282. });
  9283. if (options.scale >= 0.01) {
  9284. this.pdf.setFontSize(oldSize);
  9285. }
  9286. }
  9287. };
  9288. var drawLine = function drawLine(x, y, prevX, prevY) {
  9289. prevX = prevX || 0;
  9290. prevY = prevY || 0;
  9291. this.pdf.internal.out(getHorizontalCoordinateString(x + prevX) + ' ' + getVerticalCoordinateString(y + prevY) + ' l');
  9292. };
  9293. var drawLines = function drawLines(lines, x, y) {
  9294. return this.pdf.lines(lines, x, y, null, null);
  9295. };
  9296. var drawCurve = function drawCurve(x, y, x1, y1, x2, y2, x3, y3) {
  9297. this.pdf.internal.out([f2(getHorizontalCoordinate(x1 + x)), f2(getVerticalCoordinate(y1 + y)), f2(getHorizontalCoordinate(x2 + x)), f2(getVerticalCoordinate(y2 + y)), f2(getHorizontalCoordinate(x3 + x)), f2(getVerticalCoordinate(y3 + y)), 'c'].join(' '));
  9298. };
  9299. /**
  9300. * Return a array of objects that represent bezier curves which approximate the circular arc centered at the origin, from startAngle to endAngle (radians) with the specified radius.
  9301. *
  9302. * Each bezier curve is an object with four points, where x1,y1 and x4,y4 are the arc's end points and x2,y2 and x3,y3 are the cubic bezier's control points.
  9303. * @function createArc
  9304. */
  9305. var createArc = function createArc(radius, startAngle, endAngle, anticlockwise) {
  9306. var EPSILON = 0.00001; // Roughly 1/1000th of a degree, see below // normalize startAngle, endAngle to [-2PI, 2PI]
  9307. var twoPI = Math.PI * 2;
  9308. var startAngleN = startAngle;
  9309. if (startAngleN < twoPI || startAngleN > twoPI) {
  9310. startAngleN = startAngleN % twoPI;
  9311. }
  9312. var endAngleN = endAngle;
  9313. if (endAngleN < twoPI || endAngleN > twoPI) {
  9314. endAngleN = endAngleN % twoPI;
  9315. } // Compute the sequence of arc curves, up to PI/2 at a time. // Total arc angle is less than 2PI.
  9316. var curves = [];
  9317. var piOverTwo = Math.PI / 2.0; //var sgn = (startAngle < endAngle) ? +1 : -1; // clockwise or counterclockwise
  9318. var sgn = anticlockwise ? -1 : +1;
  9319. var a1 = startAngle;
  9320. for (var totalAngle = Math.min(twoPI, Math.abs(endAngleN - startAngleN)); totalAngle > EPSILON;) {
  9321. var a2 = a1 + sgn * Math.min(totalAngle, piOverTwo);
  9322. curves.push(createSmallArc.call(this, radius, a1, a2));
  9323. totalAngle -= Math.abs(a2 - a1);
  9324. a1 = a2;
  9325. }
  9326. return curves;
  9327. };
  9328. /**
  9329. * Cubic bezier approximation of a circular arc centered at the origin, from (radians) a1 to a2, where a2-a1 < pi/2. The arc's radius is r.
  9330. *
  9331. * Returns an object with four points, where x1,y1 and x4,y4 are the arc's end points and x2,y2 and x3,y3 are the cubic bezier's control points.
  9332. *
  9333. * This algorithm is based on the approach described in: A. Riškus, "Approximation of a Cubic Bezier Curve by Circular Arcs and Vice Versa," Information Technology and Control, 35(4), 2006 pp. 371-378.
  9334. */
  9335. var createSmallArc = function createSmallArc(r, a1, a2) {
  9336. var a = (a2 - a1) / 2.0;
  9337. var x4 = r * Math.cos(a);
  9338. var y4 = r * Math.sin(a);
  9339. var x1 = x4;
  9340. var y1 = -y4;
  9341. var q1 = x1 * x1 + y1 * y1;
  9342. var q2 = q1 + x1 * x4 + y1 * y4;
  9343. var k2 = 4 / 3 * (Math.sqrt(2 * q1 * q2) - q2) / (x1 * y4 - y1 * x4);
  9344. var x2 = x1 - k2 * y1;
  9345. var y2 = y1 + k2 * x1;
  9346. var x3 = x2;
  9347. var y3 = -y2;
  9348. var ar = a + a1;
  9349. var cos_ar = Math.cos(ar);
  9350. var sin_ar = Math.sin(ar);
  9351. return {
  9352. x1: r * Math.cos(a1),
  9353. y1: r * Math.sin(a1),
  9354. x2: x2 * cos_ar - y2 * sin_ar,
  9355. y2: x2 * sin_ar + y2 * cos_ar,
  9356. x3: x3 * cos_ar - y3 * sin_ar,
  9357. y3: x3 * sin_ar + y3 * cos_ar,
  9358. x4: r * Math.cos(a2),
  9359. y4: r * Math.sin(a2)
  9360. };
  9361. };
  9362. var rad2deg = function rad2deg(value) {
  9363. return value * 180 / Math.PI;
  9364. };
  9365. var deg2rad = function deg2rad(deg) {
  9366. return deg * Math.PI / 180;
  9367. };
  9368. var getQuadraticCurveBoundary = function getQuadraticCurveBoundary(sx, sy, cpx, cpy, ex, ey) {
  9369. var midX1 = sx + (cpx - sx) * 0.50;
  9370. var midY1 = sy + (cpy - sy) * 0.50;
  9371. var midX2 = ex + (cpx - ex) * 0.50;
  9372. var midY2 = ey + (cpy - ey) * 0.50;
  9373. var resultX1 = Math.min(sx, ex, midX1, midX2);
  9374. var resultX2 = Math.max(sx, ex, midX1, midX2);
  9375. var resultY1 = Math.min(sy, ey, midY1, midY2);
  9376. var resultY2 = Math.max(sy, ey, midY1, midY2);
  9377. return new Rectangle(resultX1, resultY1, resultX2 - resultX1, resultY2 - resultY1);
  9378. }; //De Casteljau algorithm
  9379. var getBezierCurveBoundary = function getBezierCurveBoundary(ax, ay, bx, by, cx, cy, dx, dy) {
  9380. var tobx = bx - ax;
  9381. var toby = by - ay;
  9382. var tocx = cx - bx;
  9383. var tocy = cy - by;
  9384. var todx = dx - cx;
  9385. var tody = dy - cy;
  9386. var precision = 40;
  9387. var d, px, py, qx, qy, rx, ry, tx, ty, sx, sy, x, y, i, minx, miny, maxx, maxy, toqx, toqy, torx, tory, totx, toty;
  9388. for (var i = 0; i < precision + 1; i++) {
  9389. d = i / precision;
  9390. px = ax + d * tobx;
  9391. py = ay + d * toby;
  9392. qx = bx + d * tocx;
  9393. qy = by + d * tocy;
  9394. rx = cx + d * todx;
  9395. ry = cy + d * tody;
  9396. toqx = qx - px;
  9397. toqy = qy - py;
  9398. torx = rx - qx;
  9399. tory = ry - qy;
  9400. sx = px + d * toqx;
  9401. sy = py + d * toqy;
  9402. tx = qx + d * torx;
  9403. ty = qy + d * tory;
  9404. totx = tx - sx;
  9405. toty = ty - sy;
  9406. x = sx + d * totx;
  9407. y = sy + d * toty;
  9408. if (i == 0) {
  9409. minx = x;
  9410. miny = y;
  9411. maxx = x;
  9412. maxy = y;
  9413. } else {
  9414. minx = Math.min(minx, x);
  9415. miny = Math.min(miny, y);
  9416. maxx = Math.max(maxx, x);
  9417. maxy = Math.max(maxy, y);
  9418. }
  9419. }
  9420. return new Rectangle(Math.round(minx), Math.round(miny), Math.round(maxx - minx), Math.round(maxy - miny));
  9421. };
  9422. var Point = function Point(x, y) {
  9423. var _x = x || 0;
  9424. Object.defineProperty(this, 'x', {
  9425. enumerable: true,
  9426. get: function get() {
  9427. return _x;
  9428. },
  9429. set: function set(value) {
  9430. if (!isNaN(value)) {
  9431. _x = parseFloat(value);
  9432. }
  9433. }
  9434. });
  9435. var _y = y || 0;
  9436. Object.defineProperty(this, 'y', {
  9437. enumerable: true,
  9438. get: function get() {
  9439. return _y;
  9440. },
  9441. set: function set(value) {
  9442. if (!isNaN(value)) {
  9443. _y = parseFloat(value);
  9444. }
  9445. }
  9446. });
  9447. var _type = 'pt';
  9448. Object.defineProperty(this, 'type', {
  9449. enumerable: true,
  9450. get: function get() {
  9451. return _type;
  9452. },
  9453. set: function set(value) {
  9454. _type = value.toString();
  9455. }
  9456. });
  9457. return this;
  9458. };
  9459. var Rectangle = function Rectangle(x, y, w, h) {
  9460. Point.call(this, x, y);
  9461. this.type = 'rect';
  9462. var _w = w || 0;
  9463. Object.defineProperty(this, 'w', {
  9464. enumerable: true,
  9465. get: function get() {
  9466. return _w;
  9467. },
  9468. set: function set(value) {
  9469. if (!isNaN(value)) {
  9470. _w = parseFloat(value);
  9471. }
  9472. }
  9473. });
  9474. var _h = h || 0;
  9475. Object.defineProperty(this, 'h', {
  9476. enumerable: true,
  9477. get: function get() {
  9478. return _h;
  9479. },
  9480. set: function set(value) {
  9481. if (!isNaN(value)) {
  9482. _h = parseFloat(value);
  9483. }
  9484. }
  9485. });
  9486. return this;
  9487. };
  9488. var Matrix = function Matrix(sx, shy, shx, sy, tx, ty) {
  9489. var _matrix = [];
  9490. Object.defineProperty(this, 'sx', {
  9491. get: function get() {
  9492. return _matrix[0];
  9493. },
  9494. set: function set(value) {
  9495. _matrix[0] = Math.round(value * 100000) / 100000;
  9496. }
  9497. });
  9498. Object.defineProperty(this, 'shy', {
  9499. get: function get() {
  9500. return _matrix[1];
  9501. },
  9502. set: function set(value) {
  9503. _matrix[1] = Math.round(value * 100000) / 100000;
  9504. }
  9505. });
  9506. Object.defineProperty(this, 'shx', {
  9507. get: function get() {
  9508. return _matrix[2];
  9509. },
  9510. set: function set(value) {
  9511. _matrix[2] = Math.round(value * 100000) / 100000;
  9512. }
  9513. });
  9514. Object.defineProperty(this, 'sy', {
  9515. get: function get() {
  9516. return _matrix[3];
  9517. },
  9518. set: function set(value) {
  9519. _matrix[3] = Math.round(value * 100000) / 100000;
  9520. }
  9521. });
  9522. Object.defineProperty(this, 'tx', {
  9523. get: function get() {
  9524. return _matrix[4];
  9525. },
  9526. set: function set(value) {
  9527. _matrix[4] = Math.round(value * 100000) / 100000;
  9528. }
  9529. });
  9530. Object.defineProperty(this, 'ty', {
  9531. get: function get() {
  9532. return _matrix[5];
  9533. },
  9534. set: function set(value) {
  9535. _matrix[5] = Math.round(value * 100000) / 100000;
  9536. }
  9537. });
  9538. Object.defineProperty(this, 'rotation', {
  9539. get: function get() {
  9540. return Math.atan2(this.shx, this.sx);
  9541. }
  9542. });
  9543. Object.defineProperty(this, 'scaleX', {
  9544. get: function get() {
  9545. return this.decompose().scale.sx;
  9546. }
  9547. });
  9548. Object.defineProperty(this, 'scaleY', {
  9549. get: function get() {
  9550. return this.decompose().scale.sy;
  9551. }
  9552. });
  9553. Object.defineProperty(this, 'isIdentity', {
  9554. get: function get() {
  9555. if (this.sx !== 1) {
  9556. return false;
  9557. }
  9558. if (this.shy !== 0) {
  9559. return false;
  9560. }
  9561. if (this.shx !== 0) {
  9562. return false;
  9563. }
  9564. if (this.sy !== 1) {
  9565. return false;
  9566. }
  9567. if (this.tx !== 0) {
  9568. return false;
  9569. }
  9570. if (this.ty !== 0) {
  9571. return false;
  9572. }
  9573. return true;
  9574. }
  9575. });
  9576. this.sx = !isNaN(sx) ? sx : 1;
  9577. this.shy = !isNaN(shy) ? shy : 0;
  9578. this.shx = !isNaN(shx) ? shx : 0;
  9579. this.sy = !isNaN(sy) ? sy : 1;
  9580. this.tx = !isNaN(tx) ? tx : 0;
  9581. this.ty = !isNaN(ty) ? ty : 0;
  9582. return this;
  9583. };
  9584. /**
  9585. * Multiply the matrix with given Matrix
  9586. *
  9587. * @function multiply
  9588. * @param matrix
  9589. * @returns {Matrix}
  9590. * @private
  9591. * @ignore
  9592. */
  9593. Matrix.prototype.multiply = function (matrix) {
  9594. var sx = matrix.sx * this.sx + matrix.shy * this.shx;
  9595. var shy = matrix.sx * this.shy + matrix.shy * this.sy;
  9596. var shx = matrix.shx * this.sx + matrix.sy * this.shx;
  9597. var sy = matrix.shx * this.shy + matrix.sy * this.sy;
  9598. var tx = matrix.tx * this.sx + matrix.ty * this.shx + this.tx;
  9599. var ty = matrix.tx * this.shy + matrix.ty * this.sy + this.ty;
  9600. return new Matrix(sx, shy, shx, sy, tx, ty);
  9601. };
  9602. /**
  9603. * @function decompose
  9604. * @private
  9605. * @ignore
  9606. */
  9607. Matrix.prototype.decompose = function () {
  9608. var a = this.sx;
  9609. var b = this.shy;
  9610. var c = this.shx;
  9611. var d = this.sy;
  9612. var e = this.tx;
  9613. var f = this.ty;
  9614. var scaleX = Math.sqrt(a * a + b * b);
  9615. a /= scaleX;
  9616. b /= scaleX;
  9617. var shear = a * c + b * d;
  9618. c -= a * shear;
  9619. d -= b * shear;
  9620. var scaleY = Math.sqrt(c * c + d * d);
  9621. c /= scaleY;
  9622. d /= scaleY;
  9623. shear /= scaleY;
  9624. if (a * d < b * c) {
  9625. a = -a;
  9626. b = -b;
  9627. shear = -shear;
  9628. scaleX = -scaleX;
  9629. }
  9630. return {
  9631. scale: new Matrix(scaleX, 0, 0, scaleY, 0, 0),
  9632. translate: new Matrix(1, 0, 0, 1, e, f),
  9633. rotate: new Matrix(a, b, -b, a, 0, 0),
  9634. skew: new Matrix(1, 0, shear, 1, 0, 0)
  9635. };
  9636. };
  9637. /**
  9638. * @function applyToPoint
  9639. * @private
  9640. * @ignore
  9641. */
  9642. Matrix.prototype.applyToPoint = function (pt) {
  9643. var x = pt.x * this.sx + pt.y * this.shx + this.tx;
  9644. var y = pt.x * this.shy + pt.y * this.sy + this.ty;
  9645. return new Point(x, y);
  9646. };
  9647. /**
  9648. * @function applyToRectangle
  9649. * @private
  9650. * @ignore
  9651. */
  9652. Matrix.prototype.applyToRectangle = function (rect) {
  9653. var pt1 = this.applyToPoint(rect);
  9654. var pt2 = this.applyToPoint(new Point(rect.x + rect.w, rect.y + rect.h));
  9655. return new Rectangle(pt1.x, pt1.y, pt2.x - pt1.x, pt2.y - pt1.y);
  9656. };
  9657. /**
  9658. * @function clone
  9659. * @private
  9660. * @ignore
  9661. */
  9662. Matrix.prototype.clone = function () {
  9663. var sx = this.sx;
  9664. var shy = this.shy;
  9665. var shx = this.shx;
  9666. var sy = this.sy;
  9667. var tx = this.tx;
  9668. var ty = this.ty;
  9669. return new Matrix(sx, shy, shx, sy, tx, ty);
  9670. };
  9671. })(jsPDF.API, typeof self !== 'undefined' && self || typeof window !== 'undefined' && window || typeof global !== 'undefined' && global || Function('return typeof this === "object" && this.content')() || Function('return this')());
  9672. /**
  9673. * jsPDF filters PlugIn
  9674. * Copyright (c) 2014 Aras Abbasi
  9675. *
  9676. * Licensed under the MIT License.
  9677. * http://opensource.org/licenses/mit-license
  9678. */
  9679. (function (jsPDFAPI) {
  9680. var ASCII85Encode = function ASCII85Encode(a) {
  9681. var b, c, d, e, f, g, h, i, j, k;
  9682. for (!/[^\x00-\xFF]/.test(a), b = "\x00\x00\x00\x00".slice(a.length % 4 || 4), a += b, c = [], d = 0, e = a.length; e > d; d += 4) {
  9683. f = (a.charCodeAt(d) << 24) + (a.charCodeAt(d + 1) << 16) + (a.charCodeAt(d + 2) << 8) + a.charCodeAt(d + 3), 0 !== f ? (k = f % 85, f = (f - k) / 85, j = f % 85, f = (f - j) / 85, i = f % 85, f = (f - i) / 85, h = f % 85, f = (f - h) / 85, g = f % 85, c.push(g + 33, h + 33, i + 33, j + 33, k + 33)) : c.push(122);
  9684. }
  9685. return function (a, b) {
  9686. for (var c = b; c > 0; c--) {
  9687. a.pop();
  9688. }
  9689. }(c, b.length), String.fromCharCode.apply(String, c) + "~>";
  9690. };
  9691. var ASCII85Decode = function ASCII85Decode(a) {
  9692. var c,
  9693. d,
  9694. e,
  9695. f,
  9696. g,
  9697. h = String,
  9698. l = "length",
  9699. w = 255,
  9700. x = "charCodeAt",
  9701. y = "slice",
  9702. z = "replace";
  9703. for ("~>" === a[y](-2), a = a[y](0, -2)[z](/\s/g, "")[z]("z", "!!!!!"), c = "uuuuu"[y](a[l] % 5 || 5), a += c, e = [], f = 0, g = a[l]; g > f; f += 5) {
  9704. d = 52200625 * (a[x](f) - 33) + 614125 * (a[x](f + 1) - 33) + 7225 * (a[x](f + 2) - 33) + 85 * (a[x](f + 3) - 33) + (a[x](f + 4) - 33), e.push(w & d >> 24, w & d >> 16, w & d >> 8, w & d);
  9705. }
  9706. return function (a, b) {
  9707. for (var c = b; c > 0; c--) {
  9708. a.pop();
  9709. }
  9710. }(e, c[l]), h.fromCharCode.apply(h, e);
  9711. };
  9712. /**
  9713. * TODO: Not Tested:
  9714. //https://gist.github.com/revolunet/843889
  9715. // LZW-compress a string
  9716. var LZWEncode = function(s, options) {
  9717. options = Object.assign({
  9718. predictor: 1,
  9719. colors: 1,
  9720. bitsPerComponent: 8,
  9721. columns: 1,
  9722. earlyChange: 1
  9723. }, options);
  9724. var dict = {};
  9725. var data = (s + "").split("");
  9726. var out = [];
  9727. var currChar;
  9728. var phrase = data[0];
  9729. var code = 256; //0xe000
  9730. for (var i=1; i<data.length; i++) {
  9731. currChar=data[i];
  9732. if (dict['_' + phrase + currChar] != null) {
  9733. phrase += currChar;
  9734. }
  9735. else {
  9736. out.push(phrase.length > 1 ? dict['_'+phrase] : phrase.charCodeAt(0));
  9737. dict['_' + phrase + currChar] = code;
  9738. code++;
  9739. phrase=currChar;
  9740. }
  9741. }
  9742. out.push(phrase.length > 1 ? dict['_'+phrase] : phrase.charCodeAt(0));
  9743. for (var i=0; i<out.length; i++) {
  9744. out[i] = String.fromCharCode(out[i]);
  9745. }
  9746. return out.join("");
  9747. }
  9748. // Decompress an LZW-encoded string
  9749. var LZWDecode = function(s, options) {
  9750. options = Object.assign({
  9751. predictor: 1,
  9752. colors: 1,
  9753. bitsPerComponent: 8,
  9754. columns: 1,
  9755. earlyChange: 1
  9756. }, options);
  9757. var dict = {};
  9758. var data = (s + "").split("");
  9759. var currChar = data[0];
  9760. var oldPhrase = currChar;
  9761. var out = [currChar];
  9762. var code = 256;
  9763. var phrase;
  9764. for (var i=1; i<data.length; i++) {
  9765. var currCode = data[i].charCodeAt(0);
  9766. if (currCode < 256) {
  9767. phrase = data[i];
  9768. }
  9769. else {
  9770. phrase = dict['_'+currCode] ? dict['_'+currCode] : (oldPhrase + currChar);
  9771. }
  9772. out.push(phrase);
  9773. currChar = phrase.charAt(0);
  9774. dict['_'+code] = oldPhrase + currChar;
  9775. code++;
  9776. oldPhrase = phrase;
  9777. }
  9778. return out.join("");
  9779. }
  9780. */
  9781. var ASCIIHexEncode = function ASCIIHexEncode(value) {
  9782. var result = '';
  9783. var i;
  9784. for (var i = 0; i < value.length; i += 1) {
  9785. result += ("0" + value.charCodeAt(i).toString(16)).slice(-2);
  9786. }
  9787. result += '>';
  9788. return result;
  9789. };
  9790. var ASCIIHexDecode = function ASCIIHexDecode(value) {
  9791. var regexCheckIfHex = new RegExp(/^([0-9A-Fa-f]{2})+$/);
  9792. value = value.replace(/\s/g, '');
  9793. if (value.indexOf(">") !== -1) {
  9794. value = value.substr(0, value.indexOf(">"));
  9795. }
  9796. if (value.length % 2) {
  9797. value += "0";
  9798. }
  9799. if (regexCheckIfHex.test(value) === false) {
  9800. return "";
  9801. }
  9802. var result = '';
  9803. var i;
  9804. for (var i = 0; i < value.length; i += 2) {
  9805. result += String.fromCharCode("0x" + (value[i] + value[i + 1]));
  9806. }
  9807. return result;
  9808. };
  9809. var FlateEncode = function FlateEncode(data, options) {
  9810. options = Object.assign({
  9811. predictor: 1,
  9812. colors: 1,
  9813. bitsPerComponent: 8,
  9814. columns: 1
  9815. }, options);
  9816. var arr = [];
  9817. var i = data.length;
  9818. var adler32;
  9819. var deflater;
  9820. while (i--) {
  9821. arr[i] = data.charCodeAt(i);
  9822. }
  9823. adler32 = jsPDFAPI.adler32cs.from(data);
  9824. deflater = new Deflater(6);
  9825. deflater.append(new Uint8Array(arr));
  9826. data = deflater.flush();
  9827. arr = new Uint8Array(data.length + 6);
  9828. arr.set(new Uint8Array([120, 156])), arr.set(data, 2);
  9829. arr.set(new Uint8Array([adler32 & 0xFF, adler32 >> 8 & 0xFF, adler32 >> 16 & 0xFF, adler32 >> 24 & 0xFF]), data.length + 2);
  9830. data = String.fromCharCode.apply(null, arr);
  9831. return data;
  9832. };
  9833. jsPDFAPI.processDataByFilters = function (origData, filterChain) {
  9834. var i = 0;
  9835. var data = origData || '';
  9836. var reverseChain = [];
  9837. filterChain = filterChain || [];
  9838. if (typeof filterChain === "string") {
  9839. filterChain = [filterChain];
  9840. }
  9841. for (i = 0; i < filterChain.length; i += 1) {
  9842. switch (filterChain[i]) {
  9843. case "ASCII85Decode":
  9844. case "/ASCII85Decode":
  9845. data = ASCII85Decode(data);
  9846. reverseChain.push("/ASCII85Encode");
  9847. break;
  9848. case "ASCII85Encode":
  9849. case "/ASCII85Encode":
  9850. data = ASCII85Encode(data);
  9851. reverseChain.push("/ASCII85Decode");
  9852. break;
  9853. case "ASCIIHexDecode":
  9854. case "/ASCIIHexDecode":
  9855. data = ASCIIHexDecode(data);
  9856. reverseChain.push("/ASCIIHexEncode");
  9857. break;
  9858. case "ASCIIHexEncode":
  9859. case "/ASCIIHexEncode":
  9860. data = ASCIIHexEncode(data);
  9861. reverseChain.push("/ASCIIHexDecode");
  9862. break;
  9863. case "FlateEncode":
  9864. case "/FlateEncode":
  9865. data = FlateEncode(data);
  9866. reverseChain.push("/FlateDecode");
  9867. break;
  9868. /**
  9869. case "LZWDecode":
  9870. case "/LZWDecode":
  9871. data = LZWDecode(data);
  9872. reverseChain.push("/LZWEncode");
  9873. break;
  9874. case "LZWEncode":
  9875. case "/LZWEncode":
  9876. data = LZWEncode(data);
  9877. reverseChain.push("/LZWDecode");
  9878. break;
  9879. */
  9880. default:
  9881. throw "The filter: \"" + filterChain[i] + "\" is not implemented";
  9882. }
  9883. }
  9884. return {
  9885. data: data,
  9886. reverseChain: reverseChain.reverse().join(" ")
  9887. };
  9888. };
  9889. })(jsPDF.API);
  9890. /**
  9891. * jsPDF fileloading PlugIn
  9892. * Copyright (c) 2018 Aras Abbasi (aras.abbasi@gmail.com)
  9893. *
  9894. * Licensed under the MIT License.
  9895. * http://opensource.org/licenses/mit-license
  9896. */
  9897. /**
  9898. * @name fileloading
  9899. * @module
  9900. */
  9901. (function (jsPDFAPI) {
  9902. /**
  9903. * @name loadFile
  9904. * @function
  9905. * @param {string} url
  9906. * @param {boolean} sync
  9907. * @param {function} callback
  9908. * @returns {string|undefined} result
  9909. */
  9910. jsPDFAPI.loadFile = function (url, sync, callback) {
  9911. sync = sync || true;
  9912. callback = callback || function () {};
  9913. var result;
  9914. var xhr = function xhr(url, sync, callback) {
  9915. var req = new XMLHttpRequest();
  9916. var byteArray = [];
  9917. var i = 0;
  9918. var sanitizeUnicode = function sanitizeUnicode(data) {
  9919. var dataLength = data.length;
  9920. var StringFromCharCode = String.fromCharCode; //Transform Unicode to ASCII
  9921. for (i = 0; i < dataLength; i += 1) {
  9922. byteArray.push(StringFromCharCode(data.charCodeAt(i) & 0xff));
  9923. }
  9924. return byteArray.join("");
  9925. };
  9926. req.open('GET', url, !sync); // XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
  9927. req.overrideMimeType('text\/plain; charset=x-user-defined');
  9928. if (sync === false) {
  9929. req.onload = function () {
  9930. return sanitizeUnicode(this.responseText);
  9931. };
  9932. }
  9933. req.send(null);
  9934. if (req.status !== 200) {
  9935. console.warn('Unable to load file "' + url + '"');
  9936. return;
  9937. }
  9938. if (sync) {
  9939. return sanitizeUnicode(req.responseText);
  9940. }
  9941. };
  9942. try {
  9943. result = xhr(url, sync, callback);
  9944. } catch (e) {
  9945. result = undefined;
  9946. }
  9947. return result;
  9948. };
  9949. /**
  9950. * @name loadImageFile
  9951. * @function
  9952. * @param {string} path
  9953. * @param {boolean} sync
  9954. * @param {function} callback
  9955. */
  9956. jsPDFAPI.loadImageFile = jsPDFAPI.loadFile;
  9957. })(jsPDF.API);
  9958. /**
  9959. * Copyright (c) 2018 Erik Koopmans
  9960. * Released under the MIT License.
  9961. *
  9962. * Licensed under the MIT License.
  9963. * http://opensource.org/licenses/mit-license
  9964. */
  9965. /**
  9966. * jsPDF html PlugIn
  9967. *
  9968. * @name html
  9969. * @module
  9970. */
  9971. (function (jsPDFAPI, global) {
  9972. /**
  9973. * Determine the type of a variable/object.
  9974. *
  9975. * @private
  9976. * @ignore
  9977. */
  9978. var objType = function objType(obj) {
  9979. var type = _typeof(obj);
  9980. if (type === 'undefined') return 'undefined';else if (type === 'string' || obj instanceof String) return 'string';else if (type === 'number' || obj instanceof Number) return 'number';else if (type === 'function' || obj instanceof Function) return 'function';else if (!!obj && obj.constructor === Array) return 'array';else if (obj && obj.nodeType === 1) return 'element';else if (type === 'object') return 'object';else return 'unknown';
  9981. };
  9982. /**
  9983. * Create an HTML element with optional className, innerHTML, and style.
  9984. *
  9985. * @private
  9986. * @ignore
  9987. */
  9988. var createElement = function createElement(tagName, opt) {
  9989. var el = document.createElement(tagName);
  9990. if (opt.className) el.className = opt.className;
  9991. if (opt.innerHTML) {
  9992. el.innerHTML = opt.innerHTML;
  9993. var scripts = el.getElementsByTagName('script');
  9994. for (var i = scripts.length; i-- > 0; null) {
  9995. scripts[i].parentNode.removeChild(scripts[i]);
  9996. }
  9997. }
  9998. for (var key in opt.style) {
  9999. el.style[key] = opt.style[key];
  10000. }
  10001. return el;
  10002. };
  10003. /**
  10004. * Deep-clone a node and preserve contents/properties.
  10005. *
  10006. * @private
  10007. * @ignore
  10008. */
  10009. var cloneNode = function cloneNode(node, javascriptEnabled) {
  10010. // Recursively clone the node.
  10011. var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
  10012. for (var child = node.firstChild; child; child = child.nextSibling) {
  10013. if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') {
  10014. clone.appendChild(cloneNode(child, javascriptEnabled));
  10015. }
  10016. }
  10017. if (node.nodeType === 1) {
  10018. // Preserve contents/properties of special nodes.
  10019. if (node.nodeName === 'CANVAS') {
  10020. clone.width = node.width;
  10021. clone.height = node.height;
  10022. clone.getContext('2d').drawImage(node, 0, 0);
  10023. } else if (node.nodeName === 'TEXTAREA' || node.nodeName === 'SELECT') {
  10024. clone.value = node.value;
  10025. } // Preserve the node's scroll position when it loads.
  10026. clone.addEventListener('load', function () {
  10027. clone.scrollTop = node.scrollTop;
  10028. clone.scrollLeft = node.scrollLeft;
  10029. }, true);
  10030. } // Return the cloned node.
  10031. return clone;
  10032. };
  10033. /* ----- CONSTRUCTOR ----- */
  10034. var Worker = function Worker(opt) {
  10035. // Create the root parent for the proto chain, and the starting Worker.
  10036. var root = Object.assign(Worker.convert(Promise.resolve()), JSON.parse(JSON.stringify(Worker.template)));
  10037. var self = Worker.convert(Promise.resolve(), root); // Set progress, optional settings, and return.
  10038. self = self.setProgress(1, Worker, 1, [Worker]);
  10039. self = self.set(opt);
  10040. return self;
  10041. }; // Boilerplate for subclassing Promise.
  10042. Worker.prototype = Object.create(Promise.prototype);
  10043. Worker.prototype.constructor = Worker; // Converts/casts promises into Workers.
  10044. Worker.convert = function convert(promise, inherit) {
  10045. // Uses prototypal inheritance to receive changes made to ancestors' properties.
  10046. promise.__proto__ = inherit || Worker.prototype;
  10047. return promise;
  10048. };
  10049. Worker.template = {
  10050. prop: {
  10051. src: null,
  10052. container: null,
  10053. overlay: null,
  10054. canvas: null,
  10055. img: null,
  10056. pdf: null,
  10057. pageSize: null,
  10058. callback: function callback() {}
  10059. },
  10060. progress: {
  10061. val: 0,
  10062. state: null,
  10063. n: 0,
  10064. stack: []
  10065. },
  10066. opt: {
  10067. filename: 'file.pdf',
  10068. margin: [0, 0, 0, 0],
  10069. enableLinks: true,
  10070. x: 0,
  10071. y: 0,
  10072. html2canvas: {},
  10073. jsPDF: {}
  10074. }
  10075. };
  10076. /* ----- FROM / TO ----- */
  10077. Worker.prototype.from = function from(src, type) {
  10078. function getType(src) {
  10079. switch (objType(src)) {
  10080. case 'string':
  10081. return 'string';
  10082. case 'element':
  10083. return src.nodeName.toLowerCase === 'canvas' ? 'canvas' : 'element';
  10084. default:
  10085. return 'unknown';
  10086. }
  10087. }
  10088. return this.then(function from_main() {
  10089. type = type || getType(src);
  10090. switch (type) {
  10091. case 'string':
  10092. return this.set({
  10093. src: createElement('div', {
  10094. innerHTML: src
  10095. })
  10096. });
  10097. case 'element':
  10098. return this.set({
  10099. src: src
  10100. });
  10101. case 'canvas':
  10102. return this.set({
  10103. canvas: src
  10104. });
  10105. case 'img':
  10106. return this.set({
  10107. img: src
  10108. });
  10109. default:
  10110. return this.error('Unknown source type.');
  10111. }
  10112. });
  10113. };
  10114. Worker.prototype.to = function to(target) {
  10115. // Route the 'to' request to the appropriate method.
  10116. switch (target) {
  10117. case 'container':
  10118. return this.toContainer();
  10119. case 'canvas':
  10120. return this.toCanvas();
  10121. case 'img':
  10122. return this.toImg();
  10123. case 'pdf':
  10124. return this.toPdf();
  10125. default:
  10126. return this.error('Invalid target.');
  10127. }
  10128. };
  10129. Worker.prototype.toContainer = function toContainer() {
  10130. // Set up function prerequisites.
  10131. var prereqs = [function checkSrc() {
  10132. return this.prop.src || this.error('Cannot duplicate - no source HTML.');
  10133. }, function checkPageSize() {
  10134. return this.prop.pageSize || this.setPageSize();
  10135. }];
  10136. return this.thenList(prereqs).then(function toContainer_main() {
  10137. // Define the CSS styles for the container and its overlay parent.
  10138. var overlayCSS = {
  10139. position: 'fixed',
  10140. overflow: 'hidden',
  10141. zIndex: 1000,
  10142. left: '-100000px',
  10143. right: 0,
  10144. bottom: 0,
  10145. top: 0
  10146. };
  10147. var containerCSS = {
  10148. position: 'relative',
  10149. display: 'inline-block',
  10150. width: Math.max(this.prop.src.clientWidth, this.prop.src.scrollWidth, this.prop.src.offsetWidth) + 'px',
  10151. left: 0,
  10152. right: 0,
  10153. top: 0,
  10154. margin: 'auto',
  10155. backgroundColor: 'white'
  10156. }; // Set the overlay to hidden (could be changed in the future to provide a print preview).
  10157. var source = cloneNode(this.prop.src, this.opt.html2canvas.javascriptEnabled);
  10158. if (source.tagName === 'BODY') {
  10159. containerCSS.height = Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight) + 'px';
  10160. }
  10161. this.prop.overlay = createElement('div', {
  10162. className: 'html2pdf__overlay',
  10163. style: overlayCSS
  10164. });
  10165. this.prop.container = createElement('div', {
  10166. className: 'html2pdf__container',
  10167. style: containerCSS
  10168. });
  10169. this.prop.container.appendChild(source);
  10170. this.prop.container.firstChild.appendChild(createElement('div', {
  10171. style: {
  10172. clear: 'both',
  10173. border: '0 none transparent',
  10174. margin: 0,
  10175. padding: 0,
  10176. height: 0
  10177. }
  10178. }));
  10179. this.prop.container.style.float = 'none';
  10180. this.prop.overlay.appendChild(this.prop.container);
  10181. document.body.appendChild(this.prop.overlay);
  10182. this.prop.container.firstChild.style.position = 'relative';
  10183. this.prop.container.height = Math.max(this.prop.container.firstChild.clientHeight, this.prop.container.firstChild.scrollHeight, this.prop.container.firstChild.offsetHeight) + 'px';
  10184. });
  10185. };
  10186. Worker.prototype.toCanvas = function toCanvas() {
  10187. // Set up function prerequisites.
  10188. var prereqs = [function checkContainer() {
  10189. return document.body.contains(this.prop.container) || this.toContainer();
  10190. }]; // Fulfill prereqs then create the canvas.
  10191. return this.thenList(prereqs).then(function toCanvas_main() {
  10192. // Handle old-fashioned 'onrendered' argument.
  10193. var options = Object.assign({}, this.opt.html2canvas);
  10194. delete options.onrendered;
  10195. if (!this.isHtml2CanvasLoaded()) {
  10196. return;
  10197. }
  10198. return html2canvas(this.prop.container, options);
  10199. }).then(function toCanvas_post(canvas) {
  10200. // Handle old-fashioned 'onrendered' argument.
  10201. var onRendered = this.opt.html2canvas.onrendered || function () {};
  10202. onRendered(canvas);
  10203. this.prop.canvas = canvas;
  10204. document.body.removeChild(this.prop.overlay);
  10205. });
  10206. };
  10207. Worker.prototype.toContext2d = function toContext2d() {
  10208. // Set up function prerequisites.
  10209. var prereqs = [function checkContainer() {
  10210. return document.body.contains(this.prop.container) || this.toContainer();
  10211. }]; // Fulfill prereqs then create the canvas.
  10212. return this.thenList(prereqs).then(function toContext2d_main() {
  10213. // Handle old-fashioned 'onrendered' argument.
  10214. var pdf = this.opt.jsPDF;
  10215. var options = Object.assign({
  10216. async: true,
  10217. allowTaint: true,
  10218. backgroundColor: '#ffffff',
  10219. imageTimeout: 15000,
  10220. logging: true,
  10221. proxy: null,
  10222. removeContainer: true,
  10223. foreignObjectRendering: false,
  10224. useCORS: false
  10225. }, this.opt.html2canvas);
  10226. delete options.onrendered;
  10227. pdf.context2d.autoPaging = true;
  10228. pdf.context2d.posX = this.opt.x;
  10229. pdf.context2d.posY = this.opt.y;
  10230. options.windowHeight = options.windowHeight || 0;
  10231. options.windowHeight = options.windowHeight == 0 ? Math.max(this.prop.container.clientHeight, this.prop.container.scrollHeight, this.prop.container.offsetHeight) : options.windowHeight;
  10232. if (!this.isHtml2CanvasLoaded()) {
  10233. return;
  10234. }
  10235. return html2canvas(this.prop.container, options);
  10236. }).then(function toContext2d_post(canvas) {
  10237. // Handle old-fashioned 'onrendered' argument.
  10238. var onRendered = this.opt.html2canvas.onrendered || function () {};
  10239. onRendered(canvas);
  10240. this.prop.canvas = canvas;
  10241. document.body.removeChild(this.prop.overlay);
  10242. });
  10243. };
  10244. Worker.prototype.toImg = function toImg() {
  10245. // Set up function prerequisites.
  10246. var prereqs = [function checkCanvas() {
  10247. return this.prop.canvas || this.toCanvas();
  10248. }]; // Fulfill prereqs then create the image.
  10249. return this.thenList(prereqs).then(function toImg_main() {
  10250. var imgData = this.prop.canvas.toDataURL('image/' + this.opt.image.type, this.opt.image.quality);
  10251. this.prop.img = document.createElement('img');
  10252. this.prop.img.src = imgData;
  10253. });
  10254. };
  10255. Worker.prototype.toPdf = function toPdf() {
  10256. // Set up function prerequisites.
  10257. var prereqs = [function checkContext2d() {
  10258. return this.toContext2d();
  10259. } //function checkCanvas() { return this.prop.canvas || this.toCanvas(); }
  10260. ]; // Fulfill prereqs then create the image.
  10261. return this.thenList(prereqs).then(function toPdf_main() {
  10262. // Create local copies of frequently used properties.
  10263. this.prop.pdf = this.prop.pdf || this.opt.jsPDF;
  10264. });
  10265. };
  10266. /* ----- OUTPUT / SAVE ----- */
  10267. Worker.prototype.output = function output(type, options, src) {
  10268. // Redirect requests to the correct function (outputPdf / outputImg).
  10269. src = src || 'pdf';
  10270. if (src.toLowerCase() === 'img' || src.toLowerCase() === 'image') {
  10271. return this.outputImg(type, options);
  10272. } else {
  10273. return this.outputPdf(type, options);
  10274. }
  10275. };
  10276. Worker.prototype.outputPdf = function outputPdf(type, options) {
  10277. // Set up function prerequisites.
  10278. var prereqs = [function checkPdf() {
  10279. return this.prop.pdf || this.toPdf();
  10280. }]; // Fulfill prereqs then perform the appropriate output.
  10281. return this.thenList(prereqs).then(function outputPdf_main() {
  10282. /* Currently implemented output types:
  10283. * https://rawgit.com/MrRio/jsPDF/master/docs/jspdf.js.html#line992
  10284. * save(options), arraybuffer, blob, bloburi/bloburl,
  10285. * datauristring/dataurlstring, dataurlnewwindow, datauri/dataurl
  10286. */
  10287. return this.prop.pdf.output(type, options);
  10288. });
  10289. };
  10290. Worker.prototype.outputImg = function outputImg(type, options) {
  10291. // Set up function prerequisites.
  10292. var prereqs = [function checkImg() {
  10293. return this.prop.img || this.toImg();
  10294. }]; // Fulfill prereqs then perform the appropriate output.
  10295. return this.thenList(prereqs).then(function outputImg_main() {
  10296. switch (type) {
  10297. case undefined:
  10298. case 'img':
  10299. return this.prop.img;
  10300. case 'datauristring':
  10301. case 'dataurlstring':
  10302. return this.prop.img.src;
  10303. case 'datauri':
  10304. case 'dataurl':
  10305. return document.location.href = this.prop.img.src;
  10306. default:
  10307. throw 'Image output type "' + type + '" is not supported.';
  10308. }
  10309. });
  10310. };
  10311. Worker.prototype.isHtml2CanvasLoaded = function () {
  10312. var result = typeof global.html2canvas !== "undefined";
  10313. if (!result) {
  10314. console.error("html2canvas not loaded.");
  10315. }
  10316. return result;
  10317. };
  10318. Worker.prototype.save = function save(filename) {
  10319. // Set up function prerequisites.
  10320. var prereqs = [function checkPdf() {
  10321. return this.prop.pdf || this.toPdf();
  10322. }];
  10323. if (!this.isHtml2CanvasLoaded()) {
  10324. return;
  10325. } // Fulfill prereqs, update the filename (if provided), and save the PDF.
  10326. return this.thenList(prereqs).set(filename ? {
  10327. filename: filename
  10328. } : null).then(function save_main() {
  10329. this.prop.pdf.save(this.opt.filename);
  10330. });
  10331. };
  10332. Worker.prototype.doCallback = function doCallback(filename) {
  10333. // Set up function prerequisites.
  10334. var prereqs = [function checkPdf() {
  10335. return this.prop.pdf || this.toPdf();
  10336. }];
  10337. if (!this.isHtml2CanvasLoaded()) {
  10338. return;
  10339. } // Fulfill prereqs, update the filename (if provided), and save the PDF.
  10340. return this.thenList(prereqs).then(function doCallback_main() {
  10341. this.prop.callback(this.prop.pdf);
  10342. });
  10343. };
  10344. /* ----- SET / GET ----- */
  10345. Worker.prototype.set = function set(opt) {
  10346. // TODO: Implement ordered pairs?
  10347. // Silently ignore invalid or empty input.
  10348. if (objType(opt) !== 'object') {
  10349. return this;
  10350. } // Build an array of setter functions to queue.
  10351. var fns = Object.keys(opt || {}).map(function (key) {
  10352. if (key in Worker.template.prop) {
  10353. // Set pre-defined properties.
  10354. return function set_prop() {
  10355. this.prop[key] = opt[key];
  10356. };
  10357. } else {
  10358. switch (key) {
  10359. case 'margin':
  10360. return this.setMargin.bind(this, opt.margin);
  10361. case 'jsPDF':
  10362. return function set_jsPDF() {
  10363. this.opt.jsPDF = opt.jsPDF;
  10364. return this.setPageSize();
  10365. };
  10366. case 'pageSize':
  10367. return this.setPageSize.bind(this, opt.pageSize);
  10368. default:
  10369. // Set any other properties in opt.
  10370. return function set_opt() {
  10371. this.opt[key] = opt[key];
  10372. };
  10373. }
  10374. }
  10375. }, this); // Set properties within the promise chain.
  10376. return this.then(function set_main() {
  10377. return this.thenList(fns);
  10378. });
  10379. };
  10380. Worker.prototype.get = function get(key, cbk) {
  10381. return this.then(function get_main() {
  10382. // Fetch the requested property, either as a predefined prop or in opt.
  10383. var val = key in Worker.template.prop ? this.prop[key] : this.opt[key];
  10384. return cbk ? cbk(val) : val;
  10385. });
  10386. };
  10387. Worker.prototype.setMargin = function setMargin(margin) {
  10388. return this.then(function setMargin_main() {
  10389. // Parse the margin property.
  10390. switch (objType(margin)) {
  10391. case 'number':
  10392. margin = [margin, margin, margin, margin];
  10393. case 'array':
  10394. if (margin.length === 2) {
  10395. margin = [margin[0], margin[1], margin[0], margin[1]];
  10396. }
  10397. if (margin.length === 4) {
  10398. break;
  10399. }
  10400. default:
  10401. return this.error('Invalid margin array.');
  10402. } // Set the margin property, then update pageSize.
  10403. this.opt.margin = margin;
  10404. }).then(this.setPageSize);
  10405. };
  10406. Worker.prototype.setPageSize = function setPageSize(pageSize) {
  10407. function toPx(val, k) {
  10408. return Math.floor(val * k / 72 * 96);
  10409. }
  10410. return this.then(function setPageSize_main() {
  10411. // Retrieve page-size based on jsPDF settings, if not explicitly provided.
  10412. pageSize = pageSize || jsPDF.getPageSize(this.opt.jsPDF); // Add 'inner' field if not present.
  10413. if (!pageSize.hasOwnProperty('inner')) {
  10414. pageSize.inner = {
  10415. width: pageSize.width - this.opt.margin[1] - this.opt.margin[3],
  10416. height: pageSize.height - this.opt.margin[0] - this.opt.margin[2]
  10417. };
  10418. pageSize.inner.px = {
  10419. width: toPx(pageSize.inner.width, pageSize.k),
  10420. height: toPx(pageSize.inner.height, pageSize.k)
  10421. };
  10422. pageSize.inner.ratio = pageSize.inner.height / pageSize.inner.width;
  10423. } // Attach pageSize to this.
  10424. this.prop.pageSize = pageSize;
  10425. });
  10426. };
  10427. Worker.prototype.setProgress = function setProgress(val, state, n, stack) {
  10428. // Immediately update all progress values.
  10429. if (val != null) this.progress.val = val;
  10430. if (state != null) this.progress.state = state;
  10431. if (n != null) this.progress.n = n;
  10432. if (stack != null) this.progress.stack = stack;
  10433. this.progress.ratio = this.progress.val / this.progress.state; // Return this for command chaining.
  10434. return this;
  10435. };
  10436. Worker.prototype.updateProgress = function updateProgress(val, state, n, stack) {
  10437. // Immediately update all progress values, using setProgress.
  10438. return this.setProgress(val ? this.progress.val + val : null, state ? state : null, n ? this.progress.n + n : null, stack ? this.progress.stack.concat(stack) : null);
  10439. };
  10440. /* ----- PROMISE MAPPING ----- */
  10441. Worker.prototype.then = function then(onFulfilled, onRejected) {
  10442. // Wrap `this` for encapsulation.
  10443. var self = this;
  10444. return this.thenCore(onFulfilled, onRejected, function then_main(onFulfilled, onRejected) {
  10445. // Update progress while queuing, calling, and resolving `then`.
  10446. self.updateProgress(null, null, 1, [onFulfilled]);
  10447. return Promise.prototype.then.call(this, function then_pre(val) {
  10448. self.updateProgress(null, onFulfilled);
  10449. return val;
  10450. }).then(onFulfilled, onRejected).then(function then_post(val) {
  10451. self.updateProgress(1);
  10452. return val;
  10453. });
  10454. });
  10455. };
  10456. Worker.prototype.thenCore = function thenCore(onFulfilled, onRejected, thenBase) {
  10457. // Handle optional thenBase parameter.
  10458. thenBase = thenBase || Promise.prototype.then; // Wrap `this` for encapsulation and bind it to the promise handlers.
  10459. var self = this;
  10460. if (onFulfilled) {
  10461. onFulfilled = onFulfilled.bind(self);
  10462. }
  10463. if (onRejected) {
  10464. onRejected = onRejected.bind(self);
  10465. } // Cast self into a Promise to avoid polyfills recursively defining `then`.
  10466. var isNative = Promise.toString().indexOf('[native code]') !== -1 && Promise.name === 'Promise';
  10467. var selfPromise = isNative ? self : Worker.convert(Object.assign({}, self), Promise.prototype); // Return the promise, after casting it into a Worker and preserving props.
  10468. var returnVal = thenBase.call(selfPromise, onFulfilled, onRejected);
  10469. return Worker.convert(returnVal, self.__proto__);
  10470. };
  10471. Worker.prototype.thenExternal = function thenExternal(onFulfilled, onRejected) {
  10472. // Call `then` and return a standard promise (exits the Worker chain).
  10473. return Promise.prototype.then.call(this, onFulfilled, onRejected);
  10474. };
  10475. Worker.prototype.thenList = function thenList(fns) {
  10476. // Queue a series of promise 'factories' into the promise chain.
  10477. var self = this;
  10478. fns.forEach(function thenList_forEach(fn) {
  10479. self = self.thenCore(fn);
  10480. });
  10481. return self;
  10482. };
  10483. Worker.prototype['catch'] = function (onRejected) {
  10484. // Bind `this` to the promise handler, call `catch`, and return a Worker.
  10485. if (onRejected) {
  10486. onRejected = onRejected.bind(this);
  10487. }
  10488. var returnVal = Promise.prototype['catch'].call(this, onRejected);
  10489. return Worker.convert(returnVal, this);
  10490. };
  10491. Worker.prototype.catchExternal = function catchExternal(onRejected) {
  10492. // Call `catch` and return a standard promise (exits the Worker chain).
  10493. return Promise.prototype['catch'].call(this, onRejected);
  10494. };
  10495. Worker.prototype.error = function error(msg) {
  10496. // Throw the error in the Promise chain.
  10497. return this.then(function error_main() {
  10498. throw new Error(msg);
  10499. });
  10500. };
  10501. /* ----- ALIASES ----- */
  10502. Worker.prototype.using = Worker.prototype.set;
  10503. Worker.prototype.saveAs = Worker.prototype.save;
  10504. Worker.prototype.export = Worker.prototype.output;
  10505. Worker.prototype.run = Worker.prototype.then; // Get dimensions of a PDF page, as determined by jsPDF.
  10506. jsPDF.getPageSize = function (orientation, unit, format) {
  10507. // Decode options object
  10508. if (_typeof(orientation) === 'object') {
  10509. var options = orientation;
  10510. orientation = options.orientation;
  10511. unit = options.unit || unit;
  10512. format = options.format || format;
  10513. } // Default options
  10514. unit = unit || 'mm';
  10515. format = format || 'a4';
  10516. orientation = ('' + (orientation || 'P')).toLowerCase();
  10517. var format_as_string = ('' + format).toLowerCase(); // Size in pt of various paper formats
  10518. var pageFormats = {
  10519. 'a0': [2383.94, 3370.39],
  10520. 'a1': [1683.78, 2383.94],
  10521. 'a2': [1190.55, 1683.78],
  10522. 'a3': [841.89, 1190.55],
  10523. 'a4': [595.28, 841.89],
  10524. 'a5': [419.53, 595.28],
  10525. 'a6': [297.64, 419.53],
  10526. 'a7': [209.76, 297.64],
  10527. 'a8': [147.40, 209.76],
  10528. 'a9': [104.88, 147.40],
  10529. 'a10': [73.70, 104.88],
  10530. 'b0': [2834.65, 4008.19],
  10531. 'b1': [2004.09, 2834.65],
  10532. 'b2': [1417.32, 2004.09],
  10533. 'b3': [1000.63, 1417.32],
  10534. 'b4': [708.66, 1000.63],
  10535. 'b5': [498.90, 708.66],
  10536. 'b6': [354.33, 498.90],
  10537. 'b7': [249.45, 354.33],
  10538. 'b8': [175.75, 249.45],
  10539. 'b9': [124.72, 175.75],
  10540. 'b10': [87.87, 124.72],
  10541. 'c0': [2599.37, 3676.54],
  10542. 'c1': [1836.85, 2599.37],
  10543. 'c2': [1298.27, 1836.85],
  10544. 'c3': [918.43, 1298.27],
  10545. 'c4': [649.13, 918.43],
  10546. 'c5': [459.21, 649.13],
  10547. 'c6': [323.15, 459.21],
  10548. 'c7': [229.61, 323.15],
  10549. 'c8': [161.57, 229.61],
  10550. 'c9': [113.39, 161.57],
  10551. 'c10': [79.37, 113.39],
  10552. 'dl': [311.81, 623.62],
  10553. 'letter': [612, 792],
  10554. 'government-letter': [576, 756],
  10555. 'legal': [612, 1008],
  10556. 'junior-legal': [576, 360],
  10557. 'ledger': [1224, 792],
  10558. 'tabloid': [792, 1224],
  10559. 'credit-card': [153, 243]
  10560. }; // Unit conversion
  10561. switch (unit) {
  10562. case 'pt':
  10563. var k = 1;
  10564. break;
  10565. case 'mm':
  10566. var k = 72 / 25.4;
  10567. break;
  10568. case 'cm':
  10569. var k = 72 / 2.54;
  10570. break;
  10571. case 'in':
  10572. var k = 72;
  10573. break;
  10574. case 'px':
  10575. var k = 72 / 96;
  10576. break;
  10577. case 'pc':
  10578. var k = 12;
  10579. break;
  10580. case 'em':
  10581. var k = 12;
  10582. break;
  10583. case 'ex':
  10584. var k = 6;
  10585. break;
  10586. default:
  10587. throw 'Invalid unit: ' + unit;
  10588. } // Dimensions are stored as user units and converted to points on output
  10589. if (pageFormats.hasOwnProperty(format_as_string)) {
  10590. var pageHeight = pageFormats[format_as_string][1] / k;
  10591. var pageWidth = pageFormats[format_as_string][0] / k;
  10592. } else {
  10593. try {
  10594. var pageHeight = format[1];
  10595. var pageWidth = format[0];
  10596. } catch (err) {
  10597. throw new Error('Invalid format: ' + format);
  10598. }
  10599. } // Handle page orientation
  10600. if (orientation === 'p' || orientation === 'portrait') {
  10601. orientation = 'p';
  10602. if (pageWidth > pageHeight) {
  10603. var tmp = pageWidth;
  10604. pageWidth = pageHeight;
  10605. pageHeight = tmp;
  10606. }
  10607. } else if (orientation === 'l' || orientation === 'landscape') {
  10608. orientation = 'l';
  10609. if (pageHeight > pageWidth) {
  10610. var tmp = pageWidth;
  10611. pageWidth = pageHeight;
  10612. pageHeight = tmp;
  10613. }
  10614. } else {
  10615. throw 'Invalid orientation: ' + orientation;
  10616. } // Return information (k is the unit conversion ratio from pts)
  10617. var info = {
  10618. 'width': pageWidth,
  10619. 'height': pageHeight,
  10620. 'unit': unit,
  10621. 'k': k
  10622. };
  10623. return info;
  10624. };
  10625. /**
  10626. * Generate a PDF from an HTML element or string using.
  10627. *
  10628. * @name html
  10629. * @function
  10630. * @param {Element|string} source The source element or HTML string.
  10631. * @param {Object=} options An object of optional settings.
  10632. * @description The Plugin needs html2canvas from niklasvh
  10633. */
  10634. jsPDFAPI.html = function (src, options) {
  10635. options = options || {};
  10636. options.callback = options.callback || function () {};
  10637. options.html2canvas = options.html2canvas || {};
  10638. options.html2canvas.canvas = options.html2canvas.canvas || this.canvas;
  10639. options.jsPDF = options.jsPDF || this; // Create a new worker with the given options.
  10640. var pdf = options.jsPDF;
  10641. var worker = new Worker(options);
  10642. if (!options.worker) {
  10643. // If worker is not set to true, perform the traditional 'simple' operation.
  10644. return worker.from(src).doCallback();
  10645. } else {
  10646. // Otherwise, return the worker for new Promise-based operation.
  10647. return worker;
  10648. }
  10649. return this;
  10650. };
  10651. })(jsPDF.API, typeof window !== "undefined" && window || typeof global !== "undefined" && global);
  10652. /**
  10653. * @license
  10654. * ====================================================================
  10655. * Copyright (c) 2013 Youssef Beddad, youssef.beddad@gmail.com
  10656. *
  10657. *
  10658. * ====================================================================
  10659. */
  10660. /*global jsPDF */
  10661. /**
  10662. * jsPDF JavaScript plugin
  10663. *
  10664. * @name javascript
  10665. * @module
  10666. */
  10667. (function (jsPDFAPI) {
  10668. var jsNamesObj, jsJsObj, text;
  10669. /**
  10670. * @name addJS
  10671. * @function
  10672. * @param {string} javascript The javascript to be embedded into the PDF-file.
  10673. * @returns {jsPDF}
  10674. */
  10675. jsPDFAPI.addJS = function (javascript) {
  10676. text = javascript;
  10677. this.internal.events.subscribe('postPutResources', function (javascript) {
  10678. jsNamesObj = this.internal.newObject();
  10679. this.internal.out('<<');
  10680. this.internal.out('/Names [(EmbeddedJS) ' + (jsNamesObj + 1) + ' 0 R]');
  10681. this.internal.out('>>');
  10682. this.internal.out('endobj');
  10683. jsJsObj = this.internal.newObject();
  10684. this.internal.out('<<');
  10685. this.internal.out('/S /JavaScript');
  10686. this.internal.out('/JS (' + text + ')');
  10687. this.internal.out('>>');
  10688. this.internal.out('endobj');
  10689. });
  10690. this.internal.events.subscribe('putCatalog', function () {
  10691. if (jsNamesObj !== undefined && jsJsObj !== undefined) {
  10692. this.internal.out('/Names <</JavaScript ' + jsNamesObj + ' 0 R>>');
  10693. }
  10694. });
  10695. return this;
  10696. };
  10697. })(jsPDF.API);
  10698. /**
  10699. * @license
  10700. * Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
  10701. *
  10702. * Licensed under the MIT License.
  10703. * http://opensource.org/licenses/mit-license
  10704. */
  10705. (function (jsPDFAPI) {
  10706. jsPDFAPI.events.push(['postPutResources', function () {
  10707. var pdf = this;
  10708. var rx = /^(\d+) 0 obj$/; // Write action goto objects for each page
  10709. // this.outline.destsGoto = [];
  10710. // for (var i = 0; i < totalPages; i++) {
  10711. // var id = pdf.internal.newObject();
  10712. // this.outline.destsGoto.push(id);
  10713. // pdf.internal.write("<</D[" + (i * 2 + 3) + " 0 R /XYZ null
  10714. // null null]/S/GoTo>> endobj");
  10715. // }
  10716. //
  10717. // for (var i = 0; i < dests.length; i++) {
  10718. // pdf.internal.write("(page_" + (i + 1) + ")" + dests[i] + " 0
  10719. // R");
  10720. // }
  10721. //
  10722. if (this.outline.root.children.length > 0) {
  10723. var lines = pdf.outline.render().split(/\r\n/);
  10724. for (var i = 0; i < lines.length; i++) {
  10725. var line = lines[i];
  10726. var m = rx.exec(line);
  10727. if (m != null) {
  10728. var oid = m[1];
  10729. pdf.internal.newObjectDeferredBegin(oid, false);
  10730. }
  10731. pdf.internal.write(line);
  10732. }
  10733. } // This code will write named destination for each page reference
  10734. // (page_1, etc)
  10735. if (this.outline.createNamedDestinations) {
  10736. var totalPages = this.internal.pages.length; // WARNING: this assumes jsPDF starts on page 3 and pageIDs
  10737. // follow 5, 7, 9, etc
  10738. // Write destination objects for each page
  10739. var dests = [];
  10740. for (var i = 0; i < totalPages; i++) {
  10741. var id = pdf.internal.newObject();
  10742. dests.push(id);
  10743. var info = pdf.internal.getPageInfo(i + 1);
  10744. pdf.internal.write("<< /D[" + info.objId + " 0 R /XYZ null null null]>> endobj");
  10745. } // assign a name for each destination
  10746. var names2Oid = pdf.internal.newObject();
  10747. pdf.internal.write('<< /Names [ ');
  10748. for (var i = 0; i < dests.length; i++) {
  10749. pdf.internal.write("(page_" + (i + 1) + ")" + dests[i] + " 0 R");
  10750. }
  10751. pdf.internal.write(' ] >>', 'endobj'); // var kids = pdf.internal.newObject();
  10752. // pdf.internal.write('<< /Kids [ ' + names2Oid + ' 0 R');
  10753. // pdf.internal.write(' ] >>', 'endobj');
  10754. var namesOid = pdf.internal.newObject();
  10755. pdf.internal.write('<< /Dests ' + names2Oid + " 0 R");
  10756. pdf.internal.write('>>', 'endobj');
  10757. }
  10758. }]);
  10759. jsPDFAPI.events.push(['putCatalog', function () {
  10760. var pdf = this;
  10761. if (pdf.outline.root.children.length > 0) {
  10762. pdf.internal.write("/Outlines", this.outline.makeRef(this.outline.root));
  10763. if (this.outline.createNamedDestinations) {
  10764. pdf.internal.write("/Names " + namesOid + " 0 R");
  10765. } // Open with Bookmarks showing
  10766. // pdf.internal.write("/PageMode /UseOutlines");
  10767. }
  10768. }]);
  10769. jsPDFAPI.events.push(['initialized', function () {
  10770. var pdf = this;
  10771. pdf.outline = {
  10772. createNamedDestinations: false,
  10773. root: {
  10774. children: []
  10775. }
  10776. };
  10777. /**
  10778. * Options: pageNumber
  10779. */
  10780. pdf.outline.add = function (parent, title, options) {
  10781. var item = {
  10782. title: title,
  10783. options: options,
  10784. children: []
  10785. };
  10786. if (parent == null) {
  10787. parent = this.root;
  10788. }
  10789. parent.children.push(item);
  10790. return item;
  10791. };
  10792. pdf.outline.render = function () {
  10793. this.ctx = {};
  10794. this.ctx.val = '';
  10795. this.ctx.pdf = pdf;
  10796. this.genIds_r(this.root);
  10797. this.renderRoot(this.root);
  10798. this.renderItems(this.root);
  10799. return this.ctx.val;
  10800. };
  10801. pdf.outline.genIds_r = function (node) {
  10802. node.id = pdf.internal.newObjectDeferred();
  10803. for (var i = 0; i < node.children.length; i++) {
  10804. this.genIds_r(node.children[i]);
  10805. }
  10806. };
  10807. pdf.outline.renderRoot = function (node) {
  10808. this.objStart(node);
  10809. this.line('/Type /Outlines');
  10810. if (node.children.length > 0) {
  10811. this.line('/First ' + this.makeRef(node.children[0]));
  10812. this.line('/Last ' + this.makeRef(node.children[node.children.length - 1]));
  10813. }
  10814. this.line('/Count ' + this.count_r({
  10815. count: 0
  10816. }, node));
  10817. this.objEnd();
  10818. };
  10819. pdf.outline.renderItems = function (node) {
  10820. var getHorizontalCoordinateString = this.ctx.pdf.internal.getCoordinateString;
  10821. var getVerticalCoordinateString = this.ctx.pdf.internal.getVerticalCoordinateString;
  10822. for (var i = 0; i < node.children.length; i++) {
  10823. var item = node.children[i];
  10824. this.objStart(item);
  10825. this.line('/Title ' + this.makeString(item.title));
  10826. this.line('/Parent ' + this.makeRef(node));
  10827. if (i > 0) {
  10828. this.line('/Prev ' + this.makeRef(node.children[i - 1]));
  10829. }
  10830. if (i < node.children.length - 1) {
  10831. this.line('/Next ' + this.makeRef(node.children[i + 1]));
  10832. }
  10833. if (item.children.length > 0) {
  10834. this.line('/First ' + this.makeRef(item.children[0]));
  10835. this.line('/Last ' + this.makeRef(item.children[item.children.length - 1]));
  10836. }
  10837. var count = this.count = this.count_r({
  10838. count: 0
  10839. }, item);
  10840. if (count > 0) {
  10841. this.line('/Count ' + count);
  10842. }
  10843. if (item.options) {
  10844. if (item.options.pageNumber) {
  10845. // Explicit Destination
  10846. //WARNING this assumes page ids are 3,5,7, etc.
  10847. var info = pdf.internal.getPageInfo(item.options.pageNumber);
  10848. this.line('/Dest ' + '[' + info.objId + ' 0 R /XYZ 0 ' + getVerticalCoordinateString(0) + ' 0]'); // this line does not work on all clients (pageNumber instead of page ref)
  10849. //this.line('/Dest ' + '[' + (item.options.pageNumber - 1) + ' /XYZ 0 ' + this.ctx.pdf.internal.pageSize.getHeight() + ' 0]');
  10850. // Named Destination
  10851. // this.line('/Dest (page_' + (item.options.pageNumber) + ')');
  10852. // Action Destination
  10853. // var id = pdf.internal.newObject();
  10854. // pdf.internal.write('<</D[' + (item.options.pageNumber - 1) + ' /XYZ null null null]/S/GoTo>> endobj');
  10855. // this.line('/A ' + id + ' 0 R' );
  10856. }
  10857. }
  10858. this.objEnd();
  10859. }
  10860. for (var i = 0; i < node.children.length; i++) {
  10861. var item = node.children[i];
  10862. this.renderItems(item);
  10863. }
  10864. };
  10865. pdf.outline.line = function (text) {
  10866. this.ctx.val += text + '\r\n';
  10867. };
  10868. pdf.outline.makeRef = function (node) {
  10869. return node.id + ' 0 R';
  10870. };
  10871. pdf.outline.makeString = function (val) {
  10872. return '(' + pdf.internal.pdfEscape(val) + ')';
  10873. };
  10874. pdf.outline.objStart = function (node) {
  10875. this.ctx.val += '\r\n' + node.id + ' 0 obj' + '\r\n<<\r\n';
  10876. };
  10877. pdf.outline.objEnd = function (node) {
  10878. this.ctx.val += '>> \r\n' + 'endobj' + '\r\n';
  10879. };
  10880. pdf.outline.count_r = function (ctx, node) {
  10881. for (var i = 0; i < node.children.length; i++) {
  10882. ctx.count++;
  10883. this.count_r(ctx, node.children[i]);
  10884. }
  10885. return ctx.count;
  10886. };
  10887. }]);
  10888. return this;
  10889. })(jsPDF.API);
  10890. /**
  10891. * @license
  10892. *
  10893. * Copyright (c) 2014 James Robb, https://github.com/jamesbrobb
  10894. *
  10895. *
  10896. * ====================================================================
  10897. */
  10898. /**
  10899. * jsPDF PNG PlugIn
  10900. * @name png_support
  10901. * @module
  10902. */
  10903. (function (jsPDFAPI) {
  10904. /*
  10905. * @see http://www.w3.org/TR/PNG-Chunks.html
  10906. *
  10907. Color Allowed Interpretation
  10908. Type Bit Depths
  10909. 0 1,2,4,8,16 Each pixel is a grayscale sample.
  10910. 2 8,16 Each pixel is an R,G,B triple.
  10911. 3 1,2,4,8 Each pixel is a palette index;
  10912. a PLTE chunk must appear.
  10913. 4 8,16 Each pixel is a grayscale sample,
  10914. followed by an alpha sample.
  10915. 6 8,16 Each pixel is an R,G,B triple,
  10916. followed by an alpha sample.
  10917. */
  10918. /*
  10919. * PNG filter method types
  10920. *
  10921. * @see http://www.w3.org/TR/PNG-Filters.html
  10922. * @see http://www.libpng.org/pub/png/book/chapter09.html
  10923. *
  10924. * This is what the value 'Predictor' in decode params relates to
  10925. *
  10926. * 15 is "optimal prediction", which means the prediction algorithm can change from line to line.
  10927. * In that case, you actually have to read the first byte off each line for the prediction algorthim (which should be 0-4, corresponding to PDF 10-14) and select the appropriate unprediction algorithm based on that byte.
  10928. *
  10929. 0 None
  10930. 1 Sub
  10931. 2 Up
  10932. 3 Average
  10933. 4 Paeth
  10934. */
  10935. var doesNotHavePngJS = function doesNotHavePngJS() {
  10936. return typeof PNG !== 'function' || typeof FlateStream !== 'function';
  10937. },
  10938. canCompress = function canCompress(value) {
  10939. return value !== jsPDFAPI.image_compression.NONE && hasCompressionJS();
  10940. },
  10941. hasCompressionJS = function hasCompressionJS() {
  10942. var inst = typeof Deflater === 'function';
  10943. if (!inst) throw new Error("requires deflate.js for compression");
  10944. return inst;
  10945. },
  10946. compressBytes = function compressBytes(bytes, lineLength, colorsPerPixel, compression) {
  10947. var level = 5,
  10948. filter_method = filterUp;
  10949. switch (compression) {
  10950. case jsPDFAPI.image_compression.FAST:
  10951. level = 3;
  10952. filter_method = filterSub;
  10953. break;
  10954. case jsPDFAPI.image_compression.MEDIUM:
  10955. level = 6;
  10956. filter_method = filterAverage;
  10957. break;
  10958. case jsPDFAPI.image_compression.SLOW:
  10959. level = 9;
  10960. filter_method = filterPaeth; //uses to sum to choose best filter for each line
  10961. break;
  10962. }
  10963. bytes = applyPngFilterMethod(bytes, lineLength, colorsPerPixel, filter_method);
  10964. var header = new Uint8Array(createZlibHeader(level));
  10965. var checksum = adler32(bytes);
  10966. var deflate = new Deflater(level);
  10967. var a = deflate.append(bytes);
  10968. var cBytes = deflate.flush();
  10969. var len = header.length + a.length + cBytes.length;
  10970. var cmpd = new Uint8Array(len + 4);
  10971. cmpd.set(header);
  10972. cmpd.set(a, header.length);
  10973. cmpd.set(cBytes, header.length + a.length);
  10974. cmpd[len++] = checksum >>> 24 & 0xff;
  10975. cmpd[len++] = checksum >>> 16 & 0xff;
  10976. cmpd[len++] = checksum >>> 8 & 0xff;
  10977. cmpd[len++] = checksum & 0xff;
  10978. return jsPDFAPI.arrayBufferToBinaryString(cmpd);
  10979. },
  10980. createZlibHeader = function createZlibHeader(bytes, level) {
  10981. /*
  10982. * @see http://www.ietf.org/rfc/rfc1950.txt for zlib header
  10983. */
  10984. var cm = 8;
  10985. var cinfo = Math.LOG2E * Math.log(0x8000) - 8;
  10986. var cmf = cinfo << 4 | cm;
  10987. var hdr = cmf << 8;
  10988. var flevel = Math.min(3, (level - 1 & 0xff) >> 1);
  10989. hdr |= flevel << 6;
  10990. hdr |= 0; //FDICT
  10991. hdr += 31 - hdr % 31;
  10992. return [cmf, hdr & 0xff & 0xff];
  10993. },
  10994. adler32 = function adler32(array, param) {
  10995. var adler = 1;
  10996. var s1 = adler & 0xffff,
  10997. s2 = adler >>> 16 & 0xffff;
  10998. var len = array.length;
  10999. var tlen;
  11000. var i = 0;
  11001. while (len > 0) {
  11002. tlen = len > param ? param : len;
  11003. len -= tlen;
  11004. do {
  11005. s1 += array[i++];
  11006. s2 += s1;
  11007. } while (--tlen);
  11008. s1 %= 65521;
  11009. s2 %= 65521;
  11010. }
  11011. return (s2 << 16 | s1) >>> 0;
  11012. },
  11013. applyPngFilterMethod = function applyPngFilterMethod(bytes, lineLength, colorsPerPixel, filter_method) {
  11014. var lines = bytes.length / lineLength,
  11015. result = new Uint8Array(bytes.length + lines),
  11016. filter_methods = getFilterMethods(),
  11017. i = 0,
  11018. line,
  11019. prevLine,
  11020. offset;
  11021. for (; i < lines; i++) {
  11022. offset = i * lineLength;
  11023. line = bytes.subarray(offset, offset + lineLength);
  11024. if (filter_method) {
  11025. result.set(filter_method(line, colorsPerPixel, prevLine), offset + i);
  11026. } else {
  11027. var j = 0,
  11028. len = filter_methods.length,
  11029. results = [];
  11030. for (; j < len; j++) {
  11031. results[j] = filter_methods[j](line, colorsPerPixel, prevLine);
  11032. }
  11033. var ind = getIndexOfSmallestSum(results.concat());
  11034. result.set(results[ind], offset + i);
  11035. }
  11036. prevLine = line;
  11037. }
  11038. return result;
  11039. },
  11040. filterNone = function filterNone(line, colorsPerPixel, prevLine) {
  11041. /*var result = new Uint8Array(line.length + 1);
  11042. result[0] = 0;
  11043. result.set(line, 1);*/
  11044. var result = Array.apply([], line);
  11045. result.unshift(0);
  11046. return result;
  11047. },
  11048. filterSub = function filterSub(line, colorsPerPixel, prevLine) {
  11049. var result = [],
  11050. i = 0,
  11051. len = line.length,
  11052. left;
  11053. result[0] = 1;
  11054. for (; i < len; i++) {
  11055. left = line[i - colorsPerPixel] || 0;
  11056. result[i + 1] = line[i] - left + 0x0100 & 0xff;
  11057. }
  11058. return result;
  11059. },
  11060. filterUp = function filterUp(line, colorsPerPixel, prevLine) {
  11061. var result = [],
  11062. i = 0,
  11063. len = line.length,
  11064. up;
  11065. result[0] = 2;
  11066. for (; i < len; i++) {
  11067. up = prevLine && prevLine[i] || 0;
  11068. result[i + 1] = line[i] - up + 0x0100 & 0xff;
  11069. }
  11070. return result;
  11071. },
  11072. filterAverage = function filterAverage(line, colorsPerPixel, prevLine) {
  11073. var result = [],
  11074. i = 0,
  11075. len = line.length,
  11076. left,
  11077. up;
  11078. result[0] = 3;
  11079. for (; i < len; i++) {
  11080. left = line[i - colorsPerPixel] || 0;
  11081. up = prevLine && prevLine[i] || 0;
  11082. result[i + 1] = line[i] + 0x0100 - (left + up >>> 1) & 0xff;
  11083. }
  11084. return result;
  11085. },
  11086. filterPaeth = function filterPaeth(line, colorsPerPixel, prevLine) {
  11087. var result = [],
  11088. i = 0,
  11089. len = line.length,
  11090. left,
  11091. up,
  11092. upLeft,
  11093. paeth;
  11094. result[0] = 4;
  11095. for (; i < len; i++) {
  11096. left = line[i - colorsPerPixel] || 0;
  11097. up = prevLine && prevLine[i] || 0;
  11098. upLeft = prevLine && prevLine[i - colorsPerPixel] || 0;
  11099. paeth = paethPredictor(left, up, upLeft);
  11100. result[i + 1] = line[i] - paeth + 0x0100 & 0xff;
  11101. }
  11102. return result;
  11103. },
  11104. paethPredictor = function paethPredictor(left, up, upLeft) {
  11105. var p = left + up - upLeft,
  11106. pLeft = Math.abs(p - left),
  11107. pUp = Math.abs(p - up),
  11108. pUpLeft = Math.abs(p - upLeft);
  11109. return pLeft <= pUp && pLeft <= pUpLeft ? left : pUp <= pUpLeft ? up : upLeft;
  11110. },
  11111. getFilterMethods = function getFilterMethods() {
  11112. return [filterNone, filterSub, filterUp, filterAverage, filterPaeth];
  11113. },
  11114. getIndexOfSmallestSum = function getIndexOfSmallestSum(arrays) {
  11115. var i = 0,
  11116. len = arrays.length,
  11117. sum,
  11118. min,
  11119. ind;
  11120. while (i < len) {
  11121. sum = absSum(arrays[i].slice(1));
  11122. if (sum < min || !min) {
  11123. min = sum;
  11124. ind = i;
  11125. }
  11126. i++;
  11127. }
  11128. return ind;
  11129. },
  11130. absSum = function absSum(array) {
  11131. var i = 0,
  11132. len = array.length,
  11133. sum = 0;
  11134. while (i < len) {
  11135. sum += Math.abs(array[i++]);
  11136. }
  11137. return sum;
  11138. },
  11139. getPredictorFromCompression = function getPredictorFromCompression(compression) {
  11140. var predictor;
  11141. switch (compression) {
  11142. case jsPDFAPI.image_compression.FAST:
  11143. predictor = 11;
  11144. break;
  11145. case jsPDFAPI.image_compression.MEDIUM:
  11146. predictor = 13;
  11147. break;
  11148. case jsPDFAPI.image_compression.SLOW:
  11149. predictor = 14;
  11150. break;
  11151. default:
  11152. predictor = 12;
  11153. break;
  11154. }
  11155. return predictor;
  11156. };
  11157. /**
  11158. *
  11159. * @name processPNG
  11160. * @function
  11161. * @ignore
  11162. */
  11163. jsPDFAPI.processPNG = function (imageData, imageIndex, alias, compression, dataAsBinaryString) {
  11164. var colorSpace = this.color_spaces.DEVICE_RGB,
  11165. decode = this.decode.FLATE_DECODE,
  11166. bpc = 8,
  11167. img,
  11168. dp,
  11169. trns,
  11170. colors,
  11171. pal,
  11172. smask;
  11173. /* if(this.isString(imageData)) {
  11174. }*/
  11175. if (this.isArrayBuffer(imageData)) imageData = new Uint8Array(imageData);
  11176. if (this.isArrayBufferView(imageData)) {
  11177. if (doesNotHavePngJS()) throw new Error("PNG support requires png.js and zlib.js");
  11178. img = new PNG(imageData);
  11179. imageData = img.imgData;
  11180. bpc = img.bits;
  11181. colorSpace = img.colorSpace;
  11182. colors = img.colors; //logImg(img);
  11183. /*
  11184. * colorType 6 - Each pixel is an R,G,B triple, followed by an alpha sample.
  11185. *
  11186. * colorType 4 - Each pixel is a grayscale sample, followed by an alpha sample.
  11187. *
  11188. * Extract alpha to create two separate images, using the alpha as a sMask
  11189. */
  11190. if ([4, 6].indexOf(img.colorType) !== -1) {
  11191. /*
  11192. * processes 8 bit RGBA and grayscale + alpha images
  11193. */
  11194. if (img.bits === 8) {
  11195. var pixels = img.pixelBitlength == 32 ? new Uint32Array(img.decodePixels().buffer) : img.pixelBitlength == 16 ? new Uint16Array(img.decodePixels().buffer) : new Uint8Array(img.decodePixels().buffer),
  11196. len = pixels.length,
  11197. imgData = new Uint8Array(len * img.colors),
  11198. alphaData = new Uint8Array(len),
  11199. pDiff = img.pixelBitlength - img.bits,
  11200. i = 0,
  11201. n = 0,
  11202. pixel,
  11203. pbl;
  11204. for (; i < len; i++) {
  11205. pixel = pixels[i];
  11206. pbl = 0;
  11207. while (pbl < pDiff) {
  11208. imgData[n++] = pixel >>> pbl & 0xff;
  11209. pbl = pbl + img.bits;
  11210. }
  11211. alphaData[i] = pixel >>> pbl & 0xff;
  11212. }
  11213. }
  11214. /*
  11215. * processes 16 bit RGBA and grayscale + alpha images
  11216. */
  11217. if (img.bits === 16) {
  11218. var pixels = new Uint32Array(img.decodePixels().buffer),
  11219. len = pixels.length,
  11220. imgData = new Uint8Array(len * (32 / img.pixelBitlength) * img.colors),
  11221. alphaData = new Uint8Array(len * (32 / img.pixelBitlength)),
  11222. hasColors = img.colors > 1,
  11223. i = 0,
  11224. n = 0,
  11225. a = 0,
  11226. pixel;
  11227. while (i < len) {
  11228. pixel = pixels[i++];
  11229. imgData[n++] = pixel >>> 0 & 0xFF;
  11230. if (hasColors) {
  11231. imgData[n++] = pixel >>> 16 & 0xFF;
  11232. pixel = pixels[i++];
  11233. imgData[n++] = pixel >>> 0 & 0xFF;
  11234. }
  11235. alphaData[a++] = pixel >>> 16 & 0xFF;
  11236. }
  11237. bpc = 8;
  11238. }
  11239. if (canCompress(compression)) {
  11240. imageData = compressBytes(imgData, img.width * img.colors, img.colors, compression);
  11241. smask = compressBytes(alphaData, img.width, 1, compression);
  11242. } else {
  11243. imageData = imgData;
  11244. smask = alphaData;
  11245. decode = null;
  11246. }
  11247. }
  11248. /*
  11249. * Indexed png. Each pixel is a palette index.
  11250. */
  11251. if (img.colorType === 3) {
  11252. colorSpace = this.color_spaces.INDEXED;
  11253. pal = img.palette;
  11254. if (img.transparency.indexed) {
  11255. var trans = img.transparency.indexed;
  11256. var total = 0,
  11257. i = 0,
  11258. len = trans.length;
  11259. for (; i < len; ++i) {
  11260. total += trans[i];
  11261. }
  11262. total = total / 255;
  11263. /*
  11264. * a single color is specified as 100% transparent (0),
  11265. * so we set trns to use a /Mask with that index
  11266. */
  11267. if (total === len - 1 && trans.indexOf(0) !== -1) {
  11268. trns = [trans.indexOf(0)];
  11269. /*
  11270. * there's more than one colour within the palette that specifies
  11271. * a transparency value less than 255, so we unroll the pixels to create an image sMask
  11272. */
  11273. } else if (total !== len) {
  11274. var pixels = img.decodePixels(),
  11275. alphaData = new Uint8Array(pixels.length),
  11276. i = 0,
  11277. len = pixels.length;
  11278. for (; i < len; i++) {
  11279. alphaData[i] = trans[pixels[i]];
  11280. }
  11281. smask = compressBytes(alphaData, img.width, 1);
  11282. }
  11283. }
  11284. }
  11285. var predictor = getPredictorFromCompression(compression);
  11286. if (decode === this.decode.FLATE_DECODE) dp = '/Predictor ' + predictor + ' /Colors ' + colors + ' /BitsPerComponent ' + bpc + ' /Columns ' + img.width;else //remove 'Predictor' as it applies to the type of png filter applied to its IDAT - we only apply with compression
  11287. dp = '/Colors ' + colors + ' /BitsPerComponent ' + bpc + ' /Columns ' + img.width;
  11288. if (this.isArrayBuffer(imageData) || this.isArrayBufferView(imageData)) imageData = this.arrayBufferToBinaryString(imageData);
  11289. if (smask && this.isArrayBuffer(smask) || this.isArrayBufferView(smask)) smask = this.arrayBufferToBinaryString(smask);
  11290. return this.createImageInfo(imageData, img.width, img.height, colorSpace, bpc, decode, imageIndex, alias, dp, trns, pal, smask, predictor);
  11291. }
  11292. throw new Error("Unsupported PNG image data, try using JPEG instead.");
  11293. };
  11294. })(jsPDF.API);
  11295. /**
  11296. * @license
  11297. * Copyright (c) 2017 Aras Abbasi
  11298. *
  11299. * Licensed under the MIT License.
  11300. * http://opensource.org/licenses/mit-license
  11301. */
  11302. /**
  11303. * jsPDF gif Support PlugIn
  11304. *
  11305. * @name gif_support
  11306. * @module
  11307. */
  11308. (function (jsPDFAPI) {
  11309. jsPDFAPI.processGIF89A = function (imageData, imageIndex, alias, compression, dataAsBinaryString) {
  11310. var reader = new GifReader(imageData);
  11311. var width = reader.width,
  11312. height = reader.height;
  11313. var qu = 100;
  11314. var pixels = [];
  11315. reader.decodeAndBlitFrameRGBA(0, pixels);
  11316. var rawImageData = {
  11317. data: pixels,
  11318. width: width,
  11319. height: height
  11320. };
  11321. var encoder = new JPEGEncoder(qu);
  11322. var data = encoder.encode(rawImageData, qu);
  11323. return jsPDFAPI.processJPEG.call(this, data, imageIndex, alias, compression);
  11324. };
  11325. jsPDFAPI.processGIF87A = jsPDFAPI.processGIF89A;
  11326. })(jsPDF.API);
  11327. /**
  11328. * Copyright (c) 2018 Aras Abbasi
  11329. *
  11330. * Licensed under the MIT License.
  11331. * http://opensource.org/licenses/mit-license
  11332. */
  11333. /**
  11334. * jsPDF bmp Support PlugIn
  11335. * @name bmp_support
  11336. * @module
  11337. */
  11338. (function (jsPDFAPI) {
  11339. jsPDFAPI.processBMP = function (imageData, imageIndex, alias, compression, dataAsBinaryString) {
  11340. var reader = new BmpDecoder(imageData, false);
  11341. var width = reader.width,
  11342. height = reader.height;
  11343. var qu = 100;
  11344. var pixels = reader.getData();
  11345. var rawImageData = {
  11346. data: pixels,
  11347. width: width,
  11348. height: height
  11349. };
  11350. var encoder = new JPEGEncoder(qu);
  11351. var data = encoder.encode(rawImageData, qu);
  11352. return jsPDFAPI.processJPEG.call(this, data, imageIndex, alias, compression);
  11353. };
  11354. })(jsPDF.API);
  11355. /**
  11356. * @license
  11357. * Licensed under the MIT License.
  11358. * http://opensource.org/licenses/mit-license
  11359. */
  11360. /**
  11361. * jsPDF setLanguage Plugin
  11362. *
  11363. * @name setLanguage
  11364. * @module
  11365. */
  11366. (function (jsPDFAPI) {
  11367. /**
  11368. * Add Language Tag to the generated PDF
  11369. *
  11370. * @name setLanguage
  11371. * @function
  11372. * @param {string} langCode The Language code as ISO-639-1 (e.g. 'en') or as country language code (e.g. 'en-GB').
  11373. * @returns {jsPDF}
  11374. * @example
  11375. * var doc = new jsPDF()
  11376. * doc.text(10, 10, 'This is a test')
  11377. * doc.setLanguage("en-US")
  11378. * doc.save('english.pdf')
  11379. */
  11380. jsPDFAPI.setLanguage = function (langCode) {
  11381. var langCodes = {
  11382. "af": "Afrikaans",
  11383. "sq": "Albanian",
  11384. "ar": "Arabic (Standard)",
  11385. "ar-DZ": "Arabic (Algeria)",
  11386. "ar-BH": "Arabic (Bahrain)",
  11387. "ar-EG": "Arabic (Egypt)",
  11388. "ar-IQ": "Arabic (Iraq)",
  11389. "ar-JO": "Arabic (Jordan)",
  11390. "ar-KW": "Arabic (Kuwait)",
  11391. "ar-LB": "Arabic (Lebanon)",
  11392. "ar-LY": "Arabic (Libya)",
  11393. "ar-MA": "Arabic (Morocco)",
  11394. "ar-OM": "Arabic (Oman)",
  11395. "ar-QA": "Arabic (Qatar)",
  11396. "ar-SA": "Arabic (Saudi Arabia)",
  11397. "ar-SY": "Arabic (Syria)",
  11398. "ar-TN": "Arabic (Tunisia)",
  11399. "ar-AE": "Arabic (U.A.E.)",
  11400. "ar-YE": "Arabic (Yemen)",
  11401. "an": "Aragonese",
  11402. "hy": "Armenian",
  11403. "as": "Assamese",
  11404. "ast": "Asturian",
  11405. "az": "Azerbaijani",
  11406. "eu": "Basque",
  11407. "be": "Belarusian",
  11408. "bn": "Bengali",
  11409. "bs": "Bosnian",
  11410. "br": "Breton",
  11411. "bg": "Bulgarian",
  11412. "my": "Burmese",
  11413. "ca": "Catalan",
  11414. "ch": "Chamorro",
  11415. "ce": "Chechen",
  11416. "zh": "Chinese",
  11417. "zh-HK": "Chinese (Hong Kong)",
  11418. "zh-CN": "Chinese (PRC)",
  11419. "zh-SG": "Chinese (Singapore)",
  11420. "zh-TW": "Chinese (Taiwan)",
  11421. "cv": "Chuvash",
  11422. "co": "Corsican",
  11423. "cr": "Cree",
  11424. "hr": "Croatian",
  11425. "cs": "Czech",
  11426. "da": "Danish",
  11427. "nl": "Dutch (Standard)",
  11428. "nl-BE": "Dutch (Belgian)",
  11429. "en": "English",
  11430. "en-AU": "English (Australia)",
  11431. "en-BZ": "English (Belize)",
  11432. "en-CA": "English (Canada)",
  11433. "en-IE": "English (Ireland)",
  11434. "en-JM": "English (Jamaica)",
  11435. "en-NZ": "English (New Zealand)",
  11436. "en-PH": "English (Philippines)",
  11437. "en-ZA": "English (South Africa)",
  11438. "en-TT": "English (Trinidad & Tobago)",
  11439. "en-GB": "English (United Kingdom)",
  11440. "en-US": "English (United States)",
  11441. "en-ZW": "English (Zimbabwe)",
  11442. "eo": "Esperanto",
  11443. "et": "Estonian",
  11444. "fo": "Faeroese",
  11445. "fj": "Fijian",
  11446. "fi": "Finnish",
  11447. "fr": "French (Standard)",
  11448. "fr-BE": "French (Belgium)",
  11449. "fr-CA": "French (Canada)",
  11450. "fr-FR": "French (France)",
  11451. "fr-LU": "French (Luxembourg)",
  11452. "fr-MC": "French (Monaco)",
  11453. "fr-CH": "French (Switzerland)",
  11454. "fy": "Frisian",
  11455. "fur": "Friulian",
  11456. "gd": "Gaelic (Scots)",
  11457. "gd-IE": "Gaelic (Irish)",
  11458. "gl": "Galacian",
  11459. "ka": "Georgian",
  11460. "de": "German (Standard)",
  11461. "de-AT": "German (Austria)",
  11462. "de-DE": "German (Germany)",
  11463. "de-LI": "German (Liechtenstein)",
  11464. "de-LU": "German (Luxembourg)",
  11465. "de-CH": "German (Switzerland)",
  11466. "el": "Greek",
  11467. "gu": "Gujurati",
  11468. "ht": "Haitian",
  11469. "he": "Hebrew",
  11470. "hi": "Hindi",
  11471. "hu": "Hungarian",
  11472. "is": "Icelandic",
  11473. "id": "Indonesian",
  11474. "iu": "Inuktitut",
  11475. "ga": "Irish",
  11476. "it": "Italian (Standard)",
  11477. "it-CH": "Italian (Switzerland)",
  11478. "ja": "Japanese",
  11479. "kn": "Kannada",
  11480. "ks": "Kashmiri",
  11481. "kk": "Kazakh",
  11482. "km": "Khmer",
  11483. "ky": "Kirghiz",
  11484. "tlh": "Klingon",
  11485. "ko": "Korean",
  11486. "ko-KP": "Korean (North Korea)",
  11487. "ko-KR": "Korean (South Korea)",
  11488. "la": "Latin",
  11489. "lv": "Latvian",
  11490. "lt": "Lithuanian",
  11491. "lb": "Luxembourgish",
  11492. "mk": "FYRO Macedonian",
  11493. "ms": "Malay",
  11494. "ml": "Malayalam",
  11495. "mt": "Maltese",
  11496. "mi": "Maori",
  11497. "mr": "Marathi",
  11498. "mo": "Moldavian",
  11499. "nv": "Navajo",
  11500. "ng": "Ndonga",
  11501. "ne": "Nepali",
  11502. "no": "Norwegian",
  11503. "nb": "Norwegian (Bokmal)",
  11504. "nn": "Norwegian (Nynorsk)",
  11505. "oc": "Occitan",
  11506. "or": "Oriya",
  11507. "om": "Oromo",
  11508. "fa": "Persian",
  11509. "fa-IR": "Persian/Iran",
  11510. "pl": "Polish",
  11511. "pt": "Portuguese",
  11512. "pt-BR": "Portuguese (Brazil)",
  11513. "pa": "Punjabi",
  11514. "pa-IN": "Punjabi (India)",
  11515. "pa-PK": "Punjabi (Pakistan)",
  11516. "qu": "Quechua",
  11517. "rm": "Rhaeto-Romanic",
  11518. "ro": "Romanian",
  11519. "ro-MO": "Romanian (Moldavia)",
  11520. "ru": "Russian",
  11521. "ru-MO": "Russian (Moldavia)",
  11522. "sz": "Sami (Lappish)",
  11523. "sg": "Sango",
  11524. "sa": "Sanskrit",
  11525. "sc": "Sardinian",
  11526. "sd": "Sindhi",
  11527. "si": "Singhalese",
  11528. "sr": "Serbian",
  11529. "sk": "Slovak",
  11530. "sl": "Slovenian",
  11531. "so": "Somani",
  11532. "sb": "Sorbian",
  11533. "es": "Spanish",
  11534. "es-AR": "Spanish (Argentina)",
  11535. "es-BO": "Spanish (Bolivia)",
  11536. "es-CL": "Spanish (Chile)",
  11537. "es-CO": "Spanish (Colombia)",
  11538. "es-CR": "Spanish (Costa Rica)",
  11539. "es-DO": "Spanish (Dominican Republic)",
  11540. "es-EC": "Spanish (Ecuador)",
  11541. "es-SV": "Spanish (El Salvador)",
  11542. "es-GT": "Spanish (Guatemala)",
  11543. "es-HN": "Spanish (Honduras)",
  11544. "es-MX": "Spanish (Mexico)",
  11545. "es-NI": "Spanish (Nicaragua)",
  11546. "es-PA": "Spanish (Panama)",
  11547. "es-PY": "Spanish (Paraguay)",
  11548. "es-PE": "Spanish (Peru)",
  11549. "es-PR": "Spanish (Puerto Rico)",
  11550. "es-ES": "Spanish (Spain)",
  11551. "es-UY": "Spanish (Uruguay)",
  11552. "es-VE": "Spanish (Venezuela)",
  11553. "sx": "Sutu",
  11554. "sw": "Swahili",
  11555. "sv": "Swedish",
  11556. "sv-FI": "Swedish (Finland)",
  11557. "sv-SV": "Swedish (Sweden)",
  11558. "ta": "Tamil",
  11559. "tt": "Tatar",
  11560. "te": "Teluga",
  11561. "th": "Thai",
  11562. "tig": "Tigre",
  11563. "ts": "Tsonga",
  11564. "tn": "Tswana",
  11565. "tr": "Turkish",
  11566. "tk": "Turkmen",
  11567. "uk": "Ukrainian",
  11568. "hsb": "Upper Sorbian",
  11569. "ur": "Urdu",
  11570. "ve": "Venda",
  11571. "vi": "Vietnamese",
  11572. "vo": "Volapuk",
  11573. "wa": "Walloon",
  11574. "cy": "Welsh",
  11575. "xh": "Xhosa",
  11576. "ji": "Yiddish",
  11577. "zu": "Zulu"
  11578. };
  11579. if (this.internal.languageSettings === undefined) {
  11580. this.internal.languageSettings = {};
  11581. this.internal.languageSettings.isSubscribed = false;
  11582. }
  11583. if (langCodes[langCode] !== undefined) {
  11584. this.internal.languageSettings.languageCode = langCode;
  11585. if (this.internal.languageSettings.isSubscribed === false) {
  11586. this.internal.events.subscribe("putCatalog", function () {
  11587. this.internal.write("/Lang (" + this.internal.languageSettings.languageCode + ")");
  11588. });
  11589. this.internal.languageSettings.isSubscribed = true;
  11590. }
  11591. }
  11592. return this;
  11593. };
  11594. })(jsPDF.API);
  11595. /** @license
  11596. * MIT license.
  11597. * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  11598. * 2014 Diego Casorran, https://github.com/diegocr
  11599. *
  11600. *
  11601. * ====================================================================
  11602. */
  11603. /**
  11604. * jsPDF split_text_to_size plugin
  11605. *
  11606. * @name split_text_to_size
  11607. * @module
  11608. */
  11609. (function (API) {
  11610. /**
  11611. * Returns an array of length matching length of the 'word' string, with each
  11612. * cell occupied by the width of the char in that position.
  11613. *
  11614. * @name getCharWidthsArray
  11615. * @function
  11616. * @param {string} text
  11617. * @param {Object} options
  11618. * @returns {Array}
  11619. */
  11620. var getCharWidthsArray = API.getCharWidthsArray = function (text, options) {
  11621. options = options || {};
  11622. var activeFont = options.font || this.internal.getFont();
  11623. var fontSize = options.fontSize || this.internal.getFontSize();
  11624. var charSpace = options.charSpace || this.internal.getCharSpace();
  11625. var widths = options.widths ? options.widths : activeFont.metadata.Unicode.widths;
  11626. var widthsFractionOf = widths.fof ? widths.fof : 1;
  11627. var kerning = options.kerning ? options.kerning : activeFont.metadata.Unicode.kerning;
  11628. var kerningFractionOf = kerning.fof ? kerning.fof : 1;
  11629. var i;
  11630. var l;
  11631. var char_code;
  11632. var prior_char_code = 0; //for kerning
  11633. var default_char_width = widths[0] || widthsFractionOf;
  11634. var output = [];
  11635. for (i = 0, l = text.length; i < l; i++) {
  11636. char_code = text.charCodeAt(i);
  11637. if (typeof activeFont.metadata.widthOfString === "function") {
  11638. output.push((activeFont.metadata.widthOfGlyph(activeFont.metadata.characterToGlyph(char_code)) + charSpace * (1000 / fontSize) || 0) / 1000);
  11639. } else {
  11640. output.push((widths[char_code] || default_char_width) / widthsFractionOf + (kerning[char_code] && kerning[char_code][prior_char_code] || 0) / kerningFractionOf);
  11641. }
  11642. prior_char_code = char_code;
  11643. }
  11644. return output;
  11645. };
  11646. /**
  11647. * Calculate the sum of a number-array
  11648. *
  11649. * @name getArraySum
  11650. * @public
  11651. * @function
  11652. * @param {Array} array Array of numbers
  11653. * @returns {number}
  11654. */
  11655. var getArraySum = API.getArraySum = function (array) {
  11656. var i = array.length,
  11657. output = 0;
  11658. while (i) {
  11659. i--;
  11660. output += array[i];
  11661. }
  11662. return output;
  11663. };
  11664. /**
  11665. * Returns a widths of string in a given font, if the font size is set as 1 point.
  11666. *
  11667. * In other words, this is "proportional" value. For 1 unit of font size, the length
  11668. * of the string will be that much.
  11669. *
  11670. * Multiply by font size to get actual width in *points*
  11671. * Then divide by 72 to get inches or divide by (72/25.6) to get 'mm' etc.
  11672. *
  11673. * @name getStringUnitWidth
  11674. * @public
  11675. * @function
  11676. * @param {string} text
  11677. * @param {string} options
  11678. * @returns {number} result
  11679. */
  11680. var getStringUnitWidth = API.getStringUnitWidth = function (text, options) {
  11681. options = options || {};
  11682. var fontSize = options.fontSize || this.internal.getFontSize();
  11683. var font = options.font || this.internal.getFont();
  11684. var charSpace = options.charSpace || this.internal.getCharSpace();
  11685. var result = 0;
  11686. if (typeof font.metadata.widthOfString === "function") {
  11687. result = font.metadata.widthOfString(text, fontSize, charSpace) / fontSize;
  11688. } else {
  11689. result = getArraySum(getCharWidthsArray.apply(this, arguments));
  11690. }
  11691. return result;
  11692. };
  11693. /**
  11694. returns array of lines
  11695. */
  11696. var splitLongWord = function splitLongWord(word, widths_array, firstLineMaxLen, maxLen) {
  11697. var answer = []; // 1st, chop off the piece that can fit on the hanging line.
  11698. var i = 0,
  11699. l = word.length,
  11700. workingLen = 0;
  11701. while (i !== l && workingLen + widths_array[i] < firstLineMaxLen) {
  11702. workingLen += widths_array[i];
  11703. i++;
  11704. } // this is first line.
  11705. answer.push(word.slice(0, i)); // 2nd. Split the rest into maxLen pieces.
  11706. var startOfLine = i;
  11707. workingLen = 0;
  11708. while (i !== l) {
  11709. if (workingLen + widths_array[i] > maxLen) {
  11710. answer.push(word.slice(startOfLine, i));
  11711. workingLen = 0;
  11712. startOfLine = i;
  11713. }
  11714. workingLen += widths_array[i];
  11715. i++;
  11716. }
  11717. if (startOfLine !== i) {
  11718. answer.push(word.slice(startOfLine, i));
  11719. }
  11720. return answer;
  11721. }; // Note, all sizing inputs for this function must be in "font measurement units"
  11722. // By default, for PDF, it's "point".
  11723. var splitParagraphIntoLines = function splitParagraphIntoLines(text, maxlen, options) {
  11724. // at this time works only on Western scripts, ones with space char
  11725. // separating the words. Feel free to expand.
  11726. if (!options) {
  11727. options = {};
  11728. }
  11729. var line = [],
  11730. lines = [line],
  11731. line_length = options.textIndent || 0,
  11732. separator_length = 0,
  11733. current_word_length = 0,
  11734. word,
  11735. widths_array,
  11736. words = text.split(' '),
  11737. spaceCharWidth = getCharWidthsArray.apply(this, [' ', options])[0],
  11738. i,
  11739. l,
  11740. tmp,
  11741. lineIndent;
  11742. if (options.lineIndent === -1) {
  11743. lineIndent = words[0].length + 2;
  11744. } else {
  11745. lineIndent = options.lineIndent || 0;
  11746. }
  11747. if (lineIndent) {
  11748. var pad = Array(lineIndent).join(" "),
  11749. wrds = [];
  11750. words.map(function (wrd) {
  11751. wrd = wrd.split(/\s*\n/);
  11752. if (wrd.length > 1) {
  11753. wrds = wrds.concat(wrd.map(function (wrd, idx) {
  11754. return (idx && wrd.length ? "\n" : "") + wrd;
  11755. }));
  11756. } else {
  11757. wrds.push(wrd[0]);
  11758. }
  11759. });
  11760. words = wrds;
  11761. lineIndent = getStringUnitWidth.apply(this, [pad, options]);
  11762. }
  11763. for (i = 0, l = words.length; i < l; i++) {
  11764. var force = 0;
  11765. word = words[i];
  11766. if (lineIndent && word[0] == "\n") {
  11767. word = word.substr(1);
  11768. force = 1;
  11769. }
  11770. widths_array = getCharWidthsArray.apply(this, [word, options]);
  11771. current_word_length = getArraySum(widths_array);
  11772. if (line_length + separator_length + current_word_length > maxlen || force) {
  11773. if (current_word_length > maxlen) {
  11774. // this happens when you have space-less long URLs for example.
  11775. // we just chop these to size. We do NOT insert hiphens
  11776. tmp = splitLongWord.apply(this, [word, widths_array, maxlen - (line_length + separator_length), maxlen]); // first line we add to existing line object
  11777. line.push(tmp.shift()); // it's ok to have extra space indicator there
  11778. // last line we make into new line object
  11779. line = [tmp.pop()]; // lines in the middle we apped to lines object as whole lines
  11780. while (tmp.length) {
  11781. lines.push([tmp.shift()]); // single fragment occupies whole line
  11782. }
  11783. current_word_length = getArraySum(widths_array.slice(word.length - (line[0] ? line[0].length : 0)));
  11784. } else {
  11785. // just put it on a new line
  11786. line = [word];
  11787. } // now we attach new line to lines
  11788. lines.push(line);
  11789. line_length = current_word_length + lineIndent;
  11790. separator_length = spaceCharWidth;
  11791. } else {
  11792. line.push(word);
  11793. line_length += separator_length + current_word_length;
  11794. separator_length = spaceCharWidth;
  11795. }
  11796. }
  11797. if (lineIndent) {
  11798. var postProcess = function postProcess(ln, idx) {
  11799. return (idx ? pad : '') + ln.join(" ");
  11800. };
  11801. } else {
  11802. var postProcess = function postProcess(ln) {
  11803. return ln.join(" ");
  11804. };
  11805. }
  11806. return lines.map(postProcess);
  11807. };
  11808. /**
  11809. * Splits a given string into an array of strings. Uses 'size' value
  11810. * (in measurement units declared as default for the jsPDF instance)
  11811. * and the font's "widths" and "Kerning" tables, where available, to
  11812. * determine display length of a given string for a given font.
  11813. *
  11814. * We use character's 100% of unit size (height) as width when Width
  11815. * table or other default width is not available.
  11816. *
  11817. * @name splitTextToSize
  11818. * @public
  11819. * @function
  11820. * @param {string} text Unencoded, regular JavaScript (Unicode, UTF-16 / UCS-2) string.
  11821. * @param {number} size Nominal number, measured in units default to this instance of jsPDF.
  11822. * @param {Object} options Optional flags needed for chopper to do the right thing.
  11823. * @returns {Array} array Array with strings chopped to size.
  11824. */
  11825. API.splitTextToSize = function (text, maxlen, options) {
  11826. options = options || {};
  11827. var fsize = options.fontSize || this.internal.getFontSize(),
  11828. newOptions = function (options) {
  11829. var widths = {
  11830. 0: 1
  11831. },
  11832. kerning = {};
  11833. if (!options.widths || !options.kerning) {
  11834. var f = this.internal.getFont(options.fontName, options.fontStyle),
  11835. encoding = 'Unicode'; // NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE
  11836. // Actual JavaScript-native String's 16bit char codes used.
  11837. // no multi-byte logic here
  11838. if (f.metadata[encoding]) {
  11839. return {
  11840. widths: f.metadata[encoding].widths || widths,
  11841. kerning: f.metadata[encoding].kerning || kerning
  11842. };
  11843. } else {
  11844. return {
  11845. font: f.metadata,
  11846. fontSize: this.internal.getFontSize(),
  11847. charSpace: this.internal.getCharSpace()
  11848. };
  11849. }
  11850. } else {
  11851. return {
  11852. widths: options.widths,
  11853. kerning: options.kerning
  11854. };
  11855. } // then use default values
  11856. return {
  11857. widths: widths,
  11858. kerning: kerning
  11859. };
  11860. }.call(this, options); // first we split on end-of-line chars
  11861. var paragraphs;
  11862. if (Array.isArray(text)) {
  11863. paragraphs = text;
  11864. } else {
  11865. paragraphs = text.split(/\r?\n/);
  11866. } // now we convert size (max length of line) into "font size units"
  11867. // at present time, the "font size unit" is always 'point'
  11868. // 'proportional' means, "in proportion to font size"
  11869. var fontUnit_maxLen = 1.0 * this.internal.scaleFactor * maxlen / fsize; // at this time, fsize is always in "points" regardless of the default measurement unit of the doc.
  11870. // this may change in the future?
  11871. // until then, proportional_maxlen is likely to be in 'points'
  11872. // If first line is to be indented (shorter or longer) than maxLen
  11873. // we indicate that by using CSS-style "text-indent" option.
  11874. // here it's in font units too (which is likely 'points')
  11875. // it can be negative (which makes the first line longer than maxLen)
  11876. newOptions.textIndent = options.textIndent ? options.textIndent * 1.0 * this.internal.scaleFactor / fsize : 0;
  11877. newOptions.lineIndent = options.lineIndent;
  11878. var i,
  11879. l,
  11880. output = [];
  11881. for (i = 0, l = paragraphs.length; i < l; i++) {
  11882. output = output.concat(splitParagraphIntoLines.apply(this, [paragraphs[i], fontUnit_maxLen, newOptions]));
  11883. }
  11884. return output;
  11885. };
  11886. })(jsPDF.API);
  11887. /** @license
  11888. jsPDF standard_fonts_metrics plugin
  11889. * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  11890. * MIT license.
  11891. *
  11892. * ====================================================================
  11893. */
  11894. (function (API) {
  11895. /*
  11896. # reference (Python) versions of 'compress' and 'uncompress'
  11897. # only 'uncompress' function is featured lower as JavaScript
  11898. # if you want to unit test "roundtrip", just transcribe the reference
  11899. # 'compress' function from Python into JavaScript
  11900. def compress(data):
  11901. keys = '0123456789abcdef'
  11902. values = 'klmnopqrstuvwxyz'
  11903. mapping = dict(zip(keys, values))
  11904. vals = []
  11905. for key in data.keys():
  11906. value = data[key]
  11907. try:
  11908. keystring = hex(key)[2:]
  11909. keystring = keystring[:-1] + mapping[keystring[-1:]]
  11910. except:
  11911. keystring = key.join(["'","'"])
  11912. #print('Keystring is %s' % keystring)
  11913. try:
  11914. if value < 0:
  11915. valuestring = hex(value)[3:]
  11916. numberprefix = '-'
  11917. else:
  11918. valuestring = hex(value)[2:]
  11919. numberprefix = ''
  11920. valuestring = numberprefix + valuestring[:-1] + mapping[valuestring[-1:]]
  11921. except:
  11922. if type(value) == dict:
  11923. valuestring = compress(value)
  11924. else:
  11925. raise Exception("Don't know what to do with value type %s" % type(value))
  11926. vals.append(keystring+valuestring)
  11927. return '{' + ''.join(vals) + '}'
  11928. def uncompress(data):
  11929. decoded = '0123456789abcdef'
  11930. encoded = 'klmnopqrstuvwxyz'
  11931. mapping = dict(zip(encoded, decoded))
  11932. sign = +1
  11933. stringmode = False
  11934. stringparts = []
  11935. output = {}
  11936. activeobject = output
  11937. parentchain = []
  11938. keyparts = ''
  11939. valueparts = ''
  11940. key = None
  11941. ending = set(encoded)
  11942. i = 1
  11943. l = len(data) - 1 # stripping starting, ending {}
  11944. while i != l: # stripping {}
  11945. # -, {, }, ' are special.
  11946. ch = data[i]
  11947. i += 1
  11948. if ch == "'":
  11949. if stringmode:
  11950. # end of string mode
  11951. stringmode = False
  11952. key = ''.join(stringparts)
  11953. else:
  11954. # start of string mode
  11955. stringmode = True
  11956. stringparts = []
  11957. elif stringmode == True:
  11958. #print("Adding %s to stringpart" % ch)
  11959. stringparts.append(ch)
  11960. elif ch == '{':
  11961. # start of object
  11962. parentchain.append( [activeobject, key] )
  11963. activeobject = {}
  11964. key = None
  11965. #DEBUG = True
  11966. elif ch == '}':
  11967. # end of object
  11968. parent, key = parentchain.pop()
  11969. parent[key] = activeobject
  11970. key = None
  11971. activeobject = parent
  11972. #DEBUG = False
  11973. elif ch == '-':
  11974. sign = -1
  11975. else:
  11976. # must be number
  11977. if key == None:
  11978. #debug("In Key. It is '%s', ch is '%s'" % (keyparts, ch))
  11979. if ch in ending:
  11980. #debug("End of key")
  11981. keyparts += mapping[ch]
  11982. key = int(keyparts, 16) * sign
  11983. sign = +1
  11984. keyparts = ''
  11985. else:
  11986. keyparts += ch
  11987. else:
  11988. #debug("In value. It is '%s', ch is '%s'" % (valueparts, ch))
  11989. if ch in ending:
  11990. #debug("End of value")
  11991. valueparts += mapping[ch]
  11992. activeobject[key] = int(valueparts, 16) * sign
  11993. sign = +1
  11994. key = None
  11995. valueparts = ''
  11996. else:
  11997. valueparts += ch
  11998. #debug(activeobject)
  11999. return output
  12000. */
  12001. /**
  12002. Uncompresses data compressed into custom, base16-like format.
  12003. @public
  12004. @function
  12005. @param
  12006. @returns {Type}
  12007. */
  12008. var uncompress = function uncompress(data) {
  12009. var decoded = '0123456789abcdef',
  12010. encoded = 'klmnopqrstuvwxyz',
  12011. mapping = {};
  12012. for (var i = 0; i < encoded.length; i++) {
  12013. mapping[encoded[i]] = decoded[i];
  12014. }
  12015. var undef,
  12016. output = {},
  12017. sign = 1,
  12018. stringparts // undef. will be [] in string mode
  12019. ,
  12020. activeobject = output,
  12021. parentchain = [],
  12022. parent_key_pair,
  12023. keyparts = '',
  12024. valueparts = '',
  12025. key // undef. will be Truthy when Key is resolved.
  12026. ,
  12027. datalen = data.length - 1 // stripping ending }
  12028. ,
  12029. ch;
  12030. i = 1; // stripping starting {
  12031. while (i != datalen) {
  12032. // - { } ' are special.
  12033. ch = data[i];
  12034. i += 1;
  12035. if (ch == "'") {
  12036. if (stringparts) {
  12037. // end of string mode
  12038. key = stringparts.join('');
  12039. stringparts = undef;
  12040. } else {
  12041. // start of string mode
  12042. stringparts = [];
  12043. }
  12044. } else if (stringparts) {
  12045. stringparts.push(ch);
  12046. } else if (ch == '{') {
  12047. // start of object
  12048. parentchain.push([activeobject, key]);
  12049. activeobject = {};
  12050. key = undef;
  12051. } else if (ch == '}') {
  12052. // end of object
  12053. parent_key_pair = parentchain.pop();
  12054. parent_key_pair[0][parent_key_pair[1]] = activeobject;
  12055. key = undef;
  12056. activeobject = parent_key_pair[0];
  12057. } else if (ch == '-') {
  12058. sign = -1;
  12059. } else {
  12060. // must be number
  12061. if (key === undef) {
  12062. if (mapping.hasOwnProperty(ch)) {
  12063. keyparts += mapping[ch];
  12064. key = parseInt(keyparts, 16) * sign;
  12065. sign = +1;
  12066. keyparts = '';
  12067. } else {
  12068. keyparts += ch;
  12069. }
  12070. } else {
  12071. if (mapping.hasOwnProperty(ch)) {
  12072. valueparts += mapping[ch];
  12073. activeobject[key] = parseInt(valueparts, 16) * sign;
  12074. sign = +1;
  12075. key = undef;
  12076. valueparts = '';
  12077. } else {
  12078. valueparts += ch;
  12079. }
  12080. }
  12081. }
  12082. } // end while
  12083. return output;
  12084. }; // encoding = 'Unicode'
  12085. // NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE. NO clever BOM behavior
  12086. // Actual 16bit char codes used.
  12087. // no multi-byte logic here
  12088. // Unicode characters to WinAnsiEncoding:
  12089. // {402: 131, 8211: 150, 8212: 151, 8216: 145, 8217: 146, 8218: 130, 8220: 147, 8221: 148, 8222: 132, 8224: 134, 8225: 135, 8226: 149, 8230: 133, 8364: 128, 8240:137, 8249: 139, 8250: 155, 710: 136, 8482: 153, 338: 140, 339: 156, 732: 152, 352: 138, 353: 154, 376: 159, 381: 142, 382: 158}
  12090. // as you can see, all Unicode chars are outside of 0-255 range. No char code conflicts.
  12091. // this means that you can give Win cp1252 encoded strings to jsPDF for rendering directly
  12092. // as well as give strings with some (supported by these fonts) Unicode characters and
  12093. // these will be mapped to win cp1252
  12094. // for example, you can send char code (cp1252) 0x80 or (unicode) 0x20AC, getting "Euro" glyph displayed in both cases.
  12095. var encodingBlock = {
  12096. 'codePages': ['WinAnsiEncoding'],
  12097. 'WinAnsiEncoding': uncompress("{19m8n201n9q201o9r201s9l201t9m201u8m201w9n201x9o201y8o202k8q202l8r202m9p202q8p20aw8k203k8t203t8v203u9v2cq8s212m9t15m8w15n9w2dw9s16k8u16l9u17s9z17x8y17y9y}")
  12098. },
  12099. encodings = {
  12100. 'Unicode': {
  12101. 'Courier': encodingBlock,
  12102. 'Courier-Bold': encodingBlock,
  12103. 'Courier-BoldOblique': encodingBlock,
  12104. 'Courier-Oblique': encodingBlock,
  12105. 'Helvetica': encodingBlock,
  12106. 'Helvetica-Bold': encodingBlock,
  12107. 'Helvetica-BoldOblique': encodingBlock,
  12108. 'Helvetica-Oblique': encodingBlock,
  12109. 'Times-Roman': encodingBlock,
  12110. 'Times-Bold': encodingBlock,
  12111. 'Times-BoldItalic': encodingBlock,
  12112. 'Times-Italic': encodingBlock // , 'Symbol'
  12113. // , 'ZapfDingbats'
  12114. }
  12115. },
  12116. fontMetrics = {
  12117. 'Unicode': {
  12118. // all sizing numbers are n/fontMetricsFractionOf = one font size unit
  12119. // this means that if fontMetricsFractionOf = 1000, and letter A's width is 476, it's
  12120. // width is 476/1000 or 47.6% of its height (regardless of font size)
  12121. // At this time this value applies to "widths" and "kerning" numbers.
  12122. // char code 0 represents "default" (average) width - use it for chars missing in this table.
  12123. // key 'fof' represents the "fontMetricsFractionOf" value
  12124. 'Courier-Oblique': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  12125. 'Times-BoldItalic': uncompress("{'widths'{k3o2q4ycx2r201n3m201o6o201s2l201t2l201u2l201w3m201x3m201y3m2k1t2l2r202m2n2n3m2o3m2p5n202q6o2r1w2s2l2t2l2u3m2v3t2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w3t3x3t3y3t3z3m4k5n4l4m4m4m4n4m4o4s4p4m4q4m4r4s4s4y4t2r4u3m4v4m4w3x4x5t4y4s4z4s5k3x5l4s5m4m5n3r5o3x5p4s5q4m5r5t5s4m5t3x5u3x5v2l5w1w5x2l5y3t5z3m6k2l6l3m6m3m6n2w6o3m6p2w6q2l6r3m6s3r6t1w6u1w6v3m6w1w6x4y6y3r6z3m7k3m7l3m7m2r7n2r7o1w7p3r7q2w7r4m7s3m7t2w7u2r7v2n7w1q7x2n7y3t202l3mcl4mal2ram3man3mao3map3mar3mas2lat4uau1uav3maw3way4uaz2lbk2sbl3t'fof'6obo2lbp3tbq3mbr1tbs2lbu1ybv3mbz3mck4m202k3mcm4mcn4mco4mcp4mcq5ycr4mcs4mct4mcu4mcv4mcw2r2m3rcy2rcz2rdl4sdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek3mel3mem3men3meo3mep3meq4ser2wes2wet2weu2wev2wew1wex1wey1wez1wfl3rfm3mfn3mfo3mfp3mfq3mfr3tfs3mft3rfu3rfv3rfw3rfz2w203k6o212m6o2dw2l2cq2l3t3m3u2l17s3x19m3m}'kerning'{cl{4qu5kt5qt5rs17ss5ts}201s{201ss}201t{cks4lscmscnscoscpscls2wu2yu201ts}201x{2wu2yu}2k{201ts}2w{4qx5kx5ou5qx5rs17su5tu}2x{17su5tu5ou}2y{4qx5kx5ou5qx5rs17ss5ts}'fof'-6ofn{17sw5tw5ou5qw5rs}7t{cksclscmscnscoscps4ls}3u{17su5tu5os5qs}3v{17su5tu5os5qs}7p{17su5tu}ck{4qu5kt5qt5rs17ss5ts}4l{4qu5kt5qt5rs17ss5ts}cm{4qu5kt5qt5rs17ss5ts}cn{4qu5kt5qt5rs17ss5ts}co{4qu5kt5qt5rs17ss5ts}cp{4qu5kt5qt5rs17ss5ts}6l{4qu5ou5qw5rt17su5tu}5q{ckuclucmucnucoucpu4lu}5r{ckuclucmucnucoucpu4lu}7q{cksclscmscnscoscps4ls}6p{4qu5ou5qw5rt17sw5tw}ek{4qu5ou5qw5rt17su5tu}el{4qu5ou5qw5rt17su5tu}em{4qu5ou5qw5rt17su5tu}en{4qu5ou5qw5rt17su5tu}eo{4qu5ou5qw5rt17su5tu}ep{4qu5ou5qw5rt17su5tu}es{17ss5ts5qs4qu}et{4qu5ou5qw5rt17sw5tw}eu{4qu5ou5qw5rt17ss5ts}ev{17ss5ts5qs4qu}6z{17sw5tw5ou5qw5rs}fm{17sw5tw5ou5qw5rs}7n{201ts}fo{17sw5tw5ou5qw5rs}fp{17sw5tw5ou5qw5rs}fq{17sw5tw5ou5qw5rs}7r{cksclscmscnscoscps4ls}fs{17sw5tw5ou5qw5rs}ft{17su5tu}fu{17su5tu}fv{17su5tu}fw{17su5tu}fz{cksclscmscnscoscps4ls}}}"),
  12126. 'Helvetica-Bold': uncompress("{'widths'{k3s2q4scx1w201n3r201o6o201s1w201t1w201u1w201w3m201x3m201y3m2k1w2l2l202m2n2n3r2o3r2p5t202q6o2r1s2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v2l3w3u3x3u3y3u3z3x4k6l4l4s4m4s4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3r4v4s4w3x4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v2l5w1w5x2l5y3u5z3r6k2l6l3r6m3x6n3r6o3x6p3r6q2l6r3x6s3x6t1w6u1w6v3r6w1w6x5t6y3x6z3x7k3x7l3x7m2r7n3r7o2l7p3x7q3r7r4y7s3r7t3r7u3m7v2r7w1w7x2r7y3u202l3rcl4sal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3xbq3rbr1wbs2lbu2obv3rbz3xck4s202k3rcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw1w2m2zcy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3res3ret3reu3rev3rew1wex1wey1wez1wfl3xfm3xfn3xfo3xfp3xfq3xfr3ufs3xft3xfu3xfv3xfw3xfz3r203k6o212m6o2dw2l2cq2l3t3r3u2l17s4m19m3r}'kerning'{cl{4qs5ku5ot5qs17sv5tv}201t{2ww4wy2yw}201w{2ks}201x{2ww4wy2yw}2k{201ts201xs}2w{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}2x{5ow5qs}2y{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}'fof'-6o7p{17su5tu5ot}ck{4qs5ku5ot5qs17sv5tv}4l{4qs5ku5ot5qs17sv5tv}cm{4qs5ku5ot5qs17sv5tv}cn{4qs5ku5ot5qs17sv5tv}co{4qs5ku5ot5qs17sv5tv}cp{4qs5ku5ot5qs17sv5tv}6l{17st5tt5os}17s{2kwclvcmvcnvcovcpv4lv4wwckv}5o{2kucltcmtcntcotcpt4lt4wtckt}5q{2ksclscmscnscoscps4ls4wvcks}5r{2ks4ws}5t{2kwclvcmvcnvcovcpv4lv4wwckv}eo{17st5tt5os}fu{17su5tu5ot}6p{17ss5ts}ek{17st5tt5os}el{17st5tt5os}em{17st5tt5os}en{17st5tt5os}6o{201ts}ep{17st5tt5os}es{17ss5ts}et{17ss5ts}eu{17ss5ts}ev{17ss5ts}6z{17su5tu5os5qt}fm{17su5tu5os5qt}fn{17su5tu5os5qt}fo{17su5tu5os5qt}fp{17su5tu5os5qt}fq{17su5tu5os5qt}fs{17su5tu5os5qt}ft{17su5tu5ot}7m{5os}fv{17su5tu5ot}fw{17su5tu5ot}}}"),
  12127. 'Courier': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  12128. 'Courier-BoldOblique': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  12129. 'Times-Bold': uncompress("{'widths'{k3q2q5ncx2r201n3m201o6o201s2l201t2l201u2l201w3m201x3m201y3m2k1t2l2l202m2n2n3m2o3m2p6o202q6o2r1w2s2l2t2l2u3m2v3t2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w3t3x3t3y3t3z3m4k5x4l4s4m4m4n4s4o4s4p4m4q3x4r4y4s4y4t2r4u3m4v4y4w4m4x5y4y4s4z4y5k3x5l4y5m4s5n3r5o4m5p4s5q4s5r6o5s4s5t4s5u4m5v2l5w1w5x2l5y3u5z3m6k2l6l3m6m3r6n2w6o3r6p2w6q2l6r3m6s3r6t1w6u2l6v3r6w1w6x5n6y3r6z3m7k3r7l3r7m2w7n2r7o2l7p3r7q3m7r4s7s3m7t3m7u2w7v2r7w1q7x2r7y3o202l3mcl4sal2lam3man3mao3map3mar3mas2lat4uau1yav3maw3tay4uaz2lbk2sbl3t'fof'6obo2lbp3rbr1tbs2lbu2lbv3mbz3mck4s202k3mcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw2r2m3rcy2rcz2rdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3rek3mel3mem3men3meo3mep3meq4ser2wes2wet2weu2wev2wew1wex1wey1wez1wfl3rfm3mfn3mfo3mfp3mfq3mfr3tfs3mft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3m3u2l17s4s19m3m}'kerning'{cl{4qt5ks5ot5qy5rw17sv5tv}201t{cks4lscmscnscoscpscls4wv}2k{201ts}2w{4qu5ku7mu5os5qx5ru17su5tu}2x{17su5tu5ou5qs}2y{4qv5kv7mu5ot5qz5ru17su5tu}'fof'-6o7t{cksclscmscnscoscps4ls}3u{17su5tu5os5qu}3v{17su5tu5os5qu}fu{17su5tu5ou5qu}7p{17su5tu5ou5qu}ck{4qt5ks5ot5qy5rw17sv5tv}4l{4qt5ks5ot5qy5rw17sv5tv}cm{4qt5ks5ot5qy5rw17sv5tv}cn{4qt5ks5ot5qy5rw17sv5tv}co{4qt5ks5ot5qy5rw17sv5tv}cp{4qt5ks5ot5qy5rw17sv5tv}6l{17st5tt5ou5qu}17s{ckuclucmucnucoucpu4lu4wu}5o{ckuclucmucnucoucpu4lu4wu}5q{ckzclzcmzcnzcozcpz4lz4wu}5r{ckxclxcmxcnxcoxcpx4lx4wu}5t{ckuclucmucnucoucpu4lu4wu}7q{ckuclucmucnucoucpu4lu}6p{17sw5tw5ou5qu}ek{17st5tt5qu}el{17st5tt5ou5qu}em{17st5tt5qu}en{17st5tt5qu}eo{17st5tt5qu}ep{17st5tt5ou5qu}es{17ss5ts5qu}et{17sw5tw5ou5qu}eu{17sw5tw5ou5qu}ev{17ss5ts5qu}6z{17sw5tw5ou5qu5rs}fm{17sw5tw5ou5qu5rs}fn{17sw5tw5ou5qu5rs}fo{17sw5tw5ou5qu5rs}fp{17sw5tw5ou5qu5rs}fq{17sw5tw5ou5qu5rs}7r{cktcltcmtcntcotcpt4lt5os}fs{17sw5tw5ou5qu5rs}ft{17su5tu5ou5qu}7m{5os}fv{17su5tu5ou5qu}fw{17su5tu5ou5qu}fz{cksclscmscnscoscps4ls}}}"),
  12130. 'Symbol': uncompress("{'widths'{k3uaw4r19m3m2k1t2l2l202m2y2n3m2p5n202q6o3k3m2s2l2t2l2v3r2w1t3m3m2y1t2z1wbk2sbl3r'fof'6o3n3m3o3m3p3m3q3m3r3m3s3m3t3m3u1w3v1w3w3r3x3r3y3r3z2wbp3t3l3m5v2l5x2l5z3m2q4yfr3r7v3k7w1o7x3k}'kerning'{'fof'-6o}}"),
  12131. 'Helvetica': uncompress("{'widths'{k3p2q4mcx1w201n3r201o6o201s1q201t1q201u1q201w2l201x2l201y2l2k1w2l1w202m2n2n3r2o3r2p5t202q6o2r1n2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v1w3w3u3x3u3y3u3z3r4k6p4l4m4m4m4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3m4v4m4w3r4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v1w5w1w5x1w5y2z5z3r6k2l6l3r6m3r6n3m6o3r6p3r6q1w6r3r6s3r6t1q6u1q6v3m6w1q6x5n6y3r6z3r7k3r7l3r7m2l7n3m7o1w7p3r7q3m7r4s7s3m7t3m7u3m7v2l7w1u7x2l7y3u202l3rcl4mal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3rbr1wbs2lbu2obv3rbz3xck4m202k3rcm4mcn4mco4mcp4mcq6ocr4scs4mct4mcu4mcv4mcw1w2m2ncy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3mes3ret3reu3rev3rew1wex1wey1wez1wfl3rfm3rfn3rfo3rfp3rfq3rfr3ufs3xft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3r3u1w17s4m19m3r}'kerning'{5q{4wv}cl{4qs5kw5ow5qs17sv5tv}201t{2wu4w1k2yu}201x{2wu4wy2yu}17s{2ktclucmucnu4otcpu4lu4wycoucku}2w{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}2x{17sy5ty5oy5qs}2y{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}'fof'-6o7p{17sv5tv5ow}ck{4qs5kw5ow5qs17sv5tv}4l{4qs5kw5ow5qs17sv5tv}cm{4qs5kw5ow5qs17sv5tv}cn{4qs5kw5ow5qs17sv5tv}co{4qs5kw5ow5qs17sv5tv}cp{4qs5kw5ow5qs17sv5tv}6l{17sy5ty5ow}do{17st5tt}4z{17st5tt}7s{fst}dm{17st5tt}dn{17st5tt}5o{ckwclwcmwcnwcowcpw4lw4wv}dp{17st5tt}dq{17st5tt}7t{5ow}ds{17st5tt}5t{2ktclucmucnu4otcpu4lu4wycoucku}fu{17sv5tv5ow}6p{17sy5ty5ow5qs}ek{17sy5ty5ow}el{17sy5ty5ow}em{17sy5ty5ow}en{5ty}eo{17sy5ty5ow}ep{17sy5ty5ow}es{17sy5ty5qs}et{17sy5ty5ow5qs}eu{17sy5ty5ow5qs}ev{17sy5ty5ow5qs}6z{17sy5ty5ow5qs}fm{17sy5ty5ow5qs}fn{17sy5ty5ow5qs}fo{17sy5ty5ow5qs}fp{17sy5ty5qs}fq{17sy5ty5ow5qs}7r{5ow}fs{17sy5ty5ow5qs}ft{17sv5tv5ow}7m{5ow}fv{17sv5tv5ow}fw{17sv5tv5ow}}}"),
  12132. 'Helvetica-BoldOblique': uncompress("{'widths'{k3s2q4scx1w201n3r201o6o201s1w201t1w201u1w201w3m201x3m201y3m2k1w2l2l202m2n2n3r2o3r2p5t202q6o2r1s2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v2l3w3u3x3u3y3u3z3x4k6l4l4s4m4s4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3r4v4s4w3x4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v2l5w1w5x2l5y3u5z3r6k2l6l3r6m3x6n3r6o3x6p3r6q2l6r3x6s3x6t1w6u1w6v3r6w1w6x5t6y3x6z3x7k3x7l3x7m2r7n3r7o2l7p3x7q3r7r4y7s3r7t3r7u3m7v2r7w1w7x2r7y3u202l3rcl4sal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3xbq3rbr1wbs2lbu2obv3rbz3xck4s202k3rcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw1w2m2zcy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3res3ret3reu3rev3rew1wex1wey1wez1wfl3xfm3xfn3xfo3xfp3xfq3xfr3ufs3xft3xfu3xfv3xfw3xfz3r203k6o212m6o2dw2l2cq2l3t3r3u2l17s4m19m3r}'kerning'{cl{4qs5ku5ot5qs17sv5tv}201t{2ww4wy2yw}201w{2ks}201x{2ww4wy2yw}2k{201ts201xs}2w{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}2x{5ow5qs}2y{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}'fof'-6o7p{17su5tu5ot}ck{4qs5ku5ot5qs17sv5tv}4l{4qs5ku5ot5qs17sv5tv}cm{4qs5ku5ot5qs17sv5tv}cn{4qs5ku5ot5qs17sv5tv}co{4qs5ku5ot5qs17sv5tv}cp{4qs5ku5ot5qs17sv5tv}6l{17st5tt5os}17s{2kwclvcmvcnvcovcpv4lv4wwckv}5o{2kucltcmtcntcotcpt4lt4wtckt}5q{2ksclscmscnscoscps4ls4wvcks}5r{2ks4ws}5t{2kwclvcmvcnvcovcpv4lv4wwckv}eo{17st5tt5os}fu{17su5tu5ot}6p{17ss5ts}ek{17st5tt5os}el{17st5tt5os}em{17st5tt5os}en{17st5tt5os}6o{201ts}ep{17st5tt5os}es{17ss5ts}et{17ss5ts}eu{17ss5ts}ev{17ss5ts}6z{17su5tu5os5qt}fm{17su5tu5os5qt}fn{17su5tu5os5qt}fo{17su5tu5os5qt}fp{17su5tu5os5qt}fq{17su5tu5os5qt}fs{17su5tu5os5qt}ft{17su5tu5ot}7m{5os}fv{17su5tu5ot}fw{17su5tu5ot}}}"),
  12133. 'ZapfDingbats': uncompress("{'widths'{k4u2k1w'fof'6o}'kerning'{'fof'-6o}}"),
  12134. 'Courier-Bold': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),
  12135. 'Times-Italic': uncompress("{'widths'{k3n2q4ycx2l201n3m201o5t201s2l201t2l201u2l201w3r201x3r201y3r2k1t2l2l202m2n2n3m2o3m2p5n202q5t2r1p2s2l2t2l2u3m2v4n2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w4n3x4n3y4n3z3m4k5w4l3x4m3x4n4m4o4s4p3x4q3x4r4s4s4s4t2l4u2w4v4m4w3r4x5n4y4m4z4s5k3x5l4s5m3x5n3m5o3r5p4s5q3x5r5n5s3x5t3r5u3r5v2r5w1w5x2r5y2u5z3m6k2l6l3m6m3m6n2w6o3m6p2w6q1w6r3m6s3m6t1w6u1w6v2w6w1w6x4s6y3m6z3m7k3m7l3m7m2r7n2r7o1w7p3m7q2w7r4m7s2w7t2w7u2r7v2s7w1v7x2s7y3q202l3mcl3xal2ram3man3mao3map3mar3mas2lat4wau1vav3maw4nay4waz2lbk2sbl4n'fof'6obo2lbp3mbq3obr1tbs2lbu1zbv3mbz3mck3x202k3mcm3xcn3xco3xcp3xcq5tcr4mcs3xct3xcu3xcv3xcw2l2m2ucy2lcz2ldl4mdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek3mel3mem3men3meo3mep3meq4mer2wes2wet2weu2wev2wew1wex1wey1wez1wfl3mfm3mfn3mfo3mfp3mfq3mfr4nfs3mft3mfu3mfv3mfw3mfz2w203k6o212m6m2dw2l2cq2l3t3m3u2l17s3r19m3m}'kerning'{cl{5kt4qw}201s{201sw}201t{201tw2wy2yy6q-t}201x{2wy2yy}2k{201tw}2w{7qs4qy7rs5ky7mw5os5qx5ru17su5tu}2x{17ss5ts5os}2y{7qs4qy7rs5ky7mw5os5qx5ru17su5tu}'fof'-6o6t{17ss5ts5qs}7t{5os}3v{5qs}7p{17su5tu5qs}ck{5kt4qw}4l{5kt4qw}cm{5kt4qw}cn{5kt4qw}co{5kt4qw}cp{5kt4qw}6l{4qs5ks5ou5qw5ru17su5tu}17s{2ks}5q{ckvclvcmvcnvcovcpv4lv}5r{ckuclucmucnucoucpu4lu}5t{2ks}6p{4qs5ks5ou5qw5ru17su5tu}ek{4qs5ks5ou5qw5ru17su5tu}el{4qs5ks5ou5qw5ru17su5tu}em{4qs5ks5ou5qw5ru17su5tu}en{4qs5ks5ou5qw5ru17su5tu}eo{4qs5ks5ou5qw5ru17su5tu}ep{4qs5ks5ou5qw5ru17su5tu}es{5ks5qs4qs}et{4qs5ks5ou5qw5ru17su5tu}eu{4qs5ks5qw5ru17su5tu}ev{5ks5qs4qs}ex{17ss5ts5qs}6z{4qv5ks5ou5qw5ru17su5tu}fm{4qv5ks5ou5qw5ru17su5tu}fn{4qv5ks5ou5qw5ru17su5tu}fo{4qv5ks5ou5qw5ru17su5tu}fp{4qv5ks5ou5qw5ru17su5tu}fq{4qv5ks5ou5qw5ru17su5tu}7r{5os}fs{4qv5ks5ou5qw5ru17su5tu}ft{17su5tu5qs}fu{17su5tu5qs}fv{17su5tu5qs}fw{17su5tu5qs}}}"),
  12136. 'Times-Roman': uncompress("{'widths'{k3n2q4ycx2l201n3m201o6o201s2l201t2l201u2l201w2w201x2w201y2w2k1t2l2l202m2n2n3m2o3m2p5n202q6o2r1m2s2l2t2l2u3m2v3s2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v1w3w3s3x3s3y3s3z2w4k5w4l4s4m4m4n4m4o4s4p3x4q3r4r4s4s4s4t2l4u2r4v4s4w3x4x5t4y4s4z4s5k3r5l4s5m4m5n3r5o3x5p4s5q4s5r5y5s4s5t4s5u3x5v2l5w1w5x2l5y2z5z3m6k2l6l2w6m3m6n2w6o3m6p2w6q2l6r3m6s3m6t1w6u1w6v3m6w1w6x4y6y3m6z3m7k3m7l3m7m2l7n2r7o1w7p3m7q3m7r4s7s3m7t3m7u2w7v3k7w1o7x3k7y3q202l3mcl4sal2lam3man3mao3map3mar3mas2lat4wau1vav3maw3say4waz2lbk2sbl3s'fof'6obo2lbp3mbq2xbr1tbs2lbu1zbv3mbz2wck4s202k3mcm4scn4sco4scp4scq5tcr4mcs3xct3xcu3xcv3xcw2l2m2tcy2lcz2ldl4sdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek2wel2wem2wen2weo2wep2weq4mer2wes2wet2weu2wev2wew1wex1wey1wez1wfl3mfm3mfn3mfo3mfp3mfq3mfr3sfs3mft3mfu3mfv3mfw3mfz3m203k6o212m6m2dw2l2cq2l3t3m3u1w17s4s19m3m}'kerning'{cl{4qs5ku17sw5ou5qy5rw201ss5tw201ws}201s{201ss}201t{ckw4lwcmwcnwcowcpwclw4wu201ts}2k{201ts}2w{4qs5kw5os5qx5ru17sx5tx}2x{17sw5tw5ou5qu}2y{4qs5kw5os5qx5ru17sx5tx}'fof'-6o7t{ckuclucmucnucoucpu4lu5os5rs}3u{17su5tu5qs}3v{17su5tu5qs}7p{17sw5tw5qs}ck{4qs5ku17sw5ou5qy5rw201ss5tw201ws}4l{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cm{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cn{4qs5ku17sw5ou5qy5rw201ss5tw201ws}co{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cp{4qs5ku17sw5ou5qy5rw201ss5tw201ws}6l{17su5tu5os5qw5rs}17s{2ktclvcmvcnvcovcpv4lv4wuckv}5o{ckwclwcmwcnwcowcpw4lw4wu}5q{ckyclycmycnycoycpy4ly4wu5ms}5r{cktcltcmtcntcotcpt4lt4ws}5t{2ktclvcmvcnvcovcpv4lv4wuckv}7q{cksclscmscnscoscps4ls}6p{17su5tu5qw5rs}ek{5qs5rs}el{17su5tu5os5qw5rs}em{17su5tu5os5qs5rs}en{17su5qs5rs}eo{5qs5rs}ep{17su5tu5os5qw5rs}es{5qs}et{17su5tu5qw5rs}eu{17su5tu5qs5rs}ev{5qs}6z{17sv5tv5os5qx5rs}fm{5os5qt5rs}fn{17sv5tv5os5qx5rs}fo{17sv5tv5os5qx5rs}fp{5os5qt5rs}fq{5os5qt5rs}7r{ckuclucmucnucoucpu4lu5os}fs{17sv5tv5os5qx5rs}ft{17ss5ts5qs}fu{17sw5tw5qs}fv{17sw5tw5qs}fw{17ss5ts5qs}fz{ckuclucmucnucoucpu4lu5os5rs}}}"),
  12137. 'Helvetica-Oblique': uncompress("{'widths'{k3p2q4mcx1w201n3r201o6o201s1q201t1q201u1q201w2l201x2l201y2l2k1w2l1w202m2n2n3r2o3r2p5t202q6o2r1n2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v1w3w3u3x3u3y3u3z3r4k6p4l4m4m4m4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3m4v4m4w3r4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v1w5w1w5x1w5y2z5z3r6k2l6l3r6m3r6n3m6o3r6p3r6q1w6r3r6s3r6t1q6u1q6v3m6w1q6x5n6y3r6z3r7k3r7l3r7m2l7n3m7o1w7p3r7q3m7r4s7s3m7t3m7u3m7v2l7w1u7x2l7y3u202l3rcl4mal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3rbr1wbs2lbu2obv3rbz3xck4m202k3rcm4mcn4mco4mcp4mcq6ocr4scs4mct4mcu4mcv4mcw1w2m2ncy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3mes3ret3reu3rev3rew1wex1wey1wez1wfl3rfm3rfn3rfo3rfp3rfq3rfr3ufs3xft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3r3u1w17s4m19m3r}'kerning'{5q{4wv}cl{4qs5kw5ow5qs17sv5tv}201t{2wu4w1k2yu}201x{2wu4wy2yu}17s{2ktclucmucnu4otcpu4lu4wycoucku}2w{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}2x{17sy5ty5oy5qs}2y{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}'fof'-6o7p{17sv5tv5ow}ck{4qs5kw5ow5qs17sv5tv}4l{4qs5kw5ow5qs17sv5tv}cm{4qs5kw5ow5qs17sv5tv}cn{4qs5kw5ow5qs17sv5tv}co{4qs5kw5ow5qs17sv5tv}cp{4qs5kw5ow5qs17sv5tv}6l{17sy5ty5ow}do{17st5tt}4z{17st5tt}7s{fst}dm{17st5tt}dn{17st5tt}5o{ckwclwcmwcnwcowcpw4lw4wv}dp{17st5tt}dq{17st5tt}7t{5ow}ds{17st5tt}5t{2ktclucmucnu4otcpu4lu4wycoucku}fu{17sv5tv5ow}6p{17sy5ty5ow5qs}ek{17sy5ty5ow}el{17sy5ty5ow}em{17sy5ty5ow}en{5ty}eo{17sy5ty5ow}ep{17sy5ty5ow}es{17sy5ty5qs}et{17sy5ty5ow5qs}eu{17sy5ty5ow5qs}ev{17sy5ty5ow5qs}6z{17sy5ty5ow5qs}fm{17sy5ty5ow5qs}fn{17sy5ty5ow5qs}fo{17sy5ty5ow5qs}fp{17sy5ty5qs}fq{17sy5ty5ow5qs}7r{5ow}fs{17sy5ty5ow5qs}ft{17sv5tv5ow}7m{5ow}fv{17sv5tv5ow}fw{17sv5tv5ow}}}")
  12138. }
  12139. };
  12140. /*
  12141. This event handler is fired when a new jsPDF object is initialized
  12142. This event handler appends metrics data to standard fonts within
  12143. that jsPDF instance. The metrics are mapped over Unicode character
  12144. codes, NOT CIDs or other codes matching the StandardEncoding table of the
  12145. standard PDF fonts.
  12146. Future:
  12147. Also included is the encoding maping table, converting Unicode (UCS-2, UTF-16)
  12148. char codes to StandardEncoding character codes. The encoding table is to be used
  12149. somewhere around "pdfEscape" call.
  12150. */
  12151. API.events.push(['addFont', function (data) {
  12152. var font = data.font;
  12153. var metrics,
  12154. unicode_section,
  12155. encoding = 'Unicode',
  12156. encodingBlock;
  12157. metrics = fontMetrics[encoding][font.postScriptName];
  12158. if (metrics) {
  12159. if (font.metadata[encoding]) {
  12160. unicode_section = font.metadata[encoding];
  12161. } else {
  12162. unicode_section = font.metadata[encoding] = {};
  12163. }
  12164. unicode_section.widths = metrics.widths;
  12165. unicode_section.kerning = metrics.kerning;
  12166. }
  12167. encodingBlock = encodings[encoding][font.postScriptName];
  12168. if (encodingBlock) {
  12169. if (font.metadata[encoding]) {
  12170. unicode_section = font.metadata[encoding];
  12171. } else {
  12172. unicode_section = font.metadata[encoding] = {};
  12173. }
  12174. unicode_section.encoding = encodingBlock;
  12175. if (encodingBlock.codePages && encodingBlock.codePages.length) {
  12176. font.encoding = encodingBlock.codePages[0];
  12177. }
  12178. }
  12179. }]); // end of adding event handler
  12180. })(jsPDF.API);
  12181. /**
  12182. * @license
  12183. * Licensed under the MIT License.
  12184. * http://opensource.org/licenses/mit-license
  12185. */
  12186. /**
  12187. * @name ttfsupport
  12188. * @module
  12189. */
  12190. (function (jsPDF, global) {
  12191. jsPDF.API.events.push(['addFont', function (data) {
  12192. var font = data.font;
  12193. var instance = data.instance;
  12194. if (typeof instance !== "undefined" && instance.existsFileInVFS(font.postScriptName)) {
  12195. var file = instance.getFileFromVFS(font.postScriptName);
  12196. if (typeof file !== "string") {
  12197. throw new Error("Font is not stored as string-data in vFS, import fonts or remove declaration doc.addFont('" + font.postScriptName + "').");
  12198. }
  12199. font.metadata = jsPDF.API.TTFFont.open(font.postScriptName, font.fontName, file, font.encoding);
  12200. font.metadata.Unicode = font.metadata.Unicode || {
  12201. encoding: {},
  12202. kerning: {},
  12203. widths: []
  12204. };
  12205. font.metadata.glyIdsUsed = [0];
  12206. } else if (font.isStandardFont === false) {
  12207. throw new Error("Font does not exist in vFS, import fonts or remove declaration doc.addFont('" + font.postScriptName + "').");
  12208. }
  12209. }]); // end of adding event handler
  12210. })(jsPDF, typeof self !== "undefined" && self || typeof global !== "undefined" && global || typeof window !== "undefined" && window || Function("return this")());
  12211. /** @license
  12212. * Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  12213. *
  12214. *
  12215. * ====================================================================
  12216. */
  12217. (function (jsPDFAPI) {
  12218. /**
  12219. * Parses SVG XML and converts only some of the SVG elements into
  12220. * PDF elements.
  12221. *
  12222. * Supports:
  12223. * paths
  12224. *
  12225. * @name addSvg
  12226. * @public
  12227. * @function
  12228. * @param {string} SVG-Data as Text
  12229. * @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  12230. * @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  12231. * @param {number} width of SVG (in units declared at inception of PDF document)
  12232. * @param {number} height of SVG (in units declared at inception of PDF document)
  12233. * @returns {Object} jsPDF-instance
  12234. */
  12235. jsPDFAPI.addSvg = function (svgtext, x, y, w, h) {
  12236. // 'this' is _jsPDF object returned when jsPDF is inited (new jsPDF())
  12237. var undef;
  12238. if (x === undef || y === undef) {
  12239. throw new Error("addSVG needs values for 'x' and 'y'");
  12240. }
  12241. function InjectCSS(cssbody, document) {
  12242. var styletag = document.createElement('style');
  12243. styletag.type = 'text/css';
  12244. if (styletag.styleSheet) {
  12245. // ie
  12246. styletag.styleSheet.cssText = cssbody;
  12247. } else {
  12248. // others
  12249. styletag.appendChild(document.createTextNode(cssbody));
  12250. }
  12251. document.getElementsByTagName("head")[0].appendChild(styletag);
  12252. }
  12253. function createWorkerNode(document) {
  12254. var frameID = 'childframe' // Date.now().toString() + '_' + (Math.random() * 100).toString()
  12255. ,
  12256. frame = document.createElement('iframe');
  12257. InjectCSS('.jsPDF_sillysvg_iframe {display:none;position:absolute;}', document);
  12258. frame.name = frameID;
  12259. frame.setAttribute("width", 0);
  12260. frame.setAttribute("height", 0);
  12261. frame.setAttribute("frameborder", "0");
  12262. frame.setAttribute("scrolling", "no");
  12263. frame.setAttribute("seamless", "seamless");
  12264. frame.setAttribute("class", "jsPDF_sillysvg_iframe");
  12265. document.body.appendChild(frame);
  12266. return frame;
  12267. }
  12268. function attachSVGToWorkerNode(svgtext, frame) {
  12269. var framedoc = (frame.contentWindow || frame.contentDocument).document;
  12270. framedoc.write(svgtext);
  12271. framedoc.close();
  12272. return framedoc.getElementsByTagName('svg')[0];
  12273. }
  12274. function convertPathToPDFLinesArgs(path) {
  12275. // - starting coordinate pair
  12276. // - array of arrays of vector shifts (2-len for line, 6 len for bezier)
  12277. // - scale array [horizontal, vertical] ratios
  12278. // - style (stroke, fill, both)
  12279. var x = parseFloat(path[1]),
  12280. y = parseFloat(path[2]),
  12281. vectors = [],
  12282. position = 3,
  12283. len = path.length;
  12284. while (position < len) {
  12285. if (path[position] === 'c') {
  12286. vectors.push([parseFloat(path[position + 1]), parseFloat(path[position + 2]), parseFloat(path[position + 3]), parseFloat(path[position + 4]), parseFloat(path[position + 5]), parseFloat(path[position + 6])]);
  12287. position += 7;
  12288. } else if (path[position] === 'l') {
  12289. vectors.push([parseFloat(path[position + 1]), parseFloat(path[position + 2])]);
  12290. position += 3;
  12291. } else {
  12292. position += 1;
  12293. }
  12294. }
  12295. return [x, y, vectors];
  12296. }
  12297. var workernode = createWorkerNode(document),
  12298. svgnode = attachSVGToWorkerNode(svgtext, workernode),
  12299. scale = [1, 1],
  12300. svgw = parseFloat(svgnode.getAttribute('width')),
  12301. svgh = parseFloat(svgnode.getAttribute('height'));
  12302. if (svgw && svgh) {
  12303. // setting both w and h makes image stretch to size.
  12304. // this may distort the image, but fits your demanded size
  12305. if (w && h) {
  12306. scale = [w / svgw, h / svgh];
  12307. } // if only one is set, that value is set as max and SVG
  12308. // is scaled proportionately.
  12309. else if (w) {
  12310. scale = [w / svgw, w / svgw];
  12311. } else if (h) {
  12312. scale = [h / svgh, h / svgh];
  12313. }
  12314. }
  12315. var i,
  12316. l,
  12317. tmp,
  12318. linesargs,
  12319. items = svgnode.childNodes;
  12320. for (i = 0, l = items.length; i < l; i++) {
  12321. tmp = items[i];
  12322. if (tmp.tagName && tmp.tagName.toUpperCase() === 'PATH') {
  12323. linesargs = convertPathToPDFLinesArgs(tmp.getAttribute("d").split(' ')); // path start x coordinate
  12324. linesargs[0] = linesargs[0] * scale[0] + x; // where x is upper left X of image
  12325. // path start y coordinate
  12326. linesargs[1] = linesargs[1] * scale[1] + y; // where y is upper left Y of image
  12327. // the rest of lines are vectors. these will adjust with scale value auto.
  12328. this.lines.call(this, linesargs[2] // lines
  12329. , linesargs[0] // starting x
  12330. , linesargs[1] // starting y
  12331. , scale);
  12332. }
  12333. } // clean up
  12334. // workernode.parentNode.removeChild(workernode)
  12335. return this;
  12336. }; //fallback
  12337. jsPDFAPI.addSVG = jsPDFAPI.addSvg;
  12338. /**
  12339. * Parses SVG XML and saves it as image into the PDF.
  12340. *
  12341. * Depends on canvas-element and canvg
  12342. *
  12343. * @name addSvgAsImage
  12344. * @public
  12345. * @function
  12346. * @param {string} SVG-Data as Text
  12347. * @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
  12348. * @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
  12349. * @param {number} width of SVG-Image (in units declared at inception of PDF document)
  12350. * @param {number} height of SVG-Image (in units declared at inception of PDF document)
  12351. * @param {string} alias of SVG-Image (if used multiple times)
  12352. * @param {string} compression of the generated JPEG, can have the values 'NONE', 'FAST', 'MEDIUM' and 'SLOW'
  12353. * @param {number} rotation of the image in degrees (0-359)
  12354. *
  12355. * @returns jsPDF jsPDF-instance
  12356. */
  12357. jsPDFAPI.addSvgAsImage = function (svg, x, y, w, h, alias, compression, rotation) {
  12358. if (isNaN(x) || isNaN(y)) {
  12359. console.error('jsPDF.addSvgAsImage: Invalid coordinates', arguments);
  12360. throw new Error('Invalid coordinates passed to jsPDF.addSvgAsImage');
  12361. }
  12362. if (isNaN(w) || isNaN(h)) {
  12363. console.error('jsPDF.addSvgAsImage: Invalid measurements', arguments);
  12364. throw new Error('Invalid measurements (width and/or height) passed to jsPDF.addSvgAsImage');
  12365. }
  12366. var canvas = document.createElement('canvas');
  12367. canvas.width = w;
  12368. canvas.height = h;
  12369. var ctx = canvas.getContext('2d');
  12370. ctx.fillStyle = '#fff'; /// set white fill style
  12371. ctx.fillRect(0, 0, canvas.width, canvas.height); //load a svg snippet in the canvas with id = 'drawingArea'
  12372. canvg(canvas, svg, {
  12373. ignoreMouse: true,
  12374. ignoreAnimation: true,
  12375. ignoreDimensions: true,
  12376. ignoreClear: true
  12377. });
  12378. this.addImage(canvas.toDataURL("image/jpeg", 1.0), x, y, w, h, compression, rotation);
  12379. return this;
  12380. };
  12381. })(jsPDF.API);
  12382. /**
  12383. * @license
  12384. * ====================================================================
  12385. * Copyright (c) 2013 Eduardo Menezes de Morais, eduardo.morais@usp.br
  12386. *
  12387. *
  12388. * ====================================================================
  12389. */
  12390. /**
  12391. * jsPDF total_pages plugin
  12392. * @name total_pages
  12393. * @module
  12394. */
  12395. (function (jsPDFAPI) {
  12396. /**
  12397. * @name putTotalPages
  12398. * @function
  12399. * @param {string} pageExpression Regular Expression
  12400. * @returns {jsPDF} jsPDF-instance
  12401. */
  12402. jsPDFAPI.putTotalPages = function (pageExpression) {
  12403. var replaceExpression;
  12404. var totalNumberOfPages = 0;
  12405. if (parseInt(this.internal.getFont().id.substr(1), 10) < 15) {
  12406. replaceExpression = new RegExp(pageExpression, 'g');
  12407. totalNumberOfPages = this.internal.getNumberOfPages();
  12408. } else {
  12409. replaceExpression = new RegExp(this.pdfEscape16(pageExpression, this.internal.getFont()), 'g');
  12410. totalNumberOfPages = this.pdfEscape16(this.internal.getNumberOfPages() + '', this.internal.getFont());
  12411. }
  12412. for (var n = 1; n <= this.internal.getNumberOfPages(); n++) {
  12413. for (var i = 0; i < this.internal.pages[n].length; i++) {
  12414. this.internal.pages[n][i] = this.internal.pages[n][i].replace(replaceExpression, totalNumberOfPages);
  12415. }
  12416. }
  12417. return this;
  12418. };
  12419. })(jsPDF.API);
  12420. /**
  12421. * jsPDF viewerPreferences Plugin
  12422. * @author Aras Abbasi (github.com/arasabbasi)
  12423. * Licensed under the MIT License.
  12424. * http://opensource.org/licenses/mit-license
  12425. */
  12426. /**
  12427. * Adds the ability to set ViewerPreferences and by thus
  12428. * controlling the way the document is to be presented on the
  12429. * screen or in print.
  12430. * @name viewerpreferences
  12431. * @module
  12432. */
  12433. (function (jsPDFAPI) {
  12434. /**
  12435. * Set the ViewerPreferences of the generated PDF
  12436. *
  12437. * @name viewerPreferences
  12438. * @function
  12439. * @public
  12440. * @param {Object} options Array with the ViewerPreferences<br />
  12441. * Example: doc.viewerPreferences({"FitWindow":true});<br />
  12442. * <br />
  12443. * You can set following preferences:<br />
  12444. * <br/>
  12445. * <b>HideToolbar</b> <i>(boolean)</i><br />
  12446. * Default value: false<br />
  12447. * <br />
  12448. * <b>HideMenubar</b> <i>(boolean)</i><br />
  12449. * Default value: false.<br />
  12450. * <br />
  12451. * <b>HideWindowUI</b> <i>(boolean)</i><br />
  12452. * Default value: false.<br />
  12453. * <br />
  12454. * <b>FitWindow</b> <i>(boolean)</i><br />
  12455. * Default value: false.<br />
  12456. * <br />
  12457. * <b>CenterWindow</b> <i>(boolean)</i><br />
  12458. * Default value: false<br />
  12459. * <br />
  12460. * <b>DisplayDocTitle</b> <i>(boolean)</i><br />
  12461. * Default value: false.<br />
  12462. * <br />
  12463. * <b>NonFullScreenPageMode</b> <i>(string)</i><br />
  12464. * Possible values: UseNone, UseOutlines, UseThumbs, UseOC<br />
  12465. * Default value: UseNone<br/>
  12466. * <br />
  12467. * <b>Direction</b> <i>(string)</i><br />
  12468. * Possible values: L2R, R2L<br />
  12469. * Default value: L2R.<br />
  12470. * <br />
  12471. * <b>ViewArea</b> <i>(string)</i><br />
  12472. * Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox<br />
  12473. * Default value: CropBox.<br />
  12474. * <br />
  12475. * <b>ViewClip</b> <i>(string)</i><br />
  12476. * Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox<br />
  12477. * Default value: CropBox<br />
  12478. * <br />
  12479. * <b>PrintArea</b> <i>(string)</i><br />
  12480. * Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox<br />
  12481. * Default value: CropBox<br />
  12482. * <br />
  12483. * <b>PrintClip</b> <i>(string)</i><br />
  12484. * Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox<br />
  12485. * Default value: CropBox.<br />
  12486. * <br />
  12487. * <b>PrintScaling</b> <i>(string)</i><br />
  12488. * Possible values: AppDefault, None<br />
  12489. * Default value: AppDefault.<br />
  12490. * <br />
  12491. * <b>Duplex</b> <i>(string)</i><br />
  12492. * Possible values: Simplex, DuplexFlipLongEdge, DuplexFlipShortEdge
  12493. * Default value: none<br />
  12494. * <br />
  12495. * <b>PickTrayByPDFSize</b> <i>(boolean)</i><br />
  12496. * Default value: false<br />
  12497. * <br />
  12498. * <b>PrintPageRange</b> <i>(Array)</i><br />
  12499. * Example: [[1,5], [7,9]]<br />
  12500. * Default value: as defined by PDF viewer application<br />
  12501. * <br />
  12502. * <b>NumCopies</b> <i>(Number)</i><br />
  12503. * Possible values: 1, 2, 3, 4, 5<br />
  12504. * Default value: 1<br />
  12505. * <br />
  12506. * For more information see the PDF Reference, sixth edition on Page 577
  12507. * @param {boolean} doReset True to reset the settings
  12508. * @function
  12509. * @returns jsPDF jsPDF-instance
  12510. * @example
  12511. * var doc = new jsPDF()
  12512. * doc.text('This is a test', 10, 10)
  12513. * doc.viewerPreferences({'FitWindow': true}, true)
  12514. * doc.save("viewerPreferences.pdf")
  12515. *
  12516. * // Example printing 10 copies, using cropbox, and hiding UI.
  12517. * doc.viewerPreferences({
  12518. * 'HideWindowUI': true,
  12519. * 'PrintArea': 'CropBox',
  12520. * 'NumCopies': 10
  12521. * })
  12522. */
  12523. jsPDFAPI.viewerPreferences = function (options, doReset) {
  12524. options = options || {};
  12525. doReset = doReset || false;
  12526. var configuration;
  12527. var configurationTemplate = {
  12528. "HideToolbar": {
  12529. defaultValue: false,
  12530. value: false,
  12531. type: "boolean",
  12532. explicitSet: false,
  12533. valueSet: [true, false],
  12534. pdfVersion: 1.3
  12535. },
  12536. "HideMenubar": {
  12537. defaultValue: false,
  12538. value: false,
  12539. type: "boolean",
  12540. explicitSet: false,
  12541. valueSet: [true, false],
  12542. pdfVersion: 1.3
  12543. },
  12544. "HideWindowUI": {
  12545. defaultValue: false,
  12546. value: false,
  12547. type: "boolean",
  12548. explicitSet: false,
  12549. valueSet: [true, false],
  12550. pdfVersion: 1.3
  12551. },
  12552. "FitWindow": {
  12553. defaultValue: false,
  12554. value: false,
  12555. type: "boolean",
  12556. explicitSet: false,
  12557. valueSet: [true, false],
  12558. pdfVersion: 1.3
  12559. },
  12560. "CenterWindow": {
  12561. defaultValue: false,
  12562. value: false,
  12563. type: "boolean",
  12564. explicitSet: false,
  12565. valueSet: [true, false],
  12566. pdfVersion: 1.3
  12567. },
  12568. "DisplayDocTitle": {
  12569. defaultValue: false,
  12570. value: false,
  12571. type: "boolean",
  12572. explicitSet: false,
  12573. valueSet: [true, false],
  12574. pdfVersion: 1.4
  12575. },
  12576. "NonFullScreenPageMode": {
  12577. defaultValue: "UseNone",
  12578. value: "UseNone",
  12579. type: "name",
  12580. explicitSet: false,
  12581. valueSet: ["UseNone", "UseOutlines", "UseThumbs", "UseOC"],
  12582. pdfVersion: 1.3
  12583. },
  12584. "Direction": {
  12585. defaultValue: "L2R",
  12586. value: "L2R",
  12587. type: "name",
  12588. explicitSet: false,
  12589. valueSet: ["L2R", "R2L"],
  12590. pdfVersion: 1.3
  12591. },
  12592. "ViewArea": {
  12593. defaultValue: "CropBox",
  12594. value: "CropBox",
  12595. type: "name",
  12596. explicitSet: false,
  12597. valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"],
  12598. pdfVersion: 1.4
  12599. },
  12600. "ViewClip": {
  12601. defaultValue: "CropBox",
  12602. value: "CropBox",
  12603. type: "name",
  12604. explicitSet: false,
  12605. valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"],
  12606. pdfVersion: 1.4
  12607. },
  12608. "PrintArea": {
  12609. defaultValue: "CropBox",
  12610. value: "CropBox",
  12611. type: "name",
  12612. explicitSet: false,
  12613. valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"],
  12614. pdfVersion: 1.4
  12615. },
  12616. "PrintClip": {
  12617. defaultValue: "CropBox",
  12618. value: "CropBox",
  12619. type: "name",
  12620. explicitSet: false,
  12621. valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"],
  12622. pdfVersion: 1.4
  12623. },
  12624. "PrintScaling": {
  12625. defaultValue: "AppDefault",
  12626. value: "AppDefault",
  12627. type: "name",
  12628. explicitSet: false,
  12629. valueSet: ["AppDefault", "None"],
  12630. pdfVersion: 1.6
  12631. },
  12632. "Duplex": {
  12633. defaultValue: "",
  12634. value: "none",
  12635. type: "name",
  12636. explicitSet: false,
  12637. valueSet: ["Simplex", "DuplexFlipShortEdge", "DuplexFlipLongEdge", "none"],
  12638. pdfVersion: 1.7
  12639. },
  12640. "PickTrayByPDFSize": {
  12641. defaultValue: false,
  12642. value: false,
  12643. type: "boolean",
  12644. explicitSet: false,
  12645. valueSet: [true, false],
  12646. pdfVersion: 1.7
  12647. },
  12648. "PrintPageRange": {
  12649. defaultValue: "",
  12650. value: "",
  12651. type: "array",
  12652. explicitSet: false,
  12653. valueSet: null,
  12654. pdfVersion: 1.7
  12655. },
  12656. "NumCopies": {
  12657. defaultValue: 1,
  12658. value: 1,
  12659. type: "integer",
  12660. explicitSet: false,
  12661. valueSet: null,
  12662. pdfVersion: 1.7
  12663. }
  12664. };
  12665. var configurationKeys = Object.keys(configurationTemplate);
  12666. var rangeArray = [];
  12667. var i = 0;
  12668. var j = 0;
  12669. var k = 0;
  12670. var isValid = true;
  12671. var method;
  12672. var value;
  12673. function arrayContainsElement(array, element) {
  12674. var iterator;
  12675. var result = false;
  12676. for (iterator = 0; iterator < array.length; iterator += 1) {
  12677. if (array[iterator] === element) {
  12678. result = true;
  12679. }
  12680. }
  12681. return result;
  12682. }
  12683. if (this.internal.viewerpreferences === undefined) {
  12684. this.internal.viewerpreferences = {};
  12685. this.internal.viewerpreferences.configuration = JSON.parse(JSON.stringify(configurationTemplate));
  12686. this.internal.viewerpreferences.isSubscribed = false;
  12687. }
  12688. configuration = this.internal.viewerpreferences.configuration;
  12689. if (options === "reset" || doReset === true) {
  12690. var len = configurationKeys.length;
  12691. for (k = 0; k < len; k += 1) {
  12692. configuration[configurationKeys[k]].value = configuration[configurationKeys[k]].defaultValue;
  12693. configuration[configurationKeys[k]].explicitSet = false;
  12694. }
  12695. }
  12696. if (_typeof(options) === "object") {
  12697. for (method in options) {
  12698. value = options[method];
  12699. if (arrayContainsElement(configurationKeys, method) && value !== undefined) {
  12700. if (configuration[method].type === "boolean" && typeof value === "boolean") {
  12701. configuration[method].value = value;
  12702. } else if (configuration[method].type === "name" && arrayContainsElement(configuration[method].valueSet, value)) {
  12703. configuration[method].value = value;
  12704. } else if (configuration[method].type === "integer" && Number.isInteger(value)) {
  12705. configuration[method].value = value;
  12706. } else if (configuration[method].type === "array") {
  12707. for (i = 0; i < value.length; i += 1) {
  12708. isValid = true;
  12709. if (value[i].length === 1 && typeof value[i][0] === "number") {
  12710. rangeArray.push(String(value[i] - 1));
  12711. } else if (value[i].length > 1) {
  12712. for (j = 0; j < value[i].length; j += 1) {
  12713. if (typeof value[i][j] !== "number") {
  12714. isValid = false;
  12715. }
  12716. }
  12717. if (isValid === true) {
  12718. rangeArray.push([value[i][0] - 1, value[i][1] - 1].join(" "));
  12719. }
  12720. }
  12721. }
  12722. configuration[method].value = "[" + rangeArray.join(" ") + "]";
  12723. } else {
  12724. configuration[method].value = configuration[method].defaultValue;
  12725. }
  12726. configuration[method].explicitSet = true;
  12727. }
  12728. }
  12729. }
  12730. if (this.internal.viewerpreferences.isSubscribed === false) {
  12731. this.internal.events.subscribe("putCatalog", function () {
  12732. var pdfDict = [];
  12733. var vPref;
  12734. for (vPref in configuration) {
  12735. if (configuration[vPref].explicitSet === true) {
  12736. if (configuration[vPref].type === "name") {
  12737. pdfDict.push("/" + vPref + " /" + configuration[vPref].value);
  12738. } else {
  12739. pdfDict.push("/" + vPref + " " + configuration[vPref].value);
  12740. }
  12741. }
  12742. }
  12743. if (pdfDict.length !== 0) {
  12744. this.internal.write("/ViewerPreferences\n<<\n" + pdfDict.join("\n") + "\n>>");
  12745. }
  12746. });
  12747. this.internal.viewerpreferences.isSubscribed = true;
  12748. }
  12749. this.internal.viewerpreferences.configuration = configuration;
  12750. return this;
  12751. };
  12752. })(jsPDF.API);
  12753. /** ====================================================================
  12754. * jsPDF XMP metadata plugin
  12755. * Copyright (c) 2016 Jussi Utunen, u-jussi@suomi24.fi
  12756. *
  12757. *
  12758. * ====================================================================
  12759. */
  12760. /*global jsPDF */
  12761. /**
  12762. * @name xmp_metadata
  12763. * @module
  12764. */
  12765. (function (jsPDFAPI) {
  12766. var xmpmetadata = "";
  12767. var xmpnamespaceuri = "";
  12768. var metadata_object_number = "";
  12769. /**
  12770. * Adds XMP formatted metadata to PDF
  12771. *
  12772. * @name addMetadata
  12773. * @function
  12774. * @param {String} metadata The actual metadata to be added. The metadata shall be stored as XMP simple value. Note that if the metadata string contains XML markup characters "<", ">" or "&", those characters should be written using XML entities.
  12775. * @param {String} namespaceuri Sets the namespace URI for the metadata. Last character should be slash or hash.
  12776. * @returns {jsPDF} jsPDF-instance
  12777. */
  12778. jsPDFAPI.addMetadata = function (metadata, namespaceuri) {
  12779. xmpnamespaceuri = namespaceuri || "http://jspdf.default.namespaceuri/"; //The namespace URI for an XMP name shall not be empty
  12780. xmpmetadata = metadata;
  12781. this.internal.events.subscribe('postPutResources', function () {
  12782. if (!xmpmetadata) {
  12783. metadata_object_number = "";
  12784. } else {
  12785. var xmpmeta_beginning = '<x:xmpmeta xmlns:x="adobe:ns:meta/">';
  12786. var rdf_beginning = '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:jspdf="' + xmpnamespaceuri + '"><jspdf:metadata>';
  12787. var rdf_ending = '</jspdf:metadata></rdf:Description></rdf:RDF>';
  12788. var xmpmeta_ending = '</x:xmpmeta>';
  12789. var utf8_xmpmeta_beginning = unescape(encodeURIComponent(xmpmeta_beginning));
  12790. var utf8_rdf_beginning = unescape(encodeURIComponent(rdf_beginning));
  12791. var utf8_metadata = unescape(encodeURIComponent(xmpmetadata));
  12792. var utf8_rdf_ending = unescape(encodeURIComponent(rdf_ending));
  12793. var utf8_xmpmeta_ending = unescape(encodeURIComponent(xmpmeta_ending));
  12794. var total_len = utf8_rdf_beginning.length + utf8_metadata.length + utf8_rdf_ending.length + utf8_xmpmeta_beginning.length + utf8_xmpmeta_ending.length;
  12795. metadata_object_number = this.internal.newObject();
  12796. this.internal.write('<< /Type /Metadata /Subtype /XML /Length ' + total_len + ' >>');
  12797. this.internal.write('stream');
  12798. this.internal.write(utf8_xmpmeta_beginning + utf8_rdf_beginning + utf8_metadata + utf8_rdf_ending + utf8_xmpmeta_ending);
  12799. this.internal.write('endstream');
  12800. this.internal.write('endobj');
  12801. }
  12802. });
  12803. this.internal.events.subscribe('putCatalog', function () {
  12804. if (metadata_object_number) {
  12805. this.internal.write('/Metadata ' + metadata_object_number + ' 0 R');
  12806. }
  12807. });
  12808. return this;
  12809. };
  12810. })(jsPDF.API);
  12811. /**
  12812. * @name utf8
  12813. * @module
  12814. */
  12815. (function (jsPDF, global) {
  12816. var jsPDFAPI = jsPDF.API;
  12817. /**************************************************/
  12818. /* function : toHex */
  12819. /* comment : Replace str with a hex string. */
  12820. /**************************************************/
  12821. function toHex(str) {
  12822. var hex = '';
  12823. for (var i = 0; i < str.length; i++) {
  12824. hex += '' + str.charCodeAt(i).toString(16);
  12825. }
  12826. return hex;
  12827. }
  12828. /***************************************************************************************************/
  12829. /* function : pdfEscape16 */
  12830. /* comment : The character id of a 2-byte string is converted to a hexadecimal number by obtaining */
  12831. /* the corresponding glyph id and width, and then adding padding to the string. */
  12832. /***************************************************************************************************/
  12833. var pdfEscape16 = jsPDFAPI.pdfEscape16 = function (text, font) {
  12834. var widths = font.metadata.Unicode.widths;
  12835. var padz = ["", "0", "00", "000", "0000"];
  12836. var ar = [""];
  12837. for (var i = 0, l = text.length, t; i < l; ++i) {
  12838. t = font.metadata.characterToGlyph(text.charCodeAt(i));
  12839. font.metadata.glyIdsUsed.push(t);
  12840. font.metadata.toUnicode[t] = text.charCodeAt(i);
  12841. if (widths.indexOf(t) == -1) {
  12842. widths.push(t);
  12843. widths.push([parseInt(font.metadata.widthOfGlyph(t), 10)]);
  12844. }
  12845. if (t == '0') {
  12846. //Spaces are not allowed in cmap.
  12847. return ar.join("");
  12848. } else {
  12849. t = t.toString(16);
  12850. ar.push(padz[4 - t.length], t);
  12851. }
  12852. }
  12853. return ar.join("");
  12854. };
  12855. var toUnicodeCmap = function toUnicodeCmap(map) {
  12856. var code, codes, range, unicode, unicodeMap, _i, _len;
  12857. unicodeMap = '/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo <<\n /Registry (Adobe)\n /Ordering (UCS)\n /Supplement 0\n>> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<0000><ffff>\nendcodespacerange';
  12858. codes = Object.keys(map).sort(function (a, b) {
  12859. return a - b;
  12860. });
  12861. range = [];
  12862. for (_i = 0, _len = codes.length; _i < _len; _i++) {
  12863. code = codes[_i];
  12864. if (range.length >= 100) {
  12865. unicodeMap += "\n" + range.length + " beginbfchar\n" + range.join('\n') + "\nendbfchar";
  12866. range = [];
  12867. }
  12868. unicode = ('0000' + map[code].toString(16)).slice(-4);
  12869. code = ('0000' + (+code).toString(16)).slice(-4);
  12870. range.push("<" + code + "><" + unicode + ">");
  12871. }
  12872. if (range.length) {
  12873. unicodeMap += "\n" + range.length + " beginbfchar\n" + range.join('\n') + "\nendbfchar\n";
  12874. }
  12875. unicodeMap += 'endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend';
  12876. return unicodeMap;
  12877. };
  12878. var identityHFunction = function identityHFunction(font, out, newObject, putStream) {
  12879. if (font.metadata instanceof jsPDF.API.TTFFont && font.encoding === 'Identity-H') {
  12880. //Tag with Identity-H
  12881. var widths = font.metadata.Unicode.widths;
  12882. var data = font.metadata.subset.encode(font.metadata.glyIdsUsed, 1);
  12883. var pdfOutput = data;
  12884. var pdfOutput2 = "";
  12885. for (var i = 0; i < pdfOutput.length; i++) {
  12886. pdfOutput2 += String.fromCharCode(pdfOutput[i]);
  12887. }
  12888. var fontTable = newObject();
  12889. putStream({
  12890. data: pdfOutput2,
  12891. addLength1: true
  12892. });
  12893. out('endobj');
  12894. var cmap = newObject();
  12895. var cmapData = toUnicodeCmap(font.metadata.toUnicode);
  12896. putStream({
  12897. data: cmapData,
  12898. addLength1: true
  12899. });
  12900. out('endobj');
  12901. var fontDescriptor = newObject();
  12902. out('<<');
  12903. out('/Type /FontDescriptor');
  12904. out('/FontName /' + font.fontName);
  12905. out('/FontFile2 ' + fontTable + ' 0 R');
  12906. out('/FontBBox ' + jsPDF.API.PDFObject.convert(font.metadata.bbox));
  12907. out('/Flags ' + font.metadata.flags);
  12908. out('/StemV ' + font.metadata.stemV);
  12909. out('/ItalicAngle ' + font.metadata.italicAngle);
  12910. out('/Ascent ' + font.metadata.ascender);
  12911. out('/Descent ' + font.metadata.decender);
  12912. out('/CapHeight ' + font.metadata.capHeight);
  12913. out('>>');
  12914. out('endobj');
  12915. var DescendantFont = newObject();
  12916. out('<<');
  12917. out('/Type /Font');
  12918. out('/BaseFont /' + font.fontName);
  12919. out('/FontDescriptor ' + fontDescriptor + ' 0 R');
  12920. out('/W ' + jsPDF.API.PDFObject.convert(widths));
  12921. out('/CIDToGIDMap /Identity');
  12922. out('/DW 1000');
  12923. out('/Subtype /CIDFontType2');
  12924. out('/CIDSystemInfo');
  12925. out('<<');
  12926. out('/Supplement 0');
  12927. out('/Registry (Adobe)');
  12928. out('/Ordering (' + font.encoding + ')');
  12929. out('>>');
  12930. out('>>');
  12931. out('endobj');
  12932. font.objectNumber = newObject();
  12933. out('<<');
  12934. out('/Type /Font');
  12935. out('/Subtype /Type0');
  12936. out('/ToUnicode ' + cmap + ' 0 R');
  12937. out('/BaseFont /' + font.fontName);
  12938. out('/Encoding /' + font.encoding);
  12939. out('/DescendantFonts [' + DescendantFont + ' 0 R]');
  12940. out('>>');
  12941. out('endobj');
  12942. font.isAlreadyPutted = true;
  12943. }
  12944. };
  12945. jsPDFAPI.events.push(['putFont', function (args) {
  12946. identityHFunction(args.font, args.out, args.newObject, args.putStream);
  12947. }]);
  12948. var winAnsiEncodingFunction = function winAnsiEncodingFunction(font, out, newObject, putStream) {
  12949. if (font.metadata instanceof jsPDF.API.TTFFont && font.encoding === 'WinAnsiEncoding') {
  12950. //Tag with WinAnsi encoding
  12951. var widths = font.metadata.Unicode.widths;
  12952. var data = font.metadata.rawData;
  12953. var pdfOutput = data;
  12954. var pdfOutput2 = "";
  12955. for (var i = 0; i < pdfOutput.length; i++) {
  12956. pdfOutput2 += String.fromCharCode(pdfOutput[i]);
  12957. }
  12958. var fontTable = newObject();
  12959. putStream({
  12960. data: pdfOutput2,
  12961. addLength1: true
  12962. });
  12963. out('endobj');
  12964. var cmap = newObject();
  12965. var cmapData = toUnicodeCmap(font.metadata.toUnicode);
  12966. putStream({
  12967. data: cmapData,
  12968. addLength1: true
  12969. });
  12970. out('endobj');
  12971. var fontDescriptor = newObject();
  12972. out('<<');
  12973. out('/Descent ' + font.metadata.decender);
  12974. out('/CapHeight ' + font.metadata.capHeight);
  12975. out('/StemV ' + font.metadata.stemV);
  12976. out('/Type /FontDescriptor');
  12977. out('/FontFile2 ' + fontTable + ' 0 R');
  12978. out('/Flags 96');
  12979. out('/FontBBox ' + jsPDF.API.PDFObject.convert(font.metadata.bbox));
  12980. out('/FontName /' + font.fontName);
  12981. out('/ItalicAngle ' + font.metadata.italicAngle);
  12982. out('/Ascent ' + font.metadata.ascender);
  12983. out('>>');
  12984. out('endobj');
  12985. font.objectNumber = newObject();
  12986. for (var i = 0; i < font.metadata.hmtx.widths.length; i++) {
  12987. font.metadata.hmtx.widths[i] = parseInt(font.metadata.hmtx.widths[i] * (1000 / font.metadata.head.unitsPerEm)); //Change the width of Em units to Point units.
  12988. }
  12989. out('<</Subtype/TrueType/Type/Font/ToUnicode ' + cmap + ' 0 R/BaseFont/' + font.fontName + '/FontDescriptor ' + fontDescriptor + ' 0 R' + '/Encoding/' + font.encoding + ' /FirstChar 29 /LastChar 255 /Widths ' + jsPDF.API.PDFObject.convert(font.metadata.hmtx.widths) + '>>');
  12990. out('endobj');
  12991. font.isAlreadyPutted = true;
  12992. }
  12993. };
  12994. jsPDFAPI.events.push(['putFont', function (args) {
  12995. winAnsiEncodingFunction(args.font, args.out, args.newObject, args.putStream);
  12996. }]);
  12997. var utf8TextFunction = function utf8TextFunction(args) {
  12998. var text = args.text || '';
  12999. var x = args.x;
  13000. var y = args.y;
  13001. var options = args.options || {};
  13002. var mutex = args.mutex || {};
  13003. var pdfEscape = mutex.pdfEscape;
  13004. var activeFontKey = mutex.activeFontKey;
  13005. var fonts = mutex.fonts;
  13006. var key,
  13007. fontSize = mutex.activeFontSize;
  13008. var str = '',
  13009. s = 0,
  13010. cmapConfirm;
  13011. var strText = '';
  13012. var key = activeFontKey;
  13013. var encoding = fonts[key].encoding;
  13014. if (fonts[key].encoding !== 'Identity-H') {
  13015. return {
  13016. text: text,
  13017. x: x,
  13018. y: y,
  13019. options: options,
  13020. mutex: mutex
  13021. };
  13022. }
  13023. strText = text;
  13024. key = activeFontKey;
  13025. if (Object.prototype.toString.call(text) === '[object Array]') {
  13026. strText = text[0];
  13027. }
  13028. for (s = 0; s < strText.length; s += 1) {
  13029. if (fonts[key].metadata.hasOwnProperty('cmap')) {
  13030. cmapConfirm = fonts[key].metadata.cmap.unicode.codeMap[strText[s].charCodeAt(0)];
  13031. /*
  13032. if (Object.prototype.toString.call(text) === '[object Array]') {
  13033. var i = 0;
  13034. // for (i = 0; i < text.length; i += 1) {
  13035. if (Object.prototype.toString.call(text[s]) === '[object Array]') {
  13036. cmapConfirm = fonts[key].metadata.cmap.unicode.codeMap[strText[s][0].charCodeAt(0)]; //Make sure the cmap has the corresponding glyph id
  13037. } else {
  13038. }
  13039. //}
  13040. } else {
  13041. cmapConfirm = fonts[key].metadata.cmap.unicode.codeMap[strText[s].charCodeAt(0)]; //Make sure the cmap has the corresponding glyph id
  13042. }*/
  13043. }
  13044. if (!cmapConfirm) {
  13045. if (strText[s].charCodeAt(0) < 256 && fonts[key].metadata.hasOwnProperty('Unicode')) {
  13046. str += strText[s];
  13047. } else {
  13048. str += '';
  13049. }
  13050. } else {
  13051. str += strText[s];
  13052. }
  13053. }
  13054. var result = '';
  13055. if (parseInt(key.slice(1)) < 14 || encoding === 'WinAnsiEncoding') {
  13056. //For the default 13 font
  13057. result = toHex(pdfEscape(str, key));
  13058. } else if (encoding === 'Identity-H') {
  13059. result = pdfEscape16(str, fonts[key]);
  13060. }
  13061. mutex.isHex = true;
  13062. return {
  13063. text: result,
  13064. x: x,
  13065. y: y,
  13066. options: options,
  13067. mutex: mutex
  13068. };
  13069. };
  13070. var utf8EscapeFunction = function utf8EscapeFunction(parms) {
  13071. var text = parms.text || '',
  13072. x = parms.x,
  13073. y = parms.y,
  13074. options = parms.options,
  13075. mutex = parms.mutex;
  13076. var lang = options.lang;
  13077. var tmpText = [];
  13078. var args = {
  13079. text: text,
  13080. x: x,
  13081. y: y,
  13082. options: options,
  13083. mutex: mutex
  13084. };
  13085. if (Object.prototype.toString.call(text) === '[object Array]') {
  13086. var i = 0;
  13087. for (i = 0; i < text.length; i += 1) {
  13088. if (Object.prototype.toString.call(text[i]) === '[object Array]') {
  13089. if (text[i].length === 3) {
  13090. tmpText.push([utf8TextFunction(Object.assign({}, args, {
  13091. text: text[i][0]
  13092. })).text, text[i][1], text[i][2]]);
  13093. } else {
  13094. tmpText.push(utf8TextFunction(Object.assign({}, args, {
  13095. text: text[i]
  13096. })).text);
  13097. }
  13098. } else {
  13099. tmpText.push(utf8TextFunction(Object.assign({}, args, {
  13100. text: text[i]
  13101. })).text);
  13102. }
  13103. }
  13104. parms.text = tmpText;
  13105. } else {
  13106. parms.text = utf8TextFunction(Object.assign({}, args, {
  13107. text: text
  13108. })).text;
  13109. }
  13110. };
  13111. jsPDFAPI.events.push(['postProcessText', utf8EscapeFunction]);
  13112. })(jsPDF, typeof self !== "undefined" && self || typeof global !== "undefined" && global || typeof window !== "undefined" && window || Function("return this")());
  13113. /**
  13114. * jsPDF virtual FileSystem functionality
  13115. *
  13116. * Licensed under the MIT License.
  13117. * http://opensource.org/licenses/mit-license
  13118. */
  13119. /**
  13120. * Use the vFS to handle files
  13121. *
  13122. * @name vFS
  13123. * @module
  13124. */
  13125. (function (jsPDFAPI) {
  13126. var _initializeVFS = function _initializeVFS(instance) {
  13127. if (typeof instance === "undefined") {
  13128. return false;
  13129. }
  13130. if (typeof instance.vFS === "undefined") {
  13131. instance.vFS = {};
  13132. }
  13133. return true;
  13134. };
  13135. /**
  13136. * Check if the file exists in the vFS
  13137. *
  13138. * @name existsFileInVFS
  13139. * @function
  13140. * @param {string} Possible filename in the vFS.
  13141. * @returns {boolean}
  13142. * @example
  13143. * doc.existsFileInVFS("someFile.txt");
  13144. */
  13145. jsPDFAPI.existsFileInVFS = function (filename) {
  13146. if (_initializeVFS(this.internal)) {
  13147. return typeof this.internal.vFS[filename] !== "undefined";
  13148. }
  13149. return false;
  13150. };
  13151. /**
  13152. * Add a file to the vFS
  13153. *
  13154. * @name addFileToVFS
  13155. * @function
  13156. * @param {string} filename The name of the file which should be added.
  13157. * @param {string} filecontent The content of the file.
  13158. * @returns {jsPDF}
  13159. * @example
  13160. * doc.addFileToVFS("someFile.txt", "BADFACE1");
  13161. */
  13162. jsPDFAPI.addFileToVFS = function (filename, filecontent) {
  13163. _initializeVFS(this.internal);
  13164. this.internal.vFS[filename] = filecontent;
  13165. return this;
  13166. };
  13167. /**
  13168. * Get the file from the vFS
  13169. *
  13170. * @name getFileFromVFS
  13171. * @function
  13172. * @param {string} The name of the file which gets requested.
  13173. * @returns {string}
  13174. * @example
  13175. * doc.getFileFromVFS("someFile.txt");
  13176. */
  13177. jsPDFAPI.getFileFromVFS = function (filename) {
  13178. _initializeVFS(this.internal);
  13179. if (typeof this.internal.vFS[filename] !== "undefined") {
  13180. return this.internal.vFS[filename];
  13181. }
  13182. return null;
  13183. };
  13184. })(jsPDF.API);
  13185. /*
  13186. * Copyright (c) 2012 chick307 <chick307@gmail.com>
  13187. *
  13188. * Licensed under the MIT License.
  13189. * http://opensource.org/licenses/mit-license
  13190. */
  13191. (function (jsPDF, callback) {
  13192. jsPDF.API.adler32cs = callback();
  13193. })(jsPDF, function () {
  13194. var _hasArrayBuffer = typeof ArrayBuffer === 'function' && typeof Uint8Array === 'function';
  13195. var _Buffer = null,
  13196. _isBuffer = function () {
  13197. if (!_hasArrayBuffer) return function _isBuffer() {
  13198. return false;
  13199. };
  13200. try {
  13201. var buffer = {};
  13202. if (typeof buffer.Buffer === 'function') _Buffer = buffer.Buffer;
  13203. } catch (error) {}
  13204. return function _isBuffer(value) {
  13205. return value instanceof ArrayBuffer || _Buffer !== null && value instanceof _Buffer;
  13206. };
  13207. }();
  13208. var _utf8ToBinary = function () {
  13209. if (_Buffer !== null) {
  13210. return function _utf8ToBinary(utf8String) {
  13211. return new _Buffer(utf8String, 'utf8').toString('binary');
  13212. };
  13213. } else {
  13214. return function _utf8ToBinary(utf8String) {
  13215. return unescape(encodeURIComponent(utf8String));
  13216. };
  13217. }
  13218. }();
  13219. var MOD = 65521;
  13220. var _update = function _update(checksum, binaryString) {
  13221. var a = checksum & 0xFFFF,
  13222. b = checksum >>> 16;
  13223. for (var i = 0, length = binaryString.length; i < length; i++) {
  13224. a = (a + (binaryString.charCodeAt(i) & 0xFF)) % MOD;
  13225. b = (b + a) % MOD;
  13226. }
  13227. return (b << 16 | a) >>> 0;
  13228. };
  13229. var _updateUint8Array = function _updateUint8Array(checksum, uint8Array) {
  13230. var a = checksum & 0xFFFF,
  13231. b = checksum >>> 16;
  13232. for (var i = 0, length = uint8Array.length; i < length; i++) {
  13233. a = (a + uint8Array[i]) % MOD;
  13234. b = (b + a) % MOD;
  13235. }
  13236. return (b << 16 | a) >>> 0;
  13237. };
  13238. var exports = {};
  13239. var Adler32 = exports.Adler32 = function () {
  13240. var ctor = function Adler32(checksum) {
  13241. if (!(this instanceof ctor)) {
  13242. throw new TypeError('Constructor cannot called be as a function.');
  13243. }
  13244. if (!isFinite(checksum = checksum == null ? 1 : +checksum)) {
  13245. throw new Error('First arguments needs to be a finite number.');
  13246. }
  13247. this.checksum = checksum >>> 0;
  13248. };
  13249. var proto = ctor.prototype = {};
  13250. proto.constructor = ctor;
  13251. ctor.from = function (from) {
  13252. from.prototype = proto;
  13253. return from;
  13254. }(function from(binaryString) {
  13255. if (!(this instanceof ctor)) {
  13256. throw new TypeError('Constructor cannot called be as a function.');
  13257. }
  13258. if (binaryString == null) throw new Error('First argument needs to be a string.');
  13259. this.checksum = _update(1, binaryString.toString());
  13260. });
  13261. ctor.fromUtf8 = function (fromUtf8) {
  13262. fromUtf8.prototype = proto;
  13263. return fromUtf8;
  13264. }(function fromUtf8(utf8String) {
  13265. if (!(this instanceof ctor)) {
  13266. throw new TypeError('Constructor cannot called be as a function.');
  13267. }
  13268. if (utf8String == null) throw new Error('First argument needs to be a string.');
  13269. var binaryString = _utf8ToBinary(utf8String.toString());
  13270. this.checksum = _update(1, binaryString);
  13271. });
  13272. if (_hasArrayBuffer) {
  13273. ctor.fromBuffer = function (fromBuffer) {
  13274. fromBuffer.prototype = proto;
  13275. return fromBuffer;
  13276. }(function fromBuffer(buffer) {
  13277. if (!(this instanceof ctor)) {
  13278. throw new TypeError('Constructor cannot called be as a function.');
  13279. }
  13280. if (!_isBuffer(buffer)) throw new Error('First argument needs to be ArrayBuffer.');
  13281. var array = new Uint8Array(buffer);
  13282. return this.checksum = _updateUint8Array(1, array);
  13283. });
  13284. }
  13285. proto.update = function update(binaryString) {
  13286. if (binaryString == null) throw new Error('First argument needs to be a string.');
  13287. binaryString = binaryString.toString();
  13288. return this.checksum = _update(this.checksum, binaryString);
  13289. };
  13290. proto.updateUtf8 = function updateUtf8(utf8String) {
  13291. if (utf8String == null) throw new Error('First argument needs to be a string.');
  13292. var binaryString = _utf8ToBinary(utf8String.toString());
  13293. return this.checksum = _update(this.checksum, binaryString);
  13294. };
  13295. if (_hasArrayBuffer) {
  13296. proto.updateBuffer = function updateBuffer(buffer) {
  13297. if (!_isBuffer(buffer)) throw new Error('First argument needs to be ArrayBuffer.');
  13298. var array = new Uint8Array(buffer);
  13299. return this.checksum = _updateUint8Array(this.checksum, array);
  13300. };
  13301. }
  13302. proto.clone = function clone() {
  13303. return new Adler32(this.checksum);
  13304. };
  13305. return ctor;
  13306. }();
  13307. exports.from = function from(binaryString) {
  13308. if (binaryString == null) throw new Error('First argument needs to be a string.');
  13309. return _update(1, binaryString.toString());
  13310. };
  13311. exports.fromUtf8 = function fromUtf8(utf8String) {
  13312. if (utf8String == null) throw new Error('First argument needs to be a string.');
  13313. var binaryString = _utf8ToBinary(utf8String.toString());
  13314. return _update(1, binaryString);
  13315. };
  13316. if (_hasArrayBuffer) {
  13317. exports.fromBuffer = function fromBuffer(buffer) {
  13318. if (!_isBuffer(buffer)) throw new Error('First argument need to be ArrayBuffer.');
  13319. var array = new Uint8Array(buffer);
  13320. return _updateUint8Array(1, array);
  13321. };
  13322. }
  13323. return exports;
  13324. });
  13325. /**
  13326. * Unicode Bidi Engine based on the work of Alex Shensis (@asthensis)
  13327. * MIT License
  13328. */
  13329. (function (jsPDF) {
  13330. /**
  13331. * Table of Unicode types.
  13332. *
  13333. * Generated by:
  13334. *
  13335. * var bidi = require("./bidi/index");
  13336. * var bidi_accumulate = bidi.slice(0, 256).concat(bidi.slice(0x0500, 0x0500 + 256 * 3)).
  13337. * concat(bidi.slice(0x2000, 0x2000 + 256)).concat(bidi.slice(0xFB00, 0xFB00 + 256)).
  13338. * concat(bidi.slice(0xFE00, 0xFE00 + 2 * 256));
  13339. *
  13340. * for( var i = 0; i < bidi_accumulate.length; i++) {
  13341. * if(bidi_accumulate[i] === undefined || bidi_accumulate[i] === 'ON')
  13342. * bidi_accumulate[i] = 'N'; //mark as neutral to conserve space and substitute undefined
  13343. * }
  13344. * var bidiAccumulateStr = 'return [ "' + bidi_accumulate.toString().replace(/,/g, '", "') + '" ];';
  13345. * require("fs").writeFile('unicode-types.js', bidiAccumulateStr);
  13346. *
  13347. * Based on:
  13348. * https://github.com/mathiasbynens/unicode-8.0.0
  13349. */
  13350. var bidiUnicodeTypes = ["BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "S", "B", "S", "WS", "B", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "B", "B", "B", "S", "WS", "N", "N", "ET", "ET", "ET", "N", "N", "N", "N", "N", "ES", "CS", "ES", "CS", "CS", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "CS", "N", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "N", "N", "N", "BN", "BN", "BN", "BN", "BN", "BN", "B", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "BN", "CS", "N", "ET", "ET", "ET", "ET", "N", "N", "N", "N", "L", "N", "N", "BN", "N", "N", "ET", "ET", "EN", "EN", "N", "L", "N", "N", "N", "EN", "L", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "N", "L", "L", "L", "L", "L", "L", "L", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "L", "N", "N", "N", "N", "N", "ET", "N", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "R", "NSM", "R", "NSM", "NSM", "R", "NSM", "NSM", "R", "NSM", "N", "N", "N", "N", "N", "N", "N", "N", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "N", "N", "N", "N", "N", "R", "R", "R", "R", "R", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "AN", "AN", "AN", "AN", "AN", "AN", "N", "N", "AL", "ET", "ET", "AL", "CS", "AL", "N", "N", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AL", "AL", "N", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AN", "AN", "AN", "AN", "AN", "AN", "AN", "AN", "AN", "AN", "ET", "AN", "AN", "AL", "AL", "AL", "NSM", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AN", "N", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AL", "AL", "NSM", "NSM", "N", "NSM", "NSM", "NSM", "NSM", "AL", "AL", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "N", "AL", "AL", "NSM", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "N", "N", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "AL", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "R", "R", "N", "N", "N", "N", "R", "N", "N", "N", "N", "N", "WS", "WS", "WS", "WS", "WS", "WS", "WS", "WS", "WS", "WS", "WS", "BN", "BN", "BN", "L", "R", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "WS", "B", "LRE", "RLE", "PDF", "LRO", "RLO", "CS", "ET", "ET", "ET", "ET", "ET", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "CS", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "WS", "BN", "BN", "BN", "BN", "BN", "N", "LRI", "RLI", "FSI", "PDI", "BN", "BN", "BN", "BN", "BN", "BN", "EN", "L", "N", "N", "EN", "EN", "EN", "EN", "EN", "EN", "ES", "ES", "N", "N", "N", "L", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "ES", "ES", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "N", "N", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "ET", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "N", "N", "N", "N", "N", "R", "NSM", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "ES", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "N", "R", "R", "R", "R", "R", "N", "R", "N", "R", "R", "N", "R", "R", "N", "R", "R", "R", "R", "R", "R", "R", "R", "R", "R", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "NSM", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "CS", "N", "CS", "N", "N", "CS", "N", "N", "N", "N", "N", "N", "N", "N", "N", "ET", "N", "N", "ES", "ES", "N", "N", "N", "N", "N", "ET", "ET", "N", "N", "N", "N", "N", "AL", "AL", "AL", "AL", "AL", "N", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "AL", "N", "N", "BN", "N", "N", "N", "ET", "ET", "ET", "N", "N", "N", "N", "N", "ES", "CS", "ES", "CS", "CS", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "EN", "CS", "N", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "N", "N", "N", "L", "L", "L", "L", "L", "L", "N", "N", "L", "L", "L", "L", "L", "L", "N", "N", "L", "L", "L", "L", "L", "L", "N", "N", "L", "L", "L", "N", "N", "N", "ET", "ET", "N", "N", "N", "ET", "ET", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N"];
  13351. /**
  13352. * Unicode Bidi algorithm compliant Bidi engine.
  13353. * For reference see http://unicode.org/reports/tr9/
  13354. */
  13355. /**
  13356. * constructor ( options )
  13357. *
  13358. * Initializes Bidi engine
  13359. *
  13360. * @param {Object} See 'setOptions' below for detailed description.
  13361. * options are cashed between invocation of 'doBidiReorder' method
  13362. *
  13363. * sample usage pattern of BidiEngine:
  13364. * var opt = {
  13365. * isInputVisual: true,
  13366. * isInputRtl: false,
  13367. * isOutputVisual: false,
  13368. * isOutputRtl: false,
  13369. * isSymmetricSwapping: true
  13370. * }
  13371. * var sourceToTarget = [], levels = [];
  13372. * var bidiEng = Globalize.bidiEngine(opt);
  13373. * var src = "text string to be reordered";
  13374. * var ret = bidiEng.doBidiReorder(src, sourceToTarget, levels);
  13375. */
  13376. jsPDF.__bidiEngine__ = jsPDF.prototype.__bidiEngine__ = function (options) {
  13377. var _UNICODE_TYPES = _bidiUnicodeTypes;
  13378. var _STATE_TABLE_LTR = [[0, 3, 0, 1, 0, 0, 0], [0, 3, 0, 1, 2, 2, 0], [0, 3, 0, 0x11, 2, 0, 1], [0, 3, 5, 5, 4, 1, 0], [0, 3, 0x15, 0x15, 4, 0, 1], [0, 3, 5, 5, 4, 2, 0]];
  13379. var _STATE_TABLE_RTL = [[2, 0, 1, 1, 0, 1, 0], [2, 0, 1, 1, 0, 2, 0], [2, 0, 2, 1, 3, 2, 0], [2, 0, 2, 0x21, 3, 1, 1]];
  13380. var _TYPE_NAMES_MAP = {
  13381. "L": 0,
  13382. "R": 1,
  13383. "EN": 2,
  13384. "AN": 3,
  13385. "N": 4,
  13386. "B": 5,
  13387. "S": 6
  13388. };
  13389. var _UNICODE_RANGES_MAP = {
  13390. 0: 0,
  13391. 5: 1,
  13392. 6: 2,
  13393. 7: 3,
  13394. 0x20: 4,
  13395. 0xFB: 5,
  13396. 0xFE: 6,
  13397. 0xFF: 7
  13398. };
  13399. var _SWAP_TABLE = ["(", ")", "(", "<", ">", "<", "[", "]", "[", "{", "}", "{", "\xAB", "\xBB", "\xAB", "\u2039", "\u203A", "\u2039", "\u2045", "\u2046", "\u2045", "\u207D", "\u207E", "\u207D", "\u208D", "\u208E", "\u208D", "\u2264", "\u2265", "\u2264", "\u2329", "\u232A", "\u2329", "\uFE59", "\uFE5A", "\uFE59", "\uFE5B", "\uFE5C", "\uFE5B", "\uFE5D", "\uFE5E", "\uFE5D", "\uFE64", "\uFE65", "\uFE64"];
  13400. var _LTR_RANGES_REG_EXPR = new RegExp(/^([1-4|9]|1[0-9]|2[0-9]|3[0168]|4[04589]|5[012]|7[78]|159|16[0-9]|17[0-2]|21[569]|22[03489]|250)$/);
  13401. var _lastArabic = false,
  13402. _hasUbatB,
  13403. _hasUbatS,
  13404. DIR_LTR = 0,
  13405. DIR_RTL = 1,
  13406. _isInVisual,
  13407. _isInRtl,
  13408. _isOutVisual,
  13409. _isOutRtl,
  13410. _isSymmetricSwapping,
  13411. _dir = DIR_LTR;
  13412. this.__bidiEngine__ = {};
  13413. var _init = function _init(text, sourceToTargetMap) {
  13414. if (sourceToTargetMap) {
  13415. for (var i = 0; i < text.length; i++) {
  13416. sourceToTargetMap[i] = i;
  13417. }
  13418. }
  13419. if (_isInRtl === undefined) {
  13420. _isInRtl = _isContextualDirRtl(text);
  13421. }
  13422. if (_isOutRtl === undefined) {
  13423. _isOutRtl = _isContextualDirRtl(text);
  13424. }
  13425. }; // for reference see 3.2 in http://unicode.org/reports/tr9/
  13426. //
  13427. var _getCharType = function _getCharType(ch) {
  13428. var charCode = ch.charCodeAt(),
  13429. range = charCode >> 8,
  13430. rangeIdx = _UNICODE_RANGES_MAP[range];
  13431. if (rangeIdx !== undefined) {
  13432. return _UNICODE_TYPES[rangeIdx * 256 + (charCode & 0xFF)];
  13433. } else if (range === 0xFC || range === 0xFD) {
  13434. return "AL";
  13435. } else if (_LTR_RANGES_REG_EXPR.test(range)) {
  13436. //unlikely case
  13437. return "L";
  13438. } else if (range === 8) {
  13439. // even less likely
  13440. return "R";
  13441. }
  13442. return "N"; //undefined type, mark as neutral
  13443. };
  13444. var _isContextualDirRtl = function _isContextualDirRtl(text) {
  13445. for (var i = 0, charType; i < text.length; i++) {
  13446. charType = _getCharType(text.charAt(i));
  13447. if (charType === "L") {
  13448. return false;
  13449. } else if (charType === "R") {
  13450. return true;
  13451. }
  13452. }
  13453. return false;
  13454. }; // for reference see 3.3.4 & 3.3.5 in http://unicode.org/reports/tr9/
  13455. //
  13456. var _resolveCharType = function _resolveCharType(chars, types, resolvedTypes, index) {
  13457. var cType = types[index],
  13458. wType,
  13459. nType,
  13460. i,
  13461. len;
  13462. switch (cType) {
  13463. case "L":
  13464. case "R":
  13465. _lastArabic = false;
  13466. break;
  13467. case "N":
  13468. case "AN":
  13469. break;
  13470. case "EN":
  13471. if (_lastArabic) {
  13472. cType = "AN";
  13473. }
  13474. break;
  13475. case "AL":
  13476. _lastArabic = true;
  13477. cType = "R";
  13478. break;
  13479. case "WS":
  13480. cType = "N";
  13481. break;
  13482. case "CS":
  13483. if (index < 1 || index + 1 >= types.length || (wType = resolvedTypes[index - 1]) !== "EN" && wType !== "AN" || (nType = types[index + 1]) !== "EN" && nType !== "AN") {
  13484. cType = "N";
  13485. } else if (_lastArabic) {
  13486. nType = "AN";
  13487. }
  13488. cType = nType === wType ? nType : "N";
  13489. break;
  13490. case "ES":
  13491. wType = index > 0 ? resolvedTypes[index - 1] : "B";
  13492. cType = wType === "EN" && index + 1 < types.length && types[index + 1] === "EN" ? "EN" : "N";
  13493. break;
  13494. case "ET":
  13495. if (index > 0 && resolvedTypes[index - 1] === "EN") {
  13496. cType = "EN";
  13497. break;
  13498. } else if (_lastArabic) {
  13499. cType = "N";
  13500. break;
  13501. }
  13502. i = index + 1;
  13503. len = types.length;
  13504. while (i < len && types[i] === "ET") {
  13505. i++;
  13506. }
  13507. if (i < len && types[i] === "EN") {
  13508. cType = "EN";
  13509. } else {
  13510. cType = "N";
  13511. }
  13512. break;
  13513. case "NSM":
  13514. if (_isInVisual && !_isInRtl) {
  13515. //V->L
  13516. len = types.length;
  13517. i = index + 1;
  13518. while (i < len && types[i] === "NSM") {
  13519. i++;
  13520. }
  13521. if (i < len) {
  13522. var c = chars[index];
  13523. var rtlCandidate = c >= 0x0591 && c <= 0x08FF || c === 0xFB1E;
  13524. wType = types[i];
  13525. if (rtlCandidate && (wType === "R" || wType === "AL")) {
  13526. cType = "R";
  13527. break;
  13528. }
  13529. }
  13530. }
  13531. if (index < 1 || (wType = types[index - 1]) === "B") {
  13532. cType = "N";
  13533. } else {
  13534. cType = resolvedTypes[index - 1];
  13535. }
  13536. break;
  13537. case "B":
  13538. _lastArabic = false;
  13539. _hasUbatB = true;
  13540. cType = _dir;
  13541. break;
  13542. case "S":
  13543. _hasUbatS = true;
  13544. cType = "N";
  13545. break;
  13546. case "LRE":
  13547. case "RLE":
  13548. case "LRO":
  13549. case "RLO":
  13550. case "PDF":
  13551. _lastArabic = false;
  13552. break;
  13553. case "BN":
  13554. cType = "N";
  13555. break;
  13556. }
  13557. return cType;
  13558. };
  13559. var _handleUbatS = function _handleUbatS(types, levels, length) {
  13560. for (var i = 0; i < length; i++) {
  13561. if (types[i] === "S") {
  13562. levels[i] = _dir;
  13563. for (var j = i - 1; j >= 0; j--) {
  13564. if (types[j] === "WS") {
  13565. levels[j] = _dir;
  13566. } else {
  13567. break;
  13568. }
  13569. }
  13570. }
  13571. }
  13572. };
  13573. var _invertString = function _invertString(text, sourceToTargetMap, levels) {
  13574. var charArray = text.split("");
  13575. if (levels) {
  13576. _computeLevels(charArray, levels, {
  13577. hiLevel: _dir
  13578. });
  13579. }
  13580. charArray.reverse();
  13581. sourceToTargetMap && sourceToTargetMap.reverse();
  13582. return charArray.join("");
  13583. }; // For reference see 3.3 in http://unicode.org/reports/tr9/
  13584. //
  13585. var _computeLevels = function _computeLevels(chars, levels, params) {
  13586. var action,
  13587. condition,
  13588. i,
  13589. index,
  13590. newLevel,
  13591. prevState,
  13592. condPos = -1,
  13593. len = chars.length,
  13594. newState = 0,
  13595. resolvedTypes = [],
  13596. stateTable = _dir ? _STATE_TABLE_RTL : _STATE_TABLE_LTR,
  13597. types = [];
  13598. _lastArabic = false;
  13599. _hasUbatB = false;
  13600. _hasUbatS = false;
  13601. for (i = 0; i < len; i++) {
  13602. types[i] = _getCharType(chars[i]);
  13603. }
  13604. for (index = 0; index < len; index++) {
  13605. prevState = newState;
  13606. resolvedTypes[index] = _resolveCharType(chars, types, resolvedTypes, index);
  13607. newState = stateTable[prevState][_TYPE_NAMES_MAP[resolvedTypes[index]]];
  13608. action = newState & 0xF0;
  13609. newState &= 0x0F;
  13610. levels[index] = newLevel = stateTable[newState][5];
  13611. if (action > 0) {
  13612. if (action === 0x10) {
  13613. for (i = condPos; i < index; i++) {
  13614. levels[i] = 1;
  13615. }
  13616. condPos = -1;
  13617. } else {
  13618. condPos = -1;
  13619. }
  13620. }
  13621. condition = stateTable[newState][6];
  13622. if (condition) {
  13623. if (condPos === -1) {
  13624. condPos = index;
  13625. }
  13626. } else {
  13627. if (condPos > -1) {
  13628. for (i = condPos; i < index; i++) {
  13629. levels[i] = newLevel;
  13630. }
  13631. condPos = -1;
  13632. }
  13633. }
  13634. if (types[index] === "B") {
  13635. levels[index] = 0;
  13636. }
  13637. params.hiLevel |= newLevel;
  13638. }
  13639. if (_hasUbatS) {
  13640. _handleUbatS(types, levels, len);
  13641. }
  13642. }; // for reference see 3.4 in http://unicode.org/reports/tr9/
  13643. //
  13644. var _invertByLevel = function _invertByLevel(level, charArray, sourceToTargetMap, levels, params) {
  13645. if (params.hiLevel < level) {
  13646. return;
  13647. }
  13648. if (level === 1 && _dir === DIR_RTL && !_hasUbatB) {
  13649. charArray.reverse();
  13650. sourceToTargetMap && sourceToTargetMap.reverse();
  13651. return;
  13652. }
  13653. var ch,
  13654. high,
  13655. end,
  13656. low,
  13657. len = charArray.length,
  13658. start = 0;
  13659. while (start < len) {
  13660. if (levels[start] >= level) {
  13661. end = start + 1;
  13662. while (end < len && levels[end] >= level) {
  13663. end++;
  13664. }
  13665. for (low = start, high = end - 1; low < high; low++, high--) {
  13666. ch = charArray[low];
  13667. charArray[low] = charArray[high];
  13668. charArray[high] = ch;
  13669. if (sourceToTargetMap) {
  13670. ch = sourceToTargetMap[low];
  13671. sourceToTargetMap[low] = sourceToTargetMap[high];
  13672. sourceToTargetMap[high] = ch;
  13673. }
  13674. }
  13675. start = end;
  13676. }
  13677. start++;
  13678. }
  13679. }; // for reference see 7 & BD16 in http://unicode.org/reports/tr9/
  13680. //
  13681. var _symmetricSwap = function _symmetricSwap(charArray, levels, params) {
  13682. if (params.hiLevel !== 0 && _isSymmetricSwapping) {
  13683. for (var i = 0, index; i < charArray.length; i++) {
  13684. if (levels[i] === 1) {
  13685. index = _SWAP_TABLE.indexOf(charArray[i]);
  13686. if (index >= 0) {
  13687. charArray[i] = _SWAP_TABLE[index + 1];
  13688. }
  13689. }
  13690. }
  13691. }
  13692. };
  13693. var _reorder = function _reorder(text, sourceToTargetMap, levels) {
  13694. var charArray = text.split(""),
  13695. params = {
  13696. hiLevel: _dir
  13697. };
  13698. if (!levels) {
  13699. levels = [];
  13700. }
  13701. _computeLevels(charArray, levels, params);
  13702. _symmetricSwap(charArray, levels, params);
  13703. _invertByLevel(DIR_RTL + 1, charArray, sourceToTargetMap, levels, params);
  13704. _invertByLevel(DIR_RTL, charArray, sourceToTargetMap, levels, params);
  13705. return charArray.join("");
  13706. }; // doBidiReorder( text, sourceToTargetMap, levels )
  13707. // Performs Bidi reordering by implementing Unicode Bidi algorithm.
  13708. // Returns reordered string
  13709. // @text [String]:
  13710. // - input string to be reordered, this is input parameter
  13711. // $sourceToTargetMap [Array] (optional)
  13712. // - resultant mapping between input and output strings, this is output parameter
  13713. // $levels [Array] (optional)
  13714. // - array of calculated Bidi levels, , this is output parameter
  13715. this.__bidiEngine__.doBidiReorder = function (text, sourceToTargetMap, levels) {
  13716. _init(text, sourceToTargetMap);
  13717. if (!_isInVisual && _isOutVisual && !_isOutRtl) {
  13718. // LLTR->VLTR, LRTL->VLTR
  13719. _dir = _isInRtl ? DIR_RTL : DIR_LTR;
  13720. text = _reorder(text, sourceToTargetMap, levels);
  13721. } else if (_isInVisual && _isOutVisual && _isInRtl ^ _isOutRtl) {
  13722. // VRTL->VLTR, VLTR->VRTL
  13723. _dir = _isInRtl ? DIR_RTL : DIR_LTR;
  13724. text = _invertString(text, sourceToTargetMap, levels);
  13725. } else if (!_isInVisual && _isOutVisual && _isOutRtl) {
  13726. // LLTR->VRTL, LRTL->VRTL
  13727. _dir = _isInRtl ? DIR_RTL : DIR_LTR;
  13728. text = _reorder(text, sourceToTargetMap, levels);
  13729. text = _invertString(text, sourceToTargetMap);
  13730. } else if (_isInVisual && !_isInRtl && !_isOutVisual && !_isOutRtl) {
  13731. // VLTR->LLTR
  13732. _dir = DIR_LTR;
  13733. text = _reorder(text, sourceToTargetMap, levels);
  13734. } else if (_isInVisual && !_isOutVisual && _isInRtl ^ _isOutRtl) {
  13735. // VLTR->LRTL, VRTL->LLTR
  13736. text = _invertString(text, sourceToTargetMap);
  13737. if (_isInRtl) {
  13738. //LLTR -> VLTR
  13739. _dir = DIR_LTR;
  13740. text = _reorder(text, sourceToTargetMap, levels);
  13741. } else {
  13742. //LRTL -> VRTL
  13743. _dir = DIR_RTL;
  13744. text = _reorder(text, sourceToTargetMap, levels);
  13745. text = _invertString(text, sourceToTargetMap);
  13746. }
  13747. } else if (_isInVisual && _isInRtl && !_isOutVisual && _isOutRtl) {
  13748. // VRTL->LRTL
  13749. _dir = DIR_RTL;
  13750. text = _reorder(text, sourceToTargetMap, levels);
  13751. text = _invertString(text, sourceToTargetMap);
  13752. } else if (!_isInVisual && !_isOutVisual && _isInRtl ^ _isOutRtl) {
  13753. // LRTL->LLTR, LLTR->LRTL
  13754. var isSymmetricSwappingOrig = _isSymmetricSwapping;
  13755. if (_isInRtl) {
  13756. //LRTL->LLTR
  13757. _dir = DIR_RTL;
  13758. text = _reorder(text, sourceToTargetMap, levels);
  13759. _dir = DIR_LTR;
  13760. _isSymmetricSwapping = false;
  13761. text = _reorder(text, sourceToTargetMap, levels);
  13762. _isSymmetricSwapping = isSymmetricSwappingOrig;
  13763. } else {
  13764. //LLTR->LRTL
  13765. _dir = DIR_LTR;
  13766. text = _reorder(text, sourceToTargetMap, levels);
  13767. text = _invertString(text, sourceToTargetMap);
  13768. _dir = DIR_RTL;
  13769. _isSymmetricSwapping = false;
  13770. text = _reorder(text, sourceToTargetMap, levels);
  13771. _isSymmetricSwapping = isSymmetricSwappingOrig;
  13772. text = _invertString(text, sourceToTargetMap);
  13773. }
  13774. }
  13775. return text;
  13776. };
  13777. /**
  13778. * @name setOptions( options )
  13779. * @function
  13780. * Sets options for Bidi conversion
  13781. * @param {Object}:
  13782. * - isInputVisual {boolean} (defaults to false): allowed values: true(Visual mode), false(Logical mode)
  13783. * - isInputRtl {boolean}: allowed values true(Right-to-left direction), false (Left-to-right directiion), undefined(Contectual direction, i.e.direction defined by first strong character of input string)
  13784. * - isOutputVisual {boolean} (defaults to false): allowed values: true(Visual mode), false(Logical mode)
  13785. * - isOutputRtl {boolean}: allowed values true(Right-to-left direction), false (Left-to-right directiion), undefined(Contectual direction, i.e.direction defined by first strong characterof input string)
  13786. * - isSymmetricSwapping {boolean} (defaults to false): allowed values true(needs symmetric swapping), false (no need in symmetric swapping),
  13787. */
  13788. this.__bidiEngine__.setOptions = function (options) {
  13789. if (options) {
  13790. _isInVisual = options.isInputVisual;
  13791. _isOutVisual = options.isOutputVisual;
  13792. _isInRtl = options.isInputRtl;
  13793. _isOutRtl = options.isOutputRtl;
  13794. _isSymmetricSwapping = options.isSymmetricSwapping;
  13795. }
  13796. };
  13797. this.__bidiEngine__.setOptions(options);
  13798. return this.__bidiEngine__;
  13799. };
  13800. var _bidiUnicodeTypes = bidiUnicodeTypes;
  13801. var bidiEngine = new jsPDF.__bidiEngine__({
  13802. isInputVisual: true
  13803. });
  13804. var bidiEngineFunction = function bidiEngineFunction(args) {
  13805. var text = args.text;
  13806. var x = args.x;
  13807. var y = args.y;
  13808. var options = args.options || {};
  13809. var mutex = args.mutex || {};
  13810. var lang = options.lang;
  13811. var tmpText = [];
  13812. if (Object.prototype.toString.call(text) === '[object Array]') {
  13813. var i = 0;
  13814. tmpText = [];
  13815. for (i = 0; i < text.length; i += 1) {
  13816. if (Object.prototype.toString.call(text[i]) === '[object Array]') {
  13817. tmpText.push([bidiEngine.doBidiReorder(text[i][0]), text[i][1], text[i][2]]);
  13818. } else {
  13819. tmpText.push([bidiEngine.doBidiReorder(text[i])]);
  13820. }
  13821. }
  13822. args.text = tmpText;
  13823. } else {
  13824. args.text = bidiEngine.doBidiReorder(text);
  13825. }
  13826. };
  13827. jsPDF.API.events.push(['postProcessText', bidiEngineFunction]);
  13828. })(jsPDF);
  13829. /*
  13830. Copyright (c) 2008, Adobe Systems Incorporated
  13831. All rights reserved.
  13832. Redistribution and use in source and binary forms, with or without
  13833. modification, are permitted provided that the following conditions are
  13834. met:
  13835. * Redistributions of source code must retain the above copyright notice,
  13836. this list of conditions and the following disclaimer.
  13837. * Redistributions in binary form must reproduce the above copyright
  13838. notice, this list of conditions and the following disclaimer in the
  13839. documentation and/or other materials provided with the distribution.
  13840. * Neither the name of Adobe Systems Incorporated nor the names of its
  13841. contributors may be used to endorse or promote products derived from
  13842. this software without specific prior written permission.
  13843. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  13844. IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  13845. THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  13846. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  13847. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  13848. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  13849. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  13850. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  13851. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  13852. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  13853. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  13854. */
  13855. /*
  13856. JPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009
  13857. Basic GUI blocking jpeg encoder
  13858. */
  13859. function JPEGEncoder(quality) {
  13860. var ffloor = Math.floor;
  13861. var YTable = new Array(64);
  13862. var UVTable = new Array(64);
  13863. var fdtbl_Y = new Array(64);
  13864. var fdtbl_UV = new Array(64);
  13865. var YDC_HT;
  13866. var UVDC_HT;
  13867. var YAC_HT;
  13868. var UVAC_HT;
  13869. var bitcode = new Array(65535);
  13870. var category = new Array(65535);
  13871. var outputfDCTQuant = new Array(64);
  13872. var DU = new Array(64);
  13873. var byteout = [];
  13874. var bytenew = 0;
  13875. var bytepos = 7;
  13876. var YDU = new Array(64);
  13877. var UDU = new Array(64);
  13878. var VDU = new Array(64);
  13879. var clt = new Array(256);
  13880. var RGB_YUV_TABLE = new Array(2048);
  13881. var currentQuality;
  13882. var ZigZag = [0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63];
  13883. var std_dc_luminance_nrcodes = [0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0];
  13884. var std_dc_luminance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
  13885. var std_ac_luminance_nrcodes = [0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d];
  13886. var std_ac_luminance_values = [0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa];
  13887. var std_dc_chrominance_nrcodes = [0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];
  13888. var std_dc_chrominance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
  13889. var std_ac_chrominance_nrcodes = [0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77];
  13890. var std_ac_chrominance_values = [0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa];
  13891. function initQuantTables(sf) {
  13892. var YQT = [16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99];
  13893. for (var i = 0; i < 64; i++) {
  13894. var t = ffloor((YQT[i] * sf + 50) / 100);
  13895. if (t < 1) {
  13896. t = 1;
  13897. } else if (t > 255) {
  13898. t = 255;
  13899. }
  13900. YTable[ZigZag[i]] = t;
  13901. }
  13902. var UVQT = [17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99];
  13903. for (var j = 0; j < 64; j++) {
  13904. var u = ffloor((UVQT[j] * sf + 50) / 100);
  13905. if (u < 1) {
  13906. u = 1;
  13907. } else if (u > 255) {
  13908. u = 255;
  13909. }
  13910. UVTable[ZigZag[j]] = u;
  13911. }
  13912. var aasf = [1.0, 1.387039845, 1.306562965, 1.175875602, 1.0, 0.785694958, 0.541196100, 0.275899379];
  13913. var k = 0;
  13914. for (var row = 0; row < 8; row++) {
  13915. for (var col = 0; col < 8; col++) {
  13916. fdtbl_Y[k] = 1.0 / (YTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0);
  13917. fdtbl_UV[k] = 1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0);
  13918. k++;
  13919. }
  13920. }
  13921. }
  13922. function computeHuffmanTbl(nrcodes, std_table) {
  13923. var codevalue = 0;
  13924. var pos_in_table = 0;
  13925. var HT = new Array();
  13926. for (var k = 1; k <= 16; k++) {
  13927. for (var j = 1; j <= nrcodes[k]; j++) {
  13928. HT[std_table[pos_in_table]] = [];
  13929. HT[std_table[pos_in_table]][0] = codevalue;
  13930. HT[std_table[pos_in_table]][1] = k;
  13931. pos_in_table++;
  13932. codevalue++;
  13933. }
  13934. codevalue *= 2;
  13935. }
  13936. return HT;
  13937. }
  13938. function initHuffmanTbl() {
  13939. YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes, std_dc_luminance_values);
  13940. UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes, std_dc_chrominance_values);
  13941. YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes, std_ac_luminance_values);
  13942. UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes, std_ac_chrominance_values);
  13943. }
  13944. function initCategoryNumber() {
  13945. var nrlower = 1;
  13946. var nrupper = 2;
  13947. for (var cat = 1; cat <= 15; cat++) {
  13948. //Positive numbers
  13949. for (var nr = nrlower; nr < nrupper; nr++) {
  13950. category[32767 + nr] = cat;
  13951. bitcode[32767 + nr] = [];
  13952. bitcode[32767 + nr][1] = cat;
  13953. bitcode[32767 + nr][0] = nr;
  13954. } //Negative numbers
  13955. for (var nrneg = -(nrupper - 1); nrneg <= -nrlower; nrneg++) {
  13956. category[32767 + nrneg] = cat;
  13957. bitcode[32767 + nrneg] = [];
  13958. bitcode[32767 + nrneg][1] = cat;
  13959. bitcode[32767 + nrneg][0] = nrupper - 1 + nrneg;
  13960. }
  13961. nrlower <<= 1;
  13962. nrupper <<= 1;
  13963. }
  13964. }
  13965. function initRGBYUVTable() {
  13966. for (var i = 0; i < 256; i++) {
  13967. RGB_YUV_TABLE[i] = 19595 * i;
  13968. RGB_YUV_TABLE[i + 256 >> 0] = 38470 * i;
  13969. RGB_YUV_TABLE[i + 512 >> 0] = 7471 * i + 0x8000;
  13970. RGB_YUV_TABLE[i + 768 >> 0] = -11059 * i;
  13971. RGB_YUV_TABLE[i + 1024 >> 0] = -21709 * i;
  13972. RGB_YUV_TABLE[i + 1280 >> 0] = 32768 * i + 0x807FFF;
  13973. RGB_YUV_TABLE[i + 1536 >> 0] = -27439 * i;
  13974. RGB_YUV_TABLE[i + 1792 >> 0] = -5329 * i;
  13975. }
  13976. } // IO functions
  13977. function writeBits(bs) {
  13978. var value = bs[0];
  13979. var posval = bs[1] - 1;
  13980. while (posval >= 0) {
  13981. if (value & 1 << posval) {
  13982. bytenew |= 1 << bytepos;
  13983. }
  13984. posval--;
  13985. bytepos--;
  13986. if (bytepos < 0) {
  13987. if (bytenew == 0xFF) {
  13988. writeByte(0xFF);
  13989. writeByte(0);
  13990. } else {
  13991. writeByte(bytenew);
  13992. }
  13993. bytepos = 7;
  13994. bytenew = 0;
  13995. }
  13996. }
  13997. }
  13998. function writeByte(value) {
  13999. //byteout.push(clt[value]); // write char directly instead of converting later
  14000. byteout.push(value);
  14001. }
  14002. function writeWord(value) {
  14003. writeByte(value >> 8 & 0xFF);
  14004. writeByte(value & 0xFF);
  14005. } // DCT & quantization core
  14006. function fDCTQuant(data, fdtbl) {
  14007. var d0, d1, d2, d3, d4, d5, d6, d7;
  14008. /* Pass 1: process rows. */
  14009. var dataOff = 0;
  14010. var i;
  14011. var I8 = 8;
  14012. var I64 = 64;
  14013. for (i = 0; i < I8; ++i) {
  14014. d0 = data[dataOff];
  14015. d1 = data[dataOff + 1];
  14016. d2 = data[dataOff + 2];
  14017. d3 = data[dataOff + 3];
  14018. d4 = data[dataOff + 4];
  14019. d5 = data[dataOff + 5];
  14020. d6 = data[dataOff + 6];
  14021. d7 = data[dataOff + 7];
  14022. var tmp0 = d0 + d7;
  14023. var tmp7 = d0 - d7;
  14024. var tmp1 = d1 + d6;
  14025. var tmp6 = d1 - d6;
  14026. var tmp2 = d2 + d5;
  14027. var tmp5 = d2 - d5;
  14028. var tmp3 = d3 + d4;
  14029. var tmp4 = d3 - d4;
  14030. /* Even part */
  14031. var tmp10 = tmp0 + tmp3;
  14032. /* phase 2 */
  14033. var tmp13 = tmp0 - tmp3;
  14034. var tmp11 = tmp1 + tmp2;
  14035. var tmp12 = tmp1 - tmp2;
  14036. data[dataOff] = tmp10 + tmp11;
  14037. /* phase 3 */
  14038. data[dataOff + 4] = tmp10 - tmp11;
  14039. var z1 = (tmp12 + tmp13) * 0.707106781;
  14040. /* c4 */
  14041. data[dataOff + 2] = tmp13 + z1;
  14042. /* phase 5 */
  14043. data[dataOff + 6] = tmp13 - z1;
  14044. /* Odd part */
  14045. tmp10 = tmp4 + tmp5;
  14046. /* phase 2 */
  14047. tmp11 = tmp5 + tmp6;
  14048. tmp12 = tmp6 + tmp7;
  14049. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  14050. var z5 = (tmp10 - tmp12) * 0.382683433;
  14051. /* c6 */
  14052. var z2 = 0.541196100 * tmp10 + z5;
  14053. /* c2-c6 */
  14054. var z4 = 1.306562965 * tmp12 + z5;
  14055. /* c2+c6 */
  14056. var z3 = tmp11 * 0.707106781;
  14057. /* c4 */
  14058. var z11 = tmp7 + z3;
  14059. /* phase 5 */
  14060. var z13 = tmp7 - z3;
  14061. data[dataOff + 5] = z13 + z2;
  14062. /* phase 6 */
  14063. data[dataOff + 3] = z13 - z2;
  14064. data[dataOff + 1] = z11 + z4;
  14065. data[dataOff + 7] = z11 - z4;
  14066. dataOff += 8;
  14067. /* advance pointer to next row */
  14068. }
  14069. /* Pass 2: process columns. */
  14070. dataOff = 0;
  14071. for (i = 0; i < I8; ++i) {
  14072. d0 = data[dataOff];
  14073. d1 = data[dataOff + 8];
  14074. d2 = data[dataOff + 16];
  14075. d3 = data[dataOff + 24];
  14076. d4 = data[dataOff + 32];
  14077. d5 = data[dataOff + 40];
  14078. d6 = data[dataOff + 48];
  14079. d7 = data[dataOff + 56];
  14080. var tmp0p2 = d0 + d7;
  14081. var tmp7p2 = d0 - d7;
  14082. var tmp1p2 = d1 + d6;
  14083. var tmp6p2 = d1 - d6;
  14084. var tmp2p2 = d2 + d5;
  14085. var tmp5p2 = d2 - d5;
  14086. var tmp3p2 = d3 + d4;
  14087. var tmp4p2 = d3 - d4;
  14088. /* Even part */
  14089. var tmp10p2 = tmp0p2 + tmp3p2;
  14090. /* phase 2 */
  14091. var tmp13p2 = tmp0p2 - tmp3p2;
  14092. var tmp11p2 = tmp1p2 + tmp2p2;
  14093. var tmp12p2 = tmp1p2 - tmp2p2;
  14094. data[dataOff] = tmp10p2 + tmp11p2;
  14095. /* phase 3 */
  14096. data[dataOff + 32] = tmp10p2 - tmp11p2;
  14097. var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781;
  14098. /* c4 */
  14099. data[dataOff + 16] = tmp13p2 + z1p2;
  14100. /* phase 5 */
  14101. data[dataOff + 48] = tmp13p2 - z1p2;
  14102. /* Odd part */
  14103. tmp10p2 = tmp4p2 + tmp5p2;
  14104. /* phase 2 */
  14105. tmp11p2 = tmp5p2 + tmp6p2;
  14106. tmp12p2 = tmp6p2 + tmp7p2;
  14107. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  14108. var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433;
  14109. /* c6 */
  14110. var z2p2 = 0.541196100 * tmp10p2 + z5p2;
  14111. /* c2-c6 */
  14112. var z4p2 = 1.306562965 * tmp12p2 + z5p2;
  14113. /* c2+c6 */
  14114. var z3p2 = tmp11p2 * 0.707106781;
  14115. /* c4 */
  14116. var z11p2 = tmp7p2 + z3p2;
  14117. /* phase 5 */
  14118. var z13p2 = tmp7p2 - z3p2;
  14119. data[dataOff + 40] = z13p2 + z2p2;
  14120. /* phase 6 */
  14121. data[dataOff + 24] = z13p2 - z2p2;
  14122. data[dataOff + 8] = z11p2 + z4p2;
  14123. data[dataOff + 56] = z11p2 - z4p2;
  14124. dataOff++;
  14125. /* advance pointer to next column */
  14126. } // Quantize/descale the coefficients
  14127. var fDCTQuant;
  14128. for (i = 0; i < I64; ++i) {
  14129. // Apply the quantization and scaling factor & Round to nearest integer
  14130. fDCTQuant = data[i] * fdtbl[i];
  14131. outputfDCTQuant[i] = fDCTQuant > 0.0 ? fDCTQuant + 0.5 | 0 : fDCTQuant - 0.5 | 0; //outputfDCTQuant[i] = fround(fDCTQuant);
  14132. }
  14133. return outputfDCTQuant;
  14134. }
  14135. function writeAPP0() {
  14136. writeWord(0xFFE0); // marker
  14137. writeWord(16); // length
  14138. writeByte(0x4A); // J
  14139. writeByte(0x46); // F
  14140. writeByte(0x49); // I
  14141. writeByte(0x46); // F
  14142. writeByte(0); // = "JFIF",'\0'
  14143. writeByte(1); // versionhi
  14144. writeByte(1); // versionlo
  14145. writeByte(0); // xyunits
  14146. writeWord(1); // xdensity
  14147. writeWord(1); // ydensity
  14148. writeByte(0); // thumbnwidth
  14149. writeByte(0); // thumbnheight
  14150. }
  14151. function writeSOF0(width, height) {
  14152. writeWord(0xFFC0); // marker
  14153. writeWord(17); // length, truecolor YUV JPG
  14154. writeByte(8); // precision
  14155. writeWord(height);
  14156. writeWord(width);
  14157. writeByte(3); // nrofcomponents
  14158. writeByte(1); // IdY
  14159. writeByte(0x11); // HVY
  14160. writeByte(0); // QTY
  14161. writeByte(2); // IdU
  14162. writeByte(0x11); // HVU
  14163. writeByte(1); // QTU
  14164. writeByte(3); // IdV
  14165. writeByte(0x11); // HVV
  14166. writeByte(1); // QTV
  14167. }
  14168. function writeDQT() {
  14169. writeWord(0xFFDB); // marker
  14170. writeWord(132); // length
  14171. writeByte(0);
  14172. for (var i = 0; i < 64; i++) {
  14173. writeByte(YTable[i]);
  14174. }
  14175. writeByte(1);
  14176. for (var j = 0; j < 64; j++) {
  14177. writeByte(UVTable[j]);
  14178. }
  14179. }
  14180. function writeDHT() {
  14181. writeWord(0xFFC4); // marker
  14182. writeWord(0x01A2); // length
  14183. writeByte(0); // HTYDCinfo
  14184. for (var i = 0; i < 16; i++) {
  14185. writeByte(std_dc_luminance_nrcodes[i + 1]);
  14186. }
  14187. for (var j = 0; j <= 11; j++) {
  14188. writeByte(std_dc_luminance_values[j]);
  14189. }
  14190. writeByte(0x10); // HTYACinfo
  14191. for (var k = 0; k < 16; k++) {
  14192. writeByte(std_ac_luminance_nrcodes[k + 1]);
  14193. }
  14194. for (var l = 0; l <= 161; l++) {
  14195. writeByte(std_ac_luminance_values[l]);
  14196. }
  14197. writeByte(1); // HTUDCinfo
  14198. for (var m = 0; m < 16; m++) {
  14199. writeByte(std_dc_chrominance_nrcodes[m + 1]);
  14200. }
  14201. for (var n = 0; n <= 11; n++) {
  14202. writeByte(std_dc_chrominance_values[n]);
  14203. }
  14204. writeByte(0x11); // HTUACinfo
  14205. for (var o = 0; o < 16; o++) {
  14206. writeByte(std_ac_chrominance_nrcodes[o + 1]);
  14207. }
  14208. for (var p = 0; p <= 161; p++) {
  14209. writeByte(std_ac_chrominance_values[p]);
  14210. }
  14211. }
  14212. function writeSOS() {
  14213. writeWord(0xFFDA); // marker
  14214. writeWord(12); // length
  14215. writeByte(3); // nrofcomponents
  14216. writeByte(1); // IdY
  14217. writeByte(0); // HTY
  14218. writeByte(2); // IdU
  14219. writeByte(0x11); // HTU
  14220. writeByte(3); // IdV
  14221. writeByte(0x11); // HTV
  14222. writeByte(0); // Ss
  14223. writeByte(0x3f); // Se
  14224. writeByte(0); // Bf
  14225. }
  14226. function processDU(CDU, fdtbl, DC, HTDC, HTAC) {
  14227. var EOB = HTAC[0x00];
  14228. var M16zeroes = HTAC[0xF0];
  14229. var pos;
  14230. var I16 = 16;
  14231. var I63 = 63;
  14232. var I64 = 64;
  14233. var DU_DCT = fDCTQuant(CDU, fdtbl); //ZigZag reorder
  14234. for (var j = 0; j < I64; ++j) {
  14235. DU[ZigZag[j]] = DU_DCT[j];
  14236. }
  14237. var Diff = DU[0] - DC;
  14238. DC = DU[0]; //Encode DC
  14239. if (Diff == 0) {
  14240. writeBits(HTDC[0]); // Diff might be 0
  14241. } else {
  14242. pos = 32767 + Diff;
  14243. writeBits(HTDC[category[pos]]);
  14244. writeBits(bitcode[pos]);
  14245. } //Encode ACs
  14246. var end0pos = 63; // was const... which is crazy
  14247. for (; end0pos > 0 && DU[end0pos] == 0; end0pos--) {}
  14248. if (end0pos == 0) {
  14249. writeBits(EOB);
  14250. return DC;
  14251. }
  14252. var i = 1;
  14253. var lng;
  14254. while (i <= end0pos) {
  14255. var startpos = i;
  14256. for (; DU[i] == 0 && i <= end0pos; ++i) {}
  14257. var nrzeroes = i - startpos;
  14258. if (nrzeroes >= I16) {
  14259. lng = nrzeroes >> 4;
  14260. for (var nrmarker = 1; nrmarker <= lng; ++nrmarker) {
  14261. writeBits(M16zeroes);
  14262. }
  14263. nrzeroes = nrzeroes & 0xF;
  14264. }
  14265. pos = 32767 + DU[i];
  14266. writeBits(HTAC[(nrzeroes << 4) + category[pos]]);
  14267. writeBits(bitcode[pos]);
  14268. i++;
  14269. }
  14270. if (end0pos != I63) {
  14271. writeBits(EOB);
  14272. }
  14273. return DC;
  14274. }
  14275. function initCharLookupTable() {
  14276. var sfcc = String.fromCharCode;
  14277. for (var i = 0; i < 256; i++) {
  14278. ///// ACHTUNG // 255
  14279. clt[i] = sfcc(i);
  14280. }
  14281. }
  14282. this.encode = function (image, quality) // image data object
  14283. {
  14284. var time_start = new Date().getTime();
  14285. if (quality) setQuality(quality); // Initialize bit writer
  14286. byteout = new Array();
  14287. bytenew = 0;
  14288. bytepos = 7; // Add JPEG headers
  14289. writeWord(0xFFD8); // SOI
  14290. writeAPP0();
  14291. writeDQT();
  14292. writeSOF0(image.width, image.height);
  14293. writeDHT();
  14294. writeSOS(); // Encode 8x8 macroblocks
  14295. var DCY = 0;
  14296. var DCU = 0;
  14297. var DCV = 0;
  14298. bytenew = 0;
  14299. bytepos = 7;
  14300. this.encode.displayName = "_encode_";
  14301. var imageData = image.data;
  14302. var width = image.width;
  14303. var height = image.height;
  14304. var quadWidth = width * 4;
  14305. var x,
  14306. y = 0;
  14307. var r, g, b;
  14308. var start, p, col, row, pos;
  14309. while (y < height) {
  14310. x = 0;
  14311. while (x < quadWidth) {
  14312. start = quadWidth * y + x;
  14313. p = start;
  14314. col = -1;
  14315. row = 0;
  14316. for (pos = 0; pos < 64; pos++) {
  14317. row = pos >> 3; // /8
  14318. col = (pos & 7) * 4; // %8
  14319. p = start + row * quadWidth + col;
  14320. if (y + row >= height) {
  14321. // padding bottom
  14322. p -= quadWidth * (y + 1 + row - height);
  14323. }
  14324. if (x + col >= quadWidth) {
  14325. // padding right
  14326. p -= x + col - quadWidth + 4;
  14327. }
  14328. r = imageData[p++];
  14329. g = imageData[p++];
  14330. b = imageData[p++];
  14331. /* // calculate YUV values dynamically
  14332. YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80
  14333. UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));
  14334. VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));
  14335. */
  14336. // use lookup table (slightly faster)
  14337. YDU[pos] = (RGB_YUV_TABLE[r] + RGB_YUV_TABLE[g + 256 >> 0] + RGB_YUV_TABLE[b + 512 >> 0] >> 16) - 128;
  14338. UDU[pos] = (RGB_YUV_TABLE[r + 768 >> 0] + RGB_YUV_TABLE[g + 1024 >> 0] + RGB_YUV_TABLE[b + 1280 >> 0] >> 16) - 128;
  14339. VDU[pos] = (RGB_YUV_TABLE[r + 1280 >> 0] + RGB_YUV_TABLE[g + 1536 >> 0] + RGB_YUV_TABLE[b + 1792 >> 0] >> 16) - 128;
  14340. }
  14341. DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
  14342. DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
  14343. DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
  14344. x += 32;
  14345. }
  14346. y += 8;
  14347. } ////////////////////////////////////////////////////////////////
  14348. // Do the bit alignment of the EOI marker
  14349. if (bytepos >= 0) {
  14350. var fillbits = [];
  14351. fillbits[1] = bytepos + 1;
  14352. fillbits[0] = (1 << bytepos + 1) - 1;
  14353. writeBits(fillbits);
  14354. }
  14355. writeWord(0xFFD9); //EOI
  14356. return new Uint8Array(byteout);
  14357. };
  14358. function setQuality(quality) {
  14359. if (quality <= 0) {
  14360. quality = 1;
  14361. }
  14362. if (quality > 100) {
  14363. quality = 100;
  14364. }
  14365. if (currentQuality == quality) return; // don't recalc if unchanged
  14366. var sf = 0;
  14367. if (quality < 50) {
  14368. sf = Math.floor(5000 / quality);
  14369. } else {
  14370. sf = Math.floor(200 - quality * 2);
  14371. }
  14372. initQuantTables(sf);
  14373. currentQuality = quality; //console.log('Quality set to: '+quality +'%');
  14374. }
  14375. function init() {
  14376. var time_start = new Date().getTime();
  14377. if (!quality) quality = 50; // Create tables
  14378. initCharLookupTable();
  14379. initHuffmanTbl();
  14380. initCategoryNumber();
  14381. initRGBYUVTable();
  14382. setQuality(quality);
  14383. var duration = new Date().getTime() - time_start; //console.log('Initialization '+ duration + 'ms');
  14384. }
  14385. init();
  14386. }
  14387. /*rollup-keeper-start*/
  14388. window.tmp = JPEGEncoder;
  14389. /*rollup-keeper-end*/
  14390. /**
  14391. * @author shaozilee
  14392. *
  14393. * Bmp format decoder,support 1bit 4bit 8bit 24bit bmp
  14394. *
  14395. */
  14396. function BmpDecoder(buffer, is_with_alpha) {
  14397. this.pos = 0;
  14398. this.buffer = buffer;
  14399. this.datav = new DataView(buffer.buffer);
  14400. this.is_with_alpha = !!is_with_alpha;
  14401. this.bottom_up = true;
  14402. this.flag = String.fromCharCode(this.buffer[0]) + String.fromCharCode(this.buffer[1]);
  14403. this.pos += 2;
  14404. if (["BM", "BA", "CI", "CP", "IC", "PT"].indexOf(this.flag) === -1) throw new Error("Invalid BMP File");
  14405. this.parseHeader();
  14406. this.parseBGR();
  14407. }
  14408. BmpDecoder.prototype.parseHeader = function () {
  14409. this.fileSize = this.datav.getUint32(this.pos, true);
  14410. this.pos += 4;
  14411. this.reserved = this.datav.getUint32(this.pos, true);
  14412. this.pos += 4;
  14413. this.offset = this.datav.getUint32(this.pos, true);
  14414. this.pos += 4;
  14415. this.headerSize = this.datav.getUint32(this.pos, true);
  14416. this.pos += 4;
  14417. this.width = this.datav.getUint32(this.pos, true);
  14418. this.pos += 4;
  14419. this.height = this.datav.getInt32(this.pos, true);
  14420. this.pos += 4;
  14421. this.planes = this.datav.getUint16(this.pos, true);
  14422. this.pos += 2;
  14423. this.bitPP = this.datav.getUint16(this.pos, true);
  14424. this.pos += 2;
  14425. this.compress = this.datav.getUint32(this.pos, true);
  14426. this.pos += 4;
  14427. this.rawSize = this.datav.getUint32(this.pos, true);
  14428. this.pos += 4;
  14429. this.hr = this.datav.getUint32(this.pos, true);
  14430. this.pos += 4;
  14431. this.vr = this.datav.getUint32(this.pos, true);
  14432. this.pos += 4;
  14433. this.colors = this.datav.getUint32(this.pos, true);
  14434. this.pos += 4;
  14435. this.importantColors = this.datav.getUint32(this.pos, true);
  14436. this.pos += 4;
  14437. if (this.bitPP === 16 && this.is_with_alpha) {
  14438. this.bitPP = 15;
  14439. }
  14440. if (this.bitPP < 15) {
  14441. var len = this.colors === 0 ? 1 << this.bitPP : this.colors;
  14442. this.palette = new Array(len);
  14443. for (var i = 0; i < len; i++) {
  14444. var blue = this.datav.getUint8(this.pos++, true);
  14445. var green = this.datav.getUint8(this.pos++, true);
  14446. var red = this.datav.getUint8(this.pos++, true);
  14447. var quad = this.datav.getUint8(this.pos++, true);
  14448. this.palette[i] = {
  14449. red: red,
  14450. green: green,
  14451. blue: blue,
  14452. quad: quad
  14453. };
  14454. }
  14455. }
  14456. if (this.height < 0) {
  14457. this.height *= -1;
  14458. this.bottom_up = false;
  14459. }
  14460. };
  14461. BmpDecoder.prototype.parseBGR = function () {
  14462. this.pos = this.offset;
  14463. try {
  14464. var bitn = "bit" + this.bitPP;
  14465. var len = this.width * this.height * 4;
  14466. this.data = new Uint8Array(len);
  14467. this[bitn]();
  14468. } catch (e) {
  14469. console.log("bit decode error:" + e);
  14470. }
  14471. };
  14472. BmpDecoder.prototype.bit1 = function () {
  14473. var xlen = Math.ceil(this.width / 8);
  14474. var mode = xlen % 4;
  14475. var y = this.height >= 0 ? this.height - 1 : -this.height;
  14476. for (var y = this.height - 1; y >= 0; y--) {
  14477. var line = this.bottom_up ? y : this.height - 1 - y;
  14478. for (var x = 0; x < xlen; x++) {
  14479. var b = this.datav.getUint8(this.pos++, true);
  14480. var location = line * this.width * 4 + x * 8 * 4;
  14481. for (var i = 0; i < 8; i++) {
  14482. if (x * 8 + i < this.width) {
  14483. var rgb = this.palette[b >> 7 - i & 0x1];
  14484. this.data[location + i * 4] = rgb.blue;
  14485. this.data[location + i * 4 + 1] = rgb.green;
  14486. this.data[location + i * 4 + 2] = rgb.red;
  14487. this.data[location + i * 4 + 3] = 0xFF;
  14488. } else {
  14489. break;
  14490. }
  14491. }
  14492. }
  14493. if (mode != 0) {
  14494. this.pos += 4 - mode;
  14495. }
  14496. }
  14497. };
  14498. BmpDecoder.prototype.bit4 = function () {
  14499. var xlen = Math.ceil(this.width / 2);
  14500. var mode = xlen % 4;
  14501. for (var y = this.height - 1; y >= 0; y--) {
  14502. var line = this.bottom_up ? y : this.height - 1 - y;
  14503. for (var x = 0; x < xlen; x++) {
  14504. var b = this.datav.getUint8(this.pos++, true);
  14505. var location = line * this.width * 4 + x * 2 * 4;
  14506. var before = b >> 4;
  14507. var after = b & 0x0F;
  14508. var rgb = this.palette[before];
  14509. this.data[location] = rgb.blue;
  14510. this.data[location + 1] = rgb.green;
  14511. this.data[location + 2] = rgb.red;
  14512. this.data[location + 3] = 0xFF;
  14513. if (x * 2 + 1 >= this.width) break;
  14514. rgb = this.palette[after];
  14515. this.data[location + 4] = rgb.blue;
  14516. this.data[location + 4 + 1] = rgb.green;
  14517. this.data[location + 4 + 2] = rgb.red;
  14518. this.data[location + 4 + 3] = 0xFF;
  14519. }
  14520. if (mode != 0) {
  14521. this.pos += 4 - mode;
  14522. }
  14523. }
  14524. };
  14525. BmpDecoder.prototype.bit8 = function () {
  14526. var mode = this.width % 4;
  14527. for (var y = this.height - 1; y >= 0; y--) {
  14528. var line = this.bottom_up ? y : this.height - 1 - y;
  14529. for (var x = 0; x < this.width; x++) {
  14530. var b = this.datav.getUint8(this.pos++, true);
  14531. var location = line * this.width * 4 + x * 4;
  14532. if (b < this.palette.length) {
  14533. var rgb = this.palette[b];
  14534. this.data[location] = rgb.red;
  14535. this.data[location + 1] = rgb.green;
  14536. this.data[location + 2] = rgb.blue;
  14537. this.data[location + 3] = 0xFF;
  14538. } else {
  14539. this.data[location] = 0xFF;
  14540. this.data[location + 1] = 0xFF;
  14541. this.data[location + 2] = 0xFF;
  14542. this.data[location + 3] = 0xFF;
  14543. }
  14544. }
  14545. if (mode != 0) {
  14546. this.pos += 4 - mode;
  14547. }
  14548. }
  14549. };
  14550. BmpDecoder.prototype.bit15 = function () {
  14551. var dif_w = this.width % 3;
  14552. var _11111 = parseInt("11111", 2),
  14553. _1_5 = _11111;
  14554. for (var y = this.height - 1; y >= 0; y--) {
  14555. var line = this.bottom_up ? y : this.height - 1 - y;
  14556. for (var x = 0; x < this.width; x++) {
  14557. var B = this.datav.getUint16(this.pos, true);
  14558. this.pos += 2;
  14559. var blue = (B & _1_5) / _1_5 * 255 | 0;
  14560. var green = (B >> 5 & _1_5) / _1_5 * 255 | 0;
  14561. var red = (B >> 10 & _1_5) / _1_5 * 255 | 0;
  14562. var alpha = B >> 15 ? 0xFF : 0x00;
  14563. var location = line * this.width * 4 + x * 4;
  14564. this.data[location] = red;
  14565. this.data[location + 1] = green;
  14566. this.data[location + 2] = blue;
  14567. this.data[location + 3] = alpha;
  14568. } //skip extra bytes
  14569. this.pos += dif_w;
  14570. }
  14571. };
  14572. BmpDecoder.prototype.bit16 = function () {
  14573. var dif_w = this.width % 3;
  14574. var _11111 = parseInt("11111", 2),
  14575. _1_5 = _11111;
  14576. var _111111 = parseInt("111111", 2),
  14577. _1_6 = _111111;
  14578. for (var y = this.height - 1; y >= 0; y--) {
  14579. var line = this.bottom_up ? y : this.height - 1 - y;
  14580. for (var x = 0; x < this.width; x++) {
  14581. var B = this.datav.getUint16(this.pos, true);
  14582. this.pos += 2;
  14583. var alpha = 0xFF;
  14584. var blue = (B & _1_5) / _1_5 * 255 | 0;
  14585. var green = (B >> 5 & _1_6) / _1_6 * 255 | 0;
  14586. var red = (B >> 11) / _1_5 * 255 | 0;
  14587. var location = line * this.width * 4 + x * 4;
  14588. this.data[location] = red;
  14589. this.data[location + 1] = green;
  14590. this.data[location + 2] = blue;
  14591. this.data[location + 3] = alpha;
  14592. } //skip extra bytes
  14593. this.pos += dif_w;
  14594. }
  14595. };
  14596. BmpDecoder.prototype.bit24 = function () {
  14597. //when height > 0
  14598. for (var y = this.height - 1; y >= 0; y--) {
  14599. var line = this.bottom_up ? y : this.height - 1 - y;
  14600. for (var x = 0; x < this.width; x++) {
  14601. var blue = this.datav.getUint8(this.pos++, true);
  14602. var green = this.datav.getUint8(this.pos++, true);
  14603. var red = this.datav.getUint8(this.pos++, true);
  14604. var location = line * this.width * 4 + x * 4;
  14605. this.data[location] = red;
  14606. this.data[location + 1] = green;
  14607. this.data[location + 2] = blue;
  14608. this.data[location + 3] = 0xFF;
  14609. } //skip extra bytes
  14610. this.pos += this.width % 4;
  14611. }
  14612. };
  14613. /**
  14614. * add 32bit decode func
  14615. * @author soubok
  14616. */
  14617. BmpDecoder.prototype.bit32 = function () {
  14618. //when height > 0
  14619. for (var y = this.height - 1; y >= 0; y--) {
  14620. var line = this.bottom_up ? y : this.height - 1 - y;
  14621. for (var x = 0; x < this.width; x++) {
  14622. var blue = this.datav.getUint8(this.pos++, true);
  14623. var green = this.datav.getUint8(this.pos++, true);
  14624. var red = this.datav.getUint8(this.pos++, true);
  14625. var alpha = this.datav.getUint8(this.pos++, true);
  14626. var location = line * this.width * 4 + x * 4;
  14627. this.data[location] = red;
  14628. this.data[location + 1] = green;
  14629. this.data[location + 2] = blue;
  14630. this.data[location + 3] = alpha;
  14631. } //skip extra bytes
  14632. //this.pos += (this.width % 4);
  14633. }
  14634. };
  14635. BmpDecoder.prototype.getData = function () {
  14636. return this.data;
  14637. };
  14638. /*rollup-keeper-start*/
  14639. window.tmp = BmpDecoder;
  14640. /*rollup-keeper-end*/
  14641. /*
  14642. Copyright (c) 2013 Gildas Lormeau. All rights reserved.
  14643. Redistribution and use in source and binary forms, with or without
  14644. modification, are permitted provided that the following conditions are met:
  14645. 1. Redistributions of source code must retain the above copyright notice,
  14646. this list of conditions and the following disclaimer.
  14647. 2. Redistributions in binary form must reproduce the above copyright
  14648. notice, this list of conditions and the following disclaimer in
  14649. the documentation and/or other materials provided with the distribution.
  14650. 3. The names of the authors may not be used to endorse or promote products
  14651. derived from this software without specific prior written permission.
  14652. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  14653. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  14654. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  14655. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  14656. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  14657. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  14658. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  14659. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  14660. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  14661. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14662. */
  14663. /*
  14664. * This program is based on JZlib 1.0.2 ymnk, JCraft,Inc.
  14665. * JZlib is based on zlib-1.1.3, so all credit should go authors
  14666. * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
  14667. * and contributors of zlib.
  14668. */
  14669. (function (global) {
  14670. var MAX_BITS = 15;
  14671. var D_CODES = 30;
  14672. var BL_CODES = 19;
  14673. var LENGTH_CODES = 29;
  14674. var LITERALS = 256;
  14675. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  14676. var HEAP_SIZE = 2 * L_CODES + 1;
  14677. var END_BLOCK = 256; // Bit length codes must not exceed MAX_BL_BITS bits
  14678. var MAX_BL_BITS = 7; // repeat previous bit length 3-6 times (2 bits of repeat count)
  14679. var REP_3_6 = 16; // repeat a zero length 3-10 times (3 bits of repeat count)
  14680. var REPZ_3_10 = 17; // repeat a zero length 11-138 times (7 bits of repeat count)
  14681. var REPZ_11_138 = 18; // The lengths of the bit length codes are sent in order of decreasing
  14682. // probability, to avoid transmitting the lengths for unused bit
  14683. // length codes.
  14684. var Buf_size = 8 * 2; // JZlib version : "1.0.2"
  14685. var Z_DEFAULT_COMPRESSION = -1; // compression strategy
  14686. var Z_FILTERED = 1;
  14687. var Z_HUFFMAN_ONLY = 2;
  14688. var Z_DEFAULT_STRATEGY = 0;
  14689. var Z_NO_FLUSH = 0;
  14690. var Z_PARTIAL_FLUSH = 1;
  14691. var Z_FULL_FLUSH = 3;
  14692. var Z_FINISH = 4;
  14693. var Z_OK = 0;
  14694. var Z_STREAM_END = 1;
  14695. var Z_NEED_DICT = 2;
  14696. var Z_STREAM_ERROR = -2;
  14697. var Z_DATA_ERROR = -3;
  14698. var Z_BUF_ERROR = -5; // Tree
  14699. // see definition of array dist_code below
  14700. var _dist_code = [0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29];
  14701. function Tree() {
  14702. var that = this; // dyn_tree; // the dynamic tree
  14703. // max_code; // largest code with non zero frequency
  14704. // stat_desc; // the corresponding static tree
  14705. // Compute the optimal bit lengths for a tree and update the total bit
  14706. // length
  14707. // for the current block.
  14708. // IN assertion: the fields freq and dad are set, heap[heap_max] and
  14709. // above are the tree nodes sorted by increasing frequency.
  14710. // OUT assertions: the field len is set to the optimal bit length, the
  14711. // array bl_count contains the frequencies for each bit length.
  14712. // The length opt_len is updated; static_len is also updated if stree is
  14713. // not null.
  14714. function gen_bitlen(s) {
  14715. var tree = that.dyn_tree;
  14716. var stree = that.stat_desc.static_tree;
  14717. var extra = that.stat_desc.extra_bits;
  14718. var base = that.stat_desc.extra_base;
  14719. var max_length = that.stat_desc.max_length;
  14720. var h; // heap index
  14721. var n, m; // iterate over the tree elements
  14722. var bits; // bit length
  14723. var xbits; // extra bits
  14724. var f; // frequency
  14725. var overflow = 0; // number of elements with bit length too large
  14726. for (bits = 0; bits <= MAX_BITS; bits++) {
  14727. s.bl_count[bits] = 0;
  14728. } // In a first pass, compute the optimal bit lengths (which may
  14729. // overflow in the case of the bit length tree).
  14730. tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap
  14731. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  14732. n = s.heap[h];
  14733. bits = tree[tree[n * 2 + 1] * 2 + 1] + 1;
  14734. if (bits > max_length) {
  14735. bits = max_length;
  14736. overflow++;
  14737. }
  14738. tree[n * 2 + 1] = bits; // We overwrite tree[n*2+1] which is no longer needed
  14739. if (n > that.max_code) continue; // not a leaf node
  14740. s.bl_count[bits]++;
  14741. xbits = 0;
  14742. if (n >= base) xbits = extra[n - base];
  14743. f = tree[n * 2];
  14744. s.opt_len += f * (bits + xbits);
  14745. if (stree) s.static_len += f * (stree[n * 2 + 1] + xbits);
  14746. }
  14747. if (overflow === 0) return; // This happens for example on obj2 and pic of the Calgary corpus
  14748. // Find the first bit length which could increase:
  14749. do {
  14750. bits = max_length - 1;
  14751. while (s.bl_count[bits] === 0) {
  14752. bits--;
  14753. }
  14754. s.bl_count[bits]--; // move one leaf down the tree
  14755. s.bl_count[bits + 1] += 2; // move one overflow item as its brother
  14756. s.bl_count[max_length]--; // The brother of the overflow item also moves one step up,
  14757. // but this does not affect bl_count[max_length]
  14758. overflow -= 2;
  14759. } while (overflow > 0);
  14760. for (bits = max_length; bits !== 0; bits--) {
  14761. n = s.bl_count[bits];
  14762. while (n !== 0) {
  14763. m = s.heap[--h];
  14764. if (m > that.max_code) continue;
  14765. if (tree[m * 2 + 1] != bits) {
  14766. s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2];
  14767. tree[m * 2 + 1] = bits;
  14768. }
  14769. n--;
  14770. }
  14771. }
  14772. } // Reverse the first len bits of a code, using straightforward code (a
  14773. // faster
  14774. // method would use a table)
  14775. // IN assertion: 1 <= len <= 15
  14776. function bi_reverse(code, // the value to invert
  14777. len // its bit length
  14778. ) {
  14779. var res = 0;
  14780. do {
  14781. res |= code & 1;
  14782. code >>>= 1;
  14783. res <<= 1;
  14784. } while (--len > 0);
  14785. return res >>> 1;
  14786. } // Generate the codes for a given tree and bit counts (which need not be
  14787. // optimal).
  14788. // IN assertion: the array bl_count contains the bit length statistics for
  14789. // the given tree and the field len is set for all tree elements.
  14790. // OUT assertion: the field code is set for all tree elements of non
  14791. // zero code length.
  14792. function gen_codes(tree, // the tree to decorate
  14793. max_code, // largest code with non zero frequency
  14794. bl_count // number of codes at each bit length
  14795. ) {
  14796. var next_code = []; // next code value for each
  14797. // bit length
  14798. var code = 0; // running code value
  14799. var bits; // bit index
  14800. var n; // code index
  14801. var len; // The distribution counts are first used to generate the code values
  14802. // without bit reversal.
  14803. for (bits = 1; bits <= MAX_BITS; bits++) {
  14804. next_code[bits] = code = code + bl_count[bits - 1] << 1;
  14805. } // Check that the bit counts in bl_count are consistent. The last code
  14806. // must be all ones.
  14807. // Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  14808. // "inconsistent bit counts");
  14809. // Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  14810. for (n = 0; n <= max_code; n++) {
  14811. len = tree[n * 2 + 1];
  14812. if (len === 0) continue; // Now reverse the bits
  14813. tree[n * 2] = bi_reverse(next_code[len]++, len);
  14814. }
  14815. } // Construct one Huffman tree and assigns the code bit strings and lengths.
  14816. // Update the total bit length for the current block.
  14817. // IN assertion: the field freq is set for all tree elements.
  14818. // OUT assertions: the fields len and code are set to the optimal bit length
  14819. // and corresponding code. The length opt_len is updated; static_len is
  14820. // also updated if stree is not null. The field max_code is set.
  14821. that.build_tree = function (s) {
  14822. var tree = that.dyn_tree;
  14823. var stree = that.stat_desc.static_tree;
  14824. var elems = that.stat_desc.elems;
  14825. var n, m; // iterate over heap elements
  14826. var max_code = -1; // largest code with non zero frequency
  14827. var node; // new node being created
  14828. // Construct the initial heap, with least frequent element in
  14829. // heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  14830. // heap[0] is not used.
  14831. s.heap_len = 0;
  14832. s.heap_max = HEAP_SIZE;
  14833. for (n = 0; n < elems; n++) {
  14834. if (tree[n * 2] !== 0) {
  14835. s.heap[++s.heap_len] = max_code = n;
  14836. s.depth[n] = 0;
  14837. } else {
  14838. tree[n * 2 + 1] = 0;
  14839. }
  14840. } // The pkzip format requires that at least one distance code exists,
  14841. // and that at least one bit should be sent even if there is only one
  14842. // possible code. So to avoid special checks later on we force at least
  14843. // two codes of non zero frequency.
  14844. while (s.heap_len < 2) {
  14845. node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0;
  14846. tree[node * 2] = 1;
  14847. s.depth[node] = 0;
  14848. s.opt_len--;
  14849. if (stree) s.static_len -= stree[node * 2 + 1]; // node is 0 or 1 so it does not have extra bits
  14850. }
  14851. that.max_code = max_code; // The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  14852. // establish sub-heaps of increasing lengths:
  14853. for (n = Math.floor(s.heap_len / 2); n >= 1; n--) {
  14854. s.pqdownheap(tree, n);
  14855. } // Construct the Huffman tree by repeatedly combining the least two
  14856. // frequent nodes.
  14857. node = elems; // next internal node of the tree
  14858. do {
  14859. // n = node of least frequency
  14860. n = s.heap[1];
  14861. s.heap[1] = s.heap[s.heap_len--];
  14862. s.pqdownheap(tree, 1);
  14863. m = s.heap[1]; // m = node of next least frequency
  14864. s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
  14865. s.heap[--s.heap_max] = m; // Create a new node father of n and m
  14866. tree[node * 2] = tree[n * 2] + tree[m * 2];
  14867. s.depth[node] = Math.max(s.depth[n], s.depth[m]) + 1;
  14868. tree[n * 2 + 1] = tree[m * 2 + 1] = node; // and insert the new node in the heap
  14869. s.heap[1] = node++;
  14870. s.pqdownheap(tree, 1);
  14871. } while (s.heap_len >= 2);
  14872. s.heap[--s.heap_max] = s.heap[1]; // At this point, the fields freq and dad are set. We can now
  14873. // generate the bit lengths.
  14874. gen_bitlen(s); // The field len is now set, we can generate the bit codes
  14875. gen_codes(tree, that.max_code, s.bl_count);
  14876. };
  14877. }
  14878. Tree._length_code = [0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28];
  14879. Tree.base_length = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0];
  14880. Tree.base_dist = [0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576]; // Mapping from a distance to a distance code. dist is the distance - 1 and
  14881. // must not have side effects. _dist_code[256] and _dist_code[257] are never
  14882. // used.
  14883. Tree.d_code = function (dist) {
  14884. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  14885. }; // extra bits for each length code
  14886. Tree.extra_lbits = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0]; // extra bits for each distance code
  14887. Tree.extra_dbits = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13]; // extra bits for each bit length code
  14888. Tree.extra_blbits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7];
  14889. Tree.bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; // StaticTree
  14890. function StaticTree(static_tree, extra_bits, extra_base, elems, max_length) {
  14891. var that = this;
  14892. that.static_tree = static_tree;
  14893. that.extra_bits = extra_bits;
  14894. that.extra_base = extra_base;
  14895. that.elems = elems;
  14896. that.max_length = max_length;
  14897. }
  14898. StaticTree.static_ltree = [12, 8, 140, 8, 76, 8, 204, 8, 44, 8, 172, 8, 108, 8, 236, 8, 28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188, 8, 124, 8, 252, 8, 2, 8, 130, 8, 66, 8, 194, 8, 34, 8, 162, 8, 98, 8, 226, 8, 18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178, 8, 114, 8, 242, 8, 10, 8, 138, 8, 74, 8, 202, 8, 42, 8, 170, 8, 106, 8, 234, 8, 26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186, 8, 122, 8, 250, 8, 6, 8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8, 102, 8, 230, 8, 22, 8, 150, 8, 86, 8, 214, 8, 54, 8, 182, 8, 118, 8, 246, 8, 14, 8, 142, 8, 78, 8, 206, 8, 46, 8, 174, 8, 110, 8, 238, 8, 30, 8, 158, 8, 94, 8, 222, 8, 62, 8, 190, 8, 126, 8, 254, 8, 1, 8, 129, 8, 65, 8, 193, 8, 33, 8, 161, 8, 97, 8, 225, 8, 17, 8, 145, 8, 81, 8, 209, 8, 49, 8, 177, 8, 113, 8, 241, 8, 9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169, 8, 105, 8, 233, 8, 25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185, 8, 121, 8, 249, 8, 5, 8, 133, 8, 69, 8, 197, 8, 37, 8, 165, 8, 101, 8, 229, 8, 21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181, 8, 117, 8, 245, 8, 13, 8, 141, 8, 77, 8, 205, 8, 45, 8, 173, 8, 109, 8, 237, 8, 29, 8, 157, 8, 93, 8, 221, 8, 61, 8, 189, 8, 125, 8, 253, 8, 19, 9, 275, 9, 147, 9, 403, 9, 83, 9, 339, 9, 211, 9, 467, 9, 51, 9, 307, 9, 179, 9, 435, 9, 115, 9, 371, 9, 243, 9, 499, 9, 11, 9, 267, 9, 139, 9, 395, 9, 75, 9, 331, 9, 203, 9, 459, 9, 43, 9, 299, 9, 171, 9, 427, 9, 107, 9, 363, 9, 235, 9, 491, 9, 27, 9, 283, 9, 155, 9, 411, 9, 91, 9, 347, 9, 219, 9, 475, 9, 59, 9, 315, 9, 187, 9, 443, 9, 123, 9, 379, 9, 251, 9, 507, 9, 7, 9, 263, 9, 135, 9, 391, 9, 71, 9, 327, 9, 199, 9, 455, 9, 39, 9, 295, 9, 167, 9, 423, 9, 103, 9, 359, 9, 231, 9, 487, 9, 23, 9, 279, 9, 151, 9, 407, 9, 87, 9, 343, 9, 215, 9, 471, 9, 55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375, 9, 247, 9, 503, 9, 15, 9, 271, 9, 143, 9, 399, 9, 79, 9, 335, 9, 207, 9, 463, 9, 47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367, 9, 239, 9, 495, 9, 31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351, 9, 223, 9, 479, 9, 63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383, 9, 255, 9, 511, 9, 0, 7, 64, 7, 32, 7, 96, 7, 16, 7, 80, 7, 48, 7, 112, 7, 8, 7, 72, 7, 40, 7, 104, 7, 24, 7, 88, 7, 56, 7, 120, 7, 4, 7, 68, 7, 36, 7, 100, 7, 20, 7, 84, 7, 52, 7, 116, 7, 3, 8, 131, 8, 67, 8, 195, 8, 35, 8, 163, 8, 99, 8, 227, 8];
  14899. StaticTree.static_dtree = [0, 5, 16, 5, 8, 5, 24, 5, 4, 5, 20, 5, 12, 5, 28, 5, 2, 5, 18, 5, 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, 30, 5, 1, 5, 17, 5, 9, 5, 25, 5, 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5];
  14900. StaticTree.static_l_desc = new StaticTree(StaticTree.static_ltree, Tree.extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  14901. StaticTree.static_d_desc = new StaticTree(StaticTree.static_dtree, Tree.extra_dbits, 0, D_CODES, MAX_BITS);
  14902. StaticTree.static_bl_desc = new StaticTree(null, Tree.extra_blbits, 0, BL_CODES, MAX_BL_BITS); // Deflate
  14903. var MAX_MEM_LEVEL = 9;
  14904. var DEF_MEM_LEVEL = 8;
  14905. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  14906. var that = this;
  14907. that.good_length = good_length;
  14908. that.max_lazy = max_lazy;
  14909. that.nice_length = nice_length;
  14910. that.max_chain = max_chain;
  14911. that.func = func;
  14912. }
  14913. var STORED = 0;
  14914. var FAST = 1;
  14915. var SLOW = 2;
  14916. var config_table = [new Config(0, 0, 0, 0, STORED), new Config(4, 4, 8, 4, FAST), new Config(4, 5, 16, 8, FAST), new Config(4, 6, 32, 32, FAST), new Config(4, 4, 16, 16, SLOW), new Config(8, 16, 32, 32, SLOW), new Config(8, 16, 128, 128, SLOW), new Config(8, 32, 128, 256, SLOW), new Config(32, 128, 258, 1024, SLOW), new Config(32, 258, 258, 4096, SLOW)];
  14917. var z_errmsg = ["need dictionary", // Z_NEED_DICT
  14918. // 2
  14919. "stream end", // Z_STREAM_END 1
  14920. "", // Z_OK 0
  14921. "", // Z_ERRNO (-1)
  14922. "stream error", // Z_STREAM_ERROR (-2)
  14923. "data error", // Z_DATA_ERROR (-3)
  14924. "", // Z_MEM_ERROR (-4)
  14925. "buffer error", // Z_BUF_ERROR (-5)
  14926. "", // Z_VERSION_ERROR (-6)
  14927. ""]; // block not completed, need more input or more output
  14928. var NeedMore = 0; // block flush performed
  14929. var BlockDone = 1; // finish started, need only more output at next deflate
  14930. var FinishStarted = 2; // finish done, accept no more input or output
  14931. var FinishDone = 3; // preset dictionary flag in zlib header
  14932. var PRESET_DICT = 0x20;
  14933. var INIT_STATE = 42;
  14934. var BUSY_STATE = 113;
  14935. var FINISH_STATE = 666; // The deflate compression method
  14936. var Z_DEFLATED = 8;
  14937. var STORED_BLOCK = 0;
  14938. var STATIC_TREES = 1;
  14939. var DYN_TREES = 2;
  14940. var MIN_MATCH = 3;
  14941. var MAX_MATCH = 258;
  14942. var MIN_LOOKAHEAD = MAX_MATCH + MIN_MATCH + 1;
  14943. function smaller(tree, n, m, depth) {
  14944. var tn2 = tree[n * 2];
  14945. var tm2 = tree[m * 2];
  14946. return tn2 < tm2 || tn2 == tm2 && depth[n] <= depth[m];
  14947. }
  14948. function Deflate() {
  14949. var that = this;
  14950. var strm; // pointer back to this zlib stream
  14951. var status; // as the name implies
  14952. // pending_buf; // output still pending
  14953. var pending_buf_size; // size of pending_buf
  14954. var last_flush; // value of flush param for previous deflate call
  14955. var w_size; // LZ77 window size (32K by default)
  14956. var w_bits; // log2(w_size) (8..16)
  14957. var w_mask; // w_size - 1
  14958. var window; // Sliding window. Input bytes are read into the second half of the window,
  14959. // and move to the first half later to keep a dictionary of at least wSize
  14960. // bytes. With this organization, matches are limited to a distance of
  14961. // wSize-MAX_MATCH bytes, but this ensures that IO is always
  14962. // performed with a length multiple of the block size. Also, it limits
  14963. // the window size to 64K, which is quite useful on MSDOS.
  14964. // To do: use the user input buffer as sliding window.
  14965. var window_size; // Actual size of window: 2*wSize, except when the user input buffer
  14966. // is directly used as sliding window.
  14967. var prev; // Link to older string with same hash index. To limit the size of this
  14968. // array to 64K, this link is maintained only for the last 32K strings.
  14969. // An index in this array is thus a window index modulo 32K.
  14970. var head; // Heads of the hash chains or NIL.
  14971. var ins_h; // hash index of string to be inserted
  14972. var hash_size; // number of elements in hash table
  14973. var hash_bits; // log2(hash_size)
  14974. var hash_mask; // hash_size-1
  14975. // Number of bits by which ins_h must be shifted at each input
  14976. // step. It must be such that after MIN_MATCH steps, the oldest
  14977. // byte no longer takes part in the hash key, that is:
  14978. // hash_shift * MIN_MATCH >= hash_bits
  14979. var hash_shift; // Window position at the beginning of the current output block. Gets
  14980. // negative when the window is moved backwards.
  14981. var block_start;
  14982. var match_length; // length of best match
  14983. var prev_match; // previous match
  14984. var match_available; // set if previous match exists
  14985. var strstart; // start of string to insert
  14986. var match_start; // start of matching string
  14987. var lookahead; // number of valid bytes ahead in window
  14988. // Length of the best match at previous step. Matches not greater than this
  14989. // are discarded. This is used in the lazy match evaluation.
  14990. var prev_length; // To speed up deflation, hash chains are never searched beyond this
  14991. // length. A higher limit improves compression ratio but degrades the speed.
  14992. var max_chain_length; // Attempt to find a better match only when the current match is strictly
  14993. // smaller than this value. This mechanism is used only for compression
  14994. // levels >= 4.
  14995. var max_lazy_match; // Insert new strings in the hash table only if the match length is not
  14996. // greater than this length. This saves time but degrades compression.
  14997. // max_insert_length is used only for compression levels <= 3.
  14998. var level; // compression level (1..9)
  14999. var strategy; // favor or force Huffman coding
  15000. // Use a faster search when the previous match is longer than this
  15001. var good_match; // Stop searching when current match exceeds this
  15002. var nice_match;
  15003. var dyn_ltree; // literal and length tree
  15004. var dyn_dtree; // distance tree
  15005. var bl_tree; // Huffman tree for bit lengths
  15006. var l_desc = new Tree(); // desc for literal tree
  15007. var d_desc = new Tree(); // desc for distance tree
  15008. var bl_desc = new Tree(); // desc for bit length tree
  15009. // that.heap_len; // number of elements in the heap
  15010. // that.heap_max; // element of largest frequency
  15011. // The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  15012. // The same heap array is used to build all trees.
  15013. // Depth of each subtree used as tie breaker for trees of equal frequency
  15014. that.depth = [];
  15015. var l_buf; // index for literals or lengths */
  15016. // Size of match buffer for literals/lengths. There are 4 reasons for
  15017. // limiting lit_bufsize to 64K:
  15018. // - frequencies can be kept in 16 bit counters
  15019. // - if compression is not successful for the first block, all input
  15020. // data is still in the window so we can still emit a stored block even
  15021. // when input comes from standard input. (This can also be done for
  15022. // all blocks if lit_bufsize is not greater than 32K.)
  15023. // - if compression is not successful for a file smaller than 64K, we can
  15024. // even emit a stored file instead of a stored block (saving 5 bytes).
  15025. // This is applicable only for zip (not gzip or zlib).
  15026. // - creating new Huffman trees less frequently may not provide fast
  15027. // adaptation to changes in the input data statistics. (Take for
  15028. // example a binary file with poorly compressible code followed by
  15029. // a highly compressible string table.) Smaller buffer sizes give
  15030. // fast adaptation but have of course the overhead of transmitting
  15031. // trees more frequently.
  15032. // - I can't count above 4
  15033. var lit_bufsize;
  15034. var last_lit; // running index in l_buf
  15035. // Buffer for distances. To simplify the code, d_buf and l_buf have
  15036. // the same number of elements. To use different lengths, an extra flag
  15037. // array would be necessary.
  15038. var d_buf; // index of pendig_buf
  15039. // that.opt_len; // bit length of current block with optimal trees
  15040. // that.static_len; // bit length of current block with static trees
  15041. var matches; // number of string matches in current block
  15042. var last_eob_len; // bit length of EOB code for last block
  15043. // Output buffer. bits are inserted starting at the bottom (least
  15044. // significant bits).
  15045. var bi_buf; // Number of valid bits in bi_buf. All bits above the last valid bit
  15046. // are always zero.
  15047. var bi_valid; // number of codes at each bit length for an optimal tree
  15048. that.bl_count = []; // heap used to build the Huffman trees
  15049. that.heap = [];
  15050. dyn_ltree = [];
  15051. dyn_dtree = [];
  15052. bl_tree = [];
  15053. function lm_init() {
  15054. var i;
  15055. window_size = 2 * w_size;
  15056. head[hash_size - 1] = 0;
  15057. for (i = 0; i < hash_size - 1; i++) {
  15058. head[i] = 0;
  15059. } // Set the default configuration parameters:
  15060. max_lazy_match = config_table[level].max_lazy;
  15061. good_match = config_table[level].good_length;
  15062. nice_match = config_table[level].nice_length;
  15063. max_chain_length = config_table[level].max_chain;
  15064. strstart = 0;
  15065. block_start = 0;
  15066. lookahead = 0;
  15067. match_length = prev_length = MIN_MATCH - 1;
  15068. match_available = 0;
  15069. ins_h = 0;
  15070. }
  15071. function init_block() {
  15072. var i; // Initialize the trees.
  15073. for (i = 0; i < L_CODES; i++) {
  15074. dyn_ltree[i * 2] = 0;
  15075. }
  15076. for (i = 0; i < D_CODES; i++) {
  15077. dyn_dtree[i * 2] = 0;
  15078. }
  15079. for (i = 0; i < BL_CODES; i++) {
  15080. bl_tree[i * 2] = 0;
  15081. }
  15082. dyn_ltree[END_BLOCK * 2] = 1;
  15083. that.opt_len = that.static_len = 0;
  15084. last_lit = matches = 0;
  15085. } // Initialize the tree data structures for a new zlib stream.
  15086. function tr_init() {
  15087. l_desc.dyn_tree = dyn_ltree;
  15088. l_desc.stat_desc = StaticTree.static_l_desc;
  15089. d_desc.dyn_tree = dyn_dtree;
  15090. d_desc.stat_desc = StaticTree.static_d_desc;
  15091. bl_desc.dyn_tree = bl_tree;
  15092. bl_desc.stat_desc = StaticTree.static_bl_desc;
  15093. bi_buf = 0;
  15094. bi_valid = 0;
  15095. last_eob_len = 8; // enough lookahead for inflate
  15096. // Initialize the first block of the first file:
  15097. init_block();
  15098. } // Restore the heap property by moving down the tree starting at node k,
  15099. // exchanging a node with the smallest of its two sons if necessary,
  15100. // stopping
  15101. // when the heap property is re-established (each father smaller than its
  15102. // two sons).
  15103. that.pqdownheap = function (tree, // the tree to restore
  15104. k // node to move down
  15105. ) {
  15106. var heap = that.heap;
  15107. var v = heap[k];
  15108. var j = k << 1; // left son of k
  15109. while (j <= that.heap_len) {
  15110. // Set j to the smallest of the two sons:
  15111. if (j < that.heap_len && smaller(tree, heap[j + 1], heap[j], that.depth)) {
  15112. j++;
  15113. } // Exit if v is smaller than both sons
  15114. if (smaller(tree, v, heap[j], that.depth)) break; // Exchange v with the smallest son
  15115. heap[k] = heap[j];
  15116. k = j; // And continue down the tree, setting j to the left son of k
  15117. j <<= 1;
  15118. }
  15119. heap[k] = v;
  15120. }; // Scan a literal or distance tree to determine the frequencies of the codes
  15121. // in the bit length tree.
  15122. function scan_tree(tree, // the tree to be scanned
  15123. max_code // and its largest code of non zero frequency
  15124. ) {
  15125. var n; // iterates over all tree elements
  15126. var prevlen = -1; // last emitted length
  15127. var curlen; // length of current code
  15128. var nextlen = tree[0 * 2 + 1]; // length of next code
  15129. var count = 0; // repeat count of the current code
  15130. var max_count = 7; // max repeat count
  15131. var min_count = 4; // min repeat count
  15132. if (nextlen === 0) {
  15133. max_count = 138;
  15134. min_count = 3;
  15135. }
  15136. tree[(max_code + 1) * 2 + 1] = 0xffff; // guard
  15137. for (n = 0; n <= max_code; n++) {
  15138. curlen = nextlen;
  15139. nextlen = tree[(n + 1) * 2 + 1];
  15140. if (++count < max_count && curlen == nextlen) {
  15141. continue;
  15142. } else if (count < min_count) {
  15143. bl_tree[curlen * 2] += count;
  15144. } else if (curlen !== 0) {
  15145. if (curlen != prevlen) bl_tree[curlen * 2]++;
  15146. bl_tree[REP_3_6 * 2]++;
  15147. } else if (count <= 10) {
  15148. bl_tree[REPZ_3_10 * 2]++;
  15149. } else {
  15150. bl_tree[REPZ_11_138 * 2]++;
  15151. }
  15152. count = 0;
  15153. prevlen = curlen;
  15154. if (nextlen === 0) {
  15155. max_count = 138;
  15156. min_count = 3;
  15157. } else if (curlen == nextlen) {
  15158. max_count = 6;
  15159. min_count = 3;
  15160. } else {
  15161. max_count = 7;
  15162. min_count = 4;
  15163. }
  15164. }
  15165. } // Construct the Huffman tree for the bit lengths and return the index in
  15166. // bl_order of the last bit length code to send.
  15167. function build_bl_tree() {
  15168. var max_blindex; // index of last bit length code of non zero freq
  15169. // Determine the bit length frequencies for literal and distance trees
  15170. scan_tree(dyn_ltree, l_desc.max_code);
  15171. scan_tree(dyn_dtree, d_desc.max_code); // Build the bit length tree:
  15172. bl_desc.build_tree(that); // opt_len now includes the length of the tree representations, except
  15173. // the lengths of the bit lengths codes and the 5+5+4 bits for the
  15174. // counts.
  15175. // Determine the number of bit length codes to send. The pkzip format
  15176. // requires that at least 4 bit length codes be sent. (appnote.txt says
  15177. // 3 but the actual value used is 4.)
  15178. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  15179. if (bl_tree[Tree.bl_order[max_blindex] * 2 + 1] !== 0) break;
  15180. } // Update opt_len to include the bit length tree and counts
  15181. that.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  15182. return max_blindex;
  15183. } // Output a byte on the stream.
  15184. // IN assertion: there is enough room in pending_buf.
  15185. function put_byte(p) {
  15186. that.pending_buf[that.pending++] = p;
  15187. }
  15188. function put_short(w) {
  15189. put_byte(w & 0xff);
  15190. put_byte(w >>> 8 & 0xff);
  15191. }
  15192. function putShortMSB(b) {
  15193. put_byte(b >> 8 & 0xff);
  15194. put_byte(b & 0xff & 0xff);
  15195. }
  15196. function send_bits(value, length) {
  15197. var val,
  15198. len = length;
  15199. if (bi_valid > Buf_size - len) {
  15200. val = value; // bi_buf |= (val << bi_valid);
  15201. bi_buf |= val << bi_valid & 0xffff;
  15202. put_short(bi_buf);
  15203. bi_buf = val >>> Buf_size - bi_valid;
  15204. bi_valid += len - Buf_size;
  15205. } else {
  15206. // bi_buf |= (value) << bi_valid;
  15207. bi_buf |= value << bi_valid & 0xffff;
  15208. bi_valid += len;
  15209. }
  15210. }
  15211. function send_code(c, tree) {
  15212. var c2 = c * 2;
  15213. send_bits(tree[c2] & 0xffff, tree[c2 + 1] & 0xffff);
  15214. } // Send a literal or distance tree in compressed form, using the codes in
  15215. // bl_tree.
  15216. function send_tree(tree, // the tree to be sent
  15217. max_code // and its largest code of non zero frequency
  15218. ) {
  15219. var n; // iterates over all tree elements
  15220. var prevlen = -1; // last emitted length
  15221. var curlen; // length of current code
  15222. var nextlen = tree[0 * 2 + 1]; // length of next code
  15223. var count = 0; // repeat count of the current code
  15224. var max_count = 7; // max repeat count
  15225. var min_count = 4; // min repeat count
  15226. if (nextlen === 0) {
  15227. max_count = 138;
  15228. min_count = 3;
  15229. }
  15230. for (n = 0; n <= max_code; n++) {
  15231. curlen = nextlen;
  15232. nextlen = tree[(n + 1) * 2 + 1];
  15233. if (++count < max_count && curlen == nextlen) {
  15234. continue;
  15235. } else if (count < min_count) {
  15236. do {
  15237. send_code(curlen, bl_tree);
  15238. } while (--count !== 0);
  15239. } else if (curlen !== 0) {
  15240. if (curlen != prevlen) {
  15241. send_code(curlen, bl_tree);
  15242. count--;
  15243. }
  15244. send_code(REP_3_6, bl_tree);
  15245. send_bits(count - 3, 2);
  15246. } else if (count <= 10) {
  15247. send_code(REPZ_3_10, bl_tree);
  15248. send_bits(count - 3, 3);
  15249. } else {
  15250. send_code(REPZ_11_138, bl_tree);
  15251. send_bits(count - 11, 7);
  15252. }
  15253. count = 0;
  15254. prevlen = curlen;
  15255. if (nextlen === 0) {
  15256. max_count = 138;
  15257. min_count = 3;
  15258. } else if (curlen == nextlen) {
  15259. max_count = 6;
  15260. min_count = 3;
  15261. } else {
  15262. max_count = 7;
  15263. min_count = 4;
  15264. }
  15265. }
  15266. } // Send the header for a block using dynamic Huffman trees: the counts, the
  15267. // lengths of the bit length codes, the literal tree and the distance tree.
  15268. // IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  15269. function send_all_trees(lcodes, dcodes, blcodes) {
  15270. var rank; // index in bl_order
  15271. send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt
  15272. send_bits(dcodes - 1, 5);
  15273. send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt
  15274. for (rank = 0; rank < blcodes; rank++) {
  15275. send_bits(bl_tree[Tree.bl_order[rank] * 2 + 1], 3);
  15276. }
  15277. send_tree(dyn_ltree, lcodes - 1); // literal tree
  15278. send_tree(dyn_dtree, dcodes - 1); // distance tree
  15279. } // Flush the bit buffer, keeping at most 7 bits in it.
  15280. function bi_flush() {
  15281. if (bi_valid == 16) {
  15282. put_short(bi_buf);
  15283. bi_buf = 0;
  15284. bi_valid = 0;
  15285. } else if (bi_valid >= 8) {
  15286. put_byte(bi_buf & 0xff);
  15287. bi_buf >>>= 8;
  15288. bi_valid -= 8;
  15289. }
  15290. } // Send one empty static block to give enough lookahead for inflate.
  15291. // This takes 10 bits, of which 7 may remain in the bit buffer.
  15292. // The current inflate code requires 9 bits of lookahead. If the
  15293. // last two codes for the previous block (real code plus EOB) were coded
  15294. // on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  15295. // the last real code. In this case we send two empty static blocks instead
  15296. // of one. (There are no problems if the previous block is stored or fixed.)
  15297. // To simplify the code, we assume the worst case of last real code encoded
  15298. // on one bit only.
  15299. function _tr_align() {
  15300. send_bits(STATIC_TREES << 1, 3);
  15301. send_code(END_BLOCK, StaticTree.static_ltree);
  15302. bi_flush(); // Of the 10 bits for the empty block, we have already sent
  15303. // (10 - bi_valid) bits. The lookahead for the last real code (before
  15304. // the EOB of the previous block) was thus at least one plus the length
  15305. // of the EOB plus what we have just sent of the empty static block.
  15306. if (1 + last_eob_len + 10 - bi_valid < 9) {
  15307. send_bits(STATIC_TREES << 1, 3);
  15308. send_code(END_BLOCK, StaticTree.static_ltree);
  15309. bi_flush();
  15310. }
  15311. last_eob_len = 7;
  15312. } // Save the match info and tally the frequency counts. Return true if
  15313. // the current block must be flushed.
  15314. function _tr_tally(dist, // distance of matched string
  15315. lc // match length-MIN_MATCH or unmatched char (if dist==0)
  15316. ) {
  15317. var out_length, in_length, dcode;
  15318. that.pending_buf[d_buf + last_lit * 2] = dist >>> 8 & 0xff;
  15319. that.pending_buf[d_buf + last_lit * 2 + 1] = dist & 0xff;
  15320. that.pending_buf[l_buf + last_lit] = lc & 0xff;
  15321. last_lit++;
  15322. if (dist === 0) {
  15323. // lc is the unmatched char
  15324. dyn_ltree[lc * 2]++;
  15325. } else {
  15326. matches++; // Here, lc is the match length - MIN_MATCH
  15327. dist--; // dist = match distance - 1
  15328. dyn_ltree[(Tree._length_code[lc] + LITERALS + 1) * 2]++;
  15329. dyn_dtree[Tree.d_code(dist) * 2]++;
  15330. }
  15331. if ((last_lit & 0x1fff) === 0 && level > 2) {
  15332. // Compute an upper bound for the compressed length
  15333. out_length = last_lit * 8;
  15334. in_length = strstart - block_start;
  15335. for (dcode = 0; dcode < D_CODES; dcode++) {
  15336. out_length += dyn_dtree[dcode * 2] * (5 + Tree.extra_dbits[dcode]);
  15337. }
  15338. out_length >>>= 3;
  15339. if (matches < Math.floor(last_lit / 2) && out_length < Math.floor(in_length / 2)) return true;
  15340. }
  15341. return last_lit == lit_bufsize - 1; // We avoid equality with lit_bufsize because of wraparound at 64K
  15342. // on 16 bit machines and because stored blocks are restricted to
  15343. // 64K-1 bytes.
  15344. } // Send the block data compressed using the given Huffman trees
  15345. function compress_block(ltree, dtree) {
  15346. var dist; // distance of matched string
  15347. var lc; // match length or unmatched char (if dist === 0)
  15348. var lx = 0; // running index in l_buf
  15349. var code; // the code to send
  15350. var extra; // number of extra bits to send
  15351. if (last_lit !== 0) {
  15352. do {
  15353. dist = that.pending_buf[d_buf + lx * 2] << 8 & 0xff00 | that.pending_buf[d_buf + lx * 2 + 1] & 0xff;
  15354. lc = that.pending_buf[l_buf + lx] & 0xff;
  15355. lx++;
  15356. if (dist === 0) {
  15357. send_code(lc, ltree); // send a literal byte
  15358. } else {
  15359. // Here, lc is the match length - MIN_MATCH
  15360. code = Tree._length_code[lc];
  15361. send_code(code + LITERALS + 1, ltree); // send the length
  15362. // code
  15363. extra = Tree.extra_lbits[code];
  15364. if (extra !== 0) {
  15365. lc -= Tree.base_length[code];
  15366. send_bits(lc, extra); // send the extra length bits
  15367. }
  15368. dist--; // dist is now the match distance - 1
  15369. code = Tree.d_code(dist);
  15370. send_code(code, dtree); // send the distance code
  15371. extra = Tree.extra_dbits[code];
  15372. if (extra !== 0) {
  15373. dist -= Tree.base_dist[code];
  15374. send_bits(dist, extra); // send the extra distance bits
  15375. }
  15376. } // literal or match pair ?
  15377. // Check that the overlay between pending_buf and d_buf+l_buf is
  15378. // ok:
  15379. } while (lx < last_lit);
  15380. }
  15381. send_code(END_BLOCK, ltree);
  15382. last_eob_len = ltree[END_BLOCK * 2 + 1];
  15383. } // Flush the bit buffer and align the output on a byte boundary
  15384. function bi_windup() {
  15385. if (bi_valid > 8) {
  15386. put_short(bi_buf);
  15387. } else if (bi_valid > 0) {
  15388. put_byte(bi_buf & 0xff);
  15389. }
  15390. bi_buf = 0;
  15391. bi_valid = 0;
  15392. } // Copy a stored block, storing first the length and its
  15393. // one's complement if requested.
  15394. function copy_block(buf, // the input data
  15395. len, // its length
  15396. header // true if block header must be written
  15397. ) {
  15398. bi_windup(); // align on byte boundary
  15399. last_eob_len = 8; // enough lookahead for inflate
  15400. if (header) {
  15401. put_short(len);
  15402. put_short(~len);
  15403. }
  15404. that.pending_buf.set(window.subarray(buf, buf + len), that.pending);
  15405. that.pending += len;
  15406. } // Send a stored block
  15407. function _tr_stored_block(buf, // input block
  15408. stored_len, // length of input block
  15409. eof // true if this is the last block for a file
  15410. ) {
  15411. send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3); // send block type
  15412. copy_block(buf, stored_len, true); // with header
  15413. } // Determine the best encoding for the current block: dynamic trees, static
  15414. // trees or store, and output the encoded block to the zip file.
  15415. function _tr_flush_block(buf, // input block, or NULL if too old
  15416. stored_len, // length of input block
  15417. eof // true if this is the last block for a file
  15418. ) {
  15419. var opt_lenb, static_lenb; // opt_len and static_len in bytes
  15420. var max_blindex = 0; // index of last bit length code of non zero freq
  15421. // Build the Huffman trees unless a stored block is forced
  15422. if (level > 0) {
  15423. // Construct the literal and distance trees
  15424. l_desc.build_tree(that);
  15425. d_desc.build_tree(that); // At this point, opt_len and static_len are the total bit lengths
  15426. // of
  15427. // the compressed block data, excluding the tree representations.
  15428. // Build the bit length tree for the above two trees, and get the
  15429. // index
  15430. // in bl_order of the last bit length code to send.
  15431. max_blindex = build_bl_tree(); // Determine the best encoding. Compute first the block length in
  15432. // bytes
  15433. opt_lenb = that.opt_len + 3 + 7 >>> 3;
  15434. static_lenb = that.static_len + 3 + 7 >>> 3;
  15435. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  15436. } else {
  15437. opt_lenb = static_lenb = stored_len + 5; // force a stored block
  15438. }
  15439. if (stored_len + 4 <= opt_lenb && buf != -1) {
  15440. // 4: two words for the lengths
  15441. // The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  15442. // Otherwise we can't have processed more than WSIZE input bytes
  15443. // since
  15444. // the last block flush, because compression would have been
  15445. // successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  15446. // transform a block into a stored block.
  15447. _tr_stored_block(buf, stored_len, eof);
  15448. } else if (static_lenb == opt_lenb) {
  15449. send_bits((STATIC_TREES << 1) + (eof ? 1 : 0), 3);
  15450. compress_block(StaticTree.static_ltree, StaticTree.static_dtree);
  15451. } else {
  15452. send_bits((DYN_TREES << 1) + (eof ? 1 : 0), 3);
  15453. send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1, max_blindex + 1);
  15454. compress_block(dyn_ltree, dyn_dtree);
  15455. } // The above check is made mod 2^32, for files larger than 512 MB
  15456. // and uLong implemented on 32 bits.
  15457. init_block();
  15458. if (eof) {
  15459. bi_windup();
  15460. }
  15461. }
  15462. function flush_block_only(eof) {
  15463. _tr_flush_block(block_start >= 0 ? block_start : -1, strstart - block_start, eof);
  15464. block_start = strstart;
  15465. strm.flush_pending();
  15466. } // Fill the window when the lookahead becomes insufficient.
  15467. // Updates strstart and lookahead.
  15468. //
  15469. // IN assertion: lookahead < MIN_LOOKAHEAD
  15470. // OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  15471. // At least one byte has been read, or avail_in === 0; reads are
  15472. // performed for at least two bytes (required for the zip translate_eol
  15473. // option -- not supported here).
  15474. function fill_window() {
  15475. var n, m;
  15476. var p;
  15477. var more; // Amount of free space at the end of the window.
  15478. do {
  15479. more = window_size - lookahead - strstart; // Deal with !@#$% 64K limit:
  15480. if (more === 0 && strstart === 0 && lookahead === 0) {
  15481. more = w_size;
  15482. } else if (more == -1) {
  15483. // Very unlikely, but possible on 16 bit machine if strstart ==
  15484. // 0
  15485. // and lookahead == 1 (input done one byte at time)
  15486. more--; // If the window is almost full and there is insufficient
  15487. // lookahead,
  15488. // move the upper half to the lower one to make room in the
  15489. // upper half.
  15490. } else if (strstart >= w_size + w_size - MIN_LOOKAHEAD) {
  15491. window.set(window.subarray(w_size, w_size + w_size), 0);
  15492. match_start -= w_size;
  15493. strstart -= w_size; // we now have strstart >= MAX_DIST
  15494. block_start -= w_size; // Slide the hash table (could be avoided with 32 bit values
  15495. // at the expense of memory usage). We slide even when level ==
  15496. // 0
  15497. // to keep the hash table consistent if we switch back to level
  15498. // > 0
  15499. // later. (Using level 0 permanently is not an optimal usage of
  15500. // zlib, so we don't care about this pathological case.)
  15501. n = hash_size;
  15502. p = n;
  15503. do {
  15504. m = head[--p] & 0xffff;
  15505. head[p] = m >= w_size ? m - w_size : 0;
  15506. } while (--n !== 0);
  15507. n = w_size;
  15508. p = n;
  15509. do {
  15510. m = prev[--p] & 0xffff;
  15511. prev[p] = m >= w_size ? m - w_size : 0; // If n is not on any hash chain, prev[n] is garbage but
  15512. // its value will never be used.
  15513. } while (--n !== 0);
  15514. more += w_size;
  15515. }
  15516. if (strm.avail_in === 0) return; // If there was no sliding:
  15517. // strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  15518. // more == window_size - lookahead - strstart
  15519. // => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  15520. // => more >= window_size - 2*WSIZE + 2
  15521. // In the BIG_MEM or MMAP case (not yet supported),
  15522. // window_size == input_size + MIN_LOOKAHEAD &&
  15523. // strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  15524. // Otherwise, window_size == 2*WSIZE so more >= 2.
  15525. // If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  15526. n = strm.read_buf(window, strstart + lookahead, more);
  15527. lookahead += n; // Initialize the hash value now that we have some input:
  15528. if (lookahead >= MIN_MATCH) {
  15529. ins_h = window[strstart] & 0xff;
  15530. ins_h = (ins_h << hash_shift ^ window[strstart + 1] & 0xff) & hash_mask;
  15531. } // If the whole input has less than MIN_MATCH bytes, ins_h is
  15532. // garbage,
  15533. // but this is not important since only literal bytes will be
  15534. // emitted.
  15535. } while (lookahead < MIN_LOOKAHEAD && strm.avail_in !== 0);
  15536. } // Copy without compression as much as possible from the input stream,
  15537. // return
  15538. // the current block state.
  15539. // This function does not insert new strings in the dictionary since
  15540. // uncompressible data is probably not useful. This function is used
  15541. // only for the level=0 compression option.
  15542. // NOTE: this function should be optimized to avoid extra copying from
  15543. // window to pending_buf.
  15544. function deflate_stored(flush) {
  15545. // Stored blocks are limited to 0xffff bytes, pending_buf is limited
  15546. // to pending_buf_size, and each stored block has a 5 byte header:
  15547. var max_block_size = 0xffff;
  15548. var max_start;
  15549. if (max_block_size > pending_buf_size - 5) {
  15550. max_block_size = pending_buf_size - 5;
  15551. } // Copy as much as possible from input to output:
  15552. while (true) {
  15553. // Fill the window as much as possible:
  15554. if (lookahead <= 1) {
  15555. fill_window();
  15556. if (lookahead === 0 && flush == Z_NO_FLUSH) return NeedMore;
  15557. if (lookahead === 0) break; // flush the current block
  15558. }
  15559. strstart += lookahead;
  15560. lookahead = 0; // Emit a stored block if pending_buf will be full:
  15561. max_start = block_start + max_block_size;
  15562. if (strstart === 0 || strstart >= max_start) {
  15563. // strstart === 0 is possible when wraparound on 16-bit machine
  15564. lookahead = strstart - max_start;
  15565. strstart = max_start;
  15566. flush_block_only(false);
  15567. if (strm.avail_out === 0) return NeedMore;
  15568. } // Flush if we may have to slide, otherwise block_start may become
  15569. // negative and the data will be gone:
  15570. if (strstart - block_start >= w_size - MIN_LOOKAHEAD) {
  15571. flush_block_only(false);
  15572. if (strm.avail_out === 0) return NeedMore;
  15573. }
  15574. }
  15575. flush_block_only(flush == Z_FINISH);
  15576. if (strm.avail_out === 0) return flush == Z_FINISH ? FinishStarted : NeedMore;
  15577. return flush == Z_FINISH ? FinishDone : BlockDone;
  15578. }
  15579. function longest_match(cur_match) {
  15580. var chain_length = max_chain_length; // max hash chain length
  15581. var scan = strstart; // current string
  15582. var match; // matched string
  15583. var len; // length of current match
  15584. var best_len = prev_length; // best match length so far
  15585. var limit = strstart > w_size - MIN_LOOKAHEAD ? strstart - (w_size - MIN_LOOKAHEAD) : 0;
  15586. var _nice_match = nice_match; // Stop when cur_match becomes <= limit. To simplify the code,
  15587. // we prevent matches with the string of window index 0.
  15588. var wmask = w_mask;
  15589. var strend = strstart + MAX_MATCH;
  15590. var scan_end1 = window[scan + best_len - 1];
  15591. var scan_end = window[scan + best_len]; // The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of
  15592. // 16.
  15593. // It is easy to get rid of this optimization if necessary.
  15594. // Do not waste too much time if we already have a good match:
  15595. if (prev_length >= good_match) {
  15596. chain_length >>= 2;
  15597. } // Do not look for matches beyond the end of the input. This is
  15598. // necessary
  15599. // to make deflate deterministic.
  15600. if (_nice_match > lookahead) _nice_match = lookahead;
  15601. do {
  15602. match = cur_match; // Skip to next match if the match length cannot increase
  15603. // or if the match length is less than 2:
  15604. if (window[match + best_len] != scan_end || window[match + best_len - 1] != scan_end1 || window[match] != window[scan] || window[++match] != window[scan + 1]) continue; // The check at best_len-1 can be removed because it will be made
  15605. // again later. (This heuristic is not always a win.)
  15606. // It is not necessary to compare scan[2] and match[2] since they
  15607. // are always equal when the other bytes match, given that
  15608. // the hash keys are equal and that HASH_BITS >= 8.
  15609. scan += 2;
  15610. match++; // We check for insufficient lookahead only every 8th comparison;
  15611. // the 256th check will be made at strstart+258.
  15612. do {} while (window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && scan < strend);
  15613. len = MAX_MATCH - (strend - scan);
  15614. scan = strend - MAX_MATCH;
  15615. if (len > best_len) {
  15616. match_start = cur_match;
  15617. best_len = len;
  15618. if (len >= _nice_match) break;
  15619. scan_end1 = window[scan + best_len - 1];
  15620. scan_end = window[scan + best_len];
  15621. }
  15622. } while ((cur_match = prev[cur_match & wmask] & 0xffff) > limit && --chain_length !== 0);
  15623. if (best_len <= lookahead) return best_len;
  15624. return lookahead;
  15625. } // Compress as much as possible from the input stream, return the current
  15626. // block state.
  15627. // This function does not perform lazy evaluation of matches and inserts
  15628. // new strings in the dictionary only for unmatched strings or for short
  15629. // matches. It is used only for the fast compression options.
  15630. function deflate_fast(flush) {
  15631. // short hash_head = 0; // head of the hash chain
  15632. var hash_head = 0; // head of the hash chain
  15633. var bflush; // set if current block must be flushed
  15634. while (true) {
  15635. // Make sure that we always have enough lookahead, except
  15636. // at the end of the input file. We need MAX_MATCH bytes
  15637. // for the next match, plus MIN_MATCH bytes to insert the
  15638. // string following the next match.
  15639. if (lookahead < MIN_LOOKAHEAD) {
  15640. fill_window();
  15641. if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  15642. return NeedMore;
  15643. }
  15644. if (lookahead === 0) break; // flush the current block
  15645. } // Insert the string window[strstart .. strstart+2] in the
  15646. // dictionary, and set hash_head to the head of the hash chain:
  15647. if (lookahead >= MIN_MATCH) {
  15648. ins_h = (ins_h << hash_shift ^ window[strstart + (MIN_MATCH - 1)] & 0xff) & hash_mask; // prev[strstart&w_mask]=hash_head=head[ins_h];
  15649. hash_head = head[ins_h] & 0xffff;
  15650. prev[strstart & w_mask] = head[ins_h];
  15651. head[ins_h] = strstart;
  15652. } // Find the longest match, discarding those <= prev_length.
  15653. // At this point we have always match_length < MIN_MATCH
  15654. if (hash_head !== 0 && (strstart - hash_head & 0xffff) <= w_size - MIN_LOOKAHEAD) {
  15655. // To simplify the code, we prevent matches with the string
  15656. // of window index 0 (in particular we have to avoid a match
  15657. // of the string with itself at the start of the input file).
  15658. if (strategy != Z_HUFFMAN_ONLY) {
  15659. match_length = longest_match(hash_head);
  15660. } // longest_match() sets match_start
  15661. }
  15662. if (match_length >= MIN_MATCH) {
  15663. // check_match(strstart, match_start, match_length);
  15664. bflush = _tr_tally(strstart - match_start, match_length - MIN_MATCH);
  15665. lookahead -= match_length; // Insert new strings in the hash table only if the match length
  15666. // is not too large. This saves time but degrades compression.
  15667. if (match_length <= max_lazy_match && lookahead >= MIN_MATCH) {
  15668. match_length--; // string at strstart already in hash table
  15669. do {
  15670. strstart++;
  15671. ins_h = (ins_h << hash_shift ^ window[strstart + (MIN_MATCH - 1)] & 0xff) & hash_mask; // prev[strstart&w_mask]=hash_head=head[ins_h];
  15672. hash_head = head[ins_h] & 0xffff;
  15673. prev[strstart & w_mask] = head[ins_h];
  15674. head[ins_h] = strstart; // strstart never exceeds WSIZE-MAX_MATCH, so there are
  15675. // always MIN_MATCH bytes ahead.
  15676. } while (--match_length !== 0);
  15677. strstart++;
  15678. } else {
  15679. strstart += match_length;
  15680. match_length = 0;
  15681. ins_h = window[strstart] & 0xff;
  15682. ins_h = (ins_h << hash_shift ^ window[strstart + 1] & 0xff) & hash_mask; // If lookahead < MIN_MATCH, ins_h is garbage, but it does
  15683. // not
  15684. // matter since it will be recomputed at next deflate call.
  15685. }
  15686. } else {
  15687. // No match, output a literal byte
  15688. bflush = _tr_tally(0, window[strstart] & 0xff);
  15689. lookahead--;
  15690. strstart++;
  15691. }
  15692. if (bflush) {
  15693. flush_block_only(false);
  15694. if (strm.avail_out === 0) return NeedMore;
  15695. }
  15696. }
  15697. flush_block_only(flush == Z_FINISH);
  15698. if (strm.avail_out === 0) {
  15699. if (flush == Z_FINISH) return FinishStarted;else return NeedMore;
  15700. }
  15701. return flush == Z_FINISH ? FinishDone : BlockDone;
  15702. } // Same as above, but achieves better compression. We use a lazy
  15703. // evaluation for matches: a match is finally adopted only if there is
  15704. // no better match at the next window position.
  15705. function deflate_slow(flush) {
  15706. // short hash_head = 0; // head of hash chain
  15707. var hash_head = 0; // head of hash chain
  15708. var bflush; // set if current block must be flushed
  15709. var max_insert; // Process the input block.
  15710. while (true) {
  15711. // Make sure that we always have enough lookahead, except
  15712. // at the end of the input file. We need MAX_MATCH bytes
  15713. // for the next match, plus MIN_MATCH bytes to insert the
  15714. // string following the next match.
  15715. if (lookahead < MIN_LOOKAHEAD) {
  15716. fill_window();
  15717. if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  15718. return NeedMore;
  15719. }
  15720. if (lookahead === 0) break; // flush the current block
  15721. } // Insert the string window[strstart .. strstart+2] in the
  15722. // dictionary, and set hash_head to the head of the hash chain:
  15723. if (lookahead >= MIN_MATCH) {
  15724. ins_h = (ins_h << hash_shift ^ window[strstart + (MIN_MATCH - 1)] & 0xff) & hash_mask; // prev[strstart&w_mask]=hash_head=head[ins_h];
  15725. hash_head = head[ins_h] & 0xffff;
  15726. prev[strstart & w_mask] = head[ins_h];
  15727. head[ins_h] = strstart;
  15728. } // Find the longest match, discarding those <= prev_length.
  15729. prev_length = match_length;
  15730. prev_match = match_start;
  15731. match_length = MIN_MATCH - 1;
  15732. if (hash_head !== 0 && prev_length < max_lazy_match && (strstart - hash_head & 0xffff) <= w_size - MIN_LOOKAHEAD) {
  15733. // To simplify the code, we prevent matches with the string
  15734. // of window index 0 (in particular we have to avoid a match
  15735. // of the string with itself at the start of the input file).
  15736. if (strategy != Z_HUFFMAN_ONLY) {
  15737. match_length = longest_match(hash_head);
  15738. } // longest_match() sets match_start
  15739. if (match_length <= 5 && (strategy == Z_FILTERED || match_length == MIN_MATCH && strstart - match_start > 4096)) {
  15740. // If prev_match is also MIN_MATCH, match_start is garbage
  15741. // but we will ignore the current match anyway.
  15742. match_length = MIN_MATCH - 1;
  15743. }
  15744. } // If there was a match at the previous step and the current
  15745. // match is not better, output the previous match:
  15746. if (prev_length >= MIN_MATCH && match_length <= prev_length) {
  15747. max_insert = strstart + lookahead - MIN_MATCH; // Do not insert strings in hash table beyond this.
  15748. // check_match(strstart-1, prev_match, prev_length);
  15749. bflush = _tr_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH); // Insert in hash table all strings up to the end of the match.
  15750. // strstart-1 and strstart are already inserted. If there is not
  15751. // enough lookahead, the last two strings are not inserted in
  15752. // the hash table.
  15753. lookahead -= prev_length - 1;
  15754. prev_length -= 2;
  15755. do {
  15756. if (++strstart <= max_insert) {
  15757. ins_h = (ins_h << hash_shift ^ window[strstart + (MIN_MATCH - 1)] & 0xff) & hash_mask; // prev[strstart&w_mask]=hash_head=head[ins_h];
  15758. hash_head = head[ins_h] & 0xffff;
  15759. prev[strstart & w_mask] = head[ins_h];
  15760. head[ins_h] = strstart;
  15761. }
  15762. } while (--prev_length !== 0);
  15763. match_available = 0;
  15764. match_length = MIN_MATCH - 1;
  15765. strstart++;
  15766. if (bflush) {
  15767. flush_block_only(false);
  15768. if (strm.avail_out === 0) return NeedMore;
  15769. }
  15770. } else if (match_available !== 0) {
  15771. // If there was no match at the previous position, output a
  15772. // single literal. If there was a match but the current match
  15773. // is longer, truncate the previous match to a single literal.
  15774. bflush = _tr_tally(0, window[strstart - 1] & 0xff);
  15775. if (bflush) {
  15776. flush_block_only(false);
  15777. }
  15778. strstart++;
  15779. lookahead--;
  15780. if (strm.avail_out === 0) return NeedMore;
  15781. } else {
  15782. // There is no previous match to compare with, wait for
  15783. // the next step to decide.
  15784. match_available = 1;
  15785. strstart++;
  15786. lookahead--;
  15787. }
  15788. }
  15789. if (match_available !== 0) {
  15790. bflush = _tr_tally(0, window[strstart - 1] & 0xff);
  15791. match_available = 0;
  15792. }
  15793. flush_block_only(flush == Z_FINISH);
  15794. if (strm.avail_out === 0) {
  15795. if (flush == Z_FINISH) return FinishStarted;else return NeedMore;
  15796. }
  15797. return flush == Z_FINISH ? FinishDone : BlockDone;
  15798. }
  15799. function deflateReset(strm) {
  15800. strm.total_in = strm.total_out = 0;
  15801. strm.msg = null; //
  15802. that.pending = 0;
  15803. that.pending_out = 0;
  15804. status = BUSY_STATE;
  15805. last_flush = Z_NO_FLUSH;
  15806. tr_init();
  15807. lm_init();
  15808. return Z_OK;
  15809. }
  15810. that.deflateInit = function (strm, _level, bits, _method, memLevel, _strategy) {
  15811. if (!_method) _method = Z_DEFLATED;
  15812. if (!memLevel) memLevel = DEF_MEM_LEVEL;
  15813. if (!_strategy) _strategy = Z_DEFAULT_STRATEGY; // byte[] my_version=ZLIB_VERSION;
  15814. //
  15815. // if (!version || version[0] != my_version[0]
  15816. // || stream_size != sizeof(z_stream)) {
  15817. // return Z_VERSION_ERROR;
  15818. // }
  15819. strm.msg = null;
  15820. if (_level == Z_DEFAULT_COMPRESSION) _level = 6;
  15821. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || _method != Z_DEFLATED || bits < 9 || bits > 15 || _level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) {
  15822. return Z_STREAM_ERROR;
  15823. }
  15824. strm.dstate = that;
  15825. w_bits = bits;
  15826. w_size = 1 << w_bits;
  15827. w_mask = w_size - 1;
  15828. hash_bits = memLevel + 7;
  15829. hash_size = 1 << hash_bits;
  15830. hash_mask = hash_size - 1;
  15831. hash_shift = Math.floor((hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  15832. window = new Uint8Array(w_size * 2);
  15833. prev = [];
  15834. head = [];
  15835. lit_bufsize = 1 << memLevel + 6; // 16K elements by default
  15836. // We overlay pending_buf and d_buf+l_buf. This works since the average
  15837. // output size for (length,distance) codes is <= 24 bits.
  15838. that.pending_buf = new Uint8Array(lit_bufsize * 4);
  15839. pending_buf_size = lit_bufsize * 4;
  15840. d_buf = Math.floor(lit_bufsize / 2);
  15841. l_buf = (1 + 2) * lit_bufsize;
  15842. level = _level;
  15843. strategy = _strategy;
  15844. return deflateReset(strm);
  15845. };
  15846. that.deflateEnd = function () {
  15847. if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE) {
  15848. return Z_STREAM_ERROR;
  15849. } // Deallocate in reverse order of allocations:
  15850. that.pending_buf = null;
  15851. head = null;
  15852. prev = null;
  15853. window = null; // free
  15854. that.dstate = null;
  15855. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  15856. };
  15857. that.deflateParams = function (strm, _level, _strategy) {
  15858. var err = Z_OK;
  15859. if (_level == Z_DEFAULT_COMPRESSION) {
  15860. _level = 6;
  15861. }
  15862. if (_level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) {
  15863. return Z_STREAM_ERROR;
  15864. }
  15865. if (config_table[level].func != config_table[_level].func && strm.total_in !== 0) {
  15866. // Flush the last buffer:
  15867. err = strm.deflate(Z_PARTIAL_FLUSH);
  15868. }
  15869. if (level != _level) {
  15870. level = _level;
  15871. max_lazy_match = config_table[level].max_lazy;
  15872. good_match = config_table[level].good_length;
  15873. nice_match = config_table[level].nice_length;
  15874. max_chain_length = config_table[level].max_chain;
  15875. }
  15876. strategy = _strategy;
  15877. return err;
  15878. };
  15879. that.deflateSetDictionary = function (strm, dictionary, dictLength) {
  15880. var length = dictLength;
  15881. var n,
  15882. index = 0;
  15883. if (!dictionary || status != INIT_STATE) return Z_STREAM_ERROR;
  15884. if (length < MIN_MATCH) return Z_OK;
  15885. if (length > w_size - MIN_LOOKAHEAD) {
  15886. length = w_size - MIN_LOOKAHEAD;
  15887. index = dictLength - length; // use the tail of the dictionary
  15888. }
  15889. window.set(dictionary.subarray(index, index + length), 0);
  15890. strstart = length;
  15891. block_start = length; // Insert all strings in the hash table (except for the last two bytes).
  15892. // s->lookahead stays null, so s->ins_h will be recomputed at the next
  15893. // call of fill_window.
  15894. ins_h = window[0] & 0xff;
  15895. ins_h = (ins_h << hash_shift ^ window[1] & 0xff) & hash_mask;
  15896. for (n = 0; n <= length - MIN_MATCH; n++) {
  15897. ins_h = (ins_h << hash_shift ^ window[n + (MIN_MATCH - 1)] & 0xff) & hash_mask;
  15898. prev[n & w_mask] = head[ins_h];
  15899. head[ins_h] = n;
  15900. }
  15901. return Z_OK;
  15902. };
  15903. that.deflate = function (_strm, flush) {
  15904. var i, header, level_flags, old_flush, bstate;
  15905. if (flush > Z_FINISH || flush < 0) {
  15906. return Z_STREAM_ERROR;
  15907. }
  15908. if (!_strm.next_out || !_strm.next_in && _strm.avail_in !== 0 || status == FINISH_STATE && flush != Z_FINISH) {
  15909. _strm.msg = z_errmsg[Z_NEED_DICT - Z_STREAM_ERROR];
  15910. return Z_STREAM_ERROR;
  15911. }
  15912. if (_strm.avail_out === 0) {
  15913. _strm.msg = z_errmsg[Z_NEED_DICT - Z_BUF_ERROR];
  15914. return Z_BUF_ERROR;
  15915. }
  15916. strm = _strm; // just in case
  15917. old_flush = last_flush;
  15918. last_flush = flush; // Write the zlib header
  15919. if (status == INIT_STATE) {
  15920. header = Z_DEFLATED + (w_bits - 8 << 4) << 8;
  15921. level_flags = (level - 1 & 0xff) >> 1;
  15922. if (level_flags > 3) level_flags = 3;
  15923. header |= level_flags << 6;
  15924. if (strstart !== 0) header |= PRESET_DICT;
  15925. header += 31 - header % 31;
  15926. status = BUSY_STATE;
  15927. putShortMSB(header);
  15928. } // Flush as much pending output as possible
  15929. if (that.pending !== 0) {
  15930. strm.flush_pending();
  15931. if (strm.avail_out === 0) {
  15932. // console.log(" avail_out==0");
  15933. // Since avail_out is 0, deflate will be called again with
  15934. // more output space, but possibly with both pending and
  15935. // avail_in equal to zero. There won't be anything to do,
  15936. // but this is not an error situation so make sure we
  15937. // return OK instead of BUF_ERROR at next call of deflate:
  15938. last_flush = -1;
  15939. return Z_OK;
  15940. } // Make sure there is something to do and avoid duplicate
  15941. // consecutive
  15942. // flushes. For repeated and useless calls with Z_FINISH, we keep
  15943. // returning Z_STREAM_END instead of Z_BUFF_ERROR.
  15944. } else if (strm.avail_in === 0 && flush <= old_flush && flush != Z_FINISH) {
  15945. strm.msg = z_errmsg[Z_NEED_DICT - Z_BUF_ERROR];
  15946. return Z_BUF_ERROR;
  15947. } // User must not provide more input after the first FINISH:
  15948. if (status == FINISH_STATE && strm.avail_in !== 0) {
  15949. _strm.msg = z_errmsg[Z_NEED_DICT - Z_BUF_ERROR];
  15950. return Z_BUF_ERROR;
  15951. } // Start a new block or continue the current one.
  15952. if (strm.avail_in !== 0 || lookahead !== 0 || flush != Z_NO_FLUSH && status != FINISH_STATE) {
  15953. bstate = -1;
  15954. switch (config_table[level].func) {
  15955. case STORED:
  15956. bstate = deflate_stored(flush);
  15957. break;
  15958. case FAST:
  15959. bstate = deflate_fast(flush);
  15960. break;
  15961. case SLOW:
  15962. bstate = deflate_slow(flush);
  15963. break;
  15964. default:
  15965. }
  15966. if (bstate == FinishStarted || bstate == FinishDone) {
  15967. status = FINISH_STATE;
  15968. }
  15969. if (bstate == NeedMore || bstate == FinishStarted) {
  15970. if (strm.avail_out === 0) {
  15971. last_flush = -1; // avoid BUF_ERROR next call, see above
  15972. }
  15973. return Z_OK; // If flush != Z_NO_FLUSH && avail_out === 0, the next call
  15974. // of deflate should use the same flush parameter to make sure
  15975. // that the flush is complete. So we don't have to output an
  15976. // empty block here, this will be done at next call. This also
  15977. // ensures that for a very small output buffer, we emit at most
  15978. // one empty block.
  15979. }
  15980. if (bstate == BlockDone) {
  15981. if (flush == Z_PARTIAL_FLUSH) {
  15982. _tr_align();
  15983. } else {
  15984. // FULL_FLUSH or SYNC_FLUSH
  15985. _tr_stored_block(0, 0, false); // For a full flush, this empty block will be recognized
  15986. // as a special marker by inflate_sync().
  15987. if (flush == Z_FULL_FLUSH) {
  15988. // state.head[s.hash_size-1]=0;
  15989. for (i = 0; i < hash_size
  15990. /*-1*/
  15991. ; i++) {
  15992. // forget history
  15993. head[i] = 0;
  15994. }
  15995. }
  15996. }
  15997. strm.flush_pending();
  15998. if (strm.avail_out === 0) {
  15999. last_flush = -1; // avoid BUF_ERROR at next call, see above
  16000. return Z_OK;
  16001. }
  16002. }
  16003. }
  16004. if (flush != Z_FINISH) return Z_OK;
  16005. return Z_STREAM_END;
  16006. };
  16007. } // ZStream
  16008. function ZStream() {
  16009. var that = this;
  16010. that.next_in_index = 0;
  16011. that.next_out_index = 0; // that.next_in; // next input byte
  16012. that.avail_in = 0; // number of bytes available at next_in
  16013. that.total_in = 0; // total nb of input bytes read so far
  16014. // that.next_out; // next output byte should be put there
  16015. that.avail_out = 0; // remaining free space at next_out
  16016. that.total_out = 0; // total nb of bytes output so far
  16017. // that.msg;
  16018. // that.dstate;
  16019. }
  16020. ZStream.prototype = {
  16021. deflateInit: function deflateInit(level, bits) {
  16022. var that = this;
  16023. that.dstate = new Deflate();
  16024. if (!bits) bits = MAX_BITS;
  16025. return that.dstate.deflateInit(that, level, bits);
  16026. },
  16027. deflate: function deflate(flush) {
  16028. var that = this;
  16029. if (!that.dstate) {
  16030. return Z_STREAM_ERROR;
  16031. }
  16032. return that.dstate.deflate(that, flush);
  16033. },
  16034. deflateEnd: function deflateEnd() {
  16035. var that = this;
  16036. if (!that.dstate) return Z_STREAM_ERROR;
  16037. var ret = that.dstate.deflateEnd();
  16038. that.dstate = null;
  16039. return ret;
  16040. },
  16041. deflateParams: function deflateParams(level, strategy) {
  16042. var that = this;
  16043. if (!that.dstate) return Z_STREAM_ERROR;
  16044. return that.dstate.deflateParams(that, level, strategy);
  16045. },
  16046. deflateSetDictionary: function deflateSetDictionary(dictionary, dictLength) {
  16047. var that = this;
  16048. if (!that.dstate) return Z_STREAM_ERROR;
  16049. return that.dstate.deflateSetDictionary(that, dictionary, dictLength);
  16050. },
  16051. // Read a new buffer from the current input stream, update the
  16052. // total number of bytes read. All deflate() input goes through
  16053. // this function so some applications may wish to modify it to avoid
  16054. // allocating a large strm->next_in buffer and copying from it.
  16055. // (See also flush_pending()).
  16056. read_buf: function read_buf(buf, start, size) {
  16057. var that = this;
  16058. var len = that.avail_in;
  16059. if (len > size) len = size;
  16060. if (len === 0) return 0;
  16061. that.avail_in -= len;
  16062. buf.set(that.next_in.subarray(that.next_in_index, that.next_in_index + len), start);
  16063. that.next_in_index += len;
  16064. that.total_in += len;
  16065. return len;
  16066. },
  16067. // Flush as much pending output as possible. All deflate() output goes
  16068. // through this function so some applications may wish to modify it
  16069. // to avoid allocating a large strm->next_out buffer and copying into it.
  16070. // (See also read_buf()).
  16071. flush_pending: function flush_pending() {
  16072. var that = this;
  16073. var len = that.dstate.pending;
  16074. if (len > that.avail_out) len = that.avail_out;
  16075. if (len === 0) return; // if (that.dstate.pending_buf.length <= that.dstate.pending_out || that.next_out.length <= that.next_out_index
  16076. // || that.dstate.pending_buf.length < (that.dstate.pending_out + len) || that.next_out.length < (that.next_out_index +
  16077. // len)) {
  16078. // console.log(that.dstate.pending_buf.length + ", " + that.dstate.pending_out + ", " + that.next_out.length + ", " +
  16079. // that.next_out_index + ", " + len);
  16080. // console.log("avail_out=" + that.avail_out);
  16081. // }
  16082. that.next_out.set(that.dstate.pending_buf.subarray(that.dstate.pending_out, that.dstate.pending_out + len), that.next_out_index);
  16083. that.next_out_index += len;
  16084. that.dstate.pending_out += len;
  16085. that.total_out += len;
  16086. that.avail_out -= len;
  16087. that.dstate.pending -= len;
  16088. if (that.dstate.pending === 0) {
  16089. that.dstate.pending_out = 0;
  16090. }
  16091. }
  16092. }; // Deflater
  16093. function Deflater(options) {
  16094. var that = this;
  16095. var z = new ZStream();
  16096. var bufsize = 512;
  16097. var flush = Z_NO_FLUSH;
  16098. var buf = new Uint8Array(bufsize);
  16099. var level = options ? options.level : Z_DEFAULT_COMPRESSION;
  16100. if (typeof level == "undefined") level = Z_DEFAULT_COMPRESSION;
  16101. z.deflateInit(level);
  16102. z.next_out = buf;
  16103. that.append = function (data, onprogress) {
  16104. var err,
  16105. buffers = [],
  16106. lastIndex = 0,
  16107. bufferIndex = 0,
  16108. bufferSize = 0,
  16109. array;
  16110. if (!data.length) return;
  16111. z.next_in_index = 0;
  16112. z.next_in = data;
  16113. z.avail_in = data.length;
  16114. do {
  16115. z.next_out_index = 0;
  16116. z.avail_out = bufsize;
  16117. err = z.deflate(flush);
  16118. if (err != Z_OK) throw new Error("deflating: " + z.msg);
  16119. if (z.next_out_index) if (z.next_out_index == bufsize) buffers.push(new Uint8Array(buf));else buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
  16120. bufferSize += z.next_out_index;
  16121. if (onprogress && z.next_in_index > 0 && z.next_in_index != lastIndex) {
  16122. onprogress(z.next_in_index);
  16123. lastIndex = z.next_in_index;
  16124. }
  16125. } while (z.avail_in > 0 || z.avail_out === 0);
  16126. array = new Uint8Array(bufferSize);
  16127. buffers.forEach(function (chunk) {
  16128. array.set(chunk, bufferIndex);
  16129. bufferIndex += chunk.length;
  16130. });
  16131. return array;
  16132. };
  16133. that.flush = function () {
  16134. var err,
  16135. buffers = [],
  16136. bufferIndex = 0,
  16137. bufferSize = 0,
  16138. array;
  16139. do {
  16140. z.next_out_index = 0;
  16141. z.avail_out = bufsize;
  16142. err = z.deflate(Z_FINISH);
  16143. if (err != Z_STREAM_END && err != Z_OK) throw new Error("deflating: " + z.msg);
  16144. if (bufsize - z.avail_out > 0) buffers.push(new Uint8Array(buf.subarray(0, z.next_out_index)));
  16145. bufferSize += z.next_out_index;
  16146. } while (z.avail_in > 0 || z.avail_out === 0);
  16147. z.deflateEnd();
  16148. array = new Uint8Array(bufferSize);
  16149. buffers.forEach(function (chunk) {
  16150. array.set(chunk, bufferIndex);
  16151. bufferIndex += chunk.length;
  16152. });
  16153. return array;
  16154. };
  16155. } // 'zip' may not be defined in z-worker and some tests
  16156. var env = global.zip || global;
  16157. env.Deflater = env._jzlib_Deflater = Deflater;
  16158. })(typeof self !== "undefined" && self || typeof window !== "undefined" && window || typeof global !== "undefined" && global || Function('return typeof this === "object" && this.content')() || Function('return this')()); // `self` is undefined in Firefox for Android content script context
  16159. // while `this` is nsIContentFrameMessageManager
  16160. // with an attribute `content` that corresponds to the window
  16161. /**
  16162. * A class to parse color values
  16163. * @author Stoyan Stefanov <sstoo@gmail.com>
  16164. * {@link http://www.phpied.com/rgb-color-parser-in-javascript/}
  16165. * @license Use it if you like it
  16166. */
  16167. (function (global) {
  16168. function RGBColor(color_string) {
  16169. color_string = color_string || '';
  16170. this.ok = false; // strip any leading #
  16171. if (color_string.charAt(0) == '#') {
  16172. // remove # if any
  16173. color_string = color_string.substr(1, 6);
  16174. }
  16175. color_string = color_string.replace(/ /g, '');
  16176. color_string = color_string.toLowerCase();
  16177. var channels; // before getting into regexps, try simple matches
  16178. // and overwrite the input
  16179. var simple_colors = {
  16180. aliceblue: 'f0f8ff',
  16181. antiquewhite: 'faebd7',
  16182. aqua: '00ffff',
  16183. aquamarine: '7fffd4',
  16184. azure: 'f0ffff',
  16185. beige: 'f5f5dc',
  16186. bisque: 'ffe4c4',
  16187. black: '000000',
  16188. blanchedalmond: 'ffebcd',
  16189. blue: '0000ff',
  16190. blueviolet: '8a2be2',
  16191. brown: 'a52a2a',
  16192. burlywood: 'deb887',
  16193. cadetblue: '5f9ea0',
  16194. chartreuse: '7fff00',
  16195. chocolate: 'd2691e',
  16196. coral: 'ff7f50',
  16197. cornflowerblue: '6495ed',
  16198. cornsilk: 'fff8dc',
  16199. crimson: 'dc143c',
  16200. cyan: '00ffff',
  16201. darkblue: '00008b',
  16202. darkcyan: '008b8b',
  16203. darkgoldenrod: 'b8860b',
  16204. darkgray: 'a9a9a9',
  16205. darkgreen: '006400',
  16206. darkkhaki: 'bdb76b',
  16207. darkmagenta: '8b008b',
  16208. darkolivegreen: '556b2f',
  16209. darkorange: 'ff8c00',
  16210. darkorchid: '9932cc',
  16211. darkred: '8b0000',
  16212. darksalmon: 'e9967a',
  16213. darkseagreen: '8fbc8f',
  16214. darkslateblue: '483d8b',
  16215. darkslategray: '2f4f4f',
  16216. darkturquoise: '00ced1',
  16217. darkviolet: '9400d3',
  16218. deeppink: 'ff1493',
  16219. deepskyblue: '00bfff',
  16220. dimgray: '696969',
  16221. dodgerblue: '1e90ff',
  16222. feldspar: 'd19275',
  16223. firebrick: 'b22222',
  16224. floralwhite: 'fffaf0',
  16225. forestgreen: '228b22',
  16226. fuchsia: 'ff00ff',
  16227. gainsboro: 'dcdcdc',
  16228. ghostwhite: 'f8f8ff',
  16229. gold: 'ffd700',
  16230. goldenrod: 'daa520',
  16231. gray: '808080',
  16232. green: '008000',
  16233. greenyellow: 'adff2f',
  16234. honeydew: 'f0fff0',
  16235. hotpink: 'ff69b4',
  16236. indianred: 'cd5c5c',
  16237. indigo: '4b0082',
  16238. ivory: 'fffff0',
  16239. khaki: 'f0e68c',
  16240. lavender: 'e6e6fa',
  16241. lavenderblush: 'fff0f5',
  16242. lawngreen: '7cfc00',
  16243. lemonchiffon: 'fffacd',
  16244. lightblue: 'add8e6',
  16245. lightcoral: 'f08080',
  16246. lightcyan: 'e0ffff',
  16247. lightgoldenrodyellow: 'fafad2',
  16248. lightgrey: 'd3d3d3',
  16249. lightgreen: '90ee90',
  16250. lightpink: 'ffb6c1',
  16251. lightsalmon: 'ffa07a',
  16252. lightseagreen: '20b2aa',
  16253. lightskyblue: '87cefa',
  16254. lightslateblue: '8470ff',
  16255. lightslategray: '778899',
  16256. lightsteelblue: 'b0c4de',
  16257. lightyellow: 'ffffe0',
  16258. lime: '00ff00',
  16259. limegreen: '32cd32',
  16260. linen: 'faf0e6',
  16261. magenta: 'ff00ff',
  16262. maroon: '800000',
  16263. mediumaquamarine: '66cdaa',
  16264. mediumblue: '0000cd',
  16265. mediumorchid: 'ba55d3',
  16266. mediumpurple: '9370d8',
  16267. mediumseagreen: '3cb371',
  16268. mediumslateblue: '7b68ee',
  16269. mediumspringgreen: '00fa9a',
  16270. mediumturquoise: '48d1cc',
  16271. mediumvioletred: 'c71585',
  16272. midnightblue: '191970',
  16273. mintcream: 'f5fffa',
  16274. mistyrose: 'ffe4e1',
  16275. moccasin: 'ffe4b5',
  16276. navajowhite: 'ffdead',
  16277. navy: '000080',
  16278. oldlace: 'fdf5e6',
  16279. olive: '808000',
  16280. olivedrab: '6b8e23',
  16281. orange: 'ffa500',
  16282. orangered: 'ff4500',
  16283. orchid: 'da70d6',
  16284. palegoldenrod: 'eee8aa',
  16285. palegreen: '98fb98',
  16286. paleturquoise: 'afeeee',
  16287. palevioletred: 'd87093',
  16288. papayawhip: 'ffefd5',
  16289. peachpuff: 'ffdab9',
  16290. peru: 'cd853f',
  16291. pink: 'ffc0cb',
  16292. plum: 'dda0dd',
  16293. powderblue: 'b0e0e6',
  16294. purple: '800080',
  16295. red: 'ff0000',
  16296. rosybrown: 'bc8f8f',
  16297. royalblue: '4169e1',
  16298. saddlebrown: '8b4513',
  16299. salmon: 'fa8072',
  16300. sandybrown: 'f4a460',
  16301. seagreen: '2e8b57',
  16302. seashell: 'fff5ee',
  16303. sienna: 'a0522d',
  16304. silver: 'c0c0c0',
  16305. skyblue: '87ceeb',
  16306. slateblue: '6a5acd',
  16307. slategray: '708090',
  16308. snow: 'fffafa',
  16309. springgreen: '00ff7f',
  16310. steelblue: '4682b4',
  16311. tan: 'd2b48c',
  16312. teal: '008080',
  16313. thistle: 'd8bfd8',
  16314. tomato: 'ff6347',
  16315. turquoise: '40e0d0',
  16316. violet: 'ee82ee',
  16317. violetred: 'd02090',
  16318. wheat: 'f5deb3',
  16319. white: 'ffffff',
  16320. whitesmoke: 'f5f5f5',
  16321. yellow: 'ffff00',
  16322. yellowgreen: '9acd32'
  16323. };
  16324. for (var key in simple_colors) {
  16325. if (color_string == key) {
  16326. color_string = simple_colors[key];
  16327. }
  16328. } // emd of simple type-in colors
  16329. // array of color definition objects
  16330. var color_defs = [{
  16331. re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
  16332. example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],
  16333. process: function process(bits) {
  16334. return [parseInt(bits[1]), parseInt(bits[2]), parseInt(bits[3])];
  16335. }
  16336. }, {
  16337. re: /^(\w{2})(\w{2})(\w{2})$/,
  16338. example: ['#00ff00', '336699'],
  16339. process: function process(bits) {
  16340. return [parseInt(bits[1], 16), parseInt(bits[2], 16), parseInt(bits[3], 16)];
  16341. }
  16342. }, {
  16343. re: /^(\w{1})(\w{1})(\w{1})$/,
  16344. example: ['#fb0', 'f0f'],
  16345. process: function process(bits) {
  16346. return [parseInt(bits[1] + bits[1], 16), parseInt(bits[2] + bits[2], 16), parseInt(bits[3] + bits[3], 16)];
  16347. }
  16348. }]; // search through the definitions to find a match
  16349. for (var i = 0; i < color_defs.length; i++) {
  16350. var re = color_defs[i].re;
  16351. var processor = color_defs[i].process;
  16352. var bits = re.exec(color_string);
  16353. if (bits) {
  16354. channels = processor(bits);
  16355. this.r = channels[0];
  16356. this.g = channels[1];
  16357. this.b = channels[2];
  16358. this.ok = true;
  16359. }
  16360. } // validate/cleanup values
  16361. this.r = this.r < 0 || isNaN(this.r) ? 0 : this.r > 255 ? 255 : this.r;
  16362. this.g = this.g < 0 || isNaN(this.g) ? 0 : this.g > 255 ? 255 : this.g;
  16363. this.b = this.b < 0 || isNaN(this.b) ? 0 : this.b > 255 ? 255 : this.b; // some getters
  16364. this.toRGB = function () {
  16365. return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
  16366. };
  16367. this.toHex = function () {
  16368. var r = this.r.toString(16);
  16369. var g = this.g.toString(16);
  16370. var b = this.b.toString(16);
  16371. if (r.length == 1) r = '0' + r;
  16372. if (g.length == 1) g = '0' + g;
  16373. if (b.length == 1) b = '0' + b;
  16374. return '#' + r + g + b;
  16375. };
  16376. }
  16377. global.RGBColor = RGBColor;
  16378. })(typeof self !== "undefined" && self || typeof window !== "undefined" && window || typeof global !== "undefined" && global || Function('return typeof this === "object" && this.content')() || Function('return this')()); // `self` is undefined in Firefox for Android content script context
  16379. // while `this` is nsIContentFrameMessageManager
  16380. // with an attribute `content` that corresponds to the window
  16381. /************************************************
  16382. * Title : custom font *
  16383. * Start Data : 2017. 01. 22. *
  16384. * Comment : TEXT API *
  16385. ************************************************/
  16386. /******************************
  16387. * jsPDF extension API Design *
  16388. * ****************************/
  16389. (function (jsPDF) {
  16390. var PLUS = '+'.charCodeAt(0);
  16391. var SLASH = '/'.charCodeAt(0);
  16392. var NUMBER = '0'.charCodeAt(0);
  16393. var LOWER = 'a'.charCodeAt(0);
  16394. var UPPER = 'A'.charCodeAt(0);
  16395. var PLUS_URL_SAFE = '-'.charCodeAt(0);
  16396. var SLASH_URL_SAFE = '_'.charCodeAt(0);
  16397. /*****************************************************************/
  16398. /* function : b64ToByteArray */
  16399. /* comment : Base64 encoded TTF file contents (b64) are decoded */
  16400. /* by Byte array and stored. */
  16401. /*****************************************************************/
  16402. var b64ToByteArray = function b64ToByteArray(b64) {
  16403. var i, j, l, tmp, placeHolders, arr;
  16404. if (b64.length % 4 > 0) {
  16405. throw new Error('Invalid string. Length must be a multiple of 4');
  16406. } // the number of equal signs (place holders)
  16407. // if there are two placeholders, than the two characters before it
  16408. // represent one byte
  16409. // if there is only one, then the three characters before it represent 2 bytes
  16410. // this is just a cheap hack to not do indexOf twice
  16411. var len = b64.length;
  16412. placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0; // base64 is 4/3 + up to two characters of the original data
  16413. arr = new Uint8Array(b64.length * 3 / 4 - placeHolders); // if there are placeholders, only get up to the last complete 4 chars
  16414. l = placeHolders > 0 ? b64.length - 4 : b64.length;
  16415. var L = 0;
  16416. function push(v) {
  16417. arr[L++] = v;
  16418. }
  16419. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  16420. tmp = decode(b64.charAt(i)) << 18 | decode(b64.charAt(i + 1)) << 12 | decode(b64.charAt(i + 2)) << 6 | decode(b64.charAt(i + 3));
  16421. push((tmp & 0xFF0000) >> 16);
  16422. push((tmp & 0xFF00) >> 8);
  16423. push(tmp & 0xFF);
  16424. }
  16425. if (placeHolders === 2) {
  16426. tmp = decode(b64.charAt(i)) << 2 | decode(b64.charAt(i + 1)) >> 4;
  16427. push(tmp & 0xFF);
  16428. } else if (placeHolders === 1) {
  16429. tmp = decode(b64.charAt(i)) << 10 | decode(b64.charAt(i + 1)) << 4 | decode(b64.charAt(i + 2)) >> 2;
  16430. push(tmp >> 8 & 0xFF);
  16431. push(tmp & 0xFF);
  16432. }
  16433. return arr;
  16434. };
  16435. /***************************************************************/
  16436. /* function : decode */
  16437. /* comment : Change the base64 encoded font's content to match */
  16438. /* the base64 index value. */
  16439. /***************************************************************/
  16440. var decode = function decode(elt) {
  16441. var code = elt.charCodeAt(0);
  16442. if (code === PLUS || code === PLUS_URL_SAFE) return 62; // '+'
  16443. if (code === SLASH || code === SLASH_URL_SAFE) return 63; // '/'
  16444. if (code < NUMBER) return -1; //no match
  16445. if (code < NUMBER + 10) return code - NUMBER + 26 + 26;
  16446. if (code < UPPER + 26) return code - UPPER;
  16447. if (code < LOWER + 26) return code - LOWER + 26;
  16448. };
  16449. jsPDF.API.TTFFont = function () {
  16450. /************************************************************************/
  16451. /* function : open */
  16452. /* comment : Decode the encoded ttf content and create a TTFFont object. */
  16453. /************************************************************************/
  16454. TTFFont.open = function (filename, name, vfs, encoding) {
  16455. var contents;
  16456. if (typeof vfs !== "string") {
  16457. throw new Error('Invalid argument supplied in TTFFont.open');
  16458. }
  16459. contents = b64ToByteArray(vfs);
  16460. return new TTFFont(contents, name, encoding);
  16461. };
  16462. /***************************************************************/
  16463. /* function : TTFFont gernerator */
  16464. /* comment : Decode TTF contents are parsed, Data, */
  16465. /* Subset object is created, and registerTTF function is called.*/
  16466. /***************************************************************/
  16467. function TTFFont(rawData, name, encoding) {
  16468. var data;
  16469. this.rawData = rawData;
  16470. data = this.contents = new Data(rawData);
  16471. this.contents.pos = 4;
  16472. if (data.readString(4) === 'ttcf') {
  16473. if (!name) {
  16474. throw new Error("Must specify a font name for TTC files.");
  16475. }
  16476. throw new Error("Font " + name + " not found in TTC file.");
  16477. } else {
  16478. data.pos = 0;
  16479. this.parse();
  16480. this.subset = new Subset(this);
  16481. this.registerTTF();
  16482. }
  16483. }
  16484. /********************************************************/
  16485. /* function : parse */
  16486. /* comment : TTF Parses the file contents by each table.*/
  16487. /********************************************************/
  16488. TTFFont.prototype.parse = function () {
  16489. this.directory = new Directory(this.contents);
  16490. this.head = new HeadTable(this);
  16491. this.name = new NameTable(this);
  16492. this.cmap = new CmapTable(this);
  16493. this.toUnicode = new Map();
  16494. this.hhea = new HheaTable(this);
  16495. this.maxp = new MaxpTable(this);
  16496. this.hmtx = new HmtxTable(this);
  16497. this.post = new PostTable(this);
  16498. this.os2 = new OS2Table(this);
  16499. this.loca = new LocaTable(this);
  16500. this.glyf = new GlyfTable(this);
  16501. this.ascender = this.os2.exists && this.os2.ascender || this.hhea.ascender;
  16502. this.decender = this.os2.exists && this.os2.decender || this.hhea.decender;
  16503. this.lineGap = this.os2.exists && this.os2.lineGap || this.hhea.lineGap;
  16504. return this.bbox = [this.head.xMin, this.head.yMin, this.head.xMax, this.head.yMax];
  16505. };
  16506. /***************************************************************/
  16507. /* function : registerTTF */
  16508. /* comment : Get the value to assign pdf font descriptors. */
  16509. /***************************************************************/
  16510. TTFFont.prototype.registerTTF = function () {
  16511. var e, hi, low, raw, _ref;
  16512. this.scaleFactor = 1000.0 / this.head.unitsPerEm;
  16513. this.bbox = function () {
  16514. var _i, _len, _ref, _results;
  16515. _ref = this.bbox;
  16516. _results = [];
  16517. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  16518. e = _ref[_i];
  16519. _results.push(Math.round(e * this.scaleFactor));
  16520. }
  16521. return _results;
  16522. }.call(this);
  16523. this.stemV = 0;
  16524. if (this.post.exists) {
  16525. raw = this.post.italic_angle;
  16526. hi = raw >> 16;
  16527. low = raw & 0xFF;
  16528. if (hi & 0x8000 !== 0) {
  16529. hi = -((hi ^ 0xFFFF) + 1);
  16530. }
  16531. this.italicAngle = +("" + hi + "." + low);
  16532. } else {
  16533. this.italicAngle = 0;
  16534. }
  16535. this.ascender = Math.round(this.ascender * this.scaleFactor);
  16536. this.decender = Math.round(this.decender * this.scaleFactor);
  16537. this.lineGap = Math.round(this.lineGap * this.scaleFactor);
  16538. this.capHeight = this.os2.exists && this.os2.capHeight || this.ascender;
  16539. this.xHeight = this.os2.exists && this.os2.xHeight || 0;
  16540. this.familyClass = (this.os2.exists && this.os2.familyClass || 0) >> 8;
  16541. this.isSerif = (_ref = this.familyClass) === 1 || _ref === 2 || _ref === 3 || _ref === 4 || _ref === 5 || _ref === 7;
  16542. this.isScript = this.familyClass === 10;
  16543. this.flags = 0;
  16544. if (this.post.isFixedPitch) {
  16545. this.flags |= 1 << 0;
  16546. }
  16547. if (this.isSerif) {
  16548. this.flags |= 1 << 1;
  16549. }
  16550. if (this.isScript) {
  16551. this.flags |= 1 << 3;
  16552. }
  16553. if (this.italicAngle !== 0) {
  16554. this.flags |= 1 << 6;
  16555. }
  16556. this.flags |= 1 << 5;
  16557. if (!this.cmap.unicode) {
  16558. throw new Error('No unicode cmap for font');
  16559. }
  16560. };
  16561. TTFFont.prototype.characterToGlyph = function (character) {
  16562. var _ref;
  16563. return ((_ref = this.cmap.unicode) != null ? _ref.codeMap[character] : void 0) || 0;
  16564. };
  16565. TTFFont.prototype.widthOfGlyph = function (glyph) {
  16566. var scale;
  16567. scale = 1000.0 / this.head.unitsPerEm;
  16568. return this.hmtx.forGlyph(glyph).advance * scale;
  16569. };
  16570. TTFFont.prototype.widthOfString = function (string, size, charSpace) {
  16571. var charCode, i, scale, width, _i, _ref, charSpace;
  16572. string = '' + string;
  16573. width = 0;
  16574. for (i = _i = 0, _ref = string.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  16575. charCode = string.charCodeAt(i);
  16576. width += this.widthOfGlyph(this.characterToGlyph(charCode)) + charSpace * (1000 / size) || 0;
  16577. }
  16578. scale = size / 1000;
  16579. return width * scale;
  16580. };
  16581. TTFFont.prototype.lineHeight = function (size, includeGap) {
  16582. var gap;
  16583. if (includeGap == null) {
  16584. includeGap = false;
  16585. }
  16586. gap = includeGap ? this.lineGap : 0;
  16587. return (this.ascender + gap - this.decender) / 1000 * size;
  16588. };
  16589. return TTFFont;
  16590. }();
  16591. /************************************************************************************************/
  16592. /* function : Data */
  16593. /* comment : The ttf data decoded and stored in an array is read and written to the Data object.*/
  16594. /************************************************************************************************/
  16595. var Data = function () {
  16596. function Data(data) {
  16597. this.data = data != null ? data : [];
  16598. this.pos = 0;
  16599. this.length = this.data.length;
  16600. }
  16601. Data.prototype.readByte = function () {
  16602. return this.data[this.pos++];
  16603. };
  16604. Data.prototype.writeByte = function (byte) {
  16605. return this.data[this.pos++] = byte;
  16606. };
  16607. Data.prototype.readUInt32 = function () {
  16608. var b1, b2, b3, b4;
  16609. b1 = this.readByte() * 0x1000000;
  16610. b2 = this.readByte() << 16;
  16611. b3 = this.readByte() << 8;
  16612. b4 = this.readByte();
  16613. return b1 + b2 + b3 + b4;
  16614. };
  16615. Data.prototype.writeUInt32 = function (val) {
  16616. this.writeByte(val >>> 24 & 0xff);
  16617. this.writeByte(val >> 16 & 0xff);
  16618. this.writeByte(val >> 8 & 0xff);
  16619. return this.writeByte(val & 0xff);
  16620. };
  16621. Data.prototype.readInt32 = function () {
  16622. var int;
  16623. int = this.readUInt32();
  16624. if (int >= 0x80000000) {
  16625. return int - 0x100000000;
  16626. } else {
  16627. return int;
  16628. }
  16629. };
  16630. Data.prototype.writeInt32 = function (val) {
  16631. if (val < 0) {
  16632. val += 0x100000000;
  16633. }
  16634. return this.writeUInt32(val);
  16635. };
  16636. Data.prototype.readUInt16 = function () {
  16637. var b1, b2;
  16638. b1 = this.readByte() << 8;
  16639. b2 = this.readByte();
  16640. return b1 | b2;
  16641. };
  16642. Data.prototype.writeUInt16 = function (val) {
  16643. this.writeByte(val >> 8 & 0xff);
  16644. return this.writeByte(val & 0xff);
  16645. };
  16646. Data.prototype.readInt16 = function () {
  16647. var int;
  16648. int = this.readUInt16();
  16649. if (int >= 0x8000) {
  16650. return int - 0x10000;
  16651. } else {
  16652. return int;
  16653. }
  16654. };
  16655. Data.prototype.writeInt16 = function (val) {
  16656. if (val < 0) {
  16657. val += 0x10000;
  16658. }
  16659. return this.writeUInt16(val);
  16660. };
  16661. Data.prototype.readString = function (length) {
  16662. var i, ret, _i;
  16663. ret = [];
  16664. for (i = _i = 0; 0 <= length ? _i < length : _i > length; i = 0 <= length ? ++_i : --_i) {
  16665. ret[i] = String.fromCharCode(this.readByte());
  16666. }
  16667. return ret.join('');
  16668. };
  16669. Data.prototype.writeString = function (val) {
  16670. var i, _i, _ref, _results;
  16671. _results = [];
  16672. for (i = _i = 0, _ref = val.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  16673. _results.push(this.writeByte(val.charCodeAt(i)));
  16674. }
  16675. return _results;
  16676. };
  16677. /*Data.prototype.stringAt = function (pos, length) {
  16678. this.pos = pos;
  16679. return this.readString(length);
  16680. };*/
  16681. Data.prototype.readShort = function () {
  16682. return this.readInt16();
  16683. };
  16684. Data.prototype.writeShort = function (val) {
  16685. return this.writeInt16(val);
  16686. };
  16687. Data.prototype.readLongLong = function () {
  16688. var b1, b2, b3, b4, b5, b6, b7, b8;
  16689. b1 = this.readByte();
  16690. b2 = this.readByte();
  16691. b3 = this.readByte();
  16692. b4 = this.readByte();
  16693. b5 = this.readByte();
  16694. b6 = this.readByte();
  16695. b7 = this.readByte();
  16696. b8 = this.readByte();
  16697. if (b1 & 0x80) {
  16698. return ((b1 ^ 0xff) * 0x100000000000000 + (b2 ^ 0xff) * 0x1000000000000 + (b3 ^ 0xff) * 0x10000000000 + (b4 ^ 0xff) * 0x100000000 + (b5 ^ 0xff) * 0x1000000 + (b6 ^ 0xff) * 0x10000 + (b7 ^ 0xff) * 0x100 + (b8 ^ 0xff) + 1) * -1;
  16699. }
  16700. return b1 * 0x100000000000000 + b2 * 0x1000000000000 + b3 * 0x10000000000 + b4 * 0x100000000 + b5 * 0x1000000 + b6 * 0x10000 + b7 * 0x100 + b8;
  16701. };
  16702. Data.prototype.writeLongLong = function (val) {
  16703. var high, low;
  16704. high = Math.floor(val / 0x100000000);
  16705. low = val & 0xffffffff;
  16706. this.writeByte(high >> 24 & 0xff);
  16707. this.writeByte(high >> 16 & 0xff);
  16708. this.writeByte(high >> 8 & 0xff);
  16709. this.writeByte(high & 0xff);
  16710. this.writeByte(low >> 24 & 0xff);
  16711. this.writeByte(low >> 16 & 0xff);
  16712. this.writeByte(low >> 8 & 0xff);
  16713. return this.writeByte(low & 0xff);
  16714. };
  16715. Data.prototype.readInt = function () {
  16716. return this.readInt32();
  16717. };
  16718. Data.prototype.writeInt = function (val) {
  16719. return this.writeInt32(val);
  16720. };
  16721. /*Data.prototype.slice = function (start, end) {
  16722. return this.data.slice(start, end);
  16723. };*/
  16724. Data.prototype.read = function (bytes) {
  16725. var buf, i, _i;
  16726. buf = [];
  16727. for (i = _i = 0; 0 <= bytes ? _i < bytes : _i > bytes; i = 0 <= bytes ? ++_i : --_i) {
  16728. buf.push(this.readByte());
  16729. }
  16730. return buf;
  16731. };
  16732. Data.prototype.write = function (bytes) {
  16733. var byte, _i, _len, _results;
  16734. _results = [];
  16735. for (_i = 0, _len = bytes.length; _i < _len; _i++) {
  16736. byte = bytes[_i];
  16737. _results.push(this.writeByte(byte));
  16738. }
  16739. return _results;
  16740. };
  16741. return Data;
  16742. }();
  16743. var Directory = function () {
  16744. var checksum;
  16745. /*****************************************************************************************************/
  16746. /* function : Directory generator */
  16747. /* comment : Initialize the offset, tag, length, and checksum for each table for the font to be used.*/
  16748. /*****************************************************************************************************/
  16749. function Directory(data) {
  16750. var entry, i, _i, _ref;
  16751. this.scalarType = data.readInt();
  16752. this.tableCount = data.readShort();
  16753. this.searchRange = data.readShort();
  16754. this.entrySelector = data.readShort();
  16755. this.rangeShift = data.readShort();
  16756. this.tables = {};
  16757. for (i = _i = 0, _ref = this.tableCount; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  16758. entry = {
  16759. tag: data.readString(4),
  16760. checksum: data.readInt(),
  16761. offset: data.readInt(),
  16762. length: data.readInt()
  16763. };
  16764. this.tables[entry.tag] = entry;
  16765. }
  16766. }
  16767. /********************************************************************************************************/
  16768. /* function : encode */
  16769. /* comment : It encodes and stores the font table object and information used for the directory object. */
  16770. /********************************************************************************************************/
  16771. Directory.prototype.encode = function (tables) {
  16772. var adjustment, directory, directoryLength, entrySelector, headOffset, log2, offset, rangeShift, searchRange, sum, table, tableCount, tableData, tag;
  16773. tableCount = Object.keys(tables).length;
  16774. log2 = Math.log(2);
  16775. searchRange = Math.floor(Math.log(tableCount) / log2) * 16;
  16776. entrySelector = Math.floor(searchRange / log2);
  16777. rangeShift = tableCount * 16 - searchRange;
  16778. directory = new Data();
  16779. directory.writeInt(this.scalarType);
  16780. directory.writeShort(tableCount);
  16781. directory.writeShort(searchRange);
  16782. directory.writeShort(entrySelector);
  16783. directory.writeShort(rangeShift);
  16784. directoryLength = tableCount * 16;
  16785. offset = directory.pos + directoryLength;
  16786. headOffset = null;
  16787. tableData = [];
  16788. for (tag in tables) {
  16789. table = tables[tag];
  16790. directory.writeString(tag);
  16791. directory.writeInt(checksum(table));
  16792. directory.writeInt(offset);
  16793. directory.writeInt(table.length);
  16794. tableData = tableData.concat(table);
  16795. if (tag === 'head') {
  16796. headOffset = offset;
  16797. }
  16798. offset += table.length;
  16799. while (offset % 4) {
  16800. tableData.push(0);
  16801. offset++;
  16802. }
  16803. }
  16804. directory.write(tableData);
  16805. sum = checksum(directory.data);
  16806. adjustment = 0xB1B0AFBA - sum;
  16807. directory.pos = headOffset + 8;
  16808. directory.writeUInt32(adjustment);
  16809. return directory.data;
  16810. };
  16811. /***************************************************************/
  16812. /* function : checksum */
  16813. /* comment : Duplicate the table for the tag. */
  16814. /***************************************************************/
  16815. checksum = function checksum(data) {
  16816. var i, sum, tmp, _i, _ref;
  16817. data = __slice.call(data);
  16818. while (data.length % 4) {
  16819. data.push(0);
  16820. }
  16821. tmp = new Data(data);
  16822. sum = 0;
  16823. for (i = _i = 0, _ref = data.length; _i < _ref; i = _i += 4) {
  16824. sum += tmp.readUInt32();
  16825. }
  16826. return sum & 0xFFFFFFFF;
  16827. };
  16828. return Directory;
  16829. }();
  16830. var Table,
  16831. __hasProp = {}.hasOwnProperty,
  16832. __extends = function __extends(child, parent) {
  16833. for (var key in parent) {
  16834. if (__hasProp.call(parent, key)) child[key] = parent[key];
  16835. }
  16836. function ctor() {
  16837. this.constructor = child;
  16838. }
  16839. ctor.prototype = parent.prototype;
  16840. child.prototype = new ctor();
  16841. child.__super__ = parent.prototype;
  16842. return child;
  16843. };
  16844. /***************************************************************/
  16845. /* function : Table */
  16846. /* comment : Save info for each table, and parse the table. */
  16847. /***************************************************************/
  16848. Table = function () {
  16849. function Table(file) {
  16850. var info;
  16851. this.file = file;
  16852. info = this.file.directory.tables[this.tag];
  16853. this.exists = !!info;
  16854. if (info) {
  16855. this.offset = info.offset, this.length = info.length;
  16856. this.parse(this.file.contents);
  16857. }
  16858. }
  16859. Table.prototype.parse = function () {};
  16860. Table.prototype.encode = function () {};
  16861. Table.prototype.raw = function () {
  16862. if (!this.exists) {
  16863. return null;
  16864. }
  16865. this.file.contents.pos = this.offset;
  16866. return this.file.contents.read(this.length);
  16867. };
  16868. return Table;
  16869. }();
  16870. var HeadTable = function (_super) {
  16871. __extends(HeadTable, _super);
  16872. function HeadTable() {
  16873. return HeadTable.__super__.constructor.apply(this, arguments);
  16874. }
  16875. HeadTable.prototype.tag = 'head';
  16876. HeadTable.prototype.parse = function (data) {
  16877. data.pos = this.offset;
  16878. this.version = data.readInt();
  16879. this.revision = data.readInt();
  16880. this.checkSumAdjustment = data.readInt();
  16881. this.magicNumber = data.readInt();
  16882. this.flags = data.readShort();
  16883. this.unitsPerEm = data.readShort();
  16884. this.created = data.readLongLong();
  16885. this.modified = data.readLongLong();
  16886. this.xMin = data.readShort();
  16887. this.yMin = data.readShort();
  16888. this.xMax = data.readShort();
  16889. this.yMax = data.readShort();
  16890. this.macStyle = data.readShort();
  16891. this.lowestRecPPEM = data.readShort();
  16892. this.fontDirectionHint = data.readShort();
  16893. this.indexToLocFormat = data.readShort();
  16894. return this.glyphDataFormat = data.readShort();
  16895. };
  16896. HeadTable.prototype.encode = function (indexToLocFormat) {
  16897. var table;
  16898. table = new Data();
  16899. table.writeInt(this.version);
  16900. table.writeInt(this.revision);
  16901. table.writeInt(this.checkSumAdjustment);
  16902. table.writeInt(this.magicNumber);
  16903. table.writeShort(this.flags);
  16904. table.writeShort(this.unitsPerEm);
  16905. table.writeLongLong(this.created);
  16906. table.writeLongLong(this.modified);
  16907. table.writeShort(this.xMin);
  16908. table.writeShort(this.yMin);
  16909. table.writeShort(this.xMax);
  16910. table.writeShort(this.yMax);
  16911. table.writeShort(this.macStyle);
  16912. table.writeShort(this.lowestRecPPEM);
  16913. table.writeShort(this.fontDirectionHint);
  16914. table.writeShort(indexToLocFormat);
  16915. table.writeShort(this.glyphDataFormat);
  16916. return table.data;
  16917. };
  16918. return HeadTable;
  16919. }(Table);
  16920. /************************************************************************************/
  16921. /* function : CmapEntry */
  16922. /* comment : Cmap Initializes and encodes object information (required by pdf spec).*/
  16923. /************************************************************************************/
  16924. var CmapEntry = function () {
  16925. function CmapEntry(data, offset) {
  16926. var code, count, endCode, glyphId, glyphIds, i, idDelta, idRangeOffset, index, saveOffset, segCount, segCountX2, start, startCode, tail, _i, _j, _k, _len;
  16927. this.platformID = data.readUInt16();
  16928. this.encodingID = data.readShort();
  16929. this.offset = offset + data.readInt();
  16930. saveOffset = data.pos;
  16931. data.pos = this.offset;
  16932. this.format = data.readUInt16();
  16933. this.length = data.readUInt16();
  16934. this.language = data.readUInt16();
  16935. this.isUnicode = this.platformID === 3 && this.encodingID === 1 && this.format === 4 || this.platformID === 0 && this.format === 4;
  16936. this.codeMap = {};
  16937. switch (this.format) {
  16938. case 0:
  16939. for (i = _i = 0; _i < 256; i = ++_i) {
  16940. this.codeMap[i] = data.readByte();
  16941. }
  16942. break;
  16943. case 4:
  16944. segCountX2 = data.readUInt16();
  16945. segCount = segCountX2 / 2;
  16946. data.pos += 6;
  16947. endCode = function () {
  16948. var _j, _results;
  16949. _results = [];
  16950. for (i = _j = 0; 0 <= segCount ? _j < segCount : _j > segCount; i = 0 <= segCount ? ++_j : --_j) {
  16951. _results.push(data.readUInt16());
  16952. }
  16953. return _results;
  16954. }();
  16955. data.pos += 2;
  16956. startCode = function () {
  16957. var _j, _results;
  16958. _results = [];
  16959. for (i = _j = 0; 0 <= segCount ? _j < segCount : _j > segCount; i = 0 <= segCount ? ++_j : --_j) {
  16960. _results.push(data.readUInt16());
  16961. }
  16962. return _results;
  16963. }();
  16964. idDelta = function () {
  16965. var _j, _results;
  16966. _results = [];
  16967. for (i = _j = 0; 0 <= segCount ? _j < segCount : _j > segCount; i = 0 <= segCount ? ++_j : --_j) {
  16968. _results.push(data.readUInt16());
  16969. }
  16970. return _results;
  16971. }();
  16972. idRangeOffset = function () {
  16973. var _j, _results;
  16974. _results = [];
  16975. for (i = _j = 0; 0 <= segCount ? _j < segCount : _j > segCount; i = 0 <= segCount ? ++_j : --_j) {
  16976. _results.push(data.readUInt16());
  16977. }
  16978. return _results;
  16979. }();
  16980. count = (this.length - data.pos + this.offset) / 2;
  16981. glyphIds = function () {
  16982. var _j, _results;
  16983. _results = [];
  16984. for (i = _j = 0; 0 <= count ? _j < count : _j > count; i = 0 <= count ? ++_j : --_j) {
  16985. _results.push(data.readUInt16());
  16986. }
  16987. return _results;
  16988. }();
  16989. for (i = _j = 0, _len = endCode.length; _j < _len; i = ++_j) {
  16990. tail = endCode[i];
  16991. start = startCode[i];
  16992. for (code = _k = start; start <= tail ? _k <= tail : _k >= tail; code = start <= tail ? ++_k : --_k) {
  16993. if (idRangeOffset[i] === 0) {
  16994. glyphId = code + idDelta[i];
  16995. } else {
  16996. index = idRangeOffset[i] / 2 + (code - start) - (segCount - i);
  16997. glyphId = glyphIds[index] || 0;
  16998. if (glyphId !== 0) {
  16999. glyphId += idDelta[i];
  17000. }
  17001. }
  17002. this.codeMap[code] = glyphId & 0xFFFF;
  17003. }
  17004. }
  17005. }
  17006. data.pos = saveOffset;
  17007. }
  17008. CmapEntry.encode = function (charmap, encoding) {
  17009. var charMap, code, codeMap, codes, delta, deltas, diff, endCode, endCodes, entrySelector, glyphIDs, i, id, indexes, last, map, nextID, offset, old, rangeOffsets, rangeShift, result, searchRange, segCount, segCountX2, startCode, startCodes, startGlyph, subtable, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _len5, _len6, _len7, _m, _n, _name, _o, _p, _q;
  17010. subtable = new Data();
  17011. codes = Object.keys(charmap).sort(function (a, b) {
  17012. return a - b;
  17013. });
  17014. switch (encoding) {
  17015. case 'macroman':
  17016. id = 0;
  17017. indexes = function () {
  17018. var _i, _results;
  17019. _results = [];
  17020. for (i = _i = 0; _i < 256; i = ++_i) {
  17021. _results.push(0);
  17022. }
  17023. return _results;
  17024. }();
  17025. map = {
  17026. 0: 0
  17027. };
  17028. codeMap = {};
  17029. for (_i = 0, _len = codes.length; _i < _len; _i++) {
  17030. code = codes[_i];
  17031. if (map[_name = charmap[code]] == null) {
  17032. map[_name] = ++id;
  17033. }
  17034. codeMap[code] = {
  17035. old: charmap[code],
  17036. "new": map[charmap[code]]
  17037. };
  17038. indexes[code] = map[charmap[code]];
  17039. }
  17040. subtable.writeUInt16(1);
  17041. subtable.writeUInt16(0);
  17042. subtable.writeUInt32(12);
  17043. subtable.writeUInt16(0);
  17044. subtable.writeUInt16(262);
  17045. subtable.writeUInt16(0);
  17046. subtable.write(indexes);
  17047. return result = {
  17048. charMap: codeMap,
  17049. subtable: subtable.data,
  17050. maxGlyphID: id + 1
  17051. };
  17052. case 'unicode':
  17053. startCodes = [];
  17054. endCodes = [];
  17055. nextID = 0;
  17056. map = {};
  17057. charMap = {};
  17058. last = diff = null;
  17059. for (_j = 0, _len1 = codes.length; _j < _len1; _j++) {
  17060. code = codes[_j];
  17061. old = charmap[code];
  17062. if (map[old] == null) {
  17063. map[old] = ++nextID;
  17064. }
  17065. charMap[code] = {
  17066. old: old,
  17067. "new": map[old]
  17068. };
  17069. delta = map[old] - code;
  17070. if (last == null || delta !== diff) {
  17071. if (last) {
  17072. endCodes.push(last);
  17073. }
  17074. startCodes.push(code);
  17075. diff = delta;
  17076. }
  17077. last = code;
  17078. }
  17079. if (last) {
  17080. endCodes.push(last);
  17081. }
  17082. endCodes.push(0xFFFF);
  17083. startCodes.push(0xFFFF);
  17084. segCount = startCodes.length;
  17085. segCountX2 = segCount * 2;
  17086. searchRange = 2 * Math.pow(Math.log(segCount) / Math.LN2, 2);
  17087. entrySelector = Math.log(searchRange / 2) / Math.LN2;
  17088. rangeShift = 2 * segCount - searchRange;
  17089. deltas = [];
  17090. rangeOffsets = [];
  17091. glyphIDs = [];
  17092. for (i = _k = 0, _len2 = startCodes.length; _k < _len2; i = ++_k) {
  17093. startCode = startCodes[i];
  17094. endCode = endCodes[i];
  17095. if (startCode === 0xFFFF) {
  17096. deltas.push(0);
  17097. rangeOffsets.push(0);
  17098. break;
  17099. }
  17100. startGlyph = charMap[startCode]["new"];
  17101. if (startCode - startGlyph >= 0x8000) {
  17102. deltas.push(0);
  17103. rangeOffsets.push(2 * (glyphIDs.length + segCount - i));
  17104. for (code = _l = startCode; startCode <= endCode ? _l <= endCode : _l >= endCode; code = startCode <= endCode ? ++_l : --_l) {
  17105. glyphIDs.push(charMap[code]["new"]);
  17106. }
  17107. } else {
  17108. deltas.push(startGlyph - startCode);
  17109. rangeOffsets.push(0);
  17110. }
  17111. }
  17112. subtable.writeUInt16(3);
  17113. subtable.writeUInt16(1);
  17114. subtable.writeUInt32(12);
  17115. subtable.writeUInt16(4);
  17116. subtable.writeUInt16(16 + segCount * 8 + glyphIDs.length * 2);
  17117. subtable.writeUInt16(0);
  17118. subtable.writeUInt16(segCountX2);
  17119. subtable.writeUInt16(searchRange);
  17120. subtable.writeUInt16(entrySelector);
  17121. subtable.writeUInt16(rangeShift);
  17122. for (_m = 0, _len3 = endCodes.length; _m < _len3; _m++) {
  17123. code = endCodes[_m];
  17124. subtable.writeUInt16(code);
  17125. }
  17126. subtable.writeUInt16(0);
  17127. for (_n = 0, _len4 = startCodes.length; _n < _len4; _n++) {
  17128. code = startCodes[_n];
  17129. subtable.writeUInt16(code);
  17130. }
  17131. for (_o = 0, _len5 = deltas.length; _o < _len5; _o++) {
  17132. delta = deltas[_o];
  17133. subtable.writeUInt16(delta);
  17134. }
  17135. for (_p = 0, _len6 = rangeOffsets.length; _p < _len6; _p++) {
  17136. offset = rangeOffsets[_p];
  17137. subtable.writeUInt16(offset);
  17138. }
  17139. for (_q = 0, _len7 = glyphIDs.length; _q < _len7; _q++) {
  17140. id = glyphIDs[_q];
  17141. subtable.writeUInt16(id);
  17142. }
  17143. return result = {
  17144. charMap: charMap,
  17145. subtable: subtable.data,
  17146. maxGlyphID: nextID + 1
  17147. };
  17148. }
  17149. };
  17150. return CmapEntry;
  17151. }();
  17152. var CmapTable = function (_super) {
  17153. __extends(CmapTable, _super);
  17154. function CmapTable() {
  17155. return CmapTable.__super__.constructor.apply(this, arguments);
  17156. }
  17157. CmapTable.prototype.tag = 'cmap';
  17158. CmapTable.prototype.parse = function (data) {
  17159. var entry, i, tableCount, _i;
  17160. data.pos = this.offset;
  17161. this.version = data.readUInt16();
  17162. tableCount = data.readUInt16();
  17163. this.tables = [];
  17164. this.unicode = null;
  17165. for (i = _i = 0; 0 <= tableCount ? _i < tableCount : _i > tableCount; i = 0 <= tableCount ? ++_i : --_i) {
  17166. entry = new CmapEntry(data, this.offset);
  17167. this.tables.push(entry);
  17168. if (entry.isUnicode) {
  17169. if (this.unicode == null) {
  17170. this.unicode = entry;
  17171. }
  17172. }
  17173. }
  17174. return true;
  17175. };
  17176. /*************************************************************************/
  17177. /* function : encode */
  17178. /* comment : Encode the cmap table corresponding to the input character. */
  17179. /*************************************************************************/
  17180. CmapTable.encode = function (charmap, encoding) {
  17181. var result, table;
  17182. if (encoding == null) {
  17183. encoding = 'macroman';
  17184. }
  17185. result = CmapEntry.encode(charmap, encoding);
  17186. table = new Data();
  17187. table.writeUInt16(0);
  17188. table.writeUInt16(1);
  17189. result.table = table.data.concat(result.subtable);
  17190. return result;
  17191. };
  17192. return CmapTable;
  17193. }(Table);
  17194. var HheaTable = function (_super) {
  17195. __extends(HheaTable, _super);
  17196. function HheaTable() {
  17197. return HheaTable.__super__.constructor.apply(this, arguments);
  17198. }
  17199. HheaTable.prototype.tag = 'hhea';
  17200. HheaTable.prototype.parse = function (data) {
  17201. data.pos = this.offset;
  17202. this.version = data.readInt();
  17203. this.ascender = data.readShort();
  17204. this.decender = data.readShort();
  17205. this.lineGap = data.readShort();
  17206. this.advanceWidthMax = data.readShort();
  17207. this.minLeftSideBearing = data.readShort();
  17208. this.minRightSideBearing = data.readShort();
  17209. this.xMaxExtent = data.readShort();
  17210. this.caretSlopeRise = data.readShort();
  17211. this.caretSlopeRun = data.readShort();
  17212. this.caretOffset = data.readShort();
  17213. data.pos += 4 * 2;
  17214. this.metricDataFormat = data.readShort();
  17215. return this.numberOfMetrics = data.readUInt16();
  17216. };
  17217. /*HheaTable.prototype.encode = function (ids) {
  17218. var i, table, _i, _ref;
  17219. table = new Data;
  17220. table.writeInt(this.version);
  17221. table.writeShort(this.ascender);
  17222. table.writeShort(this.decender);
  17223. table.writeShort(this.lineGap);
  17224. table.writeShort(this.advanceWidthMax);
  17225. table.writeShort(this.minLeftSideBearing);
  17226. table.writeShort(this.minRightSideBearing);
  17227. table.writeShort(this.xMaxExtent);
  17228. table.writeShort(this.caretSlopeRise);
  17229. table.writeShort(this.caretSlopeRun);
  17230. table.writeShort(this.caretOffset);
  17231. for (i = _i = 0, _ref = 4 * 2; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  17232. table.writeByte(0);
  17233. }
  17234. table.writeShort(this.metricDataFormat);
  17235. table.writeUInt16(ids.length);
  17236. return table.data;
  17237. };*/
  17238. return HheaTable;
  17239. }(Table);
  17240. var OS2Table = function (_super) {
  17241. __extends(OS2Table, _super);
  17242. function OS2Table() {
  17243. return OS2Table.__super__.constructor.apply(this, arguments);
  17244. }
  17245. OS2Table.prototype.tag = 'OS/2';
  17246. OS2Table.prototype.parse = function (data) {
  17247. var i;
  17248. data.pos = this.offset;
  17249. this.version = data.readUInt16();
  17250. this.averageCharWidth = data.readShort();
  17251. this.weightClass = data.readUInt16();
  17252. this.widthClass = data.readUInt16();
  17253. this.type = data.readShort();
  17254. this.ySubscriptXSize = data.readShort();
  17255. this.ySubscriptYSize = data.readShort();
  17256. this.ySubscriptXOffset = data.readShort();
  17257. this.ySubscriptYOffset = data.readShort();
  17258. this.ySuperscriptXSize = data.readShort();
  17259. this.ySuperscriptYSize = data.readShort();
  17260. this.ySuperscriptXOffset = data.readShort();
  17261. this.ySuperscriptYOffset = data.readShort();
  17262. this.yStrikeoutSize = data.readShort();
  17263. this.yStrikeoutPosition = data.readShort();
  17264. this.familyClass = data.readShort();
  17265. this.panose = function () {
  17266. var _i, _results;
  17267. _results = [];
  17268. for (i = _i = 0; _i < 10; i = ++_i) {
  17269. _results.push(data.readByte());
  17270. }
  17271. return _results;
  17272. }();
  17273. this.charRange = function () {
  17274. var _i, _results;
  17275. _results = [];
  17276. for (i = _i = 0; _i < 4; i = ++_i) {
  17277. _results.push(data.readInt());
  17278. }
  17279. return _results;
  17280. }();
  17281. this.vendorID = data.readString(4);
  17282. this.selection = data.readShort();
  17283. this.firstCharIndex = data.readShort();
  17284. this.lastCharIndex = data.readShort();
  17285. if (this.version > 0) {
  17286. this.ascent = data.readShort();
  17287. this.descent = data.readShort();
  17288. this.lineGap = data.readShort();
  17289. this.winAscent = data.readShort();
  17290. this.winDescent = data.readShort();
  17291. this.codePageRange = function () {
  17292. var _i, _results;
  17293. _results = [];
  17294. for (i = _i = 0; _i < 2; i = ++_i) {
  17295. _results.push(data.readInt());
  17296. }
  17297. return _results;
  17298. }();
  17299. if (this.version > 1) {
  17300. this.xHeight = data.readShort();
  17301. this.capHeight = data.readShort();
  17302. this.defaultChar = data.readShort();
  17303. this.breakChar = data.readShort();
  17304. return this.maxContext = data.readShort();
  17305. }
  17306. }
  17307. };
  17308. /*OS2Table.prototype.encode = function () {
  17309. return this.raw();
  17310. };*/
  17311. return OS2Table;
  17312. }(Table);
  17313. var PostTable = function (_super) {
  17314. __extends(PostTable, _super);
  17315. function PostTable() {
  17316. return PostTable.__super__.constructor.apply(this, arguments);
  17317. }
  17318. PostTable.prototype.tag = 'post';
  17319. PostTable.prototype.parse = function (data) {
  17320. var i, length, numberOfGlyphs, _i, _results;
  17321. data.pos = this.offset;
  17322. this.format = data.readInt();
  17323. this.italicAngle = data.readInt();
  17324. this.underlinePosition = data.readShort();
  17325. this.underlineThickness = data.readShort();
  17326. this.isFixedPitch = data.readInt();
  17327. this.minMemType42 = data.readInt();
  17328. this.maxMemType42 = data.readInt();
  17329. this.minMemType1 = data.readInt();
  17330. this.maxMemType1 = data.readInt();
  17331. switch (this.format) {
  17332. case 0x00010000:
  17333. break;
  17334. case 0x00020000:
  17335. numberOfGlyphs = data.readUInt16();
  17336. this.glyphNameIndex = [];
  17337. for (i = _i = 0; 0 <= numberOfGlyphs ? _i < numberOfGlyphs : _i > numberOfGlyphs; i = 0 <= numberOfGlyphs ? ++_i : --_i) {
  17338. this.glyphNameIndex.push(data.readUInt16());
  17339. }
  17340. this.names = [];
  17341. _results = [];
  17342. while (data.pos < this.offset + this.length) {
  17343. length = data.readByte();
  17344. _results.push(this.names.push(data.readString(length)));
  17345. }
  17346. return _results;
  17347. break;
  17348. case 0x00025000:
  17349. numberOfGlyphs = data.readUInt16();
  17350. return this.offsets = data.read(numberOfGlyphs);
  17351. case 0x00030000:
  17352. break;
  17353. case 0x00040000:
  17354. return this.map = function () {
  17355. var _j, _ref, _results1;
  17356. _results1 = [];
  17357. for (i = _j = 0, _ref = this.file.maxp.numGlyphs; 0 <= _ref ? _j < _ref : _j > _ref; i = 0 <= _ref ? ++_j : --_j) {
  17358. _results1.push(data.readUInt32());
  17359. }
  17360. return _results1;
  17361. }.call(this);
  17362. }
  17363. };
  17364. return PostTable;
  17365. }(Table);
  17366. /*********************************************************************************************************/
  17367. /* function : NameEntry */
  17368. /* comment : Store copyright information, platformID, encodingID, and languageID in the NameEntry object.*/
  17369. /*********************************************************************************************************/
  17370. var NameEntry = function () {
  17371. function NameEntry(raw, entry) {
  17372. this.raw = raw;
  17373. this.length = raw.length;
  17374. this.platformID = entry.platformID;
  17375. this.encodingID = entry.encodingID;
  17376. this.languageID = entry.languageID;
  17377. }
  17378. return NameEntry;
  17379. }();
  17380. var NameTable = function (_super) {
  17381. __extends(NameTable, _super);
  17382. function NameTable() {
  17383. return NameTable.__super__.constructor.apply(this, arguments);
  17384. }
  17385. NameTable.prototype.tag = 'name';
  17386. NameTable.prototype.parse = function (data) {
  17387. var count, entries, entry, format, i, name, stringOffset, strings, text, _i, _j, _len, _name;
  17388. data.pos = this.offset;
  17389. format = data.readShort();
  17390. count = data.readShort();
  17391. stringOffset = data.readShort();
  17392. entries = [];
  17393. for (i = _i = 0; 0 <= count ? _i < count : _i > count; i = 0 <= count ? ++_i : --_i) {
  17394. entries.push({
  17395. platformID: data.readShort(),
  17396. encodingID: data.readShort(),
  17397. languageID: data.readShort(),
  17398. nameID: data.readShort(),
  17399. length: data.readShort(),
  17400. offset: this.offset + stringOffset + data.readShort()
  17401. });
  17402. }
  17403. strings = {};
  17404. for (i = _j = 0, _len = entries.length; _j < _len; i = ++_j) {
  17405. entry = entries[i];
  17406. data.pos = entry.offset;
  17407. text = data.readString(entry.length);
  17408. name = new NameEntry(text, entry);
  17409. if (strings[_name = entry.nameID] == null) {
  17410. strings[_name] = [];
  17411. }
  17412. strings[entry.nameID].push(name);
  17413. }
  17414. this.strings = strings;
  17415. this.copyright = strings[0];
  17416. this.fontFamily = strings[1];
  17417. this.fontSubfamily = strings[2];
  17418. this.uniqueSubfamily = strings[3];
  17419. this.fontName = strings[4];
  17420. this.version = strings[5];
  17421. try {
  17422. this.postscriptName = strings[6][0].raw.replace(/[\x00-\x19\x80-\xff]/g, "");
  17423. } catch (e) {
  17424. this.postscriptName = strings[4][0].raw.replace(/[\x00-\x19\x80-\xff]/g, "");
  17425. }
  17426. this.trademark = strings[7];
  17427. this.manufacturer = strings[8];
  17428. this.designer = strings[9];
  17429. this.description = strings[10];
  17430. this.vendorUrl = strings[11];
  17431. this.designerUrl = strings[12];
  17432. this.license = strings[13];
  17433. this.licenseUrl = strings[14];
  17434. this.preferredFamily = strings[15];
  17435. this.preferredSubfamily = strings[17];
  17436. this.compatibleFull = strings[18];
  17437. return this.sampleText = strings[19];
  17438. };
  17439. /*NameTable.prototype.encode = function () {
  17440. var id, list, nameID, nameTable, postscriptName, strCount, strTable, string, strings, table, val, _i, _len, _ref;
  17441. strings = {};
  17442. _ref = this.strings;
  17443. for (id in _ref) {
  17444. val = _ref[id];
  17445. strings[id] = val;
  17446. }
  17447. postscriptName = new NameEntry("" + subsetTag + "+" + this.postscriptName, {
  17448. platformID: 1
  17449. , encodingID: 0
  17450. , languageID: 0
  17451. });
  17452. strings[6] = [postscriptName];
  17453. subsetTag = successorOf(subsetTag);
  17454. strCount = 0;
  17455. for (id in strings) {
  17456. list = strings[id];
  17457. if (list != null) {
  17458. strCount += list.length;
  17459. }
  17460. }
  17461. table = new Data;
  17462. strTable = new Data;
  17463. table.writeShort(0);
  17464. table.writeShort(strCount);
  17465. table.writeShort(6 + 12 * strCount);
  17466. for (nameID in strings) {
  17467. list = strings[nameID];
  17468. if (list != null) {
  17469. for (_i = 0, _len = list.length; _i < _len; _i++) {
  17470. string = list[_i];
  17471. table.writeShort(string.platformID);
  17472. table.writeShort(string.encodingID);
  17473. table.writeShort(string.languageID);
  17474. table.writeShort(nameID);
  17475. table.writeShort(string.length);
  17476. table.writeShort(strTable.pos);
  17477. strTable.writeString(string.raw);
  17478. }
  17479. }
  17480. }
  17481. return nameTable = {
  17482. postscriptName: postscriptName.raw
  17483. , table: table.data.concat(strTable.data)
  17484. };
  17485. };*/
  17486. return NameTable;
  17487. }(Table);
  17488. var MaxpTable = function (_super) {
  17489. __extends(MaxpTable, _super);
  17490. function MaxpTable() {
  17491. return MaxpTable.__super__.constructor.apply(this, arguments);
  17492. }
  17493. MaxpTable.prototype.tag = 'maxp';
  17494. MaxpTable.prototype.parse = function (data) {
  17495. data.pos = this.offset;
  17496. this.version = data.readInt();
  17497. this.numGlyphs = data.readUInt16();
  17498. this.maxPoints = data.readUInt16();
  17499. this.maxContours = data.readUInt16();
  17500. this.maxCompositePoints = data.readUInt16();
  17501. this.maxComponentContours = data.readUInt16();
  17502. this.maxZones = data.readUInt16();
  17503. this.maxTwilightPoints = data.readUInt16();
  17504. this.maxStorage = data.readUInt16();
  17505. this.maxFunctionDefs = data.readUInt16();
  17506. this.maxInstructionDefs = data.readUInt16();
  17507. this.maxStackElements = data.readUInt16();
  17508. this.maxSizeOfInstructions = data.readUInt16();
  17509. this.maxComponentElements = data.readUInt16();
  17510. return this.maxComponentDepth = data.readUInt16();
  17511. };
  17512. /*MaxpTable.prototype.encode = function (ids) {
  17513. var table;
  17514. table = new Data;
  17515. table.writeInt(this.version);
  17516. table.writeUInt16(ids.length);
  17517. table.writeUInt16(this.maxPoints);
  17518. table.writeUInt16(this.maxContours);
  17519. table.writeUInt16(this.maxCompositePoints);
  17520. table.writeUInt16(this.maxComponentContours);
  17521. table.writeUInt16(this.maxZones);
  17522. table.writeUInt16(this.maxTwilightPoints);
  17523. table.writeUInt16(this.maxStorage);
  17524. table.writeUInt16(this.maxFunctionDefs);
  17525. table.writeUInt16(this.maxInstructionDefs);
  17526. table.writeUInt16(this.maxStackElements);
  17527. table.writeUInt16(this.maxSizeOfInstructions);
  17528. table.writeUInt16(this.maxComponentElements);
  17529. table.writeUInt16(this.maxComponentDepth);
  17530. return table.data;
  17531. };*/
  17532. return MaxpTable;
  17533. }(Table);
  17534. var HmtxTable = function (_super) {
  17535. __extends(HmtxTable, _super);
  17536. function HmtxTable() {
  17537. return HmtxTable.__super__.constructor.apply(this, arguments);
  17538. }
  17539. HmtxTable.prototype.tag = 'hmtx';
  17540. HmtxTable.prototype.parse = function (data) {
  17541. var i, last, lsbCount, m, _i, _j, _ref, _results;
  17542. data.pos = this.offset;
  17543. this.metrics = [];
  17544. for (i = _i = 0, _ref = this.file.hhea.numberOfMetrics; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  17545. this.metrics.push({
  17546. advance: data.readUInt16(),
  17547. lsb: data.readInt16()
  17548. });
  17549. }
  17550. lsbCount = this.file.maxp.numGlyphs - this.file.hhea.numberOfMetrics;
  17551. this.leftSideBearings = function () {
  17552. var _j, _results;
  17553. _results = [];
  17554. for (i = _j = 0; 0 <= lsbCount ? _j < lsbCount : _j > lsbCount; i = 0 <= lsbCount ? ++_j : --_j) {
  17555. _results.push(data.readInt16());
  17556. }
  17557. return _results;
  17558. }();
  17559. this.widths = function () {
  17560. var _j, _len, _ref1, _results;
  17561. _ref1 = this.metrics;
  17562. _results = [];
  17563. for (_j = 0, _len = _ref1.length; _j < _len; _j++) {
  17564. m = _ref1[_j];
  17565. _results.push(m.advance);
  17566. }
  17567. return _results;
  17568. }.call(this);
  17569. last = this.widths[this.widths.length - 1];
  17570. _results = [];
  17571. for (i = _j = 0; 0 <= lsbCount ? _j < lsbCount : _j > lsbCount; i = 0 <= lsbCount ? ++_j : --_j) {
  17572. _results.push(this.widths.push(last));
  17573. }
  17574. return _results;
  17575. };
  17576. /***************************************************************/
  17577. /* function : forGlyph */
  17578. /* comment : Returns the advance width and lsb for this glyph. */
  17579. /***************************************************************/
  17580. HmtxTable.prototype.forGlyph = function (id) {
  17581. var metrics;
  17582. if (id in this.metrics) {
  17583. return this.metrics[id];
  17584. }
  17585. return metrics = {
  17586. advance: this.metrics[this.metrics.length - 1].advance,
  17587. lsb: this.leftSideBearings[id - this.metrics.length]
  17588. };
  17589. };
  17590. /*HmtxTable.prototype.encode = function (mapping) {
  17591. var id, metric, table, _i, _len;
  17592. table = new Data;
  17593. for (_i = 0, _len = mapping.length; _i < _len; _i++) {
  17594. id = mapping[_i];
  17595. metric = this.forGlyph(id);
  17596. table.writeUInt16(metric.advance);
  17597. table.writeUInt16(metric.lsb);
  17598. }
  17599. return table.data;
  17600. };*/
  17601. return HmtxTable;
  17602. }(Table);
  17603. var __slice = [].slice;
  17604. var GlyfTable = function (_super) {
  17605. __extends(GlyfTable, _super);
  17606. function GlyfTable() {
  17607. return GlyfTable.__super__.constructor.apply(this, arguments);
  17608. }
  17609. GlyfTable.prototype.tag = 'glyf';
  17610. GlyfTable.prototype.parse = function (data) {
  17611. return this.cache = {};
  17612. };
  17613. GlyfTable.prototype.glyphFor = function (id) {
  17614. id = id;
  17615. var data, index, length, loca, numberOfContours, raw, xMax, xMin, yMax, yMin;
  17616. if (id in this.cache) {
  17617. return this.cache[id];
  17618. }
  17619. loca = this.file.loca;
  17620. data = this.file.contents;
  17621. index = loca.indexOf(id);
  17622. length = loca.lengthOf(id);
  17623. if (length === 0) {
  17624. return this.cache[id] = null;
  17625. }
  17626. data.pos = this.offset + index;
  17627. raw = new Data(data.read(length));
  17628. numberOfContours = raw.readShort();
  17629. xMin = raw.readShort();
  17630. yMin = raw.readShort();
  17631. xMax = raw.readShort();
  17632. yMax = raw.readShort();
  17633. if (numberOfContours === -1) {
  17634. this.cache[id] = new CompoundGlyph(raw, xMin, yMin, xMax, yMax);
  17635. } else {
  17636. this.cache[id] = new SimpleGlyph(raw, numberOfContours, xMin, yMin, xMax, yMax);
  17637. }
  17638. return this.cache[id];
  17639. };
  17640. GlyfTable.prototype.encode = function (glyphs, mapping, old2new) {
  17641. var glyph, id, offsets, table, _i, _len;
  17642. table = [];
  17643. offsets = [];
  17644. for (_i = 0, _len = mapping.length; _i < _len; _i++) {
  17645. id = mapping[_i];
  17646. glyph = glyphs[id];
  17647. offsets.push(table.length);
  17648. if (glyph) {
  17649. table = table.concat(glyph.encode(old2new));
  17650. }
  17651. }
  17652. offsets.push(table.length);
  17653. return {
  17654. table: table,
  17655. offsets: offsets
  17656. };
  17657. };
  17658. return GlyfTable;
  17659. }(Table);
  17660. var SimpleGlyph = function () {
  17661. /**************************************************************************/
  17662. /* function : SimpleGlyph */
  17663. /* comment : Stores raw, xMin, yMin, xMax, and yMax values for this glyph.*/
  17664. /**************************************************************************/
  17665. function SimpleGlyph(raw, numberOfContours, xMin, yMin, xMax, yMax) {
  17666. this.raw = raw;
  17667. this.numberOfContours = numberOfContours;
  17668. this.xMin = xMin;
  17669. this.yMin = yMin;
  17670. this.xMax = xMax;
  17671. this.yMax = yMax;
  17672. this.compound = false;
  17673. }
  17674. SimpleGlyph.prototype.encode = function () {
  17675. return this.raw.data;
  17676. };
  17677. return SimpleGlyph;
  17678. }();
  17679. var CompoundGlyph = function () {
  17680. var ARG_1_AND_2_ARE_WORDS, MORE_COMPONENTS, WE_HAVE_AN_X_AND_Y_SCALE, WE_HAVE_A_SCALE, WE_HAVE_A_TWO_BY_TWO;
  17681. ARG_1_AND_2_ARE_WORDS = 0x0001;
  17682. WE_HAVE_A_SCALE = 0x0008;
  17683. MORE_COMPONENTS = 0x0020;
  17684. WE_HAVE_AN_X_AND_Y_SCALE = 0x0040;
  17685. WE_HAVE_A_TWO_BY_TWO = 0x0080;
  17686. /********************************************************************************************************************/
  17687. /* function : CompoundGlypg generator */
  17688. /* comment : It stores raw, xMin, yMin, xMax, yMax, glyph id, and glyph offset for the corresponding compound glyph.*/
  17689. /********************************************************************************************************************/
  17690. function CompoundGlyph(raw, xMin, yMin, xMax, yMax) {
  17691. var data, flags;
  17692. this.raw = raw;
  17693. this.xMin = xMin;
  17694. this.yMin = yMin;
  17695. this.xMax = xMax;
  17696. this.yMax = yMax;
  17697. this.compound = true;
  17698. this.glyphIDs = [];
  17699. this.glyphOffsets = [];
  17700. data = this.raw;
  17701. while (true) {
  17702. flags = data.readShort();
  17703. this.glyphOffsets.push(data.pos);
  17704. this.glyphIDs.push(data.readShort());
  17705. if (!(flags & MORE_COMPONENTS)) {
  17706. break;
  17707. }
  17708. if (flags & ARG_1_AND_2_ARE_WORDS) {
  17709. data.pos += 4;
  17710. } else {
  17711. data.pos += 2;
  17712. }
  17713. if (flags & WE_HAVE_A_TWO_BY_TWO) {
  17714. data.pos += 8;
  17715. } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) {
  17716. data.pos += 4;
  17717. } else if (flags & WE_HAVE_A_SCALE) {
  17718. data.pos += 2;
  17719. }
  17720. }
  17721. }
  17722. /****************************************************************************************************************/
  17723. /* function : CompoundGlypg encode */
  17724. /* comment : After creating a table for the characters you typed, you call directory.encode to encode the table.*/
  17725. /****************************************************************************************************************/
  17726. CompoundGlyph.prototype.encode = function (mapping) {
  17727. var i, id, result, _i, _len, _ref;
  17728. result = new Data(__slice.call(this.raw.data));
  17729. _ref = this.glyphIDs;
  17730. for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
  17731. id = _ref[i];
  17732. result.pos = this.glyphOffsets[i];
  17733. }
  17734. return result.data;
  17735. };
  17736. return CompoundGlyph;
  17737. }();
  17738. var LocaTable = function (_super) {
  17739. __extends(LocaTable, _super);
  17740. function LocaTable() {
  17741. return LocaTable.__super__.constructor.apply(this, arguments);
  17742. }
  17743. LocaTable.prototype.tag = 'loca';
  17744. LocaTable.prototype.parse = function (data) {
  17745. var format, i;
  17746. data.pos = this.offset;
  17747. format = this.file.head.indexToLocFormat;
  17748. if (format === 0) {
  17749. return this.offsets = function () {
  17750. var _i, _ref, _results;
  17751. _results = [];
  17752. for (i = _i = 0, _ref = this.length; _i < _ref; i = _i += 2) {
  17753. _results.push(data.readUInt16() * 2);
  17754. }
  17755. return _results;
  17756. }.call(this);
  17757. } else {
  17758. return this.offsets = function () {
  17759. var _i, _ref, _results;
  17760. _results = [];
  17761. for (i = _i = 0, _ref = this.length; _i < _ref; i = _i += 4) {
  17762. _results.push(data.readUInt32());
  17763. }
  17764. return _results;
  17765. }.call(this);
  17766. }
  17767. };
  17768. LocaTable.prototype.indexOf = function (id) {
  17769. return this.offsets[id];
  17770. };
  17771. LocaTable.prototype.lengthOf = function (id) {
  17772. return this.offsets[id + 1] - this.offsets[id];
  17773. };
  17774. LocaTable.prototype.encode = function (offsets, activeGlyphs) {
  17775. var LocaTable = new Uint32Array(this.offsets.length);
  17776. var glyfPtr = 0;
  17777. var listGlyf = 0;
  17778. for (var k = 0; k < LocaTable.length; ++k) {
  17779. LocaTable[k] = glyfPtr;
  17780. if (listGlyf < activeGlyphs.length && activeGlyphs[listGlyf] == k) {
  17781. ++listGlyf;
  17782. LocaTable[k] = glyfPtr;
  17783. var start = this.offsets[k];
  17784. var len = this.offsets[k + 1] - start;
  17785. if (len > 0) {
  17786. glyfPtr += len;
  17787. }
  17788. }
  17789. }
  17790. var newLocaTable = new Array(LocaTable.length * 4);
  17791. for (var j = 0; j < LocaTable.length; ++j) {
  17792. newLocaTable[4 * j + 3] = LocaTable[j] & 0x000000ff;
  17793. newLocaTable[4 * j + 2] = (LocaTable[j] & 0x0000ff00) >> 8;
  17794. newLocaTable[4 * j + 1] = (LocaTable[j] & 0x00ff0000) >> 16;
  17795. newLocaTable[4 * j] = (LocaTable[j] & 0xff000000) >> 24;
  17796. }
  17797. return newLocaTable;
  17798. };
  17799. return LocaTable;
  17800. }(Table);
  17801. /************************************************************************************/
  17802. /* function : invert */
  17803. /* comment : Change the object's (key: value) to create an object with (value: key).*/
  17804. /************************************************************************************/
  17805. var invert = function invert(object) {
  17806. var key, ret, val;
  17807. ret = {};
  17808. for (key in object) {
  17809. val = object[key];
  17810. ret[val] = key;
  17811. }
  17812. return ret;
  17813. };
  17814. /*var successorOf = function (input) {
  17815. var added, alphabet, carry, i, index, isUpperCase, last, length, next, result;
  17816. alphabet = 'abcdefghijklmnopqrstuvwxyz';
  17817. length = alphabet.length;
  17818. result = input;
  17819. i = input.length;
  17820. while (i >= 0) {
  17821. last = input.charAt(--i);
  17822. if (isNaN(last)) {
  17823. index = alphabet.indexOf(last.toLowerCase());
  17824. if (index === -1) {
  17825. next = last;
  17826. carry = true;
  17827. }
  17828. else {
  17829. next = alphabet.charAt((index + 1) % length);
  17830. isUpperCase = last === last.toUpperCase();
  17831. if (isUpperCase) {
  17832. next = next.toUpperCase();
  17833. }
  17834. carry = index + 1 >= length;
  17835. if (carry && i === 0) {
  17836. added = isUpperCase ? 'A' : 'a';
  17837. result = added + next + result.slice(1);
  17838. break;
  17839. }
  17840. }
  17841. }
  17842. else {
  17843. next = +last + 1;
  17844. carry = next > 9;
  17845. if (carry) {
  17846. next = 0;
  17847. }
  17848. if (carry && i === 0) {
  17849. result = '1' + next + result.slice(1);
  17850. break;
  17851. }
  17852. }
  17853. result = result.slice(0, i) + next + result.slice(i + 1);
  17854. if (!carry) {
  17855. break;
  17856. }
  17857. }
  17858. return result;
  17859. };*/
  17860. var Subset = function () {
  17861. function Subset(font) {
  17862. this.font = font;
  17863. this.subset = {};
  17864. this.unicodes = {};
  17865. this.next = 33;
  17866. }
  17867. /*Subset.prototype.use = function (character) {
  17868. var i, _i, _ref;
  17869. if (typeof character === 'string') {
  17870. for (i = _i = 0, _ref = character.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  17871. this.use(character.charCodeAt(i));
  17872. }
  17873. return;
  17874. }
  17875. if (!this.unicodes[character]) {
  17876. this.subset[this.next] = character;
  17877. return this.unicodes[character] = this.next++;
  17878. }
  17879. };*/
  17880. /*Subset.prototype.encodeText = function (text) {
  17881. var char, i, string, _i, _ref;
  17882. string = '';
  17883. for (i = _i = 0, _ref = text.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
  17884. char = this.unicodes[text.charCodeAt(i)];
  17885. string += String.fromCharCode(char);
  17886. }
  17887. return string;
  17888. };*/
  17889. /***************************************************************/
  17890. /* function : generateCmap */
  17891. /* comment : Returns the unicode cmap for this font. */
  17892. /***************************************************************/
  17893. Subset.prototype.generateCmap = function () {
  17894. var mapping, roman, unicode, unicodeCmap, _ref;
  17895. unicodeCmap = this.font.cmap.tables[0].codeMap;
  17896. mapping = {};
  17897. _ref = this.subset;
  17898. for (roman in _ref) {
  17899. unicode = _ref[roman];
  17900. mapping[roman] = unicodeCmap[unicode];
  17901. }
  17902. return mapping;
  17903. };
  17904. /*Subset.prototype.glyphIDs = function () {
  17905. var ret, roman, unicode, unicodeCmap, val, _ref;
  17906. unicodeCmap = this.font.cmap.tables[0].codeMap;
  17907. ret = [0];
  17908. _ref = this.subset;
  17909. for (roman in _ref) {
  17910. unicode = _ref[roman];
  17911. val = unicodeCmap[unicode];
  17912. if ((val != null) && __indexOf.call(ret, val) < 0) {
  17913. ret.push(val);
  17914. }
  17915. }
  17916. return ret.sort();
  17917. };*/
  17918. /******************************************************************/
  17919. /* function : glyphsFor */
  17920. /* comment : Returns simple glyph objects for the input character.*/
  17921. /******************************************************************/
  17922. Subset.prototype.glyphsFor = function (glyphIDs) {
  17923. var additionalIDs, glyph, glyphs, id, _i, _len, _ref;
  17924. glyphs = {};
  17925. for (_i = 0, _len = glyphIDs.length; _i < _len; _i++) {
  17926. id = glyphIDs[_i];
  17927. glyphs[id] = this.font.glyf.glyphFor(id);
  17928. }
  17929. additionalIDs = [];
  17930. for (id in glyphs) {
  17931. glyph = glyphs[id];
  17932. if (glyph != null ? glyph.compound : void 0) {
  17933. additionalIDs.push.apply(additionalIDs, glyph.glyphIDs);
  17934. }
  17935. }
  17936. if (additionalIDs.length > 0) {
  17937. _ref = this.glyphsFor(additionalIDs);
  17938. for (id in _ref) {
  17939. glyph = _ref[id];
  17940. glyphs[id] = glyph;
  17941. }
  17942. }
  17943. return glyphs;
  17944. };
  17945. /***************************************************************/
  17946. /* function : encode */
  17947. /* comment : Encode various tables for the characters you use. */
  17948. /***************************************************************/
  17949. Subset.prototype.encode = function (glyID, indexToLocFormat) {
  17950. var cmap, code, glyf, glyphs, id, ids, loca, new2old, newIDs, nextGlyphID, old2new, oldID, oldIDs, tables, _ref;
  17951. cmap = CmapTable.encode(this.generateCmap(), 'unicode');
  17952. glyphs = this.glyphsFor(glyID);
  17953. old2new = {
  17954. 0: 0
  17955. };
  17956. _ref = cmap.charMap;
  17957. for (code in _ref) {
  17958. ids = _ref[code];
  17959. old2new[ids.old] = ids["new"];
  17960. }
  17961. nextGlyphID = cmap.maxGlyphID;
  17962. for (oldID in glyphs) {
  17963. if (!(oldID in old2new)) {
  17964. old2new[oldID] = nextGlyphID++;
  17965. }
  17966. }
  17967. new2old = invert(old2new);
  17968. newIDs = Object.keys(new2old).sort(function (a, b) {
  17969. return a - b;
  17970. });
  17971. oldIDs = function () {
  17972. var _i, _len, _results;
  17973. _results = [];
  17974. for (_i = 0, _len = newIDs.length; _i < _len; _i++) {
  17975. id = newIDs[_i];
  17976. _results.push(new2old[id]);
  17977. }
  17978. return _results;
  17979. }();
  17980. glyf = this.font.glyf.encode(glyphs, oldIDs, old2new);
  17981. loca = this.font.loca.encode(glyf.offsets, oldIDs);
  17982. tables = {
  17983. cmap: this.font.cmap.raw(),
  17984. glyf: glyf.table,
  17985. loca: loca,
  17986. hmtx: this.font.hmtx.raw(),
  17987. hhea: this.font.hhea.raw(),
  17988. maxp: this.font.maxp.raw(),
  17989. post: this.font.post.raw(),
  17990. name: this.font.name.raw(),
  17991. head: this.font.head.encode(indexToLocFormat)
  17992. };
  17993. if (this.font.os2.exists) {
  17994. tables['OS/2'] = this.font.os2.raw();
  17995. }
  17996. return this.font.directory.encode(tables);
  17997. };
  17998. return Subset;
  17999. }();
  18000. jsPDF.API.PDFObject = function () {
  18001. var pad;
  18002. function PDFObject() {}
  18003. pad = function pad(str, length) {
  18004. return (Array(length + 1).join('0') + str).slice(-length);
  18005. };
  18006. /*****************************************************************************/
  18007. /* function : convert */
  18008. /* comment :Converts pdf tag's / FontBBox and array values in / W to strings */
  18009. /*****************************************************************************/
  18010. PDFObject.convert = function (object) {
  18011. var e, items, key, out, val;
  18012. if (Array.isArray(object)) {
  18013. items = function () {
  18014. var _i, _len, _results;
  18015. _results = [];
  18016. for (_i = 0, _len = object.length; _i < _len; _i++) {
  18017. e = object[_i];
  18018. _results.push(PDFObject.convert(e));
  18019. }
  18020. return _results;
  18021. }().join(' ');
  18022. return '[' + items + ']';
  18023. } else if (typeof object === 'string') {
  18024. return '/' + object;
  18025. } else if (object != null ? object.isString : void 0) {
  18026. return '(' + object + ')';
  18027. } else if (object instanceof Date) {
  18028. return '(D:' + pad(object.getUTCFullYear(), 4) + pad(object.getUTCMonth(), 2) + pad(object.getUTCDate(), 2) + pad(object.getUTCHours(), 2) + pad(object.getUTCMinutes(), 2) + pad(object.getUTCSeconds(), 2) + 'Z)';
  18029. } else if ({}.toString.call(object) === '[object Object]') {
  18030. out = ['<<'];
  18031. for (key in object) {
  18032. val = object[key];
  18033. out.push('/' + key + ' ' + PDFObject.convert(val));
  18034. }
  18035. out.push('>>');
  18036. return out.join('\n');
  18037. } else {
  18038. return '' + object;
  18039. }
  18040. };
  18041. return PDFObject;
  18042. }();
  18043. })(jsPDF);
  18044. // Generated by CoffeeScript 1.4.0
  18045. /*
  18046. # PNG.js
  18047. # Copyright (c) 2011 Devon Govett
  18048. # MIT LICENSE
  18049. #
  18050. #
  18051. */
  18052. (function (global) {
  18053. var PNG;
  18054. PNG = function () {
  18055. var APNG_BLEND_OP_SOURCE, APNG_DISPOSE_OP_BACKGROUND, APNG_DISPOSE_OP_PREVIOUS, makeImage, scratchCanvas, scratchCtx;
  18056. PNG.load = function (url, canvas, callback) {
  18057. var xhr;
  18058. if (typeof canvas === 'function') {
  18059. callback = canvas;
  18060. }
  18061. xhr = new XMLHttpRequest();
  18062. xhr.open("GET", url, true);
  18063. xhr.responseType = "arraybuffer";
  18064. xhr.onload = function () {
  18065. var data, png;
  18066. data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);
  18067. png = new PNG(data);
  18068. if (typeof (canvas != null ? canvas.getContext : void 0) === 'function') {
  18069. png.render(canvas);
  18070. }
  18071. return typeof callback === "function" ? callback(png) : void 0;
  18072. };
  18073. return xhr.send(null);
  18074. };
  18075. APNG_DISPOSE_OP_BACKGROUND = 1;
  18076. APNG_DISPOSE_OP_PREVIOUS = 2;
  18077. APNG_BLEND_OP_SOURCE = 0;
  18078. function PNG(data) {
  18079. var chunkSize, colors, palLen, delayDen, delayNum, frame, i, index, key, section, palShort, text, _i, _j, _ref;
  18080. this.data = data;
  18081. this.pos = 8;
  18082. this.palette = [];
  18083. this.imgData = [];
  18084. this.transparency = {};
  18085. this.animation = null;
  18086. this.text = {};
  18087. frame = null;
  18088. while (true) {
  18089. chunkSize = this.readUInt32();
  18090. section = function () {
  18091. var _i, _results;
  18092. _results = [];
  18093. for (i = _i = 0; _i < 4; i = ++_i) {
  18094. _results.push(String.fromCharCode(this.data[this.pos++]));
  18095. }
  18096. return _results;
  18097. }.call(this).join('');
  18098. switch (section) {
  18099. case 'IHDR':
  18100. this.width = this.readUInt32();
  18101. this.height = this.readUInt32();
  18102. this.bits = this.data[this.pos++];
  18103. this.colorType = this.data[this.pos++];
  18104. this.compressionMethod = this.data[this.pos++];
  18105. this.filterMethod = this.data[this.pos++];
  18106. this.interlaceMethod = this.data[this.pos++];
  18107. break;
  18108. case 'acTL':
  18109. this.animation = {
  18110. numFrames: this.readUInt32(),
  18111. numPlays: this.readUInt32() || Infinity,
  18112. frames: []
  18113. };
  18114. break;
  18115. case 'PLTE':
  18116. this.palette = this.read(chunkSize);
  18117. break;
  18118. case 'fcTL':
  18119. if (frame) {
  18120. this.animation.frames.push(frame);
  18121. }
  18122. this.pos += 4;
  18123. frame = {
  18124. width: this.readUInt32(),
  18125. height: this.readUInt32(),
  18126. xOffset: this.readUInt32(),
  18127. yOffset: this.readUInt32()
  18128. };
  18129. delayNum = this.readUInt16();
  18130. delayDen = this.readUInt16() || 100;
  18131. frame.delay = 1000 * delayNum / delayDen;
  18132. frame.disposeOp = this.data[this.pos++];
  18133. frame.blendOp = this.data[this.pos++];
  18134. frame.data = [];
  18135. break;
  18136. case 'IDAT':
  18137. case 'fdAT':
  18138. if (section === 'fdAT') {
  18139. this.pos += 4;
  18140. chunkSize -= 4;
  18141. }
  18142. data = (frame != null ? frame.data : void 0) || this.imgData;
  18143. for (i = _i = 0; 0 <= chunkSize ? _i < chunkSize : _i > chunkSize; i = 0 <= chunkSize ? ++_i : --_i) {
  18144. data.push(this.data[this.pos++]);
  18145. }
  18146. break;
  18147. case 'tRNS':
  18148. this.transparency = {};
  18149. switch (this.colorType) {
  18150. case 3:
  18151. palLen = this.palette.length / 3;
  18152. this.transparency.indexed = this.read(chunkSize);
  18153. if (this.transparency.indexed.length > palLen) throw new Error('More transparent colors than palette size');
  18154. /*
  18155. * According to the PNG spec trns should be increased to the same size as palette if shorter
  18156. */
  18157. //palShort = 255 - this.transparency.indexed.length;
  18158. palShort = palLen - this.transparency.indexed.length;
  18159. if (palShort > 0) {
  18160. for (i = _j = 0; 0 <= palShort ? _j < palShort : _j > palShort; i = 0 <= palShort ? ++_j : --_j) {
  18161. this.transparency.indexed.push(255);
  18162. }
  18163. }
  18164. break;
  18165. case 0:
  18166. this.transparency.grayscale = this.read(chunkSize)[0];
  18167. break;
  18168. case 2:
  18169. this.transparency.rgb = this.read(chunkSize);
  18170. }
  18171. break;
  18172. case 'tEXt':
  18173. text = this.read(chunkSize);
  18174. index = text.indexOf(0);
  18175. key = String.fromCharCode.apply(String, text.slice(0, index));
  18176. this.text[key] = String.fromCharCode.apply(String, text.slice(index + 1));
  18177. break;
  18178. case 'IEND':
  18179. if (frame) {
  18180. this.animation.frames.push(frame);
  18181. }
  18182. this.colors = function () {
  18183. switch (this.colorType) {
  18184. case 0:
  18185. case 3:
  18186. case 4:
  18187. return 1;
  18188. case 2:
  18189. case 6:
  18190. return 3;
  18191. }
  18192. }.call(this);
  18193. this.hasAlphaChannel = (_ref = this.colorType) === 4 || _ref === 6;
  18194. colors = this.colors + (this.hasAlphaChannel ? 1 : 0);
  18195. this.pixelBitlength = this.bits * colors;
  18196. this.colorSpace = function () {
  18197. switch (this.colors) {
  18198. case 1:
  18199. return 'DeviceGray';
  18200. case 3:
  18201. return 'DeviceRGB';
  18202. }
  18203. }.call(this);
  18204. this.imgData = new Uint8Array(this.imgData);
  18205. return;
  18206. default:
  18207. this.pos += chunkSize;
  18208. }
  18209. this.pos += 4;
  18210. if (this.pos > this.data.length) {
  18211. throw new Error("Incomplete or corrupt PNG file");
  18212. }
  18213. }
  18214. return;
  18215. }
  18216. PNG.prototype.read = function (bytes) {
  18217. var i, _i, _results;
  18218. _results = [];
  18219. for (i = _i = 0; 0 <= bytes ? _i < bytes : _i > bytes; i = 0 <= bytes ? ++_i : --_i) {
  18220. _results.push(this.data[this.pos++]);
  18221. }
  18222. return _results;
  18223. };
  18224. PNG.prototype.readUInt32 = function () {
  18225. var b1, b2, b3, b4;
  18226. b1 = this.data[this.pos++] << 24;
  18227. b2 = this.data[this.pos++] << 16;
  18228. b3 = this.data[this.pos++] << 8;
  18229. b4 = this.data[this.pos++];
  18230. return b1 | b2 | b3 | b4;
  18231. };
  18232. PNG.prototype.readUInt16 = function () {
  18233. var b1, b2;
  18234. b1 = this.data[this.pos++] << 8;
  18235. b2 = this.data[this.pos++];
  18236. return b1 | b2;
  18237. };
  18238. PNG.prototype.decodePixels = function (data) {
  18239. var pixelBytes = this.pixelBitlength / 8;
  18240. var fullPixels = new Uint8Array(this.width * this.height * pixelBytes);
  18241. var pos = 0;
  18242. var _this = this;
  18243. if (data == null) {
  18244. data = this.imgData;
  18245. }
  18246. if (data.length === 0) {
  18247. return new Uint8Array(0);
  18248. }
  18249. data = new FlateStream(data);
  18250. data = data.getBytes();
  18251. function pass(x0, y0, dx, dy) {
  18252. var abyte, c, col, i, left, length, p, pa, paeth, pb, pc, pixels, row, scanlineLength, upper, upperLeft, _i, _j, _k, _l, _m;
  18253. var w = Math.ceil((_this.width - x0) / dx),
  18254. h = Math.ceil((_this.height - y0) / dy);
  18255. var isFull = _this.width == w && _this.height == h;
  18256. scanlineLength = pixelBytes * w;
  18257. pixels = isFull ? fullPixels : new Uint8Array(scanlineLength * h);
  18258. length = data.length;
  18259. row = 0;
  18260. c = 0;
  18261. while (row < h && pos < length) {
  18262. switch (data[pos++]) {
  18263. case 0:
  18264. for (i = _i = 0; _i < scanlineLength; i = _i += 1) {
  18265. pixels[c++] = data[pos++];
  18266. }
  18267. break;
  18268. case 1:
  18269. for (i = _j = 0; _j < scanlineLength; i = _j += 1) {
  18270. abyte = data[pos++];
  18271. left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
  18272. pixels[c++] = (abyte + left) % 256;
  18273. }
  18274. break;
  18275. case 2:
  18276. for (i = _k = 0; _k < scanlineLength; i = _k += 1) {
  18277. abyte = data[pos++];
  18278. col = (i - i % pixelBytes) / pixelBytes;
  18279. upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + i % pixelBytes];
  18280. pixels[c++] = (upper + abyte) % 256;
  18281. }
  18282. break;
  18283. case 3:
  18284. for (i = _l = 0; _l < scanlineLength; i = _l += 1) {
  18285. abyte = data[pos++];
  18286. col = (i - i % pixelBytes) / pixelBytes;
  18287. left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
  18288. upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + i % pixelBytes];
  18289. pixels[c++] = (abyte + Math.floor((left + upper) / 2)) % 256;
  18290. }
  18291. break;
  18292. case 4:
  18293. for (i = _m = 0; _m < scanlineLength; i = _m += 1) {
  18294. abyte = data[pos++];
  18295. col = (i - i % pixelBytes) / pixelBytes;
  18296. left = i < pixelBytes ? 0 : pixels[c - pixelBytes];
  18297. if (row === 0) {
  18298. upper = upperLeft = 0;
  18299. } else {
  18300. upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + i % pixelBytes];
  18301. upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + i % pixelBytes];
  18302. }
  18303. p = left + upper - upperLeft;
  18304. pa = Math.abs(p - left);
  18305. pb = Math.abs(p - upper);
  18306. pc = Math.abs(p - upperLeft);
  18307. if (pa <= pb && pa <= pc) {
  18308. paeth = left;
  18309. } else if (pb <= pc) {
  18310. paeth = upper;
  18311. } else {
  18312. paeth = upperLeft;
  18313. }
  18314. pixels[c++] = (abyte + paeth) % 256;
  18315. }
  18316. break;
  18317. default:
  18318. throw new Error("Invalid filter algorithm: " + data[pos - 1]);
  18319. }
  18320. if (!isFull) {
  18321. var fullPos = ((y0 + row * dy) * _this.width + x0) * pixelBytes;
  18322. var partPos = row * scanlineLength;
  18323. for (i = 0; i < w; i += 1) {
  18324. for (var j = 0; j < pixelBytes; j += 1) {
  18325. fullPixels[fullPos++] = pixels[partPos++];
  18326. }
  18327. fullPos += (dx - 1) * pixelBytes;
  18328. }
  18329. }
  18330. row++;
  18331. }
  18332. }
  18333. if (_this.interlaceMethod == 1) {
  18334. /*
  18335. 1 6 4 6 2 6 4 6
  18336. 7 7 7 7 7 7 7 7
  18337. 5 6 5 6 5 6 5 6
  18338. 7 7 7 7 7 7 7 7
  18339. 3 6 4 6 3 6 4 6
  18340. 7 7 7 7 7 7 7 7
  18341. 5 6 5 6 5 6 5 6
  18342. 7 7 7 7 7 7 7 7
  18343. */
  18344. pass(0, 0, 8, 8); // 1
  18345. /* NOTE these seem to follow the pattern:
  18346. * pass(x, 0, 2*x, 2*x);
  18347. * pass(0, x, x, 2*x);
  18348. * with x being 4, 2, 1.
  18349. */
  18350. pass(4, 0, 8, 8); // 2
  18351. pass(0, 4, 4, 8); // 3
  18352. pass(2, 0, 4, 4); // 4
  18353. pass(0, 2, 2, 4); // 5
  18354. pass(1, 0, 2, 2); // 6
  18355. pass(0, 1, 1, 2); // 7
  18356. } else {
  18357. pass(0, 0, 1, 1);
  18358. }
  18359. return fullPixels;
  18360. };
  18361. PNG.prototype.decodePalette = function () {
  18362. var c, i, length, palette, pos, ret, transparency, _i, _ref, _ref1;
  18363. palette = this.palette;
  18364. transparency = this.transparency.indexed || [];
  18365. ret = new Uint8Array((transparency.length || 0) + palette.length);
  18366. pos = 0;
  18367. length = palette.length;
  18368. c = 0;
  18369. for (i = _i = 0, _ref = palette.length; _i < _ref; i = _i += 3) {
  18370. ret[pos++] = palette[i];
  18371. ret[pos++] = palette[i + 1];
  18372. ret[pos++] = palette[i + 2];
  18373. ret[pos++] = (_ref1 = transparency[c++]) != null ? _ref1 : 255;
  18374. }
  18375. return ret;
  18376. };
  18377. PNG.prototype.copyToImageData = function (imageData, pixels) {
  18378. var alpha, colors, data, i, input, j, k, length, palette, v, _ref;
  18379. colors = this.colors;
  18380. palette = null;
  18381. alpha = this.hasAlphaChannel;
  18382. if (this.palette.length) {
  18383. palette = (_ref = this._decodedPalette) != null ? _ref : this._decodedPalette = this.decodePalette();
  18384. colors = 4;
  18385. alpha = true;
  18386. }
  18387. data = imageData.data || imageData;
  18388. length = data.length;
  18389. input = palette || pixels;
  18390. i = j = 0;
  18391. if (colors === 1) {
  18392. while (i < length) {
  18393. k = palette ? pixels[i / 4] * 4 : j;
  18394. v = input[k++];
  18395. data[i++] = v;
  18396. data[i++] = v;
  18397. data[i++] = v;
  18398. data[i++] = alpha ? input[k++] : 255;
  18399. j = k;
  18400. }
  18401. } else {
  18402. while (i < length) {
  18403. k = palette ? pixels[i / 4] * 4 : j;
  18404. data[i++] = input[k++];
  18405. data[i++] = input[k++];
  18406. data[i++] = input[k++];
  18407. data[i++] = alpha ? input[k++] : 255;
  18408. j = k;
  18409. }
  18410. }
  18411. };
  18412. PNG.prototype.decode = function () {
  18413. var ret;
  18414. ret = new Uint8Array(this.width * this.height * 4);
  18415. this.copyToImageData(ret, this.decodePixels());
  18416. return ret;
  18417. };
  18418. try {
  18419. scratchCanvas = global.document.createElement('canvas');
  18420. scratchCtx = scratchCanvas.getContext('2d');
  18421. } catch (e) {
  18422. return -1;
  18423. }
  18424. makeImage = function makeImage(imageData) {
  18425. var img;
  18426. scratchCtx.width = imageData.width;
  18427. scratchCtx.height = imageData.height;
  18428. scratchCtx.clearRect(0, 0, imageData.width, imageData.height);
  18429. scratchCtx.putImageData(imageData, 0, 0);
  18430. img = new Image();
  18431. img.src = scratchCanvas.toDataURL();
  18432. return img;
  18433. };
  18434. PNG.prototype.decodeFrames = function (ctx) {
  18435. var frame, i, imageData, pixels, _i, _len, _ref, _results;
  18436. if (!this.animation) {
  18437. return;
  18438. }
  18439. _ref = this.animation.frames;
  18440. _results = [];
  18441. for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
  18442. frame = _ref[i];
  18443. imageData = ctx.createImageData(frame.width, frame.height);
  18444. pixels = this.decodePixels(new Uint8Array(frame.data));
  18445. this.copyToImageData(imageData, pixels);
  18446. frame.imageData = imageData;
  18447. _results.push(frame.image = makeImage(imageData));
  18448. }
  18449. return _results;
  18450. };
  18451. PNG.prototype.renderFrame = function (ctx, number) {
  18452. var frame, frames, prev;
  18453. frames = this.animation.frames;
  18454. frame = frames[number];
  18455. prev = frames[number - 1];
  18456. if (number === 0) {
  18457. ctx.clearRect(0, 0, this.width, this.height);
  18458. }
  18459. if ((prev != null ? prev.disposeOp : void 0) === APNG_DISPOSE_OP_BACKGROUND) {
  18460. ctx.clearRect(prev.xOffset, prev.yOffset, prev.width, prev.height);
  18461. } else if ((prev != null ? prev.disposeOp : void 0) === APNG_DISPOSE_OP_PREVIOUS) {
  18462. ctx.putImageData(prev.imageData, prev.xOffset, prev.yOffset);
  18463. }
  18464. if (frame.blendOp === APNG_BLEND_OP_SOURCE) {
  18465. ctx.clearRect(frame.xOffset, frame.yOffset, frame.width, frame.height);
  18466. }
  18467. return ctx.drawImage(frame.image, frame.xOffset, frame.yOffset);
  18468. };
  18469. PNG.prototype.animate = function (ctx) {
  18470. var _doFrame,
  18471. frameNumber,
  18472. frames,
  18473. numFrames,
  18474. numPlays,
  18475. _ref,
  18476. _this = this;
  18477. frameNumber = 0;
  18478. _ref = this.animation, numFrames = _ref.numFrames, frames = _ref.frames, numPlays = _ref.numPlays;
  18479. return (_doFrame = function doFrame() {
  18480. var f, frame;
  18481. f = frameNumber++ % numFrames;
  18482. frame = frames[f];
  18483. _this.renderFrame(ctx, f);
  18484. if (numFrames > 1 && frameNumber / numFrames < numPlays) {
  18485. return _this.animation._timeout = setTimeout(_doFrame, frame.delay);
  18486. }
  18487. })();
  18488. };
  18489. PNG.prototype.stopAnimation = function () {
  18490. var _ref;
  18491. return clearTimeout((_ref = this.animation) != null ? _ref._timeout : void 0);
  18492. };
  18493. PNG.prototype.render = function (canvas) {
  18494. var ctx, data;
  18495. if (canvas._png) {
  18496. canvas._png.stopAnimation();
  18497. }
  18498. canvas._png = this;
  18499. canvas.width = this.width;
  18500. canvas.height = this.height;
  18501. ctx = canvas.getContext("2d");
  18502. if (this.animation) {
  18503. this.decodeFrames(ctx);
  18504. return this.animate(ctx);
  18505. } else {
  18506. data = ctx.createImageData(this.width, this.height);
  18507. this.copyToImageData(data, this.decodePixels());
  18508. return ctx.putImageData(data, 0, 0);
  18509. }
  18510. };
  18511. return PNG;
  18512. }();
  18513. global.PNG = PNG;
  18514. })(typeof self !== "undefined" && self || typeof window !== "undefined" && window || typeof global !== "undefined" && global || Function('return typeof this === "object" && this.content')() || Function('return this')()); // `self` is undefined in Firefox for Android content script context
  18515. // while `this` is nsIContentFrameMessageManager
  18516. // with an attribute `content` that corresponds to the window
  18517. /*
  18518. * Extracted from pdf.js
  18519. * https://github.com/andreasgal/pdf.js
  18520. *
  18521. * Copyright (c) 2011 Mozilla Foundation
  18522. *
  18523. * Contributors: Andreas Gal <gal@mozilla.com>
  18524. * Chris G Jones <cjones@mozilla.com>
  18525. * Shaon Barman <shaon.barman@gmail.com>
  18526. * Vivien Nicolas <21@vingtetun.org>
  18527. * Justin D'Arcangelo <justindarc@gmail.com>
  18528. * Yury Delendik
  18529. *
  18530. *
  18531. */
  18532. var DecodeStream = function () {
  18533. function constructor() {
  18534. this.pos = 0;
  18535. this.bufferLength = 0;
  18536. this.eof = false;
  18537. this.buffer = null;
  18538. }
  18539. constructor.prototype = {
  18540. ensureBuffer: function decodestream_ensureBuffer(requested) {
  18541. var buffer = this.buffer;
  18542. var current = buffer ? buffer.byteLength : 0;
  18543. if (requested < current) return buffer;
  18544. var size = 512;
  18545. while (size < requested) {
  18546. size <<= 1;
  18547. }
  18548. var buffer2 = new Uint8Array(size);
  18549. for (var i = 0; i < current; ++i) {
  18550. buffer2[i] = buffer[i];
  18551. }
  18552. return this.buffer = buffer2;
  18553. },
  18554. getByte: function decodestream_getByte() {
  18555. var pos = this.pos;
  18556. while (this.bufferLength <= pos) {
  18557. if (this.eof) return null;
  18558. this.readBlock();
  18559. }
  18560. return this.buffer[this.pos++];
  18561. },
  18562. getBytes: function decodestream_getBytes(length) {
  18563. var pos = this.pos;
  18564. if (length) {
  18565. this.ensureBuffer(pos + length);
  18566. var end = pos + length;
  18567. while (!this.eof && this.bufferLength < end) {
  18568. this.readBlock();
  18569. }
  18570. var bufEnd = this.bufferLength;
  18571. if (end > bufEnd) end = bufEnd;
  18572. } else {
  18573. while (!this.eof) {
  18574. this.readBlock();
  18575. }
  18576. var end = this.bufferLength;
  18577. }
  18578. this.pos = end;
  18579. return this.buffer.subarray(pos, end);
  18580. },
  18581. lookChar: function decodestream_lookChar() {
  18582. var pos = this.pos;
  18583. while (this.bufferLength <= pos) {
  18584. if (this.eof) return null;
  18585. this.readBlock();
  18586. }
  18587. return String.fromCharCode(this.buffer[this.pos]);
  18588. },
  18589. getChar: function decodestream_getChar() {
  18590. var pos = this.pos;
  18591. while (this.bufferLength <= pos) {
  18592. if (this.eof) return null;
  18593. this.readBlock();
  18594. }
  18595. return String.fromCharCode(this.buffer[this.pos++]);
  18596. },
  18597. makeSubStream: function decodestream_makeSubstream(start, length, dict) {
  18598. var end = start + length;
  18599. while (this.bufferLength <= end && !this.eof) {
  18600. this.readBlock();
  18601. }
  18602. return new Stream(this.buffer, start, length, dict);
  18603. },
  18604. skip: function decodestream_skip(n) {
  18605. if (!n) n = 1;
  18606. this.pos += n;
  18607. },
  18608. reset: function decodestream_reset() {
  18609. this.pos = 0;
  18610. }
  18611. };
  18612. return constructor;
  18613. }();
  18614. var FlateStream = function () {
  18615. if (typeof Uint32Array === 'undefined') {
  18616. return undefined;
  18617. }
  18618. var codeLenCodeMap = new Uint32Array([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
  18619. var lengthDecode = new Uint32Array([0x00003, 0x00004, 0x00005, 0x00006, 0x00007, 0x00008, 0x00009, 0x0000a, 0x1000b, 0x1000d, 0x1000f, 0x10011, 0x20013, 0x20017, 0x2001b, 0x2001f, 0x30023, 0x3002b, 0x30033, 0x3003b, 0x40043, 0x40053, 0x40063, 0x40073, 0x50083, 0x500a3, 0x500c3, 0x500e3, 0x00102, 0x00102, 0x00102]);
  18620. var distDecode = new Uint32Array([0x00001, 0x00002, 0x00003, 0x00004, 0x10005, 0x10007, 0x20009, 0x2000d, 0x30011, 0x30019, 0x40021, 0x40031, 0x50041, 0x50061, 0x60081, 0x600c1, 0x70101, 0x70181, 0x80201, 0x80301, 0x90401, 0x90601, 0xa0801, 0xa0c01, 0xb1001, 0xb1801, 0xc2001, 0xc3001, 0xd4001, 0xd6001]);
  18621. var fixedLitCodeTab = [new Uint32Array([0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c0, 0x70108, 0x80060, 0x80020, 0x900a0, 0x80000, 0x80080, 0x80040, 0x900e0, 0x70104, 0x80058, 0x80018, 0x90090, 0x70114, 0x80078, 0x80038, 0x900d0, 0x7010c, 0x80068, 0x80028, 0x900b0, 0x80008, 0x80088, 0x80048, 0x900f0, 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c8, 0x7010a, 0x80064, 0x80024, 0x900a8, 0x80004, 0x80084, 0x80044, 0x900e8, 0x70106, 0x8005c, 0x8001c, 0x90098, 0x70116, 0x8007c, 0x8003c, 0x900d8, 0x7010e, 0x8006c, 0x8002c, 0x900b8, 0x8000c, 0x8008c, 0x8004c, 0x900f8, 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c4, 0x70109, 0x80062, 0x80022, 0x900a4, 0x80002, 0x80082, 0x80042, 0x900e4, 0x70105, 0x8005a, 0x8001a, 0x90094, 0x70115, 0x8007a, 0x8003a, 0x900d4, 0x7010d, 0x8006a, 0x8002a, 0x900b4, 0x8000a, 0x8008a, 0x8004a, 0x900f4, 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cc, 0x7010b, 0x80066, 0x80026, 0x900ac, 0x80006, 0x80086, 0x80046, 0x900ec, 0x70107, 0x8005e, 0x8001e, 0x9009c, 0x70117, 0x8007e, 0x8003e, 0x900dc, 0x7010f, 0x8006e, 0x8002e, 0x900bc, 0x8000e, 0x8008e, 0x8004e, 0x900fc, 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c2, 0x70108, 0x80061, 0x80021, 0x900a2, 0x80001, 0x80081, 0x80041, 0x900e2, 0x70104, 0x80059, 0x80019, 0x90092, 0x70114, 0x80079, 0x80039, 0x900d2, 0x7010c, 0x80069, 0x80029, 0x900b2, 0x80009, 0x80089, 0x80049, 0x900f2, 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900ca, 0x7010a, 0x80065, 0x80025, 0x900aa, 0x80005, 0x80085, 0x80045, 0x900ea, 0x70106, 0x8005d, 0x8001d, 0x9009a, 0x70116, 0x8007d, 0x8003d, 0x900da, 0x7010e, 0x8006d, 0x8002d, 0x900ba, 0x8000d, 0x8008d, 0x8004d, 0x900fa, 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c6, 0x70109, 0x80063, 0x80023, 0x900a6, 0x80003, 0x80083, 0x80043, 0x900e6, 0x70105, 0x8005b, 0x8001b, 0x90096, 0x70115, 0x8007b, 0x8003b, 0x900d6, 0x7010d, 0x8006b, 0x8002b, 0x900b6, 0x8000b, 0x8008b, 0x8004b, 0x900f6, 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900ce, 0x7010b, 0x80067, 0x80027, 0x900ae, 0x80007, 0x80087, 0x80047, 0x900ee, 0x70107, 0x8005f, 0x8001f, 0x9009e, 0x70117, 0x8007f, 0x8003f, 0x900de, 0x7010f, 0x8006f, 0x8002f, 0x900be, 0x8000f, 0x8008f, 0x8004f, 0x900fe, 0x70100, 0x80050, 0x80010, 0x80118, 0x70110, 0x80070, 0x80030, 0x900c1, 0x70108, 0x80060, 0x80020, 0x900a1, 0x80000, 0x80080, 0x80040, 0x900e1, 0x70104, 0x80058, 0x80018, 0x90091, 0x70114, 0x80078, 0x80038, 0x900d1, 0x7010c, 0x80068, 0x80028, 0x900b1, 0x80008, 0x80088, 0x80048, 0x900f1, 0x70102, 0x80054, 0x80014, 0x8011c, 0x70112, 0x80074, 0x80034, 0x900c9, 0x7010a, 0x80064, 0x80024, 0x900a9, 0x80004, 0x80084, 0x80044, 0x900e9, 0x70106, 0x8005c, 0x8001c, 0x90099, 0x70116, 0x8007c, 0x8003c, 0x900d9, 0x7010e, 0x8006c, 0x8002c, 0x900b9, 0x8000c, 0x8008c, 0x8004c, 0x900f9, 0x70101, 0x80052, 0x80012, 0x8011a, 0x70111, 0x80072, 0x80032, 0x900c5, 0x70109, 0x80062, 0x80022, 0x900a5, 0x80002, 0x80082, 0x80042, 0x900e5, 0x70105, 0x8005a, 0x8001a, 0x90095, 0x70115, 0x8007a, 0x8003a, 0x900d5, 0x7010d, 0x8006a, 0x8002a, 0x900b5, 0x8000a, 0x8008a, 0x8004a, 0x900f5, 0x70103, 0x80056, 0x80016, 0x8011e, 0x70113, 0x80076, 0x80036, 0x900cd, 0x7010b, 0x80066, 0x80026, 0x900ad, 0x80006, 0x80086, 0x80046, 0x900ed, 0x70107, 0x8005e, 0x8001e, 0x9009d, 0x70117, 0x8007e, 0x8003e, 0x900dd, 0x7010f, 0x8006e, 0x8002e, 0x900bd, 0x8000e, 0x8008e, 0x8004e, 0x900fd, 0x70100, 0x80051, 0x80011, 0x80119, 0x70110, 0x80071, 0x80031, 0x900c3, 0x70108, 0x80061, 0x80021, 0x900a3, 0x80001, 0x80081, 0x80041, 0x900e3, 0x70104, 0x80059, 0x80019, 0x90093, 0x70114, 0x80079, 0x80039, 0x900d3, 0x7010c, 0x80069, 0x80029, 0x900b3, 0x80009, 0x80089, 0x80049, 0x900f3, 0x70102, 0x80055, 0x80015, 0x8011d, 0x70112, 0x80075, 0x80035, 0x900cb, 0x7010a, 0x80065, 0x80025, 0x900ab, 0x80005, 0x80085, 0x80045, 0x900eb, 0x70106, 0x8005d, 0x8001d, 0x9009b, 0x70116, 0x8007d, 0x8003d, 0x900db, 0x7010e, 0x8006d, 0x8002d, 0x900bb, 0x8000d, 0x8008d, 0x8004d, 0x900fb, 0x70101, 0x80053, 0x80013, 0x8011b, 0x70111, 0x80073, 0x80033, 0x900c7, 0x70109, 0x80063, 0x80023, 0x900a7, 0x80003, 0x80083, 0x80043, 0x900e7, 0x70105, 0x8005b, 0x8001b, 0x90097, 0x70115, 0x8007b, 0x8003b, 0x900d7, 0x7010d, 0x8006b, 0x8002b, 0x900b7, 0x8000b, 0x8008b, 0x8004b, 0x900f7, 0x70103, 0x80057, 0x80017, 0x8011f, 0x70113, 0x80077, 0x80037, 0x900cf, 0x7010b, 0x80067, 0x80027, 0x900af, 0x80007, 0x80087, 0x80047, 0x900ef, 0x70107, 0x8005f, 0x8001f, 0x9009f, 0x70117, 0x8007f, 0x8003f, 0x900df, 0x7010f, 0x8006f, 0x8002f, 0x900bf, 0x8000f, 0x8008f, 0x8004f, 0x900ff]), 9];
  18622. var fixedDistCodeTab = [new Uint32Array([0x50000, 0x50010, 0x50008, 0x50018, 0x50004, 0x50014, 0x5000c, 0x5001c, 0x50002, 0x50012, 0x5000a, 0x5001a, 0x50006, 0x50016, 0x5000e, 0x00000, 0x50001, 0x50011, 0x50009, 0x50019, 0x50005, 0x50015, 0x5000d, 0x5001d, 0x50003, 0x50013, 0x5000b, 0x5001b, 0x50007, 0x50017, 0x5000f, 0x00000]), 5];
  18623. function error(e) {
  18624. throw new Error(e);
  18625. }
  18626. function constructor(bytes) {
  18627. //var bytes = stream.getBytes();
  18628. var bytesPos = 0;
  18629. var cmf = bytes[bytesPos++];
  18630. var flg = bytes[bytesPos++];
  18631. if (cmf == -1 || flg == -1) error('Invalid header in flate stream');
  18632. if ((cmf & 0x0f) != 0x08) error('Unknown compression method in flate stream');
  18633. if (((cmf << 8) + flg) % 31 != 0) error('Bad FCHECK in flate stream');
  18634. if (flg & 0x20) error('FDICT bit set in flate stream');
  18635. this.bytes = bytes;
  18636. this.bytesPos = bytesPos;
  18637. this.codeSize = 0;
  18638. this.codeBuf = 0;
  18639. DecodeStream.call(this);
  18640. }
  18641. constructor.prototype = Object.create(DecodeStream.prototype);
  18642. constructor.prototype.getBits = function (bits) {
  18643. var codeSize = this.codeSize;
  18644. var codeBuf = this.codeBuf;
  18645. var bytes = this.bytes;
  18646. var bytesPos = this.bytesPos;
  18647. var b;
  18648. while (codeSize < bits) {
  18649. if (typeof (b = bytes[bytesPos++]) == 'undefined') error('Bad encoding in flate stream');
  18650. codeBuf |= b << codeSize;
  18651. codeSize += 8;
  18652. }
  18653. b = codeBuf & (1 << bits) - 1;
  18654. this.codeBuf = codeBuf >> bits;
  18655. this.codeSize = codeSize -= bits;
  18656. this.bytesPos = bytesPos;
  18657. return b;
  18658. };
  18659. constructor.prototype.getCode = function (table) {
  18660. var codes = table[0];
  18661. var maxLen = table[1];
  18662. var codeSize = this.codeSize;
  18663. var codeBuf = this.codeBuf;
  18664. var bytes = this.bytes;
  18665. var bytesPos = this.bytesPos;
  18666. while (codeSize < maxLen) {
  18667. var b;
  18668. if (typeof (b = bytes[bytesPos++]) == 'undefined') error('Bad encoding in flate stream');
  18669. codeBuf |= b << codeSize;
  18670. codeSize += 8;
  18671. }
  18672. var code = codes[codeBuf & (1 << maxLen) - 1];
  18673. var codeLen = code >> 16;
  18674. var codeVal = code & 0xffff;
  18675. if (codeSize == 0 || codeSize < codeLen || codeLen == 0) error('Bad encoding in flate stream');
  18676. this.codeBuf = codeBuf >> codeLen;
  18677. this.codeSize = codeSize - codeLen;
  18678. this.bytesPos = bytesPos;
  18679. return codeVal;
  18680. };
  18681. constructor.prototype.generateHuffmanTable = function (lengths) {
  18682. var n = lengths.length; // find max code length
  18683. var maxLen = 0;
  18684. for (var i = 0; i < n; ++i) {
  18685. if (lengths[i] > maxLen) maxLen = lengths[i];
  18686. } // build the table
  18687. var size = 1 << maxLen;
  18688. var codes = new Uint32Array(size);
  18689. for (var len = 1, code = 0, skip = 2; len <= maxLen; ++len, code <<= 1, skip <<= 1) {
  18690. for (var val = 0; val < n; ++val) {
  18691. if (lengths[val] == len) {
  18692. // bit-reverse the code
  18693. var code2 = 0;
  18694. var t = code;
  18695. for (var i = 0; i < len; ++i) {
  18696. code2 = code2 << 1 | t & 1;
  18697. t >>= 1;
  18698. } // fill the table entries
  18699. for (var i = code2; i < size; i += skip) {
  18700. codes[i] = len << 16 | val;
  18701. }
  18702. ++code;
  18703. }
  18704. }
  18705. }
  18706. return [codes, maxLen];
  18707. };
  18708. constructor.prototype.readBlock = function () {
  18709. function repeat(stream, array, len, offset, what) {
  18710. var repeat = stream.getBits(len) + offset;
  18711. while (repeat-- > 0) {
  18712. array[i++] = what;
  18713. }
  18714. } // read block header
  18715. var hdr = this.getBits(3);
  18716. if (hdr & 1) this.eof = true;
  18717. hdr >>= 1;
  18718. if (hdr == 0) {
  18719. // uncompressed block
  18720. var bytes = this.bytes;
  18721. var bytesPos = this.bytesPos;
  18722. var b;
  18723. if (typeof (b = bytes[bytesPos++]) == 'undefined') error('Bad block header in flate stream');
  18724. var blockLen = b;
  18725. if (typeof (b = bytes[bytesPos++]) == 'undefined') error('Bad block header in flate stream');
  18726. blockLen |= b << 8;
  18727. if (typeof (b = bytes[bytesPos++]) == 'undefined') error('Bad block header in flate stream');
  18728. var check = b;
  18729. if (typeof (b = bytes[bytesPos++]) == 'undefined') error('Bad block header in flate stream');
  18730. check |= b << 8;
  18731. if (check != (~blockLen & 0xffff)) error('Bad uncompressed block length in flate stream');
  18732. this.codeBuf = 0;
  18733. this.codeSize = 0;
  18734. var bufferLength = this.bufferLength;
  18735. var buffer = this.ensureBuffer(bufferLength + blockLen);
  18736. var end = bufferLength + blockLen;
  18737. this.bufferLength = end;
  18738. for (var n = bufferLength; n < end; ++n) {
  18739. if (typeof (b = bytes[bytesPos++]) == 'undefined') {
  18740. this.eof = true;
  18741. break;
  18742. }
  18743. buffer[n] = b;
  18744. }
  18745. this.bytesPos = bytesPos;
  18746. return;
  18747. }
  18748. var litCodeTable;
  18749. var distCodeTable;
  18750. if (hdr == 1) {
  18751. // compressed block, fixed codes
  18752. litCodeTable = fixedLitCodeTab;
  18753. distCodeTable = fixedDistCodeTab;
  18754. } else if (hdr == 2) {
  18755. // compressed block, dynamic codes
  18756. var numLitCodes = this.getBits(5) + 257;
  18757. var numDistCodes = this.getBits(5) + 1;
  18758. var numCodeLenCodes = this.getBits(4) + 4; // build the code lengths code table
  18759. var codeLenCodeLengths = Array(codeLenCodeMap.length);
  18760. var i = 0;
  18761. while (i < numCodeLenCodes) {
  18762. codeLenCodeLengths[codeLenCodeMap[i++]] = this.getBits(3);
  18763. }
  18764. var codeLenCodeTab = this.generateHuffmanTable(codeLenCodeLengths); // build the literal and distance code tables
  18765. var len = 0;
  18766. var i = 0;
  18767. var codes = numLitCodes + numDistCodes;
  18768. var codeLengths = new Array(codes);
  18769. while (i < codes) {
  18770. var code = this.getCode(codeLenCodeTab);
  18771. if (code == 16) {
  18772. repeat(this, codeLengths, 2, 3, len);
  18773. } else if (code == 17) {
  18774. repeat(this, codeLengths, 3, 3, len = 0);
  18775. } else if (code == 18) {
  18776. repeat(this, codeLengths, 7, 11, len = 0);
  18777. } else {
  18778. codeLengths[i++] = len = code;
  18779. }
  18780. }
  18781. litCodeTable = this.generateHuffmanTable(codeLengths.slice(0, numLitCodes));
  18782. distCodeTable = this.generateHuffmanTable(codeLengths.slice(numLitCodes, codes));
  18783. } else {
  18784. error('Unknown block type in flate stream');
  18785. }
  18786. var buffer = this.buffer;
  18787. var limit = buffer ? buffer.length : 0;
  18788. var pos = this.bufferLength;
  18789. while (true) {
  18790. var code1 = this.getCode(litCodeTable);
  18791. if (code1 < 256) {
  18792. if (pos + 1 >= limit) {
  18793. buffer = this.ensureBuffer(pos + 1);
  18794. limit = buffer.length;
  18795. }
  18796. buffer[pos++] = code1;
  18797. continue;
  18798. }
  18799. if (code1 == 256) {
  18800. this.bufferLength = pos;
  18801. return;
  18802. }
  18803. code1 -= 257;
  18804. code1 = lengthDecode[code1];
  18805. var code2 = code1 >> 16;
  18806. if (code2 > 0) code2 = this.getBits(code2);
  18807. var len = (code1 & 0xffff) + code2;
  18808. code1 = this.getCode(distCodeTable);
  18809. code1 = distDecode[code1];
  18810. code2 = code1 >> 16;
  18811. if (code2 > 0) code2 = this.getBits(code2);
  18812. var dist = (code1 & 0xffff) + code2;
  18813. if (pos + len >= limit) {
  18814. buffer = this.ensureBuffer(pos + len);
  18815. limit = buffer.length;
  18816. }
  18817. for (var k = 0; k < len; ++k, ++pos) {
  18818. buffer[pos] = buffer[pos - dist];
  18819. }
  18820. }
  18821. };
  18822. return constructor;
  18823. }();
  18824. /*rollup-keeper-start*/
  18825. window.tmp = FlateStream;
  18826. /*rollup-keeper-end*/
  18827. try {
  18828. module.exports = jsPDF;
  18829. }
  18830. catch (e) {}