You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

9051 lines
302 KiB

7 years ago
  1. /* Copyright 2012 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. (function (root, factory) {
  16. 'use strict';
  17. if (typeof define === 'function' && define.amd) {
  18. define('pdfjs-dist/build/pdf', ['exports'], factory);
  19. } else if (typeof exports !== 'undefined') {
  20. factory(exports);
  21. } else {
  22. factory(root['pdfjsDistBuildPdf'] = {});
  23. }
  24. }(this, function (exports) {
  25. 'use strict';
  26. var pdfjsVersion = '1.7.225';
  27. var pdfjsBuild = '17d135f';
  28. var pdfjsFilePath = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : null;
  29. var pdfjsLibs = {};
  30. (function pdfjsWrapper() {
  31. (function (root, factory) {
  32. factory(root.pdfjsSharedUtil = {});
  33. }(this, function (exports) {
  34. var globalScope = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : this;
  35. var FONT_IDENTITY_MATRIX = [
  36. 0.001,
  37. 0,
  38. 0,
  39. 0.001,
  40. 0,
  41. 0
  42. ];
  43. var TextRenderingMode = {
  44. FILL: 0,
  45. STROKE: 1,
  46. FILL_STROKE: 2,
  47. INVISIBLE: 3,
  48. FILL_ADD_TO_PATH: 4,
  49. STROKE_ADD_TO_PATH: 5,
  50. FILL_STROKE_ADD_TO_PATH: 6,
  51. ADD_TO_PATH: 7,
  52. FILL_STROKE_MASK: 3,
  53. ADD_TO_PATH_FLAG: 4
  54. };
  55. var ImageKind = {
  56. GRAYSCALE_1BPP: 1,
  57. RGB_24BPP: 2,
  58. RGBA_32BPP: 3
  59. };
  60. var AnnotationType = {
  61. TEXT: 1,
  62. LINK: 2,
  63. FREETEXT: 3,
  64. LINE: 4,
  65. SQUARE: 5,
  66. CIRCLE: 6,
  67. POLYGON: 7,
  68. POLYLINE: 8,
  69. HIGHLIGHT: 9,
  70. UNDERLINE: 10,
  71. SQUIGGLY: 11,
  72. STRIKEOUT: 12,
  73. STAMP: 13,
  74. CARET: 14,
  75. INK: 15,
  76. POPUP: 16,
  77. FILEATTACHMENT: 17,
  78. SOUND: 18,
  79. MOVIE: 19,
  80. WIDGET: 20,
  81. SCREEN: 21,
  82. PRINTERMARK: 22,
  83. TRAPNET: 23,
  84. WATERMARK: 24,
  85. THREED: 25,
  86. REDACT: 26
  87. };
  88. var AnnotationFlag = {
  89. INVISIBLE: 0x01,
  90. HIDDEN: 0x02,
  91. PRINT: 0x04,
  92. NOZOOM: 0x08,
  93. NOROTATE: 0x10,
  94. NOVIEW: 0x20,
  95. READONLY: 0x40,
  96. LOCKED: 0x80,
  97. TOGGLENOVIEW: 0x100,
  98. LOCKEDCONTENTS: 0x200
  99. };
  100. var AnnotationFieldFlag = {
  101. READONLY: 0x0000001,
  102. REQUIRED: 0x0000002,
  103. NOEXPORT: 0x0000004,
  104. MULTILINE: 0x0001000,
  105. PASSWORD: 0x0002000,
  106. NOTOGGLETOOFF: 0x0004000,
  107. RADIO: 0x0008000,
  108. PUSHBUTTON: 0x0010000,
  109. COMBO: 0x0020000,
  110. EDIT: 0x0040000,
  111. SORT: 0x0080000,
  112. FILESELECT: 0x0100000,
  113. MULTISELECT: 0x0200000,
  114. DONOTSPELLCHECK: 0x0400000,
  115. DONOTSCROLL: 0x0800000,
  116. COMB: 0x1000000,
  117. RICHTEXT: 0x2000000,
  118. RADIOSINUNISON: 0x2000000,
  119. COMMITONSELCHANGE: 0x4000000
  120. };
  121. var AnnotationBorderStyleType = {
  122. SOLID: 1,
  123. DASHED: 2,
  124. BEVELED: 3,
  125. INSET: 4,
  126. UNDERLINE: 5
  127. };
  128. var StreamType = {
  129. UNKNOWN: 0,
  130. FLATE: 1,
  131. LZW: 2,
  132. DCT: 3,
  133. JPX: 4,
  134. JBIG: 5,
  135. A85: 6,
  136. AHX: 7,
  137. CCF: 8,
  138. RL: 9
  139. };
  140. var FontType = {
  141. UNKNOWN: 0,
  142. TYPE1: 1,
  143. TYPE1C: 2,
  144. CIDFONTTYPE0: 3,
  145. CIDFONTTYPE0C: 4,
  146. TRUETYPE: 5,
  147. CIDFONTTYPE2: 6,
  148. TYPE3: 7,
  149. OPENTYPE: 8,
  150. TYPE0: 9,
  151. MMTYPE1: 10
  152. };
  153. var VERBOSITY_LEVELS = {
  154. errors: 0,
  155. warnings: 1,
  156. infos: 5
  157. };
  158. var OPS = {
  159. dependency: 1,
  160. setLineWidth: 2,
  161. setLineCap: 3,
  162. setLineJoin: 4,
  163. setMiterLimit: 5,
  164. setDash: 6,
  165. setRenderingIntent: 7,
  166. setFlatness: 8,
  167. setGState: 9,
  168. save: 10,
  169. restore: 11,
  170. transform: 12,
  171. moveTo: 13,
  172. lineTo: 14,
  173. curveTo: 15,
  174. curveTo2: 16,
  175. curveTo3: 17,
  176. closePath: 18,
  177. rectangle: 19,
  178. stroke: 20,
  179. closeStroke: 21,
  180. fill: 22,
  181. eoFill: 23,
  182. fillStroke: 24,
  183. eoFillStroke: 25,
  184. closeFillStroke: 26,
  185. closeEOFillStroke: 27,
  186. endPath: 28,
  187. clip: 29,
  188. eoClip: 30,
  189. beginText: 31,
  190. endText: 32,
  191. setCharSpacing: 33,
  192. setWordSpacing: 34,
  193. setHScale: 35,
  194. setLeading: 36,
  195. setFont: 37,
  196. setTextRenderingMode: 38,
  197. setTextRise: 39,
  198. moveText: 40,
  199. setLeadingMoveText: 41,
  200. setTextMatrix: 42,
  201. nextLine: 43,
  202. showText: 44,
  203. showSpacedText: 45,
  204. nextLineShowText: 46,
  205. nextLineSetSpacingShowText: 47,
  206. setCharWidth: 48,
  207. setCharWidthAndBounds: 49,
  208. setStrokeColorSpace: 50,
  209. setFillColorSpace: 51,
  210. setStrokeColor: 52,
  211. setStrokeColorN: 53,
  212. setFillColor: 54,
  213. setFillColorN: 55,
  214. setStrokeGray: 56,
  215. setFillGray: 57,
  216. setStrokeRGBColor: 58,
  217. setFillRGBColor: 59,
  218. setStrokeCMYKColor: 60,
  219. setFillCMYKColor: 61,
  220. shadingFill: 62,
  221. beginInlineImage: 63,
  222. beginImageData: 64,
  223. endInlineImage: 65,
  224. paintXObject: 66,
  225. markPoint: 67,
  226. markPointProps: 68,
  227. beginMarkedContent: 69,
  228. beginMarkedContentProps: 70,
  229. endMarkedContent: 71,
  230. beginCompat: 72,
  231. endCompat: 73,
  232. paintFormXObjectBegin: 74,
  233. paintFormXObjectEnd: 75,
  234. beginGroup: 76,
  235. endGroup: 77,
  236. beginAnnotations: 78,
  237. endAnnotations: 79,
  238. beginAnnotation: 80,
  239. endAnnotation: 81,
  240. paintJpegXObject: 82,
  241. paintImageMaskXObject: 83,
  242. paintImageMaskXObjectGroup: 84,
  243. paintImageXObject: 85,
  244. paintInlineImageXObject: 86,
  245. paintInlineImageXObjectGroup: 87,
  246. paintImageXObjectRepeat: 88,
  247. paintImageMaskXObjectRepeat: 89,
  248. paintSolidColorImageMask: 90,
  249. constructPath: 91
  250. };
  251. var verbosity = VERBOSITY_LEVELS.warnings;
  252. function setVerbosityLevel(level) {
  253. verbosity = level;
  254. }
  255. function getVerbosityLevel() {
  256. return verbosity;
  257. }
  258. function info(msg) {
  259. if (verbosity >= VERBOSITY_LEVELS.infos) {
  260. console.log('Info: ' + msg);
  261. }
  262. }
  263. function warn(msg) {
  264. if (verbosity >= VERBOSITY_LEVELS.warnings) {
  265. console.log('Warning: ' + msg);
  266. }
  267. }
  268. function deprecated(details) {
  269. console.log('Deprecated API usage: ' + details);
  270. }
  271. function error(msg) {
  272. if (verbosity >= VERBOSITY_LEVELS.errors) {
  273. console.log('Error: ' + msg);
  274. console.log(backtrace());
  275. }
  276. throw new Error(msg);
  277. }
  278. function backtrace() {
  279. try {
  280. throw new Error();
  281. } catch (e) {
  282. return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
  283. }
  284. }
  285. function assert(cond, msg) {
  286. if (!cond) {
  287. error(msg);
  288. }
  289. }
  290. var UNSUPPORTED_FEATURES = {
  291. unknown: 'unknown',
  292. forms: 'forms',
  293. javaScript: 'javaScript',
  294. smask: 'smask',
  295. shadingPattern: 'shadingPattern',
  296. font: 'font'
  297. };
  298. function isSameOrigin(baseUrl, otherUrl) {
  299. try {
  300. var base = new URL(baseUrl);
  301. if (!base.origin || base.origin === 'null') {
  302. return false;
  303. }
  304. } catch (e) {
  305. return false;
  306. }
  307. var other = new URL(otherUrl, base);
  308. return base.origin === other.origin;
  309. }
  310. function isValidProtocol(url) {
  311. if (!url) {
  312. return false;
  313. }
  314. switch (url.protocol) {
  315. case 'http:':
  316. case 'https:':
  317. case 'ftp:':
  318. case 'mailto:':
  319. case 'tel:':
  320. return true;
  321. default:
  322. return false;
  323. }
  324. }
  325. function createValidAbsoluteUrl(url, baseUrl) {
  326. if (!url) {
  327. return null;
  328. }
  329. try {
  330. var absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
  331. if (isValidProtocol(absoluteUrl)) {
  332. return absoluteUrl;
  333. }
  334. } catch (ex) {
  335. }
  336. return null;
  337. }
  338. function shadow(obj, prop, value) {
  339. Object.defineProperty(obj, prop, {
  340. value: value,
  341. enumerable: true,
  342. configurable: true,
  343. writable: false
  344. });
  345. return value;
  346. }
  347. function getLookupTableFactory(initializer) {
  348. var lookup;
  349. return function () {
  350. if (initializer) {
  351. lookup = Object.create(null);
  352. initializer(lookup);
  353. initializer = null;
  354. }
  355. return lookup;
  356. };
  357. }
  358. var PasswordResponses = {
  359. NEED_PASSWORD: 1,
  360. INCORRECT_PASSWORD: 2
  361. };
  362. var PasswordException = function PasswordExceptionClosure() {
  363. function PasswordException(msg, code) {
  364. this.name = 'PasswordException';
  365. this.message = msg;
  366. this.code = code;
  367. }
  368. PasswordException.prototype = new Error();
  369. PasswordException.constructor = PasswordException;
  370. return PasswordException;
  371. }();
  372. var UnknownErrorException = function UnknownErrorExceptionClosure() {
  373. function UnknownErrorException(msg, details) {
  374. this.name = 'UnknownErrorException';
  375. this.message = msg;
  376. this.details = details;
  377. }
  378. UnknownErrorException.prototype = new Error();
  379. UnknownErrorException.constructor = UnknownErrorException;
  380. return UnknownErrorException;
  381. }();
  382. var InvalidPDFException = function InvalidPDFExceptionClosure() {
  383. function InvalidPDFException(msg) {
  384. this.name = 'InvalidPDFException';
  385. this.message = msg;
  386. }
  387. InvalidPDFException.prototype = new Error();
  388. InvalidPDFException.constructor = InvalidPDFException;
  389. return InvalidPDFException;
  390. }();
  391. var MissingPDFException = function MissingPDFExceptionClosure() {
  392. function MissingPDFException(msg) {
  393. this.name = 'MissingPDFException';
  394. this.message = msg;
  395. }
  396. MissingPDFException.prototype = new Error();
  397. MissingPDFException.constructor = MissingPDFException;
  398. return MissingPDFException;
  399. }();
  400. var UnexpectedResponseException = function UnexpectedResponseExceptionClosure() {
  401. function UnexpectedResponseException(msg, status) {
  402. this.name = 'UnexpectedResponseException';
  403. this.message = msg;
  404. this.status = status;
  405. }
  406. UnexpectedResponseException.prototype = new Error();
  407. UnexpectedResponseException.constructor = UnexpectedResponseException;
  408. return UnexpectedResponseException;
  409. }();
  410. var NotImplementedException = function NotImplementedExceptionClosure() {
  411. function NotImplementedException(msg) {
  412. this.message = msg;
  413. }
  414. NotImplementedException.prototype = new Error();
  415. NotImplementedException.prototype.name = 'NotImplementedException';
  416. NotImplementedException.constructor = NotImplementedException;
  417. return NotImplementedException;
  418. }();
  419. var MissingDataException = function MissingDataExceptionClosure() {
  420. function MissingDataException(begin, end) {
  421. this.begin = begin;
  422. this.end = end;
  423. this.message = 'Missing data [' + begin + ', ' + end + ')';
  424. }
  425. MissingDataException.prototype = new Error();
  426. MissingDataException.prototype.name = 'MissingDataException';
  427. MissingDataException.constructor = MissingDataException;
  428. return MissingDataException;
  429. }();
  430. var XRefParseException = function XRefParseExceptionClosure() {
  431. function XRefParseException(msg) {
  432. this.message = msg;
  433. }
  434. XRefParseException.prototype = new Error();
  435. XRefParseException.prototype.name = 'XRefParseException';
  436. XRefParseException.constructor = XRefParseException;
  437. return XRefParseException;
  438. }();
  439. var NullCharactersRegExp = /\x00/g;
  440. function removeNullCharacters(str) {
  441. if (typeof str !== 'string') {
  442. warn('The argument for removeNullCharacters must be a string.');
  443. return str;
  444. }
  445. return str.replace(NullCharactersRegExp, '');
  446. }
  447. function bytesToString(bytes) {
  448. assert(bytes !== null && typeof bytes === 'object' && bytes.length !== undefined, 'Invalid argument for bytesToString');
  449. var length = bytes.length;
  450. var MAX_ARGUMENT_COUNT = 8192;
  451. if (length < MAX_ARGUMENT_COUNT) {
  452. return String.fromCharCode.apply(null, bytes);
  453. }
  454. var strBuf = [];
  455. for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  456. var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  457. var chunk = bytes.subarray(i, chunkEnd);
  458. strBuf.push(String.fromCharCode.apply(null, chunk));
  459. }
  460. return strBuf.join('');
  461. }
  462. function stringToBytes(str) {
  463. assert(typeof str === 'string', 'Invalid argument for stringToBytes');
  464. var length = str.length;
  465. var bytes = new Uint8Array(length);
  466. for (var i = 0; i < length; ++i) {
  467. bytes[i] = str.charCodeAt(i) & 0xFF;
  468. }
  469. return bytes;
  470. }
  471. function arrayByteLength(arr) {
  472. if (arr.length !== undefined) {
  473. return arr.length;
  474. }
  475. assert(arr.byteLength !== undefined);
  476. return arr.byteLength;
  477. }
  478. function arraysToBytes(arr) {
  479. if (arr.length === 1 && arr[0] instanceof Uint8Array) {
  480. return arr[0];
  481. }
  482. var resultLength = 0;
  483. var i, ii = arr.length;
  484. var item, itemLength;
  485. for (i = 0; i < ii; i++) {
  486. item = arr[i];
  487. itemLength = arrayByteLength(item);
  488. resultLength += itemLength;
  489. }
  490. var pos = 0;
  491. var data = new Uint8Array(resultLength);
  492. for (i = 0; i < ii; i++) {
  493. item = arr[i];
  494. if (!(item instanceof Uint8Array)) {
  495. if (typeof item === 'string') {
  496. item = stringToBytes(item);
  497. } else {
  498. item = new Uint8Array(item);
  499. }
  500. }
  501. itemLength = item.byteLength;
  502. data.set(item, pos);
  503. pos += itemLength;
  504. }
  505. return data;
  506. }
  507. function string32(value) {
  508. return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
  509. }
  510. function log2(x) {
  511. var n = 1, i = 0;
  512. while (x > n) {
  513. n <<= 1;
  514. i++;
  515. }
  516. return i;
  517. }
  518. function readInt8(data, start) {
  519. return data[start] << 24 >> 24;
  520. }
  521. function readUint16(data, offset) {
  522. return data[offset] << 8 | data[offset + 1];
  523. }
  524. function readUint32(data, offset) {
  525. return (data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]) >>> 0;
  526. }
  527. function isLittleEndian() {
  528. var buffer8 = new Uint8Array(2);
  529. buffer8[0] = 1;
  530. var buffer16 = new Uint16Array(buffer8.buffer);
  531. return buffer16[0] === 1;
  532. }
  533. function isEvalSupported() {
  534. try {
  535. new Function('');
  536. return true;
  537. } catch (e) {
  538. return false;
  539. }
  540. }
  541. var Uint32ArrayView = function Uint32ArrayViewClosure() {
  542. function Uint32ArrayView(buffer, length) {
  543. this.buffer = buffer;
  544. this.byteLength = buffer.length;
  545. this.length = length === undefined ? this.byteLength >> 2 : length;
  546. ensureUint32ArrayViewProps(this.length);
  547. }
  548. Uint32ArrayView.prototype = Object.create(null);
  549. var uint32ArrayViewSetters = 0;
  550. function createUint32ArrayProp(index) {
  551. return {
  552. get: function () {
  553. var buffer = this.buffer, offset = index << 2;
  554. return (buffer[offset] | buffer[offset + 1] << 8 | buffer[offset + 2] << 16 | buffer[offset + 3] << 24) >>> 0;
  555. },
  556. set: function (value) {
  557. var buffer = this.buffer, offset = index << 2;
  558. buffer[offset] = value & 255;
  559. buffer[offset + 1] = value >> 8 & 255;
  560. buffer[offset + 2] = value >> 16 & 255;
  561. buffer[offset + 3] = value >>> 24 & 255;
  562. }
  563. };
  564. }
  565. function ensureUint32ArrayViewProps(length) {
  566. while (uint32ArrayViewSetters < length) {
  567. Object.defineProperty(Uint32ArrayView.prototype, uint32ArrayViewSetters, createUint32ArrayProp(uint32ArrayViewSetters));
  568. uint32ArrayViewSetters++;
  569. }
  570. }
  571. return Uint32ArrayView;
  572. }();
  573. exports.Uint32ArrayView = Uint32ArrayView;
  574. var IDENTITY_MATRIX = [
  575. 1,
  576. 0,
  577. 0,
  578. 1,
  579. 0,
  580. 0
  581. ];
  582. var Util = function UtilClosure() {
  583. function Util() {
  584. }
  585. var rgbBuf = [
  586. 'rgb(',
  587. 0,
  588. ',',
  589. 0,
  590. ',',
  591. 0,
  592. ')'
  593. ];
  594. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
  595. rgbBuf[1] = r;
  596. rgbBuf[3] = g;
  597. rgbBuf[5] = b;
  598. return rgbBuf.join('');
  599. };
  600. Util.transform = function Util_transform(m1, m2) {
  601. return [
  602. m1[0] * m2[0] + m1[2] * m2[1],
  603. m1[1] * m2[0] + m1[3] * m2[1],
  604. m1[0] * m2[2] + m1[2] * m2[3],
  605. m1[1] * m2[2] + m1[3] * m2[3],
  606. m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
  607. m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
  608. ];
  609. };
  610. Util.applyTransform = function Util_applyTransform(p, m) {
  611. var xt = p[0] * m[0] + p[1] * m[2] + m[4];
  612. var yt = p[0] * m[1] + p[1] * m[3] + m[5];
  613. return [
  614. xt,
  615. yt
  616. ];
  617. };
  618. Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
  619. var d = m[0] * m[3] - m[1] * m[2];
  620. var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  621. var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  622. return [
  623. xt,
  624. yt
  625. ];
  626. };
  627. Util.getAxialAlignedBoundingBox = function Util_getAxialAlignedBoundingBox(r, m) {
  628. var p1 = Util.applyTransform(r, m);
  629. var p2 = Util.applyTransform(r.slice(2, 4), m);
  630. var p3 = Util.applyTransform([
  631. r[0],
  632. r[3]
  633. ], m);
  634. var p4 = Util.applyTransform([
  635. r[2],
  636. r[1]
  637. ], m);
  638. return [
  639. Math.min(p1[0], p2[0], p3[0], p4[0]),
  640. Math.min(p1[1], p2[1], p3[1], p4[1]),
  641. Math.max(p1[0], p2[0], p3[0], p4[0]),
  642. Math.max(p1[1], p2[1], p3[1], p4[1])
  643. ];
  644. };
  645. Util.inverseTransform = function Util_inverseTransform(m) {
  646. var d = m[0] * m[3] - m[1] * m[2];
  647. return [
  648. m[3] / d,
  649. -m[1] / d,
  650. -m[2] / d,
  651. m[0] / d,
  652. (m[2] * m[5] - m[4] * m[3]) / d,
  653. (m[4] * m[1] - m[5] * m[0]) / d
  654. ];
  655. };
  656. Util.apply3dTransform = function Util_apply3dTransform(m, v) {
  657. return [
  658. m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
  659. m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
  660. m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
  661. ];
  662. };
  663. Util.singularValueDecompose2dScale = function Util_singularValueDecompose2dScale(m) {
  664. var transpose = [
  665. m[0],
  666. m[2],
  667. m[1],
  668. m[3]
  669. ];
  670. var a = m[0] * transpose[0] + m[1] * transpose[2];
  671. var b = m[0] * transpose[1] + m[1] * transpose[3];
  672. var c = m[2] * transpose[0] + m[3] * transpose[2];
  673. var d = m[2] * transpose[1] + m[3] * transpose[3];
  674. var first = (a + d) / 2;
  675. var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
  676. var sx = first + second || 1;
  677. var sy = first - second || 1;
  678. return [
  679. Math.sqrt(sx),
  680. Math.sqrt(sy)
  681. ];
  682. };
  683. Util.normalizeRect = function Util_normalizeRect(rect) {
  684. var r = rect.slice(0);
  685. if (rect[0] > rect[2]) {
  686. r[0] = rect[2];
  687. r[2] = rect[0];
  688. }
  689. if (rect[1] > rect[3]) {
  690. r[1] = rect[3];
  691. r[3] = rect[1];
  692. }
  693. return r;
  694. };
  695. Util.intersect = function Util_intersect(rect1, rect2) {
  696. function compare(a, b) {
  697. return a - b;
  698. }
  699. var orderedX = [
  700. rect1[0],
  701. rect1[2],
  702. rect2[0],
  703. rect2[2]
  704. ].sort(compare), orderedY = [
  705. rect1[1],
  706. rect1[3],
  707. rect2[1],
  708. rect2[3]
  709. ].sort(compare), result = [];
  710. rect1 = Util.normalizeRect(rect1);
  711. rect2 = Util.normalizeRect(rect2);
  712. if (orderedX[0] === rect1[0] && orderedX[1] === rect2[0] || orderedX[0] === rect2[0] && orderedX[1] === rect1[0]) {
  713. result[0] = orderedX[1];
  714. result[2] = orderedX[2];
  715. } else {
  716. return false;
  717. }
  718. if (orderedY[0] === rect1[1] && orderedY[1] === rect2[1] || orderedY[0] === rect2[1] && orderedY[1] === rect1[1]) {
  719. result[1] = orderedY[1];
  720. result[3] = orderedY[2];
  721. } else {
  722. return false;
  723. }
  724. return result;
  725. };
  726. Util.sign = function Util_sign(num) {
  727. return num < 0 ? -1 : 1;
  728. };
  729. var ROMAN_NUMBER_MAP = [
  730. '',
  731. 'C',
  732. 'CC',
  733. 'CCC',
  734. 'CD',
  735. 'D',
  736. 'DC',
  737. 'DCC',
  738. 'DCCC',
  739. 'CM',
  740. '',
  741. 'X',
  742. 'XX',
  743. 'XXX',
  744. 'XL',
  745. 'L',
  746. 'LX',
  747. 'LXX',
  748. 'LXXX',
  749. 'XC',
  750. '',
  751. 'I',
  752. 'II',
  753. 'III',
  754. 'IV',
  755. 'V',
  756. 'VI',
  757. 'VII',
  758. 'VIII',
  759. 'IX'
  760. ];
  761. Util.toRoman = function Util_toRoman(number, lowerCase) {
  762. assert(isInt(number) && number > 0, 'The number should be a positive integer.');
  763. var pos, romanBuf = [];
  764. while (number >= 1000) {
  765. number -= 1000;
  766. romanBuf.push('M');
  767. }
  768. pos = number / 100 | 0;
  769. number %= 100;
  770. romanBuf.push(ROMAN_NUMBER_MAP[pos]);
  771. pos = number / 10 | 0;
  772. number %= 10;
  773. romanBuf.push(ROMAN_NUMBER_MAP[10 + pos]);
  774. romanBuf.push(ROMAN_NUMBER_MAP[20 + number]);
  775. var romanStr = romanBuf.join('');
  776. return lowerCase ? romanStr.toLowerCase() : romanStr;
  777. };
  778. Util.appendToArray = function Util_appendToArray(arr1, arr2) {
  779. Array.prototype.push.apply(arr1, arr2);
  780. };
  781. Util.prependToArray = function Util_prependToArray(arr1, arr2) {
  782. Array.prototype.unshift.apply(arr1, arr2);
  783. };
  784. Util.extendObj = function extendObj(obj1, obj2) {
  785. for (var key in obj2) {
  786. obj1[key] = obj2[key];
  787. }
  788. };
  789. Util.getInheritableProperty = function Util_getInheritableProperty(dict, name, getArray) {
  790. while (dict && !dict.has(name)) {
  791. dict = dict.get('Parent');
  792. }
  793. if (!dict) {
  794. return null;
  795. }
  796. return getArray ? dict.getArray(name) : dict.get(name);
  797. };
  798. Util.inherit = function Util_inherit(sub, base, prototype) {
  799. sub.prototype = Object.create(base.prototype);
  800. sub.prototype.constructor = sub;
  801. for (var prop in prototype) {
  802. sub.prototype[prop] = prototype[prop];
  803. }
  804. };
  805. Util.loadScript = function Util_loadScript(src, callback) {
  806. var script = document.createElement('script');
  807. var loaded = false;
  808. script.setAttribute('src', src);
  809. if (callback) {
  810. script.onload = function () {
  811. if (!loaded) {
  812. callback();
  813. }
  814. loaded = true;
  815. };
  816. }
  817. document.getElementsByTagName('head')[0].appendChild(script);
  818. };
  819. return Util;
  820. }();
  821. var PageViewport = function PageViewportClosure() {
  822. function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
  823. this.viewBox = viewBox;
  824. this.scale = scale;
  825. this.rotation = rotation;
  826. this.offsetX = offsetX;
  827. this.offsetY = offsetY;
  828. var centerX = (viewBox[2] + viewBox[0]) / 2;
  829. var centerY = (viewBox[3] + viewBox[1]) / 2;
  830. var rotateA, rotateB, rotateC, rotateD;
  831. rotation = rotation % 360;
  832. rotation = rotation < 0 ? rotation + 360 : rotation;
  833. switch (rotation) {
  834. case 180:
  835. rotateA = -1;
  836. rotateB = 0;
  837. rotateC = 0;
  838. rotateD = 1;
  839. break;
  840. case 90:
  841. rotateA = 0;
  842. rotateB = 1;
  843. rotateC = 1;
  844. rotateD = 0;
  845. break;
  846. case 270:
  847. rotateA = 0;
  848. rotateB = -1;
  849. rotateC = -1;
  850. rotateD = 0;
  851. break;
  852. default:
  853. rotateA = 1;
  854. rotateB = 0;
  855. rotateC = 0;
  856. rotateD = -1;
  857. break;
  858. }
  859. if (dontFlip) {
  860. rotateC = -rotateC;
  861. rotateD = -rotateD;
  862. }
  863. var offsetCanvasX, offsetCanvasY;
  864. var width, height;
  865. if (rotateA === 0) {
  866. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  867. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  868. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  869. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  870. } else {
  871. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  872. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  873. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  874. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  875. }
  876. this.transform = [
  877. rotateA * scale,
  878. rotateB * scale,
  879. rotateC * scale,
  880. rotateD * scale,
  881. offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
  882. offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
  883. ];
  884. this.width = width;
  885. this.height = height;
  886. this.fontScale = scale;
  887. }
  888. PageViewport.prototype = {
  889. clone: function PageViewPort_clone(args) {
  890. args = args || {};
  891. var scale = 'scale' in args ? args.scale : this.scale;
  892. var rotation = 'rotation' in args ? args.rotation : this.rotation;
  893. return new PageViewport(this.viewBox.slice(), scale, rotation, this.offsetX, this.offsetY, args.dontFlip);
  894. },
  895. convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
  896. return Util.applyTransform([
  897. x,
  898. y
  899. ], this.transform);
  900. },
  901. convertToViewportRectangle: function PageViewport_convertToViewportRectangle(rect) {
  902. var tl = Util.applyTransform([
  903. rect[0],
  904. rect[1]
  905. ], this.transform);
  906. var br = Util.applyTransform([
  907. rect[2],
  908. rect[3]
  909. ], this.transform);
  910. return [
  911. tl[0],
  912. tl[1],
  913. br[0],
  914. br[1]
  915. ];
  916. },
  917. convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
  918. return Util.applyInverseTransform([
  919. x,
  920. y
  921. ], this.transform);
  922. }
  923. };
  924. return PageViewport;
  925. }();
  926. var PDFStringTranslateTable = [
  927. 0,
  928. 0,
  929. 0,
  930. 0,
  931. 0,
  932. 0,
  933. 0,
  934. 0,
  935. 0,
  936. 0,
  937. 0,
  938. 0,
  939. 0,
  940. 0,
  941. 0,
  942. 0,
  943. 0,
  944. 0,
  945. 0,
  946. 0,
  947. 0,
  948. 0,
  949. 0,
  950. 0,
  951. 0x2D8,
  952. 0x2C7,
  953. 0x2C6,
  954. 0x2D9,
  955. 0x2DD,
  956. 0x2DB,
  957. 0x2DA,
  958. 0x2DC,
  959. 0,
  960. 0,
  961. 0,
  962. 0,
  963. 0,
  964. 0,
  965. 0,
  966. 0,
  967. 0,
  968. 0,
  969. 0,
  970. 0,
  971. 0,
  972. 0,
  973. 0,
  974. 0,
  975. 0,
  976. 0,
  977. 0,
  978. 0,
  979. 0,
  980. 0,
  981. 0,
  982. 0,
  983. 0,
  984. 0,
  985. 0,
  986. 0,
  987. 0,
  988. 0,
  989. 0,
  990. 0,
  991. 0,
  992. 0,
  993. 0,
  994. 0,
  995. 0,
  996. 0,
  997. 0,
  998. 0,
  999. 0,
  1000. 0,
  1001. 0,
  1002. 0,
  1003. 0,
  1004. 0,
  1005. 0,
  1006. 0,
  1007. 0,
  1008. 0,
  1009. 0,
  1010. 0,
  1011. 0,
  1012. 0,
  1013. 0,
  1014. 0,
  1015. 0,
  1016. 0,
  1017. 0,
  1018. 0,
  1019. 0,
  1020. 0,
  1021. 0,
  1022. 0,
  1023. 0,
  1024. 0,
  1025. 0,
  1026. 0,
  1027. 0,
  1028. 0,
  1029. 0,
  1030. 0,
  1031. 0,
  1032. 0,
  1033. 0,
  1034. 0,
  1035. 0,
  1036. 0,
  1037. 0,
  1038. 0,
  1039. 0,
  1040. 0,
  1041. 0,
  1042. 0,
  1043. 0,
  1044. 0,
  1045. 0,
  1046. 0,
  1047. 0,
  1048. 0,
  1049. 0,
  1050. 0,
  1051. 0,
  1052. 0,
  1053. 0,
  1054. 0,
  1055. 0x2022,
  1056. 0x2020,
  1057. 0x2021,
  1058. 0x2026,
  1059. 0x2014,
  1060. 0x2013,
  1061. 0x192,
  1062. 0x2044,
  1063. 0x2039,
  1064. 0x203A,
  1065. 0x2212,
  1066. 0x2030,
  1067. 0x201E,
  1068. 0x201C,
  1069. 0x201D,
  1070. 0x2018,
  1071. 0x2019,
  1072. 0x201A,
  1073. 0x2122,
  1074. 0xFB01,
  1075. 0xFB02,
  1076. 0x141,
  1077. 0x152,
  1078. 0x160,
  1079. 0x178,
  1080. 0x17D,
  1081. 0x131,
  1082. 0x142,
  1083. 0x153,
  1084. 0x161,
  1085. 0x17E,
  1086. 0,
  1087. 0x20AC
  1088. ];
  1089. function stringToPDFString(str) {
  1090. var i, n = str.length, strBuf = [];
  1091. if (str[0] === '\xFE' && str[1] === '\xFF') {
  1092. for (i = 2; i < n; i += 2) {
  1093. strBuf.push(String.fromCharCode(str.charCodeAt(i) << 8 | str.charCodeAt(i + 1)));
  1094. }
  1095. } else {
  1096. for (i = 0; i < n; ++i) {
  1097. var code = PDFStringTranslateTable[str.charCodeAt(i)];
  1098. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  1099. }
  1100. }
  1101. return strBuf.join('');
  1102. }
  1103. function stringToUTF8String(str) {
  1104. return decodeURIComponent(escape(str));
  1105. }
  1106. function utf8StringToString(str) {
  1107. return unescape(encodeURIComponent(str));
  1108. }
  1109. function isEmptyObj(obj) {
  1110. for (var key in obj) {
  1111. return false;
  1112. }
  1113. return true;
  1114. }
  1115. function isBool(v) {
  1116. return typeof v === 'boolean';
  1117. }
  1118. function isInt(v) {
  1119. return typeof v === 'number' && (v | 0) === v;
  1120. }
  1121. function isNum(v) {
  1122. return typeof v === 'number';
  1123. }
  1124. function isString(v) {
  1125. return typeof v === 'string';
  1126. }
  1127. function isArray(v) {
  1128. return v instanceof Array;
  1129. }
  1130. function isArrayBuffer(v) {
  1131. return typeof v === 'object' && v !== null && v.byteLength !== undefined;
  1132. }
  1133. function isSpace(ch) {
  1134. return ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A;
  1135. }
  1136. function createPromiseCapability() {
  1137. var capability = {};
  1138. capability.promise = new Promise(function (resolve, reject) {
  1139. capability.resolve = resolve;
  1140. capability.reject = reject;
  1141. });
  1142. return capability;
  1143. }
  1144. (function PromiseClosure() {
  1145. if (globalScope.Promise) {
  1146. if (typeof globalScope.Promise.all !== 'function') {
  1147. globalScope.Promise.all = function (iterable) {
  1148. var count = 0, results = [], resolve, reject;
  1149. var promise = new globalScope.Promise(function (resolve_, reject_) {
  1150. resolve = resolve_;
  1151. reject = reject_;
  1152. });
  1153. iterable.forEach(function (p, i) {
  1154. count++;
  1155. p.then(function (result) {
  1156. results[i] = result;
  1157. count--;
  1158. if (count === 0) {
  1159. resolve(results);
  1160. }
  1161. }, reject);
  1162. });
  1163. if (count === 0) {
  1164. resolve(results);
  1165. }
  1166. return promise;
  1167. };
  1168. }
  1169. if (typeof globalScope.Promise.resolve !== 'function') {
  1170. globalScope.Promise.resolve = function (value) {
  1171. return new globalScope.Promise(function (resolve) {
  1172. resolve(value);
  1173. });
  1174. };
  1175. }
  1176. if (typeof globalScope.Promise.reject !== 'function') {
  1177. globalScope.Promise.reject = function (reason) {
  1178. return new globalScope.Promise(function (resolve, reject) {
  1179. reject(reason);
  1180. });
  1181. };
  1182. }
  1183. if (typeof globalScope.Promise.prototype.catch !== 'function') {
  1184. globalScope.Promise.prototype.catch = function (onReject) {
  1185. return globalScope.Promise.prototype.then(undefined, onReject);
  1186. };
  1187. }
  1188. return;
  1189. }
  1190. var STATUS_PENDING = 0;
  1191. var STATUS_RESOLVED = 1;
  1192. var STATUS_REJECTED = 2;
  1193. var REJECTION_TIMEOUT = 500;
  1194. var HandlerManager = {
  1195. handlers: [],
  1196. running: false,
  1197. unhandledRejections: [],
  1198. pendingRejectionCheck: false,
  1199. scheduleHandlers: function scheduleHandlers(promise) {
  1200. if (promise._status === STATUS_PENDING) {
  1201. return;
  1202. }
  1203. this.handlers = this.handlers.concat(promise._handlers);
  1204. promise._handlers = [];
  1205. if (this.running) {
  1206. return;
  1207. }
  1208. this.running = true;
  1209. setTimeout(this.runHandlers.bind(this), 0);
  1210. },
  1211. runHandlers: function runHandlers() {
  1212. var RUN_TIMEOUT = 1;
  1213. var timeoutAt = Date.now() + RUN_TIMEOUT;
  1214. while (this.handlers.length > 0) {
  1215. var handler = this.handlers.shift();
  1216. var nextStatus = handler.thisPromise._status;
  1217. var nextValue = handler.thisPromise._value;
  1218. try {
  1219. if (nextStatus === STATUS_RESOLVED) {
  1220. if (typeof handler.onResolve === 'function') {
  1221. nextValue = handler.onResolve(nextValue);
  1222. }
  1223. } else if (typeof handler.onReject === 'function') {
  1224. nextValue = handler.onReject(nextValue);
  1225. nextStatus = STATUS_RESOLVED;
  1226. if (handler.thisPromise._unhandledRejection) {
  1227. this.removeUnhandeledRejection(handler.thisPromise);
  1228. }
  1229. }
  1230. } catch (ex) {
  1231. nextStatus = STATUS_REJECTED;
  1232. nextValue = ex;
  1233. }
  1234. handler.nextPromise._updateStatus(nextStatus, nextValue);
  1235. if (Date.now() >= timeoutAt) {
  1236. break;
  1237. }
  1238. }
  1239. if (this.handlers.length > 0) {
  1240. setTimeout(this.runHandlers.bind(this), 0);
  1241. return;
  1242. }
  1243. this.running = false;
  1244. },
  1245. addUnhandledRejection: function addUnhandledRejection(promise) {
  1246. this.unhandledRejections.push({
  1247. promise: promise,
  1248. time: Date.now()
  1249. });
  1250. this.scheduleRejectionCheck();
  1251. },
  1252. removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
  1253. promise._unhandledRejection = false;
  1254. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1255. if (this.unhandledRejections[i].promise === promise) {
  1256. this.unhandledRejections.splice(i);
  1257. i--;
  1258. }
  1259. }
  1260. },
  1261. scheduleRejectionCheck: function scheduleRejectionCheck() {
  1262. if (this.pendingRejectionCheck) {
  1263. return;
  1264. }
  1265. this.pendingRejectionCheck = true;
  1266. setTimeout(function rejectionCheck() {
  1267. this.pendingRejectionCheck = false;
  1268. var now = Date.now();
  1269. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1270. if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
  1271. var unhandled = this.unhandledRejections[i].promise._value;
  1272. var msg = 'Unhandled rejection: ' + unhandled;
  1273. if (unhandled.stack) {
  1274. msg += '\n' + unhandled.stack;
  1275. }
  1276. warn(msg);
  1277. this.unhandledRejections.splice(i);
  1278. i--;
  1279. }
  1280. }
  1281. if (this.unhandledRejections.length) {
  1282. this.scheduleRejectionCheck();
  1283. }
  1284. }.bind(this), REJECTION_TIMEOUT);
  1285. }
  1286. };
  1287. var Promise = function Promise(resolver) {
  1288. this._status = STATUS_PENDING;
  1289. this._handlers = [];
  1290. try {
  1291. resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
  1292. } catch (e) {
  1293. this._reject(e);
  1294. }
  1295. };
  1296. Promise.all = function Promise_all(promises) {
  1297. var resolveAll, rejectAll;
  1298. var deferred = new Promise(function (resolve, reject) {
  1299. resolveAll = resolve;
  1300. rejectAll = reject;
  1301. });
  1302. var unresolved = promises.length;
  1303. var results = [];
  1304. if (unresolved === 0) {
  1305. resolveAll(results);
  1306. return deferred;
  1307. }
  1308. function reject(reason) {
  1309. if (deferred._status === STATUS_REJECTED) {
  1310. return;
  1311. }
  1312. results = [];
  1313. rejectAll(reason);
  1314. }
  1315. for (var i = 0, ii = promises.length; i < ii; ++i) {
  1316. var promise = promises[i];
  1317. var resolve = function (i) {
  1318. return function (value) {
  1319. if (deferred._status === STATUS_REJECTED) {
  1320. return;
  1321. }
  1322. results[i] = value;
  1323. unresolved--;
  1324. if (unresolved === 0) {
  1325. resolveAll(results);
  1326. }
  1327. };
  1328. }(i);
  1329. if (Promise.isPromise(promise)) {
  1330. promise.then(resolve, reject);
  1331. } else {
  1332. resolve(promise);
  1333. }
  1334. }
  1335. return deferred;
  1336. };
  1337. Promise.isPromise = function Promise_isPromise(value) {
  1338. return value && typeof value.then === 'function';
  1339. };
  1340. Promise.resolve = function Promise_resolve(value) {
  1341. return new Promise(function (resolve) {
  1342. resolve(value);
  1343. });
  1344. };
  1345. Promise.reject = function Promise_reject(reason) {
  1346. return new Promise(function (resolve, reject) {
  1347. reject(reason);
  1348. });
  1349. };
  1350. Promise.prototype = {
  1351. _status: null,
  1352. _value: null,
  1353. _handlers: null,
  1354. _unhandledRejection: null,
  1355. _updateStatus: function Promise__updateStatus(status, value) {
  1356. if (this._status === STATUS_RESOLVED || this._status === STATUS_REJECTED) {
  1357. return;
  1358. }
  1359. if (status === STATUS_RESOLVED && Promise.isPromise(value)) {
  1360. value.then(this._updateStatus.bind(this, STATUS_RESOLVED), this._updateStatus.bind(this, STATUS_REJECTED));
  1361. return;
  1362. }
  1363. this._status = status;
  1364. this._value = value;
  1365. if (status === STATUS_REJECTED && this._handlers.length === 0) {
  1366. this._unhandledRejection = true;
  1367. HandlerManager.addUnhandledRejection(this);
  1368. }
  1369. HandlerManager.scheduleHandlers(this);
  1370. },
  1371. _resolve: function Promise_resolve(value) {
  1372. this._updateStatus(STATUS_RESOLVED, value);
  1373. },
  1374. _reject: function Promise_reject(reason) {
  1375. this._updateStatus(STATUS_REJECTED, reason);
  1376. },
  1377. then: function Promise_then(onResolve, onReject) {
  1378. var nextPromise = new Promise(function (resolve, reject) {
  1379. this.resolve = resolve;
  1380. this.reject = reject;
  1381. });
  1382. this._handlers.push({
  1383. thisPromise: this,
  1384. onResolve: onResolve,
  1385. onReject: onReject,
  1386. nextPromise: nextPromise
  1387. });
  1388. HandlerManager.scheduleHandlers(this);
  1389. return nextPromise;
  1390. },
  1391. catch: function Promise_catch(onReject) {
  1392. return this.then(undefined, onReject);
  1393. }
  1394. };
  1395. globalScope.Promise = Promise;
  1396. }());
  1397. (function WeakMapClosure() {
  1398. if (globalScope.WeakMap) {
  1399. return;
  1400. }
  1401. var id = 0;
  1402. function WeakMap() {
  1403. this.id = '$weakmap' + id++;
  1404. }
  1405. WeakMap.prototype = {
  1406. has: function (obj) {
  1407. return !!Object.getOwnPropertyDescriptor(obj, this.id);
  1408. },
  1409. get: function (obj, defaultValue) {
  1410. return this.has(obj) ? obj[this.id] : defaultValue;
  1411. },
  1412. set: function (obj, value) {
  1413. Object.defineProperty(obj, this.id, {
  1414. value: value,
  1415. enumerable: false,
  1416. configurable: true
  1417. });
  1418. },
  1419. delete: function (obj) {
  1420. delete obj[this.id];
  1421. }
  1422. };
  1423. globalScope.WeakMap = WeakMap;
  1424. }());
  1425. var StatTimer = function StatTimerClosure() {
  1426. function rpad(str, pad, length) {
  1427. while (str.length < length) {
  1428. str += pad;
  1429. }
  1430. return str;
  1431. }
  1432. function StatTimer() {
  1433. this.started = Object.create(null);
  1434. this.times = [];
  1435. this.enabled = true;
  1436. }
  1437. StatTimer.prototype = {
  1438. time: function StatTimer_time(name) {
  1439. if (!this.enabled) {
  1440. return;
  1441. }
  1442. if (name in this.started) {
  1443. warn('Timer is already running for ' + name);
  1444. }
  1445. this.started[name] = Date.now();
  1446. },
  1447. timeEnd: function StatTimer_timeEnd(name) {
  1448. if (!this.enabled) {
  1449. return;
  1450. }
  1451. if (!(name in this.started)) {
  1452. warn('Timer has not been started for ' + name);
  1453. }
  1454. this.times.push({
  1455. 'name': name,
  1456. 'start': this.started[name],
  1457. 'end': Date.now()
  1458. });
  1459. delete this.started[name];
  1460. },
  1461. toString: function StatTimer_toString() {
  1462. var i, ii;
  1463. var times = this.times;
  1464. var out = '';
  1465. var longest = 0;
  1466. for (i = 0, ii = times.length; i < ii; ++i) {
  1467. var name = times[i]['name'];
  1468. if (name.length > longest) {
  1469. longest = name.length;
  1470. }
  1471. }
  1472. for (i = 0, ii = times.length; i < ii; ++i) {
  1473. var span = times[i];
  1474. var duration = span.end - span.start;
  1475. out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
  1476. }
  1477. return out;
  1478. }
  1479. };
  1480. return StatTimer;
  1481. }();
  1482. var createBlob = function createBlob(data, contentType) {
  1483. if (typeof Blob !== 'undefined') {
  1484. return new Blob([data], { type: contentType });
  1485. }
  1486. warn('The "Blob" constructor is not supported.');
  1487. };
  1488. var createObjectURL = function createObjectURLClosure() {
  1489. var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1490. return function createObjectURL(data, contentType, forceDataSchema) {
  1491. if (!forceDataSchema && typeof URL !== 'undefined' && URL.createObjectURL) {
  1492. var blob = createBlob(data, contentType);
  1493. return URL.createObjectURL(blob);
  1494. }
  1495. var buffer = 'data:' + contentType + ';base64,';
  1496. for (var i = 0, ii = data.length; i < ii; i += 3) {
  1497. var b1 = data[i] & 0xFF;
  1498. var b2 = data[i + 1] & 0xFF;
  1499. var b3 = data[i + 2] & 0xFF;
  1500. var d1 = b1 >> 2, d2 = (b1 & 3) << 4 | b2 >> 4;
  1501. var d3 = i + 1 < ii ? (b2 & 0xF) << 2 | b3 >> 6 : 64;
  1502. var d4 = i + 2 < ii ? b3 & 0x3F : 64;
  1503. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1504. }
  1505. return buffer;
  1506. };
  1507. }();
  1508. function MessageHandler(sourceName, targetName, comObj) {
  1509. this.sourceName = sourceName;
  1510. this.targetName = targetName;
  1511. this.comObj = comObj;
  1512. this.callbackIndex = 1;
  1513. this.postMessageTransfers = true;
  1514. var callbacksCapabilities = this.callbacksCapabilities = Object.create(null);
  1515. var ah = this.actionHandler = Object.create(null);
  1516. this._onComObjOnMessage = function messageHandlerComObjOnMessage(event) {
  1517. var data = event.data;
  1518. if (data.targetName !== this.sourceName) {
  1519. return;
  1520. }
  1521. if (data.isReply) {
  1522. var callbackId = data.callbackId;
  1523. if (data.callbackId in callbacksCapabilities) {
  1524. var callback = callbacksCapabilities[callbackId];
  1525. delete callbacksCapabilities[callbackId];
  1526. if ('error' in data) {
  1527. callback.reject(data.error);
  1528. } else {
  1529. callback.resolve(data.data);
  1530. }
  1531. } else {
  1532. error('Cannot resolve callback ' + callbackId);
  1533. }
  1534. } else if (data.action in ah) {
  1535. var action = ah[data.action];
  1536. if (data.callbackId) {
  1537. var sourceName = this.sourceName;
  1538. var targetName = data.sourceName;
  1539. Promise.resolve().then(function () {
  1540. return action[0].call(action[1], data.data);
  1541. }).then(function (result) {
  1542. comObj.postMessage({
  1543. sourceName: sourceName,
  1544. targetName: targetName,
  1545. isReply: true,
  1546. callbackId: data.callbackId,
  1547. data: result
  1548. });
  1549. }, function (reason) {
  1550. if (reason instanceof Error) {
  1551. reason = reason + '';
  1552. }
  1553. comObj.postMessage({
  1554. sourceName: sourceName,
  1555. targetName: targetName,
  1556. isReply: true,
  1557. callbackId: data.callbackId,
  1558. error: reason
  1559. });
  1560. });
  1561. } else {
  1562. action[0].call(action[1], data.data);
  1563. }
  1564. } else {
  1565. error('Unknown action from worker: ' + data.action);
  1566. }
  1567. }.bind(this);
  1568. comObj.addEventListener('message', this._onComObjOnMessage);
  1569. }
  1570. MessageHandler.prototype = {
  1571. on: function messageHandlerOn(actionName, handler, scope) {
  1572. var ah = this.actionHandler;
  1573. if (ah[actionName]) {
  1574. error('There is already an actionName called "' + actionName + '"');
  1575. }
  1576. ah[actionName] = [
  1577. handler,
  1578. scope
  1579. ];
  1580. },
  1581. send: function messageHandlerSend(actionName, data, transfers) {
  1582. var message = {
  1583. sourceName: this.sourceName,
  1584. targetName: this.targetName,
  1585. action: actionName,
  1586. data: data
  1587. };
  1588. this.postMessage(message, transfers);
  1589. },
  1590. sendWithPromise: function messageHandlerSendWithPromise(actionName, data, transfers) {
  1591. var callbackId = this.callbackIndex++;
  1592. var message = {
  1593. sourceName: this.sourceName,
  1594. targetName: this.targetName,
  1595. action: actionName,
  1596. data: data,
  1597. callbackId: callbackId
  1598. };
  1599. var capability = createPromiseCapability();
  1600. this.callbacksCapabilities[callbackId] = capability;
  1601. try {
  1602. this.postMessage(message, transfers);
  1603. } catch (e) {
  1604. capability.reject(e);
  1605. }
  1606. return capability.promise;
  1607. },
  1608. postMessage: function (message, transfers) {
  1609. if (transfers && this.postMessageTransfers) {
  1610. this.comObj.postMessage(message, transfers);
  1611. } else {
  1612. this.comObj.postMessage(message);
  1613. }
  1614. },
  1615. destroy: function () {
  1616. this.comObj.removeEventListener('message', this._onComObjOnMessage);
  1617. }
  1618. };
  1619. function loadJpegStream(id, imageUrl, objs) {
  1620. var img = new Image();
  1621. img.onload = function loadJpegStream_onloadClosure() {
  1622. objs.resolve(id, img);
  1623. };
  1624. img.onerror = function loadJpegStream_onerrorClosure() {
  1625. objs.resolve(id, null);
  1626. warn('Error during JPEG image loading');
  1627. };
  1628. img.src = imageUrl;
  1629. }
  1630. /* Any copyright is dedicated to the Public Domain.
  1631. * http://creativecommons.org/publicdomain/zero/1.0/ */
  1632. (function checkURLConstructor(scope) {
  1633. var hasWorkingUrl = false;
  1634. try {
  1635. if (typeof URL === 'function' && typeof URL.prototype === 'object' && 'origin' in URL.prototype) {
  1636. var u = new URL('b', 'http://a');
  1637. u.pathname = 'c%20d';
  1638. hasWorkingUrl = u.href === 'http://a/c%20d';
  1639. }
  1640. } catch (e) {
  1641. }
  1642. if (hasWorkingUrl) {
  1643. return;
  1644. }
  1645. var relative = Object.create(null);
  1646. relative['ftp'] = 21;
  1647. relative['file'] = 0;
  1648. relative['gopher'] = 70;
  1649. relative['http'] = 80;
  1650. relative['https'] = 443;
  1651. relative['ws'] = 80;
  1652. relative['wss'] = 443;
  1653. var relativePathDotMapping = Object.create(null);
  1654. relativePathDotMapping['%2e'] = '.';
  1655. relativePathDotMapping['.%2e'] = '..';
  1656. relativePathDotMapping['%2e.'] = '..';
  1657. relativePathDotMapping['%2e%2e'] = '..';
  1658. function isRelativeScheme(scheme) {
  1659. return relative[scheme] !== undefined;
  1660. }
  1661. function invalid() {
  1662. clear.call(this);
  1663. this._isInvalid = true;
  1664. }
  1665. function IDNAToASCII(h) {
  1666. if (h === '') {
  1667. invalid.call(this);
  1668. }
  1669. return h.toLowerCase();
  1670. }
  1671. function percentEscape(c) {
  1672. var unicode = c.charCodeAt(0);
  1673. if (unicode > 0x20 && unicode < 0x7F && [
  1674. 0x22,
  1675. 0x23,
  1676. 0x3C,
  1677. 0x3E,
  1678. 0x3F,
  1679. 0x60
  1680. ].indexOf(unicode) === -1) {
  1681. return c;
  1682. }
  1683. return encodeURIComponent(c);
  1684. }
  1685. function percentEscapeQuery(c) {
  1686. var unicode = c.charCodeAt(0);
  1687. if (unicode > 0x20 && unicode < 0x7F && [
  1688. 0x22,
  1689. 0x23,
  1690. 0x3C,
  1691. 0x3E,
  1692. 0x60
  1693. ].indexOf(unicode) === -1) {
  1694. return c;
  1695. }
  1696. return encodeURIComponent(c);
  1697. }
  1698. var EOF, ALPHA = /[a-zA-Z]/, ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/;
  1699. function parse(input, stateOverride, base) {
  1700. function err(message) {
  1701. errors.push(message);
  1702. }
  1703. var state = stateOverride || 'scheme start', cursor = 0, buffer = '', seenAt = false, seenBracket = false, errors = [];
  1704. loop:
  1705. while ((input[cursor - 1] !== EOF || cursor === 0) && !this._isInvalid) {
  1706. var c = input[cursor];
  1707. switch (state) {
  1708. case 'scheme start':
  1709. if (c && ALPHA.test(c)) {
  1710. buffer += c.toLowerCase();
  1711. state = 'scheme';
  1712. } else if (!stateOverride) {
  1713. buffer = '';
  1714. state = 'no scheme';
  1715. continue;
  1716. } else {
  1717. err('Invalid scheme.');
  1718. break loop;
  1719. }
  1720. break;
  1721. case 'scheme':
  1722. if (c && ALPHANUMERIC.test(c)) {
  1723. buffer += c.toLowerCase();
  1724. } else if (c === ':') {
  1725. this._scheme = buffer;
  1726. buffer = '';
  1727. if (stateOverride) {
  1728. break loop;
  1729. }
  1730. if (isRelativeScheme(this._scheme)) {
  1731. this._isRelative = true;
  1732. }
  1733. if (this._scheme === 'file') {
  1734. state = 'relative';
  1735. } else if (this._isRelative && base && base._scheme === this._scheme) {
  1736. state = 'relative or authority';
  1737. } else if (this._isRelative) {
  1738. state = 'authority first slash';
  1739. } else {
  1740. state = 'scheme data';
  1741. }
  1742. } else if (!stateOverride) {
  1743. buffer = '';
  1744. cursor = 0;
  1745. state = 'no scheme';
  1746. continue;
  1747. } else if (EOF === c) {
  1748. break loop;
  1749. } else {
  1750. err('Code point not allowed in scheme: ' + c);
  1751. break loop;
  1752. }
  1753. break;
  1754. case 'scheme data':
  1755. if (c === '?') {
  1756. this._query = '?';
  1757. state = 'query';
  1758. } else if (c === '#') {
  1759. this._fragment = '#';
  1760. state = 'fragment';
  1761. } else {
  1762. if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  1763. this._schemeData += percentEscape(c);
  1764. }
  1765. }
  1766. break;
  1767. case 'no scheme':
  1768. if (!base || !isRelativeScheme(base._scheme)) {
  1769. err('Missing scheme.');
  1770. invalid.call(this);
  1771. } else {
  1772. state = 'relative';
  1773. continue;
  1774. }
  1775. break;
  1776. case 'relative or authority':
  1777. if (c === '/' && input[cursor + 1] === '/') {
  1778. state = 'authority ignore slashes';
  1779. } else {
  1780. err('Expected /, got: ' + c);
  1781. state = 'relative';
  1782. continue;
  1783. }
  1784. break;
  1785. case 'relative':
  1786. this._isRelative = true;
  1787. if ('file' !== this._scheme) {
  1788. this._scheme = base._scheme;
  1789. }
  1790. if (EOF === c) {
  1791. this._host = base._host;
  1792. this._port = base._port;
  1793. this._path = base._path.slice();
  1794. this._query = base._query;
  1795. this._username = base._username;
  1796. this._password = base._password;
  1797. break loop;
  1798. } else if (c === '/' || c === '\\') {
  1799. if (c === '\\') {
  1800. err('\\ is an invalid code point.');
  1801. }
  1802. state = 'relative slash';
  1803. } else if (c === '?') {
  1804. this._host = base._host;
  1805. this._port = base._port;
  1806. this._path = base._path.slice();
  1807. this._query = '?';
  1808. this._username = base._username;
  1809. this._password = base._password;
  1810. state = 'query';
  1811. } else if (c === '#') {
  1812. this._host = base._host;
  1813. this._port = base._port;
  1814. this._path = base._path.slice();
  1815. this._query = base._query;
  1816. this._fragment = '#';
  1817. this._username = base._username;
  1818. this._password = base._password;
  1819. state = 'fragment';
  1820. } else {
  1821. var nextC = input[cursor + 1];
  1822. var nextNextC = input[cursor + 2];
  1823. if ('file' !== this._scheme || !ALPHA.test(c) || nextC !== ':' && nextC !== '|' || EOF !== nextNextC && '/' !== nextNextC && '\\' !== nextNextC && '?' !== nextNextC && '#' !== nextNextC) {
  1824. this._host = base._host;
  1825. this._port = base._port;
  1826. this._username = base._username;
  1827. this._password = base._password;
  1828. this._path = base._path.slice();
  1829. this._path.pop();
  1830. }
  1831. state = 'relative path';
  1832. continue;
  1833. }
  1834. break;
  1835. case 'relative slash':
  1836. if (c === '/' || c === '\\') {
  1837. if (c === '\\') {
  1838. err('\\ is an invalid code point.');
  1839. }
  1840. if (this._scheme === 'file') {
  1841. state = 'file host';
  1842. } else {
  1843. state = 'authority ignore slashes';
  1844. }
  1845. } else {
  1846. if ('file' !== this._scheme) {
  1847. this._host = base._host;
  1848. this._port = base._port;
  1849. this._username = base._username;
  1850. this._password = base._password;
  1851. }
  1852. state = 'relative path';
  1853. continue;
  1854. }
  1855. break;
  1856. case 'authority first slash':
  1857. if (c === '/') {
  1858. state = 'authority second slash';
  1859. } else {
  1860. err('Expected \'/\', got: ' + c);
  1861. state = 'authority ignore slashes';
  1862. continue;
  1863. }
  1864. break;
  1865. case 'authority second slash':
  1866. state = 'authority ignore slashes';
  1867. if ('/' !== c) {
  1868. err('Expected \'/\', got: ' + c);
  1869. continue;
  1870. }
  1871. break;
  1872. case 'authority ignore slashes':
  1873. if ('/' !== c && '\\' !== c) {
  1874. state = 'authority';
  1875. continue;
  1876. } else {
  1877. err('Expected authority, got: ' + c);
  1878. }
  1879. break;
  1880. case 'authority':
  1881. if (c === '@') {
  1882. if (seenAt) {
  1883. err('@ already seen.');
  1884. buffer += '%40';
  1885. }
  1886. seenAt = true;
  1887. for (var i = 0; i < buffer.length; i++) {
  1888. var cp = buffer[i];
  1889. if (cp === '\t' || cp === '\n' || cp === '\r') {
  1890. err('Invalid whitespace in authority.');
  1891. continue;
  1892. }
  1893. if (cp === ':' && this._password === null) {
  1894. this._password = '';
  1895. continue;
  1896. }
  1897. var tempC = percentEscape(cp);
  1898. if (null !== this._password) {
  1899. this._password += tempC;
  1900. } else {
  1901. this._username += tempC;
  1902. }
  1903. }
  1904. buffer = '';
  1905. } else if (c === EOF || c === '/' || c === '\\' || c === '?' || c === '#') {
  1906. cursor -= buffer.length;
  1907. buffer = '';
  1908. state = 'host';
  1909. continue;
  1910. } else {
  1911. buffer += c;
  1912. }
  1913. break;
  1914. case 'file host':
  1915. if (c === EOF || c === '/' || c === '\\' || c === '?' || c === '#') {
  1916. if (buffer.length === 2 && ALPHA.test(buffer[0]) && (buffer[1] === ':' || buffer[1] === '|')) {
  1917. state = 'relative path';
  1918. } else if (buffer.length === 0) {
  1919. state = 'relative path start';
  1920. } else {
  1921. this._host = IDNAToASCII.call(this, buffer);
  1922. buffer = '';
  1923. state = 'relative path start';
  1924. }
  1925. continue;
  1926. } else if (c === '\t' || c === '\n' || c === '\r') {
  1927. err('Invalid whitespace in file host.');
  1928. } else {
  1929. buffer += c;
  1930. }
  1931. break;
  1932. case 'host':
  1933. case 'hostname':
  1934. if (c === ':' && !seenBracket) {
  1935. this._host = IDNAToASCII.call(this, buffer);
  1936. buffer = '';
  1937. state = 'port';
  1938. if (stateOverride === 'hostname') {
  1939. break loop;
  1940. }
  1941. } else if (c === EOF || c === '/' || c === '\\' || c === '?' || c === '#') {
  1942. this._host = IDNAToASCII.call(this, buffer);
  1943. buffer = '';
  1944. state = 'relative path start';
  1945. if (stateOverride) {
  1946. break loop;
  1947. }
  1948. continue;
  1949. } else if ('\t' !== c && '\n' !== c && '\r' !== c) {
  1950. if (c === '[') {
  1951. seenBracket = true;
  1952. } else if (c === ']') {
  1953. seenBracket = false;
  1954. }
  1955. buffer += c;
  1956. } else {
  1957. err('Invalid code point in host/hostname: ' + c);
  1958. }
  1959. break;
  1960. case 'port':
  1961. if (/[0-9]/.test(c)) {
  1962. buffer += c;
  1963. } else if (c === EOF || c === '/' || c === '\\' || c === '?' || c === '#' || stateOverride) {
  1964. if ('' !== buffer) {
  1965. var temp = parseInt(buffer, 10);
  1966. if (temp !== relative[this._scheme]) {
  1967. this._port = temp + '';
  1968. }
  1969. buffer = '';
  1970. }
  1971. if (stateOverride) {
  1972. break loop;
  1973. }
  1974. state = 'relative path start';
  1975. continue;
  1976. } else if (c === '\t' || c === '\n' || c === '\r') {
  1977. err('Invalid code point in port: ' + c);
  1978. } else {
  1979. invalid.call(this);
  1980. }
  1981. break;
  1982. case 'relative path start':
  1983. if (c === '\\') {
  1984. err('\'\\\' not allowed in path.');
  1985. }
  1986. state = 'relative path';
  1987. if ('/' !== c && '\\' !== c) {
  1988. continue;
  1989. }
  1990. break;
  1991. case 'relative path':
  1992. if (c === EOF || c === '/' || c === '\\' || !stateOverride && (c === '?' || c === '#')) {
  1993. if (c === '\\') {
  1994. err('\\ not allowed in relative path.');
  1995. }
  1996. var tmp;
  1997. if (tmp = relativePathDotMapping[buffer.toLowerCase()]) {
  1998. buffer = tmp;
  1999. }
  2000. if (buffer === '..') {
  2001. this._path.pop();
  2002. if ('/' !== c && '\\' !== c) {
  2003. this._path.push('');
  2004. }
  2005. } else if (buffer === '.' && '/' !== c && '\\' !== c) {
  2006. this._path.push('');
  2007. } else if ('.' !== buffer) {
  2008. if (this._scheme === 'file' && this._path.length === 0 && buffer.length === 2 && ALPHA.test(buffer[0]) && buffer[1] === '|') {
  2009. buffer = buffer[0] + ':';
  2010. }
  2011. this._path.push(buffer);
  2012. }
  2013. buffer = '';
  2014. if (c === '?') {
  2015. this._query = '?';
  2016. state = 'query';
  2017. } else if (c === '#') {
  2018. this._fragment = '#';
  2019. state = 'fragment';
  2020. }
  2021. } else if ('\t' !== c && '\n' !== c && '\r' !== c) {
  2022. buffer += percentEscape(c);
  2023. }
  2024. break;
  2025. case 'query':
  2026. if (!stateOverride && c === '#') {
  2027. this._fragment = '#';
  2028. state = 'fragment';
  2029. } else if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  2030. this._query += percentEscapeQuery(c);
  2031. }
  2032. break;
  2033. case 'fragment':
  2034. if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  2035. this._fragment += c;
  2036. }
  2037. break;
  2038. }
  2039. cursor++;
  2040. }
  2041. }
  2042. function clear() {
  2043. this._scheme = '';
  2044. this._schemeData = '';
  2045. this._username = '';
  2046. this._password = null;
  2047. this._host = '';
  2048. this._port = '';
  2049. this._path = [];
  2050. this._query = '';
  2051. this._fragment = '';
  2052. this._isInvalid = false;
  2053. this._isRelative = false;
  2054. }
  2055. function JURL(url, base)
  2056. {
  2057. if (base !== undefined && !(base instanceof JURL)) {
  2058. base = new JURL(String(base));
  2059. }
  2060. this._url = url;
  2061. clear.call(this);
  2062. var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, '');
  2063. parse.call(this, input, null, base);
  2064. }
  2065. JURL.prototype = {
  2066. toString: function () {
  2067. return this.href;
  2068. },
  2069. get href() {
  2070. if (this._isInvalid) {
  2071. return this._url;
  2072. }
  2073. var authority = '';
  2074. if ('' !== this._username || null !== this._password) {
  2075. authority = this._username + (null !== this._password ? ':' + this._password : '') + '@';
  2076. }
  2077. return this.protocol + (this._isRelative ? '//' + authority + this.host : '') + this.pathname + this._query + this._fragment;
  2078. },
  2079. set href(href) {
  2080. clear.call(this);
  2081. parse.call(this, href);
  2082. },
  2083. get protocol() {
  2084. return this._scheme + ':';
  2085. },
  2086. set protocol(protocol) {
  2087. if (this._isInvalid) {
  2088. return;
  2089. }
  2090. parse.call(this, protocol + ':', 'scheme start');
  2091. },
  2092. get host() {
  2093. return this._isInvalid ? '' : this._port ? this._host + ':' + this._port : this._host;
  2094. },
  2095. set host(host) {
  2096. if (this._isInvalid || !this._isRelative) {
  2097. return;
  2098. }
  2099. parse.call(this, host, 'host');
  2100. },
  2101. get hostname() {
  2102. return this._host;
  2103. },
  2104. set hostname(hostname) {
  2105. if (this._isInvalid || !this._isRelative) {
  2106. return;
  2107. }
  2108. parse.call(this, hostname, 'hostname');
  2109. },
  2110. get port() {
  2111. return this._port;
  2112. },
  2113. set port(port) {
  2114. if (this._isInvalid || !this._isRelative) {
  2115. return;
  2116. }
  2117. parse.call(this, port, 'port');
  2118. },
  2119. get pathname() {
  2120. return this._isInvalid ? '' : this._isRelative ? '/' + this._path.join('/') : this._schemeData;
  2121. },
  2122. set pathname(pathname) {
  2123. if (this._isInvalid || !this._isRelative) {
  2124. return;
  2125. }
  2126. this._path = [];
  2127. parse.call(this, pathname, 'relative path start');
  2128. },
  2129. get search() {
  2130. return this._isInvalid || !this._query || this._query === '?' ? '' : this._query;
  2131. },
  2132. set search(search) {
  2133. if (this._isInvalid || !this._isRelative) {
  2134. return;
  2135. }
  2136. this._query = '?';
  2137. if (search[0] === '?') {
  2138. search = search.slice(1);
  2139. }
  2140. parse.call(this, search, 'query');
  2141. },
  2142. get hash() {
  2143. return this._isInvalid || !this._fragment || this._fragment === '#' ? '' : this._fragment;
  2144. },
  2145. set hash(hash) {
  2146. if (this._isInvalid) {
  2147. return;
  2148. }
  2149. this._fragment = '#';
  2150. if (hash[0] === '#') {
  2151. hash = hash.slice(1);
  2152. }
  2153. parse.call(this, hash, 'fragment');
  2154. },
  2155. get origin() {
  2156. var host;
  2157. if (this._isInvalid || !this._scheme) {
  2158. return '';
  2159. }
  2160. switch (this._scheme) {
  2161. case 'data':
  2162. case 'file':
  2163. case 'javascript':
  2164. case 'mailto':
  2165. return 'null';
  2166. }
  2167. host = this.host;
  2168. if (!host) {
  2169. return '';
  2170. }
  2171. return this._scheme + '://' + host;
  2172. }
  2173. };
  2174. var OriginalURL = scope.URL;
  2175. if (OriginalURL) {
  2176. JURL.createObjectURL = function (blob) {
  2177. return OriginalURL.createObjectURL.apply(OriginalURL, arguments);
  2178. };
  2179. JURL.revokeObjectURL = function (url) {
  2180. OriginalURL.revokeObjectURL(url);
  2181. };
  2182. }
  2183. scope.URL = JURL;
  2184. }(globalScope));
  2185. exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
  2186. exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
  2187. exports.OPS = OPS;
  2188. exports.VERBOSITY_LEVELS = VERBOSITY_LEVELS;
  2189. exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
  2190. exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
  2191. exports.AnnotationFieldFlag = AnnotationFieldFlag;
  2192. exports.AnnotationFlag = AnnotationFlag;
  2193. exports.AnnotationType = AnnotationType;
  2194. exports.FontType = FontType;
  2195. exports.ImageKind = ImageKind;
  2196. exports.InvalidPDFException = InvalidPDFException;
  2197. exports.MessageHandler = MessageHandler;
  2198. exports.MissingDataException = MissingDataException;
  2199. exports.MissingPDFException = MissingPDFException;
  2200. exports.NotImplementedException = NotImplementedException;
  2201. exports.PageViewport = PageViewport;
  2202. exports.PasswordException = PasswordException;
  2203. exports.PasswordResponses = PasswordResponses;
  2204. exports.StatTimer = StatTimer;
  2205. exports.StreamType = StreamType;
  2206. exports.TextRenderingMode = TextRenderingMode;
  2207. exports.UnexpectedResponseException = UnexpectedResponseException;
  2208. exports.UnknownErrorException = UnknownErrorException;
  2209. exports.Util = Util;
  2210. exports.XRefParseException = XRefParseException;
  2211. exports.arrayByteLength = arrayByteLength;
  2212. exports.arraysToBytes = arraysToBytes;
  2213. exports.assert = assert;
  2214. exports.bytesToString = bytesToString;
  2215. exports.createBlob = createBlob;
  2216. exports.createPromiseCapability = createPromiseCapability;
  2217. exports.createObjectURL = createObjectURL;
  2218. exports.deprecated = deprecated;
  2219. exports.error = error;
  2220. exports.getLookupTableFactory = getLookupTableFactory;
  2221. exports.getVerbosityLevel = getVerbosityLevel;
  2222. exports.globalScope = globalScope;
  2223. exports.info = info;
  2224. exports.isArray = isArray;
  2225. exports.isArrayBuffer = isArrayBuffer;
  2226. exports.isBool = isBool;
  2227. exports.isEmptyObj = isEmptyObj;
  2228. exports.isInt = isInt;
  2229. exports.isNum = isNum;
  2230. exports.isString = isString;
  2231. exports.isSpace = isSpace;
  2232. exports.isSameOrigin = isSameOrigin;
  2233. exports.createValidAbsoluteUrl = createValidAbsoluteUrl;
  2234. exports.isLittleEndian = isLittleEndian;
  2235. exports.isEvalSupported = isEvalSupported;
  2236. exports.loadJpegStream = loadJpegStream;
  2237. exports.log2 = log2;
  2238. exports.readInt8 = readInt8;
  2239. exports.readUint16 = readUint16;
  2240. exports.readUint32 = readUint32;
  2241. exports.removeNullCharacters = removeNullCharacters;
  2242. exports.setVerbosityLevel = setVerbosityLevel;
  2243. exports.shadow = shadow;
  2244. exports.string32 = string32;
  2245. exports.stringToBytes = stringToBytes;
  2246. exports.stringToPDFString = stringToPDFString;
  2247. exports.stringToUTF8String = stringToUTF8String;
  2248. exports.utf8StringToString = utf8StringToString;
  2249. exports.warn = warn;
  2250. }));
  2251. (function (root, factory) {
  2252. factory(root.pdfjsDisplayDOMUtils = {}, root.pdfjsSharedUtil);
  2253. }(this, function (exports, sharedUtil) {
  2254. var removeNullCharacters = sharedUtil.removeNullCharacters;
  2255. var warn = sharedUtil.warn;
  2256. var deprecated = sharedUtil.deprecated;
  2257. var createValidAbsoluteUrl = sharedUtil.createValidAbsoluteUrl;
  2258. var DEFAULT_LINK_REL = 'noopener noreferrer nofollow';
  2259. var CustomStyle = function CustomStyleClosure() {
  2260. var prefixes = [
  2261. 'ms',
  2262. 'Moz',
  2263. 'Webkit',
  2264. 'O'
  2265. ];
  2266. var _cache = Object.create(null);
  2267. function CustomStyle() {
  2268. }
  2269. CustomStyle.getProp = function get(propName, element) {
  2270. if (arguments.length === 1 && typeof _cache[propName] === 'string') {
  2271. return _cache[propName];
  2272. }
  2273. element = element || document.documentElement;
  2274. var style = element.style, prefixed, uPropName;
  2275. if (typeof style[propName] === 'string') {
  2276. return _cache[propName] = propName;
  2277. }
  2278. uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
  2279. for (var i = 0, l = prefixes.length; i < l; i++) {
  2280. prefixed = prefixes[i] + uPropName;
  2281. if (typeof style[prefixed] === 'string') {
  2282. return _cache[propName] = prefixed;
  2283. }
  2284. }
  2285. return _cache[propName] = 'undefined';
  2286. };
  2287. CustomStyle.setProp = function set(propName, element, str) {
  2288. var prop = this.getProp(propName);
  2289. if (prop !== 'undefined') {
  2290. element.style[prop] = str;
  2291. }
  2292. };
  2293. return CustomStyle;
  2294. }();
  2295. var hasCanvasTypedArrays;
  2296. hasCanvasTypedArrays = function hasCanvasTypedArrays() {
  2297. var canvas = document.createElement('canvas');
  2298. canvas.width = canvas.height = 1;
  2299. var ctx = canvas.getContext('2d');
  2300. var imageData = ctx.createImageData(1, 1);
  2301. return typeof imageData.data.buffer !== 'undefined';
  2302. };
  2303. var LinkTarget = {
  2304. NONE: 0,
  2305. SELF: 1,
  2306. BLANK: 2,
  2307. PARENT: 3,
  2308. TOP: 4
  2309. };
  2310. var LinkTargetStringMap = [
  2311. '',
  2312. '_self',
  2313. '_blank',
  2314. '_parent',
  2315. '_top'
  2316. ];
  2317. function addLinkAttributes(link, params) {
  2318. var url = params && params.url;
  2319. link.href = link.title = url ? removeNullCharacters(url) : '';
  2320. if (url) {
  2321. var target = params.target;
  2322. if (typeof target === 'undefined') {
  2323. target = getDefaultSetting('externalLinkTarget');
  2324. }
  2325. link.target = LinkTargetStringMap[target];
  2326. var rel = params.rel;
  2327. if (typeof rel === 'undefined') {
  2328. rel = getDefaultSetting('externalLinkRel');
  2329. }
  2330. link.rel = rel;
  2331. }
  2332. }
  2333. function getFilenameFromUrl(url) {
  2334. var anchor = url.indexOf('#');
  2335. var query = url.indexOf('?');
  2336. var end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
  2337. return url.substring(url.lastIndexOf('/', end) + 1, end);
  2338. }
  2339. function getDefaultSetting(id) {
  2340. var globalSettings = sharedUtil.globalScope.PDFJS;
  2341. switch (id) {
  2342. case 'pdfBug':
  2343. return globalSettings ? globalSettings.pdfBug : false;
  2344. case 'disableAutoFetch':
  2345. return globalSettings ? globalSettings.disableAutoFetch : false;
  2346. case 'disableStream':
  2347. return globalSettings ? globalSettings.disableStream : false;
  2348. case 'disableRange':
  2349. return globalSettings ? globalSettings.disableRange : false;
  2350. case 'disableFontFace':
  2351. return globalSettings ? globalSettings.disableFontFace : false;
  2352. case 'disableCreateObjectURL':
  2353. return globalSettings ? globalSettings.disableCreateObjectURL : false;
  2354. case 'disableWebGL':
  2355. return globalSettings ? globalSettings.disableWebGL : true;
  2356. case 'cMapUrl':
  2357. return globalSettings ? globalSettings.cMapUrl : null;
  2358. case 'cMapPacked':
  2359. return globalSettings ? globalSettings.cMapPacked : false;
  2360. case 'postMessageTransfers':
  2361. return globalSettings ? globalSettings.postMessageTransfers : true;
  2362. case 'workerSrc':
  2363. return globalSettings ? globalSettings.workerSrc : null;
  2364. case 'disableWorker':
  2365. return globalSettings ? globalSettings.disableWorker : false;
  2366. case 'maxImageSize':
  2367. return globalSettings ? globalSettings.maxImageSize : -1;
  2368. case 'imageResourcesPath':
  2369. return globalSettings ? globalSettings.imageResourcesPath : '';
  2370. case 'isEvalSupported':
  2371. return globalSettings ? globalSettings.isEvalSupported : true;
  2372. case 'externalLinkTarget':
  2373. if (!globalSettings) {
  2374. return LinkTarget.NONE;
  2375. }
  2376. switch (globalSettings.externalLinkTarget) {
  2377. case LinkTarget.NONE:
  2378. case LinkTarget.SELF:
  2379. case LinkTarget.BLANK:
  2380. case LinkTarget.PARENT:
  2381. case LinkTarget.TOP:
  2382. return globalSettings.externalLinkTarget;
  2383. }
  2384. warn('PDFJS.externalLinkTarget is invalid: ' + globalSettings.externalLinkTarget);
  2385. globalSettings.externalLinkTarget = LinkTarget.NONE;
  2386. return LinkTarget.NONE;
  2387. case 'externalLinkRel':
  2388. return globalSettings ? globalSettings.externalLinkRel : DEFAULT_LINK_REL;
  2389. case 'enableStats':
  2390. return !!(globalSettings && globalSettings.enableStats);
  2391. default:
  2392. throw new Error('Unknown default setting: ' + id);
  2393. }
  2394. }
  2395. function isExternalLinkTargetSet() {
  2396. var externalLinkTarget = getDefaultSetting('externalLinkTarget');
  2397. switch (externalLinkTarget) {
  2398. case LinkTarget.NONE:
  2399. return false;
  2400. case LinkTarget.SELF:
  2401. case LinkTarget.BLANK:
  2402. case LinkTarget.PARENT:
  2403. case LinkTarget.TOP:
  2404. return true;
  2405. }
  2406. }
  2407. function isValidUrl(url, allowRelative) {
  2408. deprecated('isValidUrl(), please use createValidAbsoluteUrl() instead.');
  2409. var baseUrl = allowRelative ? 'http://example.com' : null;
  2410. return createValidAbsoluteUrl(url, baseUrl) !== null;
  2411. }
  2412. exports.CustomStyle = CustomStyle;
  2413. exports.addLinkAttributes = addLinkAttributes;
  2414. exports.isExternalLinkTargetSet = isExternalLinkTargetSet;
  2415. exports.isValidUrl = isValidUrl;
  2416. exports.getFilenameFromUrl = getFilenameFromUrl;
  2417. exports.LinkTarget = LinkTarget;
  2418. exports.hasCanvasTypedArrays = hasCanvasTypedArrays;
  2419. exports.getDefaultSetting = getDefaultSetting;
  2420. exports.DEFAULT_LINK_REL = DEFAULT_LINK_REL;
  2421. }));
  2422. (function (root, factory) {
  2423. factory(root.pdfjsDisplayFontLoader = {}, root.pdfjsSharedUtil);
  2424. }(this, function (exports, sharedUtil) {
  2425. var assert = sharedUtil.assert;
  2426. var bytesToString = sharedUtil.bytesToString;
  2427. var string32 = sharedUtil.string32;
  2428. var shadow = sharedUtil.shadow;
  2429. var warn = sharedUtil.warn;
  2430. function FontLoader(docId) {
  2431. this.docId = docId;
  2432. this.styleElement = null;
  2433. this.nativeFontFaces = [];
  2434. this.loadTestFontId = 0;
  2435. this.loadingContext = {
  2436. requests: [],
  2437. nextRequestId: 0
  2438. };
  2439. }
  2440. FontLoader.prototype = {
  2441. insertRule: function fontLoaderInsertRule(rule) {
  2442. var styleElement = this.styleElement;
  2443. if (!styleElement) {
  2444. styleElement = this.styleElement = document.createElement('style');
  2445. styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId;
  2446. document.documentElement.getElementsByTagName('head')[0].appendChild(styleElement);
  2447. }
  2448. var styleSheet = styleElement.sheet;
  2449. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  2450. },
  2451. clear: function fontLoaderClear() {
  2452. var styleElement = this.styleElement;
  2453. if (styleElement) {
  2454. styleElement.parentNode.removeChild(styleElement);
  2455. styleElement = this.styleElement = null;
  2456. }
  2457. this.nativeFontFaces.forEach(function (nativeFontFace) {
  2458. document.fonts.delete(nativeFontFace);
  2459. });
  2460. this.nativeFontFaces.length = 0;
  2461. }
  2462. };
  2463. var getLoadTestFont = function () {
  2464. return atob('T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' + 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' + 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' + 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' + 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' + 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' + 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' + 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' + 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' + 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' + 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' + 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' + 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' + 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' + 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' + 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' + 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' + 'ABAAAAAAAAAAAD6AAAAAAAAA==');
  2465. };
  2466. Object.defineProperty(FontLoader.prototype, 'loadTestFont', {
  2467. get: function () {
  2468. return shadow(this, 'loadTestFont', getLoadTestFont());
  2469. },
  2470. configurable: true
  2471. });
  2472. FontLoader.prototype.addNativeFontFace = function fontLoader_addNativeFontFace(nativeFontFace) {
  2473. this.nativeFontFaces.push(nativeFontFace);
  2474. document.fonts.add(nativeFontFace);
  2475. };
  2476. FontLoader.prototype.bind = function fontLoaderBind(fonts, callback) {
  2477. var rules = [];
  2478. var fontsToLoad = [];
  2479. var fontLoadPromises = [];
  2480. var getNativeFontPromise = function (nativeFontFace) {
  2481. return nativeFontFace.loaded.catch(function (e) {
  2482. warn('Failed to load font "' + nativeFontFace.family + '": ' + e);
  2483. });
  2484. };
  2485. var isFontLoadingAPISupported = FontLoader.isFontLoadingAPISupported && !FontLoader.isSyncFontLoadingSupported;
  2486. for (var i = 0, ii = fonts.length; i < ii; i++) {
  2487. var font = fonts[i];
  2488. if (font.attached || font.loading === false) {
  2489. continue;
  2490. }
  2491. font.attached = true;
  2492. if (isFontLoadingAPISupported) {
  2493. var nativeFontFace = font.createNativeFontFace();
  2494. if (nativeFontFace) {
  2495. this.addNativeFontFace(nativeFontFace);
  2496. fontLoadPromises.push(getNativeFontPromise(nativeFontFace));
  2497. }
  2498. } else {
  2499. var rule = font.createFontFaceRule();
  2500. if (rule) {
  2501. this.insertRule(rule);
  2502. rules.push(rule);
  2503. fontsToLoad.push(font);
  2504. }
  2505. }
  2506. }
  2507. var request = this.queueLoadingCallback(callback);
  2508. if (isFontLoadingAPISupported) {
  2509. Promise.all(fontLoadPromises).then(function () {
  2510. request.complete();
  2511. });
  2512. } else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) {
  2513. this.prepareFontLoadEvent(rules, fontsToLoad, request);
  2514. } else {
  2515. request.complete();
  2516. }
  2517. };
  2518. FontLoader.prototype.queueLoadingCallback = function FontLoader_queueLoadingCallback(callback) {
  2519. function LoadLoader_completeRequest() {
  2520. assert(!request.end, 'completeRequest() cannot be called twice');
  2521. request.end = Date.now();
  2522. while (context.requests.length > 0 && context.requests[0].end) {
  2523. var otherRequest = context.requests.shift();
  2524. setTimeout(otherRequest.callback, 0);
  2525. }
  2526. }
  2527. var context = this.loadingContext;
  2528. var requestId = 'pdfjs-font-loading-' + context.nextRequestId++;
  2529. var request = {
  2530. id: requestId,
  2531. complete: LoadLoader_completeRequest,
  2532. callback: callback,
  2533. started: Date.now()
  2534. };
  2535. context.requests.push(request);
  2536. return request;
  2537. };
  2538. FontLoader.prototype.prepareFontLoadEvent = function fontLoaderPrepareFontLoadEvent(rules, fonts, request) {
  2539. function int32(data, offset) {
  2540. return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
  2541. }
  2542. function spliceString(s, offset, remove, insert) {
  2543. var chunk1 = s.substr(0, offset);
  2544. var chunk2 = s.substr(offset + remove);
  2545. return chunk1 + insert + chunk2;
  2546. }
  2547. var i, ii;
  2548. var canvas = document.createElement('canvas');
  2549. canvas.width = 1;
  2550. canvas.height = 1;
  2551. var ctx = canvas.getContext('2d');
  2552. var called = 0;
  2553. function isFontReady(name, callback) {
  2554. called++;
  2555. if (called > 30) {
  2556. warn('Load test font never loaded.');
  2557. callback();
  2558. return;
  2559. }
  2560. ctx.font = '30px ' + name;
  2561. ctx.fillText('.', 0, 20);
  2562. var imageData = ctx.getImageData(0, 0, 1, 1);
  2563. if (imageData.data[3] > 0) {
  2564. callback();
  2565. return;
  2566. }
  2567. setTimeout(isFontReady.bind(null, name, callback));
  2568. }
  2569. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  2570. var data = this.loadTestFont;
  2571. var COMMENT_OFFSET = 976;
  2572. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
  2573. var CFF_CHECKSUM_OFFSET = 16;
  2574. var XXXX_VALUE = 0x58585858;
  2575. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  2576. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  2577. checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
  2578. }
  2579. if (i < loadTestFontId.length) {
  2580. checksum = checksum - XXXX_VALUE + int32(loadTestFontId + 'XXX', i) | 0;
  2581. }
  2582. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  2583. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  2584. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' + url + '}';
  2585. this.insertRule(rule);
  2586. var names = [];
  2587. for (i = 0, ii = fonts.length; i < ii; i++) {
  2588. names.push(fonts[i].loadedName);
  2589. }
  2590. names.push(loadTestFontId);
  2591. var div = document.createElement('div');
  2592. div.setAttribute('style', 'visibility: hidden;' + 'width: 10px; height: 10px;' + 'position: absolute; top: 0px; left: 0px;');
  2593. for (i = 0, ii = names.length; i < ii; ++i) {
  2594. var span = document.createElement('span');
  2595. span.textContent = 'Hi';
  2596. span.style.fontFamily = names[i];
  2597. div.appendChild(span);
  2598. }
  2599. document.body.appendChild(div);
  2600. isFontReady(loadTestFontId, function () {
  2601. document.body.removeChild(div);
  2602. request.complete();
  2603. });
  2604. };
  2605. FontLoader.isFontLoadingAPISupported = typeof document !== 'undefined' && !!document.fonts;
  2606. var isSyncFontLoadingSupported = function isSyncFontLoadingSupported() {
  2607. if (typeof navigator === 'undefined') {
  2608. return true;
  2609. }
  2610. var supported = false;
  2611. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
  2612. if (m && m[1] >= 14) {
  2613. supported = true;
  2614. }
  2615. return supported;
  2616. };
  2617. Object.defineProperty(FontLoader, 'isSyncFontLoadingSupported', {
  2618. get: function () {
  2619. return shadow(FontLoader, 'isSyncFontLoadingSupported', isSyncFontLoadingSupported());
  2620. },
  2621. enumerable: true,
  2622. configurable: true
  2623. });
  2624. var IsEvalSupportedCached = {
  2625. get value() {
  2626. return shadow(this, 'value', sharedUtil.isEvalSupported());
  2627. }
  2628. };
  2629. var FontFaceObject = function FontFaceObjectClosure() {
  2630. function FontFaceObject(translatedData, options) {
  2631. this.compiledGlyphs = Object.create(null);
  2632. for (var i in translatedData) {
  2633. this[i] = translatedData[i];
  2634. }
  2635. this.options = options;
  2636. }
  2637. FontFaceObject.prototype = {
  2638. createNativeFontFace: function FontFaceObject_createNativeFontFace() {
  2639. if (!this.data) {
  2640. return null;
  2641. }
  2642. if (this.options.disableFontFace) {
  2643. this.disableFontFace = true;
  2644. return null;
  2645. }
  2646. var nativeFontFace = new FontFace(this.loadedName, this.data, {});
  2647. if (this.options.fontRegistry) {
  2648. this.options.fontRegistry.registerFont(this);
  2649. }
  2650. return nativeFontFace;
  2651. },
  2652. createFontFaceRule: function FontFaceObject_createFontFaceRule() {
  2653. if (!this.data) {
  2654. return null;
  2655. }
  2656. if (this.options.disableFontFace) {
  2657. this.disableFontFace = true;
  2658. return null;
  2659. }
  2660. var data = bytesToString(new Uint8Array(this.data));
  2661. var fontName = this.loadedName;
  2662. var url = 'url(data:' + this.mimetype + ';base64,' + btoa(data) + ');';
  2663. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  2664. if (this.options.fontRegistry) {
  2665. this.options.fontRegistry.registerFont(this, url);
  2666. }
  2667. return rule;
  2668. },
  2669. getPathGenerator: function FontFaceObject_getPathGenerator(objs, character) {
  2670. if (!(character in this.compiledGlyphs)) {
  2671. var cmds = objs.get(this.loadedName + '_path_' + character);
  2672. var current, i, len;
  2673. if (this.options.isEvalSupported && IsEvalSupportedCached.value) {
  2674. var args, js = '';
  2675. for (i = 0, len = cmds.length; i < len; i++) {
  2676. current = cmds[i];
  2677. if (current.args !== undefined) {
  2678. args = current.args.join(',');
  2679. } else {
  2680. args = '';
  2681. }
  2682. js += 'c.' + current.cmd + '(' + args + ');\n';
  2683. }
  2684. this.compiledGlyphs[character] = new Function('c', 'size', js);
  2685. } else {
  2686. this.compiledGlyphs[character] = function (c, size) {
  2687. for (i = 0, len = cmds.length; i < len; i++) {
  2688. current = cmds[i];
  2689. if (current.cmd === 'scale') {
  2690. current.args = [
  2691. size,
  2692. -size
  2693. ];
  2694. }
  2695. c[current.cmd].apply(c, current.args);
  2696. }
  2697. };
  2698. }
  2699. }
  2700. return this.compiledGlyphs[character];
  2701. }
  2702. };
  2703. return FontFaceObject;
  2704. }();
  2705. exports.FontFaceObject = FontFaceObject;
  2706. exports.FontLoader = FontLoader;
  2707. }));
  2708. (function (root, factory) {
  2709. factory(root.pdfjsDisplayMetadata = {}, root.pdfjsSharedUtil);
  2710. }(this, function (exports, sharedUtil) {
  2711. var error = sharedUtil.error;
  2712. function fixMetadata(meta) {
  2713. return meta.replace(/>\\376\\377([^<]+)/g, function (all, codes) {
  2714. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g, function (code, d1, d2, d3) {
  2715. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  2716. });
  2717. var chars = '';
  2718. for (var i = 0; i < bytes.length; i += 2) {
  2719. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  2720. chars += code >= 32 && code < 127 && code !== 60 && code !== 62 && code !== 38 ? String.fromCharCode(code) : '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  2721. }
  2722. return '>' + chars;
  2723. });
  2724. }
  2725. function Metadata(meta) {
  2726. if (typeof meta === 'string') {
  2727. meta = fixMetadata(meta);
  2728. var parser = new DOMParser();
  2729. meta = parser.parseFromString(meta, 'application/xml');
  2730. } else if (!(meta instanceof Document)) {
  2731. error('Metadata: Invalid metadata object');
  2732. }
  2733. this.metaDocument = meta;
  2734. this.metadata = Object.create(null);
  2735. this.parse();
  2736. }
  2737. Metadata.prototype = {
  2738. parse: function Metadata_parse() {
  2739. var doc = this.metaDocument;
  2740. var rdf = doc.documentElement;
  2741. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  2742. rdf = rdf.firstChild;
  2743. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  2744. rdf = rdf.nextSibling;
  2745. }
  2746. }
  2747. var nodeName = rdf ? rdf.nodeName.toLowerCase() : null;
  2748. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  2749. return;
  2750. }
  2751. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  2752. for (i = 0, length = children.length; i < length; i++) {
  2753. desc = children[i];
  2754. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  2755. continue;
  2756. }
  2757. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  2758. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  2759. entry = desc.childNodes[ii];
  2760. name = entry.nodeName.toLowerCase();
  2761. this.metadata[name] = entry.textContent.trim();
  2762. }
  2763. }
  2764. }
  2765. },
  2766. get: function Metadata_get(name) {
  2767. return this.metadata[name] || null;
  2768. },
  2769. has: function Metadata_has(name) {
  2770. return typeof this.metadata[name] !== 'undefined';
  2771. }
  2772. };
  2773. exports.Metadata = Metadata;
  2774. }));
  2775. (function (root, factory) {
  2776. factory(root.pdfjsDisplaySVG = {}, root.pdfjsSharedUtil);
  2777. }(this, function (exports, sharedUtil) {
  2778. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  2779. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  2780. var ImageKind = sharedUtil.ImageKind;
  2781. var OPS = sharedUtil.OPS;
  2782. var Util = sharedUtil.Util;
  2783. var isNum = sharedUtil.isNum;
  2784. var isArray = sharedUtil.isArray;
  2785. var warn = sharedUtil.warn;
  2786. var createObjectURL = sharedUtil.createObjectURL;
  2787. var SVG_DEFAULTS = {
  2788. fontStyle: 'normal',
  2789. fontWeight: 'normal',
  2790. fillColor: '#000000'
  2791. };
  2792. var convertImgDataToPng = function convertImgDataToPngClosure() {
  2793. var PNG_HEADER = new Uint8Array([
  2794. 0x89,
  2795. 0x50,
  2796. 0x4e,
  2797. 0x47,
  2798. 0x0d,
  2799. 0x0a,
  2800. 0x1a,
  2801. 0x0a
  2802. ]);
  2803. var CHUNK_WRAPPER_SIZE = 12;
  2804. var crcTable = new Int32Array(256);
  2805. for (var i = 0; i < 256; i++) {
  2806. var c = i;
  2807. for (var h = 0; h < 8; h++) {
  2808. if (c & 1) {
  2809. c = 0xedB88320 ^ c >> 1 & 0x7fffffff;
  2810. } else {
  2811. c = c >> 1 & 0x7fffffff;
  2812. }
  2813. }
  2814. crcTable[i] = c;
  2815. }
  2816. function crc32(data, start, end) {
  2817. var crc = -1;
  2818. for (var i = start; i < end; i++) {
  2819. var a = (crc ^ data[i]) & 0xff;
  2820. var b = crcTable[a];
  2821. crc = crc >>> 8 ^ b;
  2822. }
  2823. return crc ^ -1;
  2824. }
  2825. function writePngChunk(type, body, data, offset) {
  2826. var p = offset;
  2827. var len = body.length;
  2828. data[p] = len >> 24 & 0xff;
  2829. data[p + 1] = len >> 16 & 0xff;
  2830. data[p + 2] = len >> 8 & 0xff;
  2831. data[p + 3] = len & 0xff;
  2832. p += 4;
  2833. data[p] = type.charCodeAt(0) & 0xff;
  2834. data[p + 1] = type.charCodeAt(1) & 0xff;
  2835. data[p + 2] = type.charCodeAt(2) & 0xff;
  2836. data[p + 3] = type.charCodeAt(3) & 0xff;
  2837. p += 4;
  2838. data.set(body, p);
  2839. p += body.length;
  2840. var crc = crc32(data, offset + 4, p);
  2841. data[p] = crc >> 24 & 0xff;
  2842. data[p + 1] = crc >> 16 & 0xff;
  2843. data[p + 2] = crc >> 8 & 0xff;
  2844. data[p + 3] = crc & 0xff;
  2845. }
  2846. function adler32(data, start, end) {
  2847. var a = 1;
  2848. var b = 0;
  2849. for (var i = start; i < end; ++i) {
  2850. a = (a + (data[i] & 0xff)) % 65521;
  2851. b = (b + a) % 65521;
  2852. }
  2853. return b << 16 | a;
  2854. }
  2855. function encode(imgData, kind, forceDataSchema) {
  2856. var width = imgData.width;
  2857. var height = imgData.height;
  2858. var bitDepth, colorType, lineSize;
  2859. var bytes = imgData.data;
  2860. switch (kind) {
  2861. case ImageKind.GRAYSCALE_1BPP:
  2862. colorType = 0;
  2863. bitDepth = 1;
  2864. lineSize = width + 7 >> 3;
  2865. break;
  2866. case ImageKind.RGB_24BPP:
  2867. colorType = 2;
  2868. bitDepth = 8;
  2869. lineSize = width * 3;
  2870. break;
  2871. case ImageKind.RGBA_32BPP:
  2872. colorType = 6;
  2873. bitDepth = 8;
  2874. lineSize = width * 4;
  2875. break;
  2876. default:
  2877. throw new Error('invalid format');
  2878. }
  2879. var literals = new Uint8Array((1 + lineSize) * height);
  2880. var offsetLiterals = 0, offsetBytes = 0;
  2881. var y, i;
  2882. for (y = 0; y < height; ++y) {
  2883. literals[offsetLiterals++] = 0;
  2884. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals);
  2885. offsetBytes += lineSize;
  2886. offsetLiterals += lineSize;
  2887. }
  2888. if (kind === ImageKind.GRAYSCALE_1BPP) {
  2889. offsetLiterals = 0;
  2890. for (y = 0; y < height; y++) {
  2891. offsetLiterals++;
  2892. for (i = 0; i < lineSize; i++) {
  2893. literals[offsetLiterals++] ^= 0xFF;
  2894. }
  2895. }
  2896. }
  2897. var ihdr = new Uint8Array([
  2898. width >> 24 & 0xff,
  2899. width >> 16 & 0xff,
  2900. width >> 8 & 0xff,
  2901. width & 0xff,
  2902. height >> 24 & 0xff,
  2903. height >> 16 & 0xff,
  2904. height >> 8 & 0xff,
  2905. height & 0xff,
  2906. bitDepth,
  2907. colorType,
  2908. 0x00,
  2909. 0x00,
  2910. 0x00
  2911. ]);
  2912. var len = literals.length;
  2913. var maxBlockLength = 0xFFFF;
  2914. var deflateBlocks = Math.ceil(len / maxBlockLength);
  2915. var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  2916. var pi = 0;
  2917. idat[pi++] = 0x78;
  2918. idat[pi++] = 0x9c;
  2919. var pos = 0;
  2920. while (len > maxBlockLength) {
  2921. idat[pi++] = 0x00;
  2922. idat[pi++] = 0xff;
  2923. idat[pi++] = 0xff;
  2924. idat[pi++] = 0x00;
  2925. idat[pi++] = 0x00;
  2926. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  2927. pi += maxBlockLength;
  2928. pos += maxBlockLength;
  2929. len -= maxBlockLength;
  2930. }
  2931. idat[pi++] = 0x01;
  2932. idat[pi++] = len & 0xff;
  2933. idat[pi++] = len >> 8 & 0xff;
  2934. idat[pi++] = ~len & 0xffff & 0xff;
  2935. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  2936. idat.set(literals.subarray(pos), pi);
  2937. pi += literals.length - pos;
  2938. var adler = adler32(literals, 0, literals.length);
  2939. idat[pi++] = adler >> 24 & 0xff;
  2940. idat[pi++] = adler >> 16 & 0xff;
  2941. idat[pi++] = adler >> 8 & 0xff;
  2942. idat[pi++] = adler & 0xff;
  2943. var pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length;
  2944. var data = new Uint8Array(pngLength);
  2945. var offset = 0;
  2946. data.set(PNG_HEADER, offset);
  2947. offset += PNG_HEADER.length;
  2948. writePngChunk('IHDR', ihdr, data, offset);
  2949. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  2950. writePngChunk('IDATA', idat, data, offset);
  2951. offset += CHUNK_WRAPPER_SIZE + idat.length;
  2952. writePngChunk('IEND', new Uint8Array(0), data, offset);
  2953. return createObjectURL(data, 'image/png', forceDataSchema);
  2954. }
  2955. return function convertImgDataToPng(imgData, forceDataSchema) {
  2956. var kind = imgData.kind === undefined ? ImageKind.GRAYSCALE_1BPP : imgData.kind;
  2957. return encode(imgData, kind, forceDataSchema);
  2958. };
  2959. }();
  2960. var SVGExtraState = function SVGExtraStateClosure() {
  2961. function SVGExtraState() {
  2962. this.fontSizeScale = 1;
  2963. this.fontWeight = SVG_DEFAULTS.fontWeight;
  2964. this.fontSize = 0;
  2965. this.textMatrix = IDENTITY_MATRIX;
  2966. this.fontMatrix = FONT_IDENTITY_MATRIX;
  2967. this.leading = 0;
  2968. this.x = 0;
  2969. this.y = 0;
  2970. this.lineX = 0;
  2971. this.lineY = 0;
  2972. this.charSpacing = 0;
  2973. this.wordSpacing = 0;
  2974. this.textHScale = 1;
  2975. this.textRise = 0;
  2976. this.fillColor = SVG_DEFAULTS.fillColor;
  2977. this.strokeColor = '#000000';
  2978. this.fillAlpha = 1;
  2979. this.strokeAlpha = 1;
  2980. this.lineWidth = 1;
  2981. this.lineJoin = '';
  2982. this.lineCap = '';
  2983. this.miterLimit = 0;
  2984. this.dashArray = [];
  2985. this.dashPhase = 0;
  2986. this.dependencies = [];
  2987. this.activeClipUrl = null;
  2988. this.clipGroup = null;
  2989. this.maskId = '';
  2990. }
  2991. SVGExtraState.prototype = {
  2992. clone: function SVGExtraState_clone() {
  2993. return Object.create(this);
  2994. },
  2995. setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) {
  2996. this.x = x;
  2997. this.y = y;
  2998. }
  2999. };
  3000. return SVGExtraState;
  3001. }();
  3002. var SVGGraphics = function SVGGraphicsClosure() {
  3003. function opListToTree(opList) {
  3004. var opTree = [];
  3005. var tmp = [];
  3006. var opListLen = opList.length;
  3007. for (var x = 0; x < opListLen; x++) {
  3008. if (opList[x].fn === 'save') {
  3009. opTree.push({
  3010. 'fnId': 92,
  3011. 'fn': 'group',
  3012. 'items': []
  3013. });
  3014. tmp.push(opTree);
  3015. opTree = opTree[opTree.length - 1].items;
  3016. continue;
  3017. }
  3018. if (opList[x].fn === 'restore') {
  3019. opTree = tmp.pop();
  3020. } else {
  3021. opTree.push(opList[x]);
  3022. }
  3023. }
  3024. return opTree;
  3025. }
  3026. function pf(value) {
  3027. if (value === (value | 0)) {
  3028. return value.toString();
  3029. }
  3030. var s = value.toFixed(10);
  3031. var i = s.length - 1;
  3032. if (s[i] !== '0') {
  3033. return s;
  3034. }
  3035. do {
  3036. i--;
  3037. } while (s[i] === '0');
  3038. return s.substr(0, s[i] === '.' ? i : i + 1);
  3039. }
  3040. function pm(m) {
  3041. if (m[4] === 0 && m[5] === 0) {
  3042. if (m[1] === 0 && m[2] === 0) {
  3043. if (m[0] === 1 && m[3] === 1) {
  3044. return '';
  3045. }
  3046. return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')';
  3047. }
  3048. if (m[0] === m[3] && m[1] === -m[2]) {
  3049. var a = Math.acos(m[0]) * 180 / Math.PI;
  3050. return 'rotate(' + pf(a) + ')';
  3051. }
  3052. } else {
  3053. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  3054. return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3055. }
  3056. }
  3057. return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' + pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3058. }
  3059. function SVGGraphics(commonObjs, objs, forceDataSchema) {
  3060. this.current = new SVGExtraState();
  3061. this.transformMatrix = IDENTITY_MATRIX;
  3062. this.transformStack = [];
  3063. this.extraStack = [];
  3064. this.commonObjs = commonObjs;
  3065. this.objs = objs;
  3066. this.pendingEOFill = false;
  3067. this.embedFonts = false;
  3068. this.embeddedFonts = Object.create(null);
  3069. this.cssStyle = null;
  3070. this.forceDataSchema = !!forceDataSchema;
  3071. }
  3072. var NS = 'http://www.w3.org/2000/svg';
  3073. var XML_NS = 'http://www.w3.org/XML/1998/namespace';
  3074. var XLINK_NS = 'http://www.w3.org/1999/xlink';
  3075. var LINE_CAP_STYLES = [
  3076. 'butt',
  3077. 'round',
  3078. 'square'
  3079. ];
  3080. var LINE_JOIN_STYLES = [
  3081. 'miter',
  3082. 'round',
  3083. 'bevel'
  3084. ];
  3085. var clipCount = 0;
  3086. var maskCount = 0;
  3087. SVGGraphics.prototype = {
  3088. save: function SVGGraphics_save() {
  3089. this.transformStack.push(this.transformMatrix);
  3090. var old = this.current;
  3091. this.extraStack.push(old);
  3092. this.current = old.clone();
  3093. },
  3094. restore: function SVGGraphics_restore() {
  3095. this.transformMatrix = this.transformStack.pop();
  3096. this.current = this.extraStack.pop();
  3097. this.tgrp = null;
  3098. },
  3099. group: function SVGGraphics_group(items) {
  3100. this.save();
  3101. this.executeOpTree(items);
  3102. this.restore();
  3103. },
  3104. loadDependencies: function SVGGraphics_loadDependencies(operatorList) {
  3105. var fnArray = operatorList.fnArray;
  3106. var fnArrayLen = fnArray.length;
  3107. var argsArray = operatorList.argsArray;
  3108. var self = this;
  3109. for (var i = 0; i < fnArrayLen; i++) {
  3110. if (OPS.dependency === fnArray[i]) {
  3111. var deps = argsArray[i];
  3112. for (var n = 0, nn = deps.length; n < nn; n++) {
  3113. var obj = deps[n];
  3114. var common = obj.substring(0, 2) === 'g_';
  3115. var promise;
  3116. if (common) {
  3117. promise = new Promise(function (resolve) {
  3118. self.commonObjs.get(obj, resolve);
  3119. });
  3120. } else {
  3121. promise = new Promise(function (resolve) {
  3122. self.objs.get(obj, resolve);
  3123. });
  3124. }
  3125. this.current.dependencies.push(promise);
  3126. }
  3127. }
  3128. }
  3129. return Promise.all(this.current.dependencies);
  3130. },
  3131. transform: function SVGGraphics_transform(a, b, c, d, e, f) {
  3132. var transformMatrix = [
  3133. a,
  3134. b,
  3135. c,
  3136. d,
  3137. e,
  3138. f
  3139. ];
  3140. this.transformMatrix = Util.transform(this.transformMatrix, transformMatrix);
  3141. this.tgrp = null;
  3142. },
  3143. getSVG: function SVGGraphics_getSVG(operatorList, viewport) {
  3144. this.viewport = viewport;
  3145. var svgElement = this._initialize(viewport);
  3146. return this.loadDependencies(operatorList).then(function () {
  3147. this.transformMatrix = IDENTITY_MATRIX;
  3148. var opTree = this.convertOpList(operatorList);
  3149. this.executeOpTree(opTree);
  3150. return svgElement;
  3151. }.bind(this));
  3152. },
  3153. convertOpList: function SVGGraphics_convertOpList(operatorList) {
  3154. var argsArray = operatorList.argsArray;
  3155. var fnArray = operatorList.fnArray;
  3156. var fnArrayLen = fnArray.length;
  3157. var REVOPS = [];
  3158. var opList = [];
  3159. for (var op in OPS) {
  3160. REVOPS[OPS[op]] = op;
  3161. }
  3162. for (var x = 0; x < fnArrayLen; x++) {
  3163. var fnId = fnArray[x];
  3164. opList.push({
  3165. 'fnId': fnId,
  3166. 'fn': REVOPS[fnId],
  3167. 'args': argsArray[x]
  3168. });
  3169. }
  3170. return opListToTree(opList);
  3171. },
  3172. executeOpTree: function SVGGraphics_executeOpTree(opTree) {
  3173. var opTreeLen = opTree.length;
  3174. for (var x = 0; x < opTreeLen; x++) {
  3175. var fn = opTree[x].fn;
  3176. var fnId = opTree[x].fnId;
  3177. var args = opTree[x].args;
  3178. switch (fnId | 0) {
  3179. case OPS.beginText:
  3180. this.beginText();
  3181. break;
  3182. case OPS.setLeading:
  3183. this.setLeading(args);
  3184. break;
  3185. case OPS.setLeadingMoveText:
  3186. this.setLeadingMoveText(args[0], args[1]);
  3187. break;
  3188. case OPS.setFont:
  3189. this.setFont(args);
  3190. break;
  3191. case OPS.showText:
  3192. this.showText(args[0]);
  3193. break;
  3194. case OPS.showSpacedText:
  3195. this.showText(args[0]);
  3196. break;
  3197. case OPS.endText:
  3198. this.endText();
  3199. break;
  3200. case OPS.moveText:
  3201. this.moveText(args[0], args[1]);
  3202. break;
  3203. case OPS.setCharSpacing:
  3204. this.setCharSpacing(args[0]);
  3205. break;
  3206. case OPS.setWordSpacing:
  3207. this.setWordSpacing(args[0]);
  3208. break;
  3209. case OPS.setHScale:
  3210. this.setHScale(args[0]);
  3211. break;
  3212. case OPS.setTextMatrix:
  3213. this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  3214. break;
  3215. case OPS.setLineWidth:
  3216. this.setLineWidth(args[0]);
  3217. break;
  3218. case OPS.setLineJoin:
  3219. this.setLineJoin(args[0]);
  3220. break;
  3221. case OPS.setLineCap:
  3222. this.setLineCap(args[0]);
  3223. break;
  3224. case OPS.setMiterLimit:
  3225. this.setMiterLimit(args[0]);
  3226. break;
  3227. case OPS.setFillRGBColor:
  3228. this.setFillRGBColor(args[0], args[1], args[2]);
  3229. break;
  3230. case OPS.setStrokeRGBColor:
  3231. this.setStrokeRGBColor(args[0], args[1], args[2]);
  3232. break;
  3233. case OPS.setDash:
  3234. this.setDash(args[0], args[1]);
  3235. break;
  3236. case OPS.setGState:
  3237. this.setGState(args[0]);
  3238. break;
  3239. case OPS.fill:
  3240. this.fill();
  3241. break;
  3242. case OPS.eoFill:
  3243. this.eoFill();
  3244. break;
  3245. case OPS.stroke:
  3246. this.stroke();
  3247. break;
  3248. case OPS.fillStroke:
  3249. this.fillStroke();
  3250. break;
  3251. case OPS.eoFillStroke:
  3252. this.eoFillStroke();
  3253. break;
  3254. case OPS.clip:
  3255. this.clip('nonzero');
  3256. break;
  3257. case OPS.eoClip:
  3258. this.clip('evenodd');
  3259. break;
  3260. case OPS.paintSolidColorImageMask:
  3261. this.paintSolidColorImageMask();
  3262. break;
  3263. case OPS.paintJpegXObject:
  3264. this.paintJpegXObject(args[0], args[1], args[2]);
  3265. break;
  3266. case OPS.paintImageXObject:
  3267. this.paintImageXObject(args[0]);
  3268. break;
  3269. case OPS.paintInlineImageXObject:
  3270. this.paintInlineImageXObject(args[0]);
  3271. break;
  3272. case OPS.paintImageMaskXObject:
  3273. this.paintImageMaskXObject(args[0]);
  3274. break;
  3275. case OPS.paintFormXObjectBegin:
  3276. this.paintFormXObjectBegin(args[0], args[1]);
  3277. break;
  3278. case OPS.paintFormXObjectEnd:
  3279. this.paintFormXObjectEnd();
  3280. break;
  3281. case OPS.closePath:
  3282. this.closePath();
  3283. break;
  3284. case OPS.closeStroke:
  3285. this.closeStroke();
  3286. break;
  3287. case OPS.closeFillStroke:
  3288. this.closeFillStroke();
  3289. break;
  3290. case OPS.nextLine:
  3291. this.nextLine();
  3292. break;
  3293. case OPS.transform:
  3294. this.transform(args[0], args[1], args[2], args[3], args[4], args[5]);
  3295. break;
  3296. case OPS.constructPath:
  3297. this.constructPath(args[0], args[1]);
  3298. break;
  3299. case OPS.endPath:
  3300. this.endPath();
  3301. break;
  3302. case 92:
  3303. this.group(opTree[x].items);
  3304. break;
  3305. default:
  3306. warn('Unimplemented operator ' + fn);
  3307. break;
  3308. }
  3309. }
  3310. },
  3311. setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) {
  3312. this.current.wordSpacing = wordSpacing;
  3313. },
  3314. setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) {
  3315. this.current.charSpacing = charSpacing;
  3316. },
  3317. nextLine: function SVGGraphics_nextLine() {
  3318. this.moveText(0, this.current.leading);
  3319. },
  3320. setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) {
  3321. var current = this.current;
  3322. this.current.textMatrix = this.current.lineMatrix = [
  3323. a,
  3324. b,
  3325. c,
  3326. d,
  3327. e,
  3328. f
  3329. ];
  3330. this.current.x = this.current.lineX = 0;
  3331. this.current.y = this.current.lineY = 0;
  3332. current.xcoords = [];
  3333. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3334. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3335. current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px');
  3336. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3337. current.txtElement = document.createElementNS(NS, 'svg:text');
  3338. current.txtElement.appendChild(current.tspan);
  3339. },
  3340. beginText: function SVGGraphics_beginText() {
  3341. this.current.x = this.current.lineX = 0;
  3342. this.current.y = this.current.lineY = 0;
  3343. this.current.textMatrix = IDENTITY_MATRIX;
  3344. this.current.lineMatrix = IDENTITY_MATRIX;
  3345. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3346. this.current.txtElement = document.createElementNS(NS, 'svg:text');
  3347. this.current.txtgrp = document.createElementNS(NS, 'svg:g');
  3348. this.current.xcoords = [];
  3349. },
  3350. moveText: function SVGGraphics_moveText(x, y) {
  3351. var current = this.current;
  3352. this.current.x = this.current.lineX += x;
  3353. this.current.y = this.current.lineY += y;
  3354. current.xcoords = [];
  3355. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3356. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3357. current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px');
  3358. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3359. },
  3360. showText: function SVGGraphics_showText(glyphs) {
  3361. var current = this.current;
  3362. var font = current.font;
  3363. var fontSize = current.fontSize;
  3364. if (fontSize === 0) {
  3365. return;
  3366. }
  3367. var charSpacing = current.charSpacing;
  3368. var wordSpacing = current.wordSpacing;
  3369. var fontDirection = current.fontDirection;
  3370. var textHScale = current.textHScale * fontDirection;
  3371. var glyphsLength = glyphs.length;
  3372. var vertical = font.vertical;
  3373. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  3374. var x = 0, i;
  3375. for (i = 0; i < glyphsLength; ++i) {
  3376. var glyph = glyphs[i];
  3377. if (glyph === null) {
  3378. x += fontDirection * wordSpacing;
  3379. continue;
  3380. } else if (isNum(glyph)) {
  3381. x += -glyph * fontSize * 0.001;
  3382. continue;
  3383. }
  3384. current.xcoords.push(current.x + x * textHScale);
  3385. var width = glyph.width;
  3386. var character = glyph.fontChar;
  3387. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  3388. x += charWidth;
  3389. current.tspan.textContent += character;
  3390. }
  3391. if (vertical) {
  3392. current.y -= x * textHScale;
  3393. } else {
  3394. current.x += x * textHScale;
  3395. }
  3396. current.tspan.setAttributeNS(null, 'x', current.xcoords.map(pf).join(' '));
  3397. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3398. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3399. current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px');
  3400. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  3401. current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);
  3402. }
  3403. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  3404. current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);
  3405. }
  3406. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  3407. current.tspan.setAttributeNS(null, 'fill', current.fillColor);
  3408. }
  3409. current.txtElement.setAttributeNS(null, 'transform', pm(current.textMatrix) + ' scale(1, -1)');
  3410. current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
  3411. current.txtElement.appendChild(current.tspan);
  3412. current.txtgrp.appendChild(current.txtElement);
  3413. this._ensureTransformGroup().appendChild(current.txtElement);
  3414. },
  3415. setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) {
  3416. this.setLeading(-y);
  3417. this.moveText(x, y);
  3418. },
  3419. addFontStyle: function SVGGraphics_addFontStyle(fontObj) {
  3420. if (!this.cssStyle) {
  3421. this.cssStyle = document.createElementNS(NS, 'svg:style');
  3422. this.cssStyle.setAttributeNS(null, 'type', 'text/css');
  3423. this.defs.appendChild(this.cssStyle);
  3424. }
  3425. var url = createObjectURL(fontObj.data, fontObj.mimetype, this.forceDataSchema);
  3426. this.cssStyle.textContent += '@font-face { font-family: "' + fontObj.loadedName + '";' + ' src: url(' + url + '); }\n';
  3427. },
  3428. setFont: function SVGGraphics_setFont(details) {
  3429. var current = this.current;
  3430. var fontObj = this.commonObjs.get(details[0]);
  3431. var size = details[1];
  3432. this.current.font = fontObj;
  3433. if (this.embedFonts && fontObj.data && !this.embeddedFonts[fontObj.loadedName]) {
  3434. this.addFontStyle(fontObj);
  3435. this.embeddedFonts[fontObj.loadedName] = fontObj;
  3436. }
  3437. current.fontMatrix = fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX;
  3438. var bold = fontObj.black ? fontObj.bold ? 'bolder' : 'bold' : fontObj.bold ? 'bold' : 'normal';
  3439. var italic = fontObj.italic ? 'italic' : 'normal';
  3440. if (size < 0) {
  3441. size = -size;
  3442. current.fontDirection = -1;
  3443. } else {
  3444. current.fontDirection = 1;
  3445. }
  3446. current.fontSize = size;
  3447. current.fontFamily = fontObj.loadedName;
  3448. current.fontWeight = bold;
  3449. current.fontStyle = italic;
  3450. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3451. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3452. current.xcoords = [];
  3453. },
  3454. endText: function SVGGraphics_endText() {
  3455. },
  3456. setLineWidth: function SVGGraphics_setLineWidth(width) {
  3457. this.current.lineWidth = width;
  3458. },
  3459. setLineCap: function SVGGraphics_setLineCap(style) {
  3460. this.current.lineCap = LINE_CAP_STYLES[style];
  3461. },
  3462. setLineJoin: function SVGGraphics_setLineJoin(style) {
  3463. this.current.lineJoin = LINE_JOIN_STYLES[style];
  3464. },
  3465. setMiterLimit: function SVGGraphics_setMiterLimit(limit) {
  3466. this.current.miterLimit = limit;
  3467. },
  3468. setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) {
  3469. var color = Util.makeCssRgb(r, g, b);
  3470. this.current.strokeColor = color;
  3471. },
  3472. setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) {
  3473. var color = Util.makeCssRgb(r, g, b);
  3474. this.current.fillColor = color;
  3475. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3476. this.current.xcoords = [];
  3477. },
  3478. setDash: function SVGGraphics_setDash(dashArray, dashPhase) {
  3479. this.current.dashArray = dashArray;
  3480. this.current.dashPhase = dashPhase;
  3481. },
  3482. constructPath: function SVGGraphics_constructPath(ops, args) {
  3483. var current = this.current;
  3484. var x = current.x, y = current.y;
  3485. current.path = document.createElementNS(NS, 'svg:path');
  3486. var d = [];
  3487. var opLength = ops.length;
  3488. for (var i = 0, j = 0; i < opLength; i++) {
  3489. switch (ops[i] | 0) {
  3490. case OPS.rectangle:
  3491. x = args[j++];
  3492. y = args[j++];
  3493. var width = args[j++];
  3494. var height = args[j++];
  3495. var xw = x + width;
  3496. var yh = y + height;
  3497. d.push('M', pf(x), pf(y), 'L', pf(xw), pf(y), 'L', pf(xw), pf(yh), 'L', pf(x), pf(yh), 'Z');
  3498. break;
  3499. case OPS.moveTo:
  3500. x = args[j++];
  3501. y = args[j++];
  3502. d.push('M', pf(x), pf(y));
  3503. break;
  3504. case OPS.lineTo:
  3505. x = args[j++];
  3506. y = args[j++];
  3507. d.push('L', pf(x), pf(y));
  3508. break;
  3509. case OPS.curveTo:
  3510. x = args[j + 4];
  3511. y = args[j + 5];
  3512. d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y));
  3513. j += 6;
  3514. break;
  3515. case OPS.curveTo2:
  3516. x = args[j + 2];
  3517. y = args[j + 3];
  3518. d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]));
  3519. j += 4;
  3520. break;
  3521. case OPS.curveTo3:
  3522. x = args[j + 2];
  3523. y = args[j + 3];
  3524. d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y));
  3525. j += 4;
  3526. break;
  3527. case OPS.closePath:
  3528. d.push('Z');
  3529. break;
  3530. }
  3531. }
  3532. current.path.setAttributeNS(null, 'd', d.join(' '));
  3533. current.path.setAttributeNS(null, 'stroke-miterlimit', pf(current.miterLimit));
  3534. current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap);
  3535. current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);
  3536. current.path.setAttributeNS(null, 'stroke-width', pf(current.lineWidth) + 'px');
  3537. current.path.setAttributeNS(null, 'stroke-dasharray', current.dashArray.map(pf).join(' '));
  3538. current.path.setAttributeNS(null, 'stroke-dashoffset', pf(current.dashPhase) + 'px');
  3539. current.path.setAttributeNS(null, 'fill', 'none');
  3540. this._ensureTransformGroup().appendChild(current.path);
  3541. current.element = current.path;
  3542. current.setCurrentPoint(x, y);
  3543. },
  3544. endPath: function SVGGraphics_endPath() {
  3545. },
  3546. clip: function SVGGraphics_clip(type) {
  3547. var current = this.current;
  3548. var clipId = 'clippath' + clipCount;
  3549. clipCount++;
  3550. var clipPath = document.createElementNS(NS, 'svg:clipPath');
  3551. clipPath.setAttributeNS(null, 'id', clipId);
  3552. clipPath.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3553. var clipElement = current.element.cloneNode();
  3554. if (type === 'evenodd') {
  3555. clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');
  3556. } else {
  3557. clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');
  3558. }
  3559. clipPath.appendChild(clipElement);
  3560. this.defs.appendChild(clipPath);
  3561. if (current.activeClipUrl) {
  3562. current.clipGroup = null;
  3563. this.extraStack.forEach(function (prev) {
  3564. prev.clipGroup = null;
  3565. });
  3566. }
  3567. current.activeClipUrl = 'url(#' + clipId + ')';
  3568. this.tgrp = null;
  3569. },
  3570. closePath: function SVGGraphics_closePath() {
  3571. var current = this.current;
  3572. var d = current.path.getAttributeNS(null, 'd');
  3573. d += 'Z';
  3574. current.path.setAttributeNS(null, 'd', d);
  3575. },
  3576. setLeading: function SVGGraphics_setLeading(leading) {
  3577. this.current.leading = -leading;
  3578. },
  3579. setTextRise: function SVGGraphics_setTextRise(textRise) {
  3580. this.current.textRise = textRise;
  3581. },
  3582. setHScale: function SVGGraphics_setHScale(scale) {
  3583. this.current.textHScale = scale / 100;
  3584. },
  3585. setGState: function SVGGraphics_setGState(states) {
  3586. for (var i = 0, ii = states.length; i < ii; i++) {
  3587. var state = states[i];
  3588. var key = state[0];
  3589. var value = state[1];
  3590. switch (key) {
  3591. case 'LW':
  3592. this.setLineWidth(value);
  3593. break;
  3594. case 'LC':
  3595. this.setLineCap(value);
  3596. break;
  3597. case 'LJ':
  3598. this.setLineJoin(value);
  3599. break;
  3600. case 'ML':
  3601. this.setMiterLimit(value);
  3602. break;
  3603. case 'D':
  3604. this.setDash(value[0], value[1]);
  3605. break;
  3606. case 'Font':
  3607. this.setFont(value);
  3608. break;
  3609. default:
  3610. warn('Unimplemented graphic state ' + key);
  3611. break;
  3612. }
  3613. }
  3614. },
  3615. fill: function SVGGraphics_fill() {
  3616. var current = this.current;
  3617. current.element.setAttributeNS(null, 'fill', current.fillColor);
  3618. },
  3619. stroke: function SVGGraphics_stroke() {
  3620. var current = this.current;
  3621. current.element.setAttributeNS(null, 'stroke', current.strokeColor);
  3622. current.element.setAttributeNS(null, 'fill', 'none');
  3623. },
  3624. eoFill: function SVGGraphics_eoFill() {
  3625. var current = this.current;
  3626. current.element.setAttributeNS(null, 'fill', current.fillColor);
  3627. current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  3628. },
  3629. fillStroke: function SVGGraphics_fillStroke() {
  3630. this.stroke();
  3631. this.fill();
  3632. },
  3633. eoFillStroke: function SVGGraphics_eoFillStroke() {
  3634. this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  3635. this.fillStroke();
  3636. },
  3637. closeStroke: function SVGGraphics_closeStroke() {
  3638. this.closePath();
  3639. this.stroke();
  3640. },
  3641. closeFillStroke: function SVGGraphics_closeFillStroke() {
  3642. this.closePath();
  3643. this.fillStroke();
  3644. },
  3645. paintSolidColorImageMask: function SVGGraphics_paintSolidColorImageMask() {
  3646. var current = this.current;
  3647. var rect = document.createElementNS(NS, 'svg:rect');
  3648. rect.setAttributeNS(null, 'x', '0');
  3649. rect.setAttributeNS(null, 'y', '0');
  3650. rect.setAttributeNS(null, 'width', '1px');
  3651. rect.setAttributeNS(null, 'height', '1px');
  3652. rect.setAttributeNS(null, 'fill', current.fillColor);
  3653. this._ensureTransformGroup().appendChild(rect);
  3654. },
  3655. paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) {
  3656. var imgObj = this.objs.get(objId);
  3657. var imgEl = document.createElementNS(NS, 'svg:image');
  3658. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);
  3659. imgEl.setAttributeNS(null, 'width', imgObj.width + 'px');
  3660. imgEl.setAttributeNS(null, 'height', imgObj.height + 'px');
  3661. imgEl.setAttributeNS(null, 'x', '0');
  3662. imgEl.setAttributeNS(null, 'y', pf(-h));
  3663. imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')');
  3664. this._ensureTransformGroup().appendChild(imgEl);
  3665. },
  3666. paintImageXObject: function SVGGraphics_paintImageXObject(objId) {
  3667. var imgData = this.objs.get(objId);
  3668. if (!imgData) {
  3669. warn('Dependent image isn\'t ready yet');
  3670. return;
  3671. }
  3672. this.paintInlineImageXObject(imgData);
  3673. },
  3674. paintInlineImageXObject: function SVGGraphics_paintInlineImageXObject(imgData, mask) {
  3675. var width = imgData.width;
  3676. var height = imgData.height;
  3677. var imgSrc = convertImgDataToPng(imgData, this.forceDataSchema);
  3678. var cliprect = document.createElementNS(NS, 'svg:rect');
  3679. cliprect.setAttributeNS(null, 'x', '0');
  3680. cliprect.setAttributeNS(null, 'y', '0');
  3681. cliprect.setAttributeNS(null, 'width', pf(width));
  3682. cliprect.setAttributeNS(null, 'height', pf(height));
  3683. this.current.element = cliprect;
  3684. this.clip('nonzero');
  3685. var imgEl = document.createElementNS(NS, 'svg:image');
  3686. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);
  3687. imgEl.setAttributeNS(null, 'x', '0');
  3688. imgEl.setAttributeNS(null, 'y', pf(-height));
  3689. imgEl.setAttributeNS(null, 'width', pf(width) + 'px');
  3690. imgEl.setAttributeNS(null, 'height', pf(height) + 'px');
  3691. imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / width) + ' ' + pf(-1 / height) + ')');
  3692. if (mask) {
  3693. mask.appendChild(imgEl);
  3694. } else {
  3695. this._ensureTransformGroup().appendChild(imgEl);
  3696. }
  3697. },
  3698. paintImageMaskXObject: function SVGGraphics_paintImageMaskXObject(imgData) {
  3699. var current = this.current;
  3700. var width = imgData.width;
  3701. var height = imgData.height;
  3702. var fillColor = current.fillColor;
  3703. current.maskId = 'mask' + maskCount++;
  3704. var mask = document.createElementNS(NS, 'svg:mask');
  3705. mask.setAttributeNS(null, 'id', current.maskId);
  3706. var rect = document.createElementNS(NS, 'svg:rect');
  3707. rect.setAttributeNS(null, 'x', '0');
  3708. rect.setAttributeNS(null, 'y', '0');
  3709. rect.setAttributeNS(null, 'width', pf(width));
  3710. rect.setAttributeNS(null, 'height', pf(height));
  3711. rect.setAttributeNS(null, 'fill', fillColor);
  3712. rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId + ')');
  3713. this.defs.appendChild(mask);
  3714. this._ensureTransformGroup().appendChild(rect);
  3715. this.paintInlineImageXObject(imgData, mask);
  3716. },
  3717. paintFormXObjectBegin: function SVGGraphics_paintFormXObjectBegin(matrix, bbox) {
  3718. if (isArray(matrix) && matrix.length === 6) {
  3719. this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
  3720. }
  3721. if (isArray(bbox) && bbox.length === 4) {
  3722. var width = bbox[2] - bbox[0];
  3723. var height = bbox[3] - bbox[1];
  3724. var cliprect = document.createElementNS(NS, 'svg:rect');
  3725. cliprect.setAttributeNS(null, 'x', bbox[0]);
  3726. cliprect.setAttributeNS(null, 'y', bbox[1]);
  3727. cliprect.setAttributeNS(null, 'width', pf(width));
  3728. cliprect.setAttributeNS(null, 'height', pf(height));
  3729. this.current.element = cliprect;
  3730. this.clip('nonzero');
  3731. this.endPath();
  3732. }
  3733. },
  3734. paintFormXObjectEnd: function SVGGraphics_paintFormXObjectEnd() {
  3735. },
  3736. _initialize: function SVGGraphics_initialize(viewport) {
  3737. var svg = document.createElementNS(NS, 'svg:svg');
  3738. svg.setAttributeNS(null, 'version', '1.1');
  3739. svg.setAttributeNS(null, 'width', viewport.width + 'px');
  3740. svg.setAttributeNS(null, 'height', viewport.height + 'px');
  3741. svg.setAttributeNS(null, 'preserveAspectRatio', 'none');
  3742. svg.setAttributeNS(null, 'viewBox', '0 0 ' + viewport.width + ' ' + viewport.height);
  3743. var definitions = document.createElementNS(NS, 'svg:defs');
  3744. svg.appendChild(definitions);
  3745. this.defs = definitions;
  3746. var rootGroup = document.createElementNS(NS, 'svg:g');
  3747. rootGroup.setAttributeNS(null, 'transform', pm(viewport.transform));
  3748. svg.appendChild(rootGroup);
  3749. this.svg = rootGroup;
  3750. return svg;
  3751. },
  3752. _ensureClipGroup: function SVGGraphics_ensureClipGroup() {
  3753. if (!this.current.clipGroup) {
  3754. var clipGroup = document.createElementNS(NS, 'svg:g');
  3755. clipGroup.setAttributeNS(null, 'clip-path', this.current.activeClipUrl);
  3756. this.svg.appendChild(clipGroup);
  3757. this.current.clipGroup = clipGroup;
  3758. }
  3759. return this.current.clipGroup;
  3760. },
  3761. _ensureTransformGroup: function SVGGraphics_ensureTransformGroup() {
  3762. if (!this.tgrp) {
  3763. this.tgrp = document.createElementNS(NS, 'svg:g');
  3764. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3765. if (this.current.activeClipUrl) {
  3766. this._ensureClipGroup().appendChild(this.tgrp);
  3767. } else {
  3768. this.svg.appendChild(this.tgrp);
  3769. }
  3770. }
  3771. return this.tgrp;
  3772. }
  3773. };
  3774. return SVGGraphics;
  3775. }();
  3776. exports.SVGGraphics = SVGGraphics;
  3777. }));
  3778. (function (root, factory) {
  3779. factory(root.pdfjsDisplayAnnotationLayer = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils);
  3780. }(this, function (exports, sharedUtil, displayDOMUtils) {
  3781. var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType;
  3782. var AnnotationType = sharedUtil.AnnotationType;
  3783. var Util = sharedUtil.Util;
  3784. var addLinkAttributes = displayDOMUtils.addLinkAttributes;
  3785. var LinkTarget = displayDOMUtils.LinkTarget;
  3786. var getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  3787. var warn = sharedUtil.warn;
  3788. var CustomStyle = displayDOMUtils.CustomStyle;
  3789. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  3790. function AnnotationElementFactory() {
  3791. }
  3792. AnnotationElementFactory.prototype = {
  3793. create: function AnnotationElementFactory_create(parameters) {
  3794. var subtype = parameters.data.annotationType;
  3795. switch (subtype) {
  3796. case AnnotationType.LINK:
  3797. return new LinkAnnotationElement(parameters);
  3798. case AnnotationType.TEXT:
  3799. return new TextAnnotationElement(parameters);
  3800. case AnnotationType.WIDGET:
  3801. var fieldType = parameters.data.fieldType;
  3802. switch (fieldType) {
  3803. case 'Tx':
  3804. return new TextWidgetAnnotationElement(parameters);
  3805. case 'Btn':
  3806. if (parameters.data.radioButton) {
  3807. return new RadioButtonWidgetAnnotationElement(parameters);
  3808. } else if (parameters.data.checkBox) {
  3809. return new CheckboxWidgetAnnotationElement(parameters);
  3810. }
  3811. warn('Unimplemented button widget annotation: pushbutton');
  3812. break;
  3813. case 'Ch':
  3814. return new ChoiceWidgetAnnotationElement(parameters);
  3815. }
  3816. return new WidgetAnnotationElement(parameters);
  3817. case AnnotationType.POPUP:
  3818. return new PopupAnnotationElement(parameters);
  3819. case AnnotationType.HIGHLIGHT:
  3820. return new HighlightAnnotationElement(parameters);
  3821. case AnnotationType.UNDERLINE:
  3822. return new UnderlineAnnotationElement(parameters);
  3823. case AnnotationType.SQUIGGLY:
  3824. return new SquigglyAnnotationElement(parameters);
  3825. case AnnotationType.STRIKEOUT:
  3826. return new StrikeOutAnnotationElement(parameters);
  3827. case AnnotationType.FILEATTACHMENT:
  3828. return new FileAttachmentAnnotationElement(parameters);
  3829. default:
  3830. return new AnnotationElement(parameters);
  3831. }
  3832. }
  3833. };
  3834. var AnnotationElement = function AnnotationElementClosure() {
  3835. function AnnotationElement(parameters, isRenderable) {
  3836. this.isRenderable = isRenderable || false;
  3837. this.data = parameters.data;
  3838. this.layer = parameters.layer;
  3839. this.page = parameters.page;
  3840. this.viewport = parameters.viewport;
  3841. this.linkService = parameters.linkService;
  3842. this.downloadManager = parameters.downloadManager;
  3843. this.imageResourcesPath = parameters.imageResourcesPath;
  3844. this.renderInteractiveForms = parameters.renderInteractiveForms;
  3845. if (isRenderable) {
  3846. this.container = this._createContainer();
  3847. }
  3848. }
  3849. AnnotationElement.prototype = {
  3850. _createContainer: function AnnotationElement_createContainer() {
  3851. var data = this.data, page = this.page, viewport = this.viewport;
  3852. var container = document.createElement('section');
  3853. var width = data.rect[2] - data.rect[0];
  3854. var height = data.rect[3] - data.rect[1];
  3855. container.setAttribute('data-annotation-id', data.id);
  3856. var rect = Util.normalizeRect([
  3857. data.rect[0],
  3858. page.view[3] - data.rect[1] + page.view[1],
  3859. data.rect[2],
  3860. page.view[3] - data.rect[3] + page.view[1]
  3861. ]);
  3862. CustomStyle.setProp('transform', container, 'matrix(' + viewport.transform.join(',') + ')');
  3863. CustomStyle.setProp('transformOrigin', container, -rect[0] + 'px ' + -rect[1] + 'px');
  3864. if (data.borderStyle.width > 0) {
  3865. container.style.borderWidth = data.borderStyle.width + 'px';
  3866. if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) {
  3867. width = width - 2 * data.borderStyle.width;
  3868. height = height - 2 * data.borderStyle.width;
  3869. }
  3870. var horizontalRadius = data.borderStyle.horizontalCornerRadius;
  3871. var verticalRadius = data.borderStyle.verticalCornerRadius;
  3872. if (horizontalRadius > 0 || verticalRadius > 0) {
  3873. var radius = horizontalRadius + 'px / ' + verticalRadius + 'px';
  3874. CustomStyle.setProp('borderRadius', container, radius);
  3875. }
  3876. switch (data.borderStyle.style) {
  3877. case AnnotationBorderStyleType.SOLID:
  3878. container.style.borderStyle = 'solid';
  3879. break;
  3880. case AnnotationBorderStyleType.DASHED:
  3881. container.style.borderStyle = 'dashed';
  3882. break;
  3883. case AnnotationBorderStyleType.BEVELED:
  3884. warn('Unimplemented border style: beveled');
  3885. break;
  3886. case AnnotationBorderStyleType.INSET:
  3887. warn('Unimplemented border style: inset');
  3888. break;
  3889. case AnnotationBorderStyleType.UNDERLINE:
  3890. container.style.borderBottomStyle = 'solid';
  3891. break;
  3892. default:
  3893. break;
  3894. }
  3895. if (data.color) {
  3896. container.style.borderColor = Util.makeCssRgb(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0);
  3897. } else {
  3898. container.style.borderWidth = 0;
  3899. }
  3900. }
  3901. container.style.left = rect[0] + 'px';
  3902. container.style.top = rect[1] + 'px';
  3903. container.style.width = width + 'px';
  3904. container.style.height = height + 'px';
  3905. return container;
  3906. },
  3907. _createPopup: function AnnotationElement_createPopup(container, trigger, data) {
  3908. if (!trigger) {
  3909. trigger = document.createElement('div');
  3910. trigger.style.height = container.style.height;
  3911. trigger.style.width = container.style.width;
  3912. container.appendChild(trigger);
  3913. }
  3914. var popupElement = new PopupElement({
  3915. container: container,
  3916. trigger: trigger,
  3917. color: data.color,
  3918. title: data.title,
  3919. contents: data.contents,
  3920. hideWrapper: true
  3921. });
  3922. var popup = popupElement.render();
  3923. popup.style.left = container.style.width;
  3924. container.appendChild(popup);
  3925. },
  3926. render: function AnnotationElement_render() {
  3927. throw new Error('Abstract method AnnotationElement.render called');
  3928. }
  3929. };
  3930. return AnnotationElement;
  3931. }();
  3932. var LinkAnnotationElement = function LinkAnnotationElementClosure() {
  3933. function LinkAnnotationElement(parameters) {
  3934. AnnotationElement.call(this, parameters, true);
  3935. }
  3936. Util.inherit(LinkAnnotationElement, AnnotationElement, {
  3937. render: function LinkAnnotationElement_render() {
  3938. this.container.className = 'linkAnnotation';
  3939. var link = document.createElement('a');
  3940. addLinkAttributes(link, {
  3941. url: this.data.url,
  3942. target: this.data.newWindow ? LinkTarget.BLANK : undefined
  3943. });
  3944. if (!this.data.url) {
  3945. if (this.data.action) {
  3946. this._bindNamedAction(link, this.data.action);
  3947. } else {
  3948. this._bindLink(link, this.data.dest);
  3949. }
  3950. }
  3951. this.container.appendChild(link);
  3952. return this.container;
  3953. },
  3954. _bindLink: function LinkAnnotationElement_bindLink(link, destination) {
  3955. var self = this;
  3956. link.href = this.linkService.getDestinationHash(destination);
  3957. link.onclick = function () {
  3958. if (destination) {
  3959. self.linkService.navigateTo(destination);
  3960. }
  3961. return false;
  3962. };
  3963. if (destination) {
  3964. link.className = 'internalLink';
  3965. }
  3966. },
  3967. _bindNamedAction: function LinkAnnotationElement_bindNamedAction(link, action) {
  3968. var self = this;
  3969. link.href = this.linkService.getAnchorUrl('');
  3970. link.onclick = function () {
  3971. self.linkService.executeNamedAction(action);
  3972. return false;
  3973. };
  3974. link.className = 'internalLink';
  3975. }
  3976. });
  3977. return LinkAnnotationElement;
  3978. }();
  3979. var TextAnnotationElement = function TextAnnotationElementClosure() {
  3980. function TextAnnotationElement(parameters) {
  3981. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  3982. AnnotationElement.call(this, parameters, isRenderable);
  3983. }
  3984. Util.inherit(TextAnnotationElement, AnnotationElement, {
  3985. render: function TextAnnotationElement_render() {
  3986. this.container.className = 'textAnnotation';
  3987. var image = document.createElement('img');
  3988. image.style.height = this.container.style.height;
  3989. image.style.width = this.container.style.width;
  3990. image.src = this.imageResourcesPath + 'annotation-' + this.data.name.toLowerCase() + '.svg';
  3991. image.alt = '[{{type}} Annotation]';
  3992. image.dataset.l10nId = 'text_annotation_type';
  3993. image.dataset.l10nArgs = JSON.stringify({ type: this.data.name });
  3994. if (!this.data.hasPopup) {
  3995. this._createPopup(this.container, image, this.data);
  3996. }
  3997. this.container.appendChild(image);
  3998. return this.container;
  3999. }
  4000. });
  4001. return TextAnnotationElement;
  4002. }();
  4003. var WidgetAnnotationElement = function WidgetAnnotationElementClosure() {
  4004. function WidgetAnnotationElement(parameters, isRenderable) {
  4005. AnnotationElement.call(this, parameters, isRenderable);
  4006. }
  4007. Util.inherit(WidgetAnnotationElement, AnnotationElement, {
  4008. render: function WidgetAnnotationElement_render() {
  4009. return this.container;
  4010. }
  4011. });
  4012. return WidgetAnnotationElement;
  4013. }();
  4014. var TextWidgetAnnotationElement = function TextWidgetAnnotationElementClosure() {
  4015. var TEXT_ALIGNMENT = [
  4016. 'left',
  4017. 'center',
  4018. 'right'
  4019. ];
  4020. function TextWidgetAnnotationElement(parameters) {
  4021. var isRenderable = parameters.renderInteractiveForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
  4022. WidgetAnnotationElement.call(this, parameters, isRenderable);
  4023. }
  4024. Util.inherit(TextWidgetAnnotationElement, WidgetAnnotationElement, {
  4025. render: function TextWidgetAnnotationElement_render() {
  4026. this.container.className = 'textWidgetAnnotation';
  4027. var element = null;
  4028. if (this.renderInteractiveForms) {
  4029. if (this.data.multiLine) {
  4030. element = document.createElement('textarea');
  4031. element.textContent = this.data.fieldValue;
  4032. } else {
  4033. element = document.createElement('input');
  4034. element.type = 'text';
  4035. element.setAttribute('value', this.data.fieldValue);
  4036. }
  4037. element.disabled = this.data.readOnly;
  4038. if (this.data.maxLen !== null) {
  4039. element.maxLength = this.data.maxLen;
  4040. }
  4041. if (this.data.comb) {
  4042. var fieldWidth = this.data.rect[2] - this.data.rect[0];
  4043. var combWidth = fieldWidth / this.data.maxLen;
  4044. element.classList.add('comb');
  4045. element.style.letterSpacing = 'calc(' + combWidth + 'px - 1ch)';
  4046. }
  4047. } else {
  4048. element = document.createElement('div');
  4049. element.textContent = this.data.fieldValue;
  4050. element.style.verticalAlign = 'middle';
  4051. element.style.display = 'table-cell';
  4052. var font = null;
  4053. if (this.data.fontRefName) {
  4054. font = this.page.commonObjs.getData(this.data.fontRefName);
  4055. }
  4056. this._setTextStyle(element, font);
  4057. }
  4058. if (this.data.textAlignment !== null) {
  4059. element.style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  4060. }
  4061. this.container.appendChild(element);
  4062. return this.container;
  4063. },
  4064. _setTextStyle: function TextWidgetAnnotationElement_setTextStyle(element, font) {
  4065. var style = element.style;
  4066. style.fontSize = this.data.fontSize + 'px';
  4067. style.direction = this.data.fontDirection < 0 ? 'rtl' : 'ltr';
  4068. if (!font) {
  4069. return;
  4070. }
  4071. style.fontWeight = font.black ? font.bold ? '900' : 'bold' : font.bold ? 'bold' : 'normal';
  4072. style.fontStyle = font.italic ? 'italic' : 'normal';
  4073. var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : '';
  4074. var fallbackName = font.fallbackName || 'Helvetica, sans-serif';
  4075. style.fontFamily = fontFamily + fallbackName;
  4076. }
  4077. });
  4078. return TextWidgetAnnotationElement;
  4079. }();
  4080. var CheckboxWidgetAnnotationElement = function CheckboxWidgetAnnotationElementClosure() {
  4081. function CheckboxWidgetAnnotationElement(parameters) {
  4082. WidgetAnnotationElement.call(this, parameters, parameters.renderInteractiveForms);
  4083. }
  4084. Util.inherit(CheckboxWidgetAnnotationElement, WidgetAnnotationElement, {
  4085. render: function CheckboxWidgetAnnotationElement_render() {
  4086. this.container.className = 'buttonWidgetAnnotation checkBox';
  4087. var element = document.createElement('input');
  4088. element.disabled = this.data.readOnly;
  4089. element.type = 'checkbox';
  4090. if (this.data.fieldValue && this.data.fieldValue !== 'Off') {
  4091. element.setAttribute('checked', true);
  4092. }
  4093. this.container.appendChild(element);
  4094. return this.container;
  4095. }
  4096. });
  4097. return CheckboxWidgetAnnotationElement;
  4098. }();
  4099. var RadioButtonWidgetAnnotationElement = function RadioButtonWidgetAnnotationElementClosure() {
  4100. function RadioButtonWidgetAnnotationElement(parameters) {
  4101. WidgetAnnotationElement.call(this, parameters, parameters.renderInteractiveForms);
  4102. }
  4103. Util.inherit(RadioButtonWidgetAnnotationElement, WidgetAnnotationElement, {
  4104. render: function RadioButtonWidgetAnnotationElement_render() {
  4105. this.container.className = 'buttonWidgetAnnotation radioButton';
  4106. var element = document.createElement('input');
  4107. element.disabled = this.data.readOnly;
  4108. element.type = 'radio';
  4109. element.name = this.data.fieldName;
  4110. if (this.data.fieldValue === this.data.buttonValue) {
  4111. element.setAttribute('checked', true);
  4112. }
  4113. this.container.appendChild(element);
  4114. return this.container;
  4115. }
  4116. });
  4117. return RadioButtonWidgetAnnotationElement;
  4118. }();
  4119. var ChoiceWidgetAnnotationElement = function ChoiceWidgetAnnotationElementClosure() {
  4120. function ChoiceWidgetAnnotationElement(parameters) {
  4121. WidgetAnnotationElement.call(this, parameters, parameters.renderInteractiveForms);
  4122. }
  4123. Util.inherit(ChoiceWidgetAnnotationElement, WidgetAnnotationElement, {
  4124. render: function ChoiceWidgetAnnotationElement_render() {
  4125. this.container.className = 'choiceWidgetAnnotation';
  4126. var selectElement = document.createElement('select');
  4127. selectElement.disabled = this.data.readOnly;
  4128. if (!this.data.combo) {
  4129. selectElement.size = this.data.options.length;
  4130. if (this.data.multiSelect) {
  4131. selectElement.multiple = true;
  4132. }
  4133. }
  4134. for (var i = 0, ii = this.data.options.length; i < ii; i++) {
  4135. var option = this.data.options[i];
  4136. var optionElement = document.createElement('option');
  4137. optionElement.textContent = option.displayValue;
  4138. optionElement.value = option.exportValue;
  4139. if (this.data.fieldValue.indexOf(option.displayValue) >= 0) {
  4140. optionElement.setAttribute('selected', true);
  4141. }
  4142. selectElement.appendChild(optionElement);
  4143. }
  4144. this.container.appendChild(selectElement);
  4145. return this.container;
  4146. }
  4147. });
  4148. return ChoiceWidgetAnnotationElement;
  4149. }();
  4150. var PopupAnnotationElement = function PopupAnnotationElementClosure() {
  4151. function PopupAnnotationElement(parameters) {
  4152. var isRenderable = !!(parameters.data.title || parameters.data.contents);
  4153. AnnotationElement.call(this, parameters, isRenderable);
  4154. }
  4155. Util.inherit(PopupAnnotationElement, AnnotationElement, {
  4156. render: function PopupAnnotationElement_render() {
  4157. this.container.className = 'popupAnnotation';
  4158. var selector = '[data-annotation-id="' + this.data.parentId + '"]';
  4159. var parentElement = this.layer.querySelector(selector);
  4160. if (!parentElement) {
  4161. return this.container;
  4162. }
  4163. var popup = new PopupElement({
  4164. container: this.container,
  4165. trigger: parentElement,
  4166. color: this.data.color,
  4167. title: this.data.title,
  4168. contents: this.data.contents
  4169. });
  4170. var parentLeft = parseFloat(parentElement.style.left);
  4171. var parentWidth = parseFloat(parentElement.style.width);
  4172. CustomStyle.setProp('transformOrigin', this.container, -(parentLeft + parentWidth) + 'px -' + parentElement.style.top);
  4173. this.container.style.left = parentLeft + parentWidth + 'px';
  4174. this.container.appendChild(popup.render());
  4175. return this.container;
  4176. }
  4177. });
  4178. return PopupAnnotationElement;
  4179. }();
  4180. var PopupElement = function PopupElementClosure() {
  4181. var BACKGROUND_ENLIGHT = 0.7;
  4182. function PopupElement(parameters) {
  4183. this.container = parameters.container;
  4184. this.trigger = parameters.trigger;
  4185. this.color = parameters.color;
  4186. this.title = parameters.title;
  4187. this.contents = parameters.contents;
  4188. this.hideWrapper = parameters.hideWrapper || false;
  4189. this.pinned = false;
  4190. }
  4191. PopupElement.prototype = {
  4192. render: function PopupElement_render() {
  4193. var wrapper = document.createElement('div');
  4194. wrapper.className = 'popupWrapper';
  4195. this.hideElement = this.hideWrapper ? wrapper : this.container;
  4196. this.hideElement.setAttribute('hidden', true);
  4197. var popup = document.createElement('div');
  4198. popup.className = 'popup';
  4199. var color = this.color;
  4200. if (color) {
  4201. var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  4202. var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  4203. var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  4204. popup.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0);
  4205. }
  4206. var contents = this._formatContents(this.contents);
  4207. var title = document.createElement('h1');
  4208. title.textContent = this.title;
  4209. this.trigger.addEventListener('click', this._toggle.bind(this));
  4210. this.trigger.addEventListener('mouseover', this._show.bind(this, false));
  4211. this.trigger.addEventListener('mouseout', this._hide.bind(this, false));
  4212. popup.addEventListener('click', this._hide.bind(this, true));
  4213. popup.appendChild(title);
  4214. popup.appendChild(contents);
  4215. wrapper.appendChild(popup);
  4216. return wrapper;
  4217. },
  4218. _formatContents: function PopupElement_formatContents(contents) {
  4219. var p = document.createElement('p');
  4220. var lines = contents.split(/(?:\r\n?|\n)/);
  4221. for (var i = 0, ii = lines.length; i < ii; ++i) {
  4222. var line = lines[i];
  4223. p.appendChild(document.createTextNode(line));
  4224. if (i < ii - 1) {
  4225. p.appendChild(document.createElement('br'));
  4226. }
  4227. }
  4228. return p;
  4229. },
  4230. _toggle: function PopupElement_toggle() {
  4231. if (this.pinned) {
  4232. this._hide(true);
  4233. } else {
  4234. this._show(true);
  4235. }
  4236. },
  4237. _show: function PopupElement_show(pin) {
  4238. if (pin) {
  4239. this.pinned = true;
  4240. }
  4241. if (this.hideElement.hasAttribute('hidden')) {
  4242. this.hideElement.removeAttribute('hidden');
  4243. this.container.style.zIndex += 1;
  4244. }
  4245. },
  4246. _hide: function PopupElement_hide(unpin) {
  4247. if (unpin) {
  4248. this.pinned = false;
  4249. }
  4250. if (!this.hideElement.hasAttribute('hidden') && !this.pinned) {
  4251. this.hideElement.setAttribute('hidden', true);
  4252. this.container.style.zIndex -= 1;
  4253. }
  4254. }
  4255. };
  4256. return PopupElement;
  4257. }();
  4258. var HighlightAnnotationElement = function HighlightAnnotationElementClosure() {
  4259. function HighlightAnnotationElement(parameters) {
  4260. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4261. AnnotationElement.call(this, parameters, isRenderable);
  4262. }
  4263. Util.inherit(HighlightAnnotationElement, AnnotationElement, {
  4264. render: function HighlightAnnotationElement_render() {
  4265. this.container.className = 'highlightAnnotation';
  4266. if (!this.data.hasPopup) {
  4267. this._createPopup(this.container, null, this.data);
  4268. }
  4269. return this.container;
  4270. }
  4271. });
  4272. return HighlightAnnotationElement;
  4273. }();
  4274. var UnderlineAnnotationElement = function UnderlineAnnotationElementClosure() {
  4275. function UnderlineAnnotationElement(parameters) {
  4276. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4277. AnnotationElement.call(this, parameters, isRenderable);
  4278. }
  4279. Util.inherit(UnderlineAnnotationElement, AnnotationElement, {
  4280. render: function UnderlineAnnotationElement_render() {
  4281. this.container.className = 'underlineAnnotation';
  4282. if (!this.data.hasPopup) {
  4283. this._createPopup(this.container, null, this.data);
  4284. }
  4285. return this.container;
  4286. }
  4287. });
  4288. return UnderlineAnnotationElement;
  4289. }();
  4290. var SquigglyAnnotationElement = function SquigglyAnnotationElementClosure() {
  4291. function SquigglyAnnotationElement(parameters) {
  4292. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4293. AnnotationElement.call(this, parameters, isRenderable);
  4294. }
  4295. Util.inherit(SquigglyAnnotationElement, AnnotationElement, {
  4296. render: function SquigglyAnnotationElement_render() {
  4297. this.container.className = 'squigglyAnnotation';
  4298. if (!this.data.hasPopup) {
  4299. this._createPopup(this.container, null, this.data);
  4300. }
  4301. return this.container;
  4302. }
  4303. });
  4304. return SquigglyAnnotationElement;
  4305. }();
  4306. var StrikeOutAnnotationElement = function StrikeOutAnnotationElementClosure() {
  4307. function StrikeOutAnnotationElement(parameters) {
  4308. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4309. AnnotationElement.call(this, parameters, isRenderable);
  4310. }
  4311. Util.inherit(StrikeOutAnnotationElement, AnnotationElement, {
  4312. render: function StrikeOutAnnotationElement_render() {
  4313. this.container.className = 'strikeoutAnnotation';
  4314. if (!this.data.hasPopup) {
  4315. this._createPopup(this.container, null, this.data);
  4316. }
  4317. return this.container;
  4318. }
  4319. });
  4320. return StrikeOutAnnotationElement;
  4321. }();
  4322. var FileAttachmentAnnotationElement = function FileAttachmentAnnotationElementClosure() {
  4323. function FileAttachmentAnnotationElement(parameters) {
  4324. AnnotationElement.call(this, parameters, true);
  4325. this.filename = getFilenameFromUrl(parameters.data.file.filename);
  4326. this.content = parameters.data.file.content;
  4327. }
  4328. Util.inherit(FileAttachmentAnnotationElement, AnnotationElement, {
  4329. render: function FileAttachmentAnnotationElement_render() {
  4330. this.container.className = 'fileAttachmentAnnotation';
  4331. var trigger = document.createElement('div');
  4332. trigger.style.height = this.container.style.height;
  4333. trigger.style.width = this.container.style.width;
  4334. trigger.addEventListener('dblclick', this._download.bind(this));
  4335. if (!this.data.hasPopup && (this.data.title || this.data.contents)) {
  4336. this._createPopup(this.container, trigger, this.data);
  4337. }
  4338. this.container.appendChild(trigger);
  4339. return this.container;
  4340. },
  4341. _download: function FileAttachmentAnnotationElement_download() {
  4342. if (!this.downloadManager) {
  4343. warn('Download cannot be started due to unavailable download manager');
  4344. return;
  4345. }
  4346. this.downloadManager.downloadData(this.content, this.filename, '');
  4347. }
  4348. });
  4349. return FileAttachmentAnnotationElement;
  4350. }();
  4351. var AnnotationLayer = function AnnotationLayerClosure() {
  4352. return {
  4353. render: function AnnotationLayer_render(parameters) {
  4354. var annotationElementFactory = new AnnotationElementFactory();
  4355. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4356. var data = parameters.annotations[i];
  4357. if (!data) {
  4358. continue;
  4359. }
  4360. var properties = {
  4361. data: data,
  4362. layer: parameters.div,
  4363. page: parameters.page,
  4364. viewport: parameters.viewport,
  4365. linkService: parameters.linkService,
  4366. downloadManager: parameters.downloadManager,
  4367. imageResourcesPath: parameters.imageResourcesPath || getDefaultSetting('imageResourcesPath'),
  4368. renderInteractiveForms: parameters.renderInteractiveForms || false
  4369. };
  4370. var element = annotationElementFactory.create(properties);
  4371. if (element.isRenderable) {
  4372. parameters.div.appendChild(element.render());
  4373. }
  4374. }
  4375. },
  4376. update: function AnnotationLayer_update(parameters) {
  4377. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4378. var data = parameters.annotations[i];
  4379. var element = parameters.div.querySelector('[data-annotation-id="' + data.id + '"]');
  4380. if (element) {
  4381. CustomStyle.setProp('transform', element, 'matrix(' + parameters.viewport.transform.join(',') + ')');
  4382. }
  4383. }
  4384. parameters.div.removeAttribute('hidden');
  4385. }
  4386. };
  4387. }();
  4388. exports.AnnotationLayer = AnnotationLayer;
  4389. }));
  4390. (function (root, factory) {
  4391. factory(root.pdfjsDisplayTextLayer = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils);
  4392. }(this, function (exports, sharedUtil, displayDOMUtils) {
  4393. var Util = sharedUtil.Util;
  4394. var createPromiseCapability = sharedUtil.createPromiseCapability;
  4395. var CustomStyle = displayDOMUtils.CustomStyle;
  4396. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  4397. var renderTextLayer = function renderTextLayerClosure() {
  4398. var MAX_TEXT_DIVS_TO_RENDER = 100000;
  4399. var NonWhitespaceRegexp = /\S/;
  4400. function isAllWhitespace(str) {
  4401. return !NonWhitespaceRegexp.test(str);
  4402. }
  4403. var styleBuf = [
  4404. 'left: ',
  4405. 0,
  4406. 'px; top: ',
  4407. 0,
  4408. 'px; font-size: ',
  4409. 0,
  4410. 'px; font-family: ',
  4411. '',
  4412. ';'
  4413. ];
  4414. function appendText(task, geom, styles) {
  4415. var textDiv = document.createElement('div');
  4416. var textDivProperties = {
  4417. style: null,
  4418. angle: 0,
  4419. canvasWidth: 0,
  4420. isWhitespace: false,
  4421. originalTransform: null,
  4422. paddingBottom: 0,
  4423. paddingLeft: 0,
  4424. paddingRight: 0,
  4425. paddingTop: 0,
  4426. scale: 1
  4427. };
  4428. task._textDivs.push(textDiv);
  4429. if (isAllWhitespace(geom.str)) {
  4430. textDivProperties.isWhitespace = true;
  4431. task._textDivProperties.set(textDiv, textDivProperties);
  4432. return;
  4433. }
  4434. var tx = Util.transform(task._viewport.transform, geom.transform);
  4435. var angle = Math.atan2(tx[1], tx[0]);
  4436. var style = styles[geom.fontName];
  4437. if (style.vertical) {
  4438. angle += Math.PI / 2;
  4439. }
  4440. var fontHeight = Math.sqrt(tx[2] * tx[2] + tx[3] * tx[3]);
  4441. var fontAscent = fontHeight;
  4442. if (style.ascent) {
  4443. fontAscent = style.ascent * fontAscent;
  4444. } else if (style.descent) {
  4445. fontAscent = (1 + style.descent) * fontAscent;
  4446. }
  4447. var left;
  4448. var top;
  4449. if (angle === 0) {
  4450. left = tx[4];
  4451. top = tx[5] - fontAscent;
  4452. } else {
  4453. left = tx[4] + fontAscent * Math.sin(angle);
  4454. top = tx[5] - fontAscent * Math.cos(angle);
  4455. }
  4456. styleBuf[1] = left;
  4457. styleBuf[3] = top;
  4458. styleBuf[5] = fontHeight;
  4459. styleBuf[7] = style.fontFamily;
  4460. textDivProperties.style = styleBuf.join('');
  4461. textDiv.setAttribute('style', textDivProperties.style);
  4462. textDiv.textContent = geom.str;
  4463. if (getDefaultSetting('pdfBug')) {
  4464. textDiv.dataset.fontName = geom.fontName;
  4465. }
  4466. if (angle !== 0) {
  4467. textDivProperties.angle = angle * (180 / Math.PI);
  4468. }
  4469. if (geom.str.length > 1) {
  4470. if (style.vertical) {
  4471. textDivProperties.canvasWidth = geom.height * task._viewport.scale;
  4472. } else {
  4473. textDivProperties.canvasWidth = geom.width * task._viewport.scale;
  4474. }
  4475. }
  4476. task._textDivProperties.set(textDiv, textDivProperties);
  4477. if (task._enhanceTextSelection) {
  4478. var angleCos = 1, angleSin = 0;
  4479. if (angle !== 0) {
  4480. angleCos = Math.cos(angle);
  4481. angleSin = Math.sin(angle);
  4482. }
  4483. var divWidth = (style.vertical ? geom.height : geom.width) * task._viewport.scale;
  4484. var divHeight = fontHeight;
  4485. var m, b;
  4486. if (angle !== 0) {
  4487. m = [
  4488. angleCos,
  4489. angleSin,
  4490. -angleSin,
  4491. angleCos,
  4492. left,
  4493. top
  4494. ];
  4495. b = Util.getAxialAlignedBoundingBox([
  4496. 0,
  4497. 0,
  4498. divWidth,
  4499. divHeight
  4500. ], m);
  4501. } else {
  4502. b = [
  4503. left,
  4504. top,
  4505. left + divWidth,
  4506. top + divHeight
  4507. ];
  4508. }
  4509. task._bounds.push({
  4510. left: b[0],
  4511. top: b[1],
  4512. right: b[2],
  4513. bottom: b[3],
  4514. div: textDiv,
  4515. size: [
  4516. divWidth,
  4517. divHeight
  4518. ],
  4519. m: m
  4520. });
  4521. }
  4522. }
  4523. function render(task) {
  4524. if (task._canceled) {
  4525. return;
  4526. }
  4527. var textLayerFrag = task._container;
  4528. var textDivs = task._textDivs;
  4529. var capability = task._capability;
  4530. var textDivsLength = textDivs.length;
  4531. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  4532. task._renderingDone = true;
  4533. capability.resolve();
  4534. return;
  4535. }
  4536. var canvas = document.createElement('canvas');
  4537. canvas.mozOpaque = true;
  4538. var ctx = canvas.getContext('2d', { alpha: false });
  4539. var lastFontSize;
  4540. var lastFontFamily;
  4541. for (var i = 0; i < textDivsLength; i++) {
  4542. var textDiv = textDivs[i];
  4543. var textDivProperties = task._textDivProperties.get(textDiv);
  4544. if (textDivProperties.isWhitespace) {
  4545. continue;
  4546. }
  4547. var fontSize = textDiv.style.fontSize;
  4548. var fontFamily = textDiv.style.fontFamily;
  4549. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {
  4550. ctx.font = fontSize + ' ' + fontFamily;
  4551. lastFontSize = fontSize;
  4552. lastFontFamily = fontFamily;
  4553. }
  4554. var width = ctx.measureText(textDiv.textContent).width;
  4555. textLayerFrag.appendChild(textDiv);
  4556. var transform = '';
  4557. if (textDivProperties.canvasWidth !== 0 && width > 0) {
  4558. textDivProperties.scale = textDivProperties.canvasWidth / width;
  4559. transform = 'scaleX(' + textDivProperties.scale + ')';
  4560. }
  4561. if (textDivProperties.angle !== 0) {
  4562. transform = 'rotate(' + textDivProperties.angle + 'deg) ' + transform;
  4563. }
  4564. if (transform !== '') {
  4565. textDivProperties.originalTransform = transform;
  4566. CustomStyle.setProp('transform', textDiv, transform);
  4567. }
  4568. task._textDivProperties.set(textDiv, textDivProperties);
  4569. }
  4570. task._renderingDone = true;
  4571. capability.resolve();
  4572. }
  4573. function expand(task) {
  4574. var bounds = task._bounds;
  4575. var viewport = task._viewport;
  4576. var expanded = expandBounds(viewport.width, viewport.height, bounds);
  4577. for (var i = 0; i < expanded.length; i++) {
  4578. var div = bounds[i].div;
  4579. var divProperties = task._textDivProperties.get(div);
  4580. if (divProperties.angle === 0) {
  4581. divProperties.paddingLeft = bounds[i].left - expanded[i].left;
  4582. divProperties.paddingTop = bounds[i].top - expanded[i].top;
  4583. divProperties.paddingRight = expanded[i].right - bounds[i].right;
  4584. divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom;
  4585. task._textDivProperties.set(div, divProperties);
  4586. continue;
  4587. }
  4588. var e = expanded[i], b = bounds[i];
  4589. var m = b.m, c = m[0], s = m[1];
  4590. var points = [
  4591. [
  4592. 0,
  4593. 0
  4594. ],
  4595. [
  4596. 0,
  4597. b.size[1]
  4598. ],
  4599. [
  4600. b.size[0],
  4601. 0
  4602. ],
  4603. b.size
  4604. ];
  4605. var ts = new Float64Array(64);
  4606. points.forEach(function (p, i) {
  4607. var t = Util.applyTransform(p, m);
  4608. ts[i + 0] = c && (e.left - t[0]) / c;
  4609. ts[i + 4] = s && (e.top - t[1]) / s;
  4610. ts[i + 8] = c && (e.right - t[0]) / c;
  4611. ts[i + 12] = s && (e.bottom - t[1]) / s;
  4612. ts[i + 16] = s && (e.left - t[0]) / -s;
  4613. ts[i + 20] = c && (e.top - t[1]) / c;
  4614. ts[i + 24] = s && (e.right - t[0]) / -s;
  4615. ts[i + 28] = c && (e.bottom - t[1]) / c;
  4616. ts[i + 32] = c && (e.left - t[0]) / -c;
  4617. ts[i + 36] = s && (e.top - t[1]) / -s;
  4618. ts[i + 40] = c && (e.right - t[0]) / -c;
  4619. ts[i + 44] = s && (e.bottom - t[1]) / -s;
  4620. ts[i + 48] = s && (e.left - t[0]) / s;
  4621. ts[i + 52] = c && (e.top - t[1]) / -c;
  4622. ts[i + 56] = s && (e.right - t[0]) / s;
  4623. ts[i + 60] = c && (e.bottom - t[1]) / -c;
  4624. });
  4625. var findPositiveMin = function (ts, offset, count) {
  4626. var result = 0;
  4627. for (var i = 0; i < count; i++) {
  4628. var t = ts[offset++];
  4629. if (t > 0) {
  4630. result = result ? Math.min(t, result) : t;
  4631. }
  4632. }
  4633. return result;
  4634. };
  4635. var boxScale = 1 + Math.min(Math.abs(c), Math.abs(s));
  4636. divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale;
  4637. divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale;
  4638. divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale;
  4639. divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale;
  4640. task._textDivProperties.set(div, divProperties);
  4641. }
  4642. }
  4643. function expandBounds(width, height, boxes) {
  4644. var bounds = boxes.map(function (box, i) {
  4645. return {
  4646. x1: box.left,
  4647. y1: box.top,
  4648. x2: box.right,
  4649. y2: box.bottom,
  4650. index: i,
  4651. x1New: undefined,
  4652. x2New: undefined
  4653. };
  4654. });
  4655. expandBoundsLTR(width, bounds);
  4656. var expanded = new Array(boxes.length);
  4657. bounds.forEach(function (b) {
  4658. var i = b.index;
  4659. expanded[i] = {
  4660. left: b.x1New,
  4661. top: 0,
  4662. right: b.x2New,
  4663. bottom: 0
  4664. };
  4665. });
  4666. boxes.map(function (box, i) {
  4667. var e = expanded[i], b = bounds[i];
  4668. b.x1 = box.top;
  4669. b.y1 = width - e.right;
  4670. b.x2 = box.bottom;
  4671. b.y2 = width - e.left;
  4672. b.index = i;
  4673. b.x1New = undefined;
  4674. b.x2New = undefined;
  4675. });
  4676. expandBoundsLTR(height, bounds);
  4677. bounds.forEach(function (b) {
  4678. var i = b.index;
  4679. expanded[i].top = b.x1New;
  4680. expanded[i].bottom = b.x2New;
  4681. });
  4682. return expanded;
  4683. }
  4684. function expandBoundsLTR(width, bounds) {
  4685. bounds.sort(function (a, b) {
  4686. return a.x1 - b.x1 || a.index - b.index;
  4687. });
  4688. var fakeBoundary = {
  4689. x1: -Infinity,
  4690. y1: -Infinity,
  4691. x2: 0,
  4692. y2: Infinity,
  4693. index: -1,
  4694. x1New: 0,
  4695. x2New: 0
  4696. };
  4697. var horizon = [{
  4698. start: -Infinity,
  4699. end: Infinity,
  4700. boundary: fakeBoundary
  4701. }];
  4702. bounds.forEach(function (boundary) {
  4703. var i = 0;
  4704. while (i < horizon.length && horizon[i].end <= boundary.y1) {
  4705. i++;
  4706. }
  4707. var j = horizon.length - 1;
  4708. while (j >= 0 && horizon[j].start >= boundary.y2) {
  4709. j--;
  4710. }
  4711. var horizonPart, affectedBoundary;
  4712. var q, k, maxXNew = -Infinity;
  4713. for (q = i; q <= j; q++) {
  4714. horizonPart = horizon[q];
  4715. affectedBoundary = horizonPart.boundary;
  4716. var xNew;
  4717. if (affectedBoundary.x2 > boundary.x1) {
  4718. xNew = affectedBoundary.index > boundary.index ? affectedBoundary.x1New : boundary.x1;
  4719. } else if (affectedBoundary.x2New === undefined) {
  4720. xNew = (affectedBoundary.x2 + boundary.x1) / 2;
  4721. } else {
  4722. xNew = affectedBoundary.x2New;
  4723. }
  4724. if (xNew > maxXNew) {
  4725. maxXNew = xNew;
  4726. }
  4727. }
  4728. boundary.x1New = maxXNew;
  4729. for (q = i; q <= j; q++) {
  4730. horizonPart = horizon[q];
  4731. affectedBoundary = horizonPart.boundary;
  4732. if (affectedBoundary.x2New === undefined) {
  4733. if (affectedBoundary.x2 > boundary.x1) {
  4734. if (affectedBoundary.index > boundary.index) {
  4735. affectedBoundary.x2New = affectedBoundary.x2;
  4736. }
  4737. } else {
  4738. affectedBoundary.x2New = maxXNew;
  4739. }
  4740. } else if (affectedBoundary.x2New > maxXNew) {
  4741. affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2);
  4742. }
  4743. }
  4744. var changedHorizon = [], lastBoundary = null;
  4745. for (q = i; q <= j; q++) {
  4746. horizonPart = horizon[q];
  4747. affectedBoundary = horizonPart.boundary;
  4748. var useBoundary = affectedBoundary.x2 > boundary.x2 ? affectedBoundary : boundary;
  4749. if (lastBoundary === useBoundary) {
  4750. changedHorizon[changedHorizon.length - 1].end = horizonPart.end;
  4751. } else {
  4752. changedHorizon.push({
  4753. start: horizonPart.start,
  4754. end: horizonPart.end,
  4755. boundary: useBoundary
  4756. });
  4757. lastBoundary = useBoundary;
  4758. }
  4759. }
  4760. if (horizon[i].start < boundary.y1) {
  4761. changedHorizon[0].start = boundary.y1;
  4762. changedHorizon.unshift({
  4763. start: horizon[i].start,
  4764. end: boundary.y1,
  4765. boundary: horizon[i].boundary
  4766. });
  4767. }
  4768. if (boundary.y2 < horizon[j].end) {
  4769. changedHorizon[changedHorizon.length - 1].end = boundary.y2;
  4770. changedHorizon.push({
  4771. start: boundary.y2,
  4772. end: horizon[j].end,
  4773. boundary: horizon[j].boundary
  4774. });
  4775. }
  4776. for (q = i; q <= j; q++) {
  4777. horizonPart = horizon[q];
  4778. affectedBoundary = horizonPart.boundary;
  4779. if (affectedBoundary.x2New !== undefined) {
  4780. continue;
  4781. }
  4782. var used = false;
  4783. for (k = i - 1; !used && k >= 0 && horizon[k].start >= affectedBoundary.y1; k--) {
  4784. used = horizon[k].boundary === affectedBoundary;
  4785. }
  4786. for (k = j + 1; !used && k < horizon.length && horizon[k].end <= affectedBoundary.y2; k++) {
  4787. used = horizon[k].boundary === affectedBoundary;
  4788. }
  4789. for (k = 0; !used && k < changedHorizon.length; k++) {
  4790. used = changedHorizon[k].boundary === affectedBoundary;
  4791. }
  4792. if (!used) {
  4793. affectedBoundary.x2New = maxXNew;
  4794. }
  4795. }
  4796. Array.prototype.splice.apply(horizon, [
  4797. i,
  4798. j - i + 1
  4799. ].concat(changedHorizon));
  4800. });
  4801. horizon.forEach(function (horizonPart) {
  4802. var affectedBoundary = horizonPart.boundary;
  4803. if (affectedBoundary.x2New === undefined) {
  4804. affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);
  4805. }
  4806. });
  4807. }
  4808. function TextLayerRenderTask(textContent, container, viewport, textDivs, enhanceTextSelection) {
  4809. this._textContent = textContent;
  4810. this._container = container;
  4811. this._viewport = viewport;
  4812. this._textDivs = textDivs || [];
  4813. this._textDivProperties = new WeakMap();
  4814. this._renderingDone = false;
  4815. this._canceled = false;
  4816. this._capability = createPromiseCapability();
  4817. this._renderTimer = null;
  4818. this._bounds = [];
  4819. this._enhanceTextSelection = !!enhanceTextSelection;
  4820. }
  4821. TextLayerRenderTask.prototype = {
  4822. get promise() {
  4823. return this._capability.promise;
  4824. },
  4825. cancel: function TextLayer_cancel() {
  4826. this._canceled = true;
  4827. if (this._renderTimer !== null) {
  4828. clearTimeout(this._renderTimer);
  4829. this._renderTimer = null;
  4830. }
  4831. this._capability.reject('canceled');
  4832. },
  4833. _render: function TextLayer_render(timeout) {
  4834. var textItems = this._textContent.items;
  4835. var textStyles = this._textContent.styles;
  4836. for (var i = 0, len = textItems.length; i < len; i++) {
  4837. appendText(this, textItems[i], textStyles);
  4838. }
  4839. if (!timeout) {
  4840. render(this);
  4841. } else {
  4842. var self = this;
  4843. this._renderTimer = setTimeout(function () {
  4844. render(self);
  4845. self._renderTimer = null;
  4846. }, timeout);
  4847. }
  4848. },
  4849. expandTextDivs: function TextLayer_expandTextDivs(expandDivs) {
  4850. if (!this._enhanceTextSelection || !this._renderingDone) {
  4851. return;
  4852. }
  4853. if (this._bounds !== null) {
  4854. expand(this);
  4855. this._bounds = null;
  4856. }
  4857. for (var i = 0, ii = this._textDivs.length; i < ii; i++) {
  4858. var div = this._textDivs[i];
  4859. var divProperties = this._textDivProperties.get(div);
  4860. if (divProperties.isWhitespace) {
  4861. continue;
  4862. }
  4863. if (expandDivs) {
  4864. var transform = '', padding = '';
  4865. if (divProperties.scale !== 1) {
  4866. transform = 'scaleX(' + divProperties.scale + ')';
  4867. }
  4868. if (divProperties.angle !== 0) {
  4869. transform = 'rotate(' + divProperties.angle + 'deg) ' + transform;
  4870. }
  4871. if (divProperties.paddingLeft !== 0) {
  4872. padding += ' padding-left: ' + divProperties.paddingLeft / divProperties.scale + 'px;';
  4873. transform += ' translateX(' + -divProperties.paddingLeft / divProperties.scale + 'px)';
  4874. }
  4875. if (divProperties.paddingTop !== 0) {
  4876. padding += ' padding-top: ' + divProperties.paddingTop + 'px;';
  4877. transform += ' translateY(' + -divProperties.paddingTop + 'px)';
  4878. }
  4879. if (divProperties.paddingRight !== 0) {
  4880. padding += ' padding-right: ' + divProperties.paddingRight / divProperties.scale + 'px;';
  4881. }
  4882. if (divProperties.paddingBottom !== 0) {
  4883. padding += ' padding-bottom: ' + divProperties.paddingBottom + 'px;';
  4884. }
  4885. if (padding !== '') {
  4886. div.setAttribute('style', divProperties.style + padding);
  4887. }
  4888. if (transform !== '') {
  4889. CustomStyle.setProp('transform', div, transform);
  4890. }
  4891. } else {
  4892. div.style.padding = 0;
  4893. CustomStyle.setProp('transform', div, divProperties.originalTransform || '');
  4894. }
  4895. }
  4896. }
  4897. };
  4898. function renderTextLayer(renderParameters) {
  4899. var task = new TextLayerRenderTask(renderParameters.textContent, renderParameters.container, renderParameters.viewport, renderParameters.textDivs, renderParameters.enhanceTextSelection);
  4900. task._render(renderParameters.timeout);
  4901. return task;
  4902. }
  4903. return renderTextLayer;
  4904. }();
  4905. exports.renderTextLayer = renderTextLayer;
  4906. }));
  4907. (function (root, factory) {
  4908. factory(root.pdfjsDisplayWebGL = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils);
  4909. }(this, function (exports, sharedUtil, displayDOMUtils) {
  4910. var shadow = sharedUtil.shadow;
  4911. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  4912. var WebGLUtils = function WebGLUtilsClosure() {
  4913. function loadShader(gl, code, shaderType) {
  4914. var shader = gl.createShader(shaderType);
  4915. gl.shaderSource(shader, code);
  4916. gl.compileShader(shader);
  4917. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  4918. if (!compiled) {
  4919. var errorMsg = gl.getShaderInfoLog(shader);
  4920. throw new Error('Error during shader compilation: ' + errorMsg);
  4921. }
  4922. return shader;
  4923. }
  4924. function createVertexShader(gl, code) {
  4925. return loadShader(gl, code, gl.VERTEX_SHADER);
  4926. }
  4927. function createFragmentShader(gl, code) {
  4928. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  4929. }
  4930. function createProgram(gl, shaders) {
  4931. var program = gl.createProgram();
  4932. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  4933. gl.attachShader(program, shaders[i]);
  4934. }
  4935. gl.linkProgram(program);
  4936. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  4937. if (!linked) {
  4938. var errorMsg = gl.getProgramInfoLog(program);
  4939. throw new Error('Error during program linking: ' + errorMsg);
  4940. }
  4941. return program;
  4942. }
  4943. function createTexture(gl, image, textureId) {
  4944. gl.activeTexture(textureId);
  4945. var texture = gl.createTexture();
  4946. gl.bindTexture(gl.TEXTURE_2D, texture);
  4947. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4948. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4949. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4950. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4951. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  4952. return texture;
  4953. }
  4954. var currentGL, currentCanvas;
  4955. function generateGL() {
  4956. if (currentGL) {
  4957. return;
  4958. }
  4959. currentCanvas = document.createElement('canvas');
  4960. currentGL = currentCanvas.getContext('webgl', { premultipliedalpha: false });
  4961. }
  4962. var smaskVertexShaderCode = '\
  4963. attribute vec2 a_position; \
  4964. attribute vec2 a_texCoord; \
  4965. \
  4966. uniform vec2 u_resolution; \
  4967. \
  4968. varying vec2 v_texCoord; \
  4969. \
  4970. void main() { \
  4971. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  4972. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  4973. \
  4974. v_texCoord = a_texCoord; \
  4975. } ';
  4976. var smaskFragmentShaderCode = '\
  4977. precision mediump float; \
  4978. \
  4979. uniform vec4 u_backdrop; \
  4980. uniform int u_subtype; \
  4981. uniform sampler2D u_image; \
  4982. uniform sampler2D u_mask; \
  4983. \
  4984. varying vec2 v_texCoord; \
  4985. \
  4986. void main() { \
  4987. vec4 imageColor = texture2D(u_image, v_texCoord); \
  4988. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  4989. if (u_backdrop.a > 0.0) { \
  4990. maskColor.rgb = maskColor.rgb * maskColor.a + \
  4991. u_backdrop.rgb * (1.0 - maskColor.a); \
  4992. } \
  4993. float lum; \
  4994. if (u_subtype == 0) { \
  4995. lum = maskColor.a; \
  4996. } else { \
  4997. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  4998. maskColor.b * 0.11; \
  4999. } \
  5000. imageColor.a *= lum; \
  5001. imageColor.rgb *= imageColor.a; \
  5002. gl_FragColor = imageColor; \
  5003. } ';
  5004. var smaskCache = null;
  5005. function initSmaskGL() {
  5006. var canvas, gl;
  5007. generateGL();
  5008. canvas = currentCanvas;
  5009. currentCanvas = null;
  5010. gl = currentGL;
  5011. currentGL = null;
  5012. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  5013. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  5014. var program = createProgram(gl, [
  5015. vertexShader,
  5016. fragmentShader
  5017. ]);
  5018. gl.useProgram(program);
  5019. var cache = {};
  5020. cache.gl = gl;
  5021. cache.canvas = canvas;
  5022. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5023. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5024. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  5025. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  5026. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  5027. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  5028. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  5029. var texCoordBuffer = gl.createBuffer();
  5030. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  5031. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5032. 0.0,
  5033. 0.0,
  5034. 1.0,
  5035. 0.0,
  5036. 0.0,
  5037. 1.0,
  5038. 0.0,
  5039. 1.0,
  5040. 1.0,
  5041. 0.0,
  5042. 1.0,
  5043. 1.0
  5044. ]), gl.STATIC_DRAW);
  5045. gl.enableVertexAttribArray(texCoordLocation);
  5046. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  5047. gl.uniform1i(texLayerLocation, 0);
  5048. gl.uniform1i(texMaskLocation, 1);
  5049. smaskCache = cache;
  5050. }
  5051. function composeSMask(layer, mask, properties) {
  5052. var width = layer.width, height = layer.height;
  5053. if (!smaskCache) {
  5054. initSmaskGL();
  5055. }
  5056. var cache = smaskCache, canvas = cache.canvas, gl = cache.gl;
  5057. canvas.width = width;
  5058. canvas.height = height;
  5059. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5060. gl.uniform2f(cache.resolutionLocation, width, height);
  5061. if (properties.backdrop) {
  5062. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0], properties.backdrop[1], properties.backdrop[2], 1);
  5063. } else {
  5064. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  5065. }
  5066. gl.uniform1i(cache.subtypeLocation, properties.subtype === 'Luminosity' ? 1 : 0);
  5067. var texture = createTexture(gl, layer, gl.TEXTURE0);
  5068. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  5069. var buffer = gl.createBuffer();
  5070. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  5071. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5072. 0,
  5073. 0,
  5074. width,
  5075. 0,
  5076. 0,
  5077. height,
  5078. 0,
  5079. height,
  5080. width,
  5081. 0,
  5082. width,
  5083. height
  5084. ]), gl.STATIC_DRAW);
  5085. gl.enableVertexAttribArray(cache.positionLocation);
  5086. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5087. gl.clearColor(0, 0, 0, 0);
  5088. gl.enable(gl.BLEND);
  5089. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  5090. gl.clear(gl.COLOR_BUFFER_BIT);
  5091. gl.drawArrays(gl.TRIANGLES, 0, 6);
  5092. gl.flush();
  5093. gl.deleteTexture(texture);
  5094. gl.deleteTexture(maskTexture);
  5095. gl.deleteBuffer(buffer);
  5096. return canvas;
  5097. }
  5098. var figuresVertexShaderCode = '\
  5099. attribute vec2 a_position; \
  5100. attribute vec3 a_color; \
  5101. \
  5102. uniform vec2 u_resolution; \
  5103. uniform vec2 u_scale; \
  5104. uniform vec2 u_offset; \
  5105. \
  5106. varying vec4 v_color; \
  5107. \
  5108. void main() { \
  5109. vec2 position = (a_position + u_offset) * u_scale; \
  5110. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  5111. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5112. \
  5113. v_color = vec4(a_color / 255.0, 1.0); \
  5114. } ';
  5115. var figuresFragmentShaderCode = '\
  5116. precision mediump float; \
  5117. \
  5118. varying vec4 v_color; \
  5119. \
  5120. void main() { \
  5121. gl_FragColor = v_color; \
  5122. } ';
  5123. var figuresCache = null;
  5124. function initFiguresGL() {
  5125. var canvas, gl;
  5126. generateGL();
  5127. canvas = currentCanvas;
  5128. currentCanvas = null;
  5129. gl = currentGL;
  5130. currentGL = null;
  5131. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  5132. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  5133. var program = createProgram(gl, [
  5134. vertexShader,
  5135. fragmentShader
  5136. ]);
  5137. gl.useProgram(program);
  5138. var cache = {};
  5139. cache.gl = gl;
  5140. cache.canvas = canvas;
  5141. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5142. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  5143. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  5144. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5145. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  5146. figuresCache = cache;
  5147. }
  5148. function drawFigures(width, height, backgroundColor, figures, context) {
  5149. if (!figuresCache) {
  5150. initFiguresGL();
  5151. }
  5152. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  5153. canvas.width = width;
  5154. canvas.height = height;
  5155. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5156. gl.uniform2f(cache.resolutionLocation, width, height);
  5157. var count = 0;
  5158. var i, ii, rows;
  5159. for (i = 0, ii = figures.length; i < ii; i++) {
  5160. switch (figures[i].type) {
  5161. case 'lattice':
  5162. rows = figures[i].coords.length / figures[i].verticesPerRow | 0;
  5163. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  5164. break;
  5165. case 'triangles':
  5166. count += figures[i].coords.length;
  5167. break;
  5168. }
  5169. }
  5170. var coords = new Float32Array(count * 2);
  5171. var colors = new Uint8Array(count * 3);
  5172. var coordsMap = context.coords, colorsMap = context.colors;
  5173. var pIndex = 0, cIndex = 0;
  5174. for (i = 0, ii = figures.length; i < ii; i++) {
  5175. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  5176. switch (figure.type) {
  5177. case 'lattice':
  5178. var cols = figure.verticesPerRow;
  5179. rows = ps.length / cols | 0;
  5180. for (var row = 1; row < rows; row++) {
  5181. var offset = row * cols + 1;
  5182. for (var col = 1; col < cols; col++, offset++) {
  5183. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  5184. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  5185. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  5186. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  5187. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  5188. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  5189. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  5190. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  5191. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  5192. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  5193. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  5194. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  5195. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  5196. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  5197. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  5198. coords[pIndex + 6] = coords[pIndex + 2];
  5199. coords[pIndex + 7] = coords[pIndex + 3];
  5200. coords[pIndex + 8] = coords[pIndex + 4];
  5201. coords[pIndex + 9] = coords[pIndex + 5];
  5202. coords[pIndex + 10] = coordsMap[ps[offset]];
  5203. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  5204. colors[cIndex + 9] = colors[cIndex + 3];
  5205. colors[cIndex + 10] = colors[cIndex + 4];
  5206. colors[cIndex + 11] = colors[cIndex + 5];
  5207. colors[cIndex + 12] = colors[cIndex + 6];
  5208. colors[cIndex + 13] = colors[cIndex + 7];
  5209. colors[cIndex + 14] = colors[cIndex + 8];
  5210. colors[cIndex + 15] = colorsMap[cs[offset]];
  5211. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  5212. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  5213. pIndex += 12;
  5214. cIndex += 18;
  5215. }
  5216. }
  5217. break;
  5218. case 'triangles':
  5219. for (var j = 0, jj = ps.length; j < jj; j++) {
  5220. coords[pIndex] = coordsMap[ps[j]];
  5221. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  5222. colors[cIndex] = colorsMap[cs[j]];
  5223. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  5224. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  5225. pIndex += 2;
  5226. cIndex += 3;
  5227. }
  5228. break;
  5229. }
  5230. }
  5231. if (backgroundColor) {
  5232. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255, backgroundColor[2] / 255, 1.0);
  5233. } else {
  5234. gl.clearColor(0, 0, 0, 0);
  5235. }
  5236. gl.clear(gl.COLOR_BUFFER_BIT);
  5237. var coordsBuffer = gl.createBuffer();
  5238. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  5239. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  5240. gl.enableVertexAttribArray(cache.positionLocation);
  5241. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5242. var colorsBuffer = gl.createBuffer();
  5243. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  5244. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  5245. gl.enableVertexAttribArray(cache.colorLocation);
  5246. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false, 0, 0);
  5247. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  5248. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  5249. gl.drawArrays(gl.TRIANGLES, 0, count);
  5250. gl.flush();
  5251. gl.deleteBuffer(coordsBuffer);
  5252. gl.deleteBuffer(colorsBuffer);
  5253. return canvas;
  5254. }
  5255. function cleanup() {
  5256. if (smaskCache && smaskCache.canvas) {
  5257. smaskCache.canvas.width = 0;
  5258. smaskCache.canvas.height = 0;
  5259. }
  5260. if (figuresCache && figuresCache.canvas) {
  5261. figuresCache.canvas.width = 0;
  5262. figuresCache.canvas.height = 0;
  5263. }
  5264. smaskCache = null;
  5265. figuresCache = null;
  5266. }
  5267. return {
  5268. get isEnabled() {
  5269. if (getDefaultSetting('disableWebGL')) {
  5270. return false;
  5271. }
  5272. var enabled = false;
  5273. try {
  5274. generateGL();
  5275. enabled = !!currentGL;
  5276. } catch (e) {
  5277. }
  5278. return shadow(this, 'isEnabled', enabled);
  5279. },
  5280. composeSMask: composeSMask,
  5281. drawFigures: drawFigures,
  5282. clear: cleanup
  5283. };
  5284. }();
  5285. exports.WebGLUtils = WebGLUtils;
  5286. }));
  5287. (function (root, factory) {
  5288. factory(root.pdfjsDisplayPatternHelper = {}, root.pdfjsSharedUtil, root.pdfjsDisplayWebGL);
  5289. }(this, function (exports, sharedUtil, displayWebGL) {
  5290. var Util = sharedUtil.Util;
  5291. var info = sharedUtil.info;
  5292. var isArray = sharedUtil.isArray;
  5293. var error = sharedUtil.error;
  5294. var WebGLUtils = displayWebGL.WebGLUtils;
  5295. var ShadingIRs = {};
  5296. ShadingIRs.RadialAxial = {
  5297. fromIR: function RadialAxial_fromIR(raw) {
  5298. var type = raw[1];
  5299. var colorStops = raw[2];
  5300. var p0 = raw[3];
  5301. var p1 = raw[4];
  5302. var r0 = raw[5];
  5303. var r1 = raw[6];
  5304. return {
  5305. type: 'Pattern',
  5306. getPattern: function RadialAxial_getPattern(ctx) {
  5307. var grad;
  5308. if (type === 'axial') {
  5309. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  5310. } else if (type === 'radial') {
  5311. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  5312. }
  5313. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  5314. var c = colorStops[i];
  5315. grad.addColorStop(c[0], c[1]);
  5316. }
  5317. return grad;
  5318. }
  5319. };
  5320. }
  5321. };
  5322. var createMeshCanvas = function createMeshCanvasClosure() {
  5323. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5324. var coords = context.coords, colors = context.colors;
  5325. var bytes = data.data, rowSize = data.width * 4;
  5326. var tmp;
  5327. if (coords[p1 + 1] > coords[p2 + 1]) {
  5328. tmp = p1;
  5329. p1 = p2;
  5330. p2 = tmp;
  5331. tmp = c1;
  5332. c1 = c2;
  5333. c2 = tmp;
  5334. }
  5335. if (coords[p2 + 1] > coords[p3 + 1]) {
  5336. tmp = p2;
  5337. p2 = p3;
  5338. p3 = tmp;
  5339. tmp = c2;
  5340. c2 = c3;
  5341. c3 = tmp;
  5342. }
  5343. if (coords[p1 + 1] > coords[p2 + 1]) {
  5344. tmp = p1;
  5345. p1 = p2;
  5346. p2 = tmp;
  5347. tmp = c1;
  5348. c1 = c2;
  5349. c2 = tmp;
  5350. }
  5351. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5352. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5353. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5354. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5355. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5356. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5357. if (y1 >= y3) {
  5358. return;
  5359. }
  5360. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  5361. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  5362. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  5363. var minY = Math.round(y1), maxY = Math.round(y3);
  5364. var xa, car, cag, cab;
  5365. var xb, cbr, cbg, cbb;
  5366. var k;
  5367. for (var y = minY; y <= maxY; y++) {
  5368. if (y < y2) {
  5369. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  5370. xa = x1 - (x1 - x2) * k;
  5371. car = c1r - (c1r - c2r) * k;
  5372. cag = c1g - (c1g - c2g) * k;
  5373. cab = c1b - (c1b - c2b) * k;
  5374. } else {
  5375. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  5376. xa = x2 - (x2 - x3) * k;
  5377. car = c2r - (c2r - c3r) * k;
  5378. cag = c2g - (c2g - c3g) * k;
  5379. cab = c2b - (c2b - c3b) * k;
  5380. }
  5381. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  5382. xb = x1 - (x1 - x3) * k;
  5383. cbr = c1r - (c1r - c3r) * k;
  5384. cbg = c1g - (c1g - c3g) * k;
  5385. cbb = c1b - (c1b - c3b) * k;
  5386. var x1_ = Math.round(Math.min(xa, xb));
  5387. var x2_ = Math.round(Math.max(xa, xb));
  5388. var j = rowSize * y + x1_ * 4;
  5389. for (var x = x1_; x <= x2_; x++) {
  5390. k = (xa - x) / (xa - xb);
  5391. k = k < 0 ? 0 : k > 1 ? 1 : k;
  5392. bytes[j++] = car - (car - cbr) * k | 0;
  5393. bytes[j++] = cag - (cag - cbg) * k | 0;
  5394. bytes[j++] = cab - (cab - cbb) * k | 0;
  5395. bytes[j++] = 255;
  5396. }
  5397. }
  5398. }
  5399. function drawFigure(data, figure, context) {
  5400. var ps = figure.coords;
  5401. var cs = figure.colors;
  5402. var i, ii;
  5403. switch (figure.type) {
  5404. case 'lattice':
  5405. var verticesPerRow = figure.verticesPerRow;
  5406. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  5407. var cols = verticesPerRow - 1;
  5408. for (i = 0; i < rows; i++) {
  5409. var q = i * verticesPerRow;
  5410. for (var j = 0; j < cols; j++, q++) {
  5411. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5412. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5413. }
  5414. }
  5415. break;
  5416. case 'triangles':
  5417. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5418. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  5419. }
  5420. break;
  5421. default:
  5422. error('illigal figure');
  5423. break;
  5424. }
  5425. }
  5426. function createMeshCanvas(bounds, combinesScale, coords, colors, figures, backgroundColor, cachedCanvases) {
  5427. var EXPECTED_SCALE = 1.1;
  5428. var MAX_PATTERN_SIZE = 3000;
  5429. var BORDER_SIZE = 2;
  5430. var offsetX = Math.floor(bounds[0]);
  5431. var offsetY = Math.floor(bounds[1]);
  5432. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  5433. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  5434. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5435. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5436. var scaleX = boundsWidth / width;
  5437. var scaleY = boundsHeight / height;
  5438. var context = {
  5439. coords: coords,
  5440. colors: colors,
  5441. offsetX: -offsetX,
  5442. offsetY: -offsetY,
  5443. scaleX: 1 / scaleX,
  5444. scaleY: 1 / scaleY
  5445. };
  5446. var paddedWidth = width + BORDER_SIZE * 2;
  5447. var paddedHeight = height + BORDER_SIZE * 2;
  5448. var canvas, tmpCanvas, i, ii;
  5449. if (WebGLUtils.isEnabled) {
  5450. canvas = WebGLUtils.drawFigures(width, height, backgroundColor, figures, context);
  5451. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight, false);
  5452. tmpCanvas.context.drawImage(canvas, BORDER_SIZE, BORDER_SIZE);
  5453. canvas = tmpCanvas.canvas;
  5454. } else {
  5455. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight, false);
  5456. var tmpCtx = tmpCanvas.context;
  5457. var data = tmpCtx.createImageData(width, height);
  5458. if (backgroundColor) {
  5459. var bytes = data.data;
  5460. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  5461. bytes[i] = backgroundColor[0];
  5462. bytes[i + 1] = backgroundColor[1];
  5463. bytes[i + 2] = backgroundColor[2];
  5464. bytes[i + 3] = 255;
  5465. }
  5466. }
  5467. for (i = 0; i < figures.length; i++) {
  5468. drawFigure(data, figures[i], context);
  5469. }
  5470. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  5471. canvas = tmpCanvas.canvas;
  5472. }
  5473. return {
  5474. canvas: canvas,
  5475. offsetX: offsetX - BORDER_SIZE * scaleX,
  5476. offsetY: offsetY - BORDER_SIZE * scaleY,
  5477. scaleX: scaleX,
  5478. scaleY: scaleY
  5479. };
  5480. }
  5481. return createMeshCanvas;
  5482. }();
  5483. ShadingIRs.Mesh = {
  5484. fromIR: function Mesh_fromIR(raw) {
  5485. var coords = raw[2];
  5486. var colors = raw[3];
  5487. var figures = raw[4];
  5488. var bounds = raw[5];
  5489. var matrix = raw[6];
  5490. var background = raw[8];
  5491. return {
  5492. type: 'Pattern',
  5493. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  5494. var scale;
  5495. if (shadingFill) {
  5496. scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  5497. } else {
  5498. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  5499. if (matrix) {
  5500. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  5501. scale = [
  5502. scale[0] * matrixScale[0],
  5503. scale[1] * matrixScale[1]
  5504. ];
  5505. }
  5506. }
  5507. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords, colors, figures, shadingFill ? null : background, owner.cachedCanvases);
  5508. if (!shadingFill) {
  5509. ctx.setTransform.apply(ctx, owner.baseTransform);
  5510. if (matrix) {
  5511. ctx.transform.apply(ctx, matrix);
  5512. }
  5513. }
  5514. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  5515. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  5516. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  5517. }
  5518. };
  5519. }
  5520. };
  5521. ShadingIRs.Dummy = {
  5522. fromIR: function Dummy_fromIR() {
  5523. return {
  5524. type: 'Pattern',
  5525. getPattern: function Dummy_fromIR_getPattern() {
  5526. return 'hotpink';
  5527. }
  5528. };
  5529. }
  5530. };
  5531. function getShadingPatternFromIR(raw) {
  5532. var shadingIR = ShadingIRs[raw[0]];
  5533. if (!shadingIR) {
  5534. error('Unknown IR type: ' + raw[0]);
  5535. }
  5536. return shadingIR.fromIR(raw);
  5537. }
  5538. var TilingPattern = function TilingPatternClosure() {
  5539. var PaintType = {
  5540. COLORED: 1,
  5541. UNCOLORED: 2
  5542. };
  5543. var MAX_PATTERN_SIZE = 3000;
  5544. function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  5545. this.operatorList = IR[2];
  5546. this.matrix = IR[3] || [
  5547. 1,
  5548. 0,
  5549. 0,
  5550. 1,
  5551. 0,
  5552. 0
  5553. ];
  5554. this.bbox = IR[4];
  5555. this.xstep = IR[5];
  5556. this.ystep = IR[6];
  5557. this.paintType = IR[7];
  5558. this.tilingType = IR[8];
  5559. this.color = color;
  5560. this.canvasGraphicsFactory = canvasGraphicsFactory;
  5561. this.baseTransform = baseTransform;
  5562. this.type = 'Pattern';
  5563. this.ctx = ctx;
  5564. }
  5565. TilingPattern.prototype = {
  5566. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  5567. var operatorList = this.operatorList;
  5568. var bbox = this.bbox;
  5569. var xstep = this.xstep;
  5570. var ystep = this.ystep;
  5571. var paintType = this.paintType;
  5572. var tilingType = this.tilingType;
  5573. var color = this.color;
  5574. var canvasGraphicsFactory = this.canvasGraphicsFactory;
  5575. info('TilingType: ' + tilingType);
  5576. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  5577. var topLeft = [
  5578. x0,
  5579. y0
  5580. ];
  5581. var botRight = [
  5582. x0 + xstep,
  5583. y0 + ystep
  5584. ];
  5585. var width = botRight[0] - topLeft[0];
  5586. var height = botRight[1] - topLeft[1];
  5587. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  5588. var curMatrixScale = Util.singularValueDecompose2dScale(this.baseTransform);
  5589. var combinedScale = [
  5590. matrixScale[0] * curMatrixScale[0],
  5591. matrixScale[1] * curMatrixScale[1]
  5592. ];
  5593. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])), MAX_PATTERN_SIZE);
  5594. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])), MAX_PATTERN_SIZE);
  5595. var tmpCanvas = owner.cachedCanvases.getCanvas('pattern', width, height, true);
  5596. var tmpCtx = tmpCanvas.context;
  5597. var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  5598. graphics.groupLevel = owner.groupLevel;
  5599. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  5600. this.setScale(width, height, xstep, ystep);
  5601. this.transformToScale(graphics);
  5602. var tmpTranslate = [
  5603. 1,
  5604. 0,
  5605. 0,
  5606. 1,
  5607. -topLeft[0],
  5608. -topLeft[1]
  5609. ];
  5610. graphics.transform.apply(graphics, tmpTranslate);
  5611. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  5612. graphics.executeOperatorList(operatorList);
  5613. return tmpCanvas.canvas;
  5614. },
  5615. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  5616. this.scale = [
  5617. width / xstep,
  5618. height / ystep
  5619. ];
  5620. },
  5621. transformToScale: function TilingPattern_transformToScale(graphics) {
  5622. var scale = this.scale;
  5623. var tmpScale = [
  5624. scale[0],
  5625. 0,
  5626. 0,
  5627. scale[1],
  5628. 0,
  5629. 0
  5630. ];
  5631. graphics.transform.apply(graphics, tmpScale);
  5632. },
  5633. scaleToContext: function TilingPattern_scaleToContext() {
  5634. var scale = this.scale;
  5635. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  5636. },
  5637. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  5638. if (bbox && isArray(bbox) && bbox.length === 4) {
  5639. var bboxWidth = x1 - x0;
  5640. var bboxHeight = y1 - y0;
  5641. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  5642. graphics.clip();
  5643. graphics.endPath();
  5644. }
  5645. },
  5646. setFillAndStrokeStyleToContext: function setFillAndStrokeStyleToContext(context, paintType, color) {
  5647. switch (paintType) {
  5648. case PaintType.COLORED:
  5649. var ctx = this.ctx;
  5650. context.fillStyle = ctx.fillStyle;
  5651. context.strokeStyle = ctx.strokeStyle;
  5652. break;
  5653. case PaintType.UNCOLORED:
  5654. var cssColor = Util.makeCssRgb(color[0], color[1], color[2]);
  5655. context.fillStyle = cssColor;
  5656. context.strokeStyle = cssColor;
  5657. break;
  5658. default:
  5659. error('Unsupported paint type: ' + paintType);
  5660. }
  5661. },
  5662. getPattern: function TilingPattern_getPattern(ctx, owner) {
  5663. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  5664. ctx = this.ctx;
  5665. ctx.setTransform.apply(ctx, this.baseTransform);
  5666. ctx.transform.apply(ctx, this.matrix);
  5667. this.scaleToContext();
  5668. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  5669. }
  5670. };
  5671. return TilingPattern;
  5672. }();
  5673. exports.getShadingPatternFromIR = getShadingPatternFromIR;
  5674. exports.TilingPattern = TilingPattern;
  5675. }));
  5676. (function (root, factory) {
  5677. factory(root.pdfjsDisplayCanvas = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils, root.pdfjsDisplayPatternHelper, root.pdfjsDisplayWebGL);
  5678. }(this, function (exports, sharedUtil, displayDOMUtils, displayPatternHelper, displayWebGL) {
  5679. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  5680. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  5681. var ImageKind = sharedUtil.ImageKind;
  5682. var OPS = sharedUtil.OPS;
  5683. var TextRenderingMode = sharedUtil.TextRenderingMode;
  5684. var Uint32ArrayView = sharedUtil.Uint32ArrayView;
  5685. var Util = sharedUtil.Util;
  5686. var assert = sharedUtil.assert;
  5687. var info = sharedUtil.info;
  5688. var isNum = sharedUtil.isNum;
  5689. var isArray = sharedUtil.isArray;
  5690. var isLittleEndian = sharedUtil.isLittleEndian;
  5691. var error = sharedUtil.error;
  5692. var shadow = sharedUtil.shadow;
  5693. var warn = sharedUtil.warn;
  5694. var TilingPattern = displayPatternHelper.TilingPattern;
  5695. var getShadingPatternFromIR = displayPatternHelper.getShadingPatternFromIR;
  5696. var WebGLUtils = displayWebGL.WebGLUtils;
  5697. var hasCanvasTypedArrays = displayDOMUtils.hasCanvasTypedArrays;
  5698. var MIN_FONT_SIZE = 16;
  5699. var MAX_FONT_SIZE = 100;
  5700. var MAX_GROUP_SIZE = 4096;
  5701. var MIN_WIDTH_FACTOR = 0.65;
  5702. var COMPILE_TYPE3_GLYPHS = true;
  5703. var MAX_SIZE_TO_COMPILE = 1000;
  5704. var FULL_CHUNK_HEIGHT = 16;
  5705. var HasCanvasTypedArraysCached = {
  5706. get value() {
  5707. return shadow(HasCanvasTypedArraysCached, 'value', hasCanvasTypedArrays());
  5708. }
  5709. };
  5710. var IsLittleEndianCached = {
  5711. get value() {
  5712. return shadow(IsLittleEndianCached, 'value', isLittleEndian());
  5713. }
  5714. };
  5715. function createScratchCanvas(width, height) {
  5716. var canvas = document.createElement('canvas');
  5717. canvas.width = width;
  5718. canvas.height = height;
  5719. return canvas;
  5720. }
  5721. function addContextCurrentTransform(ctx) {
  5722. if (!ctx.mozCurrentTransform) {
  5723. ctx._originalSave = ctx.save;
  5724. ctx._originalRestore = ctx.restore;
  5725. ctx._originalRotate = ctx.rotate;
  5726. ctx._originalScale = ctx.scale;
  5727. ctx._originalTranslate = ctx.translate;
  5728. ctx._originalTransform = ctx.transform;
  5729. ctx._originalSetTransform = ctx.setTransform;
  5730. ctx._transformMatrix = ctx._transformMatrix || [
  5731. 1,
  5732. 0,
  5733. 0,
  5734. 1,
  5735. 0,
  5736. 0
  5737. ];
  5738. ctx._transformStack = [];
  5739. Object.defineProperty(ctx, 'mozCurrentTransform', {
  5740. get: function getCurrentTransform() {
  5741. return this._transformMatrix;
  5742. }
  5743. });
  5744. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  5745. get: function getCurrentTransformInverse() {
  5746. var m = this._transformMatrix;
  5747. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  5748. var ad_bc = a * d - b * c;
  5749. var bc_ad = b * c - a * d;
  5750. return [
  5751. d / ad_bc,
  5752. b / bc_ad,
  5753. c / bc_ad,
  5754. a / ad_bc,
  5755. (d * e - c * f) / bc_ad,
  5756. (b * e - a * f) / ad_bc
  5757. ];
  5758. }
  5759. });
  5760. ctx.save = function ctxSave() {
  5761. var old = this._transformMatrix;
  5762. this._transformStack.push(old);
  5763. this._transformMatrix = old.slice(0, 6);
  5764. this._originalSave();
  5765. };
  5766. ctx.restore = function ctxRestore() {
  5767. var prev = this._transformStack.pop();
  5768. if (prev) {
  5769. this._transformMatrix = prev;
  5770. this._originalRestore();
  5771. }
  5772. };
  5773. ctx.translate = function ctxTranslate(x, y) {
  5774. var m = this._transformMatrix;
  5775. m[4] = m[0] * x + m[2] * y + m[4];
  5776. m[5] = m[1] * x + m[3] * y + m[5];
  5777. this._originalTranslate(x, y);
  5778. };
  5779. ctx.scale = function ctxScale(x, y) {
  5780. var m = this._transformMatrix;
  5781. m[0] = m[0] * x;
  5782. m[1] = m[1] * x;
  5783. m[2] = m[2] * y;
  5784. m[3] = m[3] * y;
  5785. this._originalScale(x, y);
  5786. };
  5787. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  5788. var m = this._transformMatrix;
  5789. this._transformMatrix = [
  5790. m[0] * a + m[2] * b,
  5791. m[1] * a + m[3] * b,
  5792. m[0] * c + m[2] * d,
  5793. m[1] * c + m[3] * d,
  5794. m[0] * e + m[2] * f + m[4],
  5795. m[1] * e + m[3] * f + m[5]
  5796. ];
  5797. ctx._originalTransform(a, b, c, d, e, f);
  5798. };
  5799. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  5800. this._transformMatrix = [
  5801. a,
  5802. b,
  5803. c,
  5804. d,
  5805. e,
  5806. f
  5807. ];
  5808. ctx._originalSetTransform(a, b, c, d, e, f);
  5809. };
  5810. ctx.rotate = function ctxRotate(angle) {
  5811. var cosValue = Math.cos(angle);
  5812. var sinValue = Math.sin(angle);
  5813. var m = this._transformMatrix;
  5814. this._transformMatrix = [
  5815. m[0] * cosValue + m[2] * sinValue,
  5816. m[1] * cosValue + m[3] * sinValue,
  5817. m[0] * -sinValue + m[2] * cosValue,
  5818. m[1] * -sinValue + m[3] * cosValue,
  5819. m[4],
  5820. m[5]
  5821. ];
  5822. this._originalRotate(angle);
  5823. };
  5824. }
  5825. }
  5826. var CachedCanvases = function CachedCanvasesClosure() {
  5827. function CachedCanvases() {
  5828. this.cache = Object.create(null);
  5829. }
  5830. CachedCanvases.prototype = {
  5831. getCanvas: function CachedCanvases_getCanvas(id, width, height, trackTransform) {
  5832. var canvasEntry;
  5833. if (this.cache[id] !== undefined) {
  5834. canvasEntry = this.cache[id];
  5835. canvasEntry.canvas.width = width;
  5836. canvasEntry.canvas.height = height;
  5837. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  5838. } else {
  5839. var canvas = createScratchCanvas(width, height);
  5840. var ctx = canvas.getContext('2d');
  5841. if (trackTransform) {
  5842. addContextCurrentTransform(ctx);
  5843. }
  5844. this.cache[id] = canvasEntry = {
  5845. canvas: canvas,
  5846. context: ctx
  5847. };
  5848. }
  5849. return canvasEntry;
  5850. },
  5851. clear: function () {
  5852. for (var id in this.cache) {
  5853. var canvasEntry = this.cache[id];
  5854. canvasEntry.canvas.width = 0;
  5855. canvasEntry.canvas.height = 0;
  5856. delete this.cache[id];
  5857. }
  5858. }
  5859. };
  5860. return CachedCanvases;
  5861. }();
  5862. function compileType3Glyph(imgData) {
  5863. var POINT_TO_PROCESS_LIMIT = 1000;
  5864. var width = imgData.width, height = imgData.height;
  5865. var i, j, j0, width1 = width + 1;
  5866. var points = new Uint8Array(width1 * (height + 1));
  5867. var POINT_TYPES = new Uint8Array([
  5868. 0,
  5869. 2,
  5870. 4,
  5871. 0,
  5872. 1,
  5873. 0,
  5874. 5,
  5875. 4,
  5876. 8,
  5877. 10,
  5878. 0,
  5879. 8,
  5880. 0,
  5881. 2,
  5882. 1,
  5883. 0
  5884. ]);
  5885. var lineSize = width + 7 & ~7, data0 = imgData.data;
  5886. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  5887. for (i = 0, ii = data0.length; i < ii; i++) {
  5888. var mask = 128, elem = data0[i];
  5889. while (mask > 0) {
  5890. data[pos++] = elem & mask ? 0 : 255;
  5891. mask >>= 1;
  5892. }
  5893. }
  5894. var count = 0;
  5895. pos = 0;
  5896. if (data[pos] !== 0) {
  5897. points[0] = 1;
  5898. ++count;
  5899. }
  5900. for (j = 1; j < width; j++) {
  5901. if (data[pos] !== data[pos + 1]) {
  5902. points[j] = data[pos] ? 2 : 1;
  5903. ++count;
  5904. }
  5905. pos++;
  5906. }
  5907. if (data[pos] !== 0) {
  5908. points[j] = 2;
  5909. ++count;
  5910. }
  5911. for (i = 1; i < height; i++) {
  5912. pos = i * lineSize;
  5913. j0 = i * width1;
  5914. if (data[pos - lineSize] !== data[pos]) {
  5915. points[j0] = data[pos] ? 1 : 8;
  5916. ++count;
  5917. }
  5918. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  5919. for (j = 1; j < width; j++) {
  5920. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
  5921. if (POINT_TYPES[sum]) {
  5922. points[j0 + j] = POINT_TYPES[sum];
  5923. ++count;
  5924. }
  5925. pos++;
  5926. }
  5927. if (data[pos - lineSize] !== data[pos]) {
  5928. points[j0 + j] = data[pos] ? 2 : 4;
  5929. ++count;
  5930. }
  5931. if (count > POINT_TO_PROCESS_LIMIT) {
  5932. return null;
  5933. }
  5934. }
  5935. pos = lineSize * (height - 1);
  5936. j0 = i * width1;
  5937. if (data[pos] !== 0) {
  5938. points[j0] = 8;
  5939. ++count;
  5940. }
  5941. for (j = 1; j < width; j++) {
  5942. if (data[pos] !== data[pos + 1]) {
  5943. points[j0 + j] = data[pos] ? 4 : 8;
  5944. ++count;
  5945. }
  5946. pos++;
  5947. }
  5948. if (data[pos] !== 0) {
  5949. points[j0 + j] = 4;
  5950. ++count;
  5951. }
  5952. if (count > POINT_TO_PROCESS_LIMIT) {
  5953. return null;
  5954. }
  5955. var steps = new Int32Array([
  5956. 0,
  5957. width1,
  5958. -1,
  5959. 0,
  5960. -width1,
  5961. 0,
  5962. 0,
  5963. 0,
  5964. 1
  5965. ]);
  5966. var outlines = [];
  5967. for (i = 0; count && i <= height; i++) {
  5968. var p = i * width1;
  5969. var end = p + width;
  5970. while (p < end && !points[p]) {
  5971. p++;
  5972. }
  5973. if (p === end) {
  5974. continue;
  5975. }
  5976. var coords = [
  5977. p % width1,
  5978. i
  5979. ];
  5980. var type = points[p], p0 = p, pp;
  5981. do {
  5982. var step = steps[type];
  5983. do {
  5984. p += step;
  5985. } while (!points[p]);
  5986. pp = points[p];
  5987. if (pp !== 5 && pp !== 10) {
  5988. type = pp;
  5989. points[p] = 0;
  5990. } else {
  5991. type = pp & 0x33 * type >> 4;
  5992. points[p] &= type >> 2 | type << 2;
  5993. }
  5994. coords.push(p % width1);
  5995. coords.push(p / width1 | 0);
  5996. --count;
  5997. } while (p0 !== p);
  5998. outlines.push(coords);
  5999. --i;
  6000. }
  6001. var drawOutline = function (c) {
  6002. c.save();
  6003. c.scale(1 / width, -1 / height);
  6004. c.translate(0, -height);
  6005. c.beginPath();
  6006. for (var i = 0, ii = outlines.length; i < ii; i++) {
  6007. var o = outlines[i];
  6008. c.moveTo(o[0], o[1]);
  6009. for (var j = 2, jj = o.length; j < jj; j += 2) {
  6010. c.lineTo(o[j], o[j + 1]);
  6011. }
  6012. }
  6013. c.fill();
  6014. c.beginPath();
  6015. c.restore();
  6016. };
  6017. return drawOutline;
  6018. }
  6019. var CanvasExtraState = function CanvasExtraStateClosure() {
  6020. function CanvasExtraState(old) {
  6021. this.alphaIsShape = false;
  6022. this.fontSize = 0;
  6023. this.fontSizeScale = 1;
  6024. this.textMatrix = IDENTITY_MATRIX;
  6025. this.textMatrixScale = 1;
  6026. this.fontMatrix = FONT_IDENTITY_MATRIX;
  6027. this.leading = 0;
  6028. this.x = 0;
  6029. this.y = 0;
  6030. this.lineX = 0;
  6031. this.lineY = 0;
  6032. this.charSpacing = 0;
  6033. this.wordSpacing = 0;
  6034. this.textHScale = 1;
  6035. this.textRenderingMode = TextRenderingMode.FILL;
  6036. this.textRise = 0;
  6037. this.fillColor = '#000000';
  6038. this.strokeColor = '#000000';
  6039. this.patternFill = false;
  6040. this.fillAlpha = 1;
  6041. this.strokeAlpha = 1;
  6042. this.lineWidth = 1;
  6043. this.activeSMask = null;
  6044. this.resumeSMaskCtx = null;
  6045. this.old = old;
  6046. }
  6047. CanvasExtraState.prototype = {
  6048. clone: function CanvasExtraState_clone() {
  6049. return Object.create(this);
  6050. },
  6051. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  6052. this.x = x;
  6053. this.y = y;
  6054. }
  6055. };
  6056. return CanvasExtraState;
  6057. }();
  6058. var CanvasGraphics = function CanvasGraphicsClosure() {
  6059. var EXECUTION_TIME = 15;
  6060. var EXECUTION_STEPS = 10;
  6061. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  6062. this.ctx = canvasCtx;
  6063. this.current = new CanvasExtraState();
  6064. this.stateStack = [];
  6065. this.pendingClip = null;
  6066. this.pendingEOFill = false;
  6067. this.res = null;
  6068. this.xobjs = null;
  6069. this.commonObjs = commonObjs;
  6070. this.objs = objs;
  6071. this.imageLayer = imageLayer;
  6072. this.groupStack = [];
  6073. this.processingType3 = null;
  6074. this.baseTransform = null;
  6075. this.baseTransformStack = [];
  6076. this.groupLevel = 0;
  6077. this.smaskStack = [];
  6078. this.smaskCounter = 0;
  6079. this.tempSMask = null;
  6080. this.cachedCanvases = new CachedCanvases();
  6081. if (canvasCtx) {
  6082. addContextCurrentTransform(canvasCtx);
  6083. }
  6084. this.cachedGetSinglePixelWidth = null;
  6085. }
  6086. function putBinaryImageData(ctx, imgData) {
  6087. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  6088. ctx.putImageData(imgData, 0, 0);
  6089. return;
  6090. }
  6091. var height = imgData.height, width = imgData.width;
  6092. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6093. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6094. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6095. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6096. var srcPos = 0, destPos;
  6097. var src = imgData.data;
  6098. var dest = chunkImgData.data;
  6099. var i, j, thisChunkHeight, elemsInThisChunk;
  6100. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  6101. var srcLength = src.byteLength;
  6102. var dest32 = HasCanvasTypedArraysCached.value ? new Uint32Array(dest.buffer) : new Uint32ArrayView(dest);
  6103. var dest32DataLength = dest32.length;
  6104. var fullSrcDiff = width + 7 >> 3;
  6105. var white = 0xFFFFFFFF;
  6106. var black = IsLittleEndianCached.value || !HasCanvasTypedArraysCached.value ? 0xFF000000 : 0x000000FF;
  6107. for (i = 0; i < totalChunks; i++) {
  6108. thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6109. destPos = 0;
  6110. for (j = 0; j < thisChunkHeight; j++) {
  6111. var srcDiff = srcLength - srcPos;
  6112. var k = 0;
  6113. var kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
  6114. var kEndUnrolled = kEnd & ~7;
  6115. var mask = 0;
  6116. var srcByte = 0;
  6117. for (; k < kEndUnrolled; k += 8) {
  6118. srcByte = src[srcPos++];
  6119. dest32[destPos++] = srcByte & 128 ? white : black;
  6120. dest32[destPos++] = srcByte & 64 ? white : black;
  6121. dest32[destPos++] = srcByte & 32 ? white : black;
  6122. dest32[destPos++] = srcByte & 16 ? white : black;
  6123. dest32[destPos++] = srcByte & 8 ? white : black;
  6124. dest32[destPos++] = srcByte & 4 ? white : black;
  6125. dest32[destPos++] = srcByte & 2 ? white : black;
  6126. dest32[destPos++] = srcByte & 1 ? white : black;
  6127. }
  6128. for (; k < kEnd; k++) {
  6129. if (mask === 0) {
  6130. srcByte = src[srcPos++];
  6131. mask = 128;
  6132. }
  6133. dest32[destPos++] = srcByte & mask ? white : black;
  6134. mask >>= 1;
  6135. }
  6136. }
  6137. while (destPos < dest32DataLength) {
  6138. dest32[destPos++] = 0;
  6139. }
  6140. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6141. }
  6142. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  6143. j = 0;
  6144. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  6145. for (i = 0; i < fullChunks; i++) {
  6146. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6147. srcPos += elemsInThisChunk;
  6148. ctx.putImageData(chunkImgData, 0, j);
  6149. j += FULL_CHUNK_HEIGHT;
  6150. }
  6151. if (i < totalChunks) {
  6152. elemsInThisChunk = width * partialChunkHeight * 4;
  6153. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6154. ctx.putImageData(chunkImgData, 0, j);
  6155. }
  6156. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  6157. thisChunkHeight = FULL_CHUNK_HEIGHT;
  6158. elemsInThisChunk = width * thisChunkHeight;
  6159. for (i = 0; i < totalChunks; i++) {
  6160. if (i >= fullChunks) {
  6161. thisChunkHeight = partialChunkHeight;
  6162. elemsInThisChunk = width * thisChunkHeight;
  6163. }
  6164. destPos = 0;
  6165. for (j = elemsInThisChunk; j--;) {
  6166. dest[destPos++] = src[srcPos++];
  6167. dest[destPos++] = src[srcPos++];
  6168. dest[destPos++] = src[srcPos++];
  6169. dest[destPos++] = 255;
  6170. }
  6171. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6172. }
  6173. } else {
  6174. error('bad image kind: ' + imgData.kind);
  6175. }
  6176. }
  6177. function putBinaryImageMask(ctx, imgData) {
  6178. var height = imgData.height, width = imgData.width;
  6179. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6180. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6181. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6182. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6183. var srcPos = 0;
  6184. var src = imgData.data;
  6185. var dest = chunkImgData.data;
  6186. for (var i = 0; i < totalChunks; i++) {
  6187. var thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6188. var destPos = 3;
  6189. for (var j = 0; j < thisChunkHeight; j++) {
  6190. var mask = 0;
  6191. for (var k = 0; k < width; k++) {
  6192. if (!mask) {
  6193. var elem = src[srcPos++];
  6194. mask = 128;
  6195. }
  6196. dest[destPos] = elem & mask ? 0 : 255;
  6197. destPos += 4;
  6198. mask >>= 1;
  6199. }
  6200. }
  6201. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6202. }
  6203. }
  6204. function copyCtxState(sourceCtx, destCtx) {
  6205. var properties = [
  6206. 'strokeStyle',
  6207. 'fillStyle',
  6208. 'fillRule',
  6209. 'globalAlpha',
  6210. 'lineWidth',
  6211. 'lineCap',
  6212. 'lineJoin',
  6213. 'miterLimit',
  6214. 'globalCompositeOperation',
  6215. 'font'
  6216. ];
  6217. for (var i = 0, ii = properties.length; i < ii; i++) {
  6218. var property = properties[i];
  6219. if (sourceCtx[property] !== undefined) {
  6220. destCtx[property] = sourceCtx[property];
  6221. }
  6222. }
  6223. if (sourceCtx.setLineDash !== undefined) {
  6224. destCtx.setLineDash(sourceCtx.getLineDash());
  6225. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  6226. }
  6227. }
  6228. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  6229. var length = bytes.length;
  6230. for (var i = 3; i < length; i += 4) {
  6231. var alpha = bytes[i];
  6232. if (alpha === 0) {
  6233. bytes[i - 3] = r0;
  6234. bytes[i - 2] = g0;
  6235. bytes[i - 1] = b0;
  6236. } else if (alpha < 255) {
  6237. var alpha_ = 255 - alpha;
  6238. bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
  6239. bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
  6240. bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
  6241. }
  6242. }
  6243. }
  6244. function composeSMaskAlpha(maskData, layerData, transferMap) {
  6245. var length = maskData.length;
  6246. var scale = 1 / 255;
  6247. for (var i = 3; i < length; i += 4) {
  6248. var alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  6249. layerData[i] = layerData[i] * alpha * scale | 0;
  6250. }
  6251. }
  6252. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  6253. var length = maskData.length;
  6254. for (var i = 3; i < length; i += 4) {
  6255. var y = maskData[i - 3] * 77 + maskData[i - 2] * 152 + maskData[i - 1] * 28;
  6256. layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
  6257. }
  6258. }
  6259. function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap) {
  6260. var hasBackdrop = !!backdrop;
  6261. var r0 = hasBackdrop ? backdrop[0] : 0;
  6262. var g0 = hasBackdrop ? backdrop[1] : 0;
  6263. var b0 = hasBackdrop ? backdrop[2] : 0;
  6264. var composeFn;
  6265. if (subtype === 'Luminosity') {
  6266. composeFn = composeSMaskLuminosity;
  6267. } else {
  6268. composeFn = composeSMaskAlpha;
  6269. }
  6270. var PIXELS_TO_PROCESS = 1048576;
  6271. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  6272. for (var row = 0; row < height; row += chunkSize) {
  6273. var chunkHeight = Math.min(chunkSize, height - row);
  6274. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  6275. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  6276. if (hasBackdrop) {
  6277. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  6278. }
  6279. composeFn(maskData.data, layerData.data, transferMap);
  6280. maskCtx.putImageData(layerData, 0, row);
  6281. }
  6282. }
  6283. function composeSMask(ctx, smask, layerCtx) {
  6284. var mask = smask.canvas;
  6285. var maskCtx = smask.context;
  6286. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY);
  6287. var backdrop = smask.backdrop || null;
  6288. if (!smask.transferMap && WebGLUtils.isEnabled) {
  6289. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask, {
  6290. subtype: smask.subtype,
  6291. backdrop: backdrop
  6292. });
  6293. ctx.setTransform(1, 0, 0, 1, 0, 0);
  6294. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  6295. return;
  6296. }
  6297. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, backdrop, smask.transferMap);
  6298. ctx.drawImage(mask, 0, 0);
  6299. }
  6300. var LINE_CAP_STYLES = [
  6301. 'butt',
  6302. 'round',
  6303. 'square'
  6304. ];
  6305. var LINE_JOIN_STYLES = [
  6306. 'miter',
  6307. 'round',
  6308. 'bevel'
  6309. ];
  6310. var NORMAL_CLIP = {};
  6311. var EO_CLIP = {};
  6312. CanvasGraphics.prototype = {
  6313. beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport, transparency) {
  6314. var width = this.ctx.canvas.width;
  6315. var height = this.ctx.canvas.height;
  6316. this.ctx.save();
  6317. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  6318. this.ctx.fillRect(0, 0, width, height);
  6319. this.ctx.restore();
  6320. if (transparency) {
  6321. var transparentCanvas = this.cachedCanvases.getCanvas('transparent', width, height, true);
  6322. this.compositeCtx = this.ctx;
  6323. this.transparentCanvas = transparentCanvas.canvas;
  6324. this.ctx = transparentCanvas.context;
  6325. this.ctx.save();
  6326. this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform);
  6327. }
  6328. this.ctx.save();
  6329. if (transform) {
  6330. this.ctx.transform.apply(this.ctx, transform);
  6331. }
  6332. this.ctx.transform.apply(this.ctx, viewport.transform);
  6333. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  6334. if (this.imageLayer) {
  6335. this.imageLayer.beginLayout();
  6336. }
  6337. },
  6338. executeOperatorList: function CanvasGraphics_executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  6339. var argsArray = operatorList.argsArray;
  6340. var fnArray = operatorList.fnArray;
  6341. var i = executionStartIdx || 0;
  6342. var argsArrayLen = argsArray.length;
  6343. if (argsArrayLen === i) {
  6344. return i;
  6345. }
  6346. var chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === 'function';
  6347. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  6348. var steps = 0;
  6349. var commonObjs = this.commonObjs;
  6350. var objs = this.objs;
  6351. var fnId;
  6352. while (true) {
  6353. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  6354. stepper.breakIt(i, continueCallback);
  6355. return i;
  6356. }
  6357. fnId = fnArray[i];
  6358. if (fnId !== OPS.dependency) {
  6359. this[fnId].apply(this, argsArray[i]);
  6360. } else {
  6361. var deps = argsArray[i];
  6362. for (var n = 0, nn = deps.length; n < nn; n++) {
  6363. var depObjId = deps[n];
  6364. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  6365. var objsPool = common ? commonObjs : objs;
  6366. if (!objsPool.isResolved(depObjId)) {
  6367. objsPool.get(depObjId, continueCallback);
  6368. return i;
  6369. }
  6370. }
  6371. }
  6372. i++;
  6373. if (i === argsArrayLen) {
  6374. return i;
  6375. }
  6376. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  6377. if (Date.now() > endTime) {
  6378. continueCallback();
  6379. return i;
  6380. }
  6381. steps = 0;
  6382. }
  6383. }
  6384. },
  6385. endDrawing: function CanvasGraphics_endDrawing() {
  6386. if (this.current.activeSMask !== null) {
  6387. this.endSMaskGroup();
  6388. }
  6389. this.ctx.restore();
  6390. if (this.transparentCanvas) {
  6391. this.ctx = this.compositeCtx;
  6392. this.ctx.save();
  6393. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  6394. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  6395. this.ctx.restore();
  6396. this.transparentCanvas = null;
  6397. }
  6398. this.cachedCanvases.clear();
  6399. WebGLUtils.clear();
  6400. if (this.imageLayer) {
  6401. this.imageLayer.endLayout();
  6402. }
  6403. },
  6404. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  6405. this.current.lineWidth = width;
  6406. this.ctx.lineWidth = width;
  6407. },
  6408. setLineCap: function CanvasGraphics_setLineCap(style) {
  6409. this.ctx.lineCap = LINE_CAP_STYLES[style];
  6410. },
  6411. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  6412. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  6413. },
  6414. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  6415. this.ctx.miterLimit = limit;
  6416. },
  6417. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  6418. var ctx = this.ctx;
  6419. if (ctx.setLineDash !== undefined) {
  6420. ctx.setLineDash(dashArray);
  6421. ctx.lineDashOffset = dashPhase;
  6422. }
  6423. },
  6424. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  6425. },
  6426. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  6427. },
  6428. setGState: function CanvasGraphics_setGState(states) {
  6429. for (var i = 0, ii = states.length; i < ii; i++) {
  6430. var state = states[i];
  6431. var key = state[0];
  6432. var value = state[1];
  6433. switch (key) {
  6434. case 'LW':
  6435. this.setLineWidth(value);
  6436. break;
  6437. case 'LC':
  6438. this.setLineCap(value);
  6439. break;
  6440. case 'LJ':
  6441. this.setLineJoin(value);
  6442. break;
  6443. case 'ML':
  6444. this.setMiterLimit(value);
  6445. break;
  6446. case 'D':
  6447. this.setDash(value[0], value[1]);
  6448. break;
  6449. case 'RI':
  6450. this.setRenderingIntent(value);
  6451. break;
  6452. case 'FL':
  6453. this.setFlatness(value);
  6454. break;
  6455. case 'Font':
  6456. this.setFont(value[0], value[1]);
  6457. break;
  6458. case 'CA':
  6459. this.current.strokeAlpha = state[1];
  6460. break;
  6461. case 'ca':
  6462. this.current.fillAlpha = state[1];
  6463. this.ctx.globalAlpha = state[1];
  6464. break;
  6465. case 'BM':
  6466. if (value && value.name && value.name !== 'Normal') {
  6467. var mode = value.name.replace(/([A-Z])/g, function (c) {
  6468. return '-' + c.toLowerCase();
  6469. }).substring(1);
  6470. this.ctx.globalCompositeOperation = mode;
  6471. if (this.ctx.globalCompositeOperation !== mode) {
  6472. warn('globalCompositeOperation "' + mode + '" is not supported');
  6473. }
  6474. } else {
  6475. this.ctx.globalCompositeOperation = 'source-over';
  6476. }
  6477. break;
  6478. case 'SMask':
  6479. if (this.current.activeSMask) {
  6480. if (this.stateStack.length > 0 && this.stateStack[this.stateStack.length - 1].activeSMask === this.current.activeSMask) {
  6481. this.suspendSMaskGroup();
  6482. } else {
  6483. this.endSMaskGroup();
  6484. }
  6485. }
  6486. this.current.activeSMask = value ? this.tempSMask : null;
  6487. if (this.current.activeSMask) {
  6488. this.beginSMaskGroup();
  6489. }
  6490. this.tempSMask = null;
  6491. break;
  6492. }
  6493. }
  6494. },
  6495. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  6496. var activeSMask = this.current.activeSMask;
  6497. var drawnWidth = activeSMask.canvas.width;
  6498. var drawnHeight = activeSMask.canvas.height;
  6499. var cacheId = 'smaskGroupAt' + this.groupLevel;
  6500. var scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  6501. var currentCtx = this.ctx;
  6502. var currentTransform = currentCtx.mozCurrentTransform;
  6503. this.ctx.save();
  6504. var groupCtx = scratchCanvas.context;
  6505. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  6506. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  6507. groupCtx.transform.apply(groupCtx, currentTransform);
  6508. activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse;
  6509. copyCtxState(currentCtx, groupCtx);
  6510. this.ctx = groupCtx;
  6511. this.setGState([
  6512. [
  6513. 'BM',
  6514. 'Normal'
  6515. ],
  6516. [
  6517. 'ca',
  6518. 1
  6519. ],
  6520. [
  6521. 'CA',
  6522. 1
  6523. ]
  6524. ]);
  6525. this.groupStack.push(currentCtx);
  6526. this.groupLevel++;
  6527. },
  6528. suspendSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  6529. var groupCtx = this.ctx;
  6530. this.groupLevel--;
  6531. this.ctx = this.groupStack.pop();
  6532. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  6533. this.ctx.restore();
  6534. this.ctx.save();
  6535. copyCtxState(groupCtx, this.ctx);
  6536. this.current.resumeSMaskCtx = groupCtx;
  6537. var deltaTransform = Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
  6538. this.ctx.transform.apply(this.ctx, deltaTransform);
  6539. groupCtx.save();
  6540. groupCtx.setTransform(1, 0, 0, 1, 0, 0);
  6541. groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height);
  6542. groupCtx.restore();
  6543. },
  6544. resumeSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  6545. var groupCtx = this.current.resumeSMaskCtx;
  6546. var currentCtx = this.ctx;
  6547. this.ctx = groupCtx;
  6548. this.groupStack.push(currentCtx);
  6549. this.groupLevel++;
  6550. },
  6551. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  6552. var groupCtx = this.ctx;
  6553. this.groupLevel--;
  6554. this.ctx = this.groupStack.pop();
  6555. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  6556. this.ctx.restore();
  6557. copyCtxState(groupCtx, this.ctx);
  6558. var deltaTransform = Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
  6559. this.ctx.transform.apply(this.ctx, deltaTransform);
  6560. },
  6561. save: function CanvasGraphics_save() {
  6562. this.ctx.save();
  6563. var old = this.current;
  6564. this.stateStack.push(old);
  6565. this.current = old.clone();
  6566. this.current.resumeSMaskCtx = null;
  6567. },
  6568. restore: function CanvasGraphics_restore() {
  6569. if (this.current.resumeSMaskCtx) {
  6570. this.resumeSMaskGroup();
  6571. }
  6572. if (this.current.activeSMask !== null && (this.stateStack.length === 0 || this.stateStack[this.stateStack.length - 1].activeSMask !== this.current.activeSMask)) {
  6573. this.endSMaskGroup();
  6574. }
  6575. if (this.stateStack.length !== 0) {
  6576. this.current = this.stateStack.pop();
  6577. this.ctx.restore();
  6578. this.pendingClip = null;
  6579. this.cachedGetSinglePixelWidth = null;
  6580. }
  6581. },
  6582. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  6583. this.ctx.transform(a, b, c, d, e, f);
  6584. this.cachedGetSinglePixelWidth = null;
  6585. },
  6586. constructPath: function CanvasGraphics_constructPath(ops, args) {
  6587. var ctx = this.ctx;
  6588. var current = this.current;
  6589. var x = current.x, y = current.y;
  6590. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  6591. switch (ops[i] | 0) {
  6592. case OPS.rectangle:
  6593. x = args[j++];
  6594. y = args[j++];
  6595. var width = args[j++];
  6596. var height = args[j++];
  6597. if (width === 0) {
  6598. width = this.getSinglePixelWidth();
  6599. }
  6600. if (height === 0) {
  6601. height = this.getSinglePixelWidth();
  6602. }
  6603. var xw = x + width;
  6604. var yh = y + height;
  6605. this.ctx.moveTo(x, y);
  6606. this.ctx.lineTo(xw, y);
  6607. this.ctx.lineTo(xw, yh);
  6608. this.ctx.lineTo(x, yh);
  6609. this.ctx.lineTo(x, y);
  6610. this.ctx.closePath();
  6611. break;
  6612. case OPS.moveTo:
  6613. x = args[j++];
  6614. y = args[j++];
  6615. ctx.moveTo(x, y);
  6616. break;
  6617. case OPS.lineTo:
  6618. x = args[j++];
  6619. y = args[j++];
  6620. ctx.lineTo(x, y);
  6621. break;
  6622. case OPS.curveTo:
  6623. x = args[j + 4];
  6624. y = args[j + 5];
  6625. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
  6626. j += 6;
  6627. break;
  6628. case OPS.curveTo2:
  6629. ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
  6630. x = args[j + 2];
  6631. y = args[j + 3];
  6632. j += 4;
  6633. break;
  6634. case OPS.curveTo3:
  6635. x = args[j + 2];
  6636. y = args[j + 3];
  6637. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  6638. j += 4;
  6639. break;
  6640. case OPS.closePath:
  6641. ctx.closePath();
  6642. break;
  6643. }
  6644. }
  6645. current.setCurrentPoint(x, y);
  6646. },
  6647. closePath: function CanvasGraphics_closePath() {
  6648. this.ctx.closePath();
  6649. },
  6650. stroke: function CanvasGraphics_stroke(consumePath) {
  6651. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  6652. var ctx = this.ctx;
  6653. var strokeColor = this.current.strokeColor;
  6654. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR, this.current.lineWidth);
  6655. ctx.globalAlpha = this.current.strokeAlpha;
  6656. if (strokeColor && strokeColor.hasOwnProperty('type') && strokeColor.type === 'Pattern') {
  6657. ctx.save();
  6658. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  6659. ctx.stroke();
  6660. ctx.restore();
  6661. } else {
  6662. ctx.stroke();
  6663. }
  6664. if (consumePath) {
  6665. this.consumePath();
  6666. }
  6667. ctx.globalAlpha = this.current.fillAlpha;
  6668. },
  6669. closeStroke: function CanvasGraphics_closeStroke() {
  6670. this.closePath();
  6671. this.stroke();
  6672. },
  6673. fill: function CanvasGraphics_fill(consumePath) {
  6674. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  6675. var ctx = this.ctx;
  6676. var fillColor = this.current.fillColor;
  6677. var isPatternFill = this.current.patternFill;
  6678. var needRestore = false;
  6679. if (isPatternFill) {
  6680. ctx.save();
  6681. if (this.baseTransform) {
  6682. ctx.setTransform.apply(ctx, this.baseTransform);
  6683. }
  6684. ctx.fillStyle = fillColor.getPattern(ctx, this);
  6685. needRestore = true;
  6686. }
  6687. if (this.pendingEOFill) {
  6688. if (ctx.mozFillRule !== undefined) {
  6689. ctx.mozFillRule = 'evenodd';
  6690. ctx.fill();
  6691. ctx.mozFillRule = 'nonzero';
  6692. } else {
  6693. ctx.fill('evenodd');
  6694. }
  6695. this.pendingEOFill = false;
  6696. } else {
  6697. ctx.fill();
  6698. }
  6699. if (needRestore) {
  6700. ctx.restore();
  6701. }
  6702. if (consumePath) {
  6703. this.consumePath();
  6704. }
  6705. },
  6706. eoFill: function CanvasGraphics_eoFill() {
  6707. this.pendingEOFill = true;
  6708. this.fill();
  6709. },
  6710. fillStroke: function CanvasGraphics_fillStroke() {
  6711. this.fill(false);
  6712. this.stroke(false);
  6713. this.consumePath();
  6714. },
  6715. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  6716. this.pendingEOFill = true;
  6717. this.fillStroke();
  6718. },
  6719. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  6720. this.closePath();
  6721. this.fillStroke();
  6722. },
  6723. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  6724. this.pendingEOFill = true;
  6725. this.closePath();
  6726. this.fillStroke();
  6727. },
  6728. endPath: function CanvasGraphics_endPath() {
  6729. this.consumePath();
  6730. },
  6731. clip: function CanvasGraphics_clip() {
  6732. this.pendingClip = NORMAL_CLIP;
  6733. },
  6734. eoClip: function CanvasGraphics_eoClip() {
  6735. this.pendingClip = EO_CLIP;
  6736. },
  6737. beginText: function CanvasGraphics_beginText() {
  6738. this.current.textMatrix = IDENTITY_MATRIX;
  6739. this.current.textMatrixScale = 1;
  6740. this.current.x = this.current.lineX = 0;
  6741. this.current.y = this.current.lineY = 0;
  6742. },
  6743. endText: function CanvasGraphics_endText() {
  6744. var paths = this.pendingTextPaths;
  6745. var ctx = this.ctx;
  6746. if (paths === undefined) {
  6747. ctx.beginPath();
  6748. return;
  6749. }
  6750. ctx.save();
  6751. ctx.beginPath();
  6752. for (var i = 0; i < paths.length; i++) {
  6753. var path = paths[i];
  6754. ctx.setTransform.apply(ctx, path.transform);
  6755. ctx.translate(path.x, path.y);
  6756. path.addToPath(ctx, path.fontSize);
  6757. }
  6758. ctx.restore();
  6759. ctx.clip();
  6760. ctx.beginPath();
  6761. delete this.pendingTextPaths;
  6762. },
  6763. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  6764. this.current.charSpacing = spacing;
  6765. },
  6766. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  6767. this.current.wordSpacing = spacing;
  6768. },
  6769. setHScale: function CanvasGraphics_setHScale(scale) {
  6770. this.current.textHScale = scale / 100;
  6771. },
  6772. setLeading: function CanvasGraphics_setLeading(leading) {
  6773. this.current.leading = -leading;
  6774. },
  6775. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  6776. var fontObj = this.commonObjs.get(fontRefName);
  6777. var current = this.current;
  6778. if (!fontObj) {
  6779. error('Can\'t find font for ' + fontRefName);
  6780. }
  6781. current.fontMatrix = fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX;
  6782. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  6783. warn('Invalid font matrix for font ' + fontRefName);
  6784. }
  6785. if (size < 0) {
  6786. size = -size;
  6787. current.fontDirection = -1;
  6788. } else {
  6789. current.fontDirection = 1;
  6790. }
  6791. this.current.font = fontObj;
  6792. this.current.fontSize = size;
  6793. if (fontObj.isType3Font) {
  6794. return;
  6795. }
  6796. var name = fontObj.loadedName || 'sans-serif';
  6797. var bold = fontObj.black ? '900' : fontObj.bold ? 'bold' : 'normal';
  6798. var italic = fontObj.italic ? 'italic' : 'normal';
  6799. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  6800. var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE : size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
  6801. this.current.fontSizeScale = size / browserFontSize;
  6802. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  6803. this.ctx.font = rule;
  6804. },
  6805. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  6806. this.current.textRenderingMode = mode;
  6807. },
  6808. setTextRise: function CanvasGraphics_setTextRise(rise) {
  6809. this.current.textRise = rise;
  6810. },
  6811. moveText: function CanvasGraphics_moveText(x, y) {
  6812. this.current.x = this.current.lineX += x;
  6813. this.current.y = this.current.lineY += y;
  6814. },
  6815. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  6816. this.setLeading(-y);
  6817. this.moveText(x, y);
  6818. },
  6819. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  6820. this.current.textMatrix = [
  6821. a,
  6822. b,
  6823. c,
  6824. d,
  6825. e,
  6826. f
  6827. ];
  6828. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  6829. this.current.x = this.current.lineX = 0;
  6830. this.current.y = this.current.lineY = 0;
  6831. },
  6832. nextLine: function CanvasGraphics_nextLine() {
  6833. this.moveText(0, this.current.leading);
  6834. },
  6835. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  6836. var ctx = this.ctx;
  6837. var current = this.current;
  6838. var font = current.font;
  6839. var textRenderingMode = current.textRenderingMode;
  6840. var fontSize = current.fontSize / current.fontSizeScale;
  6841. var fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
  6842. var isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG);
  6843. var addToPath;
  6844. if (font.disableFontFace || isAddToPathSet) {
  6845. addToPath = font.getPathGenerator(this.commonObjs, character);
  6846. }
  6847. if (font.disableFontFace) {
  6848. ctx.save();
  6849. ctx.translate(x, y);
  6850. ctx.beginPath();
  6851. addToPath(ctx, fontSize);
  6852. if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  6853. ctx.fill();
  6854. }
  6855. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  6856. ctx.stroke();
  6857. }
  6858. ctx.restore();
  6859. } else {
  6860. if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  6861. ctx.fillText(character, x, y);
  6862. }
  6863. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  6864. ctx.strokeText(character, x, y);
  6865. }
  6866. }
  6867. if (isAddToPathSet) {
  6868. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  6869. paths.push({
  6870. transform: ctx.mozCurrentTransform,
  6871. x: x,
  6872. y: y,
  6873. fontSize: fontSize,
  6874. addToPath: addToPath
  6875. });
  6876. }
  6877. },
  6878. get isFontSubpixelAAEnabled() {
  6879. var ctx = document.createElement('canvas').getContext('2d');
  6880. ctx.scale(1.5, 1);
  6881. ctx.fillText('I', 0, 10);
  6882. var data = ctx.getImageData(0, 0, 10, 10).data;
  6883. var enabled = false;
  6884. for (var i = 3; i < data.length; i += 4) {
  6885. if (data[i] > 0 && data[i] < 255) {
  6886. enabled = true;
  6887. break;
  6888. }
  6889. }
  6890. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  6891. },
  6892. showText: function CanvasGraphics_showText(glyphs) {
  6893. var current = this.current;
  6894. var font = current.font;
  6895. if (font.isType3Font) {
  6896. return this.showType3Text(glyphs);
  6897. }
  6898. var fontSize = current.fontSize;
  6899. if (fontSize === 0) {
  6900. return;
  6901. }
  6902. var ctx = this.ctx;
  6903. var fontSizeScale = current.fontSizeScale;
  6904. var charSpacing = current.charSpacing;
  6905. var wordSpacing = current.wordSpacing;
  6906. var fontDirection = current.fontDirection;
  6907. var textHScale = current.textHScale * fontDirection;
  6908. var glyphsLength = glyphs.length;
  6909. var vertical = font.vertical;
  6910. var spacingDir = vertical ? 1 : -1;
  6911. var defaultVMetrics = font.defaultVMetrics;
  6912. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  6913. var simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace;
  6914. ctx.save();
  6915. ctx.transform.apply(ctx, current.textMatrix);
  6916. ctx.translate(current.x, current.y + current.textRise);
  6917. if (current.patternFill) {
  6918. ctx.fillStyle = current.fillColor.getPattern(ctx, this);
  6919. }
  6920. if (fontDirection > 0) {
  6921. ctx.scale(textHScale, -1);
  6922. } else {
  6923. ctx.scale(textHScale, 1);
  6924. }
  6925. var lineWidth = current.lineWidth;
  6926. var scale = current.textMatrixScale;
  6927. if (scale === 0 || lineWidth === 0) {
  6928. var fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
  6929. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  6930. this.cachedGetSinglePixelWidth = null;
  6931. lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
  6932. }
  6933. } else {
  6934. lineWidth /= scale;
  6935. }
  6936. if (fontSizeScale !== 1.0) {
  6937. ctx.scale(fontSizeScale, fontSizeScale);
  6938. lineWidth /= fontSizeScale;
  6939. }
  6940. ctx.lineWidth = lineWidth;
  6941. var x = 0, i;
  6942. for (i = 0; i < glyphsLength; ++i) {
  6943. var glyph = glyphs[i];
  6944. if (isNum(glyph)) {
  6945. x += spacingDir * glyph * fontSize / 1000;
  6946. continue;
  6947. }
  6948. var restoreNeeded = false;
  6949. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  6950. var character = glyph.fontChar;
  6951. var accent = glyph.accent;
  6952. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  6953. var width = glyph.width;
  6954. if (vertical) {
  6955. var vmetric, vx, vy;
  6956. vmetric = glyph.vmetric || defaultVMetrics;
  6957. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  6958. vx = -vx * widthAdvanceScale;
  6959. vy = vmetric[2] * widthAdvanceScale;
  6960. width = vmetric ? -vmetric[0] : width;
  6961. scaledX = vx / fontSizeScale;
  6962. scaledY = (x + vy) / fontSizeScale;
  6963. } else {
  6964. scaledX = x / fontSizeScale;
  6965. scaledY = 0;
  6966. }
  6967. if (font.remeasure && width > 0) {
  6968. var measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  6969. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  6970. var characterScaleX = width / measuredWidth;
  6971. restoreNeeded = true;
  6972. ctx.save();
  6973. ctx.scale(characterScaleX, 1);
  6974. scaledX /= characterScaleX;
  6975. } else if (width !== measuredWidth) {
  6976. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  6977. }
  6978. }
  6979. if (glyph.isInFont || font.missingFile) {
  6980. if (simpleFillText && !accent) {
  6981. ctx.fillText(character, scaledX, scaledY);
  6982. } else {
  6983. this.paintChar(character, scaledX, scaledY);
  6984. if (accent) {
  6985. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  6986. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  6987. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  6988. }
  6989. }
  6990. }
  6991. var charWidth = width * widthAdvanceScale + spacing * fontDirection;
  6992. x += charWidth;
  6993. if (restoreNeeded) {
  6994. ctx.restore();
  6995. }
  6996. }
  6997. if (vertical) {
  6998. current.y -= x * textHScale;
  6999. } else {
  7000. current.x += x * textHScale;
  7001. }
  7002. ctx.restore();
  7003. },
  7004. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  7005. var ctx = this.ctx;
  7006. var current = this.current;
  7007. var font = current.font;
  7008. var fontSize = current.fontSize;
  7009. var fontDirection = current.fontDirection;
  7010. var spacingDir = font.vertical ? 1 : -1;
  7011. var charSpacing = current.charSpacing;
  7012. var wordSpacing = current.wordSpacing;
  7013. var textHScale = current.textHScale * fontDirection;
  7014. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  7015. var glyphsLength = glyphs.length;
  7016. var isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE;
  7017. var i, glyph, width, spacingLength;
  7018. if (isTextInvisible || fontSize === 0) {
  7019. return;
  7020. }
  7021. this.cachedGetSinglePixelWidth = null;
  7022. ctx.save();
  7023. ctx.transform.apply(ctx, current.textMatrix);
  7024. ctx.translate(current.x, current.y);
  7025. ctx.scale(textHScale, fontDirection);
  7026. for (i = 0; i < glyphsLength; ++i) {
  7027. glyph = glyphs[i];
  7028. if (isNum(glyph)) {
  7029. spacingLength = spacingDir * glyph * fontSize / 1000;
  7030. this.ctx.translate(spacingLength, 0);
  7031. current.x += spacingLength * textHScale;
  7032. continue;
  7033. }
  7034. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7035. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  7036. if (!operatorList) {
  7037. warn('Type3 character \"' + glyph.operatorListId + '\" is not available');
  7038. continue;
  7039. }
  7040. this.processingType3 = glyph;
  7041. this.save();
  7042. ctx.scale(fontSize, fontSize);
  7043. ctx.transform.apply(ctx, fontMatrix);
  7044. this.executeOperatorList(operatorList);
  7045. this.restore();
  7046. var transformed = Util.applyTransform([
  7047. glyph.width,
  7048. 0
  7049. ], fontMatrix);
  7050. width = transformed[0] * fontSize + spacing;
  7051. ctx.translate(width, 0);
  7052. current.x += width * textHScale;
  7053. }
  7054. ctx.restore();
  7055. this.processingType3 = null;
  7056. },
  7057. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  7058. },
  7059. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  7060. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  7061. this.clip();
  7062. this.endPath();
  7063. },
  7064. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  7065. var pattern;
  7066. if (IR[0] === 'TilingPattern') {
  7067. var color = IR[1];
  7068. var baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice();
  7069. var self = this;
  7070. var canvasGraphicsFactory = {
  7071. createCanvasGraphics: function (ctx) {
  7072. return new CanvasGraphics(ctx, self.commonObjs, self.objs);
  7073. }
  7074. };
  7075. pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
  7076. } else {
  7077. pattern = getShadingPatternFromIR(IR);
  7078. }
  7079. return pattern;
  7080. },
  7081. setStrokeColorN: function CanvasGraphics_setStrokeColorN() {
  7082. this.current.strokeColor = this.getColorN_Pattern(arguments);
  7083. },
  7084. setFillColorN: function CanvasGraphics_setFillColorN() {
  7085. this.current.fillColor = this.getColorN_Pattern(arguments);
  7086. this.current.patternFill = true;
  7087. },
  7088. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  7089. var color = Util.makeCssRgb(r, g, b);
  7090. this.ctx.strokeStyle = color;
  7091. this.current.strokeColor = color;
  7092. },
  7093. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  7094. var color = Util.makeCssRgb(r, g, b);
  7095. this.ctx.fillStyle = color;
  7096. this.current.fillColor = color;
  7097. this.current.patternFill = false;
  7098. },
  7099. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  7100. var ctx = this.ctx;
  7101. this.save();
  7102. var pattern = getShadingPatternFromIR(patternIR);
  7103. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  7104. var inv = ctx.mozCurrentTransformInverse;
  7105. if (inv) {
  7106. var canvas = ctx.canvas;
  7107. var width = canvas.width;
  7108. var height = canvas.height;
  7109. var bl = Util.applyTransform([
  7110. 0,
  7111. 0
  7112. ], inv);
  7113. var br = Util.applyTransform([
  7114. 0,
  7115. height
  7116. ], inv);
  7117. var ul = Util.applyTransform([
  7118. width,
  7119. 0
  7120. ], inv);
  7121. var ur = Util.applyTransform([
  7122. width,
  7123. height
  7124. ], inv);
  7125. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  7126. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  7127. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  7128. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  7129. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  7130. } else {
  7131. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  7132. }
  7133. this.restore();
  7134. },
  7135. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  7136. error('Should not call beginInlineImage');
  7137. },
  7138. beginImageData: function CanvasGraphics_beginImageData() {
  7139. error('Should not call beginImageData');
  7140. },
  7141. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix, bbox) {
  7142. this.save();
  7143. this.baseTransformStack.push(this.baseTransform);
  7144. if (isArray(matrix) && matrix.length === 6) {
  7145. this.transform.apply(this, matrix);
  7146. }
  7147. this.baseTransform = this.ctx.mozCurrentTransform;
  7148. if (isArray(bbox) && bbox.length === 4) {
  7149. var width = bbox[2] - bbox[0];
  7150. var height = bbox[3] - bbox[1];
  7151. this.ctx.rect(bbox[0], bbox[1], width, height);
  7152. this.clip();
  7153. this.endPath();
  7154. }
  7155. },
  7156. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  7157. this.restore();
  7158. this.baseTransform = this.baseTransformStack.pop();
  7159. },
  7160. beginGroup: function CanvasGraphics_beginGroup(group) {
  7161. this.save();
  7162. var currentCtx = this.ctx;
  7163. if (!group.isolated) {
  7164. info('TODO: Support non-isolated groups.');
  7165. }
  7166. if (group.knockout) {
  7167. warn('Knockout groups not supported.');
  7168. }
  7169. var currentTransform = currentCtx.mozCurrentTransform;
  7170. if (group.matrix) {
  7171. currentCtx.transform.apply(currentCtx, group.matrix);
  7172. }
  7173. assert(group.bbox, 'Bounding box is required.');
  7174. var bounds = Util.getAxialAlignedBoundingBox(group.bbox, currentCtx.mozCurrentTransform);
  7175. var canvasBounds = [
  7176. 0,
  7177. 0,
  7178. currentCtx.canvas.width,
  7179. currentCtx.canvas.height
  7180. ];
  7181. bounds = Util.intersect(bounds, canvasBounds) || [
  7182. 0,
  7183. 0,
  7184. 0,
  7185. 0
  7186. ];
  7187. var offsetX = Math.floor(bounds[0]);
  7188. var offsetY = Math.floor(bounds[1]);
  7189. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  7190. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  7191. var scaleX = 1, scaleY = 1;
  7192. if (drawnWidth > MAX_GROUP_SIZE) {
  7193. scaleX = drawnWidth / MAX_GROUP_SIZE;
  7194. drawnWidth = MAX_GROUP_SIZE;
  7195. }
  7196. if (drawnHeight > MAX_GROUP_SIZE) {
  7197. scaleY = drawnHeight / MAX_GROUP_SIZE;
  7198. drawnHeight = MAX_GROUP_SIZE;
  7199. }
  7200. var cacheId = 'groupAt' + this.groupLevel;
  7201. if (group.smask) {
  7202. cacheId += '_smask_' + this.smaskCounter++ % 2;
  7203. }
  7204. var scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  7205. var groupCtx = scratchCanvas.context;
  7206. groupCtx.scale(1 / scaleX, 1 / scaleY);
  7207. groupCtx.translate(-offsetX, -offsetY);
  7208. groupCtx.transform.apply(groupCtx, currentTransform);
  7209. if (group.smask) {
  7210. this.smaskStack.push({
  7211. canvas: scratchCanvas.canvas,
  7212. context: groupCtx,
  7213. offsetX: offsetX,
  7214. offsetY: offsetY,
  7215. scaleX: scaleX,
  7216. scaleY: scaleY,
  7217. subtype: group.smask.subtype,
  7218. backdrop: group.smask.backdrop,
  7219. transferMap: group.smask.transferMap || null,
  7220. startTransformInverse: null
  7221. });
  7222. } else
  7223. {
  7224. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  7225. currentCtx.translate(offsetX, offsetY);
  7226. currentCtx.scale(scaleX, scaleY);
  7227. }
  7228. copyCtxState(currentCtx, groupCtx);
  7229. this.ctx = groupCtx;
  7230. this.setGState([
  7231. [
  7232. 'BM',
  7233. 'Normal'
  7234. ],
  7235. [
  7236. 'ca',
  7237. 1
  7238. ],
  7239. [
  7240. 'CA',
  7241. 1
  7242. ]
  7243. ]);
  7244. this.groupStack.push(currentCtx);
  7245. this.groupLevel++;
  7246. this.current.activeSMask = null;
  7247. },
  7248. endGroup: function CanvasGraphics_endGroup(group) {
  7249. this.groupLevel--;
  7250. var groupCtx = this.ctx;
  7251. this.ctx = this.groupStack.pop();
  7252. if (this.ctx.imageSmoothingEnabled !== undefined) {
  7253. this.ctx.imageSmoothingEnabled = false;
  7254. } else {
  7255. this.ctx.mozImageSmoothingEnabled = false;
  7256. }
  7257. if (group.smask) {
  7258. this.tempSMask = this.smaskStack.pop();
  7259. } else {
  7260. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  7261. }
  7262. this.restore();
  7263. },
  7264. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  7265. this.save();
  7266. this.current = new CanvasExtraState();
  7267. if (this.baseTransform) {
  7268. this.ctx.setTransform.apply(this.ctx, this.baseTransform);
  7269. }
  7270. },
  7271. endAnnotations: function CanvasGraphics_endAnnotations() {
  7272. this.restore();
  7273. },
  7274. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform, matrix) {
  7275. this.save();
  7276. if (isArray(rect) && rect.length === 4) {
  7277. var width = rect[2] - rect[0];
  7278. var height = rect[3] - rect[1];
  7279. this.ctx.rect(rect[0], rect[1], width, height);
  7280. this.clip();
  7281. this.endPath();
  7282. }
  7283. this.transform.apply(this, transform);
  7284. this.transform.apply(this, matrix);
  7285. },
  7286. endAnnotation: function CanvasGraphics_endAnnotation() {
  7287. this.restore();
  7288. },
  7289. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  7290. var domImage = this.objs.get(objId);
  7291. if (!domImage) {
  7292. warn('Dependent image isn\'t ready yet');
  7293. return;
  7294. }
  7295. this.save();
  7296. var ctx = this.ctx;
  7297. ctx.scale(1 / w, -1 / h);
  7298. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height, 0, -h, w, h);
  7299. if (this.imageLayer) {
  7300. var currentTransform = ctx.mozCurrentTransformInverse;
  7301. var position = this.getCanvasPosition(0, 0);
  7302. this.imageLayer.appendImage({
  7303. objId: objId,
  7304. left: position[0],
  7305. top: position[1],
  7306. width: w / currentTransform[0],
  7307. height: h / currentTransform[3]
  7308. });
  7309. }
  7310. this.restore();
  7311. },
  7312. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  7313. var ctx = this.ctx;
  7314. var width = img.width, height = img.height;
  7315. var fillColor = this.current.fillColor;
  7316. var isPatternFill = this.current.patternFill;
  7317. var glyph = this.processingType3;
  7318. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  7319. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  7320. glyph.compiled = compileType3Glyph({
  7321. data: img.data,
  7322. width: width,
  7323. height: height
  7324. });
  7325. } else {
  7326. glyph.compiled = null;
  7327. }
  7328. }
  7329. if (glyph && glyph.compiled) {
  7330. glyph.compiled(ctx);
  7331. return;
  7332. }
  7333. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height);
  7334. var maskCtx = maskCanvas.context;
  7335. maskCtx.save();
  7336. putBinaryImageMask(maskCtx, img);
  7337. maskCtx.globalCompositeOperation = 'source-in';
  7338. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  7339. maskCtx.fillRect(0, 0, width, height);
  7340. maskCtx.restore();
  7341. this.paintInlineImageXObject(maskCanvas.canvas);
  7342. },
  7343. paintImageMaskXObjectRepeat: function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX, scaleY, positions) {
  7344. var width = imgData.width;
  7345. var height = imgData.height;
  7346. var fillColor = this.current.fillColor;
  7347. var isPatternFill = this.current.patternFill;
  7348. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height);
  7349. var maskCtx = maskCanvas.context;
  7350. maskCtx.save();
  7351. putBinaryImageMask(maskCtx, imgData);
  7352. maskCtx.globalCompositeOperation = 'source-in';
  7353. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  7354. maskCtx.fillRect(0, 0, width, height);
  7355. maskCtx.restore();
  7356. var ctx = this.ctx;
  7357. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  7358. ctx.save();
  7359. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  7360. ctx.scale(1, -1);
  7361. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  7362. ctx.restore();
  7363. }
  7364. },
  7365. paintImageMaskXObjectGroup: function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  7366. var ctx = this.ctx;
  7367. var fillColor = this.current.fillColor;
  7368. var isPatternFill = this.current.patternFill;
  7369. for (var i = 0, ii = images.length; i < ii; i++) {
  7370. var image = images[i];
  7371. var width = image.width, height = image.height;
  7372. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height);
  7373. var maskCtx = maskCanvas.context;
  7374. maskCtx.save();
  7375. putBinaryImageMask(maskCtx, image);
  7376. maskCtx.globalCompositeOperation = 'source-in';
  7377. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  7378. maskCtx.fillRect(0, 0, width, height);
  7379. maskCtx.restore();
  7380. ctx.save();
  7381. ctx.transform.apply(ctx, image.transform);
  7382. ctx.scale(1, -1);
  7383. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  7384. ctx.restore();
  7385. }
  7386. },
  7387. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  7388. var imgData = this.objs.get(objId);
  7389. if (!imgData) {
  7390. warn('Dependent image isn\'t ready yet');
  7391. return;
  7392. }
  7393. this.paintInlineImageXObject(imgData);
  7394. },
  7395. paintImageXObjectRepeat: function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  7396. var imgData = this.objs.get(objId);
  7397. if (!imgData) {
  7398. warn('Dependent image isn\'t ready yet');
  7399. return;
  7400. }
  7401. var width = imgData.width;
  7402. var height = imgData.height;
  7403. var map = [];
  7404. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  7405. map.push({
  7406. transform: [
  7407. scaleX,
  7408. 0,
  7409. 0,
  7410. scaleY,
  7411. positions[i],
  7412. positions[i + 1]
  7413. ],
  7414. x: 0,
  7415. y: 0,
  7416. w: width,
  7417. h: height
  7418. });
  7419. }
  7420. this.paintInlineImageXObjectGroup(imgData, map);
  7421. },
  7422. paintInlineImageXObject: function CanvasGraphics_paintInlineImageXObject(imgData) {
  7423. var width = imgData.width;
  7424. var height = imgData.height;
  7425. var ctx = this.ctx;
  7426. this.save();
  7427. ctx.scale(1 / width, -1 / height);
  7428. var currentTransform = ctx.mozCurrentTransformInverse;
  7429. var a = currentTransform[0], b = currentTransform[1];
  7430. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  7431. var c = currentTransform[2], d = currentTransform[3];
  7432. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  7433. var imgToPaint, tmpCanvas;
  7434. if (imgData instanceof HTMLElement || !imgData.data) {
  7435. imgToPaint = imgData;
  7436. } else {
  7437. tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', width, height);
  7438. var tmpCtx = tmpCanvas.context;
  7439. putBinaryImageData(tmpCtx, imgData);
  7440. imgToPaint = tmpCanvas.canvas;
  7441. }
  7442. var paintWidth = width, paintHeight = height;
  7443. var tmpCanvasId = 'prescale1';
  7444. while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
  7445. var newWidth = paintWidth, newHeight = paintHeight;
  7446. if (widthScale > 2 && paintWidth > 1) {
  7447. newWidth = Math.ceil(paintWidth / 2);
  7448. widthScale /= paintWidth / newWidth;
  7449. }
  7450. if (heightScale > 2 && paintHeight > 1) {
  7451. newHeight = Math.ceil(paintHeight / 2);
  7452. heightScale /= paintHeight / newHeight;
  7453. }
  7454. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  7455. tmpCtx = tmpCanvas.context;
  7456. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  7457. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
  7458. imgToPaint = tmpCanvas.canvas;
  7459. paintWidth = newWidth;
  7460. paintHeight = newHeight;
  7461. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  7462. }
  7463. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, -height, width, height);
  7464. if (this.imageLayer) {
  7465. var position = this.getCanvasPosition(0, -height);
  7466. this.imageLayer.appendImage({
  7467. imgData: imgData,
  7468. left: position[0],
  7469. top: position[1],
  7470. width: width / currentTransform[0],
  7471. height: height / currentTransform[3]
  7472. });
  7473. }
  7474. this.restore();
  7475. },
  7476. paintInlineImageXObjectGroup: function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  7477. var ctx = this.ctx;
  7478. var w = imgData.width;
  7479. var h = imgData.height;
  7480. var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h);
  7481. var tmpCtx = tmpCanvas.context;
  7482. putBinaryImageData(tmpCtx, imgData);
  7483. for (var i = 0, ii = map.length; i < ii; i++) {
  7484. var entry = map[i];
  7485. ctx.save();
  7486. ctx.transform.apply(ctx, entry.transform);
  7487. ctx.scale(1, -1);
  7488. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  7489. if (this.imageLayer) {
  7490. var position = this.getCanvasPosition(entry.x, entry.y);
  7491. this.imageLayer.appendImage({
  7492. imgData: imgData,
  7493. left: position[0],
  7494. top: position[1],
  7495. width: w,
  7496. height: h
  7497. });
  7498. }
  7499. ctx.restore();
  7500. }
  7501. },
  7502. paintSolidColorImageMask: function CanvasGraphics_paintSolidColorImageMask() {
  7503. this.ctx.fillRect(0, 0, 1, 1);
  7504. },
  7505. paintXObject: function CanvasGraphics_paintXObject() {
  7506. warn('Unsupported \'paintXObject\' command.');
  7507. },
  7508. markPoint: function CanvasGraphics_markPoint(tag) {
  7509. },
  7510. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  7511. },
  7512. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  7513. },
  7514. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(tag, properties) {
  7515. },
  7516. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  7517. },
  7518. beginCompat: function CanvasGraphics_beginCompat() {
  7519. },
  7520. endCompat: function CanvasGraphics_endCompat() {
  7521. },
  7522. consumePath: function CanvasGraphics_consumePath() {
  7523. var ctx = this.ctx;
  7524. if (this.pendingClip) {
  7525. if (this.pendingClip === EO_CLIP) {
  7526. if (ctx.mozFillRule !== undefined) {
  7527. ctx.mozFillRule = 'evenodd';
  7528. ctx.clip();
  7529. ctx.mozFillRule = 'nonzero';
  7530. } else {
  7531. ctx.clip('evenodd');
  7532. }
  7533. } else {
  7534. ctx.clip();
  7535. }
  7536. this.pendingClip = null;
  7537. }
  7538. ctx.beginPath();
  7539. },
  7540. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  7541. if (this.cachedGetSinglePixelWidth === null) {
  7542. this.ctx.save();
  7543. var inverse = this.ctx.mozCurrentTransformInverse;
  7544. this.ctx.restore();
  7545. this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(inverse[0] * inverse[0] + inverse[1] * inverse[1], inverse[2] * inverse[2] + inverse[3] * inverse[3]));
  7546. }
  7547. return this.cachedGetSinglePixelWidth;
  7548. },
  7549. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  7550. var transform = this.ctx.mozCurrentTransform;
  7551. return [
  7552. transform[0] * x + transform[2] * y + transform[4],
  7553. transform[1] * x + transform[3] * y + transform[5]
  7554. ];
  7555. }
  7556. };
  7557. for (var op in OPS) {
  7558. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  7559. }
  7560. return CanvasGraphics;
  7561. }();
  7562. exports.CanvasGraphics = CanvasGraphics;
  7563. exports.createScratchCanvas = createScratchCanvas;
  7564. }));
  7565. (function (root, factory) {
  7566. factory(root.pdfjsDisplayAPI = {}, root.pdfjsSharedUtil, root.pdfjsDisplayFontLoader, root.pdfjsDisplayCanvas, root.pdfjsDisplayMetadata, root.pdfjsDisplayDOMUtils);
  7567. }(this, function (exports, sharedUtil, displayFontLoader, displayCanvas, displayMetadata, displayDOMUtils, amdRequire) {
  7568. var InvalidPDFException = sharedUtil.InvalidPDFException;
  7569. var MessageHandler = sharedUtil.MessageHandler;
  7570. var MissingPDFException = sharedUtil.MissingPDFException;
  7571. var PageViewport = sharedUtil.PageViewport;
  7572. var PasswordResponses = sharedUtil.PasswordResponses;
  7573. var PasswordException = sharedUtil.PasswordException;
  7574. var StatTimer = sharedUtil.StatTimer;
  7575. var UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  7576. var UnknownErrorException = sharedUtil.UnknownErrorException;
  7577. var Util = sharedUtil.Util;
  7578. var createPromiseCapability = sharedUtil.createPromiseCapability;
  7579. var error = sharedUtil.error;
  7580. var deprecated = sharedUtil.deprecated;
  7581. var getVerbosityLevel = sharedUtil.getVerbosityLevel;
  7582. var info = sharedUtil.info;
  7583. var isInt = sharedUtil.isInt;
  7584. var isArray = sharedUtil.isArray;
  7585. var isArrayBuffer = sharedUtil.isArrayBuffer;
  7586. var isSameOrigin = sharedUtil.isSameOrigin;
  7587. var loadJpegStream = sharedUtil.loadJpegStream;
  7588. var stringToBytes = sharedUtil.stringToBytes;
  7589. var globalScope = sharedUtil.globalScope;
  7590. var warn = sharedUtil.warn;
  7591. var FontFaceObject = displayFontLoader.FontFaceObject;
  7592. var FontLoader = displayFontLoader.FontLoader;
  7593. var CanvasGraphics = displayCanvas.CanvasGraphics;
  7594. var createScratchCanvas = displayCanvas.createScratchCanvas;
  7595. var Metadata = displayMetadata.Metadata;
  7596. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  7597. var DEFAULT_RANGE_CHUNK_SIZE = 65536;
  7598. var isWorkerDisabled = false;
  7599. var workerSrc;
  7600. var isPostMessageTransfersDisabled = false;
  7601. var fakeWorkerFilesLoader = null;
  7602. var useRequireEnsure = false;
  7603. if (typeof window === 'undefined') {
  7604. isWorkerDisabled = true;
  7605. if (typeof require.ensure === 'undefined') {
  7606. require.ensure = require('node-ensure');
  7607. }
  7608. useRequireEnsure = true;
  7609. }
  7610. if (typeof __webpack_require__ !== 'undefined') {
  7611. useRequireEnsure = true;
  7612. }
  7613. if (typeof requirejs !== 'undefined' && requirejs.toUrl) {
  7614. workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js');
  7615. }
  7616. var dynamicLoaderSupported = typeof requirejs !== 'undefined' && requirejs.load;
  7617. fakeWorkerFilesLoader = useRequireEnsure ? function (callback) {
  7618. require.ensure([], function () {
  7619. var worker = require('./pdf.worker.js');
  7620. callback(worker.WorkerMessageHandler);
  7621. });
  7622. } : dynamicLoaderSupported ? function (callback) {
  7623. requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) {
  7624. callback(worker.WorkerMessageHandler);
  7625. });
  7626. } : null;
  7627. function getDocument(src, pdfDataRangeTransport, passwordCallback, progressCallback) {
  7628. var task = new PDFDocumentLoadingTask();
  7629. if (arguments.length > 1) {
  7630. deprecated('getDocument is called with pdfDataRangeTransport, ' + 'passwordCallback or progressCallback argument');
  7631. }
  7632. if (pdfDataRangeTransport) {
  7633. if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) {
  7634. pdfDataRangeTransport = Object.create(pdfDataRangeTransport);
  7635. pdfDataRangeTransport.length = src.length;
  7636. pdfDataRangeTransport.initialData = src.initialData;
  7637. if (!pdfDataRangeTransport.abort) {
  7638. pdfDataRangeTransport.abort = function () {
  7639. };
  7640. }
  7641. }
  7642. src = Object.create(src);
  7643. src.range = pdfDataRangeTransport;
  7644. }
  7645. task.onPassword = passwordCallback || null;
  7646. task.onProgress = progressCallback || null;
  7647. var source;
  7648. if (typeof src === 'string') {
  7649. source = { url: src };
  7650. } else if (isArrayBuffer(src)) {
  7651. source = { data: src };
  7652. } else if (src instanceof PDFDataRangeTransport) {
  7653. source = { range: src };
  7654. } else {
  7655. if (typeof src !== 'object') {
  7656. error('Invalid parameter in getDocument, need either Uint8Array, ' + 'string or a parameter object');
  7657. }
  7658. if (!src.url && !src.data && !src.range) {
  7659. error('Invalid parameter object: need either .data, .range or .url');
  7660. }
  7661. source = src;
  7662. }
  7663. var params = {};
  7664. var rangeTransport = null;
  7665. var worker = null;
  7666. for (var key in source) {
  7667. if (key === 'url' && typeof window !== 'undefined') {
  7668. params[key] = new URL(source[key], window.location).href;
  7669. continue;
  7670. } else if (key === 'range') {
  7671. rangeTransport = source[key];
  7672. continue;
  7673. } else if (key === 'worker') {
  7674. worker = source[key];
  7675. continue;
  7676. } else if (key === 'data' && !(source[key] instanceof Uint8Array)) {
  7677. var pdfBytes = source[key];
  7678. if (typeof pdfBytes === 'string') {
  7679. params[key] = stringToBytes(pdfBytes);
  7680. } else if (typeof pdfBytes === 'object' && pdfBytes !== null && !isNaN(pdfBytes.length)) {
  7681. params[key] = new Uint8Array(pdfBytes);
  7682. } else if (isArrayBuffer(pdfBytes)) {
  7683. params[key] = new Uint8Array(pdfBytes);
  7684. } else {
  7685. error('Invalid PDF binary data: either typed array, string or ' + 'array-like object is expected in the data property.');
  7686. }
  7687. continue;
  7688. }
  7689. params[key] = source[key];
  7690. }
  7691. params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
  7692. if (!worker) {
  7693. worker = new PDFWorker();
  7694. task._worker = worker;
  7695. }
  7696. var docId = task.docId;
  7697. worker.promise.then(function () {
  7698. if (task.destroyed) {
  7699. throw new Error('Loading aborted');
  7700. }
  7701. return _fetchDocument(worker, params, rangeTransport, docId).then(function (workerId) {
  7702. if (task.destroyed) {
  7703. throw new Error('Loading aborted');
  7704. }
  7705. var messageHandler = new MessageHandler(docId, workerId, worker.port);
  7706. var transport = new WorkerTransport(messageHandler, task, rangeTransport);
  7707. task._transport = transport;
  7708. messageHandler.send('Ready', null);
  7709. });
  7710. }).catch(task._capability.reject);
  7711. return task;
  7712. }
  7713. function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
  7714. if (worker.destroyed) {
  7715. return Promise.reject(new Error('Worker was destroyed'));
  7716. }
  7717. source.disableAutoFetch = getDefaultSetting('disableAutoFetch');
  7718. source.disableStream = getDefaultSetting('disableStream');
  7719. source.chunkedViewerLoading = !!pdfDataRangeTransport;
  7720. if (pdfDataRangeTransport) {
  7721. source.length = pdfDataRangeTransport.length;
  7722. source.initialData = pdfDataRangeTransport.initialData;
  7723. }
  7724. return worker.messageHandler.sendWithPromise('GetDocRequest', {
  7725. docId: docId,
  7726. source: source,
  7727. disableRange: getDefaultSetting('disableRange'),
  7728. maxImageSize: getDefaultSetting('maxImageSize'),
  7729. cMapUrl: getDefaultSetting('cMapUrl'),
  7730. cMapPacked: getDefaultSetting('cMapPacked'),
  7731. disableFontFace: getDefaultSetting('disableFontFace'),
  7732. disableCreateObjectURL: getDefaultSetting('disableCreateObjectURL'),
  7733. postMessageTransfers: getDefaultSetting('postMessageTransfers') && !isPostMessageTransfersDisabled,
  7734. docBaseUrl: source.docBaseUrl
  7735. }).then(function (workerId) {
  7736. if (worker.destroyed) {
  7737. throw new Error('Worker was destroyed');
  7738. }
  7739. return workerId;
  7740. });
  7741. }
  7742. var PDFDocumentLoadingTask = function PDFDocumentLoadingTaskClosure() {
  7743. var nextDocumentId = 0;
  7744. function PDFDocumentLoadingTask() {
  7745. this._capability = createPromiseCapability();
  7746. this._transport = null;
  7747. this._worker = null;
  7748. this.docId = 'd' + nextDocumentId++;
  7749. this.destroyed = false;
  7750. this.onPassword = null;
  7751. this.onProgress = null;
  7752. this.onUnsupportedFeature = null;
  7753. }
  7754. PDFDocumentLoadingTask.prototype = {
  7755. get promise() {
  7756. return this._capability.promise;
  7757. },
  7758. destroy: function () {
  7759. this.destroyed = true;
  7760. var transportDestroyed = !this._transport ? Promise.resolve() : this._transport.destroy();
  7761. return transportDestroyed.then(function () {
  7762. this._transport = null;
  7763. if (this._worker) {
  7764. this._worker.destroy();
  7765. this._worker = null;
  7766. }
  7767. }.bind(this));
  7768. },
  7769. then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) {
  7770. return this.promise.then.apply(this.promise, arguments);
  7771. }
  7772. };
  7773. return PDFDocumentLoadingTask;
  7774. }();
  7775. var PDFDataRangeTransport = function pdfDataRangeTransportClosure() {
  7776. function PDFDataRangeTransport(length, initialData) {
  7777. this.length = length;
  7778. this.initialData = initialData;
  7779. this._rangeListeners = [];
  7780. this._progressListeners = [];
  7781. this._progressiveReadListeners = [];
  7782. this._readyCapability = createPromiseCapability();
  7783. }
  7784. PDFDataRangeTransport.prototype = {
  7785. addRangeListener: function PDFDataRangeTransport_addRangeListener(listener) {
  7786. this._rangeListeners.push(listener);
  7787. },
  7788. addProgressListener: function PDFDataRangeTransport_addProgressListener(listener) {
  7789. this._progressListeners.push(listener);
  7790. },
  7791. addProgressiveReadListener: function PDFDataRangeTransport_addProgressiveReadListener(listener) {
  7792. this._progressiveReadListeners.push(listener);
  7793. },
  7794. onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {
  7795. var listeners = this._rangeListeners;
  7796. for (var i = 0, n = listeners.length; i < n; ++i) {
  7797. listeners[i](begin, chunk);
  7798. }
  7799. },
  7800. onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {
  7801. this._readyCapability.promise.then(function () {
  7802. var listeners = this._progressListeners;
  7803. for (var i = 0, n = listeners.length; i < n; ++i) {
  7804. listeners[i](loaded);
  7805. }
  7806. }.bind(this));
  7807. },
  7808. onDataProgressiveRead: function PDFDataRangeTransport_onDataProgress(chunk) {
  7809. this._readyCapability.promise.then(function () {
  7810. var listeners = this._progressiveReadListeners;
  7811. for (var i = 0, n = listeners.length; i < n; ++i) {
  7812. listeners[i](chunk);
  7813. }
  7814. }.bind(this));
  7815. },
  7816. transportReady: function PDFDataRangeTransport_transportReady() {
  7817. this._readyCapability.resolve();
  7818. },
  7819. requestDataRange: function PDFDataRangeTransport_requestDataRange(begin, end) {
  7820. throw new Error('Abstract method PDFDataRangeTransport.requestDataRange');
  7821. },
  7822. abort: function PDFDataRangeTransport_abort() {
  7823. }
  7824. };
  7825. return PDFDataRangeTransport;
  7826. }();
  7827. var PDFDocumentProxy = function PDFDocumentProxyClosure() {
  7828. function PDFDocumentProxy(pdfInfo, transport, loadingTask) {
  7829. this.pdfInfo = pdfInfo;
  7830. this.transport = transport;
  7831. this.loadingTask = loadingTask;
  7832. }
  7833. PDFDocumentProxy.prototype = {
  7834. get numPages() {
  7835. return this.pdfInfo.numPages;
  7836. },
  7837. get fingerprint() {
  7838. return this.pdfInfo.fingerprint;
  7839. },
  7840. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  7841. return this.transport.getPage(pageNumber);
  7842. },
  7843. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  7844. return this.transport.getPageIndex(ref);
  7845. },
  7846. getDestinations: function PDFDocumentProxy_getDestinations() {
  7847. return this.transport.getDestinations();
  7848. },
  7849. getDestination: function PDFDocumentProxy_getDestination(id) {
  7850. return this.transport.getDestination(id);
  7851. },
  7852. getPageLabels: function PDFDocumentProxy_getPageLabels() {
  7853. return this.transport.getPageLabels();
  7854. },
  7855. getAttachments: function PDFDocumentProxy_getAttachments() {
  7856. return this.transport.getAttachments();
  7857. },
  7858. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  7859. return this.transport.getJavaScript();
  7860. },
  7861. getOutline: function PDFDocumentProxy_getOutline() {
  7862. return this.transport.getOutline();
  7863. },
  7864. getMetadata: function PDFDocumentProxy_getMetadata() {
  7865. return this.transport.getMetadata();
  7866. },
  7867. getData: function PDFDocumentProxy_getData() {
  7868. return this.transport.getData();
  7869. },
  7870. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  7871. return this.transport.downloadInfoCapability.promise;
  7872. },
  7873. getStats: function PDFDocumentProxy_getStats() {
  7874. return this.transport.getStats();
  7875. },
  7876. cleanup: function PDFDocumentProxy_cleanup() {
  7877. this.transport.startCleanup();
  7878. },
  7879. destroy: function PDFDocumentProxy_destroy() {
  7880. return this.loadingTask.destroy();
  7881. }
  7882. };
  7883. return PDFDocumentProxy;
  7884. }();
  7885. var PDFPageProxy = function PDFPageProxyClosure() {
  7886. function PDFPageProxy(pageIndex, pageInfo, transport) {
  7887. this.pageIndex = pageIndex;
  7888. this.pageInfo = pageInfo;
  7889. this.transport = transport;
  7890. this.stats = new StatTimer();
  7891. this.stats.enabled = getDefaultSetting('enableStats');
  7892. this.commonObjs = transport.commonObjs;
  7893. this.objs = new PDFObjects();
  7894. this.cleanupAfterRender = false;
  7895. this.pendingCleanup = false;
  7896. this.intentStates = Object.create(null);
  7897. this.destroyed = false;
  7898. }
  7899. PDFPageProxy.prototype = {
  7900. get pageNumber() {
  7901. return this.pageIndex + 1;
  7902. },
  7903. get rotate() {
  7904. return this.pageInfo.rotate;
  7905. },
  7906. get ref() {
  7907. return this.pageInfo.ref;
  7908. },
  7909. get userUnit() {
  7910. return this.pageInfo.userUnit;
  7911. },
  7912. get view() {
  7913. return this.pageInfo.view;
  7914. },
  7915. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  7916. if (arguments.length < 2) {
  7917. rotate = this.rotate;
  7918. }
  7919. return new PageViewport(this.view, scale, rotate, 0, 0);
  7920. },
  7921. getAnnotations: function PDFPageProxy_getAnnotations(params) {
  7922. var intent = params && params.intent || null;
  7923. if (!this.annotationsPromise || this.annotationsIntent !== intent) {
  7924. this.annotationsPromise = this.transport.getAnnotations(this.pageIndex, intent);
  7925. this.annotationsIntent = intent;
  7926. }
  7927. return this.annotationsPromise;
  7928. },
  7929. render: function PDFPageProxy_render(params) {
  7930. var stats = this.stats;
  7931. stats.time('Overall');
  7932. this.pendingCleanup = false;
  7933. var renderingIntent = params.intent === 'print' ? 'print' : 'display';
  7934. var renderInteractiveForms = params.renderInteractiveForms === true ? true : false;
  7935. if (!this.intentStates[renderingIntent]) {
  7936. this.intentStates[renderingIntent] = Object.create(null);
  7937. }
  7938. var intentState = this.intentStates[renderingIntent];
  7939. if (!intentState.displayReadyCapability) {
  7940. intentState.receivingOperatorList = true;
  7941. intentState.displayReadyCapability = createPromiseCapability();
  7942. intentState.operatorList = {
  7943. fnArray: [],
  7944. argsArray: [],
  7945. lastChunk: false
  7946. };
  7947. this.stats.time('Page Request');
  7948. this.transport.messageHandler.send('RenderPageRequest', {
  7949. pageIndex: this.pageNumber - 1,
  7950. intent: renderingIntent,
  7951. renderInteractiveForms: renderInteractiveForms
  7952. });
  7953. }
  7954. var internalRenderTask = new InternalRenderTask(complete, params, this.objs, this.commonObjs, intentState.operatorList, this.pageNumber);
  7955. internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print';
  7956. if (!intentState.renderTasks) {
  7957. intentState.renderTasks = [];
  7958. }
  7959. intentState.renderTasks.push(internalRenderTask);
  7960. var renderTask = internalRenderTask.task;
  7961. if (params.continueCallback) {
  7962. deprecated('render is used with continueCallback parameter');
  7963. renderTask.onContinue = params.continueCallback;
  7964. }
  7965. var self = this;
  7966. intentState.displayReadyCapability.promise.then(function pageDisplayReadyPromise(transparency) {
  7967. if (self.pendingCleanup) {
  7968. complete();
  7969. return;
  7970. }
  7971. stats.time('Rendering');
  7972. internalRenderTask.initializeGraphics(transparency);
  7973. internalRenderTask.operatorListChanged();
  7974. }, function pageDisplayReadPromiseError(reason) {
  7975. complete(reason);
  7976. });
  7977. function complete(error) {
  7978. var i = intentState.renderTasks.indexOf(internalRenderTask);
  7979. if (i >= 0) {
  7980. intentState.renderTasks.splice(i, 1);
  7981. }
  7982. if (self.cleanupAfterRender) {
  7983. self.pendingCleanup = true;
  7984. }
  7985. self._tryCleanup();
  7986. if (error) {
  7987. internalRenderTask.capability.reject(error);
  7988. } else {
  7989. internalRenderTask.capability.resolve();
  7990. }
  7991. stats.timeEnd('Rendering');
  7992. stats.timeEnd('Overall');
  7993. }
  7994. return renderTask;
  7995. },
  7996. getOperatorList: function PDFPageProxy_getOperatorList() {
  7997. function operatorListChanged() {
  7998. if (intentState.operatorList.lastChunk) {
  7999. intentState.opListReadCapability.resolve(intentState.operatorList);
  8000. var i = intentState.renderTasks.indexOf(opListTask);
  8001. if (i >= 0) {
  8002. intentState.renderTasks.splice(i, 1);
  8003. }
  8004. }
  8005. }
  8006. var renderingIntent = 'oplist';
  8007. if (!this.intentStates[renderingIntent]) {
  8008. this.intentStates[renderingIntent] = Object.create(null);
  8009. }
  8010. var intentState = this.intentStates[renderingIntent];
  8011. var opListTask;
  8012. if (!intentState.opListReadCapability) {
  8013. opListTask = {};
  8014. opListTask.operatorListChanged = operatorListChanged;
  8015. intentState.receivingOperatorList = true;
  8016. intentState.opListReadCapability = createPromiseCapability();
  8017. intentState.renderTasks = [];
  8018. intentState.renderTasks.push(opListTask);
  8019. intentState.operatorList = {
  8020. fnArray: [],
  8021. argsArray: [],
  8022. lastChunk: false
  8023. };
  8024. this.transport.messageHandler.send('RenderPageRequest', {
  8025. pageIndex: this.pageIndex,
  8026. intent: renderingIntent
  8027. });
  8028. }
  8029. return intentState.opListReadCapability.promise;
  8030. },
  8031. getTextContent: function PDFPageProxy_getTextContent(params) {
  8032. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  8033. pageIndex: this.pageNumber - 1,
  8034. normalizeWhitespace: params && params.normalizeWhitespace === true ? true : false,
  8035. combineTextItems: params && params.disableCombineTextItems === true ? false : true
  8036. });
  8037. },
  8038. _destroy: function PDFPageProxy_destroy() {
  8039. this.destroyed = true;
  8040. this.transport.pageCache[this.pageIndex] = null;
  8041. var waitOn = [];
  8042. Object.keys(this.intentStates).forEach(function (intent) {
  8043. if (intent === 'oplist') {
  8044. return;
  8045. }
  8046. var intentState = this.intentStates[intent];
  8047. intentState.renderTasks.forEach(function (renderTask) {
  8048. var renderCompleted = renderTask.capability.promise.catch(function () {
  8049. });
  8050. waitOn.push(renderCompleted);
  8051. renderTask.cancel();
  8052. });
  8053. }, this);
  8054. this.objs.clear();
  8055. this.annotationsPromise = null;
  8056. this.pendingCleanup = false;
  8057. return Promise.all(waitOn);
  8058. },
  8059. destroy: function () {
  8060. deprecated('page destroy method, use cleanup() instead');
  8061. this.cleanup();
  8062. },
  8063. cleanup: function PDFPageProxy_cleanup() {
  8064. this.pendingCleanup = true;
  8065. this._tryCleanup();
  8066. },
  8067. _tryCleanup: function PDFPageProxy_tryCleanup() {
  8068. if (!this.pendingCleanup || Object.keys(this.intentStates).some(function (intent) {
  8069. var intentState = this.intentStates[intent];
  8070. return intentState.renderTasks.length !== 0 || intentState.receivingOperatorList;
  8071. }, this)) {
  8072. return;
  8073. }
  8074. Object.keys(this.intentStates).forEach(function (intent) {
  8075. delete this.intentStates[intent];
  8076. }, this);
  8077. this.objs.clear();
  8078. this.annotationsPromise = null;
  8079. this.pendingCleanup = false;
  8080. },
  8081. _startRenderPage: function PDFPageProxy_startRenderPage(transparency, intent) {
  8082. var intentState = this.intentStates[intent];
  8083. if (intentState.displayReadyCapability) {
  8084. intentState.displayReadyCapability.resolve(transparency);
  8085. }
  8086. },
  8087. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk, intent) {
  8088. var intentState = this.intentStates[intent];
  8089. var i, ii;
  8090. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  8091. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  8092. intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
  8093. }
  8094. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  8095. for (i = 0; i < intentState.renderTasks.length; i++) {
  8096. intentState.renderTasks[i].operatorListChanged();
  8097. }
  8098. if (operatorListChunk.lastChunk) {
  8099. intentState.receivingOperatorList = false;
  8100. this._tryCleanup();
  8101. }
  8102. }
  8103. };
  8104. return PDFPageProxy;
  8105. }();
  8106. var PDFWorker = function PDFWorkerClosure() {
  8107. var nextFakeWorkerId = 0;
  8108. function getWorkerSrc() {
  8109. if (typeof workerSrc !== 'undefined') {
  8110. return workerSrc;
  8111. }
  8112. if (getDefaultSetting('workerSrc')) {
  8113. return getDefaultSetting('workerSrc');
  8114. }
  8115. if (pdfjsFilePath) {
  8116. return pdfjsFilePath.replace(/\.js$/i, '.worker.js');
  8117. }
  8118. error('No PDFJS.workerSrc specified');
  8119. }
  8120. var fakeWorkerFilesLoadedCapability;
  8121. function setupFakeWorkerGlobal() {
  8122. var WorkerMessageHandler;
  8123. if (fakeWorkerFilesLoadedCapability) {
  8124. return fakeWorkerFilesLoadedCapability.promise;
  8125. }
  8126. fakeWorkerFilesLoadedCapability = createPromiseCapability();
  8127. var loader = fakeWorkerFilesLoader || function (callback) {
  8128. Util.loadScript(getWorkerSrc(), function () {
  8129. callback(window.pdfjsDistBuildPdfWorker.WorkerMessageHandler);
  8130. });
  8131. };
  8132. loader(fakeWorkerFilesLoadedCapability.resolve);
  8133. return fakeWorkerFilesLoadedCapability.promise;
  8134. }
  8135. function FakeWorkerPort(defer) {
  8136. this._listeners = [];
  8137. this._defer = defer;
  8138. this._deferred = Promise.resolve(undefined);
  8139. }
  8140. FakeWorkerPort.prototype = {
  8141. postMessage: function (obj, transfers) {
  8142. function cloneValue(value) {
  8143. if (typeof value !== 'object' || value === null) {
  8144. return value;
  8145. }
  8146. if (cloned.has(value)) {
  8147. return cloned.get(value);
  8148. }
  8149. var result;
  8150. var buffer;
  8151. if ((buffer = value.buffer) && isArrayBuffer(buffer)) {
  8152. var transferable = transfers && transfers.indexOf(buffer) >= 0;
  8153. if (value === buffer) {
  8154. result = value;
  8155. } else if (transferable) {
  8156. result = new value.constructor(buffer, value.byteOffset, value.byteLength);
  8157. } else {
  8158. result = new value.constructor(value);
  8159. }
  8160. cloned.set(value, result);
  8161. return result;
  8162. }
  8163. result = isArray(value) ? [] : {};
  8164. cloned.set(value, result);
  8165. for (var i in value) {
  8166. var desc, p = value;
  8167. while (!(desc = Object.getOwnPropertyDescriptor(p, i))) {
  8168. p = Object.getPrototypeOf(p);
  8169. }
  8170. if (typeof desc.value === 'undefined' || typeof desc.value === 'function') {
  8171. continue;
  8172. }
  8173. result[i] = cloneValue(desc.value);
  8174. }
  8175. return result;
  8176. }
  8177. if (!this._defer) {
  8178. this._listeners.forEach(function (listener) {
  8179. listener.call(this, { data: obj });
  8180. }, this);
  8181. return;
  8182. }
  8183. var cloned = new WeakMap();
  8184. var e = { data: cloneValue(obj) };
  8185. this._deferred.then(function () {
  8186. this._listeners.forEach(function (listener) {
  8187. listener.call(this, e);
  8188. }, this);
  8189. }.bind(this));
  8190. },
  8191. addEventListener: function (name, listener) {
  8192. this._listeners.push(listener);
  8193. },
  8194. removeEventListener: function (name, listener) {
  8195. var i = this._listeners.indexOf(listener);
  8196. this._listeners.splice(i, 1);
  8197. },
  8198. terminate: function () {
  8199. this._listeners = [];
  8200. }
  8201. };
  8202. function createCDNWrapper(url) {
  8203. var wrapper = 'importScripts(\'' + url + '\');';
  8204. return URL.createObjectURL(new Blob([wrapper]));
  8205. }
  8206. function PDFWorker(name) {
  8207. this.name = name;
  8208. this.destroyed = false;
  8209. this._readyCapability = createPromiseCapability();
  8210. this._port = null;
  8211. this._webWorker = null;
  8212. this._messageHandler = null;
  8213. this._initialize();
  8214. }
  8215. PDFWorker.prototype = {
  8216. get promise() {
  8217. return this._readyCapability.promise;
  8218. },
  8219. get port() {
  8220. return this._port;
  8221. },
  8222. get messageHandler() {
  8223. return this._messageHandler;
  8224. },
  8225. _initialize: function PDFWorker_initialize() {
  8226. if (!isWorkerDisabled && !getDefaultSetting('disableWorker') && typeof Worker !== 'undefined') {
  8227. var workerSrc = getWorkerSrc();
  8228. try {
  8229. if (!isSameOrigin(window.location.href, workerSrc)) {
  8230. workerSrc = createCDNWrapper(new URL(workerSrc, window.location).href);
  8231. }
  8232. var worker = new Worker(workerSrc);
  8233. var messageHandler = new MessageHandler('main', 'worker', worker);
  8234. var terminateEarly = function () {
  8235. worker.removeEventListener('error', onWorkerError);
  8236. messageHandler.destroy();
  8237. worker.terminate();
  8238. if (this.destroyed) {
  8239. this._readyCapability.reject(new Error('Worker was destroyed'));
  8240. } else {
  8241. this._setupFakeWorker();
  8242. }
  8243. }.bind(this);
  8244. var onWorkerError = function (event) {
  8245. if (!this._webWorker) {
  8246. terminateEarly();
  8247. }
  8248. }.bind(this);
  8249. worker.addEventListener('error', onWorkerError);
  8250. messageHandler.on('test', function PDFWorker_test(data) {
  8251. worker.removeEventListener('error', onWorkerError);
  8252. if (this.destroyed) {
  8253. terminateEarly();
  8254. return;
  8255. }
  8256. var supportTypedArray = data && data.supportTypedArray;
  8257. if (supportTypedArray) {
  8258. this._messageHandler = messageHandler;
  8259. this._port = worker;
  8260. this._webWorker = worker;
  8261. if (!data.supportTransfers) {
  8262. isPostMessageTransfersDisabled = true;
  8263. }
  8264. this._readyCapability.resolve();
  8265. messageHandler.send('configure', { verbosity: getVerbosityLevel() });
  8266. } else {
  8267. this._setupFakeWorker();
  8268. messageHandler.destroy();
  8269. worker.terminate();
  8270. }
  8271. }.bind(this));
  8272. messageHandler.on('console_log', function (data) {
  8273. console.log.apply(console, data);
  8274. });
  8275. messageHandler.on('console_error', function (data) {
  8276. console.error.apply(console, data);
  8277. });
  8278. messageHandler.on('ready', function (data) {
  8279. worker.removeEventListener('error', onWorkerError);
  8280. if (this.destroyed) {
  8281. terminateEarly();
  8282. return;
  8283. }
  8284. try {
  8285. sendTest();
  8286. } catch (e) {
  8287. this._setupFakeWorker();
  8288. }
  8289. }.bind(this));
  8290. var sendTest = function () {
  8291. var postMessageTransfers = getDefaultSetting('postMessageTransfers') && !isPostMessageTransfersDisabled;
  8292. var testObj = new Uint8Array([postMessageTransfers ? 255 : 0]);
  8293. try {
  8294. messageHandler.send('test', testObj, [testObj.buffer]);
  8295. } catch (ex) {
  8296. info('Cannot use postMessage transfers');
  8297. testObj[0] = 0;
  8298. messageHandler.send('test', testObj);
  8299. }
  8300. };
  8301. sendTest();
  8302. return;
  8303. } catch (e) {
  8304. info('The worker has been disabled.');
  8305. }
  8306. }
  8307. this._setupFakeWorker();
  8308. },
  8309. _setupFakeWorker: function PDFWorker_setupFakeWorker() {
  8310. if (!isWorkerDisabled && !getDefaultSetting('disableWorker')) {
  8311. warn('Setting up fake worker.');
  8312. isWorkerDisabled = true;
  8313. }
  8314. setupFakeWorkerGlobal().then(function (WorkerMessageHandler) {
  8315. if (this.destroyed) {
  8316. this._readyCapability.reject(new Error('Worker was destroyed'));
  8317. return;
  8318. }
  8319. var isTypedArraysPresent = Uint8Array !== Float32Array;
  8320. var port = new FakeWorkerPort(isTypedArraysPresent);
  8321. this._port = port;
  8322. var id = 'fake' + nextFakeWorkerId++;
  8323. var workerHandler = new MessageHandler(id + '_worker', id, port);
  8324. WorkerMessageHandler.setup(workerHandler, port);
  8325. var messageHandler = new MessageHandler(id, id + '_worker', port);
  8326. this._messageHandler = messageHandler;
  8327. this._readyCapability.resolve();
  8328. }.bind(this));
  8329. },
  8330. destroy: function PDFWorker_destroy() {
  8331. this.destroyed = true;
  8332. if (this._webWorker) {
  8333. this._webWorker.terminate();
  8334. this._webWorker = null;
  8335. }
  8336. this._port = null;
  8337. if (this._messageHandler) {
  8338. this._messageHandler.destroy();
  8339. this._messageHandler = null;
  8340. }
  8341. }
  8342. };
  8343. return PDFWorker;
  8344. }();
  8345. var WorkerTransport = function WorkerTransportClosure() {
  8346. function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) {
  8347. this.messageHandler = messageHandler;
  8348. this.loadingTask = loadingTask;
  8349. this.pdfDataRangeTransport = pdfDataRangeTransport;
  8350. this.commonObjs = new PDFObjects();
  8351. this.fontLoader = new FontLoader(loadingTask.docId);
  8352. this.destroyed = false;
  8353. this.destroyCapability = null;
  8354. this._passwordCapability = null;
  8355. this.pageCache = [];
  8356. this.pagePromises = [];
  8357. this.downloadInfoCapability = createPromiseCapability();
  8358. this.setupMessageHandler();
  8359. }
  8360. WorkerTransport.prototype = {
  8361. destroy: function WorkerTransport_destroy() {
  8362. if (this.destroyCapability) {
  8363. return this.destroyCapability.promise;
  8364. }
  8365. this.destroyed = true;
  8366. this.destroyCapability = createPromiseCapability();
  8367. if (this._passwordCapability) {
  8368. this._passwordCapability.reject(new Error('Worker was destroyed during onPassword callback'));
  8369. }
  8370. var waitOn = [];
  8371. this.pageCache.forEach(function (page) {
  8372. if (page) {
  8373. waitOn.push(page._destroy());
  8374. }
  8375. });
  8376. this.pageCache = [];
  8377. this.pagePromises = [];
  8378. var self = this;
  8379. var terminated = this.messageHandler.sendWithPromise('Terminate', null);
  8380. waitOn.push(terminated);
  8381. Promise.all(waitOn).then(function () {
  8382. self.fontLoader.clear();
  8383. if (self.pdfDataRangeTransport) {
  8384. self.pdfDataRangeTransport.abort();
  8385. self.pdfDataRangeTransport = null;
  8386. }
  8387. if (self.messageHandler) {
  8388. self.messageHandler.destroy();
  8389. self.messageHandler = null;
  8390. }
  8391. self.destroyCapability.resolve();
  8392. }, this.destroyCapability.reject);
  8393. return this.destroyCapability.promise;
  8394. },
  8395. setupMessageHandler: function WorkerTransport_setupMessageHandler() {
  8396. var messageHandler = this.messageHandler;
  8397. var loadingTask = this.loadingTask;
  8398. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  8399. if (pdfDataRangeTransport) {
  8400. pdfDataRangeTransport.addRangeListener(function (begin, chunk) {
  8401. messageHandler.send('OnDataRange', {
  8402. begin: begin,
  8403. chunk: chunk
  8404. });
  8405. });
  8406. pdfDataRangeTransport.addProgressListener(function (loaded) {
  8407. messageHandler.send('OnDataProgress', { loaded: loaded });
  8408. });
  8409. pdfDataRangeTransport.addProgressiveReadListener(function (chunk) {
  8410. messageHandler.send('OnDataRange', { chunk: chunk });
  8411. });
  8412. messageHandler.on('RequestDataRange', function transportDataRange(data) {
  8413. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  8414. }, this);
  8415. }
  8416. messageHandler.on('GetDoc', function transportDoc(data) {
  8417. var pdfInfo = data.pdfInfo;
  8418. this.numPages = data.pdfInfo.numPages;
  8419. var loadingTask = this.loadingTask;
  8420. var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask);
  8421. this.pdfDocument = pdfDocument;
  8422. loadingTask._capability.resolve(pdfDocument);
  8423. }, this);
  8424. messageHandler.on('PasswordRequest', function transportPasswordRequest(exception) {
  8425. this._passwordCapability = createPromiseCapability();
  8426. if (loadingTask.onPassword) {
  8427. var updatePassword = function (password) {
  8428. this._passwordCapability.resolve({ password: password });
  8429. }.bind(this);
  8430. loadingTask.onPassword(updatePassword, exception.code);
  8431. } else {
  8432. this._passwordCapability.reject(new PasswordException(exception.message, exception.code));
  8433. }
  8434. return this._passwordCapability.promise;
  8435. }, this);
  8436. messageHandler.on('PasswordException', function transportPasswordException(exception) {
  8437. loadingTask._capability.reject(new PasswordException(exception.message, exception.code));
  8438. }, this);
  8439. messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
  8440. this.loadingTask._capability.reject(new InvalidPDFException(exception.message));
  8441. }, this);
  8442. messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
  8443. this.loadingTask._capability.reject(new MissingPDFException(exception.message));
  8444. }, this);
  8445. messageHandler.on('UnexpectedResponse', function transportUnexpectedResponse(exception) {
  8446. this.loadingTask._capability.reject(new UnexpectedResponseException(exception.message, exception.status));
  8447. }, this);
  8448. messageHandler.on('UnknownError', function transportUnknownError(exception) {
  8449. this.loadingTask._capability.reject(new UnknownErrorException(exception.message, exception.details));
  8450. }, this);
  8451. messageHandler.on('DataLoaded', function transportPage(data) {
  8452. this.downloadInfoCapability.resolve(data);
  8453. }, this);
  8454. messageHandler.on('PDFManagerReady', function transportPage(data) {
  8455. if (this.pdfDataRangeTransport) {
  8456. this.pdfDataRangeTransport.transportReady();
  8457. }
  8458. }, this);
  8459. messageHandler.on('StartRenderPage', function transportRender(data) {
  8460. if (this.destroyed) {
  8461. return;
  8462. }
  8463. var page = this.pageCache[data.pageIndex];
  8464. page.stats.timeEnd('Page Request');
  8465. page._startRenderPage(data.transparency, data.intent);
  8466. }, this);
  8467. messageHandler.on('RenderPageChunk', function transportRender(data) {
  8468. if (this.destroyed) {
  8469. return;
  8470. }
  8471. var page = this.pageCache[data.pageIndex];
  8472. page._renderPageChunk(data.operatorList, data.intent);
  8473. }, this);
  8474. messageHandler.on('commonobj', function transportObj(data) {
  8475. if (this.destroyed) {
  8476. return;
  8477. }
  8478. var id = data[0];
  8479. var type = data[1];
  8480. if (this.commonObjs.hasData(id)) {
  8481. return;
  8482. }
  8483. switch (type) {
  8484. case 'Font':
  8485. var exportedData = data[2];
  8486. if ('error' in exportedData) {
  8487. var exportedError = exportedData.error;
  8488. warn('Error during font loading: ' + exportedError);
  8489. this.commonObjs.resolve(id, exportedError);
  8490. break;
  8491. }
  8492. var fontRegistry = null;
  8493. if (getDefaultSetting('pdfBug') && globalScope.FontInspector && globalScope['FontInspector'].enabled) {
  8494. fontRegistry = {
  8495. registerFont: function (font, url) {
  8496. globalScope['FontInspector'].fontAdded(font, url);
  8497. }
  8498. };
  8499. }
  8500. var font = new FontFaceObject(exportedData, {
  8501. isEvalSuported: getDefaultSetting('isEvalSupported'),
  8502. disableFontFace: getDefaultSetting('disableFontFace'),
  8503. fontRegistry: fontRegistry
  8504. });
  8505. this.fontLoader.bind([font], function fontReady(fontObjs) {
  8506. this.commonObjs.resolve(id, font);
  8507. }.bind(this));
  8508. break;
  8509. case 'FontPath':
  8510. this.commonObjs.resolve(id, data[2]);
  8511. break;
  8512. default:
  8513. error('Got unknown common object type ' + type);
  8514. }
  8515. }, this);
  8516. messageHandler.on('obj', function transportObj(data) {
  8517. if (this.destroyed) {
  8518. return;
  8519. }
  8520. var id = data[0];
  8521. var pageIndex = data[1];
  8522. var type = data[2];
  8523. var pageProxy = this.pageCache[pageIndex];
  8524. var imageData;
  8525. if (pageProxy.objs.hasData(id)) {
  8526. return;
  8527. }
  8528. switch (type) {
  8529. case 'JpegStream':
  8530. imageData = data[3];
  8531. loadJpegStream(id, imageData, pageProxy.objs);
  8532. break;
  8533. case 'Image':
  8534. imageData = data[3];
  8535. pageProxy.objs.resolve(id, imageData);
  8536. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  8537. if (imageData && 'data' in imageData && imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  8538. pageProxy.cleanupAfterRender = true;
  8539. }
  8540. break;
  8541. default:
  8542. error('Got unknown object type ' + type);
  8543. }
  8544. }, this);
  8545. messageHandler.on('DocProgress', function transportDocProgress(data) {
  8546. if (this.destroyed) {
  8547. return;
  8548. }
  8549. var loadingTask = this.loadingTask;
  8550. if (loadingTask.onProgress) {
  8551. loadingTask.onProgress({
  8552. loaded: data.loaded,
  8553. total: data.total
  8554. });
  8555. }
  8556. }, this);
  8557. messageHandler.on('PageError', function transportError(data) {
  8558. if (this.destroyed) {
  8559. return;
  8560. }
  8561. var page = this.pageCache[data.pageNum - 1];
  8562. var intentState = page.intentStates[data.intent];
  8563. if (intentState.displayReadyCapability) {
  8564. intentState.displayReadyCapability.reject(data.error);
  8565. } else {
  8566. error(data.error);
  8567. }
  8568. if (intentState.operatorList) {
  8569. intentState.operatorList.lastChunk = true;
  8570. for (var i = 0; i < intentState.renderTasks.length; i++) {
  8571. intentState.renderTasks[i].operatorListChanged();
  8572. }
  8573. }
  8574. }, this);
  8575. messageHandler.on('UnsupportedFeature', function transportUnsupportedFeature(data) {
  8576. if (this.destroyed) {
  8577. return;
  8578. }
  8579. var featureId = data.featureId;
  8580. var loadingTask = this.loadingTask;
  8581. if (loadingTask.onUnsupportedFeature) {
  8582. loadingTask.onUnsupportedFeature(featureId);
  8583. }
  8584. _UnsupportedManager.notify(featureId);
  8585. }, this);
  8586. messageHandler.on('JpegDecode', function (data) {
  8587. if (this.destroyed) {
  8588. return Promise.reject(new Error('Worker was destroyed'));
  8589. }
  8590. var imageUrl = data[0];
  8591. var components = data[1];
  8592. if (components !== 3 && components !== 1) {
  8593. return Promise.reject(new Error('Only 3 components or 1 component can be returned'));
  8594. }
  8595. return new Promise(function (resolve, reject) {
  8596. var img = new Image();
  8597. img.onload = function () {
  8598. var width = img.width;
  8599. var height = img.height;
  8600. var size = width * height;
  8601. var rgbaLength = size * 4;
  8602. var buf = new Uint8Array(size * components);
  8603. var tmpCanvas = createScratchCanvas(width, height);
  8604. var tmpCtx = tmpCanvas.getContext('2d');
  8605. tmpCtx.drawImage(img, 0, 0);
  8606. var data = tmpCtx.getImageData(0, 0, width, height).data;
  8607. var i, j;
  8608. if (components === 3) {
  8609. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  8610. buf[j] = data[i];
  8611. buf[j + 1] = data[i + 1];
  8612. buf[j + 2] = data[i + 2];
  8613. }
  8614. } else if (components === 1) {
  8615. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  8616. buf[j] = data[i];
  8617. }
  8618. }
  8619. resolve({
  8620. data: buf,
  8621. width: width,
  8622. height: height
  8623. });
  8624. };
  8625. img.onerror = function () {
  8626. reject(new Error('JpegDecode failed to load image'));
  8627. };
  8628. img.src = imageUrl;
  8629. });
  8630. }, this);
  8631. },
  8632. getData: function WorkerTransport_getData() {
  8633. return this.messageHandler.sendWithPromise('GetData', null);
  8634. },
  8635. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  8636. if (!isInt(pageNumber) || pageNumber <= 0 || pageNumber > this.numPages) {
  8637. return Promise.reject(new Error('Invalid page request'));
  8638. }
  8639. var pageIndex = pageNumber - 1;
  8640. if (pageIndex in this.pagePromises) {
  8641. return this.pagePromises[pageIndex];
  8642. }
  8643. var promise = this.messageHandler.sendWithPromise('GetPage', { pageIndex: pageIndex }).then(function (pageInfo) {
  8644. if (this.destroyed) {
  8645. throw new Error('Transport destroyed');
  8646. }
  8647. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  8648. this.pageCache[pageIndex] = page;
  8649. return page;
  8650. }.bind(this));
  8651. this.pagePromises[pageIndex] = promise;
  8652. return promise;
  8653. },
  8654. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  8655. return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref }).catch(function (reason) {
  8656. return Promise.reject(new Error(reason));
  8657. });
  8658. },
  8659. getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) {
  8660. return this.messageHandler.sendWithPromise('GetAnnotations', {
  8661. pageIndex: pageIndex,
  8662. intent: intent
  8663. });
  8664. },
  8665. getDestinations: function WorkerTransport_getDestinations() {
  8666. return this.messageHandler.sendWithPromise('GetDestinations', null);
  8667. },
  8668. getDestination: function WorkerTransport_getDestination(id) {
  8669. return this.messageHandler.sendWithPromise('GetDestination', { id: id });
  8670. },
  8671. getPageLabels: function WorkerTransport_getPageLabels() {
  8672. return this.messageHandler.sendWithPromise('GetPageLabels', null);
  8673. },
  8674. getAttachments: function WorkerTransport_getAttachments() {
  8675. return this.messageHandler.sendWithPromise('GetAttachments', null);
  8676. },
  8677. getJavaScript: function WorkerTransport_getJavaScript() {
  8678. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  8679. },
  8680. getOutline: function WorkerTransport_getOutline() {
  8681. return this.messageHandler.sendWithPromise('GetOutline', null);
  8682. },
  8683. getMetadata: function WorkerTransport_getMetadata() {
  8684. return this.messageHandler.sendWithPromise('GetMetadata', null).then(function transportMetadata(results) {
  8685. return {
  8686. info: results[0],
  8687. metadata: results[1] ? new Metadata(results[1]) : null
  8688. };
  8689. });
  8690. },
  8691. getStats: function WorkerTransport_getStats() {
  8692. return this.messageHandler.sendWithPromise('GetStats', null);
  8693. },
  8694. startCleanup: function WorkerTransport_startCleanup() {
  8695. this.messageHandler.sendWithPromise('Cleanup', null).then(function endCleanup() {
  8696. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  8697. var page = this.pageCache[i];
  8698. if (page) {
  8699. page.cleanup();
  8700. }
  8701. }
  8702. this.commonObjs.clear();
  8703. this.fontLoader.clear();
  8704. }.bind(this));
  8705. }
  8706. };
  8707. return WorkerTransport;
  8708. }();
  8709. var PDFObjects = function PDFObjectsClosure() {
  8710. function PDFObjects() {
  8711. this.objs = Object.create(null);
  8712. }
  8713. PDFObjects.prototype = {
  8714. ensureObj: function PDFObjects_ensureObj(objId) {
  8715. if (this.objs[objId]) {
  8716. return this.objs[objId];
  8717. }
  8718. var obj = {
  8719. capability: createPromiseCapability(),
  8720. data: null,
  8721. resolved: false
  8722. };
  8723. this.objs[objId] = obj;
  8724. return obj;
  8725. },
  8726. get: function PDFObjects_get(objId, callback) {
  8727. if (callback) {
  8728. this.ensureObj(objId).capability.promise.then(callback);
  8729. return null;
  8730. }
  8731. var obj = this.objs[objId];
  8732. if (!obj || !obj.resolved) {
  8733. error('Requesting object that isn\'t resolved yet ' + objId);
  8734. }
  8735. return obj.data;
  8736. },
  8737. resolve: function PDFObjects_resolve(objId, data) {
  8738. var obj = this.ensureObj(objId);
  8739. obj.resolved = true;
  8740. obj.data = data;
  8741. obj.capability.resolve(data);
  8742. },
  8743. isResolved: function PDFObjects_isResolved(objId) {
  8744. var objs = this.objs;
  8745. if (!objs[objId]) {
  8746. return false;
  8747. }
  8748. return objs[objId].resolved;
  8749. },
  8750. hasData: function PDFObjects_hasData(objId) {
  8751. return this.isResolved(objId);
  8752. },
  8753. getData: function PDFObjects_getData(objId) {
  8754. var objs = this.objs;
  8755. if (!objs[objId] || !objs[objId].resolved) {
  8756. return null;
  8757. }
  8758. return objs[objId].data;
  8759. },
  8760. clear: function PDFObjects_clear() {
  8761. this.objs = Object.create(null);
  8762. }
  8763. };
  8764. return PDFObjects;
  8765. }();
  8766. var RenderTask = function RenderTaskClosure() {
  8767. function RenderTask(internalRenderTask) {
  8768. this._internalRenderTask = internalRenderTask;
  8769. this.onContinue = null;
  8770. }
  8771. RenderTask.prototype = {
  8772. get promise() {
  8773. return this._internalRenderTask.capability.promise;
  8774. },
  8775. cancel: function RenderTask_cancel() {
  8776. this._internalRenderTask.cancel();
  8777. },
  8778. then: function RenderTask_then(onFulfilled, onRejected) {
  8779. return this.promise.then.apply(this.promise, arguments);
  8780. }
  8781. };
  8782. return RenderTask;
  8783. }();
  8784. var InternalRenderTask = function InternalRenderTaskClosure() {
  8785. function InternalRenderTask(callback, params, objs, commonObjs, operatorList, pageNumber) {
  8786. this.callback = callback;
  8787. this.params = params;
  8788. this.objs = objs;
  8789. this.commonObjs = commonObjs;
  8790. this.operatorListIdx = null;
  8791. this.operatorList = operatorList;
  8792. this.pageNumber = pageNumber;
  8793. this.running = false;
  8794. this.graphicsReadyCallback = null;
  8795. this.graphicsReady = false;
  8796. this.useRequestAnimationFrame = false;
  8797. this.cancelled = false;
  8798. this.capability = createPromiseCapability();
  8799. this.task = new RenderTask(this);
  8800. this._continueBound = this._continue.bind(this);
  8801. this._scheduleNextBound = this._scheduleNext.bind(this);
  8802. this._nextBound = this._next.bind(this);
  8803. }
  8804. InternalRenderTask.prototype = {
  8805. initializeGraphics: function InternalRenderTask_initializeGraphics(transparency) {
  8806. if (this.cancelled) {
  8807. return;
  8808. }
  8809. if (getDefaultSetting('pdfBug') && globalScope.StepperManager && globalScope.StepperManager.enabled) {
  8810. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  8811. this.stepper.init(this.operatorList);
  8812. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  8813. }
  8814. var params = this.params;
  8815. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs, this.objs, params.imageLayer);
  8816. this.gfx.beginDrawing(params.transform, params.viewport, transparency);
  8817. this.operatorListIdx = 0;
  8818. this.graphicsReady = true;
  8819. if (this.graphicsReadyCallback) {
  8820. this.graphicsReadyCallback();
  8821. }
  8822. },
  8823. cancel: function InternalRenderTask_cancel() {
  8824. this.running = false;
  8825. this.cancelled = true;
  8826. this.callback('cancelled');
  8827. },
  8828. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  8829. if (!this.graphicsReady) {
  8830. if (!this.graphicsReadyCallback) {
  8831. this.graphicsReadyCallback = this._continueBound;
  8832. }
  8833. return;
  8834. }
  8835. if (this.stepper) {
  8836. this.stepper.updateOperatorList(this.operatorList);
  8837. }
  8838. if (this.running) {
  8839. return;
  8840. }
  8841. this._continue();
  8842. },
  8843. _continue: function InternalRenderTask__continue() {
  8844. this.running = true;
  8845. if (this.cancelled) {
  8846. return;
  8847. }
  8848. if (this.task.onContinue) {
  8849. this.task.onContinue(this._scheduleNextBound);
  8850. } else {
  8851. this._scheduleNext();
  8852. }
  8853. },
  8854. _scheduleNext: function InternalRenderTask__scheduleNext() {
  8855. if (this.useRequestAnimationFrame && typeof window !== 'undefined') {
  8856. window.requestAnimationFrame(this._nextBound);
  8857. } else {
  8858. Promise.resolve(undefined).then(this._nextBound);
  8859. }
  8860. },
  8861. _next: function InternalRenderTask__next() {
  8862. if (this.cancelled) {
  8863. return;
  8864. }
  8865. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
  8866. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  8867. this.running = false;
  8868. if (this.operatorList.lastChunk) {
  8869. this.gfx.endDrawing();
  8870. this.callback();
  8871. }
  8872. }
  8873. }
  8874. };
  8875. return InternalRenderTask;
  8876. }();
  8877. var _UnsupportedManager = function UnsupportedManagerClosure() {
  8878. var listeners = [];
  8879. return {
  8880. listen: function (cb) {
  8881. deprecated('Global UnsupportedManager.listen is used: ' + ' use PDFDocumentLoadingTask.onUnsupportedFeature instead');
  8882. listeners.push(cb);
  8883. },
  8884. notify: function (featureId) {
  8885. for (var i = 0, ii = listeners.length; i < ii; i++) {
  8886. listeners[i](featureId);
  8887. }
  8888. }
  8889. };
  8890. }();
  8891. if (typeof pdfjsVersion !== 'undefined') {
  8892. exports.version = pdfjsVersion;
  8893. }
  8894. if (typeof pdfjsBuild !== 'undefined') {
  8895. exports.build = pdfjsBuild;
  8896. }
  8897. exports.getDocument = getDocument;
  8898. exports.PDFDataRangeTransport = PDFDataRangeTransport;
  8899. exports.PDFWorker = PDFWorker;
  8900. exports.PDFDocumentProxy = PDFDocumentProxy;
  8901. exports.PDFPageProxy = PDFPageProxy;
  8902. exports._UnsupportedManager = _UnsupportedManager;
  8903. }));
  8904. (function (root, factory) {
  8905. factory(root.pdfjsDisplayGlobal = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils, root.pdfjsDisplayAPI, root.pdfjsDisplayAnnotationLayer, root.pdfjsDisplayTextLayer, root.pdfjsDisplayMetadata, root.pdfjsDisplaySVG);
  8906. }(this, function (exports, sharedUtil, displayDOMUtils, displayAPI, displayAnnotationLayer, displayTextLayer, displayMetadata, displaySVG) {
  8907. var globalScope = sharedUtil.globalScope;
  8908. var deprecated = sharedUtil.deprecated;
  8909. var warn = sharedUtil.warn;
  8910. var LinkTarget = displayDOMUtils.LinkTarget;
  8911. var DEFAULT_LINK_REL = displayDOMUtils.DEFAULT_LINK_REL;
  8912. var isWorker = typeof window === 'undefined';
  8913. if (!globalScope.PDFJS) {
  8914. globalScope.PDFJS = {};
  8915. }
  8916. var PDFJS = globalScope.PDFJS;
  8917. if (typeof pdfjsVersion !== 'undefined') {
  8918. PDFJS.version = pdfjsVersion;
  8919. }
  8920. if (typeof pdfjsBuild !== 'undefined') {
  8921. PDFJS.build = pdfjsBuild;
  8922. }
  8923. PDFJS.pdfBug = false;
  8924. if (PDFJS.verbosity !== undefined) {
  8925. sharedUtil.setVerbosityLevel(PDFJS.verbosity);
  8926. }
  8927. delete PDFJS.verbosity;
  8928. Object.defineProperty(PDFJS, 'verbosity', {
  8929. get: function () {
  8930. return sharedUtil.getVerbosityLevel();
  8931. },
  8932. set: function (level) {
  8933. sharedUtil.setVerbosityLevel(level);
  8934. },
  8935. enumerable: true,
  8936. configurable: true
  8937. });
  8938. PDFJS.VERBOSITY_LEVELS = sharedUtil.VERBOSITY_LEVELS;
  8939. PDFJS.OPS = sharedUtil.OPS;
  8940. PDFJS.UNSUPPORTED_FEATURES = sharedUtil.UNSUPPORTED_FEATURES;
  8941. PDFJS.isValidUrl = displayDOMUtils.isValidUrl;
  8942. PDFJS.shadow = sharedUtil.shadow;
  8943. PDFJS.createBlob = sharedUtil.createBlob;
  8944. PDFJS.createObjectURL = function PDFJS_createObjectURL(data, contentType) {
  8945. return sharedUtil.createObjectURL(data, contentType, PDFJS.disableCreateObjectURL);
  8946. };
  8947. Object.defineProperty(PDFJS, 'isLittleEndian', {
  8948. configurable: true,
  8949. get: function PDFJS_isLittleEndian() {
  8950. var value = sharedUtil.isLittleEndian();
  8951. return sharedUtil.shadow(PDFJS, 'isLittleEndian', value);
  8952. }
  8953. });
  8954. PDFJS.removeNullCharacters = sharedUtil.removeNullCharacters;
  8955. PDFJS.PasswordResponses = sharedUtil.PasswordResponses;
  8956. PDFJS.PasswordException = sharedUtil.PasswordException;
  8957. PDFJS.UnknownErrorException = sharedUtil.UnknownErrorException;
  8958. PDFJS.InvalidPDFException = sharedUtil.InvalidPDFException;
  8959. PDFJS.MissingPDFException = sharedUtil.MissingPDFException;
  8960. PDFJS.UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  8961. PDFJS.Util = sharedUtil.Util;
  8962. PDFJS.PageViewport = sharedUtil.PageViewport;
  8963. PDFJS.createPromiseCapability = sharedUtil.createPromiseCapability;
  8964. PDFJS.maxImageSize = PDFJS.maxImageSize === undefined ? -1 : PDFJS.maxImageSize;
  8965. PDFJS.cMapUrl = PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl;
  8966. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  8967. PDFJS.disableFontFace = PDFJS.disableFontFace === undefined ? false : PDFJS.disableFontFace;
  8968. PDFJS.imageResourcesPath = PDFJS.imageResourcesPath === undefined ? '' : PDFJS.imageResourcesPath;
  8969. PDFJS.disableWorker = PDFJS.disableWorker === undefined ? false : PDFJS.disableWorker;
  8970. PDFJS.workerSrc = PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc;
  8971. PDFJS.disableRange = PDFJS.disableRange === undefined ? false : PDFJS.disableRange;
  8972. PDFJS.disableStream = PDFJS.disableStream === undefined ? false : PDFJS.disableStream;
  8973. PDFJS.disableAutoFetch = PDFJS.disableAutoFetch === undefined ? false : PDFJS.disableAutoFetch;
  8974. PDFJS.pdfBug = PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug;
  8975. PDFJS.postMessageTransfers = PDFJS.postMessageTransfers === undefined ? true : PDFJS.postMessageTransfers;
  8976. PDFJS.disableCreateObjectURL = PDFJS.disableCreateObjectURL === undefined ? false : PDFJS.disableCreateObjectURL;
  8977. PDFJS.disableWebGL = PDFJS.disableWebGL === undefined ? true : PDFJS.disableWebGL;
  8978. PDFJS.externalLinkTarget = PDFJS.externalLinkTarget === undefined ? LinkTarget.NONE : PDFJS.externalLinkTarget;
  8979. PDFJS.externalLinkRel = PDFJS.externalLinkRel === undefined ? DEFAULT_LINK_REL : PDFJS.externalLinkRel;
  8980. PDFJS.isEvalSupported = PDFJS.isEvalSupported === undefined ? true : PDFJS.isEvalSupported;
  8981. var savedOpenExternalLinksInNewWindow = PDFJS.openExternalLinksInNewWindow;
  8982. delete PDFJS.openExternalLinksInNewWindow;
  8983. Object.defineProperty(PDFJS, 'openExternalLinksInNewWindow', {
  8984. get: function () {
  8985. return PDFJS.externalLinkTarget === LinkTarget.BLANK;
  8986. },
  8987. set: function (value) {
  8988. if (value) {
  8989. deprecated('PDFJS.openExternalLinksInNewWindow, please use ' + '"PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.');
  8990. }
  8991. if (PDFJS.externalLinkTarget !== LinkTarget.NONE) {
  8992. warn('PDFJS.externalLinkTarget is already initialized');
  8993. return;
  8994. }
  8995. PDFJS.externalLinkTarget = value ? LinkTarget.BLANK : LinkTarget.NONE;
  8996. },
  8997. enumerable: true,
  8998. configurable: true
  8999. });
  9000. if (savedOpenExternalLinksInNewWindow) {
  9001. PDFJS.openExternalLinksInNewWindow = savedOpenExternalLinksInNewWindow;
  9002. }
  9003. PDFJS.getDocument = displayAPI.getDocument;
  9004. PDFJS.PDFDataRangeTransport = displayAPI.PDFDataRangeTransport;
  9005. PDFJS.PDFWorker = displayAPI.PDFWorker;
  9006. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  9007. configurable: true,
  9008. get: function PDFJS_hasCanvasTypedArrays() {
  9009. var value = displayDOMUtils.hasCanvasTypedArrays();
  9010. return sharedUtil.shadow(PDFJS, 'hasCanvasTypedArrays', value);
  9011. }
  9012. });
  9013. PDFJS.CustomStyle = displayDOMUtils.CustomStyle;
  9014. PDFJS.LinkTarget = LinkTarget;
  9015. PDFJS.addLinkAttributes = displayDOMUtils.addLinkAttributes;
  9016. PDFJS.getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  9017. PDFJS.isExternalLinkTargetSet = displayDOMUtils.isExternalLinkTargetSet;
  9018. PDFJS.AnnotationLayer = displayAnnotationLayer.AnnotationLayer;
  9019. PDFJS.renderTextLayer = displayTextLayer.renderTextLayer;
  9020. PDFJS.Metadata = displayMetadata.Metadata;
  9021. PDFJS.SVGGraphics = displaySVG.SVGGraphics;
  9022. PDFJS.UnsupportedManager = displayAPI._UnsupportedManager;
  9023. exports.globalScope = globalScope;
  9024. exports.isWorker = isWorker;
  9025. exports.PDFJS = globalScope.PDFJS;
  9026. }));
  9027. }.call(pdfjsLibs));
  9028. exports.PDFJS = pdfjsLibs.pdfjsDisplayGlobal.PDFJS;
  9029. exports.build = pdfjsLibs.pdfjsDisplayAPI.build;
  9030. exports.version = pdfjsLibs.pdfjsDisplayAPI.version;
  9031. exports.getDocument = pdfjsLibs.pdfjsDisplayAPI.getDocument;
  9032. exports.PDFDataRangeTransport = pdfjsLibs.pdfjsDisplayAPI.PDFDataRangeTransport;
  9033. exports.PDFWorker = pdfjsLibs.pdfjsDisplayAPI.PDFWorker;
  9034. exports.renderTextLayer = pdfjsLibs.pdfjsDisplayTextLayer.renderTextLayer;
  9035. exports.AnnotationLayer = pdfjsLibs.pdfjsDisplayAnnotationLayer.AnnotationLayer;
  9036. exports.CustomStyle = pdfjsLibs.pdfjsDisplayDOMUtils.CustomStyle;
  9037. exports.PasswordResponses = pdfjsLibs.pdfjsSharedUtil.PasswordResponses;
  9038. exports.InvalidPDFException = pdfjsLibs.pdfjsSharedUtil.InvalidPDFException;
  9039. exports.MissingPDFException = pdfjsLibs.pdfjsSharedUtil.MissingPDFException;
  9040. exports.SVGGraphics = pdfjsLibs.pdfjsDisplaySVG.SVGGraphics;
  9041. exports.UnexpectedResponseException = pdfjsLibs.pdfjsSharedUtil.UnexpectedResponseException;
  9042. exports.OPS = pdfjsLibs.pdfjsSharedUtil.OPS;
  9043. exports.UNSUPPORTED_FEATURES = pdfjsLibs.pdfjsSharedUtil.UNSUPPORTED_FEATURES;
  9044. exports.isValidUrl = pdfjsLibs.pdfjsDisplayDOMUtils.isValidUrl;
  9045. exports.createValidAbsoluteUrl = pdfjsLibs.pdfjsSharedUtil.createValidAbsoluteUrl;
  9046. exports.createObjectURL = pdfjsLibs.pdfjsSharedUtil.createObjectURL;
  9047. exports.removeNullCharacters = pdfjsLibs.pdfjsSharedUtil.removeNullCharacters;
  9048. exports.shadow = pdfjsLibs.pdfjsSharedUtil.shadow;
  9049. exports.createBlob = pdfjsLibs.pdfjsSharedUtil.createBlob;
  9050. exports.getFilenameFromUrl = pdfjsLibs.pdfjsDisplayDOMUtils.getFilenameFromUrl;
  9051. exports.addLinkAttributes = pdfjsLibs.pdfjsDisplayDOMUtils.addLinkAttributes;
  9052. }));