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.

8052 lines
256 KiB

  1. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  3. /* Copyright 2012 Mozilla Foundation
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /*jshint globalstrict: false */
  18. /* globals PDFJS */
  19. // Initializing PDFJS global object (if still undefined)
  20. if (typeof PDFJS === 'undefined') {
  21. (typeof window !== 'undefined' ? window : this).PDFJS = {};
  22. }
  23. PDFJS.version = '1.1.114';
  24. PDFJS.build = '3fd44fd';
  25. (function pdfjsWrapper() {
  26. // Use strict in our context only - users might not want it
  27. 'use strict';
  28. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  29. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  30. /* Copyright 2012 Mozilla Foundation
  31. *
  32. * Licensed under the Apache License, Version 2.0 (the "License");
  33. * you may not use this file except in compliance with the License.
  34. * You may obtain a copy of the License at
  35. *
  36. * http://www.apache.org/licenses/LICENSE-2.0
  37. *
  38. * Unless required by applicable law or agreed to in writing, software
  39. * distributed under the License is distributed on an "AS IS" BASIS,
  40. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41. * See the License for the specific language governing permissions and
  42. * limitations under the License.
  43. */
  44. /* globals Cmd, ColorSpace, Dict, MozBlobBuilder, Name, PDFJS, Ref, URL,
  45. Promise */
  46. 'use strict';
  47. var globalScope = (typeof window === 'undefined') ? this : window;
  48. var isWorker = (typeof window === 'undefined');
  49. var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
  50. var TextRenderingMode = {
  51. FILL: 0,
  52. STROKE: 1,
  53. FILL_STROKE: 2,
  54. INVISIBLE: 3,
  55. FILL_ADD_TO_PATH: 4,
  56. STROKE_ADD_TO_PATH: 5,
  57. FILL_STROKE_ADD_TO_PATH: 6,
  58. ADD_TO_PATH: 7,
  59. FILL_STROKE_MASK: 3,
  60. ADD_TO_PATH_FLAG: 4
  61. };
  62. var ImageKind = {
  63. GRAYSCALE_1BPP: 1,
  64. RGB_24BPP: 2,
  65. RGBA_32BPP: 3
  66. };
  67. var AnnotationType = {
  68. WIDGET: 1,
  69. TEXT: 2,
  70. LINK: 3
  71. };
  72. var StreamType = {
  73. UNKNOWN: 0,
  74. FLATE: 1,
  75. LZW: 2,
  76. DCT: 3,
  77. JPX: 4,
  78. JBIG: 5,
  79. A85: 6,
  80. AHX: 7,
  81. CCF: 8,
  82. RL: 9
  83. };
  84. var FontType = {
  85. UNKNOWN: 0,
  86. TYPE1: 1,
  87. TYPE1C: 2,
  88. CIDFONTTYPE0: 3,
  89. CIDFONTTYPE0C: 4,
  90. TRUETYPE: 5,
  91. CIDFONTTYPE2: 6,
  92. TYPE3: 7,
  93. OPENTYPE: 8,
  94. TYPE0: 9,
  95. MMTYPE1: 10
  96. };
  97. // The global PDFJS object exposes the API
  98. // In production, it will be declared outside a global wrapper
  99. // In development, it will be declared here
  100. if (!globalScope.PDFJS) {
  101. globalScope.PDFJS = {};
  102. }
  103. globalScope.PDFJS.pdfBug = false;
  104. PDFJS.VERBOSITY_LEVELS = {
  105. errors: 0,
  106. warnings: 1,
  107. infos: 5
  108. };
  109. // All the possible operations for an operator list.
  110. var OPS = PDFJS.OPS = {
  111. // Intentionally start from 1 so it is easy to spot bad operators that will be
  112. // 0's.
  113. dependency: 1,
  114. setLineWidth: 2,
  115. setLineCap: 3,
  116. setLineJoin: 4,
  117. setMiterLimit: 5,
  118. setDash: 6,
  119. setRenderingIntent: 7,
  120. setFlatness: 8,
  121. setGState: 9,
  122. save: 10,
  123. restore: 11,
  124. transform: 12,
  125. moveTo: 13,
  126. lineTo: 14,
  127. curveTo: 15,
  128. curveTo2: 16,
  129. curveTo3: 17,
  130. closePath: 18,
  131. rectangle: 19,
  132. stroke: 20,
  133. closeStroke: 21,
  134. fill: 22,
  135. eoFill: 23,
  136. fillStroke: 24,
  137. eoFillStroke: 25,
  138. closeFillStroke: 26,
  139. closeEOFillStroke: 27,
  140. endPath: 28,
  141. clip: 29,
  142. eoClip: 30,
  143. beginText: 31,
  144. endText: 32,
  145. setCharSpacing: 33,
  146. setWordSpacing: 34,
  147. setHScale: 35,
  148. setLeading: 36,
  149. setFont: 37,
  150. setTextRenderingMode: 38,
  151. setTextRise: 39,
  152. moveText: 40,
  153. setLeadingMoveText: 41,
  154. setTextMatrix: 42,
  155. nextLine: 43,
  156. showText: 44,
  157. showSpacedText: 45,
  158. nextLineShowText: 46,
  159. nextLineSetSpacingShowText: 47,
  160. setCharWidth: 48,
  161. setCharWidthAndBounds: 49,
  162. setStrokeColorSpace: 50,
  163. setFillColorSpace: 51,
  164. setStrokeColor: 52,
  165. setStrokeColorN: 53,
  166. setFillColor: 54,
  167. setFillColorN: 55,
  168. setStrokeGray: 56,
  169. setFillGray: 57,
  170. setStrokeRGBColor: 58,
  171. setFillRGBColor: 59,
  172. setStrokeCMYKColor: 60,
  173. setFillCMYKColor: 61,
  174. shadingFill: 62,
  175. beginInlineImage: 63,
  176. beginImageData: 64,
  177. endInlineImage: 65,
  178. paintXObject: 66,
  179. markPoint: 67,
  180. markPointProps: 68,
  181. beginMarkedContent: 69,
  182. beginMarkedContentProps: 70,
  183. endMarkedContent: 71,
  184. beginCompat: 72,
  185. endCompat: 73,
  186. paintFormXObjectBegin: 74,
  187. paintFormXObjectEnd: 75,
  188. beginGroup: 76,
  189. endGroup: 77,
  190. beginAnnotations: 78,
  191. endAnnotations: 79,
  192. beginAnnotation: 80,
  193. endAnnotation: 81,
  194. paintJpegXObject: 82,
  195. paintImageMaskXObject: 83,
  196. paintImageMaskXObjectGroup: 84,
  197. paintImageXObject: 85,
  198. paintInlineImageXObject: 86,
  199. paintInlineImageXObjectGroup: 87,
  200. paintImageXObjectRepeat: 88,
  201. paintImageMaskXObjectRepeat: 89,
  202. paintSolidColorImageMask: 90,
  203. constructPath: 91
  204. };
  205. // A notice for devs. These are good for things that are helpful to devs, such
  206. // as warning that Workers were disabled, which is important to devs but not
  207. // end users.
  208. function info(msg) {
  209. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) {
  210. console.log('Info: ' + msg);
  211. }
  212. }
  213. // Non-fatal warnings.
  214. function warn(msg) {
  215. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) {
  216. console.log('Warning: ' + msg);
  217. }
  218. }
  219. // Fatal errors that should trigger the fallback UI and halt execution by
  220. // throwing an exception.
  221. function error(msg) {
  222. if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.errors) {
  223. console.log('Error: ' + msg);
  224. console.log(backtrace());
  225. }
  226. UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown);
  227. throw new Error(msg);
  228. }
  229. function backtrace() {
  230. try {
  231. throw new Error();
  232. } catch (e) {
  233. return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
  234. }
  235. }
  236. function assert(cond, msg) {
  237. if (!cond) {
  238. error(msg);
  239. }
  240. }
  241. var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = {
  242. unknown: 'unknown',
  243. forms: 'forms',
  244. javaScript: 'javaScript',
  245. smask: 'smask',
  246. shadingPattern: 'shadingPattern',
  247. font: 'font'
  248. };
  249. var UnsupportedManager = PDFJS.UnsupportedManager =
  250. (function UnsupportedManagerClosure() {
  251. var listeners = [];
  252. return {
  253. listen: function (cb) {
  254. listeners.push(cb);
  255. },
  256. notify: function (featureId) {
  257. warn('Unsupported feature "' + featureId + '"');
  258. for (var i = 0, ii = listeners.length; i < ii; i++) {
  259. listeners[i](featureId);
  260. }
  261. }
  262. };
  263. })();
  264. // Combines two URLs. The baseUrl shall be absolute URL. If the url is an
  265. // absolute URL, it will be returned as is.
  266. function combineUrl(baseUrl, url) {
  267. if (!url) {
  268. return baseUrl;
  269. }
  270. if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) {
  271. return url;
  272. }
  273. var i;
  274. if (url.charAt(0) === '/') {
  275. // absolute path
  276. i = baseUrl.indexOf('://');
  277. if (url.charAt(1) === '/') {
  278. ++i;
  279. } else {
  280. i = baseUrl.indexOf('/', i + 3);
  281. }
  282. return baseUrl.substring(0, i) + url;
  283. } else {
  284. // relative path
  285. var pathLength = baseUrl.length;
  286. i = baseUrl.lastIndexOf('#');
  287. pathLength = i >= 0 ? i : pathLength;
  288. i = baseUrl.lastIndexOf('?', pathLength);
  289. pathLength = i >= 0 ? i : pathLength;
  290. var prefixLength = baseUrl.lastIndexOf('/', pathLength);
  291. return baseUrl.substring(0, prefixLength + 1) + url;
  292. }
  293. }
  294. // Validates if URL is safe and allowed, e.g. to avoid XSS.
  295. function isValidUrl(url, allowRelative) {
  296. if (!url) {
  297. return false;
  298. }
  299. // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
  300. // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  301. var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
  302. if (!protocol) {
  303. return allowRelative;
  304. }
  305. protocol = protocol[0].toLowerCase();
  306. switch (protocol) {
  307. case 'http':
  308. case 'https':
  309. case 'ftp':
  310. case 'mailto':
  311. case 'tel':
  312. return true;
  313. default:
  314. return false;
  315. }
  316. }
  317. PDFJS.isValidUrl = isValidUrl;
  318. function shadow(obj, prop, value) {
  319. Object.defineProperty(obj, prop, { value: value,
  320. enumerable: true,
  321. configurable: true,
  322. writable: false });
  323. return value;
  324. }
  325. PDFJS.shadow = shadow;
  326. var PasswordResponses = PDFJS.PasswordResponses = {
  327. NEED_PASSWORD: 1,
  328. INCORRECT_PASSWORD: 2
  329. };
  330. var PasswordException = (function PasswordExceptionClosure() {
  331. function PasswordException(msg, code) {
  332. this.name = 'PasswordException';
  333. this.message = msg;
  334. this.code = code;
  335. }
  336. PasswordException.prototype = new Error();
  337. PasswordException.constructor = PasswordException;
  338. return PasswordException;
  339. })();
  340. PDFJS.PasswordException = PasswordException;
  341. var UnknownErrorException = (function UnknownErrorExceptionClosure() {
  342. function UnknownErrorException(msg, details) {
  343. this.name = 'UnknownErrorException';
  344. this.message = msg;
  345. this.details = details;
  346. }
  347. UnknownErrorException.prototype = new Error();
  348. UnknownErrorException.constructor = UnknownErrorException;
  349. return UnknownErrorException;
  350. })();
  351. PDFJS.UnknownErrorException = UnknownErrorException;
  352. var InvalidPDFException = (function InvalidPDFExceptionClosure() {
  353. function InvalidPDFException(msg) {
  354. this.name = 'InvalidPDFException';
  355. this.message = msg;
  356. }
  357. InvalidPDFException.prototype = new Error();
  358. InvalidPDFException.constructor = InvalidPDFException;
  359. return InvalidPDFException;
  360. })();
  361. PDFJS.InvalidPDFException = InvalidPDFException;
  362. var MissingPDFException = (function MissingPDFExceptionClosure() {
  363. function MissingPDFException(msg) {
  364. this.name = 'MissingPDFException';
  365. this.message = msg;
  366. }
  367. MissingPDFException.prototype = new Error();
  368. MissingPDFException.constructor = MissingPDFException;
  369. return MissingPDFException;
  370. })();
  371. PDFJS.MissingPDFException = MissingPDFException;
  372. var UnexpectedResponseException =
  373. (function UnexpectedResponseExceptionClosure() {
  374. function UnexpectedResponseException(msg, status) {
  375. this.name = 'UnexpectedResponseException';
  376. this.message = msg;
  377. this.status = status;
  378. }
  379. UnexpectedResponseException.prototype = new Error();
  380. UnexpectedResponseException.constructor = UnexpectedResponseException;
  381. return UnexpectedResponseException;
  382. })();
  383. PDFJS.UnexpectedResponseException = UnexpectedResponseException;
  384. var NotImplementedException = (function NotImplementedExceptionClosure() {
  385. function NotImplementedException(msg) {
  386. this.message = msg;
  387. }
  388. NotImplementedException.prototype = new Error();
  389. NotImplementedException.prototype.name = 'NotImplementedException';
  390. NotImplementedException.constructor = NotImplementedException;
  391. return NotImplementedException;
  392. })();
  393. var MissingDataException = (function MissingDataExceptionClosure() {
  394. function MissingDataException(begin, end) {
  395. this.begin = begin;
  396. this.end = end;
  397. this.message = 'Missing data [' + begin + ', ' + end + ')';
  398. }
  399. MissingDataException.prototype = new Error();
  400. MissingDataException.prototype.name = 'MissingDataException';
  401. MissingDataException.constructor = MissingDataException;
  402. return MissingDataException;
  403. })();
  404. var XRefParseException = (function XRefParseExceptionClosure() {
  405. function XRefParseException(msg) {
  406. this.message = msg;
  407. }
  408. XRefParseException.prototype = new Error();
  409. XRefParseException.prototype.name = 'XRefParseException';
  410. XRefParseException.constructor = XRefParseException;
  411. return XRefParseException;
  412. })();
  413. function bytesToString(bytes) {
  414. assert(bytes !== null && typeof bytes === 'object' &&
  415. bytes.length !== undefined, 'Invalid argument for bytesToString');
  416. var length = bytes.length;
  417. var MAX_ARGUMENT_COUNT = 8192;
  418. if (length < MAX_ARGUMENT_COUNT) {
  419. return String.fromCharCode.apply(null, bytes);
  420. }
  421. var strBuf = [];
  422. for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  423. var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  424. var chunk = bytes.subarray(i, chunkEnd);
  425. strBuf.push(String.fromCharCode.apply(null, chunk));
  426. }
  427. return strBuf.join('');
  428. }
  429. function stringToBytes(str) {
  430. assert(typeof str === 'string', 'Invalid argument for stringToBytes');
  431. var length = str.length;
  432. var bytes = new Uint8Array(length);
  433. for (var i = 0; i < length; ++i) {
  434. bytes[i] = str.charCodeAt(i) & 0xFF;
  435. }
  436. return bytes;
  437. }
  438. function string32(value) {
  439. return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,
  440. (value >> 8) & 0xff, value & 0xff);
  441. }
  442. function log2(x) {
  443. var n = 1, i = 0;
  444. while (x > n) {
  445. n <<= 1;
  446. i++;
  447. }
  448. return i;
  449. }
  450. function readInt8(data, start) {
  451. return (data[start] << 24) >> 24;
  452. }
  453. function readUint16(data, offset) {
  454. return (data[offset] << 8) | data[offset + 1];
  455. }
  456. function readUint32(data, offset) {
  457. return ((data[offset] << 24) | (data[offset + 1] << 16) |
  458. (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
  459. }
  460. // Lazy test the endianness of the platform
  461. // NOTE: This will be 'true' for simulated TypedArrays
  462. function isLittleEndian() {
  463. var buffer8 = new Uint8Array(2);
  464. buffer8[0] = 1;
  465. var buffer16 = new Uint16Array(buffer8.buffer);
  466. return (buffer16[0] === 1);
  467. }
  468. Object.defineProperty(PDFJS, 'isLittleEndian', {
  469. configurable: true,
  470. get: function PDFJS_isLittleEndian() {
  471. return shadow(PDFJS, 'isLittleEndian', isLittleEndian());
  472. }
  473. });
  474. //#if !(FIREFOX || MOZCENTRAL || B2G || CHROME)
  475. //// Lazy test if the userAgant support CanvasTypedArrays
  476. function hasCanvasTypedArrays() {
  477. var canvas = document.createElement('canvas');
  478. canvas.width = canvas.height = 1;
  479. var ctx = canvas.getContext('2d');
  480. var imageData = ctx.createImageData(1, 1);
  481. return (typeof imageData.data.buffer !== 'undefined');
  482. }
  483. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  484. configurable: true,
  485. get: function PDFJS_hasCanvasTypedArrays() {
  486. return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays());
  487. }
  488. });
  489. var Uint32ArrayView = (function Uint32ArrayViewClosure() {
  490. function Uint32ArrayView(buffer, length) {
  491. this.buffer = buffer;
  492. this.byteLength = buffer.length;
  493. this.length = length === undefined ? (this.byteLength >> 2) : length;
  494. ensureUint32ArrayViewProps(this.length);
  495. }
  496. Uint32ArrayView.prototype = Object.create(null);
  497. var uint32ArrayViewSetters = 0;
  498. function createUint32ArrayProp(index) {
  499. return {
  500. get: function () {
  501. var buffer = this.buffer, offset = index << 2;
  502. return (buffer[offset] | (buffer[offset + 1] << 8) |
  503. (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;
  504. },
  505. set: function (value) {
  506. var buffer = this.buffer, offset = index << 2;
  507. buffer[offset] = value & 255;
  508. buffer[offset + 1] = (value >> 8) & 255;
  509. buffer[offset + 2] = (value >> 16) & 255;
  510. buffer[offset + 3] = (value >>> 24) & 255;
  511. }
  512. };
  513. }
  514. function ensureUint32ArrayViewProps(length) {
  515. while (uint32ArrayViewSetters < length) {
  516. Object.defineProperty(Uint32ArrayView.prototype,
  517. uint32ArrayViewSetters,
  518. createUint32ArrayProp(uint32ArrayViewSetters));
  519. uint32ArrayViewSetters++;
  520. }
  521. }
  522. return Uint32ArrayView;
  523. })();
  524. //#else
  525. //PDFJS.hasCanvasTypedArrays = true;
  526. //#endif
  527. var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
  528. var Util = PDFJS.Util = (function UtilClosure() {
  529. function Util() {}
  530. var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];
  531. // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
  532. // creating many intermediate strings.
  533. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
  534. rgbBuf[1] = r;
  535. rgbBuf[3] = g;
  536. rgbBuf[5] = b;
  537. return rgbBuf.join('');
  538. };
  539. // Concatenates two transformation matrices together and returns the result.
  540. Util.transform = function Util_transform(m1, m2) {
  541. return [
  542. m1[0] * m2[0] + m1[2] * m2[1],
  543. m1[1] * m2[0] + m1[3] * m2[1],
  544. m1[0] * m2[2] + m1[2] * m2[3],
  545. m1[1] * m2[2] + m1[3] * m2[3],
  546. m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
  547. m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
  548. ];
  549. };
  550. // For 2d affine transforms
  551. Util.applyTransform = function Util_applyTransform(p, m) {
  552. var xt = p[0] * m[0] + p[1] * m[2] + m[4];
  553. var yt = p[0] * m[1] + p[1] * m[3] + m[5];
  554. return [xt, yt];
  555. };
  556. Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
  557. var d = m[0] * m[3] - m[1] * m[2];
  558. var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  559. var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  560. return [xt, yt];
  561. };
  562. // Applies the transform to the rectangle and finds the minimum axially
  563. // aligned bounding box.
  564. Util.getAxialAlignedBoundingBox =
  565. function Util_getAxialAlignedBoundingBox(r, m) {
  566. var p1 = Util.applyTransform(r, m);
  567. var p2 = Util.applyTransform(r.slice(2, 4), m);
  568. var p3 = Util.applyTransform([r[0], r[3]], m);
  569. var p4 = Util.applyTransform([r[2], r[1]], m);
  570. return [
  571. Math.min(p1[0], p2[0], p3[0], p4[0]),
  572. Math.min(p1[1], p2[1], p3[1], p4[1]),
  573. Math.max(p1[0], p2[0], p3[0], p4[0]),
  574. Math.max(p1[1], p2[1], p3[1], p4[1])
  575. ];
  576. };
  577. Util.inverseTransform = function Util_inverseTransform(m) {
  578. var d = m[0] * m[3] - m[1] * m[2];
  579. return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
  580. (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
  581. };
  582. // Apply a generic 3d matrix M on a 3-vector v:
  583. // | a b c | | X |
  584. // | d e f | x | Y |
  585. // | g h i | | Z |
  586. // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
  587. // with v as [X,Y,Z]
  588. Util.apply3dTransform = function Util_apply3dTransform(m, v) {
  589. return [
  590. m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
  591. m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
  592. m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
  593. ];
  594. };
  595. // This calculation uses Singular Value Decomposition.
  596. // The SVD can be represented with formula A = USV. We are interested in the
  597. // matrix S here because it represents the scale values.
  598. Util.singularValueDecompose2dScale =
  599. function Util_singularValueDecompose2dScale(m) {
  600. var transpose = [m[0], m[2], m[1], m[3]];
  601. // Multiply matrix m with its transpose.
  602. var a = m[0] * transpose[0] + m[1] * transpose[2];
  603. var b = m[0] * transpose[1] + m[1] * transpose[3];
  604. var c = m[2] * transpose[0] + m[3] * transpose[2];
  605. var d = m[2] * transpose[1] + m[3] * transpose[3];
  606. // Solve the second degree polynomial to get roots.
  607. var first = (a + d) / 2;
  608. var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
  609. var sx = first + second || 1;
  610. var sy = first - second || 1;
  611. // Scale values are the square roots of the eigenvalues.
  612. return [Math.sqrt(sx), Math.sqrt(sy)];
  613. };
  614. // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
  615. // For coordinate systems whose origin lies in the bottom-left, this
  616. // means normalization to (BL,TR) ordering. For systems with origin in the
  617. // top-left, this means (TL,BR) ordering.
  618. Util.normalizeRect = function Util_normalizeRect(rect) {
  619. var r = rect.slice(0); // clone rect
  620. if (rect[0] > rect[2]) {
  621. r[0] = rect[2];
  622. r[2] = rect[0];
  623. }
  624. if (rect[1] > rect[3]) {
  625. r[1] = rect[3];
  626. r[3] = rect[1];
  627. }
  628. return r;
  629. };
  630. // Returns a rectangle [x1, y1, x2, y2] corresponding to the
  631. // intersection of rect1 and rect2. If no intersection, returns 'false'
  632. // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
  633. Util.intersect = function Util_intersect(rect1, rect2) {
  634. function compare(a, b) {
  635. return a - b;
  636. }
  637. // Order points along the axes
  638. var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
  639. orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
  640. result = [];
  641. rect1 = Util.normalizeRect(rect1);
  642. rect2 = Util.normalizeRect(rect2);
  643. // X: first and second points belong to different rectangles?
  644. if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
  645. (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
  646. // Intersection must be between second and third points
  647. result[0] = orderedX[1];
  648. result[2] = orderedX[2];
  649. } else {
  650. return false;
  651. }
  652. // Y: first and second points belong to different rectangles?
  653. if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
  654. (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
  655. // Intersection must be between second and third points
  656. result[1] = orderedY[1];
  657. result[3] = orderedY[2];
  658. } else {
  659. return false;
  660. }
  661. return result;
  662. };
  663. Util.sign = function Util_sign(num) {
  664. return num < 0 ? -1 : 1;
  665. };
  666. Util.appendToArray = function Util_appendToArray(arr1, arr2) {
  667. Array.prototype.push.apply(arr1, arr2);
  668. };
  669. Util.prependToArray = function Util_prependToArray(arr1, arr2) {
  670. Array.prototype.unshift.apply(arr1, arr2);
  671. };
  672. Util.extendObj = function extendObj(obj1, obj2) {
  673. for (var key in obj2) {
  674. obj1[key] = obj2[key];
  675. }
  676. };
  677. Util.getInheritableProperty = function Util_getInheritableProperty(dict,
  678. name) {
  679. while (dict && !dict.has(name)) {
  680. dict = dict.get('Parent');
  681. }
  682. if (!dict) {
  683. return null;
  684. }
  685. return dict.get(name);
  686. };
  687. Util.inherit = function Util_inherit(sub, base, prototype) {
  688. sub.prototype = Object.create(base.prototype);
  689. sub.prototype.constructor = sub;
  690. for (var prop in prototype) {
  691. sub.prototype[prop] = prototype[prop];
  692. }
  693. };
  694. Util.loadScript = function Util_loadScript(src, callback) {
  695. var script = document.createElement('script');
  696. var loaded = false;
  697. script.setAttribute('src', src);
  698. if (callback) {
  699. script.onload = function() {
  700. if (!loaded) {
  701. callback();
  702. }
  703. loaded = true;
  704. };
  705. }
  706. document.getElementsByTagName('head')[0].appendChild(script);
  707. };
  708. return Util;
  709. })();
  710. /**
  711. * PDF page viewport created based on scale, rotation and offset.
  712. * @class
  713. * @alias PDFJS.PageViewport
  714. */
  715. var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() {
  716. /**
  717. * @constructor
  718. * @private
  719. * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
  720. * @param scale {number} scale of the viewport.
  721. * @param rotation {number} rotations of the viewport in degrees.
  722. * @param offsetX {number} offset X
  723. * @param offsetY {number} offset Y
  724. * @param dontFlip {boolean} if true, axis Y will not be flipped.
  725. */
  726. function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
  727. this.viewBox = viewBox;
  728. this.scale = scale;
  729. this.rotation = rotation;
  730. this.offsetX = offsetX;
  731. this.offsetY = offsetY;
  732. // creating transform to convert pdf coordinate system to the normal
  733. // canvas like coordinates taking in account scale and rotation
  734. var centerX = (viewBox[2] + viewBox[0]) / 2;
  735. var centerY = (viewBox[3] + viewBox[1]) / 2;
  736. var rotateA, rotateB, rotateC, rotateD;
  737. rotation = rotation % 360;
  738. rotation = rotation < 0 ? rotation + 360 : rotation;
  739. switch (rotation) {
  740. case 180:
  741. rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
  742. break;
  743. case 90:
  744. rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
  745. break;
  746. case 270:
  747. rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
  748. break;
  749. //case 0:
  750. default:
  751. rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
  752. break;
  753. }
  754. if (dontFlip) {
  755. rotateC = -rotateC; rotateD = -rotateD;
  756. }
  757. var offsetCanvasX, offsetCanvasY;
  758. var width, height;
  759. if (rotateA === 0) {
  760. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  761. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  762. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  763. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  764. } else {
  765. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  766. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  767. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  768. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  769. }
  770. // creating transform for the following operations:
  771. // translate(-centerX, -centerY), rotate and flip vertically,
  772. // scale, and translate(offsetCanvasX, offsetCanvasY)
  773. this.transform = [
  774. rotateA * scale,
  775. rotateB * scale,
  776. rotateC * scale,
  777. rotateD * scale,
  778. offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
  779. offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
  780. ];
  781. this.width = width;
  782. this.height = height;
  783. this.fontScale = scale;
  784. }
  785. PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ {
  786. /**
  787. * Clones viewport with additional properties.
  788. * @param args {Object} (optional) If specified, may contain the 'scale' or
  789. * 'rotation' properties to override the corresponding properties in
  790. * the cloned viewport.
  791. * @returns {PDFJS.PageViewport} Cloned viewport.
  792. */
  793. clone: function PageViewPort_clone(args) {
  794. args = args || {};
  795. var scale = 'scale' in args ? args.scale : this.scale;
  796. var rotation = 'rotation' in args ? args.rotation : this.rotation;
  797. return new PageViewport(this.viewBox.slice(), scale, rotation,
  798. this.offsetX, this.offsetY, args.dontFlip);
  799. },
  800. /**
  801. * Converts PDF point to the viewport coordinates. For examples, useful for
  802. * converting PDF location into canvas pixel coordinates.
  803. * @param x {number} X coordinate.
  804. * @param y {number} Y coordinate.
  805. * @returns {Object} Object that contains 'x' and 'y' properties of the
  806. * point in the viewport coordinate space.
  807. * @see {@link convertToPdfPoint}
  808. * @see {@link convertToViewportRectangle}
  809. */
  810. convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
  811. return Util.applyTransform([x, y], this.transform);
  812. },
  813. /**
  814. * Converts PDF rectangle to the viewport coordinates.
  815. * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
  816. * @returns {Array} Contains corresponding coordinates of the rectangle
  817. * in the viewport coordinate space.
  818. * @see {@link convertToViewportPoint}
  819. */
  820. convertToViewportRectangle:
  821. function PageViewport_convertToViewportRectangle(rect) {
  822. var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
  823. var br = Util.applyTransform([rect[2], rect[3]], this.transform);
  824. return [tl[0], tl[1], br[0], br[1]];
  825. },
  826. /**
  827. * Converts viewport coordinates to the PDF location. For examples, useful
  828. * for converting canvas pixel location into PDF one.
  829. * @param x {number} X coordinate.
  830. * @param y {number} Y coordinate.
  831. * @returns {Object} Object that contains 'x' and 'y' properties of the
  832. * point in the PDF coordinate space.
  833. * @see {@link convertToViewportPoint}
  834. */
  835. convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
  836. return Util.applyInverseTransform([x, y], this.transform);
  837. }
  838. };
  839. return PageViewport;
  840. })();
  841. var PDFStringTranslateTable = [
  842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  843. 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
  844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,
  848. 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,
  849. 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,
  850. 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC
  851. ];
  852. function stringToPDFString(str) {
  853. var i, n = str.length, strBuf = [];
  854. if (str[0] === '\xFE' && str[1] === '\xFF') {
  855. // UTF16BE BOM
  856. for (i = 2; i < n; i += 2) {
  857. strBuf.push(String.fromCharCode(
  858. (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
  859. }
  860. } else {
  861. for (i = 0; i < n; ++i) {
  862. var code = PDFStringTranslateTable[str.charCodeAt(i)];
  863. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  864. }
  865. }
  866. return strBuf.join('');
  867. }
  868. function stringToUTF8String(str) {
  869. return decodeURIComponent(escape(str));
  870. }
  871. function isEmptyObj(obj) {
  872. for (var key in obj) {
  873. return false;
  874. }
  875. return true;
  876. }
  877. function isBool(v) {
  878. return typeof v === 'boolean';
  879. }
  880. function isInt(v) {
  881. return typeof v === 'number' && ((v | 0) === v);
  882. }
  883. function isNum(v) {
  884. return typeof v === 'number';
  885. }
  886. function isString(v) {
  887. return typeof v === 'string';
  888. }
  889. function isName(v) {
  890. return v instanceof Name;
  891. }
  892. function isCmd(v, cmd) {
  893. return v instanceof Cmd && (cmd === undefined || v.cmd === cmd);
  894. }
  895. function isDict(v, type) {
  896. if (!(v instanceof Dict)) {
  897. return false;
  898. }
  899. if (!type) {
  900. return true;
  901. }
  902. var dictType = v.get('Type');
  903. return isName(dictType) && dictType.name === type;
  904. }
  905. function isArray(v) {
  906. return v instanceof Array;
  907. }
  908. function isStream(v) {
  909. return typeof v === 'object' && v !== null && v.getBytes !== undefined;
  910. }
  911. function isArrayBuffer(v) {
  912. return typeof v === 'object' && v !== null && v.byteLength !== undefined;
  913. }
  914. function isRef(v) {
  915. return v instanceof Ref;
  916. }
  917. /**
  918. * Promise Capability object.
  919. *
  920. * @typedef {Object} PromiseCapability
  921. * @property {Promise} promise - A promise object.
  922. * @property {function} resolve - Fullfills the promise.
  923. * @property {function} reject - Rejects the promise.
  924. */
  925. /**
  926. * Creates a promise capability object.
  927. * @alias PDFJS.createPromiseCapability
  928. *
  929. * @return {PromiseCapability} A capability object contains:
  930. * - a Promise, resolve and reject methods.
  931. */
  932. function createPromiseCapability() {
  933. var capability = {};
  934. capability.promise = new Promise(function (resolve, reject) {
  935. capability.resolve = resolve;
  936. capability.reject = reject;
  937. });
  938. return capability;
  939. }
  940. PDFJS.createPromiseCapability = createPromiseCapability;
  941. /**
  942. * Polyfill for Promises:
  943. * The following promise implementation tries to generally implement the
  944. * Promise/A+ spec. Some notable differences from other promise libaries are:
  945. * - There currently isn't a seperate deferred and promise object.
  946. * - Unhandled rejections eventually show an error if they aren't handled.
  947. *
  948. * Based off of the work in:
  949. * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
  950. */
  951. (function PromiseClosure() {
  952. if (globalScope.Promise) {
  953. // Promises existing in the DOM/Worker, checking presence of all/resolve
  954. if (typeof globalScope.Promise.all !== 'function') {
  955. globalScope.Promise.all = function (iterable) {
  956. var count = 0, results = [], resolve, reject;
  957. var promise = new globalScope.Promise(function (resolve_, reject_) {
  958. resolve = resolve_;
  959. reject = reject_;
  960. });
  961. iterable.forEach(function (p, i) {
  962. count++;
  963. p.then(function (result) {
  964. results[i] = result;
  965. count--;
  966. if (count === 0) {
  967. resolve(results);
  968. }
  969. }, reject);
  970. });
  971. if (count === 0) {
  972. resolve(results);
  973. }
  974. return promise;
  975. };
  976. }
  977. if (typeof globalScope.Promise.resolve !== 'function') {
  978. globalScope.Promise.resolve = function (value) {
  979. return new globalScope.Promise(function (resolve) { resolve(value); });
  980. };
  981. }
  982. if (typeof globalScope.Promise.reject !== 'function') {
  983. globalScope.Promise.reject = function (reason) {
  984. return new globalScope.Promise(function (resolve, reject) {
  985. reject(reason);
  986. });
  987. };
  988. }
  989. if (typeof globalScope.Promise.prototype.catch !== 'function') {
  990. globalScope.Promise.prototype.catch = function (onReject) {
  991. return globalScope.Promise.prototype.then(undefined, onReject);
  992. };
  993. }
  994. return;
  995. }
  996. //#if !MOZCENTRAL
  997. var STATUS_PENDING = 0;
  998. var STATUS_RESOLVED = 1;
  999. var STATUS_REJECTED = 2;
  1000. // In an attempt to avoid silent exceptions, unhandled rejections are
  1001. // tracked and if they aren't handled in a certain amount of time an
  1002. // error is logged.
  1003. var REJECTION_TIMEOUT = 500;
  1004. var HandlerManager = {
  1005. handlers: [],
  1006. running: false,
  1007. unhandledRejections: [],
  1008. pendingRejectionCheck: false,
  1009. scheduleHandlers: function scheduleHandlers(promise) {
  1010. if (promise._status === STATUS_PENDING) {
  1011. return;
  1012. }
  1013. this.handlers = this.handlers.concat(promise._handlers);
  1014. promise._handlers = [];
  1015. if (this.running) {
  1016. return;
  1017. }
  1018. this.running = true;
  1019. setTimeout(this.runHandlers.bind(this), 0);
  1020. },
  1021. runHandlers: function runHandlers() {
  1022. var RUN_TIMEOUT = 1; // ms
  1023. var timeoutAt = Date.now() + RUN_TIMEOUT;
  1024. while (this.handlers.length > 0) {
  1025. var handler = this.handlers.shift();
  1026. var nextStatus = handler.thisPromise._status;
  1027. var nextValue = handler.thisPromise._value;
  1028. try {
  1029. if (nextStatus === STATUS_RESOLVED) {
  1030. if (typeof handler.onResolve === 'function') {
  1031. nextValue = handler.onResolve(nextValue);
  1032. }
  1033. } else if (typeof handler.onReject === 'function') {
  1034. nextValue = handler.onReject(nextValue);
  1035. nextStatus = STATUS_RESOLVED;
  1036. if (handler.thisPromise._unhandledRejection) {
  1037. this.removeUnhandeledRejection(handler.thisPromise);
  1038. }
  1039. }
  1040. } catch (ex) {
  1041. nextStatus = STATUS_REJECTED;
  1042. nextValue = ex;
  1043. }
  1044. handler.nextPromise._updateStatus(nextStatus, nextValue);
  1045. if (Date.now() >= timeoutAt) {
  1046. break;
  1047. }
  1048. }
  1049. if (this.handlers.length > 0) {
  1050. setTimeout(this.runHandlers.bind(this), 0);
  1051. return;
  1052. }
  1053. this.running = false;
  1054. },
  1055. addUnhandledRejection: function addUnhandledRejection(promise) {
  1056. this.unhandledRejections.push({
  1057. promise: promise,
  1058. time: Date.now()
  1059. });
  1060. this.scheduleRejectionCheck();
  1061. },
  1062. removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
  1063. promise._unhandledRejection = false;
  1064. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1065. if (this.unhandledRejections[i].promise === promise) {
  1066. this.unhandledRejections.splice(i);
  1067. i--;
  1068. }
  1069. }
  1070. },
  1071. scheduleRejectionCheck: function scheduleRejectionCheck() {
  1072. if (this.pendingRejectionCheck) {
  1073. return;
  1074. }
  1075. this.pendingRejectionCheck = true;
  1076. setTimeout(function rejectionCheck() {
  1077. this.pendingRejectionCheck = false;
  1078. var now = Date.now();
  1079. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1080. if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
  1081. var unhandled = this.unhandledRejections[i].promise._value;
  1082. var msg = 'Unhandled rejection: ' + unhandled;
  1083. if (unhandled.stack) {
  1084. msg += '\n' + unhandled.stack;
  1085. }
  1086. warn(msg);
  1087. this.unhandledRejections.splice(i);
  1088. i--;
  1089. }
  1090. }
  1091. if (this.unhandledRejections.length) {
  1092. this.scheduleRejectionCheck();
  1093. }
  1094. }.bind(this), REJECTION_TIMEOUT);
  1095. }
  1096. };
  1097. function Promise(resolver) {
  1098. this._status = STATUS_PENDING;
  1099. this._handlers = [];
  1100. try {
  1101. resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
  1102. } catch (e) {
  1103. this._reject(e);
  1104. }
  1105. }
  1106. /**
  1107. * Builds a promise that is resolved when all the passed in promises are
  1108. * resolved.
  1109. * @param {array} array of data and/or promises to wait for.
  1110. * @return {Promise} New dependant promise.
  1111. */
  1112. Promise.all = function Promise_all(promises) {
  1113. var resolveAll, rejectAll;
  1114. var deferred = new Promise(function (resolve, reject) {
  1115. resolveAll = resolve;
  1116. rejectAll = reject;
  1117. });
  1118. var unresolved = promises.length;
  1119. var results = [];
  1120. if (unresolved === 0) {
  1121. resolveAll(results);
  1122. return deferred;
  1123. }
  1124. function reject(reason) {
  1125. if (deferred._status === STATUS_REJECTED) {
  1126. return;
  1127. }
  1128. results = [];
  1129. rejectAll(reason);
  1130. }
  1131. for (var i = 0, ii = promises.length; i < ii; ++i) {
  1132. var promise = promises[i];
  1133. var resolve = (function(i) {
  1134. return function(value) {
  1135. if (deferred._status === STATUS_REJECTED) {
  1136. return;
  1137. }
  1138. results[i] = value;
  1139. unresolved--;
  1140. if (unresolved === 0) {
  1141. resolveAll(results);
  1142. }
  1143. };
  1144. })(i);
  1145. if (Promise.isPromise(promise)) {
  1146. promise.then(resolve, reject);
  1147. } else {
  1148. resolve(promise);
  1149. }
  1150. }
  1151. return deferred;
  1152. };
  1153. /**
  1154. * Checks if the value is likely a promise (has a 'then' function).
  1155. * @return {boolean} true if value is thenable
  1156. */
  1157. Promise.isPromise = function Promise_isPromise(value) {
  1158. return value && typeof value.then === 'function';
  1159. };
  1160. /**
  1161. * Creates resolved promise
  1162. * @param value resolve value
  1163. * @returns {Promise}
  1164. */
  1165. Promise.resolve = function Promise_resolve(value) {
  1166. return new Promise(function (resolve) { resolve(value); });
  1167. };
  1168. /**
  1169. * Creates rejected promise
  1170. * @param reason rejection value
  1171. * @returns {Promise}
  1172. */
  1173. Promise.reject = function Promise_reject(reason) {
  1174. return new Promise(function (resolve, reject) { reject(reason); });
  1175. };
  1176. Promise.prototype = {
  1177. _status: null,
  1178. _value: null,
  1179. _handlers: null,
  1180. _unhandledRejection: null,
  1181. _updateStatus: function Promise__updateStatus(status, value) {
  1182. if (this._status === STATUS_RESOLVED ||
  1183. this._status === STATUS_REJECTED) {
  1184. return;
  1185. }
  1186. if (status === STATUS_RESOLVED &&
  1187. Promise.isPromise(value)) {
  1188. value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
  1189. this._updateStatus.bind(this, STATUS_REJECTED));
  1190. return;
  1191. }
  1192. this._status = status;
  1193. this._value = value;
  1194. if (status === STATUS_REJECTED && this._handlers.length === 0) {
  1195. this._unhandledRejection = true;
  1196. HandlerManager.addUnhandledRejection(this);
  1197. }
  1198. HandlerManager.scheduleHandlers(this);
  1199. },
  1200. _resolve: function Promise_resolve(value) {
  1201. this._updateStatus(STATUS_RESOLVED, value);
  1202. },
  1203. _reject: function Promise_reject(reason) {
  1204. this._updateStatus(STATUS_REJECTED, reason);
  1205. },
  1206. then: function Promise_then(onResolve, onReject) {
  1207. var nextPromise = new Promise(function (resolve, reject) {
  1208. this.resolve = resolve;
  1209. this.reject = reject;
  1210. });
  1211. this._handlers.push({
  1212. thisPromise: this,
  1213. onResolve: onResolve,
  1214. onReject: onReject,
  1215. nextPromise: nextPromise
  1216. });
  1217. HandlerManager.scheduleHandlers(this);
  1218. return nextPromise;
  1219. },
  1220. catch: function Promise_catch(onReject) {
  1221. return this.then(undefined, onReject);
  1222. }
  1223. };
  1224. globalScope.Promise = Promise;
  1225. //#else
  1226. //throw new Error('DOM Promise is not present');
  1227. //#endif
  1228. })();
  1229. var StatTimer = (function StatTimerClosure() {
  1230. function rpad(str, pad, length) {
  1231. while (str.length < length) {
  1232. str += pad;
  1233. }
  1234. return str;
  1235. }
  1236. function StatTimer() {
  1237. this.started = {};
  1238. this.times = [];
  1239. this.enabled = true;
  1240. }
  1241. StatTimer.prototype = {
  1242. time: function StatTimer_time(name) {
  1243. if (!this.enabled) {
  1244. return;
  1245. }
  1246. if (name in this.started) {
  1247. warn('Timer is already running for ' + name);
  1248. }
  1249. this.started[name] = Date.now();
  1250. },
  1251. timeEnd: function StatTimer_timeEnd(name) {
  1252. if (!this.enabled) {
  1253. return;
  1254. }
  1255. if (!(name in this.started)) {
  1256. warn('Timer has not been started for ' + name);
  1257. }
  1258. this.times.push({
  1259. 'name': name,
  1260. 'start': this.started[name],
  1261. 'end': Date.now()
  1262. });
  1263. // Remove timer from started so it can be called again.
  1264. delete this.started[name];
  1265. },
  1266. toString: function StatTimer_toString() {
  1267. var i, ii;
  1268. var times = this.times;
  1269. var out = '';
  1270. // Find the longest name for padding purposes.
  1271. var longest = 0;
  1272. for (i = 0, ii = times.length; i < ii; ++i) {
  1273. var name = times[i]['name'];
  1274. if (name.length > longest) {
  1275. longest = name.length;
  1276. }
  1277. }
  1278. for (i = 0, ii = times.length; i < ii; ++i) {
  1279. var span = times[i];
  1280. var duration = span.end - span.start;
  1281. out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
  1282. }
  1283. return out;
  1284. }
  1285. };
  1286. return StatTimer;
  1287. })();
  1288. PDFJS.createBlob = function createBlob(data, contentType) {
  1289. if (typeof Blob !== 'undefined') {
  1290. return new Blob([data], { type: contentType });
  1291. }
  1292. // Blob builder is deprecated in FF14 and removed in FF18.
  1293. var bb = new MozBlobBuilder();
  1294. bb.append(data);
  1295. return bb.getBlob(contentType);
  1296. };
  1297. PDFJS.createObjectURL = (function createObjectURLClosure() {
  1298. // Blob/createObjectURL is not available, falling back to data schema.
  1299. var digits =
  1300. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1301. return function createObjectURL(data, contentType) {
  1302. if (!PDFJS.disableCreateObjectURL &&
  1303. typeof URL !== 'undefined' && URL.createObjectURL) {
  1304. var blob = PDFJS.createBlob(data, contentType);
  1305. return URL.createObjectURL(blob);
  1306. }
  1307. var buffer = 'data:' + contentType + ';base64,';
  1308. for (var i = 0, ii = data.length; i < ii; i += 3) {
  1309. var b1 = data[i] & 0xFF;
  1310. var b2 = data[i + 1] & 0xFF;
  1311. var b3 = data[i + 2] & 0xFF;
  1312. var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
  1313. var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
  1314. var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
  1315. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1316. }
  1317. return buffer;
  1318. };
  1319. })();
  1320. function MessageHandler(name, comObj) {
  1321. this.name = name;
  1322. this.comObj = comObj;
  1323. this.callbackIndex = 1;
  1324. this.postMessageTransfers = true;
  1325. var callbacksCapabilities = this.callbacksCapabilities = {};
  1326. var ah = this.actionHandler = {};
  1327. ah['console_log'] = [function ahConsoleLog(data) {
  1328. console.log.apply(console, data);
  1329. }];
  1330. ah['console_error'] = [function ahConsoleError(data) {
  1331. console.error.apply(console, data);
  1332. }];
  1333. ah['_unsupported_feature'] = [function ah_unsupportedFeature(data) {
  1334. UnsupportedManager.notify(data);
  1335. }];
  1336. comObj.onmessage = function messageHandlerComObjOnMessage(event) {
  1337. var data = event.data;
  1338. if (data.isReply) {
  1339. var callbackId = data.callbackId;
  1340. if (data.callbackId in callbacksCapabilities) {
  1341. var callback = callbacksCapabilities[callbackId];
  1342. delete callbacksCapabilities[callbackId];
  1343. if ('error' in data) {
  1344. callback.reject(data.error);
  1345. } else {
  1346. callback.resolve(data.data);
  1347. }
  1348. } else {
  1349. error('Cannot resolve callback ' + callbackId);
  1350. }
  1351. } else if (data.action in ah) {
  1352. var action = ah[data.action];
  1353. if (data.callbackId) {
  1354. Promise.resolve().then(function () {
  1355. return action[0].call(action[1], data.data);
  1356. }).then(function (result) {
  1357. comObj.postMessage({
  1358. isReply: true,
  1359. callbackId: data.callbackId,
  1360. data: result
  1361. });
  1362. }, function (reason) {
  1363. comObj.postMessage({
  1364. isReply: true,
  1365. callbackId: data.callbackId,
  1366. error: reason
  1367. });
  1368. });
  1369. } else {
  1370. action[0].call(action[1], data.data);
  1371. }
  1372. } else {
  1373. error('Unknown action from worker: ' + data.action);
  1374. }
  1375. };
  1376. }
  1377. MessageHandler.prototype = {
  1378. on: function messageHandlerOn(actionName, handler, scope) {
  1379. var ah = this.actionHandler;
  1380. if (ah[actionName]) {
  1381. error('There is already an actionName called "' + actionName + '"');
  1382. }
  1383. ah[actionName] = [handler, scope];
  1384. },
  1385. /**
  1386. * Sends a message to the comObj to invoke the action with the supplied data.
  1387. * @param {String} actionName Action to call.
  1388. * @param {JSON} data JSON data to send.
  1389. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
  1390. */
  1391. send: function messageHandlerSend(actionName, data, transfers) {
  1392. var message = {
  1393. action: actionName,
  1394. data: data
  1395. };
  1396. this.postMessage(message, transfers);
  1397. },
  1398. /**
  1399. * Sends a message to the comObj to invoke the action with the supplied data.
  1400. * Expects that other side will callback with the response.
  1401. * @param {String} actionName Action to call.
  1402. * @param {JSON} data JSON data to send.
  1403. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
  1404. * @returns {Promise} Promise to be resolved with response data.
  1405. */
  1406. sendWithPromise:
  1407. function messageHandlerSendWithPromise(actionName, data, transfers) {
  1408. var callbackId = this.callbackIndex++;
  1409. var message = {
  1410. action: actionName,
  1411. data: data,
  1412. callbackId: callbackId
  1413. };
  1414. var capability = createPromiseCapability();
  1415. this.callbacksCapabilities[callbackId] = capability;
  1416. try {
  1417. this.postMessage(message, transfers);
  1418. } catch (e) {
  1419. capability.reject(e);
  1420. }
  1421. return capability.promise;
  1422. },
  1423. /**
  1424. * Sends raw message to the comObj.
  1425. * @private
  1426. * @param message {Object} Raw message.
  1427. * @param transfers List of transfers/ArrayBuffers, or undefined.
  1428. */
  1429. postMessage: function (message, transfers) {
  1430. if (transfers && this.postMessageTransfers) {
  1431. this.comObj.postMessage(message, transfers);
  1432. } else {
  1433. this.comObj.postMessage(message);
  1434. }
  1435. }
  1436. };
  1437. function loadJpegStream(id, imageUrl, objs) {
  1438. var img = new Image();
  1439. img.onload = (function loadJpegStream_onloadClosure() {
  1440. objs.resolve(id, img);
  1441. });
  1442. img.onerror = (function loadJpegStream_onerrorClosure() {
  1443. objs.resolve(id, null);
  1444. warn('Error during JPEG image loading');
  1445. });
  1446. img.src = imageUrl;
  1447. }
  1448. /**
  1449. * The maximum allowed image size in total pixels e.g. width * height. Images
  1450. * above this value will not be drawn. Use -1 for no limit.
  1451. * @var {number}
  1452. */
  1453. PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ?
  1454. -1 : PDFJS.maxImageSize);
  1455. /**
  1456. * The url of where the predefined Adobe CMaps are located. Include trailing
  1457. * slash.
  1458. * @var {string}
  1459. */
  1460. PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl);
  1461. /**
  1462. * Specifies if CMaps are binary packed.
  1463. * @var {boolean}
  1464. */
  1465. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  1466. /**
  1467. * By default fonts are converted to OpenType fonts and loaded via font face
  1468. * rules. If disabled, the font will be rendered using a built in font renderer
  1469. * that constructs the glyphs with primitive path commands.
  1470. * @var {boolean}
  1471. */
  1472. PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ?
  1473. false : PDFJS.disableFontFace);
  1474. /**
  1475. * Path for image resources, mainly for annotation icons. Include trailing
  1476. * slash.
  1477. * @var {string}
  1478. */
  1479. PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ?
  1480. '' : PDFJS.imageResourcesPath);
  1481. /**
  1482. * Disable the web worker and run all code on the main thread. This will happen
  1483. * automatically if the browser doesn't support workers or sending typed arrays
  1484. * to workers.
  1485. * @var {boolean}
  1486. */
  1487. PDFJS.disableWorker = (PDFJS.disableWorker === undefined ?
  1488. false : PDFJS.disableWorker);
  1489. /**
  1490. * Path and filename of the worker file. Required when the worker is enabled in
  1491. * development mode. If unspecified in the production build, the worker will be
  1492. * loaded based on the location of the pdf.js file.
  1493. * @var {string}
  1494. */
  1495. PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc);
  1496. /**
  1497. * Disable range request loading of PDF files. When enabled and if the server
  1498. * supports partial content requests then the PDF will be fetched in chunks.
  1499. * Enabled (false) by default.
  1500. * @var {boolean}
  1501. */
  1502. PDFJS.disableRange = (PDFJS.disableRange === undefined ?
  1503. false : PDFJS.disableRange);
  1504. /**
  1505. * Disable streaming of PDF file data. By default PDF.js attempts to load PDF
  1506. * in chunks. This default behavior can be disabled.
  1507. * @var {boolean}
  1508. */
  1509. PDFJS.disableStream = (PDFJS.disableStream === undefined ?
  1510. false : PDFJS.disableStream);
  1511. /**
  1512. * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js
  1513. * will automatically keep fetching more data even if it isn't needed to display
  1514. * the current page. This default behavior can be disabled.
  1515. *
  1516. * NOTE: It is also necessary to disable streaming, see above,
  1517. * in order for disabling of pre-fetching to work correctly.
  1518. * @var {boolean}
  1519. */
  1520. PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ?
  1521. false : PDFJS.disableAutoFetch);
  1522. /**
  1523. * Enables special hooks for debugging PDF.js.
  1524. * @var {boolean}
  1525. */
  1526. PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug);
  1527. /**
  1528. * Enables transfer usage in postMessage for ArrayBuffers.
  1529. * @var {boolean}
  1530. */
  1531. PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ?
  1532. true : PDFJS.postMessageTransfers);
  1533. /**
  1534. * Disables URL.createObjectURL usage.
  1535. * @var {boolean}
  1536. */
  1537. PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ?
  1538. false : PDFJS.disableCreateObjectURL);
  1539. /**
  1540. * Disables WebGL usage.
  1541. * @var {boolean}
  1542. */
  1543. PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ?
  1544. true : PDFJS.disableWebGL);
  1545. /**
  1546. * Disables fullscreen support, and by extension Presentation Mode,
  1547. * in browsers which support the fullscreen API.
  1548. * @var {boolean}
  1549. */
  1550. PDFJS.disableFullscreen = (PDFJS.disableFullscreen === undefined ?
  1551. false : PDFJS.disableFullscreen);
  1552. /**
  1553. * Enables CSS only zooming.
  1554. * @var {boolean}
  1555. */
  1556. PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ?
  1557. false : PDFJS.useOnlyCssZoom);
  1558. /**
  1559. * Controls the logging level.
  1560. * The constants from PDFJS.VERBOSITY_LEVELS should be used:
  1561. * - errors
  1562. * - warnings [default]
  1563. * - infos
  1564. * @var {number}
  1565. */
  1566. PDFJS.verbosity = (PDFJS.verbosity === undefined ?
  1567. PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity);
  1568. /**
  1569. * The maximum supported canvas size in total pixels e.g. width * height.
  1570. * The default value is 4096 * 4096. Use -1 for no limit.
  1571. * @var {number}
  1572. */
  1573. PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ?
  1574. 16777216 : PDFJS.maxCanvasPixels);
  1575. /**
  1576. * Opens external links in a new window if enabled. The default behavior opens
  1577. * external links in the PDF.js window.
  1578. * @var {boolean}
  1579. */
  1580. PDFJS.openExternalLinksInNewWindow = (
  1581. PDFJS.openExternalLinksInNewWindow === undefined ?
  1582. false : PDFJS.openExternalLinksInNewWindow);
  1583. /**
  1584. * Document initialization / loading parameters object.
  1585. *
  1586. * @typedef {Object} DocumentInitParameters
  1587. * @property {string} url - The URL of the PDF.
  1588. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays
  1589. * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,
  1590. * use atob() to convert it to a binary string first.
  1591. * @property {Object} httpHeaders - Basic authentication headers.
  1592. * @property {boolean} withCredentials - Indicates whether or not cross-site
  1593. * Access-Control requests should be made using credentials such as cookies
  1594. * or authorization headers. The default is false.
  1595. * @property {string} password - For decrypting password-protected PDFs.
  1596. * @property {TypedArray} initialData - A typed array with the first portion or
  1597. * all of the pdf data. Used by the extension since some data is already
  1598. * loaded before the switch to range requests.
  1599. * @property {number} length - The PDF file length. It's used for progress
  1600. * reports and range requests operations.
  1601. * @property {PDFDataRangeTransport} range
  1602. */
  1603. /**
  1604. * @typedef {Object} PDFDocumentStats
  1605. * @property {Array} streamTypes - Used stream types in the document (an item
  1606. * is set to true if specific stream ID was used in the document).
  1607. * @property {Array} fontTypes - Used font type in the document (an item is set
  1608. * to true if specific font ID was used in the document).
  1609. */
  1610. /**
  1611. * This is the main entry point for loading a PDF and interacting with it.
  1612. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  1613. * is used, which means it must follow the same origin rules that any XHR does
  1614. * e.g. No cross domain requests without CORS.
  1615. *
  1616. * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src
  1617. * Can be a url to where a PDF is located, a typed array (Uint8Array)
  1618. * already populated with data or parameter object.
  1619. *
  1620. * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used
  1621. * if you want to manually serve range requests for data in the PDF.
  1622. *
  1623. * @param {function} passwordCallback (deprecated) It is used to request a
  1624. * password if wrong or no password was provided. The callback receives two
  1625. * parameters: function that needs to be called with new password and reason
  1626. * (see {PasswordResponses}).
  1627. *
  1628. * @param {function} progressCallback (deprecated) It is used to be able to
  1629. * monitor the loading progress of the PDF file (necessary to implement e.g.
  1630. * a loading bar). The callback receives an {Object} with the properties:
  1631. * {number} loaded and {number} total.
  1632. *
  1633. * @return {PDFDocumentLoadingTask}
  1634. */
  1635. PDFJS.getDocument = function getDocument(src,
  1636. pdfDataRangeTransport,
  1637. passwordCallback,
  1638. progressCallback) {
  1639. var task = new PDFDocumentLoadingTask();
  1640. // Support of the obsolete arguments (for compatibility with API v1.0)
  1641. if (pdfDataRangeTransport) {
  1642. if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) {
  1643. // Not a PDFDataRangeTransport instance, trying to add missing properties.
  1644. pdfDataRangeTransport = Object.create(pdfDataRangeTransport);
  1645. pdfDataRangeTransport.length = src.length;
  1646. pdfDataRangeTransport.initialData = src.initialData;
  1647. }
  1648. src = Object.create(src);
  1649. src.range = pdfDataRangeTransport;
  1650. }
  1651. task.onPassword = passwordCallback || null;
  1652. task.onProgress = progressCallback || null;
  1653. var workerInitializedCapability, transport;
  1654. var source;
  1655. if (typeof src === 'string') {
  1656. source = { url: src };
  1657. } else if (isArrayBuffer(src)) {
  1658. source = { data: src };
  1659. } else if (src instanceof PDFDataRangeTransport) {
  1660. source = { range: src };
  1661. } else {
  1662. if (typeof src !== 'object') {
  1663. error('Invalid parameter in getDocument, need either Uint8Array, ' +
  1664. 'string or a parameter object');
  1665. }
  1666. if (!src.url && !src.data && !src.range) {
  1667. error('Invalid parameter object: need either .data, .range or .url');
  1668. }
  1669. source = src;
  1670. }
  1671. var params = {};
  1672. for (var key in source) {
  1673. if (key === 'url' && typeof window !== 'undefined') {
  1674. // The full path is required in the 'url' field.
  1675. params[key] = combineUrl(window.location.href, source[key]);
  1676. continue;
  1677. } else if (key === 'range') {
  1678. continue;
  1679. } else if (key === 'data' && !(source[key] instanceof Uint8Array)) {
  1680. // Converting string or array-like data to Uint8Array.
  1681. var pdfBytes = source[key];
  1682. if (typeof pdfBytes === 'string') {
  1683. params[key] = stringToBytes(pdfBytes);
  1684. } else if (typeof pdfBytes === 'object' && pdfBytes !== null &&
  1685. !isNaN(pdfBytes.length)) {
  1686. params[key] = new Uint8Array(pdfBytes);
  1687. } else {
  1688. error('Invalid PDF binary data: either typed array, string or ' +
  1689. 'array-like object is expected in the data property.');
  1690. }
  1691. continue;
  1692. }
  1693. params[key] = source[key];
  1694. }
  1695. workerInitializedCapability = createPromiseCapability();
  1696. transport = new WorkerTransport(workerInitializedCapability, source.range);
  1697. workerInitializedCapability.promise.then(function transportInitialized() {
  1698. transport.fetchDocument(task, params);
  1699. });
  1700. return task;
  1701. };
  1702. /**
  1703. * PDF document loading operation.
  1704. * @class
  1705. */
  1706. var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {
  1707. /** @constructs PDFDocumentLoadingTask */
  1708. function PDFDocumentLoadingTask() {
  1709. this._capability = createPromiseCapability();
  1710. /**
  1711. * Callback to request a password if wrong or no password was provided.
  1712. * The callback receives two parameters: function that needs to be called
  1713. * with new password and reason (see {PasswordResponses}).
  1714. */
  1715. this.onPassword = null;
  1716. /**
  1717. * Callback to be able to monitor the loading progress of the PDF file
  1718. * (necessary to implement e.g. a loading bar). The callback receives
  1719. * an {Object} with the properties: {number} loaded and {number} total.
  1720. */
  1721. this.onProgress = null;
  1722. }
  1723. PDFDocumentLoadingTask.prototype =
  1724. /** @lends PDFDocumentLoadingTask.prototype */ {
  1725. /**
  1726. * @return {Promise}
  1727. */
  1728. get promise() {
  1729. return this._capability.promise;
  1730. },
  1731. // TODO add cancel or abort method
  1732. /**
  1733. * Registers callbacks to indicate the document loading completion.
  1734. *
  1735. * @param {function} onFulfilled The callback for the loading completion.
  1736. * @param {function} onRejected The callback for the loading failure.
  1737. * @return {Promise} A promise that is resolved after the onFulfilled or
  1738. * onRejected callback.
  1739. */
  1740. then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) {
  1741. return this.promise.then.apply(this.promise, arguments);
  1742. }
  1743. };
  1744. return PDFDocumentLoadingTask;
  1745. })();
  1746. /**
  1747. * Abstract class to support range requests file loading.
  1748. * @class
  1749. */
  1750. var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() {
  1751. /**
  1752. * @constructs PDFDataRangeTransport
  1753. * @param {number} length
  1754. * @param {Uint8Array} initialData
  1755. */
  1756. function PDFDataRangeTransport(length, initialData) {
  1757. this.length = length;
  1758. this.initialData = initialData;
  1759. this._rangeListeners = [];
  1760. this._progressListeners = [];
  1761. this._progressiveReadListeners = [];
  1762. this._readyCapability = createPromiseCapability();
  1763. }
  1764. PDFDataRangeTransport.prototype =
  1765. /** @lends PDFDataRangeTransport.prototype */ {
  1766. addRangeListener:
  1767. function PDFDataRangeTransport_addRangeListener(listener) {
  1768. this._rangeListeners.push(listener);
  1769. },
  1770. addProgressListener:
  1771. function PDFDataRangeTransport_addProgressListener(listener) {
  1772. this._progressListeners.push(listener);
  1773. },
  1774. addProgressiveReadListener:
  1775. function PDFDataRangeTransport_addProgressiveReadListener(listener) {
  1776. this._progressiveReadListeners.push(listener);
  1777. },
  1778. onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {
  1779. var listeners = this._rangeListeners;
  1780. for (var i = 0, n = listeners.length; i < n; ++i) {
  1781. listeners[i](begin, chunk);
  1782. }
  1783. },
  1784. onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {
  1785. this._readyCapability.promise.then(function () {
  1786. var listeners = this._progressListeners;
  1787. for (var i = 0, n = listeners.length; i < n; ++i) {
  1788. listeners[i](loaded);
  1789. }
  1790. }.bind(this));
  1791. },
  1792. onDataProgressiveRead:
  1793. function PDFDataRangeTransport_onDataProgress(chunk) {
  1794. this._readyCapability.promise.then(function () {
  1795. var listeners = this._progressiveReadListeners;
  1796. for (var i = 0, n = listeners.length; i < n; ++i) {
  1797. listeners[i](chunk);
  1798. }
  1799. }.bind(this));
  1800. },
  1801. transportReady: function PDFDataRangeTransport_transportReady() {
  1802. this._readyCapability.resolve();
  1803. },
  1804. requestDataRange:
  1805. function PDFDataRangeTransport_requestDataRange(begin, end) {
  1806. throw new Error('Abstract method PDFDataRangeTransport.requestDataRange');
  1807. }
  1808. };
  1809. return PDFDataRangeTransport;
  1810. })();
  1811. PDFJS.PDFDataRangeTransport = PDFDataRangeTransport;
  1812. /**
  1813. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  1814. * properties that can be read synchronously.
  1815. * @class
  1816. */
  1817. var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
  1818. function PDFDocumentProxy(pdfInfo, transport) {
  1819. this.pdfInfo = pdfInfo;
  1820. this.transport = transport;
  1821. }
  1822. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
  1823. /**
  1824. * @return {number} Total number of pages the PDF contains.
  1825. */
  1826. get numPages() {
  1827. return this.pdfInfo.numPages;
  1828. },
  1829. /**
  1830. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  1831. * unique.
  1832. */
  1833. get fingerprint() {
  1834. return this.pdfInfo.fingerprint;
  1835. },
  1836. /**
  1837. * @param {number} pageNumber The page number to get. The first page is 1.
  1838. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  1839. * object.
  1840. */
  1841. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  1842. return this.transport.getPage(pageNumber);
  1843. },
  1844. /**
  1845. * @param {{num: number, gen: number}} ref The page reference. Must have
  1846. * the 'num' and 'gen' properties.
  1847. * @return {Promise} A promise that is resolved with the page index that is
  1848. * associated with the reference.
  1849. */
  1850. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  1851. return this.transport.getPageIndex(ref);
  1852. },
  1853. /**
  1854. * @return {Promise} A promise that is resolved with a lookup table for
  1855. * mapping named destinations to reference numbers.
  1856. *
  1857. * This can be slow for large documents: use getDestination instead
  1858. */
  1859. getDestinations: function PDFDocumentProxy_getDestinations() {
  1860. return this.transport.getDestinations();
  1861. },
  1862. /**
  1863. * @param {string} id The named destination to get.
  1864. * @return {Promise} A promise that is resolved with all information
  1865. * of the given named destination.
  1866. */
  1867. getDestination: function PDFDocumentProxy_getDestination(id) {
  1868. return this.transport.getDestination(id);
  1869. },
  1870. /**
  1871. * @return {Promise} A promise that is resolved with a lookup table for
  1872. * mapping named attachments to their content.
  1873. */
  1874. getAttachments: function PDFDocumentProxy_getAttachments() {
  1875. return this.transport.getAttachments();
  1876. },
  1877. /**
  1878. * @return {Promise} A promise that is resolved with an array of all the
  1879. * JavaScript strings in the name tree.
  1880. */
  1881. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  1882. return this.transport.getJavaScript();
  1883. },
  1884. /**
  1885. * @return {Promise} A promise that is resolved with an {Array} that is a
  1886. * tree outline (if it has one) of the PDF. The tree is in the format of:
  1887. * [
  1888. * {
  1889. * title: string,
  1890. * bold: boolean,
  1891. * italic: boolean,
  1892. * color: rgb array,
  1893. * dest: dest obj,
  1894. * items: array of more items like this
  1895. * },
  1896. * ...
  1897. * ].
  1898. */
  1899. getOutline: function PDFDocumentProxy_getOutline() {
  1900. return this.transport.getOutline();
  1901. },
  1902. /**
  1903. * @return {Promise} A promise that is resolved with an {Object} that has
  1904. * info and metadata properties. Info is an {Object} filled with anything
  1905. * available in the information dictionary and similarly metadata is a
  1906. * {Metadata} object with information from the metadata section of the PDF.
  1907. */
  1908. getMetadata: function PDFDocumentProxy_getMetadata() {
  1909. return this.transport.getMetadata();
  1910. },
  1911. /**
  1912. * @return {Promise} A promise that is resolved with a TypedArray that has
  1913. * the raw data from the PDF.
  1914. */
  1915. getData: function PDFDocumentProxy_getData() {
  1916. return this.transport.getData();
  1917. },
  1918. /**
  1919. * @return {Promise} A promise that is resolved when the document's data
  1920. * is loaded. It is resolved with an {Object} that contains the length
  1921. * property that indicates size of the PDF data in bytes.
  1922. */
  1923. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  1924. return this.transport.downloadInfoCapability.promise;
  1925. },
  1926. /**
  1927. * @return {Promise} A promise this is resolved with current stats about
  1928. * document structures (see {@link PDFDocumentStats}).
  1929. */
  1930. getStats: function PDFDocumentProxy_getStats() {
  1931. return this.transport.getStats();
  1932. },
  1933. /**
  1934. * Cleans up resources allocated by the document, e.g. created @font-face.
  1935. */
  1936. cleanup: function PDFDocumentProxy_cleanup() {
  1937. this.transport.startCleanup();
  1938. },
  1939. /**
  1940. * Destroys current document instance and terminates worker.
  1941. */
  1942. destroy: function PDFDocumentProxy_destroy() {
  1943. this.transport.destroy();
  1944. }
  1945. };
  1946. return PDFDocumentProxy;
  1947. })();
  1948. /**
  1949. * Page text content.
  1950. *
  1951. * @typedef {Object} TextContent
  1952. * @property {array} items - array of {@link TextItem}
  1953. * @property {Object} styles - {@link TextStyles} objects, indexed by font
  1954. * name.
  1955. */
  1956. /**
  1957. * Page text content part.
  1958. *
  1959. * @typedef {Object} TextItem
  1960. * @property {string} str - text content.
  1961. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  1962. * @property {array} transform - transformation matrix.
  1963. * @property {number} width - width in device space.
  1964. * @property {number} height - height in device space.
  1965. * @property {string} fontName - font name used by pdf.js for converted font.
  1966. */
  1967. /**
  1968. * Text style.
  1969. *
  1970. * @typedef {Object} TextStyle
  1971. * @property {number} ascent - font ascent.
  1972. * @property {number} descent - font descent.
  1973. * @property {boolean} vertical - text is in vertical mode.
  1974. * @property {string} fontFamily - possible font family
  1975. */
  1976. /**
  1977. * Page render parameters.
  1978. *
  1979. * @typedef {Object} RenderParameters
  1980. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  1981. * @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by
  1982. * calling of PDFPage.getViewport method.
  1983. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  1984. * (default value is 'display').
  1985. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  1986. * endLayout and appendImage functions.
  1987. * @property {function} continueCallback - (deprecated) A function that will be
  1988. * called each time the rendering is paused. To continue
  1989. * rendering call the function that is the first argument
  1990. * to the callback.
  1991. */
  1992. /**
  1993. * PDF page operator list.
  1994. *
  1995. * @typedef {Object} PDFOperatorList
  1996. * @property {Array} fnArray - Array containing the operator functions.
  1997. * @property {Array} argsArray - Array containing the arguments of the
  1998. * functions.
  1999. */
  2000. /**
  2001. * Proxy to a PDFPage in the worker thread.
  2002. * @class
  2003. */
  2004. var PDFPageProxy = (function PDFPageProxyClosure() {
  2005. function PDFPageProxy(pageIndex, pageInfo, transport) {
  2006. this.pageIndex = pageIndex;
  2007. this.pageInfo = pageInfo;
  2008. this.transport = transport;
  2009. this.stats = new StatTimer();
  2010. this.stats.enabled = !!globalScope.PDFJS.enableStats;
  2011. this.commonObjs = transport.commonObjs;
  2012. this.objs = new PDFObjects();
  2013. this.cleanupAfterRender = false;
  2014. this.pendingDestroy = false;
  2015. this.intentStates = {};
  2016. }
  2017. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
  2018. /**
  2019. * @return {number} Page number of the page. First page is 1.
  2020. */
  2021. get pageNumber() {
  2022. return this.pageIndex + 1;
  2023. },
  2024. /**
  2025. * @return {number} The number of degrees the page is rotated clockwise.
  2026. */
  2027. get rotate() {
  2028. return this.pageInfo.rotate;
  2029. },
  2030. /**
  2031. * @return {Object} The reference that points to this page. It has 'num' and
  2032. * 'gen' properties.
  2033. */
  2034. get ref() {
  2035. return this.pageInfo.ref;
  2036. },
  2037. /**
  2038. * @return {Array} An array of the visible portion of the PDF page in the
  2039. * user space units - [x1, y1, x2, y2].
  2040. */
  2041. get view() {
  2042. return this.pageInfo.view;
  2043. },
  2044. /**
  2045. * @param {number} scale The desired scale of the viewport.
  2046. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  2047. * defaults to the page rotation.
  2048. * @return {PDFJS.PageViewport} Contains 'width' and 'height' properties
  2049. * along with transforms required for rendering.
  2050. */
  2051. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  2052. if (arguments.length < 2) {
  2053. rotate = this.rotate;
  2054. }
  2055. return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0);
  2056. },
  2057. /**
  2058. * @return {Promise} A promise that is resolved with an {Array} of the
  2059. * annotation objects.
  2060. */
  2061. getAnnotations: function PDFPageProxy_getAnnotations() {
  2062. if (this.annotationsPromise) {
  2063. return this.annotationsPromise;
  2064. }
  2065. var promise = this.transport.getAnnotations(this.pageIndex);
  2066. this.annotationsPromise = promise;
  2067. return promise;
  2068. },
  2069. /**
  2070. * Begins the process of rendering a page to the desired context.
  2071. * @param {RenderParameters} params Page render parameters.
  2072. * @return {RenderTask} An object that contains the promise, which
  2073. * is resolved when the page finishes rendering.
  2074. */
  2075. render: function PDFPageProxy_render(params) {
  2076. var stats = this.stats;
  2077. stats.time('Overall');
  2078. // If there was a pending destroy cancel it so no cleanup happens during
  2079. // this call to render.
  2080. this.pendingDestroy = false;
  2081. var renderingIntent = (params.intent === 'print' ? 'print' : 'display');
  2082. if (!this.intentStates[renderingIntent]) {
  2083. this.intentStates[renderingIntent] = {};
  2084. }
  2085. var intentState = this.intentStates[renderingIntent];
  2086. // If there's no displayReadyCapability yet, then the operatorList
  2087. // was never requested before. Make the request and create the promise.
  2088. if (!intentState.displayReadyCapability) {
  2089. intentState.receivingOperatorList = true;
  2090. intentState.displayReadyCapability = createPromiseCapability();
  2091. intentState.operatorList = {
  2092. fnArray: [],
  2093. argsArray: [],
  2094. lastChunk: false
  2095. };
  2096. this.stats.time('Page Request');
  2097. this.transport.messageHandler.send('RenderPageRequest', {
  2098. pageIndex: this.pageNumber - 1,
  2099. intent: renderingIntent
  2100. });
  2101. }
  2102. var internalRenderTask = new InternalRenderTask(complete, params,
  2103. this.objs,
  2104. this.commonObjs,
  2105. intentState.operatorList,
  2106. this.pageNumber);
  2107. if (!intentState.renderTasks) {
  2108. intentState.renderTasks = [];
  2109. }
  2110. intentState.renderTasks.push(internalRenderTask);
  2111. var renderTask = internalRenderTask.task;
  2112. // Obsolete parameter support
  2113. if (params.continueCallback) {
  2114. renderTask.onContinue = params.continueCallback;
  2115. }
  2116. var self = this;
  2117. intentState.displayReadyCapability.promise.then(
  2118. function pageDisplayReadyPromise(transparency) {
  2119. if (self.pendingDestroy) {
  2120. complete();
  2121. return;
  2122. }
  2123. stats.time('Rendering');
  2124. internalRenderTask.initalizeGraphics(transparency);
  2125. internalRenderTask.operatorListChanged();
  2126. },
  2127. function pageDisplayReadPromiseError(reason) {
  2128. complete(reason);
  2129. }
  2130. );
  2131. function complete(error) {
  2132. var i = intentState.renderTasks.indexOf(internalRenderTask);
  2133. if (i >= 0) {
  2134. intentState.renderTasks.splice(i, 1);
  2135. }
  2136. if (self.cleanupAfterRender) {
  2137. self.pendingDestroy = true;
  2138. }
  2139. self._tryDestroy();
  2140. if (error) {
  2141. internalRenderTask.capability.reject(error);
  2142. } else {
  2143. internalRenderTask.capability.resolve();
  2144. }
  2145. stats.timeEnd('Rendering');
  2146. stats.timeEnd('Overall');
  2147. }
  2148. return renderTask;
  2149. },
  2150. /**
  2151. * @return {Promise} A promise resolved with an {@link PDFOperatorList}
  2152. * object that represents page's operator list.
  2153. */
  2154. getOperatorList: function PDFPageProxy_getOperatorList() {
  2155. function operatorListChanged() {
  2156. if (intentState.operatorList.lastChunk) {
  2157. intentState.opListReadCapability.resolve(intentState.operatorList);
  2158. }
  2159. }
  2160. var renderingIntent = 'oplist';
  2161. if (!this.intentStates[renderingIntent]) {
  2162. this.intentStates[renderingIntent] = {};
  2163. }
  2164. var intentState = this.intentStates[renderingIntent];
  2165. if (!intentState.opListReadCapability) {
  2166. var opListTask = {};
  2167. opListTask.operatorListChanged = operatorListChanged;
  2168. intentState.receivingOperatorList = true;
  2169. intentState.opListReadCapability = createPromiseCapability();
  2170. intentState.renderTasks = [];
  2171. intentState.renderTasks.push(opListTask);
  2172. intentState.operatorList = {
  2173. fnArray: [],
  2174. argsArray: [],
  2175. lastChunk: false
  2176. };
  2177. this.transport.messageHandler.send('RenderPageRequest', {
  2178. pageIndex: this.pageIndex,
  2179. intent: renderingIntent
  2180. });
  2181. }
  2182. return intentState.opListReadCapability.promise;
  2183. },
  2184. /**
  2185. * @return {Promise} That is resolved a {@link TextContent}
  2186. * object that represent the page text content.
  2187. */
  2188. getTextContent: function PDFPageProxy_getTextContent() {
  2189. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  2190. pageIndex: this.pageNumber - 1
  2191. });
  2192. },
  2193. /**
  2194. * Destroys resources allocated by the page.
  2195. */
  2196. destroy: function PDFPageProxy_destroy() {
  2197. this.pendingDestroy = true;
  2198. this._tryDestroy();
  2199. },
  2200. /**
  2201. * For internal use only. Attempts to clean up if rendering is in a state
  2202. * where that's possible.
  2203. * @ignore
  2204. */
  2205. _tryDestroy: function PDFPageProxy__destroy() {
  2206. if (!this.pendingDestroy ||
  2207. Object.keys(this.intentStates).some(function(intent) {
  2208. var intentState = this.intentStates[intent];
  2209. return (intentState.renderTasks.length !== 0 ||
  2210. intentState.receivingOperatorList);
  2211. }, this)) {
  2212. return;
  2213. }
  2214. Object.keys(this.intentStates).forEach(function(intent) {
  2215. delete this.intentStates[intent];
  2216. }, this);
  2217. this.objs.clear();
  2218. this.annotationsPromise = null;
  2219. this.pendingDestroy = false;
  2220. },
  2221. /**
  2222. * For internal use only.
  2223. * @ignore
  2224. */
  2225. _startRenderPage: function PDFPageProxy_startRenderPage(transparency,
  2226. intent) {
  2227. var intentState = this.intentStates[intent];
  2228. // TODO Refactor RenderPageRequest to separate rendering
  2229. // and operator list logic
  2230. if (intentState.displayReadyCapability) {
  2231. intentState.displayReadyCapability.resolve(transparency);
  2232. }
  2233. },
  2234. /**
  2235. * For internal use only.
  2236. * @ignore
  2237. */
  2238. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk,
  2239. intent) {
  2240. var intentState = this.intentStates[intent];
  2241. var i, ii;
  2242. // Add the new chunk to the current operator list.
  2243. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  2244. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  2245. intentState.operatorList.argsArray.push(
  2246. operatorListChunk.argsArray[i]);
  2247. }
  2248. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  2249. // Notify all the rendering tasks there are more operators to be consumed.
  2250. for (i = 0; i < intentState.renderTasks.length; i++) {
  2251. intentState.renderTasks[i].operatorListChanged();
  2252. }
  2253. if (operatorListChunk.lastChunk) {
  2254. intentState.receivingOperatorList = false;
  2255. this._tryDestroy();
  2256. }
  2257. }
  2258. };
  2259. return PDFPageProxy;
  2260. })();
  2261. /**
  2262. * For internal use only.
  2263. * @ignore
  2264. */
  2265. var WorkerTransport = (function WorkerTransportClosure() {
  2266. function WorkerTransport(workerInitializedCapability, pdfDataRangeTransport) {
  2267. this.pdfDataRangeTransport = pdfDataRangeTransport;
  2268. this.workerInitializedCapability = workerInitializedCapability;
  2269. this.commonObjs = new PDFObjects();
  2270. this.loadingTask = null;
  2271. this.pageCache = [];
  2272. this.pagePromises = [];
  2273. this.downloadInfoCapability = createPromiseCapability();
  2274. // If worker support isn't disabled explicit and the browser has worker
  2275. // support, create a new web worker and test if it/the browser fullfills
  2276. // all requirements to run parts of pdf.js in a web worker.
  2277. // Right now, the requirement is, that an Uint8Array is still an Uint8Array
  2278. // as it arrives on the worker. Chrome added this with version 15.
  2279. //#if !SINGLE_FILE
  2280. if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') {
  2281. var workerSrc = PDFJS.workerSrc;
  2282. if (!workerSrc) {
  2283. error('No PDFJS.workerSrc specified');
  2284. }
  2285. try {
  2286. // Some versions of FF can't create a worker on localhost, see:
  2287. // https://bugzilla.mozilla.org/show_bug.cgi?id=683280
  2288. var worker = new Worker(workerSrc);
  2289. var messageHandler = new MessageHandler('main', worker);
  2290. this.messageHandler = messageHandler;
  2291. messageHandler.on('test', function transportTest(data) {
  2292. var supportTypedArray = data && data.supportTypedArray;
  2293. if (supportTypedArray) {
  2294. this.worker = worker;
  2295. if (!data.supportTransfers) {
  2296. PDFJS.postMessageTransfers = false;
  2297. }
  2298. this.setupMessageHandler(messageHandler);
  2299. workerInitializedCapability.resolve();
  2300. } else {
  2301. this.setupFakeWorker();
  2302. }
  2303. }.bind(this));
  2304. var testObj = new Uint8Array([PDFJS.postMessageTransfers ? 255 : 0]);
  2305. // Some versions of Opera throw a DATA_CLONE_ERR on serializing the
  2306. // typed array. Also, checking if we can use transfers.
  2307. try {
  2308. messageHandler.send('test', testObj, [testObj.buffer]);
  2309. } catch (ex) {
  2310. info('Cannot use postMessage transfers');
  2311. testObj[0] = 0;
  2312. messageHandler.send('test', testObj);
  2313. }
  2314. return;
  2315. } catch (e) {
  2316. info('The worker has been disabled.');
  2317. }
  2318. }
  2319. //#endif
  2320. // Either workers are disabled, not supported or have thrown an exception.
  2321. // Thus, we fallback to a faked worker.
  2322. this.setupFakeWorker();
  2323. }
  2324. WorkerTransport.prototype = {
  2325. destroy: function WorkerTransport_destroy() {
  2326. this.pageCache = [];
  2327. this.pagePromises = [];
  2328. var self = this;
  2329. this.messageHandler.sendWithPromise('Terminate', null).then(function () {
  2330. FontLoader.clear();
  2331. if (self.worker) {
  2332. self.worker.terminate();
  2333. }
  2334. });
  2335. },
  2336. setupFakeWorker: function WorkerTransport_setupFakeWorker() {
  2337. globalScope.PDFJS.disableWorker = true;
  2338. if (!PDFJS.fakeWorkerFilesLoadedCapability) {
  2339. PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability();
  2340. // In the developer build load worker_loader which in turn loads all the
  2341. // other files and resolves the promise. In production only the
  2342. // pdf.worker.js file is needed.
  2343. //#if !PRODUCTION
  2344. Util.loadScript(PDFJS.workerSrc);
  2345. //#endif
  2346. //#if PRODUCTION && SINGLE_FILE
  2347. // PDFJS.fakeWorkerFilesLoadedCapability.resolve();
  2348. //#endif
  2349. //#if PRODUCTION && !SINGLE_FILE
  2350. // Util.loadScript(PDFJS.workerSrc, function() {
  2351. // PDFJS.fakeWorkerFilesLoadedCapability.resolve();
  2352. // });
  2353. //#endif
  2354. }
  2355. PDFJS.fakeWorkerFilesLoadedCapability.promise.then(function () {
  2356. warn('Setting up fake worker.');
  2357. // If we don't use a worker, just post/sendMessage to the main thread.
  2358. var fakeWorker = {
  2359. postMessage: function WorkerTransport_postMessage(obj) {
  2360. fakeWorker.onmessage({data: obj});
  2361. },
  2362. terminate: function WorkerTransport_terminate() {}
  2363. };
  2364. var messageHandler = new MessageHandler('main', fakeWorker);
  2365. this.setupMessageHandler(messageHandler);
  2366. // If the main thread is our worker, setup the handling for the messages
  2367. // the main thread sends to it self.
  2368. PDFJS.WorkerMessageHandler.setup(messageHandler);
  2369. this.workerInitializedCapability.resolve();
  2370. }.bind(this));
  2371. },
  2372. setupMessageHandler:
  2373. function WorkerTransport_setupMessageHandler(messageHandler) {
  2374. this.messageHandler = messageHandler;
  2375. function updatePassword(password) {
  2376. messageHandler.send('UpdatePassword', password);
  2377. }
  2378. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  2379. if (pdfDataRangeTransport) {
  2380. pdfDataRangeTransport.addRangeListener(function(begin, chunk) {
  2381. messageHandler.send('OnDataRange', {
  2382. begin: begin,
  2383. chunk: chunk
  2384. });
  2385. });
  2386. pdfDataRangeTransport.addProgressListener(function(loaded) {
  2387. messageHandler.send('OnDataProgress', {
  2388. loaded: loaded
  2389. });
  2390. });
  2391. pdfDataRangeTransport.addProgressiveReadListener(function(chunk) {
  2392. messageHandler.send('OnDataRange', {
  2393. chunk: chunk
  2394. });
  2395. });
  2396. messageHandler.on('RequestDataRange',
  2397. function transportDataRange(data) {
  2398. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  2399. }, this);
  2400. }
  2401. messageHandler.on('GetDoc', function transportDoc(data) {
  2402. var pdfInfo = data.pdfInfo;
  2403. this.numPages = data.pdfInfo.numPages;
  2404. var pdfDocument = new PDFDocumentProxy(pdfInfo, this);
  2405. this.pdfDocument = pdfDocument;
  2406. this.loadingTask._capability.resolve(pdfDocument);
  2407. }, this);
  2408. messageHandler.on('NeedPassword',
  2409. function transportNeedPassword(exception) {
  2410. var loadingTask = this.loadingTask;
  2411. if (loadingTask.onPassword) {
  2412. return loadingTask.onPassword(updatePassword,
  2413. PasswordResponses.NEED_PASSWORD);
  2414. }
  2415. loadingTask._capability.reject(
  2416. new PasswordException(exception.message, exception.code));
  2417. }, this);
  2418. messageHandler.on('IncorrectPassword',
  2419. function transportIncorrectPassword(exception) {
  2420. var loadingTask = this.loadingTask;
  2421. if (loadingTask.onPassword) {
  2422. return loadingTask.onPassword(updatePassword,
  2423. PasswordResponses.INCORRECT_PASSWORD);
  2424. }
  2425. loadingTask._capability.reject(
  2426. new PasswordException(exception.message, exception.code));
  2427. }, this);
  2428. messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
  2429. this.loadingTask._capability.reject(
  2430. new InvalidPDFException(exception.message));
  2431. }, this);
  2432. messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
  2433. this.loadingTask._capability.reject(
  2434. new MissingPDFException(exception.message));
  2435. }, this);
  2436. messageHandler.on('UnexpectedResponse',
  2437. function transportUnexpectedResponse(exception) {
  2438. this.loadingTask._capability.reject(
  2439. new UnexpectedResponseException(exception.message, exception.status));
  2440. }, this);
  2441. messageHandler.on('UnknownError',
  2442. function transportUnknownError(exception) {
  2443. this.loadingTask._capability.reject(
  2444. new UnknownErrorException(exception.message, exception.details));
  2445. }, this);
  2446. messageHandler.on('DataLoaded', function transportPage(data) {
  2447. this.downloadInfoCapability.resolve(data);
  2448. }, this);
  2449. messageHandler.on('PDFManagerReady', function transportPage(data) {
  2450. if (this.pdfDataRangeTransport) {
  2451. this.pdfDataRangeTransport.transportReady();
  2452. }
  2453. }, this);
  2454. messageHandler.on('StartRenderPage', function transportRender(data) {
  2455. var page = this.pageCache[data.pageIndex];
  2456. page.stats.timeEnd('Page Request');
  2457. page._startRenderPage(data.transparency, data.intent);
  2458. }, this);
  2459. messageHandler.on('RenderPageChunk', function transportRender(data) {
  2460. var page = this.pageCache[data.pageIndex];
  2461. page._renderPageChunk(data.operatorList, data.intent);
  2462. }, this);
  2463. messageHandler.on('commonobj', function transportObj(data) {
  2464. var id = data[0];
  2465. var type = data[1];
  2466. if (this.commonObjs.hasData(id)) {
  2467. return;
  2468. }
  2469. switch (type) {
  2470. case 'Font':
  2471. var exportedData = data[2];
  2472. var font;
  2473. if ('error' in exportedData) {
  2474. var error = exportedData.error;
  2475. warn('Error during font loading: ' + error);
  2476. this.commonObjs.resolve(id, error);
  2477. break;
  2478. } else {
  2479. font = new FontFaceObject(exportedData);
  2480. }
  2481. FontLoader.bind(
  2482. [font],
  2483. function fontReady(fontObjs) {
  2484. this.commonObjs.resolve(id, font);
  2485. }.bind(this)
  2486. );
  2487. break;
  2488. case 'FontPath':
  2489. this.commonObjs.resolve(id, data[2]);
  2490. break;
  2491. default:
  2492. error('Got unknown common object type ' + type);
  2493. }
  2494. }, this);
  2495. messageHandler.on('obj', function transportObj(data) {
  2496. var id = data[0];
  2497. var pageIndex = data[1];
  2498. var type = data[2];
  2499. var pageProxy = this.pageCache[pageIndex];
  2500. var imageData;
  2501. if (pageProxy.objs.hasData(id)) {
  2502. return;
  2503. }
  2504. switch (type) {
  2505. case 'JpegStream':
  2506. imageData = data[3];
  2507. loadJpegStream(id, imageData, pageProxy.objs);
  2508. break;
  2509. case 'Image':
  2510. imageData = data[3];
  2511. pageProxy.objs.resolve(id, imageData);
  2512. // heuristics that will allow not to store large data
  2513. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  2514. if (imageData && 'data' in imageData &&
  2515. imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  2516. pageProxy.cleanupAfterRender = true;
  2517. }
  2518. break;
  2519. default:
  2520. error('Got unknown object type ' + type);
  2521. }
  2522. }, this);
  2523. messageHandler.on('DocProgress', function transportDocProgress(data) {
  2524. var loadingTask = this.loadingTask;
  2525. if (loadingTask.onProgress) {
  2526. loadingTask.onProgress({
  2527. loaded: data.loaded,
  2528. total: data.total
  2529. });
  2530. }
  2531. }, this);
  2532. messageHandler.on('PageError', function transportError(data) {
  2533. var page = this.pageCache[data.pageNum - 1];
  2534. var intentState = page.intentStates[data.intent];
  2535. if (intentState.displayReadyCapability) {
  2536. intentState.displayReadyCapability.reject(data.error);
  2537. } else {
  2538. error(data.error);
  2539. }
  2540. }, this);
  2541. messageHandler.on('JpegDecode', function(data) {
  2542. var imageUrl = data[0];
  2543. var components = data[1];
  2544. if (components !== 3 && components !== 1) {
  2545. return Promise.reject(
  2546. new Error('Only 3 components or 1 component can be returned'));
  2547. }
  2548. return new Promise(function (resolve, reject) {
  2549. var img = new Image();
  2550. img.onload = function () {
  2551. var width = img.width;
  2552. var height = img.height;
  2553. var size = width * height;
  2554. var rgbaLength = size * 4;
  2555. var buf = new Uint8Array(size * components);
  2556. var tmpCanvas = createScratchCanvas(width, height);
  2557. var tmpCtx = tmpCanvas.getContext('2d');
  2558. tmpCtx.drawImage(img, 0, 0);
  2559. var data = tmpCtx.getImageData(0, 0, width, height).data;
  2560. var i, j;
  2561. if (components === 3) {
  2562. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  2563. buf[j] = data[i];
  2564. buf[j + 1] = data[i + 1];
  2565. buf[j + 2] = data[i + 2];
  2566. }
  2567. } else if (components === 1) {
  2568. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  2569. buf[j] = data[i];
  2570. }
  2571. }
  2572. resolve({ data: buf, width: width, height: height});
  2573. };
  2574. img.onerror = function () {
  2575. reject(new Error('JpegDecode failed to load image'));
  2576. };
  2577. img.src = imageUrl;
  2578. });
  2579. });
  2580. },
  2581. fetchDocument: function WorkerTransport_fetchDocument(loadingTask, source) {
  2582. this.loadingTask = loadingTask;
  2583. source.disableAutoFetch = PDFJS.disableAutoFetch;
  2584. source.disableStream = PDFJS.disableStream;
  2585. source.chunkedViewerLoading = !!this.pdfDataRangeTransport;
  2586. if (this.pdfDataRangeTransport) {
  2587. source.length = this.pdfDataRangeTransport.length;
  2588. source.initialData = this.pdfDataRangeTransport.initialData;
  2589. }
  2590. this.messageHandler.send('GetDocRequest', {
  2591. source: source,
  2592. disableRange: PDFJS.disableRange,
  2593. maxImageSize: PDFJS.maxImageSize,
  2594. cMapUrl: PDFJS.cMapUrl,
  2595. cMapPacked: PDFJS.cMapPacked,
  2596. disableFontFace: PDFJS.disableFontFace,
  2597. disableCreateObjectURL: PDFJS.disableCreateObjectURL,
  2598. verbosity: PDFJS.verbosity
  2599. });
  2600. },
  2601. getData: function WorkerTransport_getData() {
  2602. return this.messageHandler.sendWithPromise('GetData', null);
  2603. },
  2604. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  2605. if (pageNumber <= 0 || pageNumber > this.numPages ||
  2606. (pageNumber|0) !== pageNumber) {
  2607. return Promise.reject(new Error('Invalid page request'));
  2608. }
  2609. var pageIndex = pageNumber - 1;
  2610. if (pageIndex in this.pagePromises) {
  2611. return this.pagePromises[pageIndex];
  2612. }
  2613. var promise = this.messageHandler.sendWithPromise('GetPage', {
  2614. pageIndex: pageIndex
  2615. }).then(function (pageInfo) {
  2616. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  2617. this.pageCache[pageIndex] = page;
  2618. return page;
  2619. }.bind(this));
  2620. this.pagePromises[pageIndex] = promise;
  2621. return promise;
  2622. },
  2623. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  2624. return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref });
  2625. },
  2626. getAnnotations: function WorkerTransport_getAnnotations(pageIndex) {
  2627. return this.messageHandler.sendWithPromise('GetAnnotations',
  2628. { pageIndex: pageIndex });
  2629. },
  2630. getDestinations: function WorkerTransport_getDestinations() {
  2631. return this.messageHandler.sendWithPromise('GetDestinations', null);
  2632. },
  2633. getDestination: function WorkerTransport_getDestination(id) {
  2634. return this.messageHandler.sendWithPromise('GetDestination', { id: id } );
  2635. },
  2636. getAttachments: function WorkerTransport_getAttachments() {
  2637. return this.messageHandler.sendWithPromise('GetAttachments', null);
  2638. },
  2639. getJavaScript: function WorkerTransport_getJavaScript() {
  2640. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  2641. },
  2642. getOutline: function WorkerTransport_getOutline() {
  2643. return this.messageHandler.sendWithPromise('GetOutline', null);
  2644. },
  2645. getMetadata: function WorkerTransport_getMetadata() {
  2646. return this.messageHandler.sendWithPromise('GetMetadata', null).
  2647. then(function transportMetadata(results) {
  2648. return {
  2649. info: results[0],
  2650. metadata: (results[1] ? new PDFJS.Metadata(results[1]) : null)
  2651. };
  2652. });
  2653. },
  2654. getStats: function WorkerTransport_getStats() {
  2655. return this.messageHandler.sendWithPromise('GetStats', null);
  2656. },
  2657. startCleanup: function WorkerTransport_startCleanup() {
  2658. this.messageHandler.sendWithPromise('Cleanup', null).
  2659. then(function endCleanup() {
  2660. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  2661. var page = this.pageCache[i];
  2662. if (page) {
  2663. page.destroy();
  2664. }
  2665. }
  2666. this.commonObjs.clear();
  2667. FontLoader.clear();
  2668. }.bind(this));
  2669. }
  2670. };
  2671. return WorkerTransport;
  2672. })();
  2673. /**
  2674. * A PDF document and page is built of many objects. E.g. there are objects
  2675. * for fonts, images, rendering code and such. These objects might get processed
  2676. * inside of a worker. The `PDFObjects` implements some basic functions to
  2677. * manage these objects.
  2678. * @ignore
  2679. */
  2680. var PDFObjects = (function PDFObjectsClosure() {
  2681. function PDFObjects() {
  2682. this.objs = {};
  2683. }
  2684. PDFObjects.prototype = {
  2685. /**
  2686. * Internal function.
  2687. * Ensures there is an object defined for `objId`.
  2688. */
  2689. ensureObj: function PDFObjects_ensureObj(objId) {
  2690. if (this.objs[objId]) {
  2691. return this.objs[objId];
  2692. }
  2693. var obj = {
  2694. capability: createPromiseCapability(),
  2695. data: null,
  2696. resolved: false
  2697. };
  2698. this.objs[objId] = obj;
  2699. return obj;
  2700. },
  2701. /**
  2702. * If called *without* callback, this returns the data of `objId` but the
  2703. * object needs to be resolved. If it isn't, this function throws.
  2704. *
  2705. * If called *with* a callback, the callback is called with the data of the
  2706. * object once the object is resolved. That means, if you call this
  2707. * function and the object is already resolved, the callback gets called
  2708. * right away.
  2709. */
  2710. get: function PDFObjects_get(objId, callback) {
  2711. // If there is a callback, then the get can be async and the object is
  2712. // not required to be resolved right now
  2713. if (callback) {
  2714. this.ensureObj(objId).capability.promise.then(callback);
  2715. return null;
  2716. }
  2717. // If there isn't a callback, the user expects to get the resolved data
  2718. // directly.
  2719. var obj = this.objs[objId];
  2720. // If there isn't an object yet or the object isn't resolved, then the
  2721. // data isn't ready yet!
  2722. if (!obj || !obj.resolved) {
  2723. error('Requesting object that isn\'t resolved yet ' + objId);
  2724. }
  2725. return obj.data;
  2726. },
  2727. /**
  2728. * Resolves the object `objId` with optional `data`.
  2729. */
  2730. resolve: function PDFObjects_resolve(objId, data) {
  2731. var obj = this.ensureObj(objId);
  2732. obj.resolved = true;
  2733. obj.data = data;
  2734. obj.capability.resolve(data);
  2735. },
  2736. isResolved: function PDFObjects_isResolved(objId) {
  2737. var objs = this.objs;
  2738. if (!objs[objId]) {
  2739. return false;
  2740. } else {
  2741. return objs[objId].resolved;
  2742. }
  2743. },
  2744. hasData: function PDFObjects_hasData(objId) {
  2745. return this.isResolved(objId);
  2746. },
  2747. /**
  2748. * Returns the data of `objId` if object exists, null otherwise.
  2749. */
  2750. getData: function PDFObjects_getData(objId) {
  2751. var objs = this.objs;
  2752. if (!objs[objId] || !objs[objId].resolved) {
  2753. return null;
  2754. } else {
  2755. return objs[objId].data;
  2756. }
  2757. },
  2758. clear: function PDFObjects_clear() {
  2759. this.objs = {};
  2760. }
  2761. };
  2762. return PDFObjects;
  2763. })();
  2764. /**
  2765. * Allows controlling of the rendering tasks.
  2766. * @class
  2767. */
  2768. var RenderTask = (function RenderTaskClosure() {
  2769. function RenderTask(internalRenderTask) {
  2770. this._internalRenderTask = internalRenderTask;
  2771. /**
  2772. * Callback for incremental rendering -- a function that will be called
  2773. * each time the rendering is paused. To continue rendering call the
  2774. * function that is the first argument to the callback.
  2775. * @type {function}
  2776. */
  2777. this.onContinue = null;
  2778. }
  2779. RenderTask.prototype = /** @lends RenderTask.prototype */ {
  2780. /**
  2781. * Promise for rendering task completion.
  2782. * @return {Promise}
  2783. */
  2784. get promise() {
  2785. return this._internalRenderTask.capability.promise;
  2786. },
  2787. /**
  2788. * Cancels the rendering task. If the task is currently rendering it will
  2789. * not be cancelled until graphics pauses with a timeout. The promise that
  2790. * this object extends will resolved when cancelled.
  2791. */
  2792. cancel: function RenderTask_cancel() {
  2793. this._internalRenderTask.cancel();
  2794. },
  2795. /**
  2796. * Registers callbacks to indicate the rendering task completion.
  2797. *
  2798. * @param {function} onFulfilled The callback for the rendering completion.
  2799. * @param {function} onRejected The callback for the rendering failure.
  2800. * @return {Promise} A promise that is resolved after the onFulfilled or
  2801. * onRejected callback.
  2802. */
  2803. then: function RenderTask_then(onFulfilled, onRejected) {
  2804. return this.promise.then.apply(this.promise, arguments);
  2805. }
  2806. };
  2807. return RenderTask;
  2808. })();
  2809. /**
  2810. * For internal use only.
  2811. * @ignore
  2812. */
  2813. var InternalRenderTask = (function InternalRenderTaskClosure() {
  2814. function InternalRenderTask(callback, params, objs, commonObjs, operatorList,
  2815. pageNumber) {
  2816. this.callback = callback;
  2817. this.params = params;
  2818. this.objs = objs;
  2819. this.commonObjs = commonObjs;
  2820. this.operatorListIdx = null;
  2821. this.operatorList = operatorList;
  2822. this.pageNumber = pageNumber;
  2823. this.running = false;
  2824. this.graphicsReadyCallback = null;
  2825. this.graphicsReady = false;
  2826. this.cancelled = false;
  2827. this.capability = createPromiseCapability();
  2828. this.task = new RenderTask(this);
  2829. // caching this-bound methods
  2830. this._continueBound = this._continue.bind(this);
  2831. this._scheduleNextBound = this._scheduleNext.bind(this);
  2832. this._nextBound = this._next.bind(this);
  2833. }
  2834. InternalRenderTask.prototype = {
  2835. initalizeGraphics:
  2836. function InternalRenderTask_initalizeGraphics(transparency) {
  2837. if (this.cancelled) {
  2838. return;
  2839. }
  2840. if (PDFJS.pdfBug && 'StepperManager' in globalScope &&
  2841. globalScope.StepperManager.enabled) {
  2842. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  2843. this.stepper.init(this.operatorList);
  2844. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  2845. }
  2846. var params = this.params;
  2847. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs,
  2848. this.objs, params.imageLayer);
  2849. this.gfx.beginDrawing(params.viewport, transparency);
  2850. this.operatorListIdx = 0;
  2851. this.graphicsReady = true;
  2852. if (this.graphicsReadyCallback) {
  2853. this.graphicsReadyCallback();
  2854. }
  2855. },
  2856. cancel: function InternalRenderTask_cancel() {
  2857. this.running = false;
  2858. this.cancelled = true;
  2859. this.callback('cancelled');
  2860. },
  2861. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  2862. if (!this.graphicsReady) {
  2863. if (!this.graphicsReadyCallback) {
  2864. this.graphicsReadyCallback = this._continueBound;
  2865. }
  2866. return;
  2867. }
  2868. if (this.stepper) {
  2869. this.stepper.updateOperatorList(this.operatorList);
  2870. }
  2871. if (this.running) {
  2872. return;
  2873. }
  2874. this._continue();
  2875. },
  2876. _continue: function InternalRenderTask__continue() {
  2877. this.running = true;
  2878. if (this.cancelled) {
  2879. return;
  2880. }
  2881. if (this.task.onContinue) {
  2882. this.task.onContinue.call(this.task, this._scheduleNextBound);
  2883. } else {
  2884. this._scheduleNext();
  2885. }
  2886. },
  2887. _scheduleNext: function InternalRenderTask__scheduleNext() {
  2888. window.requestAnimationFrame(this._nextBound);
  2889. },
  2890. _next: function InternalRenderTask__next() {
  2891. if (this.cancelled) {
  2892. return;
  2893. }
  2894. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList,
  2895. this.operatorListIdx,
  2896. this._continueBound,
  2897. this.stepper);
  2898. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  2899. this.running = false;
  2900. if (this.operatorList.lastChunk) {
  2901. this.gfx.endDrawing();
  2902. this.callback();
  2903. }
  2904. }
  2905. }
  2906. };
  2907. return InternalRenderTask;
  2908. })();
  2909. var Metadata = PDFJS.Metadata = (function MetadataClosure() {
  2910. function fixMetadata(meta) {
  2911. return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) {
  2912. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g,
  2913. function(code, d1, d2, d3) {
  2914. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  2915. });
  2916. var chars = '';
  2917. for (var i = 0; i < bytes.length; i += 2) {
  2918. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  2919. chars += code >= 32 && code < 127 && code !== 60 && code !== 62 &&
  2920. code !== 38 && false ? String.fromCharCode(code) :
  2921. '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  2922. }
  2923. return '>' + chars;
  2924. });
  2925. }
  2926. function Metadata(meta) {
  2927. if (typeof meta === 'string') {
  2928. // Ghostscript produces invalid metadata
  2929. meta = fixMetadata(meta);
  2930. var parser = new DOMParser();
  2931. meta = parser.parseFromString(meta, 'application/xml');
  2932. } else if (!(meta instanceof Document)) {
  2933. error('Metadata: Invalid metadata object');
  2934. }
  2935. this.metaDocument = meta;
  2936. this.metadata = {};
  2937. this.parse();
  2938. }
  2939. Metadata.prototype = {
  2940. parse: function Metadata_parse() {
  2941. var doc = this.metaDocument;
  2942. var rdf = doc.documentElement;
  2943. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta>
  2944. rdf = rdf.firstChild;
  2945. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  2946. rdf = rdf.nextSibling;
  2947. }
  2948. }
  2949. var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null;
  2950. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  2951. return;
  2952. }
  2953. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  2954. for (i = 0, length = children.length; i < length; i++) {
  2955. desc = children[i];
  2956. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  2957. continue;
  2958. }
  2959. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  2960. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  2961. entry = desc.childNodes[ii];
  2962. name = entry.nodeName.toLowerCase();
  2963. this.metadata[name] = entry.textContent.trim();
  2964. }
  2965. }
  2966. }
  2967. },
  2968. get: function Metadata_get(name) {
  2969. return this.metadata[name] || null;
  2970. },
  2971. has: function Metadata_has(name) {
  2972. return typeof this.metadata[name] !== 'undefined';
  2973. }
  2974. };
  2975. return Metadata;
  2976. })();
  2977. // <canvas> contexts store most of the state we need natively.
  2978. // However, PDF needs a bit more state, which we store here.
  2979. // Minimal font size that would be used during canvas fillText operations.
  2980. var MIN_FONT_SIZE = 16;
  2981. // Maximum font size that would be used during canvas fillText operations.
  2982. var MAX_FONT_SIZE = 100;
  2983. var MAX_GROUP_SIZE = 4096;
  2984. // Heuristic value used when enforcing minimum line widths.
  2985. var MIN_WIDTH_FACTOR = 0.65;
  2986. var COMPILE_TYPE3_GLYPHS = true;
  2987. var MAX_SIZE_TO_COMPILE = 1000;
  2988. var FULL_CHUNK_HEIGHT = 16;
  2989. function createScratchCanvas(width, height) {
  2990. var canvas = document.createElement('canvas');
  2991. canvas.width = width;
  2992. canvas.height = height;
  2993. return canvas;
  2994. }
  2995. function addContextCurrentTransform(ctx) {
  2996. // If the context doesn't expose a `mozCurrentTransform`, add a JS based one.
  2997. if (!ctx.mozCurrentTransform) {
  2998. ctx._originalSave = ctx.save;
  2999. ctx._originalRestore = ctx.restore;
  3000. ctx._originalRotate = ctx.rotate;
  3001. ctx._originalScale = ctx.scale;
  3002. ctx._originalTranslate = ctx.translate;
  3003. ctx._originalTransform = ctx.transform;
  3004. ctx._originalSetTransform = ctx.setTransform;
  3005. ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
  3006. ctx._transformStack = [];
  3007. Object.defineProperty(ctx, 'mozCurrentTransform', {
  3008. get: function getCurrentTransform() {
  3009. return this._transformMatrix;
  3010. }
  3011. });
  3012. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  3013. get: function getCurrentTransformInverse() {
  3014. // Calculation done using WolframAlpha:
  3015. // http://www.wolframalpha.com/input/?
  3016. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  3017. var m = this._transformMatrix;
  3018. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  3019. var ad_bc = a * d - b * c;
  3020. var bc_ad = b * c - a * d;
  3021. return [
  3022. d / ad_bc,
  3023. b / bc_ad,
  3024. c / bc_ad,
  3025. a / ad_bc,
  3026. (d * e - c * f) / bc_ad,
  3027. (b * e - a * f) / ad_bc
  3028. ];
  3029. }
  3030. });
  3031. ctx.save = function ctxSave() {
  3032. var old = this._transformMatrix;
  3033. this._transformStack.push(old);
  3034. this._transformMatrix = old.slice(0, 6);
  3035. this._originalSave();
  3036. };
  3037. ctx.restore = function ctxRestore() {
  3038. var prev = this._transformStack.pop();
  3039. if (prev) {
  3040. this._transformMatrix = prev;
  3041. this._originalRestore();
  3042. }
  3043. };
  3044. ctx.translate = function ctxTranslate(x, y) {
  3045. var m = this._transformMatrix;
  3046. m[4] = m[0] * x + m[2] * y + m[4];
  3047. m[5] = m[1] * x + m[3] * y + m[5];
  3048. this._originalTranslate(x, y);
  3049. };
  3050. ctx.scale = function ctxScale(x, y) {
  3051. var m = this._transformMatrix;
  3052. m[0] = m[0] * x;
  3053. m[1] = m[1] * x;
  3054. m[2] = m[2] * y;
  3055. m[3] = m[3] * y;
  3056. this._originalScale(x, y);
  3057. };
  3058. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  3059. var m = this._transformMatrix;
  3060. this._transformMatrix = [
  3061. m[0] * a + m[2] * b,
  3062. m[1] * a + m[3] * b,
  3063. m[0] * c + m[2] * d,
  3064. m[1] * c + m[3] * d,
  3065. m[0] * e + m[2] * f + m[4],
  3066. m[1] * e + m[3] * f + m[5]
  3067. ];
  3068. ctx._originalTransform(a, b, c, d, e, f);
  3069. };
  3070. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  3071. this._transformMatrix = [a, b, c, d, e, f];
  3072. ctx._originalSetTransform(a, b, c, d, e, f);
  3073. };
  3074. ctx.rotate = function ctxRotate(angle) {
  3075. var cosValue = Math.cos(angle);
  3076. var sinValue = Math.sin(angle);
  3077. var m = this._transformMatrix;
  3078. this._transformMatrix = [
  3079. m[0] * cosValue + m[2] * sinValue,
  3080. m[1] * cosValue + m[3] * sinValue,
  3081. m[0] * (-sinValue) + m[2] * cosValue,
  3082. m[1] * (-sinValue) + m[3] * cosValue,
  3083. m[4],
  3084. m[5]
  3085. ];
  3086. this._originalRotate(angle);
  3087. };
  3088. }
  3089. }
  3090. var CachedCanvases = (function CachedCanvasesClosure() {
  3091. var cache = {};
  3092. return {
  3093. getCanvas: function CachedCanvases_getCanvas(id, width, height,
  3094. trackTransform) {
  3095. var canvasEntry;
  3096. if (cache[id] !== undefined) {
  3097. canvasEntry = cache[id];
  3098. canvasEntry.canvas.width = width;
  3099. canvasEntry.canvas.height = height;
  3100. // reset canvas transform for emulated mozCurrentTransform, if needed
  3101. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  3102. } else {
  3103. var canvas = createScratchCanvas(width, height);
  3104. var ctx = canvas.getContext('2d');
  3105. if (trackTransform) {
  3106. addContextCurrentTransform(ctx);
  3107. }
  3108. cache[id] = canvasEntry = {canvas: canvas, context: ctx};
  3109. }
  3110. return canvasEntry;
  3111. },
  3112. clear: function () {
  3113. for (var id in cache) {
  3114. var canvasEntry = cache[id];
  3115. // Zeroing the width and height causes Firefox to release graphics
  3116. // resources immediately, which can greatly reduce memory consumption.
  3117. canvasEntry.canvas.width = 0;
  3118. canvasEntry.canvas.height = 0;
  3119. delete cache[id];
  3120. }
  3121. }
  3122. };
  3123. })();
  3124. function compileType3Glyph(imgData) {
  3125. var POINT_TO_PROCESS_LIMIT = 1000;
  3126. var width = imgData.width, height = imgData.height;
  3127. var i, j, j0, width1 = width + 1;
  3128. var points = new Uint8Array(width1 * (height + 1));
  3129. var POINT_TYPES =
  3130. new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
  3131. // decodes bit-packed mask data
  3132. var lineSize = (width + 7) & ~7, data0 = imgData.data;
  3133. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  3134. for (i = 0, ii = data0.length; i < ii; i++) {
  3135. var mask = 128, elem = data0[i];
  3136. while (mask > 0) {
  3137. data[pos++] = (elem & mask) ? 0 : 255;
  3138. mask >>= 1;
  3139. }
  3140. }
  3141. // finding iteresting points: every point is located between mask pixels,
  3142. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  3143. // will have flags assigned based on neighboring mask pixels:
  3144. // 4 | 8
  3145. // --P--
  3146. // 2 | 1
  3147. // We are interested only in points with the flags:
  3148. // - outside corners: 1, 2, 4, 8;
  3149. // - inside corners: 7, 11, 13, 14;
  3150. // - and, intersections: 5, 10.
  3151. var count = 0;
  3152. pos = 0;
  3153. if (data[pos] !== 0) {
  3154. points[0] = 1;
  3155. ++count;
  3156. }
  3157. for (j = 1; j < width; j++) {
  3158. if (data[pos] !== data[pos + 1]) {
  3159. points[j] = data[pos] ? 2 : 1;
  3160. ++count;
  3161. }
  3162. pos++;
  3163. }
  3164. if (data[pos] !== 0) {
  3165. points[j] = 2;
  3166. ++count;
  3167. }
  3168. for (i = 1; i < height; i++) {
  3169. pos = i * lineSize;
  3170. j0 = i * width1;
  3171. if (data[pos - lineSize] !== data[pos]) {
  3172. points[j0] = data[pos] ? 1 : 8;
  3173. ++count;
  3174. }
  3175. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  3176. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  3177. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  3178. for (j = 1; j < width; j++) {
  3179. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) +
  3180. (data[pos - lineSize + 1] ? 8 : 0);
  3181. if (POINT_TYPES[sum]) {
  3182. points[j0 + j] = POINT_TYPES[sum];
  3183. ++count;
  3184. }
  3185. pos++;
  3186. }
  3187. if (data[pos - lineSize] !== data[pos]) {
  3188. points[j0 + j] = data[pos] ? 2 : 4;
  3189. ++count;
  3190. }
  3191. if (count > POINT_TO_PROCESS_LIMIT) {
  3192. return null;
  3193. }
  3194. }
  3195. pos = lineSize * (height - 1);
  3196. j0 = i * width1;
  3197. if (data[pos] !== 0) {
  3198. points[j0] = 8;
  3199. ++count;
  3200. }
  3201. for (j = 1; j < width; j++) {
  3202. if (data[pos] !== data[pos + 1]) {
  3203. points[j0 + j] = data[pos] ? 4 : 8;
  3204. ++count;
  3205. }
  3206. pos++;
  3207. }
  3208. if (data[pos] !== 0) {
  3209. points[j0 + j] = 4;
  3210. ++count;
  3211. }
  3212. if (count > POINT_TO_PROCESS_LIMIT) {
  3213. return null;
  3214. }
  3215. // building outlines
  3216. var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
  3217. var outlines = [];
  3218. for (i = 0; count && i <= height; i++) {
  3219. var p = i * width1;
  3220. var end = p + width;
  3221. while (p < end && !points[p]) {
  3222. p++;
  3223. }
  3224. if (p === end) {
  3225. continue;
  3226. }
  3227. var coords = [p % width1, i];
  3228. var type = points[p], p0 = p, pp;
  3229. do {
  3230. var step = steps[type];
  3231. do {
  3232. p += step;
  3233. } while (!points[p]);
  3234. pp = points[p];
  3235. if (pp !== 5 && pp !== 10) {
  3236. // set new direction
  3237. type = pp;
  3238. // delete mark
  3239. points[p] = 0;
  3240. } else { // type is 5 or 10, ie, a crossing
  3241. // set new direction
  3242. type = pp & ((0x33 * type) >> 4);
  3243. // set new type for "future hit"
  3244. points[p] &= (type >> 2 | type << 2);
  3245. }
  3246. coords.push(p % width1);
  3247. coords.push((p / width1) | 0);
  3248. --count;
  3249. } while (p0 !== p);
  3250. outlines.push(coords);
  3251. --i;
  3252. }
  3253. var drawOutline = function(c) {
  3254. c.save();
  3255. // the path shall be painted in [0..1]x[0..1] space
  3256. c.scale(1 / width, -1 / height);
  3257. c.translate(0, -height);
  3258. c.beginPath();
  3259. for (var i = 0, ii = outlines.length; i < ii; i++) {
  3260. var o = outlines[i];
  3261. c.moveTo(o[0], o[1]);
  3262. for (var j = 2, jj = o.length; j < jj; j += 2) {
  3263. c.lineTo(o[j], o[j+1]);
  3264. }
  3265. }
  3266. c.fill();
  3267. c.beginPath();
  3268. c.restore();
  3269. };
  3270. return drawOutline;
  3271. }
  3272. var CanvasExtraState = (function CanvasExtraStateClosure() {
  3273. function CanvasExtraState(old) {
  3274. // Are soft masks and alpha values shapes or opacities?
  3275. this.alphaIsShape = false;
  3276. this.fontSize = 0;
  3277. this.fontSizeScale = 1;
  3278. this.textMatrix = IDENTITY_MATRIX;
  3279. this.textMatrixScale = 1;
  3280. this.fontMatrix = FONT_IDENTITY_MATRIX;
  3281. this.leading = 0;
  3282. // Current point (in user coordinates)
  3283. this.x = 0;
  3284. this.y = 0;
  3285. // Start of text line (in text coordinates)
  3286. this.lineX = 0;
  3287. this.lineY = 0;
  3288. // Character and word spacing
  3289. this.charSpacing = 0;
  3290. this.wordSpacing = 0;
  3291. this.textHScale = 1;
  3292. this.textRenderingMode = TextRenderingMode.FILL;
  3293. this.textRise = 0;
  3294. // Default fore and background colors
  3295. this.fillColor = '#000000';
  3296. this.strokeColor = '#000000';
  3297. this.patternFill = false;
  3298. // Note: fill alpha applies to all non-stroking operations
  3299. this.fillAlpha = 1;
  3300. this.strokeAlpha = 1;
  3301. this.lineWidth = 1;
  3302. this.activeSMask = null; // nonclonable field (see the save method below)
  3303. this.old = old;
  3304. }
  3305. CanvasExtraState.prototype = {
  3306. clone: function CanvasExtraState_clone() {
  3307. return Object.create(this);
  3308. },
  3309. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  3310. this.x = x;
  3311. this.y = y;
  3312. }
  3313. };
  3314. return CanvasExtraState;
  3315. })();
  3316. var CanvasGraphics = (function CanvasGraphicsClosure() {
  3317. // Defines the time the executeOperatorList is going to be executing
  3318. // before it stops and shedules a continue of execution.
  3319. var EXECUTION_TIME = 15;
  3320. // Defines the number of steps before checking the execution time
  3321. var EXECUTION_STEPS = 10;
  3322. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  3323. this.ctx = canvasCtx;
  3324. this.current = new CanvasExtraState();
  3325. this.stateStack = [];
  3326. this.pendingClip = null;
  3327. this.pendingEOFill = false;
  3328. this.res = null;
  3329. this.xobjs = null;
  3330. this.commonObjs = commonObjs;
  3331. this.objs = objs;
  3332. this.imageLayer = imageLayer;
  3333. this.groupStack = [];
  3334. this.processingType3 = null;
  3335. // Patterns are painted relative to the initial page/form transform, see pdf
  3336. // spec 8.7.2 NOTE 1.
  3337. this.baseTransform = null;
  3338. this.baseTransformStack = [];
  3339. this.groupLevel = 0;
  3340. this.smaskStack = [];
  3341. this.smaskCounter = 0;
  3342. this.tempSMask = null;
  3343. if (canvasCtx) {
  3344. // NOTE: if mozCurrentTransform is polyfilled, then the current state of
  3345. // the transformation must already be set in canvasCtx._transformMatrix.
  3346. addContextCurrentTransform(canvasCtx);
  3347. }
  3348. this.cachedGetSinglePixelWidth = null;
  3349. }
  3350. function putBinaryImageData(ctx, imgData) {
  3351. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  3352. ctx.putImageData(imgData, 0, 0);
  3353. return;
  3354. }
  3355. // Put the image data to the canvas in chunks, rather than putting the
  3356. // whole image at once. This saves JS memory, because the ImageData object
  3357. // is smaller. It also possibly saves C++ memory within the implementation
  3358. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  3359. // the data passed to putImageData()). |n| shouldn't be too small, however,
  3360. // because too many putImageData() calls will slow things down.
  3361. //
  3362. // Note: as written, if the last chunk is partial, the putImageData() call
  3363. // will (conceptually) put pixels past the bounds of the canvas. But
  3364. // that's ok; any such pixels are ignored.
  3365. var height = imgData.height, width = imgData.width;
  3366. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  3367. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  3368. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  3369. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  3370. var srcPos = 0, destPos;
  3371. var src = imgData.data;
  3372. var dest = chunkImgData.data;
  3373. var i, j, thisChunkHeight, elemsInThisChunk;
  3374. // There are multiple forms in which the pixel data can be passed, and
  3375. // imgData.kind tells us which one this is.
  3376. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  3377. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  3378. var srcLength = src.byteLength;
  3379. var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) :
  3380. new Uint32ArrayView(dest);
  3381. var dest32DataLength = dest32.length;
  3382. var fullSrcDiff = (width + 7) >> 3;
  3383. var white = 0xFFFFFFFF;
  3384. var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ?
  3385. 0xFF000000 : 0x000000FF;
  3386. for (i = 0; i < totalChunks; i++) {
  3387. thisChunkHeight =
  3388. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  3389. destPos = 0;
  3390. for (j = 0; j < thisChunkHeight; j++) {
  3391. var srcDiff = srcLength - srcPos;
  3392. var k = 0;
  3393. var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7;
  3394. var kEndUnrolled = kEnd & ~7;
  3395. var mask = 0;
  3396. var srcByte = 0;
  3397. for (; k < kEndUnrolled; k += 8) {
  3398. srcByte = src[srcPos++];
  3399. dest32[destPos++] = (srcByte & 128) ? white : black;
  3400. dest32[destPos++] = (srcByte & 64) ? white : black;
  3401. dest32[destPos++] = (srcByte & 32) ? white : black;
  3402. dest32[destPos++] = (srcByte & 16) ? white : black;
  3403. dest32[destPos++] = (srcByte & 8) ? white : black;
  3404. dest32[destPos++] = (srcByte & 4) ? white : black;
  3405. dest32[destPos++] = (srcByte & 2) ? white : black;
  3406. dest32[destPos++] = (srcByte & 1) ? white : black;
  3407. }
  3408. for (; k < kEnd; k++) {
  3409. if (mask === 0) {
  3410. srcByte = src[srcPos++];
  3411. mask = 128;
  3412. }
  3413. dest32[destPos++] = (srcByte & mask) ? white : black;
  3414. mask >>= 1;
  3415. }
  3416. }
  3417. // We ran out of input. Make all remaining pixels transparent.
  3418. while (destPos < dest32DataLength) {
  3419. dest32[destPos++] = 0;
  3420. }
  3421. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  3422. }
  3423. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  3424. // RGBA, 32-bits per pixel.
  3425. j = 0;
  3426. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  3427. for (i = 0; i < fullChunks; i++) {
  3428. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  3429. srcPos += elemsInThisChunk;
  3430. ctx.putImageData(chunkImgData, 0, j);
  3431. j += FULL_CHUNK_HEIGHT;
  3432. }
  3433. if (i < totalChunks) {
  3434. elemsInThisChunk = width * partialChunkHeight * 4;
  3435. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  3436. ctx.putImageData(chunkImgData, 0, j);
  3437. }
  3438. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  3439. // RGB, 24-bits per pixel.
  3440. thisChunkHeight = FULL_CHUNK_HEIGHT;
  3441. elemsInThisChunk = width * thisChunkHeight;
  3442. for (i = 0; i < totalChunks; i++) {
  3443. if (i >= fullChunks) {
  3444. thisChunkHeight = partialChunkHeight;
  3445. elemsInThisChunk = width * thisChunkHeight;
  3446. }
  3447. destPos = 0;
  3448. for (j = elemsInThisChunk; j--;) {
  3449. dest[destPos++] = src[srcPos++];
  3450. dest[destPos++] = src[srcPos++];
  3451. dest[destPos++] = src[srcPos++];
  3452. dest[destPos++] = 255;
  3453. }
  3454. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  3455. }
  3456. } else {
  3457. error('bad image kind: ' + imgData.kind);
  3458. }
  3459. }
  3460. function putBinaryImageMask(ctx, imgData) {
  3461. var height = imgData.height, width = imgData.width;
  3462. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  3463. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  3464. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  3465. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  3466. var srcPos = 0;
  3467. var src = imgData.data;
  3468. var dest = chunkImgData.data;
  3469. for (var i = 0; i < totalChunks; i++) {
  3470. var thisChunkHeight =
  3471. (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  3472. // Expand the mask so it can be used by the canvas. Any required
  3473. // inversion has already been handled.
  3474. var destPos = 3; // alpha component offset
  3475. for (var j = 0; j < thisChunkHeight; j++) {
  3476. var mask = 0;
  3477. for (var k = 0; k < width; k++) {
  3478. if (!mask) {
  3479. var elem = src[srcPos++];
  3480. mask = 128;
  3481. }
  3482. dest[destPos] = (elem & mask) ? 0 : 255;
  3483. destPos += 4;
  3484. mask >>= 1;
  3485. }
  3486. }
  3487. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  3488. }
  3489. }
  3490. function copyCtxState(sourceCtx, destCtx) {
  3491. var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha',
  3492. 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit',
  3493. 'globalCompositeOperation', 'font'];
  3494. for (var i = 0, ii = properties.length; i < ii; i++) {
  3495. var property = properties[i];
  3496. if (sourceCtx[property] !== undefined) {
  3497. destCtx[property] = sourceCtx[property];
  3498. }
  3499. }
  3500. if (sourceCtx.setLineDash !== undefined) {
  3501. destCtx.setLineDash(sourceCtx.getLineDash());
  3502. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  3503. } else if (sourceCtx.mozDashOffset !== undefined) {
  3504. destCtx.mozDash = sourceCtx.mozDash;
  3505. destCtx.mozDashOffset = sourceCtx.mozDashOffset;
  3506. }
  3507. }
  3508. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  3509. var length = bytes.length;
  3510. for (var i = 3; i < length; i += 4) {
  3511. var alpha = bytes[i];
  3512. if (alpha === 0) {
  3513. bytes[i - 3] = r0;
  3514. bytes[i - 2] = g0;
  3515. bytes[i - 1] = b0;
  3516. } else if (alpha < 255) {
  3517. var alpha_ = 255 - alpha;
  3518. bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8;
  3519. bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8;
  3520. bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8;
  3521. }
  3522. }
  3523. }
  3524. function composeSMaskAlpha(maskData, layerData) {
  3525. var length = maskData.length;
  3526. var scale = 1 / 255;
  3527. for (var i = 3; i < length; i += 4) {
  3528. var alpha = maskData[i];
  3529. layerData[i] = (layerData[i] * alpha * scale) | 0;
  3530. }
  3531. }
  3532. function composeSMaskLuminosity(maskData, layerData) {
  3533. var length = maskData.length;
  3534. for (var i = 3; i < length; i += 4) {
  3535. var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000
  3536. (maskData[i - 2] * 152) + // * 0.59 ....
  3537. (maskData[i - 1] * 28); // * 0.11 ....
  3538. layerData[i] = (layerData[i] * y) >> 16;
  3539. }
  3540. }
  3541. function genericComposeSMask(maskCtx, layerCtx, width, height,
  3542. subtype, backdrop) {
  3543. var hasBackdrop = !!backdrop;
  3544. var r0 = hasBackdrop ? backdrop[0] : 0;
  3545. var g0 = hasBackdrop ? backdrop[1] : 0;
  3546. var b0 = hasBackdrop ? backdrop[2] : 0;
  3547. var composeFn;
  3548. if (subtype === 'Luminosity') {
  3549. composeFn = composeSMaskLuminosity;
  3550. } else {
  3551. composeFn = composeSMaskAlpha;
  3552. }
  3553. // processing image in chunks to save memory
  3554. var PIXELS_TO_PROCESS = 1048576;
  3555. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  3556. for (var row = 0; row < height; row += chunkSize) {
  3557. var chunkHeight = Math.min(chunkSize, height - row);
  3558. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  3559. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  3560. if (hasBackdrop) {
  3561. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  3562. }
  3563. composeFn(maskData.data, layerData.data);
  3564. maskCtx.putImageData(layerData, 0, row);
  3565. }
  3566. }
  3567. function composeSMask(ctx, smask, layerCtx) {
  3568. var mask = smask.canvas;
  3569. var maskCtx = smask.context;
  3570. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY,
  3571. smask.offsetX, smask.offsetY);
  3572. var backdrop = smask.backdrop || null;
  3573. if (WebGLUtils.isEnabled) {
  3574. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask,
  3575. {subtype: smask.subtype, backdrop: backdrop});
  3576. ctx.setTransform(1, 0, 0, 1, 0, 0);
  3577. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  3578. return;
  3579. }
  3580. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height,
  3581. smask.subtype, backdrop);
  3582. ctx.drawImage(mask, 0, 0);
  3583. }
  3584. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  3585. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  3586. var NORMAL_CLIP = {};
  3587. var EO_CLIP = {};
  3588. CanvasGraphics.prototype = {
  3589. beginDrawing: function CanvasGraphics_beginDrawing(viewport, transparency) {
  3590. // For pdfs that use blend modes we have to clear the canvas else certain
  3591. // blend modes can look wrong since we'd be blending with a white
  3592. // backdrop. The problem with a transparent backdrop though is we then
  3593. // don't get sub pixel anti aliasing on text, so we fill with white if
  3594. // we can.
  3595. var width = this.ctx.canvas.width;
  3596. var height = this.ctx.canvas.height;
  3597. if (transparency) {
  3598. this.ctx.clearRect(0, 0, width, height);
  3599. } else {
  3600. this.ctx.mozOpaque = true;
  3601. this.ctx.save();
  3602. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  3603. this.ctx.fillRect(0, 0, width, height);
  3604. this.ctx.restore();
  3605. }
  3606. var transform = viewport.transform;
  3607. this.ctx.save();
  3608. this.ctx.transform.apply(this.ctx, transform);
  3609. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  3610. if (this.imageLayer) {
  3611. this.imageLayer.beginLayout();
  3612. }
  3613. },
  3614. executeOperatorList: function CanvasGraphics_executeOperatorList(
  3615. operatorList,
  3616. executionStartIdx, continueCallback,
  3617. stepper) {
  3618. var argsArray = operatorList.argsArray;
  3619. var fnArray = operatorList.fnArray;
  3620. var i = executionStartIdx || 0;
  3621. var argsArrayLen = argsArray.length;
  3622. // Sometimes the OperatorList to execute is empty.
  3623. if (argsArrayLen === i) {
  3624. return i;
  3625. }
  3626. var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS &&
  3627. typeof continueCallback === 'function');
  3628. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  3629. var steps = 0;
  3630. var commonObjs = this.commonObjs;
  3631. var objs = this.objs;
  3632. var fnId;
  3633. while (true) {
  3634. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  3635. stepper.breakIt(i, continueCallback);
  3636. return i;
  3637. }
  3638. fnId = fnArray[i];
  3639. if (fnId !== OPS.dependency) {
  3640. this[fnId].apply(this, argsArray[i]);
  3641. } else {
  3642. var deps = argsArray[i];
  3643. for (var n = 0, nn = deps.length; n < nn; n++) {
  3644. var depObjId = deps[n];
  3645. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  3646. var objsPool = common ? commonObjs : objs;
  3647. // If the promise isn't resolved yet, add the continueCallback
  3648. // to the promise and bail out.
  3649. if (!objsPool.isResolved(depObjId)) {
  3650. objsPool.get(depObjId, continueCallback);
  3651. return i;
  3652. }
  3653. }
  3654. }
  3655. i++;
  3656. // If the entire operatorList was executed, stop as were done.
  3657. if (i === argsArrayLen) {
  3658. return i;
  3659. }
  3660. // If the execution took longer then a certain amount of time and
  3661. // `continueCallback` is specified, interrupt the execution.
  3662. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  3663. if (Date.now() > endTime) {
  3664. continueCallback();
  3665. return i;
  3666. }
  3667. steps = 0;
  3668. }
  3669. // If the operatorList isn't executed completely yet OR the execution
  3670. // time was short enough, do another execution round.
  3671. }
  3672. },
  3673. endDrawing: function CanvasGraphics_endDrawing() {
  3674. this.ctx.restore();
  3675. CachedCanvases.clear();
  3676. WebGLUtils.clear();
  3677. if (this.imageLayer) {
  3678. this.imageLayer.endLayout();
  3679. }
  3680. },
  3681. // Graphics state
  3682. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  3683. this.current.lineWidth = width;
  3684. this.ctx.lineWidth = width;
  3685. },
  3686. setLineCap: function CanvasGraphics_setLineCap(style) {
  3687. this.ctx.lineCap = LINE_CAP_STYLES[style];
  3688. },
  3689. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  3690. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  3691. },
  3692. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  3693. this.ctx.miterLimit = limit;
  3694. },
  3695. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  3696. var ctx = this.ctx;
  3697. if (ctx.setLineDash !== undefined) {
  3698. ctx.setLineDash(dashArray);
  3699. ctx.lineDashOffset = dashPhase;
  3700. } else {
  3701. ctx.mozDash = dashArray;
  3702. ctx.mozDashOffset = dashPhase;
  3703. }
  3704. },
  3705. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  3706. // Maybe if we one day fully support color spaces this will be important
  3707. // for now we can ignore.
  3708. // TODO set rendering intent?
  3709. },
  3710. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  3711. // There's no way to control this with canvas, but we can safely ignore.
  3712. // TODO set flatness?
  3713. },
  3714. setGState: function CanvasGraphics_setGState(states) {
  3715. for (var i = 0, ii = states.length; i < ii; i++) {
  3716. var state = states[i];
  3717. var key = state[0];
  3718. var value = state[1];
  3719. switch (key) {
  3720. case 'LW':
  3721. this.setLineWidth(value);
  3722. break;
  3723. case 'LC':
  3724. this.setLineCap(value);
  3725. break;
  3726. case 'LJ':
  3727. this.setLineJoin(value);
  3728. break;
  3729. case 'ML':
  3730. this.setMiterLimit(value);
  3731. break;
  3732. case 'D':
  3733. this.setDash(value[0], value[1]);
  3734. break;
  3735. case 'RI':
  3736. this.setRenderingIntent(value);
  3737. break;
  3738. case 'FL':
  3739. this.setFlatness(value);
  3740. break;
  3741. case 'Font':
  3742. this.setFont(value[0], value[1]);
  3743. break;
  3744. case 'CA':
  3745. this.current.strokeAlpha = state[1];
  3746. break;
  3747. case 'ca':
  3748. this.current.fillAlpha = state[1];
  3749. this.ctx.globalAlpha = state[1];
  3750. break;
  3751. case 'BM':
  3752. if (value && value.name && (value.name !== 'Normal')) {
  3753. var mode = value.name.replace(/([A-Z])/g,
  3754. function(c) {
  3755. return '-' + c.toLowerCase();
  3756. }
  3757. ).substring(1);
  3758. this.ctx.globalCompositeOperation = mode;
  3759. if (this.ctx.globalCompositeOperation !== mode) {
  3760. warn('globalCompositeOperation "' + mode +
  3761. '" is not supported');
  3762. }
  3763. } else {
  3764. this.ctx.globalCompositeOperation = 'source-over';
  3765. }
  3766. break;
  3767. case 'SMask':
  3768. if (this.current.activeSMask) {
  3769. this.endSMaskGroup();
  3770. }
  3771. this.current.activeSMask = value ? this.tempSMask : null;
  3772. if (this.current.activeSMask) {
  3773. this.beginSMaskGroup();
  3774. }
  3775. this.tempSMask = null;
  3776. break;
  3777. }
  3778. }
  3779. },
  3780. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  3781. var activeSMask = this.current.activeSMask;
  3782. var drawnWidth = activeSMask.canvas.width;
  3783. var drawnHeight = activeSMask.canvas.height;
  3784. var cacheId = 'smaskGroupAt' + this.groupLevel;
  3785. var scratchCanvas = CachedCanvases.getCanvas(
  3786. cacheId, drawnWidth, drawnHeight, true);
  3787. var currentCtx = this.ctx;
  3788. var currentTransform = currentCtx.mozCurrentTransform;
  3789. this.ctx.save();
  3790. var groupCtx = scratchCanvas.context;
  3791. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  3792. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  3793. groupCtx.transform.apply(groupCtx, currentTransform);
  3794. copyCtxState(currentCtx, groupCtx);
  3795. this.ctx = groupCtx;
  3796. this.setGState([
  3797. ['BM', 'Normal'],
  3798. ['ca', 1],
  3799. ['CA', 1]
  3800. ]);
  3801. this.groupStack.push(currentCtx);
  3802. this.groupLevel++;
  3803. },
  3804. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  3805. var groupCtx = this.ctx;
  3806. this.groupLevel--;
  3807. this.ctx = this.groupStack.pop();
  3808. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  3809. this.ctx.restore();
  3810. },
  3811. save: function CanvasGraphics_save() {
  3812. this.ctx.save();
  3813. var old = this.current;
  3814. this.stateStack.push(old);
  3815. this.current = old.clone();
  3816. this.current.activeSMask = null;
  3817. },
  3818. restore: function CanvasGraphics_restore() {
  3819. if (this.stateStack.length !== 0) {
  3820. if (this.current.activeSMask !== null) {
  3821. this.endSMaskGroup();
  3822. }
  3823. this.current = this.stateStack.pop();
  3824. this.ctx.restore();
  3825. this.cachedGetSinglePixelWidth = null;
  3826. }
  3827. },
  3828. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  3829. this.ctx.transform(a, b, c, d, e, f);
  3830. this.cachedGetSinglePixelWidth = null;
  3831. },
  3832. // Path
  3833. constructPath: function CanvasGraphics_constructPath(ops, args) {
  3834. var ctx = this.ctx;
  3835. var current = this.current;
  3836. var x = current.x, y = current.y;
  3837. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  3838. switch (ops[i] | 0) {
  3839. case OPS.rectangle:
  3840. x = args[j++];
  3841. y = args[j++];
  3842. var width = args[j++];
  3843. var height = args[j++];
  3844. if (width === 0) {
  3845. width = this.getSinglePixelWidth();
  3846. }
  3847. if (height === 0) {
  3848. height = this.getSinglePixelWidth();
  3849. }
  3850. var xw = x + width;
  3851. var yh = y + height;
  3852. this.ctx.moveTo(x, y);
  3853. this.ctx.lineTo(xw, y);
  3854. this.ctx.lineTo(xw, yh);
  3855. this.ctx.lineTo(x, yh);
  3856. this.ctx.lineTo(x, y);
  3857. this.ctx.closePath();
  3858. break;
  3859. case OPS.moveTo:
  3860. x = args[j++];
  3861. y = args[j++];
  3862. ctx.moveTo(x, y);
  3863. break;
  3864. case OPS.lineTo:
  3865. x = args[j++];
  3866. y = args[j++];
  3867. ctx.lineTo(x, y);
  3868. break;
  3869. case OPS.curveTo:
  3870. x = args[j + 4];
  3871. y = args[j + 5];
  3872. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3],
  3873. x, y);
  3874. j += 6;
  3875. break;
  3876. case OPS.curveTo2:
  3877. ctx.bezierCurveTo(x, y, args[j], args[j + 1],
  3878. args[j + 2], args[j + 3]);
  3879. x = args[j + 2];
  3880. y = args[j + 3];
  3881. j += 4;
  3882. break;
  3883. case OPS.curveTo3:
  3884. x = args[j + 2];
  3885. y = args[j + 3];
  3886. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  3887. j += 4;
  3888. break;
  3889. case OPS.closePath:
  3890. ctx.closePath();
  3891. break;
  3892. }
  3893. }
  3894. current.setCurrentPoint(x, y);
  3895. },
  3896. closePath: function CanvasGraphics_closePath() {
  3897. this.ctx.closePath();
  3898. },
  3899. stroke: function CanvasGraphics_stroke(consumePath) {
  3900. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  3901. var ctx = this.ctx;
  3902. var strokeColor = this.current.strokeColor;
  3903. // Prevent drawing too thin lines by enforcing a minimum line width.
  3904. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR,
  3905. this.current.lineWidth);
  3906. // For stroke we want to temporarily change the global alpha to the
  3907. // stroking alpha.
  3908. ctx.globalAlpha = this.current.strokeAlpha;
  3909. if (strokeColor && strokeColor.hasOwnProperty('type') &&
  3910. strokeColor.type === 'Pattern') {
  3911. // for patterns, we transform to pattern space, calculate
  3912. // the pattern, call stroke, and restore to user space
  3913. ctx.save();
  3914. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  3915. ctx.stroke();
  3916. ctx.restore();
  3917. } else {
  3918. ctx.stroke();
  3919. }
  3920. if (consumePath) {
  3921. this.consumePath();
  3922. }
  3923. // Restore the global alpha to the fill alpha
  3924. ctx.globalAlpha = this.current.fillAlpha;
  3925. },
  3926. closeStroke: function CanvasGraphics_closeStroke() {
  3927. this.closePath();
  3928. this.stroke();
  3929. },
  3930. fill: function CanvasGraphics_fill(consumePath) {
  3931. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  3932. var ctx = this.ctx;
  3933. var fillColor = this.current.fillColor;
  3934. var isPatternFill = this.current.patternFill;
  3935. var needRestore = false;
  3936. if (isPatternFill) {
  3937. ctx.save();
  3938. ctx.fillStyle = fillColor.getPattern(ctx, this);
  3939. needRestore = true;
  3940. }
  3941. if (this.pendingEOFill) {
  3942. if (ctx.mozFillRule !== undefined) {
  3943. ctx.mozFillRule = 'evenodd';
  3944. ctx.fill();
  3945. ctx.mozFillRule = 'nonzero';
  3946. } else {
  3947. try {
  3948. ctx.fill('evenodd');
  3949. } catch (ex) {
  3950. // shouldn't really happen, but browsers might think differently
  3951. ctx.fill();
  3952. }
  3953. }
  3954. this.pendingEOFill = false;
  3955. } else {
  3956. ctx.fill();
  3957. }
  3958. if (needRestore) {
  3959. ctx.restore();
  3960. }
  3961. if (consumePath) {
  3962. this.consumePath();
  3963. }
  3964. },
  3965. eoFill: function CanvasGraphics_eoFill() {
  3966. this.pendingEOFill = true;
  3967. this.fill();
  3968. },
  3969. fillStroke: function CanvasGraphics_fillStroke() {
  3970. this.fill(false);
  3971. this.stroke(false);
  3972. this.consumePath();
  3973. },
  3974. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  3975. this.pendingEOFill = true;
  3976. this.fillStroke();
  3977. },
  3978. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  3979. this.closePath();
  3980. this.fillStroke();
  3981. },
  3982. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  3983. this.pendingEOFill = true;
  3984. this.closePath();
  3985. this.fillStroke();
  3986. },
  3987. endPath: function CanvasGraphics_endPath() {
  3988. this.consumePath();
  3989. },
  3990. // Clipping
  3991. clip: function CanvasGraphics_clip() {
  3992. this.pendingClip = NORMAL_CLIP;
  3993. },
  3994. eoClip: function CanvasGraphics_eoClip() {
  3995. this.pendingClip = EO_CLIP;
  3996. },
  3997. // Text
  3998. beginText: function CanvasGraphics_beginText() {
  3999. this.current.textMatrix = IDENTITY_MATRIX;
  4000. this.current.textMatrixScale = 1;
  4001. this.current.x = this.current.lineX = 0;
  4002. this.current.y = this.current.lineY = 0;
  4003. },
  4004. endText: function CanvasGraphics_endText() {
  4005. var paths = this.pendingTextPaths;
  4006. var ctx = this.ctx;
  4007. if (paths === undefined) {
  4008. ctx.beginPath();
  4009. return;
  4010. }
  4011. ctx.save();
  4012. ctx.beginPath();
  4013. for (var i = 0; i < paths.length; i++) {
  4014. var path = paths[i];
  4015. ctx.setTransform.apply(ctx, path.transform);
  4016. ctx.translate(path.x, path.y);
  4017. path.addToPath(ctx, path.fontSize);
  4018. }
  4019. ctx.restore();
  4020. ctx.clip();
  4021. ctx.beginPath();
  4022. delete this.pendingTextPaths;
  4023. },
  4024. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  4025. this.current.charSpacing = spacing;
  4026. },
  4027. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  4028. this.current.wordSpacing = spacing;
  4029. },
  4030. setHScale: function CanvasGraphics_setHScale(scale) {
  4031. this.current.textHScale = scale / 100;
  4032. },
  4033. setLeading: function CanvasGraphics_setLeading(leading) {
  4034. this.current.leading = -leading;
  4035. },
  4036. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  4037. var fontObj = this.commonObjs.get(fontRefName);
  4038. var current = this.current;
  4039. if (!fontObj) {
  4040. error('Can\'t find font for ' + fontRefName);
  4041. }
  4042. current.fontMatrix = (fontObj.fontMatrix ?
  4043. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  4044. // A valid matrix needs all main diagonal elements to be non-zero
  4045. // This also ensures we bypass FF bugzilla bug #719844.
  4046. if (current.fontMatrix[0] === 0 ||
  4047. current.fontMatrix[3] === 0) {
  4048. warn('Invalid font matrix for font ' + fontRefName);
  4049. }
  4050. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  4051. // and in some docs this can be negative (inverted x-y axes).
  4052. if (size < 0) {
  4053. size = -size;
  4054. current.fontDirection = -1;
  4055. } else {
  4056. current.fontDirection = 1;
  4057. }
  4058. this.current.font = fontObj;
  4059. this.current.fontSize = size;
  4060. if (fontObj.isType3Font) {
  4061. return; // we don't need ctx.font for Type3 fonts
  4062. }
  4063. var name = fontObj.loadedName || 'sans-serif';
  4064. var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
  4065. (fontObj.bold ? 'bold' : 'normal');
  4066. var italic = fontObj.italic ? 'italic' : 'normal';
  4067. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  4068. // Some font backends cannot handle fonts below certain size.
  4069. // Keeping the font at minimal size and using the fontSizeScale to change
  4070. // the current transformation matrix before the fillText/strokeText.
  4071. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  4072. var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE :
  4073. size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
  4074. this.current.fontSizeScale = size / browserFontSize;
  4075. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  4076. this.ctx.font = rule;
  4077. },
  4078. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  4079. this.current.textRenderingMode = mode;
  4080. },
  4081. setTextRise: function CanvasGraphics_setTextRise(rise) {
  4082. this.current.textRise = rise;
  4083. },
  4084. moveText: function CanvasGraphics_moveText(x, y) {
  4085. this.current.x = this.current.lineX += x;
  4086. this.current.y = this.current.lineY += y;
  4087. },
  4088. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  4089. this.setLeading(-y);
  4090. this.moveText(x, y);
  4091. },
  4092. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  4093. this.current.textMatrix = [a, b, c, d, e, f];
  4094. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  4095. this.current.x = this.current.lineX = 0;
  4096. this.current.y = this.current.lineY = 0;
  4097. },
  4098. nextLine: function CanvasGraphics_nextLine() {
  4099. this.moveText(0, this.current.leading);
  4100. },
  4101. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  4102. var ctx = this.ctx;
  4103. var current = this.current;
  4104. var font = current.font;
  4105. var textRenderingMode = current.textRenderingMode;
  4106. var fontSize = current.fontSize / current.fontSizeScale;
  4107. var fillStrokeMode = textRenderingMode &
  4108. TextRenderingMode.FILL_STROKE_MASK;
  4109. var isAddToPathSet = !!(textRenderingMode &
  4110. TextRenderingMode.ADD_TO_PATH_FLAG);
  4111. var addToPath;
  4112. if (font.disableFontFace || isAddToPathSet) {
  4113. addToPath = font.getPathGenerator(this.commonObjs, character);
  4114. }
  4115. if (font.disableFontFace) {
  4116. ctx.save();
  4117. ctx.translate(x, y);
  4118. ctx.beginPath();
  4119. addToPath(ctx, fontSize);
  4120. if (fillStrokeMode === TextRenderingMode.FILL ||
  4121. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4122. ctx.fill();
  4123. }
  4124. if (fillStrokeMode === TextRenderingMode.STROKE ||
  4125. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4126. ctx.stroke();
  4127. }
  4128. ctx.restore();
  4129. } else {
  4130. if (fillStrokeMode === TextRenderingMode.FILL ||
  4131. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4132. ctx.fillText(character, x, y);
  4133. }
  4134. if (fillStrokeMode === TextRenderingMode.STROKE ||
  4135. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4136. ctx.strokeText(character, x, y);
  4137. }
  4138. }
  4139. if (isAddToPathSet) {
  4140. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  4141. paths.push({
  4142. transform: ctx.mozCurrentTransform,
  4143. x: x,
  4144. y: y,
  4145. fontSize: fontSize,
  4146. addToPath: addToPath
  4147. });
  4148. }
  4149. },
  4150. get isFontSubpixelAAEnabled() {
  4151. // Checks if anti-aliasing is enabled when scaled text is painted.
  4152. // On Windows GDI scaled fonts looks bad.
  4153. var ctx = document.createElement('canvas').getContext('2d');
  4154. ctx.scale(1.5, 1);
  4155. ctx.fillText('I', 0, 10);
  4156. var data = ctx.getImageData(0, 0, 10, 10).data;
  4157. var enabled = false;
  4158. for (var i = 3; i < data.length; i += 4) {
  4159. if (data[i] > 0 && data[i] < 255) {
  4160. enabled = true;
  4161. break;
  4162. }
  4163. }
  4164. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  4165. },
  4166. showText: function CanvasGraphics_showText(glyphs) {
  4167. var current = this.current;
  4168. var font = current.font;
  4169. if (font.isType3Font) {
  4170. return this.showType3Text(glyphs);
  4171. }
  4172. var fontSize = current.fontSize;
  4173. if (fontSize === 0) {
  4174. return;
  4175. }
  4176. var ctx = this.ctx;
  4177. var fontSizeScale = current.fontSizeScale;
  4178. var charSpacing = current.charSpacing;
  4179. var wordSpacing = current.wordSpacing;
  4180. var fontDirection = current.fontDirection;
  4181. var textHScale = current.textHScale * fontDirection;
  4182. var glyphsLength = glyphs.length;
  4183. var vertical = font.vertical;
  4184. var defaultVMetrics = font.defaultVMetrics;
  4185. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  4186. var simpleFillText =
  4187. current.textRenderingMode === TextRenderingMode.FILL &&
  4188. !font.disableFontFace;
  4189. ctx.save();
  4190. ctx.transform.apply(ctx, current.textMatrix);
  4191. ctx.translate(current.x, current.y + current.textRise);
  4192. if (fontDirection > 0) {
  4193. ctx.scale(textHScale, -1);
  4194. } else {
  4195. ctx.scale(textHScale, 1);
  4196. }
  4197. var lineWidth = current.lineWidth;
  4198. var scale = current.textMatrixScale;
  4199. if (scale === 0 || lineWidth === 0) {
  4200. var fillStrokeMode = current.textRenderingMode &
  4201. TextRenderingMode.FILL_STROKE_MASK;
  4202. if (fillStrokeMode === TextRenderingMode.STROKE ||
  4203. fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  4204. this.cachedGetSinglePixelWidth = null;
  4205. lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
  4206. }
  4207. } else {
  4208. lineWidth /= scale;
  4209. }
  4210. if (fontSizeScale !== 1.0) {
  4211. ctx.scale(fontSizeScale, fontSizeScale);
  4212. lineWidth /= fontSizeScale;
  4213. }
  4214. ctx.lineWidth = lineWidth;
  4215. var x = 0, i;
  4216. for (i = 0; i < glyphsLength; ++i) {
  4217. var glyph = glyphs[i];
  4218. if (glyph === null) {
  4219. // word break
  4220. x += fontDirection * wordSpacing;
  4221. continue;
  4222. } else if (isNum(glyph)) {
  4223. x += -glyph * fontSize * 0.001;
  4224. continue;
  4225. }
  4226. var restoreNeeded = false;
  4227. var character = glyph.fontChar;
  4228. var accent = glyph.accent;
  4229. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  4230. var width = glyph.width;
  4231. if (vertical) {
  4232. var vmetric, vx, vy;
  4233. vmetric = glyph.vmetric || defaultVMetrics;
  4234. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  4235. vx = -vx * widthAdvanceScale;
  4236. vy = vmetric[2] * widthAdvanceScale;
  4237. width = vmetric ? -vmetric[0] : width;
  4238. scaledX = vx / fontSizeScale;
  4239. scaledY = (x + vy) / fontSizeScale;
  4240. } else {
  4241. scaledX = x / fontSizeScale;
  4242. scaledY = 0;
  4243. }
  4244. if (font.remeasure && width > 0 && this.isFontSubpixelAAEnabled) {
  4245. // some standard fonts may not have the exact width, trying to
  4246. // rescale per character
  4247. var measuredWidth = ctx.measureText(character).width * 1000 /
  4248. fontSize * fontSizeScale;
  4249. var characterScaleX = width / measuredWidth;
  4250. restoreNeeded = true;
  4251. ctx.save();
  4252. ctx.scale(characterScaleX, 1);
  4253. scaledX /= characterScaleX;
  4254. }
  4255. if (simpleFillText && !accent) {
  4256. // common case
  4257. ctx.fillText(character, scaledX, scaledY);
  4258. } else {
  4259. this.paintChar(character, scaledX, scaledY);
  4260. if (accent) {
  4261. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  4262. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  4263. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  4264. }
  4265. }
  4266. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  4267. x += charWidth;
  4268. if (restoreNeeded) {
  4269. ctx.restore();
  4270. }
  4271. }
  4272. if (vertical) {
  4273. current.y -= x * textHScale;
  4274. } else {
  4275. current.x += x * textHScale;
  4276. }
  4277. ctx.restore();
  4278. },
  4279. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  4280. // Type3 fonts - each glyph is a "mini-PDF"
  4281. var ctx = this.ctx;
  4282. var current = this.current;
  4283. var font = current.font;
  4284. var fontSize = current.fontSize;
  4285. var fontDirection = current.fontDirection;
  4286. var charSpacing = current.charSpacing;
  4287. var wordSpacing = current.wordSpacing;
  4288. var textHScale = current.textHScale * fontDirection;
  4289. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  4290. var glyphsLength = glyphs.length;
  4291. var isTextInvisible =
  4292. current.textRenderingMode === TextRenderingMode.INVISIBLE;
  4293. var i, glyph, width;
  4294. if (isTextInvisible || fontSize === 0) {
  4295. return;
  4296. }
  4297. ctx.save();
  4298. ctx.transform.apply(ctx, current.textMatrix);
  4299. ctx.translate(current.x, current.y);
  4300. ctx.scale(textHScale, fontDirection);
  4301. for (i = 0; i < glyphsLength; ++i) {
  4302. glyph = glyphs[i];
  4303. if (glyph === null) {
  4304. // word break
  4305. this.ctx.translate(wordSpacing, 0);
  4306. current.x += wordSpacing * textHScale;
  4307. continue;
  4308. } else if (isNum(glyph)) {
  4309. var spacingLength = -glyph * 0.001 * fontSize;
  4310. this.ctx.translate(spacingLength, 0);
  4311. current.x += spacingLength * textHScale;
  4312. continue;
  4313. }
  4314. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  4315. if (!operatorList) {
  4316. warn('Type3 character \"' + glyph.operatorListId +
  4317. '\" is not available');
  4318. continue;
  4319. }
  4320. this.processingType3 = glyph;
  4321. this.save();
  4322. ctx.scale(fontSize, fontSize);
  4323. ctx.transform.apply(ctx, fontMatrix);
  4324. this.executeOperatorList(operatorList);
  4325. this.restore();
  4326. var transformed = Util.applyTransform([glyph.width, 0], fontMatrix);
  4327. width = transformed[0] * fontSize + charSpacing;
  4328. ctx.translate(width, 0);
  4329. current.x += width * textHScale;
  4330. }
  4331. ctx.restore();
  4332. this.processingType3 = null;
  4333. },
  4334. // Type3 fonts
  4335. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  4336. // We can safely ignore this since the width should be the same
  4337. // as the width in the Widths array.
  4338. },
  4339. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth,
  4340. yWidth,
  4341. llx,
  4342. lly,
  4343. urx,
  4344. ury) {
  4345. // TODO According to the spec we're also suppose to ignore any operators
  4346. // that set color or include images while processing this type3 font.
  4347. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  4348. this.clip();
  4349. this.endPath();
  4350. },
  4351. // Color
  4352. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  4353. var pattern;
  4354. if (IR[0] === 'TilingPattern') {
  4355. var color = IR[1];
  4356. pattern = new TilingPattern(IR, color, this.ctx, this.objs,
  4357. this.commonObjs, this.baseTransform);
  4358. } else {
  4359. pattern = getShadingPatternFromIR(IR);
  4360. }
  4361. return pattern;
  4362. },
  4363. setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) {
  4364. this.current.strokeColor = this.getColorN_Pattern(arguments);
  4365. },
  4366. setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) {
  4367. this.current.fillColor = this.getColorN_Pattern(arguments);
  4368. this.current.patternFill = true;
  4369. },
  4370. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  4371. var color = Util.makeCssRgb(r, g, b);
  4372. this.ctx.strokeStyle = color;
  4373. this.current.strokeColor = color;
  4374. },
  4375. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  4376. var color = Util.makeCssRgb(r, g, b);
  4377. this.ctx.fillStyle = color;
  4378. this.current.fillColor = color;
  4379. this.current.patternFill = false;
  4380. },
  4381. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  4382. var ctx = this.ctx;
  4383. this.save();
  4384. var pattern = getShadingPatternFromIR(patternIR);
  4385. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  4386. var inv = ctx.mozCurrentTransformInverse;
  4387. if (inv) {
  4388. var canvas = ctx.canvas;
  4389. var width = canvas.width;
  4390. var height = canvas.height;
  4391. var bl = Util.applyTransform([0, 0], inv);
  4392. var br = Util.applyTransform([0, height], inv);
  4393. var ul = Util.applyTransform([width, 0], inv);
  4394. var ur = Util.applyTransform([width, height], inv);
  4395. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  4396. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  4397. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  4398. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  4399. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  4400. } else {
  4401. // HACK to draw the gradient onto an infinite rectangle.
  4402. // PDF gradients are drawn across the entire image while
  4403. // Canvas only allows gradients to be drawn in a rectangle
  4404. // The following bug should allow us to remove this.
  4405. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  4406. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  4407. }
  4408. this.restore();
  4409. },
  4410. // Images
  4411. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  4412. error('Should not call beginInlineImage');
  4413. },
  4414. beginImageData: function CanvasGraphics_beginImageData() {
  4415. error('Should not call beginImageData');
  4416. },
  4417. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix,
  4418. bbox) {
  4419. this.save();
  4420. this.baseTransformStack.push(this.baseTransform);
  4421. if (isArray(matrix) && 6 === matrix.length) {
  4422. this.transform.apply(this, matrix);
  4423. }
  4424. this.baseTransform = this.ctx.mozCurrentTransform;
  4425. if (isArray(bbox) && 4 === bbox.length) {
  4426. var width = bbox[2] - bbox[0];
  4427. var height = bbox[3] - bbox[1];
  4428. this.ctx.rect(bbox[0], bbox[1], width, height);
  4429. this.clip();
  4430. this.endPath();
  4431. }
  4432. },
  4433. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  4434. this.restore();
  4435. this.baseTransform = this.baseTransformStack.pop();
  4436. },
  4437. beginGroup: function CanvasGraphics_beginGroup(group) {
  4438. this.save();
  4439. var currentCtx = this.ctx;
  4440. // TODO non-isolated groups - according to Rik at adobe non-isolated
  4441. // group results aren't usually that different and they even have tools
  4442. // that ignore this setting. Notes from Rik on implmenting:
  4443. // - When you encounter an transparency group, create a new canvas with
  4444. // the dimensions of the bbox
  4445. // - copy the content from the previous canvas to the new canvas
  4446. // - draw as usual
  4447. // - remove the backdrop alpha:
  4448. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  4449. // value of your transparency group and 'alphaBackdrop' the alpha of the
  4450. // backdrop
  4451. // - remove background color:
  4452. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  4453. if (!group.isolated) {
  4454. info('TODO: Support non-isolated groups.');
  4455. }
  4456. // TODO knockout - supposedly possible with the clever use of compositing
  4457. // modes.
  4458. if (group.knockout) {
  4459. warn('Knockout groups not supported.');
  4460. }
  4461. var currentTransform = currentCtx.mozCurrentTransform;
  4462. if (group.matrix) {
  4463. currentCtx.transform.apply(currentCtx, group.matrix);
  4464. }
  4465. assert(group.bbox, 'Bounding box is required.');
  4466. // Based on the current transform figure out how big the bounding box
  4467. // will actually be.
  4468. var bounds = Util.getAxialAlignedBoundingBox(
  4469. group.bbox,
  4470. currentCtx.mozCurrentTransform);
  4471. // Clip the bounding box to the current canvas.
  4472. var canvasBounds = [0,
  4473. 0,
  4474. currentCtx.canvas.width,
  4475. currentCtx.canvas.height];
  4476. bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
  4477. // Use ceil in case we're between sizes so we don't create canvas that is
  4478. // too small and make the canvas at least 1x1 pixels.
  4479. var offsetX = Math.floor(bounds[0]);
  4480. var offsetY = Math.floor(bounds[1]);
  4481. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  4482. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  4483. var scaleX = 1, scaleY = 1;
  4484. if (drawnWidth > MAX_GROUP_SIZE) {
  4485. scaleX = drawnWidth / MAX_GROUP_SIZE;
  4486. drawnWidth = MAX_GROUP_SIZE;
  4487. }
  4488. if (drawnHeight > MAX_GROUP_SIZE) {
  4489. scaleY = drawnHeight / MAX_GROUP_SIZE;
  4490. drawnHeight = MAX_GROUP_SIZE;
  4491. }
  4492. var cacheId = 'groupAt' + this.groupLevel;
  4493. if (group.smask) {
  4494. // Using two cache entries is case if masks are used one after another.
  4495. cacheId += '_smask_' + ((this.smaskCounter++) % 2);
  4496. }
  4497. var scratchCanvas = CachedCanvases.getCanvas(
  4498. cacheId, drawnWidth, drawnHeight, true);
  4499. var groupCtx = scratchCanvas.context;
  4500. // Since we created a new canvas that is just the size of the bounding box
  4501. // we have to translate the group ctx.
  4502. groupCtx.scale(1 / scaleX, 1 / scaleY);
  4503. groupCtx.translate(-offsetX, -offsetY);
  4504. groupCtx.transform.apply(groupCtx, currentTransform);
  4505. if (group.smask) {
  4506. // Saving state and cached mask to be used in setGState.
  4507. this.smaskStack.push({
  4508. canvas: scratchCanvas.canvas,
  4509. context: groupCtx,
  4510. offsetX: offsetX,
  4511. offsetY: offsetY,
  4512. scaleX: scaleX,
  4513. scaleY: scaleY,
  4514. subtype: group.smask.subtype,
  4515. backdrop: group.smask.backdrop
  4516. });
  4517. } else {
  4518. // Setup the current ctx so when the group is popped we draw it at the
  4519. // right location.
  4520. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  4521. currentCtx.translate(offsetX, offsetY);
  4522. currentCtx.scale(scaleX, scaleY);
  4523. }
  4524. // The transparency group inherits all off the current graphics state
  4525. // except the blend mode, soft mask, and alpha constants.
  4526. copyCtxState(currentCtx, groupCtx);
  4527. this.ctx = groupCtx;
  4528. this.setGState([
  4529. ['BM', 'Normal'],
  4530. ['ca', 1],
  4531. ['CA', 1]
  4532. ]);
  4533. this.groupStack.push(currentCtx);
  4534. this.groupLevel++;
  4535. },
  4536. endGroup: function CanvasGraphics_endGroup(group) {
  4537. this.groupLevel--;
  4538. var groupCtx = this.ctx;
  4539. this.ctx = this.groupStack.pop();
  4540. // Turn off image smoothing to avoid sub pixel interpolation which can
  4541. // look kind of blurry for some pdfs.
  4542. if (this.ctx.imageSmoothingEnabled !== undefined) {
  4543. this.ctx.imageSmoothingEnabled = false;
  4544. } else {
  4545. this.ctx.mozImageSmoothingEnabled = false;
  4546. }
  4547. if (group.smask) {
  4548. this.tempSMask = this.smaskStack.pop();
  4549. } else {
  4550. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  4551. }
  4552. this.restore();
  4553. },
  4554. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  4555. this.save();
  4556. this.current = new CanvasExtraState();
  4557. },
  4558. endAnnotations: function CanvasGraphics_endAnnotations() {
  4559. this.restore();
  4560. },
  4561. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform,
  4562. matrix) {
  4563. this.save();
  4564. if (isArray(rect) && 4 === rect.length) {
  4565. var width = rect[2] - rect[0];
  4566. var height = rect[3] - rect[1];
  4567. this.ctx.rect(rect[0], rect[1], width, height);
  4568. this.clip();
  4569. this.endPath();
  4570. }
  4571. this.transform.apply(this, transform);
  4572. this.transform.apply(this, matrix);
  4573. },
  4574. endAnnotation: function CanvasGraphics_endAnnotation() {
  4575. this.restore();
  4576. },
  4577. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  4578. var domImage = this.objs.get(objId);
  4579. if (!domImage) {
  4580. warn('Dependent image isn\'t ready yet');
  4581. return;
  4582. }
  4583. this.save();
  4584. var ctx = this.ctx;
  4585. // scale the image to the unit square
  4586. ctx.scale(1 / w, -1 / h);
  4587. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height,
  4588. 0, -h, w, h);
  4589. if (this.imageLayer) {
  4590. var currentTransform = ctx.mozCurrentTransformInverse;
  4591. var position = this.getCanvasPosition(0, 0);
  4592. this.imageLayer.appendImage({
  4593. objId: objId,
  4594. left: position[0],
  4595. top: position[1],
  4596. width: w / currentTransform[0],
  4597. height: h / currentTransform[3]
  4598. });
  4599. }
  4600. this.restore();
  4601. },
  4602. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  4603. var ctx = this.ctx;
  4604. var width = img.width, height = img.height;
  4605. var fillColor = this.current.fillColor;
  4606. var isPatternFill = this.current.patternFill;
  4607. var glyph = this.processingType3;
  4608. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  4609. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  4610. glyph.compiled =
  4611. compileType3Glyph({data: img.data, width: width, height: height});
  4612. } else {
  4613. glyph.compiled = null;
  4614. }
  4615. }
  4616. if (glyph && glyph.compiled) {
  4617. glyph.compiled(ctx);
  4618. return;
  4619. }
  4620. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4621. var maskCtx = maskCanvas.context;
  4622. maskCtx.save();
  4623. putBinaryImageMask(maskCtx, img);
  4624. maskCtx.globalCompositeOperation = 'source-in';
  4625. maskCtx.fillStyle = isPatternFill ?
  4626. fillColor.getPattern(maskCtx, this) : fillColor;
  4627. maskCtx.fillRect(0, 0, width, height);
  4628. maskCtx.restore();
  4629. this.paintInlineImageXObject(maskCanvas.canvas);
  4630. },
  4631. paintImageMaskXObjectRepeat:
  4632. function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX,
  4633. scaleY, positions) {
  4634. var width = imgData.width;
  4635. var height = imgData.height;
  4636. var fillColor = this.current.fillColor;
  4637. var isPatternFill = this.current.patternFill;
  4638. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4639. var maskCtx = maskCanvas.context;
  4640. maskCtx.save();
  4641. putBinaryImageMask(maskCtx, imgData);
  4642. maskCtx.globalCompositeOperation = 'source-in';
  4643. maskCtx.fillStyle = isPatternFill ?
  4644. fillColor.getPattern(maskCtx, this) : fillColor;
  4645. maskCtx.fillRect(0, 0, width, height);
  4646. maskCtx.restore();
  4647. var ctx = this.ctx;
  4648. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  4649. ctx.save();
  4650. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  4651. ctx.scale(1, -1);
  4652. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  4653. 0, -1, 1, 1);
  4654. ctx.restore();
  4655. }
  4656. },
  4657. paintImageMaskXObjectGroup:
  4658. function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  4659. var ctx = this.ctx;
  4660. var fillColor = this.current.fillColor;
  4661. var isPatternFill = this.current.patternFill;
  4662. for (var i = 0, ii = images.length; i < ii; i++) {
  4663. var image = images[i];
  4664. var width = image.width, height = image.height;
  4665. var maskCanvas = CachedCanvases.getCanvas('maskCanvas', width, height);
  4666. var maskCtx = maskCanvas.context;
  4667. maskCtx.save();
  4668. putBinaryImageMask(maskCtx, image);
  4669. maskCtx.globalCompositeOperation = 'source-in';
  4670. maskCtx.fillStyle = isPatternFill ?
  4671. fillColor.getPattern(maskCtx, this) : fillColor;
  4672. maskCtx.fillRect(0, 0, width, height);
  4673. maskCtx.restore();
  4674. ctx.save();
  4675. ctx.transform.apply(ctx, image.transform);
  4676. ctx.scale(1, -1);
  4677. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height,
  4678. 0, -1, 1, 1);
  4679. ctx.restore();
  4680. }
  4681. },
  4682. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  4683. var imgData = this.objs.get(objId);
  4684. if (!imgData) {
  4685. warn('Dependent image isn\'t ready yet');
  4686. return;
  4687. }
  4688. this.paintInlineImageXObject(imgData);
  4689. },
  4690. paintImageXObjectRepeat:
  4691. function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY,
  4692. positions) {
  4693. var imgData = this.objs.get(objId);
  4694. if (!imgData) {
  4695. warn('Dependent image isn\'t ready yet');
  4696. return;
  4697. }
  4698. var width = imgData.width;
  4699. var height = imgData.height;
  4700. var map = [];
  4701. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  4702. map.push({transform: [scaleX, 0, 0, scaleY, positions[i],
  4703. positions[i + 1]], x: 0, y: 0, w: width, h: height});
  4704. }
  4705. this.paintInlineImageXObjectGroup(imgData, map);
  4706. },
  4707. paintInlineImageXObject:
  4708. function CanvasGraphics_paintInlineImageXObject(imgData) {
  4709. var width = imgData.width;
  4710. var height = imgData.height;
  4711. var ctx = this.ctx;
  4712. this.save();
  4713. // scale the image to the unit square
  4714. ctx.scale(1 / width, -1 / height);
  4715. var currentTransform = ctx.mozCurrentTransformInverse;
  4716. var a = currentTransform[0], b = currentTransform[1];
  4717. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  4718. var c = currentTransform[2], d = currentTransform[3];
  4719. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  4720. var imgToPaint, tmpCanvas;
  4721. // instanceof HTMLElement does not work in jsdom node.js module
  4722. if (imgData instanceof HTMLElement || !imgData.data) {
  4723. imgToPaint = imgData;
  4724. } else {
  4725. tmpCanvas = CachedCanvases.getCanvas('inlineImage', width, height);
  4726. var tmpCtx = tmpCanvas.context;
  4727. putBinaryImageData(tmpCtx, imgData);
  4728. imgToPaint = tmpCanvas.canvas;
  4729. }
  4730. var paintWidth = width, paintHeight = height;
  4731. var tmpCanvasId = 'prescale1';
  4732. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  4733. // pixels during drawImage operation, painting on the temporary canvas(es)
  4734. // that are twice smaller in size
  4735. while ((widthScale > 2 && paintWidth > 1) ||
  4736. (heightScale > 2 && paintHeight > 1)) {
  4737. var newWidth = paintWidth, newHeight = paintHeight;
  4738. if (widthScale > 2 && paintWidth > 1) {
  4739. newWidth = Math.ceil(paintWidth / 2);
  4740. widthScale /= paintWidth / newWidth;
  4741. }
  4742. if (heightScale > 2 && paintHeight > 1) {
  4743. newHeight = Math.ceil(paintHeight / 2);
  4744. heightScale /= paintHeight / newHeight;
  4745. }
  4746. tmpCanvas = CachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  4747. tmpCtx = tmpCanvas.context;
  4748. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  4749. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  4750. 0, 0, newWidth, newHeight);
  4751. imgToPaint = tmpCanvas.canvas;
  4752. paintWidth = newWidth;
  4753. paintHeight = newHeight;
  4754. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  4755. }
  4756. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight,
  4757. 0, -height, width, height);
  4758. if (this.imageLayer) {
  4759. var position = this.getCanvasPosition(0, -height);
  4760. this.imageLayer.appendImage({
  4761. imgData: imgData,
  4762. left: position[0],
  4763. top: position[1],
  4764. width: width / currentTransform[0],
  4765. height: height / currentTransform[3]
  4766. });
  4767. }
  4768. this.restore();
  4769. },
  4770. paintInlineImageXObjectGroup:
  4771. function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  4772. var ctx = this.ctx;
  4773. var w = imgData.width;
  4774. var h = imgData.height;
  4775. var tmpCanvas = CachedCanvases.getCanvas('inlineImage', w, h);
  4776. var tmpCtx = tmpCanvas.context;
  4777. putBinaryImageData(tmpCtx, imgData);
  4778. for (var i = 0, ii = map.length; i < ii; i++) {
  4779. var entry = map[i];
  4780. ctx.save();
  4781. ctx.transform.apply(ctx, entry.transform);
  4782. ctx.scale(1, -1);
  4783. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h,
  4784. 0, -1, 1, 1);
  4785. if (this.imageLayer) {
  4786. var position = this.getCanvasPosition(entry.x, entry.y);
  4787. this.imageLayer.appendImage({
  4788. imgData: imgData,
  4789. left: position[0],
  4790. top: position[1],
  4791. width: w,
  4792. height: h
  4793. });
  4794. }
  4795. ctx.restore();
  4796. }
  4797. },
  4798. paintSolidColorImageMask:
  4799. function CanvasGraphics_paintSolidColorImageMask() {
  4800. this.ctx.fillRect(0, 0, 1, 1);
  4801. },
  4802. // Marked content
  4803. markPoint: function CanvasGraphics_markPoint(tag) {
  4804. // TODO Marked content.
  4805. },
  4806. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  4807. // TODO Marked content.
  4808. },
  4809. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  4810. // TODO Marked content.
  4811. },
  4812. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(
  4813. tag, properties) {
  4814. // TODO Marked content.
  4815. },
  4816. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  4817. // TODO Marked content.
  4818. },
  4819. // Compatibility
  4820. beginCompat: function CanvasGraphics_beginCompat() {
  4821. // TODO ignore undefined operators (should we do that anyway?)
  4822. },
  4823. endCompat: function CanvasGraphics_endCompat() {
  4824. // TODO stop ignoring undefined operators
  4825. },
  4826. // Helper functions
  4827. consumePath: function CanvasGraphics_consumePath() {
  4828. var ctx = this.ctx;
  4829. if (this.pendingClip) {
  4830. if (this.pendingClip === EO_CLIP) {
  4831. if (ctx.mozFillRule !== undefined) {
  4832. ctx.mozFillRule = 'evenodd';
  4833. ctx.clip();
  4834. ctx.mozFillRule = 'nonzero';
  4835. } else {
  4836. try {
  4837. ctx.clip('evenodd');
  4838. } catch (ex) {
  4839. // shouldn't really happen, but browsers might think differently
  4840. ctx.clip();
  4841. }
  4842. }
  4843. } else {
  4844. ctx.clip();
  4845. }
  4846. this.pendingClip = null;
  4847. }
  4848. ctx.beginPath();
  4849. },
  4850. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  4851. if (this.cachedGetSinglePixelWidth === null) {
  4852. var inverse = this.ctx.mozCurrentTransformInverse;
  4853. // max of the current horizontal and vertical scale
  4854. this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(
  4855. (inverse[0] * inverse[0] + inverse[1] * inverse[1]),
  4856. (inverse[2] * inverse[2] + inverse[3] * inverse[3])));
  4857. }
  4858. return this.cachedGetSinglePixelWidth;
  4859. },
  4860. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  4861. var transform = this.ctx.mozCurrentTransform;
  4862. return [
  4863. transform[0] * x + transform[2] * y + transform[4],
  4864. transform[1] * x + transform[3] * y + transform[5]
  4865. ];
  4866. }
  4867. };
  4868. for (var op in OPS) {
  4869. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  4870. }
  4871. return CanvasGraphics;
  4872. })();
  4873. var WebGLUtils = (function WebGLUtilsClosure() {
  4874. function loadShader(gl, code, shaderType) {
  4875. var shader = gl.createShader(shaderType);
  4876. gl.shaderSource(shader, code);
  4877. gl.compileShader(shader);
  4878. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  4879. if (!compiled) {
  4880. var errorMsg = gl.getShaderInfoLog(shader);
  4881. throw new Error('Error during shader compilation: ' + errorMsg);
  4882. }
  4883. return shader;
  4884. }
  4885. function createVertexShader(gl, code) {
  4886. return loadShader(gl, code, gl.VERTEX_SHADER);
  4887. }
  4888. function createFragmentShader(gl, code) {
  4889. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  4890. }
  4891. function createProgram(gl, shaders) {
  4892. var program = gl.createProgram();
  4893. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  4894. gl.attachShader(program, shaders[i]);
  4895. }
  4896. gl.linkProgram(program);
  4897. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  4898. if (!linked) {
  4899. var errorMsg = gl.getProgramInfoLog(program);
  4900. throw new Error('Error during program linking: ' + errorMsg);
  4901. }
  4902. return program;
  4903. }
  4904. function createTexture(gl, image, textureId) {
  4905. gl.activeTexture(textureId);
  4906. var texture = gl.createTexture();
  4907. gl.bindTexture(gl.TEXTURE_2D, texture);
  4908. // Set the parameters so we can render any size image.
  4909. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4910. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4911. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4912. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4913. // Upload the image into the texture.
  4914. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  4915. return texture;
  4916. }
  4917. var currentGL, currentCanvas;
  4918. function generateGL() {
  4919. if (currentGL) {
  4920. return;
  4921. }
  4922. currentCanvas = document.createElement('canvas');
  4923. currentGL = currentCanvas.getContext('webgl',
  4924. { premultipliedalpha: false });
  4925. }
  4926. var smaskVertexShaderCode = '\
  4927. attribute vec2 a_position; \
  4928. attribute vec2 a_texCoord; \
  4929. \
  4930. uniform vec2 u_resolution; \
  4931. \
  4932. varying vec2 v_texCoord; \
  4933. \
  4934. void main() { \
  4935. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  4936. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  4937. \
  4938. v_texCoord = a_texCoord; \
  4939. } ';
  4940. var smaskFragmentShaderCode = '\
  4941. precision mediump float; \
  4942. \
  4943. uniform vec4 u_backdrop; \
  4944. uniform int u_subtype; \
  4945. uniform sampler2D u_image; \
  4946. uniform sampler2D u_mask; \
  4947. \
  4948. varying vec2 v_texCoord; \
  4949. \
  4950. void main() { \
  4951. vec4 imageColor = texture2D(u_image, v_texCoord); \
  4952. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  4953. if (u_backdrop.a > 0.0) { \
  4954. maskColor.rgb = maskColor.rgb * maskColor.a + \
  4955. u_backdrop.rgb * (1.0 - maskColor.a); \
  4956. } \
  4957. float lum; \
  4958. if (u_subtype == 0) { \
  4959. lum = maskColor.a; \
  4960. } else { \
  4961. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  4962. maskColor.b * 0.11; \
  4963. } \
  4964. imageColor.a *= lum; \
  4965. imageColor.rgb *= imageColor.a; \
  4966. gl_FragColor = imageColor; \
  4967. } ';
  4968. var smaskCache = null;
  4969. function initSmaskGL() {
  4970. var canvas, gl;
  4971. generateGL();
  4972. canvas = currentCanvas;
  4973. currentCanvas = null;
  4974. gl = currentGL;
  4975. currentGL = null;
  4976. // setup a GLSL program
  4977. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  4978. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  4979. var program = createProgram(gl, [vertexShader, fragmentShader]);
  4980. gl.useProgram(program);
  4981. var cache = {};
  4982. cache.gl = gl;
  4983. cache.canvas = canvas;
  4984. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  4985. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  4986. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  4987. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  4988. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  4989. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  4990. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  4991. // provide texture coordinates for the rectangle.
  4992. var texCoordBuffer = gl.createBuffer();
  4993. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  4994. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  4995. 0.0, 0.0,
  4996. 1.0, 0.0,
  4997. 0.0, 1.0,
  4998. 0.0, 1.0,
  4999. 1.0, 0.0,
  5000. 1.0, 1.0]), gl.STATIC_DRAW);
  5001. gl.enableVertexAttribArray(texCoordLocation);
  5002. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  5003. gl.uniform1i(texLayerLocation, 0);
  5004. gl.uniform1i(texMaskLocation, 1);
  5005. smaskCache = cache;
  5006. }
  5007. function composeSMask(layer, mask, properties) {
  5008. var width = layer.width, height = layer.height;
  5009. if (!smaskCache) {
  5010. initSmaskGL();
  5011. }
  5012. var cache = smaskCache,canvas = cache.canvas, gl = cache.gl;
  5013. canvas.width = width;
  5014. canvas.height = height;
  5015. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5016. gl.uniform2f(cache.resolutionLocation, width, height);
  5017. if (properties.backdrop) {
  5018. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0],
  5019. properties.backdrop[1], properties.backdrop[2], 1);
  5020. } else {
  5021. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  5022. }
  5023. gl.uniform1i(cache.subtypeLocation,
  5024. properties.subtype === 'Luminosity' ? 1 : 0);
  5025. // Create a textures
  5026. var texture = createTexture(gl, layer, gl.TEXTURE0);
  5027. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  5028. // Create a buffer and put a single clipspace rectangle in
  5029. // it (2 triangles)
  5030. var buffer = gl.createBuffer();
  5031. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  5032. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5033. 0, 0,
  5034. width, 0,
  5035. 0, height,
  5036. 0, height,
  5037. width, 0,
  5038. width, height]), gl.STATIC_DRAW);
  5039. gl.enableVertexAttribArray(cache.positionLocation);
  5040. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5041. // draw
  5042. gl.clearColor(0, 0, 0, 0);
  5043. gl.enable(gl.BLEND);
  5044. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  5045. gl.clear(gl.COLOR_BUFFER_BIT);
  5046. gl.drawArrays(gl.TRIANGLES, 0, 6);
  5047. gl.flush();
  5048. gl.deleteTexture(texture);
  5049. gl.deleteTexture(maskTexture);
  5050. gl.deleteBuffer(buffer);
  5051. return canvas;
  5052. }
  5053. var figuresVertexShaderCode = '\
  5054. attribute vec2 a_position; \
  5055. attribute vec3 a_color; \
  5056. \
  5057. uniform vec2 u_resolution; \
  5058. uniform vec2 u_scale; \
  5059. uniform vec2 u_offset; \
  5060. \
  5061. varying vec4 v_color; \
  5062. \
  5063. void main() { \
  5064. vec2 position = (a_position + u_offset) * u_scale; \
  5065. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  5066. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5067. \
  5068. v_color = vec4(a_color / 255.0, 1.0); \
  5069. } ';
  5070. var figuresFragmentShaderCode = '\
  5071. precision mediump float; \
  5072. \
  5073. varying vec4 v_color; \
  5074. \
  5075. void main() { \
  5076. gl_FragColor = v_color; \
  5077. } ';
  5078. var figuresCache = null;
  5079. function initFiguresGL() {
  5080. var canvas, gl;
  5081. generateGL();
  5082. canvas = currentCanvas;
  5083. currentCanvas = null;
  5084. gl = currentGL;
  5085. currentGL = null;
  5086. // setup a GLSL program
  5087. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  5088. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  5089. var program = createProgram(gl, [vertexShader, fragmentShader]);
  5090. gl.useProgram(program);
  5091. var cache = {};
  5092. cache.gl = gl;
  5093. cache.canvas = canvas;
  5094. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5095. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  5096. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  5097. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5098. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  5099. figuresCache = cache;
  5100. }
  5101. function drawFigures(width, height, backgroundColor, figures, context) {
  5102. if (!figuresCache) {
  5103. initFiguresGL();
  5104. }
  5105. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  5106. canvas.width = width;
  5107. canvas.height = height;
  5108. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5109. gl.uniform2f(cache.resolutionLocation, width, height);
  5110. // count triangle points
  5111. var count = 0;
  5112. var i, ii, rows;
  5113. for (i = 0, ii = figures.length; i < ii; i++) {
  5114. switch (figures[i].type) {
  5115. case 'lattice':
  5116. rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0;
  5117. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  5118. break;
  5119. case 'triangles':
  5120. count += figures[i].coords.length;
  5121. break;
  5122. }
  5123. }
  5124. // transfer data
  5125. var coords = new Float32Array(count * 2);
  5126. var colors = new Uint8Array(count * 3);
  5127. var coordsMap = context.coords, colorsMap = context.colors;
  5128. var pIndex = 0, cIndex = 0;
  5129. for (i = 0, ii = figures.length; i < ii; i++) {
  5130. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  5131. switch (figure.type) {
  5132. case 'lattice':
  5133. var cols = figure.verticesPerRow;
  5134. rows = (ps.length / cols) | 0;
  5135. for (var row = 1; row < rows; row++) {
  5136. var offset = row * cols + 1;
  5137. for (var col = 1; col < cols; col++, offset++) {
  5138. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  5139. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  5140. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  5141. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  5142. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  5143. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  5144. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  5145. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  5146. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  5147. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  5148. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  5149. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  5150. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  5151. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  5152. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  5153. coords[pIndex + 6] = coords[pIndex + 2];
  5154. coords[pIndex + 7] = coords[pIndex + 3];
  5155. coords[pIndex + 8] = coords[pIndex + 4];
  5156. coords[pIndex + 9] = coords[pIndex + 5];
  5157. coords[pIndex + 10] = coordsMap[ps[offset]];
  5158. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  5159. colors[cIndex + 9] = colors[cIndex + 3];
  5160. colors[cIndex + 10] = colors[cIndex + 4];
  5161. colors[cIndex + 11] = colors[cIndex + 5];
  5162. colors[cIndex + 12] = colors[cIndex + 6];
  5163. colors[cIndex + 13] = colors[cIndex + 7];
  5164. colors[cIndex + 14] = colors[cIndex + 8];
  5165. colors[cIndex + 15] = colorsMap[cs[offset]];
  5166. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  5167. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  5168. pIndex += 12;
  5169. cIndex += 18;
  5170. }
  5171. }
  5172. break;
  5173. case 'triangles':
  5174. for (var j = 0, jj = ps.length; j < jj; j++) {
  5175. coords[pIndex] = coordsMap[ps[j]];
  5176. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  5177. colors[cIndex] = colorsMap[cs[i]];
  5178. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  5179. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  5180. pIndex += 2;
  5181. cIndex += 3;
  5182. }
  5183. break;
  5184. }
  5185. }
  5186. // draw
  5187. if (backgroundColor) {
  5188. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255,
  5189. backgroundColor[2] / 255, 1.0);
  5190. } else {
  5191. gl.clearColor(0, 0, 0, 0);
  5192. }
  5193. gl.clear(gl.COLOR_BUFFER_BIT);
  5194. var coordsBuffer = gl.createBuffer();
  5195. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  5196. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  5197. gl.enableVertexAttribArray(cache.positionLocation);
  5198. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5199. var colorsBuffer = gl.createBuffer();
  5200. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  5201. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  5202. gl.enableVertexAttribArray(cache.colorLocation);
  5203. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false,
  5204. 0, 0);
  5205. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  5206. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  5207. gl.drawArrays(gl.TRIANGLES, 0, count);
  5208. gl.flush();
  5209. gl.deleteBuffer(coordsBuffer);
  5210. gl.deleteBuffer(colorsBuffer);
  5211. return canvas;
  5212. }
  5213. function cleanup() {
  5214. if (smaskCache && smaskCache.canvas) {
  5215. smaskCache.canvas.width = 0;
  5216. smaskCache.canvas.height = 0;
  5217. }
  5218. if (figuresCache && figuresCache.canvas) {
  5219. figuresCache.canvas.width = 0;
  5220. figuresCache.canvas.height = 0;
  5221. }
  5222. smaskCache = null;
  5223. figuresCache = null;
  5224. }
  5225. return {
  5226. get isEnabled() {
  5227. if (PDFJS.disableWebGL) {
  5228. return false;
  5229. }
  5230. var enabled = false;
  5231. try {
  5232. generateGL();
  5233. enabled = !!currentGL;
  5234. } catch (e) { }
  5235. return shadow(this, 'isEnabled', enabled);
  5236. },
  5237. composeSMask: composeSMask,
  5238. drawFigures: drawFigures,
  5239. clear: cleanup
  5240. };
  5241. })();
  5242. var ShadingIRs = {};
  5243. ShadingIRs.RadialAxial = {
  5244. fromIR: function RadialAxial_fromIR(raw) {
  5245. var type = raw[1];
  5246. var colorStops = raw[2];
  5247. var p0 = raw[3];
  5248. var p1 = raw[4];
  5249. var r0 = raw[5];
  5250. var r1 = raw[6];
  5251. return {
  5252. type: 'Pattern',
  5253. getPattern: function RadialAxial_getPattern(ctx) {
  5254. var grad;
  5255. if (type === 'axial') {
  5256. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  5257. } else if (type === 'radial') {
  5258. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  5259. }
  5260. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  5261. var c = colorStops[i];
  5262. grad.addColorStop(c[0], c[1]);
  5263. }
  5264. return grad;
  5265. }
  5266. };
  5267. }
  5268. };
  5269. var createMeshCanvas = (function createMeshCanvasClosure() {
  5270. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5271. // Very basic Gouraud-shaded triangle rasterization algorithm.
  5272. var coords = context.coords, colors = context.colors;
  5273. var bytes = data.data, rowSize = data.width * 4;
  5274. var tmp;
  5275. if (coords[p1 + 1] > coords[p2 + 1]) {
  5276. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5277. }
  5278. if (coords[p2 + 1] > coords[p3 + 1]) {
  5279. tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp;
  5280. }
  5281. if (coords[p1 + 1] > coords[p2 + 1]) {
  5282. tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp;
  5283. }
  5284. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  5285. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  5286. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  5287. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  5288. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  5289. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  5290. if (y1 >= y3) {
  5291. return;
  5292. }
  5293. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  5294. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  5295. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  5296. var minY = Math.round(y1), maxY = Math.round(y3);
  5297. var xa, car, cag, cab;
  5298. var xb, cbr, cbg, cbb;
  5299. var k;
  5300. for (var y = minY; y <= maxY; y++) {
  5301. if (y < y2) {
  5302. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  5303. xa = x1 - (x1 - x2) * k;
  5304. car = c1r - (c1r - c2r) * k;
  5305. cag = c1g - (c1g - c2g) * k;
  5306. cab = c1b - (c1b - c2b) * k;
  5307. } else {
  5308. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  5309. xa = x2 - (x2 - x3) * k;
  5310. car = c2r - (c2r - c3r) * k;
  5311. cag = c2g - (c2g - c3g) * k;
  5312. cab = c2b - (c2b - c3b) * k;
  5313. }
  5314. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  5315. xb = x1 - (x1 - x3) * k;
  5316. cbr = c1r - (c1r - c3r) * k;
  5317. cbg = c1g - (c1g - c3g) * k;
  5318. cbb = c1b - (c1b - c3b) * k;
  5319. var x1_ = Math.round(Math.min(xa, xb));
  5320. var x2_ = Math.round(Math.max(xa, xb));
  5321. var j = rowSize * y + x1_ * 4;
  5322. for (var x = x1_; x <= x2_; x++) {
  5323. k = (xa - x) / (xa - xb);
  5324. k = k < 0 ? 0 : k > 1 ? 1 : k;
  5325. bytes[j++] = (car - (car - cbr) * k) | 0;
  5326. bytes[j++] = (cag - (cag - cbg) * k) | 0;
  5327. bytes[j++] = (cab - (cab - cbb) * k) | 0;
  5328. bytes[j++] = 255;
  5329. }
  5330. }
  5331. }
  5332. function drawFigure(data, figure, context) {
  5333. var ps = figure.coords;
  5334. var cs = figure.colors;
  5335. var i, ii;
  5336. switch (figure.type) {
  5337. case 'lattice':
  5338. var verticesPerRow = figure.verticesPerRow;
  5339. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  5340. var cols = verticesPerRow - 1;
  5341. for (i = 0; i < rows; i++) {
  5342. var q = i * verticesPerRow;
  5343. for (var j = 0; j < cols; j++, q++) {
  5344. drawTriangle(data, context,
  5345. ps[q], ps[q + 1], ps[q + verticesPerRow],
  5346. cs[q], cs[q + 1], cs[q + verticesPerRow]);
  5347. drawTriangle(data, context,
  5348. ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow],
  5349. cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  5350. }
  5351. }
  5352. break;
  5353. case 'triangles':
  5354. for (i = 0, ii = ps.length; i < ii; i += 3) {
  5355. drawTriangle(data, context,
  5356. ps[i], ps[i + 1], ps[i + 2],
  5357. cs[i], cs[i + 1], cs[i + 2]);
  5358. }
  5359. break;
  5360. default:
  5361. error('illigal figure');
  5362. break;
  5363. }
  5364. }
  5365. function createMeshCanvas(bounds, combinesScale, coords, colors, figures,
  5366. backgroundColor) {
  5367. // we will increase scale on some weird factor to let antialiasing take
  5368. // care of "rough" edges
  5369. var EXPECTED_SCALE = 1.1;
  5370. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5371. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5372. var offsetX = Math.floor(bounds[0]);
  5373. var offsetY = Math.floor(bounds[1]);
  5374. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  5375. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  5376. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] *
  5377. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5378. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] *
  5379. EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  5380. var scaleX = boundsWidth / width;
  5381. var scaleY = boundsHeight / height;
  5382. var context = {
  5383. coords: coords,
  5384. colors: colors,
  5385. offsetX: -offsetX,
  5386. offsetY: -offsetY,
  5387. scaleX: 1 / scaleX,
  5388. scaleY: 1 / scaleY
  5389. };
  5390. var canvas, tmpCanvas, i, ii;
  5391. if (WebGLUtils.isEnabled) {
  5392. canvas = WebGLUtils.drawFigures(width, height, backgroundColor,
  5393. figures, context);
  5394. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  5395. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  5396. tmpCanvas.context.drawImage(canvas, 0, 0);
  5397. canvas = tmpCanvas.canvas;
  5398. } else {
  5399. tmpCanvas = CachedCanvases.getCanvas('mesh', width, height, false);
  5400. var tmpCtx = tmpCanvas.context;
  5401. var data = tmpCtx.createImageData(width, height);
  5402. if (backgroundColor) {
  5403. var bytes = data.data;
  5404. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  5405. bytes[i] = backgroundColor[0];
  5406. bytes[i + 1] = backgroundColor[1];
  5407. bytes[i + 2] = backgroundColor[2];
  5408. bytes[i + 3] = 255;
  5409. }
  5410. }
  5411. for (i = 0; i < figures.length; i++) {
  5412. drawFigure(data, figures[i], context);
  5413. }
  5414. tmpCtx.putImageData(data, 0, 0);
  5415. canvas = tmpCanvas.canvas;
  5416. }
  5417. return {canvas: canvas, offsetX: offsetX, offsetY: offsetY,
  5418. scaleX: scaleX, scaleY: scaleY};
  5419. }
  5420. return createMeshCanvas;
  5421. })();
  5422. ShadingIRs.Mesh = {
  5423. fromIR: function Mesh_fromIR(raw) {
  5424. //var type = raw[1];
  5425. var coords = raw[2];
  5426. var colors = raw[3];
  5427. var figures = raw[4];
  5428. var bounds = raw[5];
  5429. var matrix = raw[6];
  5430. //var bbox = raw[7];
  5431. var background = raw[8];
  5432. return {
  5433. type: 'Pattern',
  5434. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  5435. var scale;
  5436. if (shadingFill) {
  5437. scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  5438. } else {
  5439. // Obtain scale from matrix and current transformation matrix.
  5440. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  5441. if (matrix) {
  5442. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  5443. scale = [scale[0] * matrixScale[0],
  5444. scale[1] * matrixScale[1]];
  5445. }
  5446. }
  5447. // Rasterizing on the main thread since sending/queue large canvases
  5448. // might cause OOM.
  5449. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords,
  5450. colors, figures, shadingFill ? null : background);
  5451. if (!shadingFill) {
  5452. ctx.setTransform.apply(ctx, owner.baseTransform);
  5453. if (matrix) {
  5454. ctx.transform.apply(ctx, matrix);
  5455. }
  5456. }
  5457. ctx.translate(temporaryPatternCanvas.offsetX,
  5458. temporaryPatternCanvas.offsetY);
  5459. ctx.scale(temporaryPatternCanvas.scaleX,
  5460. temporaryPatternCanvas.scaleY);
  5461. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  5462. }
  5463. };
  5464. }
  5465. };
  5466. ShadingIRs.Dummy = {
  5467. fromIR: function Dummy_fromIR() {
  5468. return {
  5469. type: 'Pattern',
  5470. getPattern: function Dummy_fromIR_getPattern() {
  5471. return 'hotpink';
  5472. }
  5473. };
  5474. }
  5475. };
  5476. function getShadingPatternFromIR(raw) {
  5477. var shadingIR = ShadingIRs[raw[0]];
  5478. if (!shadingIR) {
  5479. error('Unknown IR type: ' + raw[0]);
  5480. }
  5481. return shadingIR.fromIR(raw);
  5482. }
  5483. var TilingPattern = (function TilingPatternClosure() {
  5484. var PaintType = {
  5485. COLORED: 1,
  5486. UNCOLORED: 2
  5487. };
  5488. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough
  5489. function TilingPattern(IR, color, ctx, objs, commonObjs, baseTransform) {
  5490. this.operatorList = IR[2];
  5491. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  5492. this.bbox = IR[4];
  5493. this.xstep = IR[5];
  5494. this.ystep = IR[6];
  5495. this.paintType = IR[7];
  5496. this.tilingType = IR[8];
  5497. this.color = color;
  5498. this.objs = objs;
  5499. this.commonObjs = commonObjs;
  5500. this.baseTransform = baseTransform;
  5501. this.type = 'Pattern';
  5502. this.ctx = ctx;
  5503. }
  5504. TilingPattern.prototype = {
  5505. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  5506. var operatorList = this.operatorList;
  5507. var bbox = this.bbox;
  5508. var xstep = this.xstep;
  5509. var ystep = this.ystep;
  5510. var paintType = this.paintType;
  5511. var tilingType = this.tilingType;
  5512. var color = this.color;
  5513. var objs = this.objs;
  5514. var commonObjs = this.commonObjs;
  5515. info('TilingType: ' + tilingType);
  5516. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  5517. var topLeft = [x0, y0];
  5518. // we want the canvas to be as large as the step size
  5519. var botRight = [x0 + xstep, y0 + ystep];
  5520. var width = botRight[0] - topLeft[0];
  5521. var height = botRight[1] - topLeft[1];
  5522. // Obtain scale from matrix and current transformation matrix.
  5523. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  5524. var curMatrixScale = Util.singularValueDecompose2dScale(
  5525. this.baseTransform);
  5526. var combinedScale = [matrixScale[0] * curMatrixScale[0],
  5527. matrixScale[1] * curMatrixScale[1]];
  5528. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  5529. // Use width and height values that are as close as possible to the end
  5530. // result when the pattern is used. Too low value makes the pattern look
  5531. // blurry. Too large value makes it look too crispy.
  5532. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])),
  5533. MAX_PATTERN_SIZE);
  5534. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])),
  5535. MAX_PATTERN_SIZE);
  5536. var tmpCanvas = CachedCanvases.getCanvas('pattern', width, height, true);
  5537. var tmpCtx = tmpCanvas.context;
  5538. var graphics = new CanvasGraphics(tmpCtx, commonObjs, objs);
  5539. graphics.groupLevel = owner.groupLevel;
  5540. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  5541. this.setScale(width, height, xstep, ystep);
  5542. this.transformToScale(graphics);
  5543. // transform coordinates to pattern space
  5544. var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
  5545. graphics.transform.apply(graphics, tmpTranslate);
  5546. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  5547. graphics.executeOperatorList(operatorList);
  5548. return tmpCanvas.canvas;
  5549. },
  5550. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  5551. this.scale = [width / xstep, height / ystep];
  5552. },
  5553. transformToScale: function TilingPattern_transformToScale(graphics) {
  5554. var scale = this.scale;
  5555. var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
  5556. graphics.transform.apply(graphics, tmpScale);
  5557. },
  5558. scaleToContext: function TilingPattern_scaleToContext() {
  5559. var scale = this.scale;
  5560. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  5561. },
  5562. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  5563. if (bbox && isArray(bbox) && bbox.length === 4) {
  5564. var bboxWidth = x1 - x0;
  5565. var bboxHeight = y1 - y0;
  5566. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  5567. graphics.clip();
  5568. graphics.endPath();
  5569. }
  5570. },
  5571. setFillAndStrokeStyleToContext:
  5572. function setFillAndStrokeStyleToContext(context, paintType, color) {
  5573. switch (paintType) {
  5574. case PaintType.COLORED:
  5575. var ctx = this.ctx;
  5576. context.fillStyle = ctx.fillStyle;
  5577. context.strokeStyle = ctx.strokeStyle;
  5578. break;
  5579. case PaintType.UNCOLORED:
  5580. var cssColor = Util.makeCssRgb(color[0], color[1], color[2]);
  5581. context.fillStyle = cssColor;
  5582. context.strokeStyle = cssColor;
  5583. break;
  5584. default:
  5585. error('Unsupported paint type: ' + paintType);
  5586. }
  5587. },
  5588. getPattern: function TilingPattern_getPattern(ctx, owner) {
  5589. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  5590. ctx = this.ctx;
  5591. ctx.setTransform.apply(ctx, this.baseTransform);
  5592. ctx.transform.apply(ctx, this.matrix);
  5593. this.scaleToContext();
  5594. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  5595. }
  5596. };
  5597. return TilingPattern;
  5598. })();
  5599. PDFJS.disableFontFace = false;
  5600. var FontLoader = {
  5601. insertRule: function fontLoaderInsertRule(rule) {
  5602. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  5603. if (!styleElement) {
  5604. styleElement = document.createElement('style');
  5605. styleElement.id = 'PDFJS_FONT_STYLE_TAG';
  5606. document.documentElement.getElementsByTagName('head')[0].appendChild(
  5607. styleElement);
  5608. }
  5609. var styleSheet = styleElement.sheet;
  5610. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  5611. },
  5612. clear: function fontLoaderClear() {
  5613. var styleElement = document.getElementById('PDFJS_FONT_STYLE_TAG');
  5614. if (styleElement) {
  5615. styleElement.parentNode.removeChild(styleElement);
  5616. }
  5617. //#if !(MOZCENTRAL)
  5618. this.nativeFontFaces.forEach(function(nativeFontFace) {
  5619. document.fonts.delete(nativeFontFace);
  5620. });
  5621. this.nativeFontFaces.length = 0;
  5622. //#endif
  5623. },
  5624. //#if !(MOZCENTRAL)
  5625. get loadTestFont() {
  5626. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  5627. // height.
  5628. return shadow(this, 'loadTestFont', atob(
  5629. 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' +
  5630. 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' +
  5631. 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' +
  5632. 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' +
  5633. 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' +
  5634. 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' +
  5635. 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' +
  5636. 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' +
  5637. 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' +
  5638. 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' +
  5639. 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' +
  5640. 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' +
  5641. 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' +
  5642. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5643. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5644. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' +
  5645. 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' +
  5646. 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' +
  5647. 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' +
  5648. 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' +
  5649. 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' +
  5650. 'ABAAAAAAAAAAAD6AAAAAAAAA=='
  5651. ));
  5652. },
  5653. loadTestFontId: 0,
  5654. loadingContext: {
  5655. requests: [],
  5656. nextRequestId: 0
  5657. },
  5658. isSyncFontLoadingSupported: (function detectSyncFontLoadingSupport() {
  5659. if (isWorker) {
  5660. return false;
  5661. }
  5662. // User agent string sniffing is bad, but there is no reliable way to tell
  5663. // if font is fully loaded and ready to be used with canvas.
  5664. var userAgent = window.navigator.userAgent;
  5665. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent);
  5666. if (m && m[1] >= 14) {
  5667. return true;
  5668. }
  5669. // TODO other browsers
  5670. if (userAgent === 'node') {
  5671. return true;
  5672. }
  5673. return false;
  5674. })(),
  5675. nativeFontFaces: [],
  5676. isFontLoadingAPISupported: (!isWorker && typeof document !== 'undefined' &&
  5677. !!document.fonts),
  5678. addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) {
  5679. this.nativeFontFaces.push(nativeFontFace);
  5680. document.fonts.add(nativeFontFace);
  5681. },
  5682. bind: function fontLoaderBind(fonts, callback) {
  5683. assert(!isWorker, 'bind() shall be called from main thread');
  5684. var rules = [];
  5685. var fontsToLoad = [];
  5686. var fontLoadPromises = [];
  5687. for (var i = 0, ii = fonts.length; i < ii; i++) {
  5688. var font = fonts[i];
  5689. // Add the font to the DOM only once or skip if the font
  5690. // is already loaded.
  5691. if (font.attached || font.loading === false) {
  5692. continue;
  5693. }
  5694. font.attached = true;
  5695. if (this.isFontLoadingAPISupported) {
  5696. var nativeFontFace = font.createNativeFontFace();
  5697. if (nativeFontFace) {
  5698. fontLoadPromises.push(nativeFontFace.loaded);
  5699. }
  5700. } else {
  5701. var rule = font.bindDOM();
  5702. if (rule) {
  5703. rules.push(rule);
  5704. fontsToLoad.push(font);
  5705. }
  5706. }
  5707. }
  5708. var request = FontLoader.queueLoadingCallback(callback);
  5709. if (this.isFontLoadingAPISupported) {
  5710. Promise.all(fontsToLoad).then(function() {
  5711. request.complete();
  5712. });
  5713. } else if (rules.length > 0 && !this.isSyncFontLoadingSupported) {
  5714. FontLoader.prepareFontLoadEvent(rules, fontsToLoad, request);
  5715. } else {
  5716. request.complete();
  5717. }
  5718. },
  5719. queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) {
  5720. function LoadLoader_completeRequest() {
  5721. assert(!request.end, 'completeRequest() cannot be called twice');
  5722. request.end = Date.now();
  5723. // sending all completed requests in order how they were queued
  5724. while (context.requests.length > 0 && context.requests[0].end) {
  5725. var otherRequest = context.requests.shift();
  5726. setTimeout(otherRequest.callback, 0);
  5727. }
  5728. }
  5729. var context = FontLoader.loadingContext;
  5730. var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++);
  5731. var request = {
  5732. id: requestId,
  5733. complete: LoadLoader_completeRequest,
  5734. callback: callback,
  5735. started: Date.now()
  5736. };
  5737. context.requests.push(request);
  5738. return request;
  5739. },
  5740. prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules,
  5741. fonts,
  5742. request) {
  5743. /** Hack begin */
  5744. // There's currently no event when a font has finished downloading so the
  5745. // following code is a dirty hack to 'guess' when a font is
  5746. // ready. It's assumed fonts are loaded in order, so add a known test
  5747. // font after the desired fonts and then test for the loading of that
  5748. // test font.
  5749. function int32(data, offset) {
  5750. return (data.charCodeAt(offset) << 24) |
  5751. (data.charCodeAt(offset + 1) << 16) |
  5752. (data.charCodeAt(offset + 2) << 8) |
  5753. (data.charCodeAt(offset + 3) & 0xff);
  5754. }
  5755. function spliceString(s, offset, remove, insert) {
  5756. var chunk1 = s.substr(0, offset);
  5757. var chunk2 = s.substr(offset + remove);
  5758. return chunk1 + insert + chunk2;
  5759. }
  5760. var i, ii;
  5761. var canvas = document.createElement('canvas');
  5762. canvas.width = 1;
  5763. canvas.height = 1;
  5764. var ctx = canvas.getContext('2d');
  5765. var called = 0;
  5766. function isFontReady(name, callback) {
  5767. called++;
  5768. // With setTimeout clamping this gives the font ~100ms to load.
  5769. if(called > 30) {
  5770. warn('Load test font never loaded.');
  5771. callback();
  5772. return;
  5773. }
  5774. ctx.font = '30px ' + name;
  5775. ctx.fillText('.', 0, 20);
  5776. var imageData = ctx.getImageData(0, 0, 1, 1);
  5777. if (imageData.data[3] > 0) {
  5778. callback();
  5779. return;
  5780. }
  5781. setTimeout(isFontReady.bind(null, name, callback));
  5782. }
  5783. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  5784. // Chromium seems to cache fonts based on a hash of the actual font data,
  5785. // so the font must be modified for each load test else it will appear to
  5786. // be loaded already.
  5787. // TODO: This could maybe be made faster by avoiding the btoa of the full
  5788. // font by splitting it in chunks before hand and padding the font id.
  5789. var data = this.loadTestFont;
  5790. var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum)
  5791. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length,
  5792. loadTestFontId);
  5793. // CFF checksum is important for IE, adjusting it
  5794. var CFF_CHECKSUM_OFFSET = 16;
  5795. var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X'
  5796. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  5797. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  5798. checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0;
  5799. }
  5800. if (i < loadTestFontId.length) { // align to 4 bytes boundary
  5801. checksum = (checksum - XXXX_VALUE +
  5802. int32(loadTestFontId + 'XXX', i)) | 0;
  5803. }
  5804. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  5805. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  5806. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' +
  5807. url + '}';
  5808. FontLoader.insertRule(rule);
  5809. var names = [];
  5810. for (i = 0, ii = fonts.length; i < ii; i++) {
  5811. names.push(fonts[i].loadedName);
  5812. }
  5813. names.push(loadTestFontId);
  5814. var div = document.createElement('div');
  5815. div.setAttribute('style',
  5816. 'visibility: hidden;' +
  5817. 'width: 10px; height: 10px;' +
  5818. 'position: absolute; top: 0px; left: 0px;');
  5819. for (i = 0, ii = names.length; i < ii; ++i) {
  5820. var span = document.createElement('span');
  5821. span.textContent = 'Hi';
  5822. span.style.fontFamily = names[i];
  5823. div.appendChild(span);
  5824. }
  5825. document.body.appendChild(div);
  5826. isFontReady(loadTestFontId, function() {
  5827. document.body.removeChild(div);
  5828. request.complete();
  5829. });
  5830. /** Hack end */
  5831. }
  5832. //#else
  5833. //bind: function fontLoaderBind(fonts, callback) {
  5834. // assert(!isWorker, 'bind() shall be called from main thread');
  5835. //
  5836. // for (var i = 0, ii = fonts.length; i < ii; i++) {
  5837. // var font = fonts[i];
  5838. // if (font.attached) {
  5839. // continue;
  5840. // }
  5841. //
  5842. // font.attached = true;
  5843. // font.bindDOM()
  5844. // }
  5845. //
  5846. // setTimeout(callback);
  5847. //}
  5848. //#endif
  5849. };
  5850. var FontFaceObject = (function FontFaceObjectClosure() {
  5851. function FontFaceObject(name, file, properties) {
  5852. this.compiledGlyphs = {};
  5853. if (arguments.length === 1) {
  5854. // importing translated data
  5855. var data = arguments[0];
  5856. for (var i in data) {
  5857. this[i] = data[i];
  5858. }
  5859. return;
  5860. }
  5861. }
  5862. FontFaceObject.prototype = {
  5863. //#if !(MOZCENTRAL)
  5864. createNativeFontFace: function FontFaceObject_createNativeFontFace() {
  5865. if (!this.data) {
  5866. return null;
  5867. }
  5868. if (PDFJS.disableFontFace) {
  5869. this.disableFontFace = true;
  5870. return null;
  5871. }
  5872. var nativeFontFace = new FontFace(this.loadedName, this.data, {});
  5873. FontLoader.addNativeFontFace(nativeFontFace);
  5874. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  5875. globalScope['FontInspector'].enabled) {
  5876. globalScope['FontInspector'].fontAdded(this);
  5877. }
  5878. return nativeFontFace;
  5879. },
  5880. //#endif
  5881. bindDOM: function FontFaceObject_bindDOM() {
  5882. if (!this.data) {
  5883. return null;
  5884. }
  5885. if (PDFJS.disableFontFace) {
  5886. this.disableFontFace = true;
  5887. return null;
  5888. }
  5889. var data = bytesToString(new Uint8Array(this.data));
  5890. var fontName = this.loadedName;
  5891. // Add the font-face rule to the document
  5892. var url = ('url(data:' + this.mimetype + ';base64,' +
  5893. window.btoa(data) + ');');
  5894. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  5895. FontLoader.insertRule(rule);
  5896. if (PDFJS.pdfBug && 'FontInspector' in globalScope &&
  5897. globalScope['FontInspector'].enabled) {
  5898. globalScope['FontInspector'].fontAdded(this, url);
  5899. }
  5900. return rule;
  5901. },
  5902. getPathGenerator: function FontLoader_getPathGenerator(objs, character) {
  5903. if (!(character in this.compiledGlyphs)) {
  5904. var js = objs.get(this.loadedName + '_path_' + character);
  5905. /*jshint -W054 */
  5906. this.compiledGlyphs[character] = new Function('c', 'size', js);
  5907. }
  5908. return this.compiledGlyphs[character];
  5909. }
  5910. };
  5911. return FontFaceObject;
  5912. })();
  5913. var ANNOT_MIN_SIZE = 10; // px
  5914. var AnnotationUtils = (function AnnotationUtilsClosure() {
  5915. // TODO(mack): This dupes some of the logic in CanvasGraphics.setFont()
  5916. function setTextStyles(element, item, fontObj) {
  5917. var style = element.style;
  5918. style.fontSize = item.fontSize + 'px';
  5919. style.direction = item.fontDirection < 0 ? 'rtl': 'ltr';
  5920. if (!fontObj) {
  5921. return;
  5922. }
  5923. style.fontWeight = fontObj.black ?
  5924. (fontObj.bold ? 'bolder' : 'bold') :
  5925. (fontObj.bold ? 'bold' : 'normal');
  5926. style.fontStyle = fontObj.italic ? 'italic' : 'normal';
  5927. var fontName = fontObj.loadedName;
  5928. var fontFamily = fontName ? '"' + fontName + '", ' : '';
  5929. // Use a reasonable default font if the font doesn't specify a fallback
  5930. var fallbackName = fontObj.fallbackName || 'Helvetica, sans-serif';
  5931. style.fontFamily = fontFamily + fallbackName;
  5932. }
  5933. function initContainer(item, drawBorder) {
  5934. var container = document.createElement('section');
  5935. var cstyle = container.style;
  5936. var width = item.rect[2] - item.rect[0];
  5937. var height = item.rect[3] - item.rect[1];
  5938. var bWidth = item.borderWidth || 0;
  5939. if (bWidth) {
  5940. width = width - 2 * bWidth;
  5941. height = height - 2 * bWidth;
  5942. cstyle.borderWidth = bWidth + 'px';
  5943. var color = item.color;
  5944. if (drawBorder && color) {
  5945. cstyle.borderStyle = 'solid';
  5946. cstyle.borderColor = Util.makeCssRgb(Math.round(color[0] * 255),
  5947. Math.round(color[1] * 255),
  5948. Math.round(color[2] * 255));
  5949. }
  5950. }
  5951. cstyle.width = width + 'px';
  5952. cstyle.height = height + 'px';
  5953. return container;
  5954. }
  5955. function getHtmlElementForTextWidgetAnnotation(item, commonObjs) {
  5956. var element = document.createElement('div');
  5957. var width = item.rect[2] - item.rect[0];
  5958. var height = item.rect[3] - item.rect[1];
  5959. element.style.width = width + 'px';
  5960. element.style.height = height + 'px';
  5961. element.style.display = 'table';
  5962. var content = document.createElement('div');
  5963. content.textContent = item.fieldValue;
  5964. var textAlignment = item.textAlignment;
  5965. content.style.textAlign = ['left', 'center', 'right'][textAlignment];
  5966. content.style.verticalAlign = 'middle';
  5967. content.style.display = 'table-cell';
  5968. var fontObj = item.fontRefName ?
  5969. commonObjs.getData(item.fontRefName) : null;
  5970. setTextStyles(content, item, fontObj);
  5971. element.appendChild(content);
  5972. return element;
  5973. }
  5974. function getHtmlElementForTextAnnotation(item) {
  5975. var rect = item.rect;
  5976. // sanity check because of OOo-generated PDFs
  5977. if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) {
  5978. rect[3] = rect[1] + ANNOT_MIN_SIZE;
  5979. }
  5980. if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) {
  5981. rect[2] = rect[0] + (rect[3] - rect[1]); // make it square
  5982. }
  5983. var container = initContainer(item, false);
  5984. container.className = 'annotText';
  5985. var image = document.createElement('img');
  5986. image.style.height = container.style.height;
  5987. image.style.width = container.style.width;
  5988. var iconName = item.name;
  5989. image.src = PDFJS.imageResourcesPath + 'annotation-' +
  5990. iconName.toLowerCase() + '.svg';
  5991. image.alt = '[{{type}} Annotation]';
  5992. image.dataset.l10nId = 'text_annotation_type';
  5993. image.dataset.l10nArgs = JSON.stringify({type: iconName});
  5994. var contentWrapper = document.createElement('div');
  5995. contentWrapper.className = 'annotTextContentWrapper';
  5996. contentWrapper.style.left = Math.floor(rect[2] - rect[0] + 5) + 'px';
  5997. contentWrapper.style.top = '-10px';
  5998. var content = document.createElement('div');
  5999. content.className = 'annotTextContent';
  6000. content.setAttribute('hidden', true);
  6001. var i, ii;
  6002. if (item.hasBgColor) {
  6003. var color = item.color;
  6004. // Enlighten the color (70%)
  6005. var BACKGROUND_ENLIGHT = 0.7;
  6006. var r = BACKGROUND_ENLIGHT * (1.0 - color[0]) + color[0];
  6007. var g = BACKGROUND_ENLIGHT * (1.0 - color[1]) + color[1];
  6008. var b = BACKGROUND_ENLIGHT * (1.0 - color[2]) + color[2];
  6009. content.style.backgroundColor = Util.makeCssRgb((r * 255) | 0,
  6010. (g * 255) | 0,
  6011. (b * 255) | 0);
  6012. }
  6013. var title = document.createElement('h1');
  6014. var text = document.createElement('p');
  6015. title.textContent = item.title;
  6016. if (!item.content && !item.title) {
  6017. content.setAttribute('hidden', true);
  6018. } else {
  6019. var e = document.createElement('span');
  6020. var lines = item.content.split(/(?:\r\n?|\n)/);
  6021. for (i = 0, ii = lines.length; i < ii; ++i) {
  6022. var line = lines[i];
  6023. e.appendChild(document.createTextNode(line));
  6024. if (i < (ii - 1)) {
  6025. e.appendChild(document.createElement('br'));
  6026. }
  6027. }
  6028. text.appendChild(e);
  6029. var pinned = false;
  6030. var showAnnotation = function showAnnotation(pin) {
  6031. if (pin) {
  6032. pinned = true;
  6033. }
  6034. if (content.hasAttribute('hidden')) {
  6035. container.style.zIndex += 1;
  6036. content.removeAttribute('hidden');
  6037. }
  6038. };
  6039. var hideAnnotation = function hideAnnotation(unpin) {
  6040. if (unpin) {
  6041. pinned = false;
  6042. }
  6043. if (!content.hasAttribute('hidden') && !pinned) {
  6044. container.style.zIndex -= 1;
  6045. content.setAttribute('hidden', true);
  6046. }
  6047. };
  6048. var toggleAnnotation = function toggleAnnotation() {
  6049. if (pinned) {
  6050. hideAnnotation(true);
  6051. } else {
  6052. showAnnotation(true);
  6053. }
  6054. };
  6055. image.addEventListener('click', function image_clickHandler() {
  6056. toggleAnnotation();
  6057. }, false);
  6058. image.addEventListener('mouseover', function image_mouseOverHandler() {
  6059. showAnnotation();
  6060. }, false);
  6061. image.addEventListener('mouseout', function image_mouseOutHandler() {
  6062. hideAnnotation();
  6063. }, false);
  6064. content.addEventListener('click', function content_clickHandler() {
  6065. hideAnnotation(true);
  6066. }, false);
  6067. }
  6068. content.appendChild(title);
  6069. content.appendChild(text);
  6070. contentWrapper.appendChild(content);
  6071. container.appendChild(image);
  6072. container.appendChild(contentWrapper);
  6073. return container;
  6074. }
  6075. function getHtmlElementForLinkAnnotation(item) {
  6076. var container = initContainer(item, true);
  6077. container.className = 'annotLink';
  6078. var link = document.createElement('a');
  6079. link.href = link.title = item.url || '';
  6080. if (item.url && PDFJS.openExternalLinksInNewWindow) {
  6081. link.target = '_blank';
  6082. }
  6083. container.appendChild(link);
  6084. return container;
  6085. }
  6086. function getHtmlElement(data, objs) {
  6087. switch (data.annotationType) {
  6088. case AnnotationType.WIDGET:
  6089. return getHtmlElementForTextWidgetAnnotation(data, objs);
  6090. case AnnotationType.TEXT:
  6091. return getHtmlElementForTextAnnotation(data);
  6092. case AnnotationType.LINK:
  6093. return getHtmlElementForLinkAnnotation(data);
  6094. default:
  6095. throw new Error('Unsupported annotationType: ' + data.annotationType);
  6096. }
  6097. }
  6098. return {
  6099. getHtmlElement: getHtmlElement
  6100. };
  6101. })();
  6102. PDFJS.AnnotationUtils = AnnotationUtils;
  6103. //#if (GENERIC || SINGLE_FILE)
  6104. var SVG_DEFAULTS = {
  6105. fontStyle: 'normal',
  6106. fontWeight: 'normal',
  6107. fillColor: '#000000'
  6108. };
  6109. var convertImgDataToPng = (function convertImgDataToPngClosure() {
  6110. var PNG_HEADER =
  6111. new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
  6112. var CHUNK_WRAPPER_SIZE = 12;
  6113. var crcTable = new Int32Array(256);
  6114. for (var i = 0; i < 256; i++) {
  6115. var c = i;
  6116. for (var h = 0; h < 8; h++) {
  6117. if (c & 1) {
  6118. c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff);
  6119. } else {
  6120. c = (c >> 1) & 0x7fffffff;
  6121. }
  6122. }
  6123. crcTable[i] = c;
  6124. }
  6125. function crc32(data, start, end) {
  6126. var crc = -1;
  6127. for (var i = start; i < end; i++) {
  6128. var a = (crc ^ data[i]) & 0xff;
  6129. var b = crcTable[a];
  6130. crc = (crc >>> 8) ^ b;
  6131. }
  6132. return crc ^ -1;
  6133. }
  6134. function writePngChunk(type, body, data, offset) {
  6135. var p = offset;
  6136. var len = body.length;
  6137. data[p] = len >> 24 & 0xff;
  6138. data[p + 1] = len >> 16 & 0xff;
  6139. data[p + 2] = len >> 8 & 0xff;
  6140. data[p + 3] = len & 0xff;
  6141. p += 4;
  6142. data[p] = type.charCodeAt(0) & 0xff;
  6143. data[p + 1] = type.charCodeAt(1) & 0xff;
  6144. data[p + 2] = type.charCodeAt(2) & 0xff;
  6145. data[p + 3] = type.charCodeAt(3) & 0xff;
  6146. p += 4;
  6147. data.set(body, p);
  6148. p += body.length;
  6149. var crc = crc32(data, offset + 4, p);
  6150. data[p] = crc >> 24 & 0xff;
  6151. data[p + 1] = crc >> 16 & 0xff;
  6152. data[p + 2] = crc >> 8 & 0xff;
  6153. data[p + 3] = crc & 0xff;
  6154. }
  6155. function adler32(data, start, end) {
  6156. var a = 1;
  6157. var b = 0;
  6158. for (var i = start; i < end; ++i) {
  6159. a = (a + (data[i] & 0xff)) % 65521;
  6160. b = (b + a) % 65521;
  6161. }
  6162. return (b << 16) | a;
  6163. }
  6164. function encode(imgData, kind) {
  6165. var width = imgData.width;
  6166. var height = imgData.height;
  6167. var bitDepth, colorType, lineSize;
  6168. var bytes = imgData.data;
  6169. switch (kind) {
  6170. case ImageKind.GRAYSCALE_1BPP:
  6171. colorType = 0;
  6172. bitDepth = 1;
  6173. lineSize = (width + 7) >> 3;
  6174. break;
  6175. case ImageKind.RGB_24BPP:
  6176. colorType = 2;
  6177. bitDepth = 8;
  6178. lineSize = width * 3;
  6179. break;
  6180. case ImageKind.RGBA_32BPP:
  6181. colorType = 6;
  6182. bitDepth = 8;
  6183. lineSize = width * 4;
  6184. break;
  6185. default:
  6186. throw new Error('invalid format');
  6187. }
  6188. // prefix every row with predictor 0
  6189. var literals = new Uint8Array((1 + lineSize) * height);
  6190. var offsetLiterals = 0, offsetBytes = 0;
  6191. var y, i;
  6192. for (y = 0; y < height; ++y) {
  6193. literals[offsetLiterals++] = 0; // no prediction
  6194. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize),
  6195. offsetLiterals);
  6196. offsetBytes += lineSize;
  6197. offsetLiterals += lineSize;
  6198. }
  6199. if (kind === ImageKind.GRAYSCALE_1BPP) {
  6200. // inverting for B/W
  6201. offsetLiterals = 0;
  6202. for (y = 0; y < height; y++) {
  6203. offsetLiterals++; // skipping predictor
  6204. for (i = 0; i < lineSize; i++) {
  6205. literals[offsetLiterals++] ^= 0xFF;
  6206. }
  6207. }
  6208. }
  6209. var ihdr = new Uint8Array([
  6210. width >> 24 & 0xff,
  6211. width >> 16 & 0xff,
  6212. width >> 8 & 0xff,
  6213. width & 0xff,
  6214. height >> 24 & 0xff,
  6215. height >> 16 & 0xff,
  6216. height >> 8 & 0xff,
  6217. height & 0xff,
  6218. bitDepth, // bit depth
  6219. colorType, // color type
  6220. 0x00, // compression method
  6221. 0x00, // filter method
  6222. 0x00 // interlace method
  6223. ]);
  6224. var len = literals.length;
  6225. var maxBlockLength = 0xFFFF;
  6226. var deflateBlocks = Math.ceil(len / maxBlockLength);
  6227. var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  6228. var pi = 0;
  6229. idat[pi++] = 0x78; // compression method and flags
  6230. idat[pi++] = 0x9c; // flags
  6231. var pos = 0;
  6232. while (len > maxBlockLength) {
  6233. // writing non-final DEFLATE blocks type 0 and length of 65535
  6234. idat[pi++] = 0x00;
  6235. idat[pi++] = 0xff;
  6236. idat[pi++] = 0xff;
  6237. idat[pi++] = 0x00;
  6238. idat[pi++] = 0x00;
  6239. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  6240. pi += maxBlockLength;
  6241. pos += maxBlockLength;
  6242. len -= maxBlockLength;
  6243. }
  6244. // writing non-final DEFLATE blocks type 0
  6245. idat[pi++] = 0x01;
  6246. idat[pi++] = len & 0xff;
  6247. idat[pi++] = len >> 8 & 0xff;
  6248. idat[pi++] = (~len & 0xffff) & 0xff;
  6249. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  6250. idat.set(literals.subarray(pos), pi);
  6251. pi += literals.length - pos;
  6252. var adler = adler32(literals, 0, literals.length); // checksum
  6253. idat[pi++] = adler >> 24 & 0xff;
  6254. idat[pi++] = adler >> 16 & 0xff;
  6255. idat[pi++] = adler >> 8 & 0xff;
  6256. idat[pi++] = adler & 0xff;
  6257. // PNG will consists: header, IHDR+data, IDAT+data, and IEND.
  6258. var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) +
  6259. ihdr.length + idat.length;
  6260. var data = new Uint8Array(pngLength);
  6261. var offset = 0;
  6262. data.set(PNG_HEADER, offset);
  6263. offset += PNG_HEADER.length;
  6264. writePngChunk('IHDR', ihdr, data, offset);
  6265. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  6266. writePngChunk('IDATA', idat, data, offset);
  6267. offset += CHUNK_WRAPPER_SIZE + idat.length;
  6268. writePngChunk('IEND', new Uint8Array(0), data, offset);
  6269. return PDFJS.createObjectURL(data, 'image/png');
  6270. }
  6271. return function convertImgDataToPng(imgData) {
  6272. var kind = (imgData.kind === undefined ?
  6273. ImageKind.GRAYSCALE_1BPP : imgData.kind);
  6274. return encode(imgData, kind);
  6275. };
  6276. })();
  6277. var SVGExtraState = (function SVGExtraStateClosure() {
  6278. function SVGExtraState() {
  6279. this.fontSizeScale = 1;
  6280. this.fontWeight = SVG_DEFAULTS.fontWeight;
  6281. this.fontSize = 0;
  6282. this.textMatrix = IDENTITY_MATRIX;
  6283. this.fontMatrix = FONT_IDENTITY_MATRIX;
  6284. this.leading = 0;
  6285. // Current point (in user coordinates)
  6286. this.x = 0;
  6287. this.y = 0;
  6288. // Start of text line (in text coordinates)
  6289. this.lineX = 0;
  6290. this.lineY = 0;
  6291. // Character and word spacing
  6292. this.charSpacing = 0;
  6293. this.wordSpacing = 0;
  6294. this.textHScale = 1;
  6295. this.textRise = 0;
  6296. // Default foreground and background colors
  6297. this.fillColor = SVG_DEFAULTS.fillColor;
  6298. this.strokeColor = '#000000';
  6299. this.fillAlpha = 1;
  6300. this.strokeAlpha = 1;
  6301. this.lineWidth = 1;
  6302. this.lineJoin = '';
  6303. this.lineCap = '';
  6304. this.miterLimit = 0;
  6305. this.dashArray = [];
  6306. this.dashPhase = 0;
  6307. this.dependencies = [];
  6308. // Clipping
  6309. this.clipId = '';
  6310. this.pendingClip = false;
  6311. this.maskId = '';
  6312. }
  6313. SVGExtraState.prototype = {
  6314. clone: function SVGExtraState_clone() {
  6315. return Object.create(this);
  6316. },
  6317. setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) {
  6318. this.x = x;
  6319. this.y = y;
  6320. }
  6321. };
  6322. return SVGExtraState;
  6323. })();
  6324. var SVGGraphics = (function SVGGraphicsClosure() {
  6325. function createScratchSVG(width, height) {
  6326. var NS = 'http://www.w3.org/2000/svg';
  6327. var svg = document.createElementNS(NS, 'svg:svg');
  6328. svg.setAttributeNS(null, 'version', '1.1');
  6329. svg.setAttributeNS(null, 'width', width + 'px');
  6330. svg.setAttributeNS(null, 'height', height + 'px');
  6331. svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);
  6332. return svg;
  6333. }
  6334. function opListToTree(opList) {
  6335. var opTree = [];
  6336. var tmp = [];
  6337. var opListLen = opList.length;
  6338. for (var x = 0; x < opListLen; x++) {
  6339. if (opList[x].fn === 'save') {
  6340. opTree.push({'fnId': 92, 'fn': 'group', 'items': []});
  6341. tmp.push(opTree);
  6342. opTree = opTree[opTree.length - 1].items;
  6343. continue;
  6344. }
  6345. if(opList[x].fn === 'restore') {
  6346. opTree = tmp.pop();
  6347. } else {
  6348. opTree.push(opList[x]);
  6349. }
  6350. }
  6351. return opTree;
  6352. }
  6353. /**
  6354. * Formats float number.
  6355. * @param value {number} number to format.
  6356. * @returns {string}
  6357. */
  6358. function pf(value) {
  6359. if (value === (value | 0)) { // integer number
  6360. return value.toString();
  6361. }
  6362. var s = value.toFixed(10);
  6363. var i = s.length - 1;
  6364. if (s[i] !== '0') {
  6365. return s;
  6366. }
  6367. // removing trailing zeros
  6368. do {
  6369. i--;
  6370. } while (s[i] === '0');
  6371. return s.substr(0, s[i] === '.' ? i : i + 1);
  6372. }
  6373. /**
  6374. * Formats transform matrix. The standard rotation, scale and translate
  6375. * matrices are replaced by their shorter forms, and for identity matrix
  6376. * returns empty string to save the memory.
  6377. * @param m {Array} matrix to format.
  6378. * @returns {string}
  6379. */
  6380. function pm(m) {
  6381. if (m[4] === 0 && m[5] === 0) {
  6382. if (m[1] === 0 && m[2] === 0) {
  6383. if (m[0] === 1 && m[3] === 1) {
  6384. return '';
  6385. }
  6386. return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')';
  6387. }
  6388. if (m[0] === m[3] && m[1] === -m[2]) {
  6389. var a = Math.acos(m[0]) * 180 / Math.PI;
  6390. return 'rotate(' + pf(a) + ')';
  6391. }
  6392. } else {
  6393. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  6394. return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  6395. }
  6396. }
  6397. return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' +
  6398. pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  6399. }
  6400. function SVGGraphics(commonObjs, objs) {
  6401. this.current = new SVGExtraState();
  6402. this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix
  6403. this.transformStack = [];
  6404. this.extraStack = [];
  6405. this.commonObjs = commonObjs;
  6406. this.objs = objs;
  6407. this.pendingEOFill = false;
  6408. this.embedFonts = false;
  6409. this.embeddedFonts = {};
  6410. this.cssStyle = null;
  6411. }
  6412. var NS = 'http://www.w3.org/2000/svg';
  6413. var XML_NS = 'http://www.w3.org/XML/1998/namespace';
  6414. var XLINK_NS = 'http://www.w3.org/1999/xlink';
  6415. var LINE_CAP_STYLES = ['butt', 'round', 'square'];
  6416. var LINE_JOIN_STYLES = ['miter', 'round', 'bevel'];
  6417. var clipCount = 0;
  6418. var maskCount = 0;
  6419. SVGGraphics.prototype = {
  6420. save: function SVGGraphics_save() {
  6421. this.transformStack.push(this.transformMatrix);
  6422. var old = this.current;
  6423. this.extraStack.push(old);
  6424. this.current = old.clone();
  6425. },
  6426. restore: function SVGGraphics_restore() {
  6427. this.transformMatrix = this.transformStack.pop();
  6428. this.current = this.extraStack.pop();
  6429. this.tgrp = document.createElementNS(NS, 'svg:g');
  6430. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6431. this.pgrp.appendChild(this.tgrp);
  6432. },
  6433. group: function SVGGraphics_group(items) {
  6434. this.save();
  6435. this.executeOpTree(items);
  6436. this.restore();
  6437. },
  6438. loadDependencies: function SVGGraphics_loadDependencies(operatorList) {
  6439. var fnArray = operatorList.fnArray;
  6440. var fnArrayLen = fnArray.length;
  6441. var argsArray = operatorList.argsArray;
  6442. var self = this;
  6443. for (var i = 0; i < fnArrayLen; i++) {
  6444. if (OPS.dependency === fnArray[i]) {
  6445. var deps = argsArray[i];
  6446. for (var n = 0, nn = deps.length; n < nn; n++) {
  6447. var obj = deps[n];
  6448. var common = obj.substring(0, 2) === 'g_';
  6449. var promise;
  6450. if (common) {
  6451. promise = new Promise(function(resolve) {
  6452. self.commonObjs.get(obj, resolve);
  6453. });
  6454. } else {
  6455. promise = new Promise(function(resolve) {
  6456. self.objs.get(obj, resolve);
  6457. });
  6458. }
  6459. this.current.dependencies.push(promise);
  6460. }
  6461. }
  6462. }
  6463. return Promise.all(this.current.dependencies);
  6464. },
  6465. transform: function SVGGraphics_transform(a, b, c, d, e, f) {
  6466. var transformMatrix = [a, b, c, d, e, f];
  6467. this.transformMatrix = PDFJS.Util.transform(this.transformMatrix,
  6468. transformMatrix);
  6469. this.tgrp = document.createElementNS(NS, 'svg:g');
  6470. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6471. },
  6472. getSVG: function SVGGraphics_getSVG(operatorList, viewport) {
  6473. this.svg = createScratchSVG(viewport.width, viewport.height);
  6474. this.viewport = viewport;
  6475. return this.loadDependencies(operatorList).then(function () {
  6476. this.transformMatrix = IDENTITY_MATRIX;
  6477. this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group
  6478. this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform));
  6479. this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group
  6480. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6481. this.defs = document.createElementNS(NS, 'svg:defs');
  6482. this.pgrp.appendChild(this.defs);
  6483. this.pgrp.appendChild(this.tgrp);
  6484. this.svg.appendChild(this.pgrp);
  6485. var opTree = this.convertOpList(operatorList);
  6486. this.executeOpTree(opTree);
  6487. return this.svg;
  6488. }.bind(this));
  6489. },
  6490. convertOpList: function SVGGraphics_convertOpList(operatorList) {
  6491. var argsArray = operatorList.argsArray;
  6492. var fnArray = operatorList.fnArray;
  6493. var fnArrayLen = fnArray.length;
  6494. var REVOPS = [];
  6495. var opList = [];
  6496. for (var op in OPS) {
  6497. REVOPS[OPS[op]] = op;
  6498. }
  6499. for (var x = 0; x < fnArrayLen; x++) {
  6500. var fnId = fnArray[x];
  6501. opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]});
  6502. }
  6503. return opListToTree(opList);
  6504. },
  6505. executeOpTree: function SVGGraphics_executeOpTree(opTree) {
  6506. var opTreeLen = opTree.length;
  6507. for(var x = 0; x < opTreeLen; x++) {
  6508. var fn = opTree[x].fn;
  6509. var fnId = opTree[x].fnId;
  6510. var args = opTree[x].args;
  6511. switch (fnId | 0) {
  6512. case OPS.beginText:
  6513. this.beginText();
  6514. break;
  6515. case OPS.setLeading:
  6516. this.setLeading(args);
  6517. break;
  6518. case OPS.setLeadingMoveText:
  6519. this.setLeadingMoveText(args[0], args[1]);
  6520. break;
  6521. case OPS.setFont:
  6522. this.setFont(args);
  6523. break;
  6524. case OPS.showText:
  6525. this.showText(args[0]);
  6526. break;
  6527. case OPS.showSpacedText:
  6528. this.showText(args[0]);
  6529. break;
  6530. case OPS.endText:
  6531. this.endText();
  6532. break;
  6533. case OPS.moveText:
  6534. this.moveText(args[0], args[1]);
  6535. break;
  6536. case OPS.setCharSpacing:
  6537. this.setCharSpacing(args[0]);
  6538. break;
  6539. case OPS.setWordSpacing:
  6540. this.setWordSpacing(args[0]);
  6541. break;
  6542. case OPS.setHScale:
  6543. this.setHScale(args[0]);
  6544. break;
  6545. case OPS.setTextMatrix:
  6546. this.setTextMatrix(args[0], args[1], args[2],
  6547. args[3], args[4], args[5]);
  6548. break;
  6549. case OPS.setLineWidth:
  6550. this.setLineWidth(args[0]);
  6551. break;
  6552. case OPS.setLineJoin:
  6553. this.setLineJoin(args[0]);
  6554. break;
  6555. case OPS.setLineCap:
  6556. this.setLineCap(args[0]);
  6557. break;
  6558. case OPS.setMiterLimit:
  6559. this.setMiterLimit(args[0]);
  6560. break;
  6561. case OPS.setFillRGBColor:
  6562. this.setFillRGBColor(args[0], args[1], args[2]);
  6563. break;
  6564. case OPS.setStrokeRGBColor:
  6565. this.setStrokeRGBColor(args[0], args[1], args[2]);
  6566. break;
  6567. case OPS.setDash:
  6568. this.setDash(args[0], args[1]);
  6569. break;
  6570. case OPS.setGState:
  6571. this.setGState(args[0]);
  6572. break;
  6573. case OPS.fill:
  6574. this.fill();
  6575. break;
  6576. case OPS.eoFill:
  6577. this.eoFill();
  6578. break;
  6579. case OPS.stroke:
  6580. this.stroke();
  6581. break;
  6582. case OPS.fillStroke:
  6583. this.fillStroke();
  6584. break;
  6585. case OPS.eoFillStroke:
  6586. this.eoFillStroke();
  6587. break;
  6588. case OPS.clip:
  6589. this.clip('nonzero');
  6590. break;
  6591. case OPS.eoClip:
  6592. this.clip('evenodd');
  6593. break;
  6594. case OPS.paintSolidColorImageMask:
  6595. this.paintSolidColorImageMask();
  6596. break;
  6597. case OPS.paintJpegXObject:
  6598. this.paintJpegXObject(args[0], args[1], args[2]);
  6599. break;
  6600. case OPS.paintImageXObject:
  6601. this.paintImageXObject(args[0]);
  6602. break;
  6603. case OPS.paintInlineImageXObject:
  6604. this.paintInlineImageXObject(args[0]);
  6605. break;
  6606. case OPS.paintImageMaskXObject:
  6607. this.paintImageMaskXObject(args[0]);
  6608. break;
  6609. case OPS.paintFormXObjectBegin:
  6610. this.paintFormXObjectBegin(args[0], args[1]);
  6611. break;
  6612. case OPS.paintFormXObjectEnd:
  6613. this.paintFormXObjectEnd();
  6614. break;
  6615. case OPS.closePath:
  6616. this.closePath();
  6617. break;
  6618. case OPS.closeStroke:
  6619. this.closeStroke();
  6620. break;
  6621. case OPS.closeFillStroke:
  6622. this.closeFillStroke();
  6623. break;
  6624. case OPS.nextLine:
  6625. this.nextLine();
  6626. break;
  6627. case OPS.transform:
  6628. this.transform(args[0], args[1], args[2], args[3],
  6629. args[4], args[5]);
  6630. break;
  6631. case OPS.constructPath:
  6632. this.constructPath(args[0], args[1]);
  6633. break;
  6634. case OPS.endPath:
  6635. this.endPath();
  6636. break;
  6637. case 92:
  6638. this.group(opTree[x].items);
  6639. break;
  6640. default:
  6641. warn('Unimplemented method '+ fn);
  6642. break;
  6643. }
  6644. }
  6645. },
  6646. setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) {
  6647. this.current.wordSpacing = wordSpacing;
  6648. },
  6649. setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) {
  6650. this.current.charSpacing = charSpacing;
  6651. },
  6652. nextLine: function SVGGraphics_nextLine() {
  6653. this.moveText(0, this.current.leading);
  6654. },
  6655. setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) {
  6656. var current = this.current;
  6657. this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f];
  6658. this.current.x = this.current.lineX = 0;
  6659. this.current.y = this.current.lineY = 0;
  6660. current.xcoords = [];
  6661. current.tspan = document.createElementNS(NS, 'svg:tspan');
  6662. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  6663. current.tspan.setAttributeNS(null, 'font-size',
  6664. pf(current.fontSize) + 'px');
  6665. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  6666. current.txtElement = document.createElementNS(NS, 'svg:text');
  6667. current.txtElement.appendChild(current.tspan);
  6668. },
  6669. beginText: function SVGGraphics_beginText() {
  6670. this.current.x = this.current.lineX = 0;
  6671. this.current.y = this.current.lineY = 0;
  6672. this.current.textMatrix = IDENTITY_MATRIX;
  6673. this.current.lineMatrix = IDENTITY_MATRIX;
  6674. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  6675. this.current.txtElement = document.createElementNS(NS, 'svg:text');
  6676. this.current.txtgrp = document.createElementNS(NS, 'svg:g');
  6677. this.current.xcoords = [];
  6678. },
  6679. moveText: function SVGGraphics_moveText(x, y) {
  6680. var current = this.current;
  6681. this.current.x = this.current.lineX += x;
  6682. this.current.y = this.current.lineY += y;
  6683. current.xcoords = [];
  6684. current.tspan = document.createElementNS(NS, 'svg:tspan');
  6685. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  6686. current.tspan.setAttributeNS(null, 'font-size',
  6687. pf(current.fontSize) + 'px');
  6688. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  6689. },
  6690. showText: function SVGGraphics_showText(glyphs) {
  6691. var current = this.current;
  6692. var font = current.font;
  6693. var fontSize = current.fontSize;
  6694. if (fontSize === 0) {
  6695. return;
  6696. }
  6697. var charSpacing = current.charSpacing;
  6698. var wordSpacing = current.wordSpacing;
  6699. var fontDirection = current.fontDirection;
  6700. var textHScale = current.textHScale * fontDirection;
  6701. var glyphsLength = glyphs.length;
  6702. var vertical = font.vertical;
  6703. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  6704. var x = 0, i;
  6705. for (i = 0; i < glyphsLength; ++i) {
  6706. var glyph = glyphs[i];
  6707. if (glyph === null) {
  6708. // word break
  6709. x += fontDirection * wordSpacing;
  6710. continue;
  6711. } else if (isNum(glyph)) {
  6712. x += -glyph * fontSize * 0.001;
  6713. continue;
  6714. }
  6715. current.xcoords.push(current.x + x * textHScale);
  6716. var width = glyph.width;
  6717. var character = glyph.fontChar;
  6718. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  6719. x += charWidth;
  6720. current.tspan.textContent += character;
  6721. }
  6722. if (vertical) {
  6723. current.y -= x * textHScale;
  6724. } else {
  6725. current.x += x * textHScale;
  6726. }
  6727. current.tspan.setAttributeNS(null, 'x',
  6728. current.xcoords.map(pf).join(' '));
  6729. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  6730. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  6731. current.tspan.setAttributeNS(null, 'font-size',
  6732. pf(current.fontSize) + 'px');
  6733. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  6734. current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);
  6735. }
  6736. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  6737. current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);
  6738. }
  6739. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  6740. current.tspan.setAttributeNS(null, 'fill', current.fillColor);
  6741. }
  6742. current.txtElement.setAttributeNS(null, 'transform',
  6743. pm(current.textMatrix) +
  6744. ' scale(1, -1)' );
  6745. current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
  6746. current.txtElement.appendChild(current.tspan);
  6747. current.txtgrp.appendChild(current.txtElement);
  6748. this.tgrp.appendChild(current.txtElement);
  6749. },
  6750. setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) {
  6751. this.setLeading(-y);
  6752. this.moveText(x, y);
  6753. },
  6754. addFontStyle: function SVGGraphics_addFontStyle(fontObj) {
  6755. if (!this.cssStyle) {
  6756. this.cssStyle = document.createElementNS(NS, 'svg:style');
  6757. this.cssStyle.setAttributeNS(null, 'type', 'text/css');
  6758. this.defs.appendChild(this.cssStyle);
  6759. }
  6760. var url = PDFJS.createObjectURL(fontObj.data, fontObj.mimetype);
  6761. this.cssStyle.textContent +=
  6762. '@font-face { font-family: "' + fontObj.loadedName + '";' +
  6763. ' src: url(' + url + '); }\n';
  6764. },
  6765. setFont: function SVGGraphics_setFont(details) {
  6766. var current = this.current;
  6767. var fontObj = this.commonObjs.get(details[0]);
  6768. var size = details[1];
  6769. this.current.font = fontObj;
  6770. if (this.embedFonts && fontObj.data &&
  6771. !this.embeddedFonts[fontObj.loadedName]) {
  6772. this.addFontStyle(fontObj);
  6773. this.embeddedFonts[fontObj.loadedName] = fontObj;
  6774. }
  6775. current.fontMatrix = (fontObj.fontMatrix ?
  6776. fontObj.fontMatrix : FONT_IDENTITY_MATRIX);
  6777. var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') :
  6778. (fontObj.bold ? 'bold' : 'normal');
  6779. var italic = fontObj.italic ? 'italic' : 'normal';
  6780. if (size < 0) {
  6781. size = -size;
  6782. current.fontDirection = -1;
  6783. } else {
  6784. current.fontDirection = 1;
  6785. }
  6786. current.fontSize = size;
  6787. current.fontFamily = fontObj.loadedName;
  6788. current.fontWeight = bold;
  6789. current.fontStyle = italic;
  6790. current.tspan = document.createElementNS(NS, 'svg:tspan');
  6791. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  6792. current.xcoords = [];
  6793. },
  6794. endText: function SVGGraphics_endText() {
  6795. if (this.current.pendingClip) {
  6796. this.cgrp.appendChild(this.tgrp);
  6797. this.pgrp.appendChild(this.cgrp);
  6798. } else {
  6799. this.pgrp.appendChild(this.tgrp);
  6800. }
  6801. this.tgrp = document.createElementNS(NS, 'svg:g');
  6802. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6803. },
  6804. // Path properties
  6805. setLineWidth: function SVGGraphics_setLineWidth(width) {
  6806. this.current.lineWidth = width;
  6807. },
  6808. setLineCap: function SVGGraphics_setLineCap(style) {
  6809. this.current.lineCap = LINE_CAP_STYLES[style];
  6810. },
  6811. setLineJoin: function SVGGraphics_setLineJoin(style) {
  6812. this.current.lineJoin = LINE_JOIN_STYLES[style];
  6813. },
  6814. setMiterLimit: function SVGGraphics_setMiterLimit(limit) {
  6815. this.current.miterLimit = limit;
  6816. },
  6817. setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) {
  6818. var color = Util.makeCssRgb(r, g, b);
  6819. this.current.strokeColor = color;
  6820. },
  6821. setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) {
  6822. var color = Util.makeCssRgb(r, g, b);
  6823. this.current.fillColor = color;
  6824. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  6825. this.current.xcoords = [];
  6826. },
  6827. setDash: function SVGGraphics_setDash(dashArray, dashPhase) {
  6828. this.current.dashArray = dashArray;
  6829. this.current.dashPhase = dashPhase;
  6830. },
  6831. constructPath: function SVGGraphics_constructPath(ops, args) {
  6832. var current = this.current;
  6833. var x = current.x, y = current.y;
  6834. current.path = document.createElementNS(NS, 'svg:path');
  6835. var d = [];
  6836. var opLength = ops.length;
  6837. for (var i = 0, j = 0; i < opLength; i++) {
  6838. switch (ops[i] | 0) {
  6839. case OPS.rectangle:
  6840. x = args[j++];
  6841. y = args[j++];
  6842. var width = args[j++];
  6843. var height = args[j++];
  6844. var xw = x + width;
  6845. var yh = y + height;
  6846. d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh),
  6847. 'L', pf(x), pf(yh), 'Z');
  6848. break;
  6849. case OPS.moveTo:
  6850. x = args[j++];
  6851. y = args[j++];
  6852. d.push('M', pf(x), pf(y));
  6853. break;
  6854. case OPS.lineTo:
  6855. x = args[j++];
  6856. y = args[j++];
  6857. d.push('L', pf(x) , pf(y));
  6858. break;
  6859. case OPS.curveTo:
  6860. x = args[j + 4];
  6861. y = args[j + 5];
  6862. d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]),
  6863. pf(args[j + 3]), pf(x), pf(y));
  6864. j += 6;
  6865. break;
  6866. case OPS.curveTo2:
  6867. x = args[j + 2];
  6868. y = args[j + 3];
  6869. d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]),
  6870. pf(args[j + 2]), pf(args[j + 3]));
  6871. j += 4;
  6872. break;
  6873. case OPS.curveTo3:
  6874. x = args[j + 2];
  6875. y = args[j + 3];
  6876. d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y),
  6877. pf(x), pf(y));
  6878. j += 4;
  6879. break;
  6880. case OPS.closePath:
  6881. d.push('Z');
  6882. break;
  6883. }
  6884. }
  6885. current.path.setAttributeNS(null, 'd', d.join(' '));
  6886. current.path.setAttributeNS(null, 'stroke-miterlimit',
  6887. pf(current.miterLimit));
  6888. current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap);
  6889. current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);
  6890. current.path.setAttributeNS(null, 'stroke-width',
  6891. pf(current.lineWidth) + 'px');
  6892. current.path.setAttributeNS(null, 'stroke-dasharray',
  6893. current.dashArray.map(pf).join(' '));
  6894. current.path.setAttributeNS(null, 'stroke-dashoffset',
  6895. pf(current.dashPhase) + 'px');
  6896. current.path.setAttributeNS(null, 'fill', 'none');
  6897. this.tgrp.appendChild(current.path);
  6898. if (current.pendingClip) {
  6899. this.cgrp.appendChild(this.tgrp);
  6900. this.pgrp.appendChild(this.cgrp);
  6901. } else {
  6902. this.pgrp.appendChild(this.tgrp);
  6903. }
  6904. // Saving a reference in current.element so that it can be addressed
  6905. // in 'fill' and 'stroke'
  6906. current.element = current.path;
  6907. current.setCurrentPoint(x, y);
  6908. },
  6909. endPath: function SVGGraphics_endPath() {
  6910. var current = this.current;
  6911. if (current.pendingClip) {
  6912. this.cgrp.appendChild(this.tgrp);
  6913. this.pgrp.appendChild(this.cgrp);
  6914. } else {
  6915. this.pgrp.appendChild(this.tgrp);
  6916. }
  6917. this.tgrp = document.createElementNS(NS, 'svg:g');
  6918. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6919. },
  6920. clip: function SVGGraphics_clip(type) {
  6921. var current = this.current;
  6922. // Add current path to clipping path
  6923. current.clipId = 'clippath' + clipCount;
  6924. clipCount++;
  6925. this.clippath = document.createElementNS(NS, 'svg:clipPath');
  6926. this.clippath.setAttributeNS(null, 'id', current.clipId);
  6927. var clipElement = current.element.cloneNode();
  6928. if (type === 'evenodd') {
  6929. clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');
  6930. } else {
  6931. clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');
  6932. }
  6933. this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  6934. this.clippath.appendChild(clipElement);
  6935. this.defs.appendChild(this.clippath);
  6936. // Create a new group with that attribute
  6937. current.pendingClip = true;
  6938. this.cgrp = document.createElementNS(NS, 'svg:g');
  6939. this.cgrp.setAttributeNS(null, 'clip-path',
  6940. 'url(#' + current.clipId + ')');
  6941. this.pgrp.appendChild(this.cgrp);
  6942. },
  6943. closePath: function SVGGraphics_closePath() {
  6944. var current = this.current;
  6945. var d = current.path.getAttributeNS(null, 'd');
  6946. d += 'Z';
  6947. current.path.setAttributeNS(null, 'd', d);
  6948. },
  6949. setLeading: function SVGGraphics_setLeading(leading) {
  6950. this.current.leading = -leading;
  6951. },
  6952. setTextRise: function SVGGraphics_setTextRise(textRise) {
  6953. this.current.textRise = textRise;
  6954. },
  6955. setHScale: function SVGGraphics_setHScale(scale) {
  6956. this.current.textHScale = scale / 100;
  6957. },
  6958. setGState: function SVGGraphics_setGState(states) {
  6959. for (var i = 0, ii = states.length; i < ii; i++) {
  6960. var state = states[i];
  6961. var key = state[0];
  6962. var value = state[1];
  6963. switch (key) {
  6964. case 'LW':
  6965. this.setLineWidth(value);
  6966. break;
  6967. case 'LC':
  6968. this.setLineCap(value);
  6969. break;
  6970. case 'LJ':
  6971. this.setLineJoin(value);
  6972. break;
  6973. case 'ML':
  6974. this.setMiterLimit(value);
  6975. break;
  6976. case 'D':
  6977. this.setDash(value[0], value[1]);
  6978. break;
  6979. case 'RI':
  6980. break;
  6981. case 'FL':
  6982. break;
  6983. case 'Font':
  6984. this.setFont(value);
  6985. break;
  6986. case 'CA':
  6987. break;
  6988. case 'ca':
  6989. break;
  6990. case 'BM':
  6991. break;
  6992. case 'SMask':
  6993. break;
  6994. }
  6995. }
  6996. },
  6997. fill: function SVGGraphics_fill() {
  6998. var current = this.current;
  6999. current.element.setAttributeNS(null, 'fill', current.fillColor);
  7000. },
  7001. stroke: function SVGGraphics_stroke() {
  7002. var current = this.current;
  7003. current.element.setAttributeNS(null, 'stroke', current.strokeColor);
  7004. current.element.setAttributeNS(null, 'fill', 'none');
  7005. },
  7006. eoFill: function SVGGraphics_eoFill() {
  7007. var current = this.current;
  7008. current.element.setAttributeNS(null, 'fill', current.fillColor);
  7009. current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  7010. },
  7011. fillStroke: function SVGGraphics_fillStroke() {
  7012. // Order is important since stroke wants fill to be none.
  7013. // First stroke, then if fill needed, it will be overwritten.
  7014. this.stroke();
  7015. this.fill();
  7016. },
  7017. eoFillStroke: function SVGGraphics_eoFillStroke() {
  7018. this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  7019. this.fillStroke();
  7020. },
  7021. closeStroke: function SVGGraphics_closeStroke() {
  7022. this.closePath();
  7023. this.stroke();
  7024. },
  7025. closeFillStroke: function SVGGraphics_closeFillStroke() {
  7026. this.closePath();
  7027. this.fillStroke();
  7028. },
  7029. paintSolidColorImageMask:
  7030. function SVGGraphics_paintSolidColorImageMask() {
  7031. var current = this.current;
  7032. var rect = document.createElementNS(NS, 'svg:rect');
  7033. rect.setAttributeNS(null, 'x', '0');
  7034. rect.setAttributeNS(null, 'y', '0');
  7035. rect.setAttributeNS(null, 'width', '1px');
  7036. rect.setAttributeNS(null, 'height', '1px');
  7037. rect.setAttributeNS(null, 'fill', current.fillColor);
  7038. this.tgrp.appendChild(rect);
  7039. },
  7040. paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) {
  7041. var current = this.current;
  7042. var imgObj = this.objs.get(objId);
  7043. var imgEl = document.createElementNS(NS, 'svg:image');
  7044. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);
  7045. imgEl.setAttributeNS(null, 'width', imgObj.width + 'px');
  7046. imgEl.setAttributeNS(null, 'height', imgObj.height + 'px');
  7047. imgEl.setAttributeNS(null, 'x', '0');
  7048. imgEl.setAttributeNS(null, 'y', pf(-h));
  7049. imgEl.setAttributeNS(null, 'transform',
  7050. 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')');
  7051. this.tgrp.appendChild(imgEl);
  7052. if (current.pendingClip) {
  7053. this.cgrp.appendChild(this.tgrp);
  7054. this.pgrp.appendChild(this.cgrp);
  7055. } else {
  7056. this.pgrp.appendChild(this.tgrp);
  7057. }
  7058. },
  7059. paintImageXObject: function SVGGraphics_paintImageXObject(objId) {
  7060. var imgData = this.objs.get(objId);
  7061. if (!imgData) {
  7062. warn('Dependent image isn\'t ready yet');
  7063. return;
  7064. }
  7065. this.paintInlineImageXObject(imgData);
  7066. },
  7067. paintInlineImageXObject:
  7068. function SVGGraphics_paintInlineImageXObject(imgData, mask) {
  7069. var current = this.current;
  7070. var width = imgData.width;
  7071. var height = imgData.height;
  7072. var imgSrc = convertImgDataToPng(imgData);
  7073. var cliprect = document.createElementNS(NS, 'svg:rect');
  7074. cliprect.setAttributeNS(null, 'x', '0');
  7075. cliprect.setAttributeNS(null, 'y', '0');
  7076. cliprect.setAttributeNS(null, 'width', pf(width));
  7077. cliprect.setAttributeNS(null, 'height', pf(height));
  7078. current.element = cliprect;
  7079. this.clip('nonzero');
  7080. var imgEl = document.createElementNS(NS, 'svg:image');
  7081. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);
  7082. imgEl.setAttributeNS(null, 'x', '0');
  7083. imgEl.setAttributeNS(null, 'y', pf(-height));
  7084. imgEl.setAttributeNS(null, 'width', pf(width) + 'px');
  7085. imgEl.setAttributeNS(null, 'height', pf(height) + 'px');
  7086. imgEl.setAttributeNS(null, 'transform',
  7087. 'scale(' + pf(1 / width) + ' ' +
  7088. pf(-1 / height) + ')');
  7089. if (mask) {
  7090. mask.appendChild(imgEl);
  7091. } else {
  7092. this.tgrp.appendChild(imgEl);
  7093. }
  7094. if (current.pendingClip) {
  7095. this.cgrp.appendChild(this.tgrp);
  7096. this.pgrp.appendChild(this.cgrp);
  7097. } else {
  7098. this.pgrp.appendChild(this.tgrp);
  7099. }
  7100. },
  7101. paintImageMaskXObject:
  7102. function SVGGraphics_paintImageMaskXObject(imgData) {
  7103. var current = this.current;
  7104. var width = imgData.width;
  7105. var height = imgData.height;
  7106. var fillColor = current.fillColor;
  7107. current.maskId = 'mask' + maskCount++;
  7108. var mask = document.createElementNS(NS, 'svg:mask');
  7109. mask.setAttributeNS(null, 'id', current.maskId);
  7110. var rect = document.createElementNS(NS, 'svg:rect');
  7111. rect.setAttributeNS(null, 'x', '0');
  7112. rect.setAttributeNS(null, 'y', '0');
  7113. rect.setAttributeNS(null, 'width', pf(width));
  7114. rect.setAttributeNS(null, 'height', pf(height));
  7115. rect.setAttributeNS(null, 'fill', fillColor);
  7116. rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')');
  7117. this.defs.appendChild(mask);
  7118. this.tgrp.appendChild(rect);
  7119. this.paintInlineImageXObject(imgData, mask);
  7120. },
  7121. paintFormXObjectBegin:
  7122. function SVGGraphics_paintFormXObjectBegin(matrix, bbox) {
  7123. this.save();
  7124. if (isArray(matrix) && matrix.length === 6) {
  7125. this.transform(matrix[0], matrix[1], matrix[2],
  7126. matrix[3], matrix[4], matrix[5]);
  7127. }
  7128. if (isArray(bbox) && bbox.length === 4) {
  7129. var width = bbox[2] - bbox[0];
  7130. var height = bbox[3] - bbox[1];
  7131. var cliprect = document.createElementNS(NS, 'svg:rect');
  7132. cliprect.setAttributeNS(null, 'x', bbox[0]);
  7133. cliprect.setAttributeNS(null, 'y', bbox[1]);
  7134. cliprect.setAttributeNS(null, 'width', pf(width));
  7135. cliprect.setAttributeNS(null, 'height', pf(height));
  7136. this.current.element = cliprect;
  7137. this.clip('nonzero');
  7138. this.endPath();
  7139. }
  7140. },
  7141. paintFormXObjectEnd:
  7142. function SVGGraphics_paintFormXObjectEnd() {
  7143. this.restore();
  7144. }
  7145. };
  7146. return SVGGraphics;
  7147. })();
  7148. PDFJS.SVGGraphics = SVGGraphics;
  7149. //#endif
  7150. }).call((typeof window === 'undefined') ? this : window);
  7151. if (!PDFJS.workerSrc && typeof document !== 'undefined') {
  7152. // workerSrc is not set -- using last script url to define default location
  7153. PDFJS.workerSrc = (function () {
  7154. 'use strict';
  7155. var scriptTagContainer = document.body ||
  7156. document.getElementsByTagName('head')[0];
  7157. var pdfjsSrc = scriptTagContainer.lastChild.src;
  7158. return pdfjsSrc && pdfjsSrc.replace(/\.js$/i, '.worker.js');
  7159. })();
  7160. }