2
0

api_spec.js 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2018 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * Javascript code in this page
  21. */
  22. "use strict";
  23. var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
  24. var _test_utils = require("./test_utils");
  25. var _util = require("../../shared/util");
  26. var _dom_utils = require("../../display/dom_utils");
  27. var _api = require("../../display/api");
  28. var _worker_options = require("../../display/worker_options");
  29. var _is_node = _interopRequireDefault(require("../../shared/is_node"));
  30. var _metadata = require("../../display/metadata");
  31. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  32. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
  33. function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
  34. function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
  35. function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
  36. function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
  37. function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
  38. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  39. describe('api', function () {
  40. var basicApiFileName = 'basicapi.pdf';
  41. var basicApiFileLength = 105779;
  42. var basicApiGetDocumentParams = (0, _test_utils.buildGetDocumentParams)(basicApiFileName);
  43. var CanvasFactory;
  44. beforeAll(function (done) {
  45. if ((0, _is_node.default)()) {
  46. CanvasFactory = new _test_utils.NodeCanvasFactory();
  47. } else {
  48. CanvasFactory = new _dom_utils.DOMCanvasFactory();
  49. }
  50. done();
  51. });
  52. afterAll(function (done) {
  53. CanvasFactory = null;
  54. done();
  55. });
  56. function waitSome(callback) {
  57. var WAIT_TIMEOUT = 10;
  58. setTimeout(function () {
  59. callback();
  60. }, WAIT_TIMEOUT);
  61. }
  62. describe('getDocument', function () {
  63. it('creates pdf doc from URL', function (done) {
  64. var loadingTask = (0, _api.getDocument)(basicApiGetDocumentParams);
  65. var progressReportedCapability = (0, _util.createPromiseCapability)();
  66. loadingTask.onProgress = function (progressData) {
  67. if (!progressReportedCapability.settled) {
  68. progressReportedCapability.resolve(progressData);
  69. }
  70. };
  71. var promises = [progressReportedCapability.promise, loadingTask.promise];
  72. Promise.all(promises).then(function (data) {
  73. expect(data[0].loaded / data[0].total >= 0).toEqual(true);
  74. expect(data[1] instanceof _api.PDFDocumentProxy).toEqual(true);
  75. expect(loadingTask).toEqual(data[1].loadingTask);
  76. loadingTask.destroy().then(done);
  77. }).catch(done.fail);
  78. });
  79. it('creates pdf doc from URL and aborts before worker initialized', function (done) {
  80. var loadingTask = (0, _api.getDocument)(basicApiGetDocumentParams);
  81. var destroyed = loadingTask.destroy();
  82. loadingTask.promise.then(function (reason) {
  83. done.fail('shall fail loading');
  84. }).catch(function (reason) {
  85. expect(true).toEqual(true);
  86. destroyed.then(done);
  87. });
  88. });
  89. it('creates pdf doc from URL and aborts loading after worker initialized', function (done) {
  90. var loadingTask = (0, _api.getDocument)(basicApiGetDocumentParams);
  91. var destroyed = loadingTask._worker.promise.then(function () {
  92. return loadingTask.destroy();
  93. });
  94. destroyed.then(function (data) {
  95. expect(true).toEqual(true);
  96. done();
  97. }).catch(done.fail);
  98. });
  99. it('creates pdf doc from typed array', function (done) {
  100. var typedArrayPdf;
  101. if ((0, _is_node.default)()) {
  102. typedArrayPdf = _test_utils.NodeFileReaderFactory.fetch({
  103. path: _test_utils.TEST_PDFS_PATH.node + basicApiFileName
  104. });
  105. } else {
  106. var nonBinaryRequest = false;
  107. var request = new XMLHttpRequest();
  108. request.open('GET', _test_utils.TEST_PDFS_PATH.dom + basicApiFileName, false);
  109. try {
  110. request.responseType = 'arraybuffer';
  111. nonBinaryRequest = request.responseType !== 'arraybuffer';
  112. } catch (e) {
  113. nonBinaryRequest = true;
  114. }
  115. if (nonBinaryRequest && request.overrideMimeType) {
  116. request.overrideMimeType('text/plain; charset=x-user-defined');
  117. }
  118. request.send(null);
  119. if (nonBinaryRequest) {
  120. typedArrayPdf = (0, _util.stringToBytes)(request.responseText);
  121. } else {
  122. typedArrayPdf = new Uint8Array(request.response);
  123. }
  124. }
  125. expect(typedArrayPdf.length).toEqual(basicApiFileLength);
  126. var loadingTask = (0, _api.getDocument)(typedArrayPdf);
  127. var progressReportedCapability = (0, _util.createPromiseCapability)();
  128. loadingTask.onProgress = function (data) {
  129. progressReportedCapability.resolve(data);
  130. };
  131. Promise.all([loadingTask.promise, progressReportedCapability.promise]).then(function (data) {
  132. expect(data[0] instanceof _api.PDFDocumentProxy).toEqual(true);
  133. expect(data[1].loaded / data[1].total).toEqual(1);
  134. loadingTask.destroy().then(done);
  135. }).catch(done.fail);
  136. });
  137. it('creates pdf doc from invalid PDF file', function (done) {
  138. var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('bug1020226.pdf'));
  139. loadingTask.promise.then(function () {
  140. done.fail('shall fail loading');
  141. }).catch(function (error) {
  142. expect(error instanceof _util.InvalidPDFException).toEqual(true);
  143. loadingTask.destroy().then(done);
  144. });
  145. });
  146. it('creates pdf doc from non-existent URL', function (done) {
  147. var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('non-existent.pdf'));
  148. loadingTask.promise.then(function (error) {
  149. done.fail('shall fail loading');
  150. }).catch(function (error) {
  151. expect(error instanceof _util.MissingPDFException).toEqual(true);
  152. loadingTask.destroy().then(done);
  153. });
  154. });
  155. it('creates pdf doc from PDF file protected with user and owner password', function (done) {
  156. var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('pr6531_1.pdf'));
  157. var passwordNeededCapability = (0, _util.createPromiseCapability)();
  158. var passwordIncorrectCapability = (0, _util.createPromiseCapability)();
  159. loadingTask.onPassword = function (updatePassword, reason) {
  160. if (reason === _util.PasswordResponses.NEED_PASSWORD && !passwordNeededCapability.settled) {
  161. passwordNeededCapability.resolve();
  162. updatePassword('qwerty');
  163. return;
  164. }
  165. if (reason === _util.PasswordResponses.INCORRECT_PASSWORD && !passwordIncorrectCapability.settled) {
  166. passwordIncorrectCapability.resolve();
  167. updatePassword('asdfasdf');
  168. return;
  169. }
  170. expect(false).toEqual(true);
  171. };
  172. var promises = [passwordNeededCapability.promise, passwordIncorrectCapability.promise, loadingTask.promise];
  173. Promise.all(promises).then(function (data) {
  174. expect(data[2] instanceof _api.PDFDocumentProxy).toEqual(true);
  175. loadingTask.destroy().then(done);
  176. }).catch(done.fail);
  177. });
  178. it('creates pdf doc from PDF file protected with only a user password', function (done) {
  179. var filename = 'pr6531_2.pdf';
  180. var passwordNeededLoadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(filename, {
  181. password: ''
  182. }));
  183. var result1 = passwordNeededLoadingTask.promise.then(function () {
  184. done.fail('shall fail with no password');
  185. return Promise.reject(new Error('loadingTask should be rejected'));
  186. }, function (data) {
  187. expect(data instanceof _util.PasswordException).toEqual(true);
  188. expect(data.code).toEqual(_util.PasswordResponses.NEED_PASSWORD);
  189. return passwordNeededLoadingTask.destroy();
  190. });
  191. var passwordIncorrectLoadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(filename, {
  192. password: 'qwerty'
  193. }));
  194. var result2 = passwordIncorrectLoadingTask.promise.then(function () {
  195. done.fail('shall fail with wrong password');
  196. return Promise.reject(new Error('loadingTask should be rejected'));
  197. }, function (data) {
  198. expect(data instanceof _util.PasswordException).toEqual(true);
  199. expect(data.code).toEqual(_util.PasswordResponses.INCORRECT_PASSWORD);
  200. return passwordIncorrectLoadingTask.destroy();
  201. });
  202. var passwordAcceptedLoadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(filename, {
  203. password: 'asdfasdf'
  204. }));
  205. var result3 = passwordAcceptedLoadingTask.promise.then(function (data) {
  206. expect(data instanceof _api.PDFDocumentProxy).toEqual(true);
  207. return passwordAcceptedLoadingTask.destroy();
  208. });
  209. Promise.all([result1, result2, result3]).then(function () {
  210. done();
  211. }).catch(done.fail);
  212. });
  213. it('creates pdf doc from password protected PDF file and aborts/throws ' + 'in the onPassword callback (issue 7806)', function (done) {
  214. var filename = 'issue3371.pdf';
  215. var passwordNeededLoadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(filename));
  216. var passwordIncorrectLoadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(filename, {
  217. password: 'qwerty'
  218. }));
  219. var passwordNeededDestroyed;
  220. passwordNeededLoadingTask.onPassword = function (callback, reason) {
  221. if (reason === _util.PasswordResponses.NEED_PASSWORD) {
  222. passwordNeededDestroyed = passwordNeededLoadingTask.destroy();
  223. return;
  224. }
  225. expect(false).toEqual(true);
  226. };
  227. var result1 = passwordNeededLoadingTask.promise.then(function () {
  228. done.fail('shall fail since the loadingTask should be destroyed');
  229. return Promise.reject(new Error('loadingTask should be rejected'));
  230. }, function (reason) {
  231. expect(reason instanceof _util.PasswordException).toEqual(true);
  232. expect(reason.code).toEqual(_util.PasswordResponses.NEED_PASSWORD);
  233. return passwordNeededDestroyed;
  234. });
  235. passwordIncorrectLoadingTask.onPassword = function (callback, reason) {
  236. if (reason === _util.PasswordResponses.INCORRECT_PASSWORD) {
  237. throw new Error('Incorrect password');
  238. }
  239. expect(false).toEqual(true);
  240. };
  241. var result2 = passwordIncorrectLoadingTask.promise.then(function () {
  242. done.fail('shall fail since the onPassword callback should throw');
  243. return Promise.reject(new Error('loadingTask should be rejected'));
  244. }, function (reason) {
  245. expect(reason instanceof _util.PasswordException).toEqual(true);
  246. expect(reason.code).toEqual(_util.PasswordResponses.INCORRECT_PASSWORD);
  247. return passwordIncorrectLoadingTask.destroy();
  248. });
  249. Promise.all([result1, result2]).then(function () {
  250. done();
  251. }).catch(done.fail);
  252. });
  253. });
  254. describe('PDFWorker', function () {
  255. it('worker created or destroyed', function (done) {
  256. if ((0, _is_node.default)()) {
  257. pending('Worker is not supported in Node.js.');
  258. }
  259. var worker = new _api.PDFWorker({
  260. name: 'test1'
  261. });
  262. worker.promise.then(function () {
  263. expect(worker.name).toEqual('test1');
  264. expect(!!worker.port).toEqual(true);
  265. expect(worker.destroyed).toEqual(false);
  266. expect(!!worker._webWorker).toEqual(true);
  267. expect(worker.port === worker._webWorker).toEqual(true);
  268. worker.destroy();
  269. expect(!!worker.port).toEqual(false);
  270. expect(worker.destroyed).toEqual(true);
  271. done();
  272. }).catch(done.fail);
  273. });
  274. it('worker created or destroyed by getDocument', function (done) {
  275. if ((0, _is_node.default)()) {
  276. pending('Worker is not supported in Node.js.');
  277. }
  278. var loadingTask = (0, _api.getDocument)(basicApiGetDocumentParams);
  279. var worker;
  280. loadingTask.promise.then(function () {
  281. worker = loadingTask._worker;
  282. expect(!!worker).toEqual(true);
  283. });
  284. var destroyPromise = loadingTask.promise.then(function () {
  285. return loadingTask.destroy();
  286. });
  287. destroyPromise.then(function () {
  288. var destroyedWorker = loadingTask._worker;
  289. expect(!!destroyedWorker).toEqual(false);
  290. expect(worker.destroyed).toEqual(true);
  291. done();
  292. }).catch(done.fail);
  293. });
  294. it('worker created and can be used in getDocument', function (done) {
  295. if ((0, _is_node.default)()) {
  296. pending('Worker is not supported in Node.js.');
  297. }
  298. var worker = new _api.PDFWorker({
  299. name: 'test1'
  300. });
  301. var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(basicApiFileName, {
  302. worker: worker
  303. }));
  304. loadingTask.promise.then(function () {
  305. var docWorker = loadingTask._worker;
  306. expect(!!docWorker).toEqual(false);
  307. var messageHandlerPort = loadingTask._transport.messageHandler.comObj;
  308. expect(messageHandlerPort === worker.port).toEqual(true);
  309. });
  310. var destroyPromise = loadingTask.promise.then(function () {
  311. return loadingTask.destroy();
  312. });
  313. destroyPromise.then(function () {
  314. expect(worker.destroyed).toEqual(false);
  315. worker.destroy();
  316. done();
  317. }).catch(done.fail);
  318. });
  319. it('creates more than one worker', function (done) {
  320. if ((0, _is_node.default)()) {
  321. pending('Worker is not supported in Node.js.');
  322. }
  323. var worker1 = new _api.PDFWorker({
  324. name: 'test1'
  325. });
  326. var worker2 = new _api.PDFWorker({
  327. name: 'test2'
  328. });
  329. var worker3 = new _api.PDFWorker({
  330. name: 'test3'
  331. });
  332. var ready = Promise.all([worker1.promise, worker2.promise, worker3.promise]);
  333. ready.then(function () {
  334. expect(worker1.port !== worker2.port && worker1.port !== worker3.port && worker2.port !== worker3.port).toEqual(true);
  335. worker1.destroy();
  336. worker2.destroy();
  337. worker3.destroy();
  338. done();
  339. }).catch(done.fail);
  340. });
  341. it('gets current workerSrc', function () {
  342. if ((0, _is_node.default)()) {
  343. pending('Worker is not supported in Node.js.');
  344. }
  345. var workerSrc = _api.PDFWorker.getWorkerSrc();
  346. expect(_typeof(workerSrc)).toEqual('string');
  347. expect(workerSrc).toEqual(_worker_options.GlobalWorkerOptions.workerSrc);
  348. });
  349. });
  350. describe('PDFDocument', function () {
  351. var loadingTask;
  352. var doc;
  353. beforeAll(function (done) {
  354. loadingTask = (0, _api.getDocument)(basicApiGetDocumentParams);
  355. loadingTask.promise.then(function (data) {
  356. doc = data;
  357. done();
  358. });
  359. });
  360. afterAll(function (done) {
  361. loadingTask.destroy().then(done);
  362. });
  363. it('gets number of pages', function () {
  364. expect(doc.numPages).toEqual(3);
  365. });
  366. it('gets fingerprint', function () {
  367. var fingerprint = doc.fingerprint;
  368. expect(_typeof(fingerprint)).toEqual('string');
  369. expect(fingerprint.length > 0).toEqual(true);
  370. });
  371. it('gets page', function (done) {
  372. var promise = doc.getPage(1);
  373. promise.then(function (data) {
  374. expect(data instanceof _api.PDFPageProxy).toEqual(true);
  375. expect(data.pageIndex).toEqual(0);
  376. done();
  377. }).catch(done.fail);
  378. });
  379. it('gets non-existent page', function (done) {
  380. var outOfRangePromise = doc.getPage(100);
  381. var nonIntegerPromise = doc.getPage(2.5);
  382. var nonNumberPromise = doc.getPage('1');
  383. outOfRangePromise = outOfRangePromise.then(function () {
  384. throw new Error('shall fail for out-of-range pageNumber parameter');
  385. }, function (reason) {
  386. expect(reason instanceof Error).toEqual(true);
  387. });
  388. nonIntegerPromise = nonIntegerPromise.then(function () {
  389. throw new Error('shall fail for non-integer pageNumber parameter');
  390. }, function (reason) {
  391. expect(reason instanceof Error).toEqual(true);
  392. });
  393. nonNumberPromise = nonNumberPromise.then(function () {
  394. throw new Error('shall fail for non-number pageNumber parameter');
  395. }, function (reason) {
  396. expect(reason instanceof Error).toEqual(true);
  397. });
  398. Promise.all([outOfRangePromise, nonIntegerPromise, nonNumberPromise]).then(function () {
  399. done();
  400. }).catch(done.fail);
  401. });
  402. it('gets page index', function (done) {
  403. var ref = {
  404. num: 17,
  405. gen: 0
  406. };
  407. var promise = doc.getPageIndex(ref);
  408. promise.then(function (pageIndex) {
  409. expect(pageIndex).toEqual(1);
  410. done();
  411. }).catch(done.fail);
  412. });
  413. it('gets invalid page index', function (done) {
  414. var ref = {
  415. num: 3,
  416. gen: 0
  417. };
  418. var promise = doc.getPageIndex(ref);
  419. promise.then(function () {
  420. done.fail('shall fail for invalid page reference.');
  421. }).catch(function (reason) {
  422. expect(reason instanceof Error).toEqual(true);
  423. done();
  424. });
  425. });
  426. it('gets destinations, from /Dests dictionary', function (done) {
  427. var promise = doc.getDestinations();
  428. promise.then(function (data) {
  429. expect(data).toEqual({
  430. chapter1: [{
  431. gen: 0,
  432. num: 17
  433. }, {
  434. name: 'XYZ'
  435. }, 0, 841.89, null]
  436. });
  437. done();
  438. }).catch(done.fail);
  439. });
  440. it('gets a destination, from /Dests dictionary', function (done) {
  441. var promise = doc.getDestination('chapter1');
  442. promise.then(function (data) {
  443. expect(data).toEqual([{
  444. gen: 0,
  445. num: 17
  446. }, {
  447. name: 'XYZ'
  448. }, 0, 841.89, null]);
  449. done();
  450. }).catch(done.fail);
  451. });
  452. it('gets a non-existent destination, from /Dests dictionary', function (done) {
  453. var promise = doc.getDestination('non-existent-named-destination');
  454. promise.then(function (data) {
  455. expect(data).toEqual(null);
  456. done();
  457. }).catch(done.fail);
  458. });
  459. it('gets destinations, from /Names (NameTree) dictionary', function (done) {
  460. var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('issue6204.pdf'));
  461. var promise = loadingTask.promise.then(function (pdfDocument) {
  462. return pdfDocument.getDestinations();
  463. });
  464. promise.then(function (destinations) {
  465. expect(destinations).toEqual({
  466. 'Page.1': [{
  467. num: 1,
  468. gen: 0
  469. }, {
  470. name: 'XYZ'
  471. }, 0, 375, null],
  472. 'Page.2': [{
  473. num: 6,
  474. gen: 0
  475. }, {
  476. name: 'XYZ'
  477. }, 0, 375, null]
  478. });
  479. loadingTask.destroy().then(done);
  480. }).catch(done.fail);
  481. });
  482. it('gets a destination, from /Names (NameTree) dictionary', function (done) {
  483. var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('issue6204.pdf'));
  484. var promise = loadingTask.promise.then(function (pdfDocument) {
  485. return pdfDocument.getDestination('Page.1');
  486. });
  487. promise.then(function (destination) {
  488. expect(destination).toEqual([{
  489. num: 1,
  490. gen: 0
  491. }, {
  492. name: 'XYZ'
  493. }, 0, 375, null]);
  494. loadingTask.destroy().then(done);
  495. }).catch(done.fail);
  496. });
  497. it('gets a non-existent destination, from /Names (NameTree) dictionary', function (done) {
  498. var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('issue6204.pdf'));
  499. var promise = loadingTask.promise.then(function (pdfDocument) {
  500. return pdfDocument.getDestination('non-existent-named-destination');
  501. });
  502. promise.then(function (destination) {
  503. expect(destination).toEqual(null);
  504. loadingTask.destroy().then(done);
  505. }).catch(done.fail);
  506. });
  507. it('gets non-string destination', function (done) {
  508. var numberPromise = doc.getDestination(4.3);
  509. var booleanPromise = doc.getDestination(true);
  510. var arrayPromise = doc.getDestination([{
  511. num: 17,
  512. gen: 0
  513. }, {
  514. name: 'XYZ'
  515. }, 0, 841.89, null]);
  516. numberPromise = numberPromise.then(function () {
  517. throw new Error('shall fail for non-string destination.');
  518. }, function (reason) {
  519. expect(reason instanceof Error).toEqual(true);
  520. });
  521. booleanPromise = booleanPromise.then(function () {
  522. throw new Error('shall fail for non-string destination.');
  523. }, function (reason) {
  524. expect(reason instanceof Error).toEqual(true);
  525. });
  526. arrayPromise = arrayPromise.then(function () {
  527. throw new Error('shall fail for non-string destination.');
  528. }, function (reason) {
  529. expect(reason instanceof Error).toEqual(true);
  530. });
  531. Promise.all([numberPromise, booleanPromise, arrayPromise]).then(done, done.fail);
  532. });
  533. it('gets non-existent page labels', function (done) {
  534. var promise = doc.getPageLabels();
  535. promise.then(function (data) {
  536. expect(data).toEqual(null);
  537. done();
  538. }).catch(done.fail);
  539. });
  540. it('gets page labels', function (done) {
  541. var loadingTask0 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('bug793632.pdf'));
  542. var promise0 = loadingTask0.promise.then(function (pdfDoc) {
  543. return pdfDoc.getPageLabels();
  544. });
  545. var loadingTask1 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('issue1453.pdf'));
  546. var promise1 = loadingTask1.promise.then(function (pdfDoc) {
  547. return pdfDoc.getPageLabels();
  548. });
  549. var loadingTask2 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('rotation.pdf'));
  550. var promise2 = loadingTask2.promise.then(function (pdfDoc) {
  551. return pdfDoc.getPageLabels();
  552. });
  553. var loadingTask3 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('bad-PageLabels.pdf'));
  554. var promise3 = loadingTask3.promise.then(function (pdfDoc) {
  555. return pdfDoc.getPageLabels();
  556. });
  557. Promise.all([promise0, promise1, promise2, promise3]).then(function (pageLabels) {
  558. expect(pageLabels[0]).toEqual(['i', 'ii', 'iii', '1']);
  559. expect(pageLabels[1]).toEqual(['Front Page1']);
  560. expect(pageLabels[2]).toEqual(['1', '2']);
  561. expect(pageLabels[3]).toEqual(['X3']);
  562. Promise.all([loadingTask0.destroy(), loadingTask1.destroy(), loadingTask2.destroy(), loadingTask3.destroy()]).then(done);
  563. }).catch(done.fail);
  564. });
  565. it('gets default page mode', function (done) {
  566. var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('tracemonkey.pdf'));
  567. loadingTask.promise.then(function (pdfDocument) {
  568. return pdfDocument.getPageMode();
  569. }).then(function (mode) {
  570. expect(mode).toEqual('UseNone');
  571. loadingTask.destroy().then(done);
  572. }).catch(done.fail);
  573. });
  574. it('gets non-default page mode', function (done) {
  575. doc.getPageMode().then(function (mode) {
  576. expect(mode).toEqual('UseOutlines');
  577. done();
  578. }).catch(done.fail);
  579. });
  580. it('gets default open action destination', function (done) {
  581. var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('tracemonkey.pdf'));
  582. loadingTask.promise.then(function (pdfDocument) {
  583. return pdfDocument.getOpenActionDestination();
  584. }).then(function (dest) {
  585. expect(dest).toEqual(null);
  586. loadingTask.destroy().then(done);
  587. }).catch(done.fail);
  588. });
  589. it('gets non-default open action destination', function (done) {
  590. doc.getOpenActionDestination().then(function (dest) {
  591. expect(dest).toEqual([{
  592. num: 15,
  593. gen: 0
  594. }, {
  595. name: 'FitH'
  596. }, null]);
  597. done();
  598. }).catch(done.fail);
  599. });
  600. it('gets non-existent attachments', function (done) {
  601. var promise = doc.getAttachments();
  602. promise.then(function (data) {
  603. expect(data).toEqual(null);
  604. done();
  605. }).catch(done.fail);
  606. });
  607. it('gets attachments', function (done) {
  608. if ((0, _is_node.default)()) {
  609. pending('TODO: Use a non-linked test-case.');
  610. }
  611. var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('bug766138.pdf'));
  612. var promise = loadingTask.promise.then(function (pdfDoc) {
  613. return pdfDoc.getAttachments();
  614. });
  615. promise.then(function (data) {
  616. var attachment = data['Press Quality.joboptions'];
  617. expect(attachment.filename).toEqual('Press Quality.joboptions');
  618. expect(attachment.content instanceof Uint8Array).toBeTruthy();
  619. expect(attachment.content.length).toEqual(30098);
  620. loadingTask.destroy().then(done);
  621. }).catch(done.fail);
  622. });
  623. it('gets javascript', function (done) {
  624. var promise = doc.getJavaScript();
  625. promise.then(function (data) {
  626. expect(data).toEqual(null);
  627. done();
  628. }).catch(done.fail);
  629. });
  630. var viewerPrintRegExp = /\bprint\s*\(/;
  631. it('gets javascript with printing instructions (Print action)', function (done) {
  632. var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('bug1001080.pdf'));
  633. var promise = loadingTask.promise.then(function (doc) {
  634. return doc.getJavaScript();
  635. });
  636. promise.then(function (data) {
  637. expect(data).toEqual(['print({});']);
  638. expect(data[0]).toMatch(viewerPrintRegExp);
  639. loadingTask.destroy().then(done);
  640. }).catch(done.fail);
  641. });
  642. it('gets javascript with printing instructions (JS action)', function (done) {
  643. var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('issue6106.pdf'));
  644. var promise = loadingTask.promise.then(function (doc) {
  645. return doc.getJavaScript();
  646. });
  647. promise.then(function (data) {
  648. expect(data).toEqual(['this.print({bUI:true,bSilent:false,bShrinkToFit:true});']);
  649. expect(data[0]).toMatch(viewerPrintRegExp);
  650. loadingTask.destroy().then(done);
  651. }).catch(done.fail);
  652. });
  653. it('gets non-existent outline', function (done) {
  654. var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('tracemonkey.pdf'));
  655. var promise = loadingTask.promise.then(function (pdfDocument) {
  656. return pdfDocument.getOutline();
  657. });
  658. promise.then(function (outline) {
  659. expect(outline).toEqual(null);
  660. loadingTask.destroy().then(done);
  661. }).catch(done.fail);
  662. });
  663. it('gets outline', function (done) {
  664. var promise = doc.getOutline();
  665. promise.then(function (outline) {
  666. expect(Array.isArray(outline)).toEqual(true);
  667. expect(outline.length).toEqual(2);
  668. var outlineItem = outline[1];
  669. expect(outlineItem.title).toEqual('Chapter 1');
  670. expect(Array.isArray(outlineItem.dest)).toEqual(true);
  671. expect(outlineItem.url).toEqual(null);
  672. expect(outlineItem.unsafeUrl).toBeUndefined();
  673. expect(outlineItem.newWindow).toBeUndefined();
  674. expect(outlineItem.bold).toEqual(true);
  675. expect(outlineItem.italic).toEqual(false);
  676. expect(outlineItem.color).toEqual(new Uint8ClampedArray([0, 64, 128]));
  677. expect(outlineItem.items.length).toEqual(1);
  678. expect(outlineItem.items[0].title).toEqual('Paragraph 1.1');
  679. done();
  680. }).catch(done.fail);
  681. });
  682. it('gets outline containing a url', function (done) {
  683. var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('issue3214.pdf'));
  684. loadingTask.promise.then(function (pdfDocument) {
  685. pdfDocument.getOutline().then(function (outline) {
  686. expect(Array.isArray(outline)).toEqual(true);
  687. expect(outline.length).toEqual(5);
  688. var outlineItemTwo = outline[2];
  689. expect(_typeof(outlineItemTwo.title)).toEqual('string');
  690. expect(outlineItemTwo.dest).toEqual(null);
  691. expect(outlineItemTwo.url).toEqual('http://google.com/');
  692. expect(outlineItemTwo.unsafeUrl).toEqual('http://google.com');
  693. expect(outlineItemTwo.newWindow).toBeUndefined();
  694. var outlineItemOne = outline[1];
  695. expect(outlineItemOne.bold).toEqual(false);
  696. expect(outlineItemOne.italic).toEqual(true);
  697. expect(outlineItemOne.color).toEqual(new Uint8ClampedArray([0, 0, 0]));
  698. loadingTask.destroy().then(done);
  699. });
  700. }).catch(done.fail);
  701. });
  702. it('gets non-existent permissions', function (done) {
  703. doc.getPermissions().then(function (permissions) {
  704. expect(permissions).toEqual(null);
  705. done();
  706. }).catch(done.fail);
  707. });
  708. it('gets permissions', function (done) {
  709. var loadingTask0 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('issue9972-1.pdf'));
  710. var promise0 = loadingTask0.promise.then(function (pdfDocument) {
  711. return pdfDocument.getPermissions();
  712. });
  713. var loadingTask1 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('issue9972-2.pdf'));
  714. var promise1 = loadingTask1.promise.then(function (pdfDocument) {
  715. return pdfDocument.getPermissions();
  716. });
  717. var loadingTask2 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('issue9972-3.pdf'));
  718. var promise2 = loadingTask2.promise.then(function (pdfDocument) {
  719. return pdfDocument.getPermissions();
  720. });
  721. var totalPermissionCount = Object.keys(_util.PermissionFlag).length;
  722. Promise.all([promise0, promise1, promise2]).then(function (permissions) {
  723. expect(permissions[0].length).toEqual(totalPermissionCount - 1);
  724. expect(permissions[0].includes(_util.PermissionFlag.MODIFY_CONTENTS)).toBeFalsy();
  725. expect(permissions[1].length).toEqual(totalPermissionCount - 2);
  726. expect(permissions[1].includes(_util.PermissionFlag.PRINT)).toBeFalsy();
  727. expect(permissions[1].includes(_util.PermissionFlag.PRINT_HIGH_QUALITY)).toBeFalsy();
  728. expect(permissions[2].length).toEqual(totalPermissionCount - 1);
  729. expect(permissions[2].includes(_util.PermissionFlag.COPY)).toBeFalsy();
  730. Promise.all([loadingTask0.destroy(), loadingTask1.destroy(), loadingTask2.destroy()]).then(done);
  731. }).catch(done.fail);
  732. });
  733. it('gets metadata', function (done) {
  734. var promise = doc.getMetadata();
  735. promise.then(function (_ref) {
  736. var info = _ref.info,
  737. metadata = _ref.metadata,
  738. contentDispositionFilename = _ref.contentDispositionFilename;
  739. expect(info['Title']).toEqual('Basic API Test');
  740. expect(info['Custom']).toEqual(undefined);
  741. expect(info['PDFFormatVersion']).toEqual('1.7');
  742. expect(info['IsLinearized']).toEqual(false);
  743. expect(info['IsAcroFormPresent']).toEqual(false);
  744. expect(info['IsXFAPresent']).toEqual(false);
  745. expect(metadata instanceof _metadata.Metadata).toEqual(true);
  746. expect(metadata.get('dc:title')).toEqual('Basic API Test');
  747. expect(contentDispositionFilename).toEqual(null);
  748. done();
  749. }).catch(done.fail);
  750. });
  751. it('gets metadata, with custom info dict entries', function (done) {
  752. var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('tracemonkey.pdf'));
  753. loadingTask.promise.then(function (pdfDocument) {
  754. return pdfDocument.getMetadata();
  755. }).then(function (_ref2) {
  756. var info = _ref2.info,
  757. metadata = _ref2.metadata,
  758. contentDispositionFilename = _ref2.contentDispositionFilename;
  759. expect(info['Creator']).toEqual('TeX');
  760. expect(info['Producer']).toEqual('pdfeTeX-1.21a');
  761. expect(info['CreationDate']).toEqual('D:20090401163925-07\'00\'');
  762. var custom = info['Custom'];
  763. expect(_typeof(custom) === 'object' && custom !== null).toEqual(true);
  764. expect(custom['PTEX.Fullbanner']).toEqual('This is pdfeTeX, ' + 'Version 3.141592-1.21a-2.2 (Web2C 7.5.4) kpathsea version 3.5.6');
  765. expect(info['PDFFormatVersion']).toEqual('1.4');
  766. expect(info['IsLinearized']).toEqual(false);
  767. expect(info['IsAcroFormPresent']).toEqual(false);
  768. expect(info['IsXFAPresent']).toEqual(false);
  769. expect(metadata).toEqual(null);
  770. expect(contentDispositionFilename).toEqual(null);
  771. loadingTask.destroy().then(done);
  772. }).catch(done.fail);
  773. });
  774. it('gets data', function (done) {
  775. var promise = doc.getData();
  776. promise.then(function (data) {
  777. expect(data instanceof Uint8Array).toEqual(true);
  778. expect(data.length).toEqual(basicApiFileLength);
  779. done();
  780. }).catch(done.fail);
  781. });
  782. it('gets download info', function (done) {
  783. var promise = doc.getDownloadInfo();
  784. promise.then(function (data) {
  785. expect(data).toEqual({
  786. length: basicApiFileLength
  787. });
  788. done();
  789. }).catch(done.fail);
  790. });
  791. it('gets document stats', function (done) {
  792. var promise = doc.getStats();
  793. promise.then(function (stats) {
  794. expect(stats).toEqual({
  795. streamTypes: [],
  796. fontTypes: []
  797. });
  798. done();
  799. }).catch(done.fail);
  800. });
  801. it('checks that fingerprints are unique', function (done) {
  802. var loadingTask1 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('issue4436r.pdf'));
  803. var loadingTask2 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('issue4575.pdf'));
  804. var promises = [loadingTask1.promise, loadingTask2.promise];
  805. Promise.all(promises).then(function (data) {
  806. var fingerprint1 = data[0].fingerprint;
  807. expect(_typeof(fingerprint1)).toEqual('string');
  808. expect(fingerprint1.length > 0).toEqual(true);
  809. var fingerprint2 = data[1].fingerprint;
  810. expect(_typeof(fingerprint2)).toEqual('string');
  811. expect(fingerprint2.length > 0).toEqual(true);
  812. expect(fingerprint1).not.toEqual(fingerprint2);
  813. Promise.all([loadingTask1.destroy(), loadingTask2.destroy()]).then(done);
  814. }).catch(done.fail);
  815. });
  816. describe('Cross-origin', function () {
  817. var loadingTask;
  818. function _checkCanLoad(expectSuccess, filename, options) {
  819. if ((0, _is_node.default)()) {
  820. pending('Cannot simulate cross-origin requests in Node.js');
  821. }
  822. var params = (0, _test_utils.buildGetDocumentParams)(filename, options);
  823. var url = new URL(params.url);
  824. if (url.hostname === 'localhost') {
  825. url.hostname = '127.0.0.1';
  826. } else if (params.url.hostname === '127.0.0.1') {
  827. url.hostname = 'localhost';
  828. } else {
  829. pending('Can only run cross-origin test on localhost!');
  830. }
  831. params.url = url.href;
  832. loadingTask = (0, _api.getDocument)(params);
  833. return loadingTask.promise.then(function (pdf) {
  834. return pdf.destroy();
  835. }).then(function () {
  836. expect(expectSuccess).toEqual(true);
  837. }, function (error) {
  838. if (expectSuccess) {
  839. expect(error).toEqual('There should not be any error');
  840. }
  841. expect(expectSuccess).toEqual(false);
  842. });
  843. }
  844. function testCanLoad(filename, options) {
  845. return _checkCanLoad(true, filename, options);
  846. }
  847. function testCannotLoad(filename, options) {
  848. return _checkCanLoad(false, filename, options);
  849. }
  850. afterEach(function (done) {
  851. if (loadingTask) {
  852. loadingTask.destroy().then(done);
  853. } else {
  854. done();
  855. }
  856. });
  857. it('server disallows cors', function (done) {
  858. testCannotLoad('basicapi.pdf').then(done);
  859. });
  860. it('server allows cors without credentials, default withCredentials', function (done) {
  861. testCanLoad('basicapi.pdf?cors=withoutCredentials').then(done);
  862. });
  863. it('server allows cors without credentials, and withCredentials=false', function (done) {
  864. testCanLoad('basicapi.pdf?cors=withoutCredentials', {
  865. withCredentials: false
  866. }).then(done);
  867. });
  868. it('server allows cors without credentials, but withCredentials=true', function (done) {
  869. testCannotLoad('basicapi.pdf?cors=withoutCredentials', {
  870. withCredentials: true
  871. }).then(done);
  872. });
  873. it('server allows cors with credentials, and withCredentials=true', function (done) {
  874. testCanLoad('basicapi.pdf?cors=withCredentials', {
  875. withCredentials: true
  876. }).then(done);
  877. });
  878. it('server allows cors with credentials, and withCredentials=false', function (done) {
  879. testCanLoad('basicapi.pdf?cors=withCredentials', {
  880. withCredentials: false
  881. }).then(done);
  882. });
  883. });
  884. });
  885. describe('Page', function () {
  886. var loadingTask;
  887. var pdfDocument, page;
  888. beforeAll(function (done) {
  889. loadingTask = (0, _api.getDocument)(basicApiGetDocumentParams);
  890. loadingTask.promise.then(function (doc) {
  891. pdfDocument = doc;
  892. pdfDocument.getPage(1).then(function (data) {
  893. page = data;
  894. done();
  895. });
  896. }).catch(done.fail);
  897. });
  898. afterAll(function (done) {
  899. loadingTask.destroy().then(done);
  900. });
  901. it('gets page number', function () {
  902. expect(page.pageNumber).toEqual(1);
  903. });
  904. it('gets rotate', function () {
  905. expect(page.rotate).toEqual(0);
  906. });
  907. it('gets ref', function () {
  908. expect(page.ref).toEqual({
  909. num: 15,
  910. gen: 0
  911. });
  912. });
  913. it('gets userUnit', function () {
  914. expect(page.userUnit).toEqual(1.0);
  915. });
  916. it('gets view', function () {
  917. expect(page.view).toEqual([0, 0, 595.28, 841.89]);
  918. });
  919. it('gets viewport', function () {
  920. var viewport = page.getViewport({
  921. scale: 1.5,
  922. rotation: 90
  923. });
  924. expect(viewport.viewBox).toEqual(page.view);
  925. expect(viewport.scale).toEqual(1.5);
  926. expect(viewport.rotation).toEqual(90);
  927. expect(viewport.transform).toEqual([0, 1.5, 1.5, 0, 0, 0]);
  928. expect(viewport.width).toEqual(1262.835);
  929. expect(viewport.height).toEqual(892.92);
  930. });
  931. it('gets viewport respecting "dontFlip" argument', function () {
  932. var scale = 1;
  933. var rotation = 135;
  934. var viewport = page.getViewport({
  935. scale: scale,
  936. rotation: rotation
  937. });
  938. var dontFlipViewport = page.getViewport({
  939. scale: scale,
  940. rotation: rotation,
  941. dontFlip: true
  942. });
  943. expect(dontFlipViewport).not.toEqual(viewport);
  944. expect(dontFlipViewport).toEqual(viewport.clone({
  945. dontFlip: true
  946. }));
  947. expect(viewport.transform).toEqual([1, 0, 0, -1, 0, 841.89]);
  948. expect(dontFlipViewport.transform).toEqual([1, 0, -0, 1, 0, 0]);
  949. });
  950. it('gets annotations', function (done) {
  951. var defaultPromise = page.getAnnotations().then(function (data) {
  952. expect(data.length).toEqual(4);
  953. });
  954. var displayPromise = page.getAnnotations({
  955. intent: 'display'
  956. }).then(function (data) {
  957. expect(data.length).toEqual(4);
  958. });
  959. var printPromise = page.getAnnotations({
  960. intent: 'print'
  961. }).then(function (data) {
  962. expect(data.length).toEqual(4);
  963. });
  964. Promise.all([defaultPromise, displayPromise, printPromise]).then(function () {
  965. done();
  966. }).catch(done.fail);
  967. });
  968. it('gets annotations containing relative URLs (bug 766086)', function (done) {
  969. var filename = 'bug766086.pdf';
  970. var defaultLoadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(filename));
  971. var defaultPromise = defaultLoadingTask.promise.then(function (pdfDoc) {
  972. return pdfDoc.getPage(1).then(function (pdfPage) {
  973. return pdfPage.getAnnotations();
  974. });
  975. });
  976. var docBaseUrlLoadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(filename, {
  977. docBaseUrl: 'http://www.example.com/test/pdfs/qwerty.pdf'
  978. }));
  979. var docBaseUrlPromise = docBaseUrlLoadingTask.promise.then(function (pdfDoc) {
  980. return pdfDoc.getPage(1).then(function (pdfPage) {
  981. return pdfPage.getAnnotations();
  982. });
  983. });
  984. var invalidDocBaseUrlLoadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(filename, {
  985. docBaseUrl: 'qwerty.pdf'
  986. }));
  987. var invalidDocBaseUrlPromise = invalidDocBaseUrlLoadingTask.promise.then(function (pdfDoc) {
  988. return pdfDoc.getPage(1).then(function (pdfPage) {
  989. return pdfPage.getAnnotations();
  990. });
  991. });
  992. Promise.all([defaultPromise, docBaseUrlPromise, invalidDocBaseUrlPromise]).then(function (data) {
  993. var defaultAnnotations = data[0];
  994. var docBaseUrlAnnotations = data[1];
  995. var invalidDocBaseUrlAnnotations = data[2];
  996. expect(defaultAnnotations[0].url).toBeUndefined();
  997. expect(defaultAnnotations[0].unsafeUrl).toEqual('../../0021/002156/215675E.pdf#15');
  998. expect(docBaseUrlAnnotations[0].url).toEqual('http://www.example.com/0021/002156/215675E.pdf#15');
  999. expect(docBaseUrlAnnotations[0].unsafeUrl).toEqual('../../0021/002156/215675E.pdf#15');
  1000. expect(invalidDocBaseUrlAnnotations[0].url).toBeUndefined();
  1001. expect(invalidDocBaseUrlAnnotations[0].unsafeUrl).toEqual('../../0021/002156/215675E.pdf#15');
  1002. Promise.all([defaultLoadingTask.destroy(), docBaseUrlLoadingTask.destroy(), invalidDocBaseUrlLoadingTask.destroy()]).then(done);
  1003. }).catch(done.fail);
  1004. });
  1005. it('gets text content', function (done) {
  1006. var defaultPromise = page.getTextContent();
  1007. var parametersPromise = page.getTextContent({
  1008. normalizeWhitespace: true,
  1009. disableCombineTextItems: true
  1010. });
  1011. var promises = [defaultPromise, parametersPromise];
  1012. Promise.all(promises).then(function (data) {
  1013. expect(!!data[0].items).toEqual(true);
  1014. expect(data[0].items.length).toEqual(7);
  1015. expect(!!data[0].styles).toEqual(true);
  1016. expect(JSON.stringify(data[0])).toEqual(JSON.stringify(data[1]));
  1017. done();
  1018. }).catch(done.fail);
  1019. });
  1020. it('gets text content, with correct properties (issue 8276)', function (done) {
  1021. var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('issue8276_reduced.pdf'));
  1022. loadingTask.promise.then(function (pdfDoc) {
  1023. pdfDoc.getPage(1).then(function (pdfPage) {
  1024. pdfPage.getTextContent().then(function (_ref3) {
  1025. var items = _ref3.items,
  1026. styles = _ref3.styles;
  1027. expect(items.length).toEqual(1);
  1028. expect(Object.keys(styles)).toEqual(['Times']);
  1029. expect(items[0]).toEqual({
  1030. dir: 'ltr',
  1031. fontName: 'Times',
  1032. height: 18,
  1033. str: 'Issue 8276',
  1034. transform: [18, 0, 0, 18, 441.81, 708.4499999999999],
  1035. width: 77.49
  1036. });
  1037. expect(styles.Times).toEqual({
  1038. fontFamily: 'serif',
  1039. ascent: NaN,
  1040. descent: NaN,
  1041. vertical: false
  1042. });
  1043. loadingTask.destroy().then(done);
  1044. });
  1045. });
  1046. }).catch(done.fail);
  1047. });
  1048. it('gets operator list', function (done) {
  1049. var promise = page.getOperatorList();
  1050. promise.then(function (oplist) {
  1051. expect(!!oplist.fnArray).toEqual(true);
  1052. expect(!!oplist.argsArray).toEqual(true);
  1053. expect(oplist.lastChunk).toEqual(true);
  1054. done();
  1055. }).catch(done.fail);
  1056. });
  1057. it('gets operatorList with JPEG image (issue 4888)', function (done) {
  1058. var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('cmykjpeg.pdf'));
  1059. loadingTask.promise.then(function (pdfDoc) {
  1060. pdfDoc.getPage(1).then(function (pdfPage) {
  1061. pdfPage.getOperatorList().then(function (opList) {
  1062. var imgIndex = opList.fnArray.indexOf(_util.OPS.paintImageXObject);
  1063. var imgArgs = opList.argsArray[imgIndex];
  1064. var _pdfPage$objs$get = pdfPage.objs.get(imgArgs[0]),
  1065. data = _pdfPage$objs$get.data;
  1066. expect(data instanceof Uint8ClampedArray).toEqual(true);
  1067. expect(data.length).toEqual(90000);
  1068. loadingTask.destroy().then(done);
  1069. });
  1070. });
  1071. }).catch(done.fail);
  1072. });
  1073. it('gets document stats after parsing page', function (done) {
  1074. var promise = page.getOperatorList().then(function () {
  1075. return pdfDocument.getStats();
  1076. });
  1077. var expectedStreamTypes = [];
  1078. expectedStreamTypes[_util.StreamType.FLATE] = true;
  1079. var expectedFontTypes = [];
  1080. expectedFontTypes[_util.FontType.TYPE1] = true;
  1081. expectedFontTypes[_util.FontType.CIDFONTTYPE2] = true;
  1082. promise.then(function (stats) {
  1083. expect(stats).toEqual({
  1084. streamTypes: expectedStreamTypes,
  1085. fontTypes: expectedFontTypes
  1086. });
  1087. done();
  1088. }).catch(done.fail);
  1089. });
  1090. it('gets page stats after parsing page, without `pdfBug` set', function (done) {
  1091. page.getOperatorList().then(function (opList) {
  1092. return page.stats;
  1093. }).then(function (stats) {
  1094. expect(stats).toEqual(null);
  1095. done();
  1096. }, done.fail);
  1097. });
  1098. it('gets page stats after parsing page, with `pdfBug` set', function (done) {
  1099. var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(basicApiFileName, {
  1100. pdfBug: true
  1101. }));
  1102. loadingTask.promise.then(function (pdfDoc) {
  1103. return pdfDoc.getPage(1).then(function (pdfPage) {
  1104. return pdfPage.getOperatorList().then(function (opList) {
  1105. return pdfPage.stats;
  1106. });
  1107. });
  1108. }).then(function (stats) {
  1109. expect(stats instanceof _dom_utils.StatTimer).toEqual(true);
  1110. expect(stats.times.length).toEqual(1);
  1111. var _stats$times = _slicedToArray(stats.times, 1),
  1112. statEntry = _stats$times[0];
  1113. expect(statEntry.name).toEqual('Page Request');
  1114. expect(statEntry.end - statEntry.start).toBeGreaterThan(0);
  1115. loadingTask.destroy().then(done);
  1116. }, done.fail);
  1117. });
  1118. it('gets page stats after rendering page, with `pdfBug` set', function (done) {
  1119. var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(basicApiFileName, {
  1120. pdfBug: true
  1121. }));
  1122. var canvasAndCtx;
  1123. loadingTask.promise.then(function (pdfDoc) {
  1124. return pdfDoc.getPage(1).then(function (pdfPage) {
  1125. var viewport = pdfPage.getViewport({
  1126. scale: 1
  1127. });
  1128. canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height);
  1129. var renderTask = pdfPage.render({
  1130. canvasContext: canvasAndCtx.context,
  1131. canvasFactory: CanvasFactory,
  1132. viewport: viewport
  1133. });
  1134. return renderTask.promise.then(function () {
  1135. return pdfPage.stats;
  1136. });
  1137. });
  1138. }).then(function (stats) {
  1139. expect(stats instanceof _dom_utils.StatTimer).toEqual(true);
  1140. expect(stats.times.length).toEqual(3);
  1141. var _stats$times2 = _slicedToArray(stats.times, 3),
  1142. statEntryOne = _stats$times2[0],
  1143. statEntryTwo = _stats$times2[1],
  1144. statEntryThree = _stats$times2[2];
  1145. expect(statEntryOne.name).toEqual('Page Request');
  1146. expect(statEntryOne.end - statEntryOne.start).toBeGreaterThan(0);
  1147. expect(statEntryTwo.name).toEqual('Rendering');
  1148. expect(statEntryTwo.end - statEntryTwo.start).toBeGreaterThan(0);
  1149. expect(statEntryThree.name).toEqual('Overall');
  1150. expect(statEntryThree.end - statEntryThree.start).toBeGreaterThan(0);
  1151. CanvasFactory.destroy(canvasAndCtx);
  1152. loadingTask.destroy().then(done);
  1153. }, done.fail);
  1154. });
  1155. it('cancels rendering of page', function (done) {
  1156. var viewport = page.getViewport({
  1157. scale: 1
  1158. });
  1159. var canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height);
  1160. var renderTask = page.render({
  1161. canvasContext: canvasAndCtx.context,
  1162. canvasFactory: CanvasFactory,
  1163. viewport: viewport
  1164. });
  1165. renderTask.cancel();
  1166. renderTask.promise.then(function () {
  1167. done.fail('shall cancel rendering');
  1168. }).catch(function (error) {
  1169. expect(error instanceof _dom_utils.RenderingCancelledException).toEqual(true);
  1170. expect(error.type).toEqual('canvas');
  1171. CanvasFactory.destroy(canvasAndCtx);
  1172. done();
  1173. });
  1174. });
  1175. it('re-render page, using the same canvas, after cancelling rendering', function (done) {
  1176. var viewport = page.getViewport({
  1177. scale: 1
  1178. });
  1179. var canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height);
  1180. var renderTask = page.render({
  1181. canvasContext: canvasAndCtx.context,
  1182. canvasFactory: CanvasFactory,
  1183. viewport: viewport
  1184. });
  1185. renderTask.cancel();
  1186. renderTask.promise.then(function () {
  1187. throw new Error('shall cancel rendering');
  1188. }, function (reason) {
  1189. expect(reason instanceof _dom_utils.RenderingCancelledException).toEqual(true);
  1190. }).then(function () {
  1191. var reRenderTask = page.render({
  1192. canvasContext: canvasAndCtx.context,
  1193. canvasFactory: CanvasFactory,
  1194. viewport: viewport
  1195. });
  1196. return reRenderTask.promise;
  1197. }).then(function () {
  1198. CanvasFactory.destroy(canvasAndCtx);
  1199. done();
  1200. }, done.fail);
  1201. });
  1202. it('multiple render() on the same canvas', function (done) {
  1203. var viewport = page.getViewport({
  1204. scale: 1
  1205. });
  1206. var canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height);
  1207. var renderTask1 = page.render({
  1208. canvasContext: canvasAndCtx.context,
  1209. canvasFactory: CanvasFactory,
  1210. viewport: viewport
  1211. });
  1212. var renderTask2 = page.render({
  1213. canvasContext: canvasAndCtx.context,
  1214. canvasFactory: CanvasFactory,
  1215. viewport: viewport
  1216. });
  1217. Promise.all([renderTask1.promise, renderTask2.promise.then(function () {
  1218. done.fail('shall fail rendering');
  1219. }, function (reason) {
  1220. expect(/multiple render\(\)/.test(reason.message)).toEqual(true);
  1221. })]).then(done);
  1222. });
  1223. });
  1224. describe('Multiple `getDocument` instances', function () {
  1225. var pdf1 = (0, _test_utils.buildGetDocumentParams)('tracemonkey.pdf');
  1226. var pdf2 = (0, _test_utils.buildGetDocumentParams)('TAMReview.pdf');
  1227. var pdf3 = (0, _test_utils.buildGetDocumentParams)('issue6068.pdf');
  1228. var loadingTasks = [];
  1229. var pdfDocuments = [];
  1230. function renderPDF(_x) {
  1231. return _renderPDF.apply(this, arguments);
  1232. }
  1233. function _renderPDF() {
  1234. _renderPDF = _asyncToGenerator(
  1235. /*#__PURE__*/
  1236. _regenerator.default.mark(function _callee(filename) {
  1237. var loadingTask, pdf, page, viewport, canvasAndCtx, renderTask, data;
  1238. return _regenerator.default.wrap(function _callee$(_context) {
  1239. while (1) {
  1240. switch (_context.prev = _context.next) {
  1241. case 0:
  1242. loadingTask = (0, _api.getDocument)(filename);
  1243. loadingTasks.push(loadingTask);
  1244. _context.next = 4;
  1245. return loadingTask.promise;
  1246. case 4:
  1247. pdf = _context.sent;
  1248. pdfDocuments.push(pdf);
  1249. _context.next = 8;
  1250. return pdf.getPage(1);
  1251. case 8:
  1252. page = _context.sent;
  1253. viewport = page.getViewport({
  1254. scale: 1.2
  1255. });
  1256. canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height);
  1257. renderTask = page.render({
  1258. canvasContext: canvasAndCtx.context,
  1259. canvasFactory: CanvasFactory,
  1260. viewport: viewport
  1261. });
  1262. _context.next = 14;
  1263. return renderTask.promise;
  1264. case 14:
  1265. data = canvasAndCtx.canvas.toDataURL();
  1266. CanvasFactory.destroy(canvasAndCtx);
  1267. return _context.abrupt("return", data);
  1268. case 17:
  1269. case "end":
  1270. return _context.stop();
  1271. }
  1272. }
  1273. }, _callee, this);
  1274. }));
  1275. return _renderPDF.apply(this, arguments);
  1276. }
  1277. afterEach(function (done) {
  1278. var destroyPromises = pdfDocuments.map(function (pdfDocument) {
  1279. return pdfDocument.destroy();
  1280. });
  1281. var destroyPromises2 = loadingTasks.map(function (loadingTask) {
  1282. return loadingTask.destroy();
  1283. });
  1284. Promise.all(destroyPromises.concat(destroyPromises2)).then(function () {
  1285. done();
  1286. });
  1287. });
  1288. it('should correctly render PDFs in parallel', function (done) {
  1289. var baseline1, baseline2, baseline3;
  1290. var promiseDone = renderPDF(pdf1).then(function (data1) {
  1291. baseline1 = data1;
  1292. return renderPDF(pdf2);
  1293. }).then(function (data2) {
  1294. baseline2 = data2;
  1295. return renderPDF(pdf3);
  1296. }).then(function (data3) {
  1297. baseline3 = data3;
  1298. return Promise.all([renderPDF(pdf1), renderPDF(pdf2), renderPDF(pdf3)]);
  1299. }).then(function (dataUrls) {
  1300. expect(dataUrls[0]).toEqual(baseline1);
  1301. expect(dataUrls[1]).toEqual(baseline2);
  1302. expect(dataUrls[2]).toEqual(baseline3);
  1303. return true;
  1304. });
  1305. promiseDone.then(function () {
  1306. done();
  1307. }).catch(done.fail);
  1308. });
  1309. });
  1310. describe('PDFDataRangeTransport', function () {
  1311. var loadPromise;
  1312. function getDocumentData() {
  1313. var pdfPath = new URL('../pdfs/tracemonkey.pdf', window.location).href;
  1314. if (loadPromise) {
  1315. return loadPromise;
  1316. }
  1317. loadPromise = new Promise(function (resolve, reject) {
  1318. var xhr = new XMLHttpRequest(pdfPath);
  1319. xhr.open('GET', pdfPath);
  1320. xhr.responseType = 'arraybuffer';
  1321. xhr.onload = function () {
  1322. resolve(new Uint8Array(xhr.response));
  1323. };
  1324. xhr.onerror = function () {
  1325. reject(new Error('PDF is not loaded'));
  1326. };
  1327. xhr.send();
  1328. });
  1329. return loadPromise;
  1330. }
  1331. it('should fetch document info and page using ranges', function (done) {
  1332. if ((0, _is_node.default)()) {
  1333. pending('XMLHttpRequest is not supported in Node.js.');
  1334. }
  1335. var transport;
  1336. var initialDataLength = 4000;
  1337. var fetches = 0;
  1338. var getDocumentPromise = getDocumentData().then(function (data) {
  1339. var initialData = data.subarray(0, initialDataLength);
  1340. transport = new _api.PDFDataRangeTransport(data.length, initialData);
  1341. transport.requestDataRange = function (begin, end) {
  1342. fetches++;
  1343. waitSome(function () {
  1344. transport.onDataProgress(4000);
  1345. transport.onDataRange(begin, data.subarray(begin, end));
  1346. });
  1347. };
  1348. var loadingTask = (0, _api.getDocument)(transport);
  1349. return loadingTask.promise;
  1350. });
  1351. var pdfDocument;
  1352. var getPagePromise = getDocumentPromise.then(function (pdfDocument_) {
  1353. pdfDocument = pdfDocument_;
  1354. var pagePromise = pdfDocument.getPage(10);
  1355. return pagePromise;
  1356. });
  1357. getPagePromise.then(function (page) {
  1358. expect(pdfDocument.numPages).toEqual(14);
  1359. expect(page.rotate).toEqual(0);
  1360. expect(fetches).toBeGreaterThan(2);
  1361. done();
  1362. }).catch(done.fail);
  1363. });
  1364. it('should fetch document info and page using range and streaming', function (done) {
  1365. if ((0, _is_node.default)()) {
  1366. pending('XMLHttpRequest is not supported in Node.js.');
  1367. }
  1368. var transport;
  1369. var initialDataLength = 4000;
  1370. var fetches = 0;
  1371. var getDocumentPromise = getDocumentData().then(function (data) {
  1372. var initialData = data.subarray(0, initialDataLength);
  1373. transport = new _api.PDFDataRangeTransport(data.length, initialData);
  1374. transport.requestDataRange = function (begin, end) {
  1375. fetches++;
  1376. if (fetches === 1) {
  1377. transport.onDataProgressiveRead(data.subarray(initialDataLength));
  1378. }
  1379. waitSome(function () {
  1380. transport.onDataRange(begin, data.subarray(begin, end));
  1381. });
  1382. };
  1383. var loadingTask = (0, _api.getDocument)(transport);
  1384. return loadingTask.promise;
  1385. });
  1386. var pdfDocument;
  1387. var getPagePromise = getDocumentPromise.then(function (pdfDocument_) {
  1388. pdfDocument = pdfDocument_;
  1389. var pagePromise = pdfDocument.getPage(10);
  1390. return pagePromise;
  1391. });
  1392. getPagePromise.then(function (page) {
  1393. expect(pdfDocument.numPages).toEqual(14);
  1394. expect(page.rotate).toEqual(0);
  1395. expect(fetches).toEqual(1);
  1396. done();
  1397. }).catch(done.fail);
  1398. });
  1399. });
  1400. });