api_spec.js 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2021 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 _util = require("../../shared/util.js");
  24. var _test_utils = require("./test_utils.js");
  25. var _api = require("../../display/api.js");
  26. var _display_utils = require("../../display/display_utils.js");
  27. var _ui_utils = require("../../web/ui_utils.js");
  28. var _image_utils = require("../../core/image_utils.js");
  29. var _worker_options = require("../../display/worker_options.js");
  30. var _is_node = require("../../shared/is_node.js");
  31. var _metadata = require("../../display/metadata.js");
  32. describe("api", function () {
  33. const basicApiFileName = "basicapi.pdf";
  34. const basicApiFileLength = 105779;
  35. const basicApiGetDocumentParams = (0, _test_utils.buildGetDocumentParams)(basicApiFileName);
  36. let CanvasFactory;
  37. beforeAll(function () {
  38. CanvasFactory = new _api.DefaultCanvasFactory();
  39. });
  40. afterAll(function () {
  41. CanvasFactory = null;
  42. });
  43. function waitSome(callback) {
  44. const WAIT_TIMEOUT = 10;
  45. setTimeout(function () {
  46. callback();
  47. }, WAIT_TIMEOUT);
  48. }
  49. describe("getDocument", function () {
  50. it("creates pdf doc from URL-string", async function () {
  51. const urlStr = _test_utils.TEST_PDFS_PATH + basicApiFileName;
  52. const loadingTask = (0, _api.getDocument)(urlStr);
  53. expect(loadingTask instanceof _api.PDFDocumentLoadingTask).toEqual(true);
  54. const pdfDocument = await loadingTask.promise;
  55. expect(typeof urlStr).toEqual("string");
  56. expect(pdfDocument instanceof _api.PDFDocumentProxy).toEqual(true);
  57. expect(pdfDocument.numPages).toEqual(3);
  58. await loadingTask.destroy();
  59. });
  60. it("creates pdf doc from URL-object", async function () {
  61. if (_is_node.isNodeJS) {
  62. pending("window.location is not supported in Node.js.");
  63. }
  64. const urlObj = new URL(_test_utils.TEST_PDFS_PATH + basicApiFileName, window.location);
  65. const loadingTask = (0, _api.getDocument)(urlObj);
  66. expect(loadingTask instanceof _api.PDFDocumentLoadingTask).toEqual(true);
  67. const pdfDocument = await loadingTask.promise;
  68. expect(urlObj instanceof URL).toEqual(true);
  69. expect(pdfDocument instanceof _api.PDFDocumentProxy).toEqual(true);
  70. expect(pdfDocument.numPages).toEqual(3);
  71. await loadingTask.destroy();
  72. });
  73. it("creates pdf doc from URL", async function () {
  74. const loadingTask = (0, _api.getDocument)(basicApiGetDocumentParams);
  75. expect(loadingTask instanceof _api.PDFDocumentLoadingTask).toEqual(true);
  76. const progressReportedCapability = (0, _util.createPromiseCapability)();
  77. loadingTask.onProgress = function (progressData) {
  78. if (!progressReportedCapability.settled) {
  79. progressReportedCapability.resolve(progressData);
  80. }
  81. };
  82. const data = await Promise.all([progressReportedCapability.promise, loadingTask.promise]);
  83. expect(data[0].loaded / data[0].total >= 0).toEqual(true);
  84. expect(data[1] instanceof _api.PDFDocumentProxy).toEqual(true);
  85. expect(loadingTask).toEqual(data[1].loadingTask);
  86. await loadingTask.destroy();
  87. });
  88. it("creates pdf doc from URL and aborts before worker initialized", async function () {
  89. const loadingTask = (0, _api.getDocument)(basicApiGetDocumentParams);
  90. expect(loadingTask instanceof _api.PDFDocumentLoadingTask).toEqual(true);
  91. const destroyed = loadingTask.destroy();
  92. try {
  93. await loadingTask.promise;
  94. expect(false).toEqual(true);
  95. } catch (reason) {
  96. expect(true).toEqual(true);
  97. await destroyed;
  98. }
  99. });
  100. it("creates pdf doc from URL and aborts loading after worker initialized", async function () {
  101. const loadingTask = (0, _api.getDocument)(basicApiGetDocumentParams);
  102. expect(loadingTask instanceof _api.PDFDocumentLoadingTask).toEqual(true);
  103. const destroyed = loadingTask._worker.promise.then(function () {
  104. return loadingTask.destroy();
  105. });
  106. await destroyed;
  107. expect(true).toEqual(true);
  108. });
  109. it("creates pdf doc from typed array", async function () {
  110. const typedArrayPdf = await _test_utils.DefaultFileReaderFactory.fetch({
  111. path: _test_utils.TEST_PDFS_PATH + basicApiFileName
  112. });
  113. expect(typedArrayPdf.length).toEqual(basicApiFileLength);
  114. const loadingTask = (0, _api.getDocument)(typedArrayPdf);
  115. expect(loadingTask instanceof _api.PDFDocumentLoadingTask).toEqual(true);
  116. const progressReportedCapability = (0, _util.createPromiseCapability)();
  117. loadingTask.onProgress = function (data) {
  118. progressReportedCapability.resolve(data);
  119. };
  120. const data = await Promise.all([loadingTask.promise, progressReportedCapability.promise]);
  121. expect(data[0] instanceof _api.PDFDocumentProxy).toEqual(true);
  122. expect(data[1].loaded / data[1].total).toEqual(1);
  123. await loadingTask.destroy();
  124. });
  125. it("creates pdf doc from invalid PDF file", async function () {
  126. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("bug1020226.pdf"));
  127. expect(loadingTask instanceof _api.PDFDocumentLoadingTask).toEqual(true);
  128. try {
  129. await loadingTask.promise;
  130. expect(false).toEqual(true);
  131. } catch (reason) {
  132. expect(reason instanceof _util.InvalidPDFException).toEqual(true);
  133. expect(reason.message).toEqual("Invalid PDF structure.");
  134. }
  135. await loadingTask.destroy();
  136. });
  137. it("creates pdf doc from non-existent URL", async function () {
  138. if (!_is_node.isNodeJS) {
  139. pending("Fails intermittently on Linux in browsers.");
  140. }
  141. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("non-existent.pdf"));
  142. expect(loadingTask instanceof _api.PDFDocumentLoadingTask).toEqual(true);
  143. try {
  144. await loadingTask.promise;
  145. expect(false).toEqual(true);
  146. } catch (reason) {
  147. expect(reason instanceof _util.MissingPDFException).toEqual(true);
  148. }
  149. await loadingTask.destroy();
  150. });
  151. it("creates pdf doc from PDF file protected with user and owner password", async function () {
  152. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("pr6531_1.pdf"));
  153. expect(loadingTask instanceof _api.PDFDocumentLoadingTask).toEqual(true);
  154. const passwordNeededCapability = (0, _util.createPromiseCapability)();
  155. const passwordIncorrectCapability = (0, _util.createPromiseCapability)();
  156. loadingTask.onPassword = function (updatePassword, reason) {
  157. if (reason === _util.PasswordResponses.NEED_PASSWORD && !passwordNeededCapability.settled) {
  158. passwordNeededCapability.resolve();
  159. updatePassword("qwerty");
  160. return;
  161. }
  162. if (reason === _util.PasswordResponses.INCORRECT_PASSWORD && !passwordIncorrectCapability.settled) {
  163. passwordIncorrectCapability.resolve();
  164. updatePassword("asdfasdf");
  165. return;
  166. }
  167. expect(false).toEqual(true);
  168. };
  169. const data = await Promise.all([passwordNeededCapability.promise, passwordIncorrectCapability.promise, loadingTask.promise]);
  170. expect(data[2] instanceof _api.PDFDocumentProxy).toEqual(true);
  171. await loadingTask.destroy();
  172. });
  173. it("creates pdf doc from PDF file protected with only a user password", async function () {
  174. const filename = "pr6531_2.pdf";
  175. const passwordNeededLoadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(filename, {
  176. password: ""
  177. }));
  178. expect(passwordNeededLoadingTask instanceof _api.PDFDocumentLoadingTask).toEqual(true);
  179. const result1 = passwordNeededLoadingTask.promise.then(function () {
  180. expect(false).toEqual(true);
  181. return Promise.reject(new Error("loadingTask should be rejected"));
  182. }, function (data) {
  183. expect(data instanceof _util.PasswordException).toEqual(true);
  184. expect(data.code).toEqual(_util.PasswordResponses.NEED_PASSWORD);
  185. return passwordNeededLoadingTask.destroy();
  186. });
  187. const passwordIncorrectLoadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(filename, {
  188. password: "qwerty"
  189. }));
  190. expect(passwordIncorrectLoadingTask instanceof _api.PDFDocumentLoadingTask).toEqual(true);
  191. const result2 = passwordIncorrectLoadingTask.promise.then(function () {
  192. expect(false).toEqual(true);
  193. return Promise.reject(new Error("loadingTask should be rejected"));
  194. }, function (data) {
  195. expect(data instanceof _util.PasswordException).toEqual(true);
  196. expect(data.code).toEqual(_util.PasswordResponses.INCORRECT_PASSWORD);
  197. return passwordIncorrectLoadingTask.destroy();
  198. });
  199. const passwordAcceptedLoadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(filename, {
  200. password: "asdfasdf"
  201. }));
  202. expect(passwordAcceptedLoadingTask instanceof _api.PDFDocumentLoadingTask).toEqual(true);
  203. const result3 = passwordAcceptedLoadingTask.promise.then(function (data) {
  204. expect(data instanceof _api.PDFDocumentProxy).toEqual(true);
  205. return passwordAcceptedLoadingTask.destroy();
  206. });
  207. await Promise.all([result1, result2, result3]);
  208. });
  209. it("creates pdf doc from password protected PDF file and aborts/throws " + "in the onPassword callback (issue 7806)", async function () {
  210. const filename = "issue3371.pdf";
  211. const passwordNeededLoadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(filename));
  212. expect(passwordNeededLoadingTask instanceof _api.PDFDocumentLoadingTask).toEqual(true);
  213. const passwordIncorrectLoadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(filename, {
  214. password: "qwerty"
  215. }));
  216. expect(passwordIncorrectLoadingTask instanceof _api.PDFDocumentLoadingTask).toEqual(true);
  217. let passwordNeededDestroyed;
  218. passwordNeededLoadingTask.onPassword = function (callback, reason) {
  219. if (reason === _util.PasswordResponses.NEED_PASSWORD) {
  220. passwordNeededDestroyed = passwordNeededLoadingTask.destroy();
  221. return;
  222. }
  223. expect(false).toEqual(true);
  224. };
  225. const result1 = passwordNeededLoadingTask.promise.then(function () {
  226. expect(false).toEqual(true);
  227. return Promise.reject(new Error("loadingTask should be rejected"));
  228. }, function (reason) {
  229. expect(reason instanceof _util.PasswordException).toEqual(true);
  230. expect(reason.code).toEqual(_util.PasswordResponses.NEED_PASSWORD);
  231. return passwordNeededDestroyed;
  232. });
  233. passwordIncorrectLoadingTask.onPassword = function (callback, reason) {
  234. if (reason === _util.PasswordResponses.INCORRECT_PASSWORD) {
  235. throw new Error("Incorrect password");
  236. }
  237. expect(false).toEqual(true);
  238. };
  239. const result2 = passwordIncorrectLoadingTask.promise.then(function () {
  240. expect(false).toEqual(true);
  241. return Promise.reject(new Error("loadingTask should be rejected"));
  242. }, function (reason) {
  243. expect(reason instanceof _util.PasswordException).toEqual(true);
  244. expect(reason.code).toEqual(_util.PasswordResponses.INCORRECT_PASSWORD);
  245. return passwordIncorrectLoadingTask.destroy();
  246. });
  247. await Promise.all([result1, result2]);
  248. });
  249. it("creates pdf doc from empty typed array", async function () {
  250. const loadingTask = (0, _api.getDocument)(new Uint8Array(0));
  251. expect(loadingTask instanceof _api.PDFDocumentLoadingTask).toEqual(true);
  252. try {
  253. await loadingTask.promise;
  254. expect(false).toEqual(true);
  255. } catch (reason) {
  256. expect(reason instanceof _util.InvalidPDFException).toEqual(true);
  257. expect(reason.message).toEqual("The PDF file is empty, i.e. its size is zero bytes.");
  258. }
  259. await loadingTask.destroy();
  260. });
  261. it("checks that `docId`s are unique and increasing", async function () {
  262. const loadingTask1 = (0, _api.getDocument)(basicApiGetDocumentParams);
  263. expect(loadingTask1 instanceof _api.PDFDocumentLoadingTask).toEqual(true);
  264. await loadingTask1.promise;
  265. const docId1 = loadingTask1.docId;
  266. const loadingTask2 = (0, _api.getDocument)(basicApiGetDocumentParams);
  267. expect(loadingTask2 instanceof _api.PDFDocumentLoadingTask).toEqual(true);
  268. await loadingTask2.promise;
  269. const docId2 = loadingTask2.docId;
  270. expect(docId1).not.toEqual(docId2);
  271. const docIdRegExp = /^d(\d+)$/,
  272. docNum1 = docIdRegExp.exec(docId1)?.[1],
  273. docNum2 = docIdRegExp.exec(docId2)?.[1];
  274. expect(+docNum1).toBeLessThan(+docNum2);
  275. await Promise.all([loadingTask1.destroy(), loadingTask2.destroy()]);
  276. });
  277. });
  278. describe("PDFWorker", function () {
  279. it("worker created or destroyed", async function () {
  280. if (_is_node.isNodeJS) {
  281. pending("Worker is not supported in Node.js.");
  282. }
  283. const worker = new _api.PDFWorker({
  284. name: "test1"
  285. });
  286. await worker.promise;
  287. expect(worker.name).toEqual("test1");
  288. expect(!!worker.port).toEqual(true);
  289. expect(worker.destroyed).toEqual(false);
  290. expect(!!worker._webWorker).toEqual(true);
  291. expect(worker.port === worker._webWorker).toEqual(true);
  292. worker.destroy();
  293. expect(!!worker.port).toEqual(false);
  294. expect(worker.destroyed).toEqual(true);
  295. });
  296. it("worker created or destroyed by getDocument", async function () {
  297. if (_is_node.isNodeJS) {
  298. pending("Worker is not supported in Node.js.");
  299. }
  300. const loadingTask = (0, _api.getDocument)(basicApiGetDocumentParams);
  301. let worker;
  302. loadingTask.promise.then(function () {
  303. worker = loadingTask._worker;
  304. expect(!!worker).toEqual(true);
  305. });
  306. const destroyPromise = loadingTask.promise.then(function () {
  307. return loadingTask.destroy();
  308. });
  309. await destroyPromise;
  310. const destroyedWorker = loadingTask._worker;
  311. expect(!!destroyedWorker).toEqual(false);
  312. expect(worker.destroyed).toEqual(true);
  313. });
  314. it("worker created and can be used in getDocument", async function () {
  315. if (_is_node.isNodeJS) {
  316. pending("Worker is not supported in Node.js.");
  317. }
  318. const worker = new _api.PDFWorker({
  319. name: "test1"
  320. });
  321. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(basicApiFileName, {
  322. worker
  323. }));
  324. loadingTask.promise.then(function () {
  325. const docWorker = loadingTask._worker;
  326. expect(!!docWorker).toEqual(false);
  327. const messageHandlerPort = loadingTask._transport.messageHandler.comObj;
  328. expect(messageHandlerPort === worker.port).toEqual(true);
  329. });
  330. const destroyPromise = loadingTask.promise.then(function () {
  331. return loadingTask.destroy();
  332. });
  333. await destroyPromise;
  334. expect(worker.destroyed).toEqual(false);
  335. worker.destroy();
  336. });
  337. it("creates more than one worker", async function () {
  338. if (_is_node.isNodeJS) {
  339. pending("Worker is not supported in Node.js.");
  340. }
  341. const worker1 = new _api.PDFWorker({
  342. name: "test1"
  343. });
  344. const worker2 = new _api.PDFWorker({
  345. name: "test2"
  346. });
  347. const worker3 = new _api.PDFWorker({
  348. name: "test3"
  349. });
  350. await Promise.all([worker1.promise, worker2.promise, worker3.promise]);
  351. expect(worker1.port !== worker2.port && worker1.port !== worker3.port && worker2.port !== worker3.port).toEqual(true);
  352. worker1.destroy();
  353. worker2.destroy();
  354. worker3.destroy();
  355. });
  356. it("gets current workerSrc", function () {
  357. if (_is_node.isNodeJS) {
  358. pending("Worker is not supported in Node.js.");
  359. }
  360. const workerSrc = _api.PDFWorker.workerSrc;
  361. expect(typeof workerSrc).toEqual("string");
  362. expect(workerSrc).toEqual(_worker_options.GlobalWorkerOptions.workerSrc);
  363. });
  364. });
  365. describe("PDFDocument", function () {
  366. let pdfLoadingTask, pdfDocument;
  367. beforeAll(async function () {
  368. pdfLoadingTask = (0, _api.getDocument)(basicApiGetDocumentParams);
  369. pdfDocument = await pdfLoadingTask.promise;
  370. });
  371. afterAll(async function () {
  372. await pdfLoadingTask.destroy();
  373. });
  374. it("gets number of pages", function () {
  375. expect(pdfDocument.numPages).toEqual(3);
  376. });
  377. it("gets fingerprints", function () {
  378. expect(pdfDocument.fingerprints).toEqual(["ea8b35919d6279a369e835bde778611b", null]);
  379. });
  380. it("gets fingerprints, from modified document", async function () {
  381. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("annotation-tx.pdf"));
  382. const pdfDoc = await loadingTask.promise;
  383. expect(pdfDoc.fingerprints).toEqual(["3ebd77c320274649a68f10dbf3b9f882", "e7087346aa4b4ae0911c1f1643b57345"]);
  384. await loadingTask.destroy();
  385. });
  386. it("gets page", async function () {
  387. const data = await pdfDocument.getPage(1);
  388. expect(data instanceof _api.PDFPageProxy).toEqual(true);
  389. expect(data.pageNumber).toEqual(1);
  390. });
  391. it("gets non-existent page", async function () {
  392. let outOfRangePromise = pdfDocument.getPage(100);
  393. let nonIntegerPromise = pdfDocument.getPage(2.5);
  394. let nonNumberPromise = pdfDocument.getPage("1");
  395. outOfRangePromise = outOfRangePromise.then(function () {
  396. throw new Error("shall fail for out-of-range pageNumber parameter");
  397. }, function (reason) {
  398. expect(reason instanceof Error).toEqual(true);
  399. });
  400. nonIntegerPromise = nonIntegerPromise.then(function () {
  401. throw new Error("shall fail for non-integer pageNumber parameter");
  402. }, function (reason) {
  403. expect(reason instanceof Error).toEqual(true);
  404. });
  405. nonNumberPromise = nonNumberPromise.then(function () {
  406. throw new Error("shall fail for non-number pageNumber parameter");
  407. }, function (reason) {
  408. expect(reason instanceof Error).toEqual(true);
  409. });
  410. await Promise.all([outOfRangePromise, nonIntegerPromise, nonNumberPromise]);
  411. });
  412. it("gets page, from /Pages tree with circular reference", async function () {
  413. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("Pages-tree-refs.pdf"));
  414. const page1 = loadingTask.promise.then(function (pdfDoc) {
  415. return pdfDoc.getPage(1).then(function (pdfPage) {
  416. expect(pdfPage instanceof _api.PDFPageProxy).toEqual(true);
  417. expect(pdfPage.ref).toEqual({
  418. num: 6,
  419. gen: 0
  420. });
  421. }, function (reason) {
  422. throw new Error("shall not fail for valid page");
  423. });
  424. });
  425. const page2 = loadingTask.promise.then(function (pdfDoc) {
  426. return pdfDoc.getPage(2).then(function (pdfPage) {
  427. throw new Error("shall fail for invalid page");
  428. }, function (reason) {
  429. expect(reason instanceof Error).toEqual(true);
  430. expect(reason.message).toEqual("Pages tree contains circular reference.");
  431. });
  432. });
  433. await Promise.all([page1, page2]);
  434. await loadingTask.destroy();
  435. });
  436. it("gets page index", async function () {
  437. const ref = {
  438. num: 17,
  439. gen: 0
  440. };
  441. const pageIndex = await pdfDocument.getPageIndex(ref);
  442. expect(pageIndex).toEqual(1);
  443. });
  444. it("gets invalid page index", async function () {
  445. const ref = {
  446. num: 3,
  447. gen: 0
  448. };
  449. try {
  450. await pdfDocument.getPageIndex(ref);
  451. expect(false).toEqual(true);
  452. } catch (reason) {
  453. expect(reason instanceof Error).toEqual(true);
  454. }
  455. });
  456. it("gets destinations, from /Dests dictionary", async function () {
  457. const destinations = await pdfDocument.getDestinations();
  458. expect(destinations).toEqual({
  459. chapter1: [{
  460. gen: 0,
  461. num: 17
  462. }, {
  463. name: "XYZ"
  464. }, 0, 841.89, null]
  465. });
  466. });
  467. it("gets a destination, from /Dests dictionary", async function () {
  468. const destination = await pdfDocument.getDestination("chapter1");
  469. expect(destination).toEqual([{
  470. gen: 0,
  471. num: 17
  472. }, {
  473. name: "XYZ"
  474. }, 0, 841.89, null]);
  475. });
  476. it("gets a non-existent destination, from /Dests dictionary", async function () {
  477. const destination = await pdfDocument.getDestination("non-existent-named-destination");
  478. expect(destination).toEqual(null);
  479. });
  480. it("gets destinations, from /Names (NameTree) dictionary", async function () {
  481. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("issue6204.pdf"));
  482. const pdfDoc = await loadingTask.promise;
  483. const destinations = await pdfDoc.getDestinations();
  484. expect(destinations).toEqual({
  485. "Page.1": [{
  486. num: 1,
  487. gen: 0
  488. }, {
  489. name: "XYZ"
  490. }, 0, 375, null],
  491. "Page.2": [{
  492. num: 6,
  493. gen: 0
  494. }, {
  495. name: "XYZ"
  496. }, 0, 375, null]
  497. });
  498. await loadingTask.destroy();
  499. });
  500. it("gets a destination, from /Names (NameTree) dictionary", async function () {
  501. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("issue6204.pdf"));
  502. const pdfDoc = await loadingTask.promise;
  503. const destination = await pdfDoc.getDestination("Page.1");
  504. expect(destination).toEqual([{
  505. num: 1,
  506. gen: 0
  507. }, {
  508. name: "XYZ"
  509. }, 0, 375, null]);
  510. await loadingTask.destroy();
  511. });
  512. it("gets a non-existent destination, from /Names (NameTree) dictionary", async function () {
  513. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("issue6204.pdf"));
  514. const pdfDoc = await loadingTask.promise;
  515. const destination = await pdfDoc.getDestination("non-existent-named-destination");
  516. expect(destination).toEqual(null);
  517. await loadingTask.destroy();
  518. });
  519. it("gets a destination, from out-of-order /Names (NameTree) dictionary (issue 10272)", async function () {
  520. if (_is_node.isNodeJS) {
  521. pending("Linked test-cases are not supported in Node.js.");
  522. }
  523. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("issue10272.pdf"));
  524. const pdfDoc = await loadingTask.promise;
  525. const destination = await pdfDoc.getDestination("link_1");
  526. expect(destination).toEqual([{
  527. num: 17,
  528. gen: 0
  529. }, {
  530. name: "XYZ"
  531. }, 69, 125, 0]);
  532. await loadingTask.destroy();
  533. });
  534. it("gets non-string destination", async function () {
  535. let numberPromise = pdfDocument.getDestination(4.3);
  536. let booleanPromise = pdfDocument.getDestination(true);
  537. let arrayPromise = pdfDocument.getDestination([{
  538. num: 17,
  539. gen: 0
  540. }, {
  541. name: "XYZ"
  542. }, 0, 841.89, null]);
  543. numberPromise = numberPromise.then(function () {
  544. throw new Error("shall fail for non-string destination.");
  545. }, function (reason) {
  546. expect(reason instanceof Error).toEqual(true);
  547. });
  548. booleanPromise = booleanPromise.then(function () {
  549. throw new Error("shall fail for non-string destination.");
  550. }, function (reason) {
  551. expect(reason instanceof Error).toEqual(true);
  552. });
  553. arrayPromise = arrayPromise.then(function () {
  554. throw new Error("shall fail for non-string destination.");
  555. }, function (reason) {
  556. expect(reason instanceof Error).toEqual(true);
  557. });
  558. await Promise.all([numberPromise, booleanPromise, arrayPromise]);
  559. });
  560. it("gets non-existent page labels", async function () {
  561. const pageLabels = await pdfDocument.getPageLabels();
  562. expect(pageLabels).toEqual(null);
  563. });
  564. it("gets page labels", async function () {
  565. const loadingTask0 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("bug793632.pdf"));
  566. const promise0 = loadingTask0.promise.then(function (pdfDoc) {
  567. return pdfDoc.getPageLabels();
  568. });
  569. const loadingTask1 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("issue1453.pdf"));
  570. const promise1 = loadingTask1.promise.then(function (pdfDoc) {
  571. return pdfDoc.getPageLabels();
  572. });
  573. const loadingTask2 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("rotation.pdf"));
  574. const promise2 = loadingTask2.promise.then(function (pdfDoc) {
  575. return pdfDoc.getPageLabels();
  576. });
  577. const loadingTask3 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("bad-PageLabels.pdf"));
  578. const promise3 = loadingTask3.promise.then(function (pdfDoc) {
  579. return pdfDoc.getPageLabels();
  580. });
  581. const pageLabels = await Promise.all([promise0, promise1, promise2, promise3]);
  582. expect(pageLabels[0]).toEqual(["i", "ii", "iii", "1"]);
  583. expect(pageLabels[1]).toEqual(["Front Page1"]);
  584. expect(pageLabels[2]).toEqual(["1", "2"]);
  585. expect(pageLabels[3]).toEqual(["X3"]);
  586. await Promise.all([loadingTask0.destroy(), loadingTask1.destroy(), loadingTask2.destroy(), loadingTask3.destroy()]);
  587. });
  588. it("gets default page layout", async function () {
  589. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("tracemonkey.pdf"));
  590. const pdfDoc = await loadingTask.promise;
  591. const pageLayout = await pdfDoc.getPageLayout();
  592. expect(pageLayout).toEqual("");
  593. await loadingTask.destroy();
  594. });
  595. it("gets non-default page layout", async function () {
  596. const pageLayout = await pdfDocument.getPageLayout();
  597. expect(pageLayout).toEqual("SinglePage");
  598. });
  599. it("gets default page mode", async function () {
  600. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("tracemonkey.pdf"));
  601. const pdfDoc = await loadingTask.promise;
  602. const pageMode = await pdfDoc.getPageMode();
  603. expect(pageMode).toEqual("UseNone");
  604. await loadingTask.destroy();
  605. });
  606. it("gets non-default page mode", async function () {
  607. const pageMode = await pdfDocument.getPageMode();
  608. expect(pageMode).toEqual("UseOutlines");
  609. });
  610. it("gets default viewer preferences", async function () {
  611. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("tracemonkey.pdf"));
  612. const pdfDoc = await loadingTask.promise;
  613. const prefs = await pdfDoc.getViewerPreferences();
  614. expect(prefs).toEqual(null);
  615. await loadingTask.destroy();
  616. });
  617. it("gets non-default viewer preferences", async function () {
  618. const prefs = await pdfDocument.getViewerPreferences();
  619. expect(prefs).toEqual({
  620. Direction: "L2R"
  621. });
  622. });
  623. it("gets default open action", async function () {
  624. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("tracemonkey.pdf"));
  625. const pdfDoc = await loadingTask.promise;
  626. const openAction = await pdfDoc.getOpenAction();
  627. expect(openAction).toEqual(null);
  628. await loadingTask.destroy();
  629. });
  630. it("gets non-default open action (with destination)", async function () {
  631. const openAction = await pdfDocument.getOpenAction();
  632. expect(openAction.dest).toEqual([{
  633. num: 15,
  634. gen: 0
  635. }, {
  636. name: "FitH"
  637. }, null]);
  638. expect(openAction.action).toBeUndefined();
  639. });
  640. it("gets non-default open action (with Print action)", async function () {
  641. const loadingTask1 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("bug1001080.pdf"));
  642. const loadingTask2 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("issue11442_reduced.pdf"));
  643. const promise1 = loadingTask1.promise.then(function (pdfDoc) {
  644. return pdfDoc.getOpenAction();
  645. }).then(function (openAction) {
  646. expect(openAction.dest).toBeUndefined();
  647. expect(openAction.action).toEqual("Print");
  648. return loadingTask1.destroy();
  649. });
  650. const promise2 = loadingTask2.promise.then(function (pdfDoc) {
  651. return pdfDoc.getOpenAction();
  652. }).then(function (openAction) {
  653. expect(openAction.dest).toBeUndefined();
  654. expect(openAction.action).toEqual("Print");
  655. return loadingTask2.destroy();
  656. });
  657. await Promise.all([promise1, promise2]);
  658. });
  659. it("gets non-existent attachments", async function () {
  660. const attachments = await pdfDocument.getAttachments();
  661. expect(attachments).toEqual(null);
  662. });
  663. it("gets attachments", async function () {
  664. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("attachment.pdf"));
  665. const pdfDoc = await loadingTask.promise;
  666. const attachments = await pdfDoc.getAttachments();
  667. const attachment = attachments["foo.txt"];
  668. expect(attachment.filename).toEqual("foo.txt");
  669. expect(attachment.content).toEqual(new Uint8Array([98, 97, 114, 32, 98, 97, 122, 32, 10]));
  670. await loadingTask.destroy();
  671. });
  672. it("gets javascript", async function () {
  673. const javascript = await pdfDocument.getJavaScript();
  674. expect(javascript).toEqual(null);
  675. });
  676. it("gets javascript with printing instructions (JS action)", async function () {
  677. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("issue6106.pdf"));
  678. const pdfDoc = await loadingTask.promise;
  679. const javascript = await pdfDoc.getJavaScript();
  680. expect(javascript).toEqual(["this.print({bUI:true,bSilent:false,bShrinkToFit:true});"]);
  681. expect(javascript[0]).toMatch(_ui_utils.AutoPrintRegExp);
  682. await loadingTask.destroy();
  683. });
  684. it("gets hasJSActions, in document without javaScript", async function () {
  685. const hasJSActions = await pdfDocument.hasJSActions();
  686. expect(hasJSActions).toEqual(false);
  687. });
  688. it("gets hasJSActions, in document with javaScript", async function () {
  689. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("doc_actions.pdf"));
  690. const pdfDoc = await loadingTask.promise;
  691. const hasJSActions = await pdfDoc.hasJSActions();
  692. expect(hasJSActions).toEqual(true);
  693. await loadingTask.destroy();
  694. });
  695. it("gets non-existent JSActions", async function () {
  696. const jsActions = await pdfDocument.getJSActions();
  697. expect(jsActions).toEqual(null);
  698. });
  699. it("gets JSActions", async function () {
  700. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("doc_actions.pdf"));
  701. const pdfDoc = await loadingTask.promise;
  702. const docActions = await pdfDoc.getJSActions();
  703. const page1 = await pdfDoc.getPage(1);
  704. const page1Actions = await page1.getJSActions();
  705. const page3 = await pdfDoc.getPage(3);
  706. const page3Actions = await page3.getJSActions();
  707. expect(docActions).toEqual({
  708. DidPrint: [`this.getField("Text2").value = "DidPrint";`],
  709. DidSave: [`this.getField("Text2").value = "DidSave";`],
  710. WillClose: [`this.getField("Text1").value = "WillClose";`],
  711. WillPrint: [`this.getField("Text1").value = "WillPrint";`],
  712. WillSave: [`this.getField("Text1").value = "WillSave";`]
  713. });
  714. expect(page1Actions).toEqual({
  715. PageOpen: [`this.getField("Text1").value = "PageOpen 1";`],
  716. PageClose: [`this.getField("Text2").value = "PageClose 1";`]
  717. });
  718. expect(page3Actions).toEqual({
  719. PageOpen: [`this.getField("Text5").value = "PageOpen 3";`],
  720. PageClose: [`this.getField("Text6").value = "PageClose 3";`]
  721. });
  722. await loadingTask.destroy();
  723. });
  724. it("gets non-existent outline", async function () {
  725. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("tracemonkey.pdf"));
  726. const pdfDoc = await loadingTask.promise;
  727. const outline = await pdfDoc.getOutline();
  728. expect(outline).toEqual(null);
  729. await loadingTask.destroy();
  730. });
  731. it("gets outline", async function () {
  732. const outline = await pdfDocument.getOutline();
  733. expect(Array.isArray(outline)).toEqual(true);
  734. expect(outline.length).toEqual(2);
  735. const outlineItem = outline[1];
  736. expect(outlineItem.title).toEqual("Chapter 1");
  737. expect(Array.isArray(outlineItem.dest)).toEqual(true);
  738. expect(outlineItem.url).toEqual(null);
  739. expect(outlineItem.unsafeUrl).toBeUndefined();
  740. expect(outlineItem.newWindow).toBeUndefined();
  741. expect(outlineItem.bold).toEqual(true);
  742. expect(outlineItem.italic).toEqual(false);
  743. expect(outlineItem.color).toEqual(new Uint8ClampedArray([0, 64, 128]));
  744. expect(outlineItem.items.length).toEqual(1);
  745. expect(outlineItem.items[0].title).toEqual("Paragraph 1.1");
  746. });
  747. it("gets outline containing a URL", async function () {
  748. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("issue3214.pdf"));
  749. const pdfDoc = await loadingTask.promise;
  750. const outline = await pdfDoc.getOutline();
  751. expect(Array.isArray(outline)).toEqual(true);
  752. expect(outline.length).toEqual(5);
  753. const outlineItemTwo = outline[2];
  754. expect(typeof outlineItemTwo.title).toEqual("string");
  755. expect(outlineItemTwo.dest).toEqual(null);
  756. expect(outlineItemTwo.url).toEqual("http://google.com/");
  757. expect(outlineItemTwo.unsafeUrl).toEqual("http://google.com");
  758. expect(outlineItemTwo.newWindow).toBeUndefined();
  759. const outlineItemOne = outline[1];
  760. expect(outlineItemOne.bold).toEqual(false);
  761. expect(outlineItemOne.italic).toEqual(true);
  762. expect(outlineItemOne.color).toEqual(new Uint8ClampedArray([0, 0, 0]));
  763. await loadingTask.destroy();
  764. });
  765. it("gets non-existent permissions", async function () {
  766. const permissions = await pdfDocument.getPermissions();
  767. expect(permissions).toEqual(null);
  768. });
  769. it("gets permissions", async function () {
  770. const loadingTask0 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("issue9972-1.pdf"));
  771. const promise0 = loadingTask0.promise.then(function (pdfDoc) {
  772. return pdfDoc.getPermissions();
  773. });
  774. const loadingTask1 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("issue9972-2.pdf"));
  775. const promise1 = loadingTask1.promise.then(function (pdfDoc) {
  776. return pdfDoc.getPermissions();
  777. });
  778. const loadingTask2 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("issue9972-3.pdf"));
  779. const promise2 = loadingTask2.promise.then(function (pdfDoc) {
  780. return pdfDoc.getPermissions();
  781. });
  782. const totalPermissionCount = Object.keys(_util.PermissionFlag).length;
  783. const permissions = await Promise.all([promise0, promise1, promise2]);
  784. expect(permissions[0].length).toEqual(totalPermissionCount - 1);
  785. expect(permissions[0].includes(_util.PermissionFlag.MODIFY_CONTENTS)).toBeFalsy();
  786. expect(permissions[1].length).toEqual(totalPermissionCount - 2);
  787. expect(permissions[1].includes(_util.PermissionFlag.PRINT)).toBeFalsy();
  788. expect(permissions[1].includes(_util.PermissionFlag.PRINT_HIGH_QUALITY)).toBeFalsy();
  789. expect(permissions[2].length).toEqual(totalPermissionCount - 1);
  790. expect(permissions[2].includes(_util.PermissionFlag.COPY)).toBeFalsy();
  791. await Promise.all([loadingTask0.destroy(), loadingTask1.destroy(), loadingTask2.destroy()]);
  792. });
  793. it("gets metadata", async function () {
  794. const {
  795. info,
  796. metadata,
  797. contentDispositionFilename,
  798. contentLength
  799. } = await pdfDocument.getMetadata();
  800. expect(info.Title).toEqual("Basic API Test");
  801. expect(info.Custom).toEqual(undefined);
  802. expect(info.PDFFormatVersion).toEqual("1.7");
  803. expect(info.IsLinearized).toEqual(false);
  804. expect(info.IsAcroFormPresent).toEqual(false);
  805. expect(info.IsXFAPresent).toEqual(false);
  806. expect(info.IsCollectionPresent).toEqual(false);
  807. expect(info.IsSignaturesPresent).toEqual(false);
  808. expect(metadata instanceof _metadata.Metadata).toEqual(true);
  809. expect(metadata.get("dc:title")).toEqual("Basic API Test");
  810. expect(contentDispositionFilename).toEqual(null);
  811. expect(contentLength).toEqual(basicApiFileLength);
  812. });
  813. it("gets metadata, with custom info dict entries", async function () {
  814. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("tracemonkey.pdf"));
  815. const pdfDoc = await loadingTask.promise;
  816. const {
  817. info,
  818. metadata,
  819. contentDispositionFilename,
  820. contentLength
  821. } = await pdfDoc.getMetadata();
  822. expect(info.Creator).toEqual("TeX");
  823. expect(info.Producer).toEqual("pdfeTeX-1.21a");
  824. expect(info.CreationDate).toEqual("D:20090401163925-07'00'");
  825. const custom = info.Custom;
  826. expect(typeof custom === "object" && custom !== null).toEqual(true);
  827. expect(custom["PTEX.Fullbanner"]).toEqual("This is pdfeTeX, " + "Version 3.141592-1.21a-2.2 (Web2C 7.5.4) kpathsea version 3.5.6");
  828. expect(info.PDFFormatVersion).toEqual("1.4");
  829. expect(info.IsLinearized).toEqual(false);
  830. expect(info.IsAcroFormPresent).toEqual(false);
  831. expect(info.IsXFAPresent).toEqual(false);
  832. expect(info.IsCollectionPresent).toEqual(false);
  833. expect(info.IsSignaturesPresent).toEqual(false);
  834. expect(metadata).toEqual(null);
  835. expect(contentDispositionFilename).toEqual(null);
  836. expect(contentLength).toEqual(1016315);
  837. await loadingTask.destroy();
  838. });
  839. it("gets metadata, with missing PDF header (bug 1606566)", async function () {
  840. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("bug1606566.pdf"));
  841. const pdfDoc = await loadingTask.promise;
  842. const {
  843. info,
  844. metadata,
  845. contentDispositionFilename,
  846. contentLength
  847. } = await pdfDoc.getMetadata();
  848. expect(info.PDFFormatVersion).toEqual(null);
  849. expect(info.IsLinearized).toEqual(false);
  850. expect(info.IsAcroFormPresent).toEqual(false);
  851. expect(info.IsXFAPresent).toEqual(false);
  852. expect(info.IsCollectionPresent).toEqual(false);
  853. expect(info.IsSignaturesPresent).toEqual(false);
  854. expect(metadata).toEqual(null);
  855. expect(contentDispositionFilename).toEqual(null);
  856. expect(contentLength).toEqual(624);
  857. await loadingTask.destroy();
  858. });
  859. it("gets markInfo", async function () {
  860. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("annotation-line.pdf"));
  861. const pdfDoc = await loadingTask.promise;
  862. const markInfo = await pdfDoc.getMarkInfo();
  863. expect(markInfo.Marked).toEqual(true);
  864. expect(markInfo.UserProperties).toEqual(false);
  865. expect(markInfo.Suspects).toEqual(false);
  866. });
  867. it("gets data", async function () {
  868. const data = await pdfDocument.getData();
  869. expect(data instanceof Uint8Array).toEqual(true);
  870. expect(data.length).toEqual(basicApiFileLength);
  871. });
  872. it("gets download info", async function () {
  873. const downloadInfo = await pdfDocument.getDownloadInfo();
  874. expect(downloadInfo).toEqual({
  875. length: basicApiFileLength
  876. });
  877. });
  878. it("gets document stats", async function () {
  879. const stats = await pdfDocument.getStats();
  880. expect(stats).toEqual({
  881. streamTypes: {},
  882. fontTypes: {}
  883. });
  884. });
  885. it("cleans up document resources", async function () {
  886. await pdfDocument.cleanup();
  887. expect(true).toEqual(true);
  888. });
  889. it("checks that fingerprints are unique", async function () {
  890. const loadingTask1 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("issue4436r.pdf"));
  891. const loadingTask2 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("issue4575.pdf"));
  892. const data = await Promise.all([loadingTask1.promise, loadingTask2.promise]);
  893. const fingerprints1 = data[0].fingerprints;
  894. const fingerprints2 = data[1].fingerprints;
  895. expect(fingerprints1).not.toEqual(fingerprints2);
  896. expect(fingerprints1).toEqual(["2f695a83d6e7553c24fc08b7ac69712d", null]);
  897. expect(fingerprints2).toEqual(["04c7126b34a46b6d4d6e7a1eff7edcb6", null]);
  898. await Promise.all([loadingTask1.destroy(), loadingTask2.destroy()]);
  899. });
  900. it("write a value in an annotation, save the pdf and load it", async function () {
  901. let loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("evaljs.pdf"));
  902. let pdfDoc = await loadingTask.promise;
  903. const value = "Hello World";
  904. pdfDoc.annotationStorage.setValue("55R", {
  905. value
  906. });
  907. const data = await pdfDoc.saveDocument();
  908. await loadingTask.destroy();
  909. loadingTask = (0, _api.getDocument)(data);
  910. pdfDoc = await loadingTask.promise;
  911. const pdfPage = await pdfDoc.getPage(1);
  912. const annotations = await pdfPage.getAnnotations();
  913. const field = annotations.find(annotation => annotation.id === "55R");
  914. expect(!!field).toEqual(true);
  915. expect(field.fieldValue).toEqual(value);
  916. await loadingTask.destroy();
  917. });
  918. describe("Cross-origin", function () {
  919. let loadingTask;
  920. function _checkCanLoad(expectSuccess, filename, options) {
  921. if (_is_node.isNodeJS) {
  922. pending("Cannot simulate cross-origin requests in Node.js");
  923. }
  924. const params = (0, _test_utils.buildGetDocumentParams)(filename, options);
  925. const url = new URL(params.url);
  926. if (url.hostname === "localhost") {
  927. url.hostname = "127.0.0.1";
  928. } else if (params.url.hostname === "127.0.0.1") {
  929. url.hostname = "localhost";
  930. } else {
  931. pending("Can only run cross-origin test on localhost!");
  932. }
  933. params.url = url.href;
  934. loadingTask = (0, _api.getDocument)(params);
  935. return loadingTask.promise.then(function (pdf) {
  936. return pdf.destroy();
  937. }).then(function () {
  938. expect(expectSuccess).toEqual(true);
  939. }, function (error) {
  940. if (expectSuccess) {
  941. expect(error).toEqual("There should not be any error");
  942. }
  943. expect(expectSuccess).toEqual(false);
  944. });
  945. }
  946. function testCanLoad(filename, options) {
  947. return _checkCanLoad(true, filename, options);
  948. }
  949. function testCannotLoad(filename, options) {
  950. return _checkCanLoad(false, filename, options);
  951. }
  952. afterEach(async function () {
  953. if (loadingTask && !loadingTask.destroyed) {
  954. await loadingTask.destroy();
  955. }
  956. });
  957. it("server disallows cors", async function () {
  958. await testCannotLoad("basicapi.pdf");
  959. });
  960. it("server allows cors without credentials, default withCredentials", async function () {
  961. await testCanLoad("basicapi.pdf?cors=withoutCredentials");
  962. });
  963. it("server allows cors without credentials, and withCredentials=false", async function () {
  964. await testCanLoad("basicapi.pdf?cors=withoutCredentials", {
  965. withCredentials: false
  966. });
  967. });
  968. it("server allows cors without credentials, but withCredentials=true", async function () {
  969. await testCannotLoad("basicapi.pdf?cors=withoutCredentials", {
  970. withCredentials: true
  971. });
  972. });
  973. it("server allows cors with credentials, and withCredentials=true", async function () {
  974. await testCanLoad("basicapi.pdf?cors=withCredentials", {
  975. withCredentials: true
  976. });
  977. });
  978. it("server allows cors with credentials, and withCredentials=false", async function () {
  979. await testCanLoad("basicapi.pdf?cors=withCredentials", {
  980. withCredentials: false
  981. });
  982. });
  983. });
  984. });
  985. describe("Page", function () {
  986. let pdfLoadingTask, pdfDocument, page;
  987. beforeAll(async function () {
  988. pdfLoadingTask = (0, _api.getDocument)(basicApiGetDocumentParams);
  989. pdfDocument = await pdfLoadingTask.promise;
  990. page = await pdfDocument.getPage(1);
  991. });
  992. afterAll(async function () {
  993. await pdfLoadingTask.destroy();
  994. });
  995. it("gets page number", function () {
  996. expect(page.pageNumber).toEqual(1);
  997. });
  998. it("gets rotate", function () {
  999. expect(page.rotate).toEqual(0);
  1000. });
  1001. it("gets ref", function () {
  1002. expect(page.ref).toEqual({
  1003. num: 15,
  1004. gen: 0
  1005. });
  1006. });
  1007. it("gets userUnit", function () {
  1008. expect(page.userUnit).toEqual(1.0);
  1009. });
  1010. it("gets view", function () {
  1011. expect(page.view).toEqual([0, 0, 595.28, 841.89]);
  1012. });
  1013. it("gets view, with empty/invalid bounding boxes", async function () {
  1014. const viewLoadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("boundingBox_invalid.pdf"));
  1015. const pdfDoc = await viewLoadingTask.promise;
  1016. const numPages = pdfDoc.numPages;
  1017. expect(numPages).toEqual(3);
  1018. const viewPromises = [];
  1019. for (let i = 0; i < numPages; i++) {
  1020. viewPromises[i] = pdfDoc.getPage(i + 1).then(pdfPage => {
  1021. return pdfPage.view;
  1022. });
  1023. }
  1024. const [page1, page2, page3] = await Promise.all(viewPromises);
  1025. expect(page1).toEqual([0, 0, 612, 792]);
  1026. expect(page2).toEqual([0, 0, 800, 600]);
  1027. expect(page3).toEqual([0, 0, 600, 800]);
  1028. await viewLoadingTask.destroy();
  1029. });
  1030. it("gets viewport", function () {
  1031. const viewport = page.getViewport({
  1032. scale: 1.5,
  1033. rotation: 90
  1034. });
  1035. expect(viewport.viewBox).toEqual(page.view);
  1036. expect(viewport.scale).toEqual(1.5);
  1037. expect(viewport.rotation).toEqual(90);
  1038. expect(viewport.transform).toEqual([0, 1.5, 1.5, 0, 0, 0]);
  1039. expect(viewport.width).toEqual(1262.835);
  1040. expect(viewport.height).toEqual(892.92);
  1041. });
  1042. it('gets viewport with "offsetX/offsetY" arguments', function () {
  1043. const viewport = page.getViewport({
  1044. scale: 1,
  1045. rotation: 0,
  1046. offsetX: 100,
  1047. offsetY: -100
  1048. });
  1049. expect(viewport.transform).toEqual([1, 0, 0, -1, 100, 741.89]);
  1050. });
  1051. it('gets viewport respecting "dontFlip" argument', function () {
  1052. const scale = 1,
  1053. rotation = 0;
  1054. const viewport = page.getViewport({
  1055. scale,
  1056. rotation
  1057. });
  1058. const dontFlipViewport = page.getViewport({
  1059. scale,
  1060. rotation,
  1061. dontFlip: true
  1062. });
  1063. expect(dontFlipViewport).not.toEqual(viewport);
  1064. expect(dontFlipViewport).toEqual(viewport.clone({
  1065. dontFlip: true
  1066. }));
  1067. expect(viewport.transform).toEqual([1, 0, 0, -1, 0, 841.89]);
  1068. expect(dontFlipViewport.transform).toEqual([1, 0, -0, 1, 0, 0]);
  1069. });
  1070. it("gets viewport with invalid rotation", function () {
  1071. expect(function () {
  1072. page.getViewport({
  1073. scale: 1,
  1074. rotation: 45
  1075. });
  1076. }).toThrow(new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees."));
  1077. });
  1078. it("gets annotations", async function () {
  1079. const defaultPromise = page.getAnnotations().then(function (data) {
  1080. expect(data.length).toEqual(4);
  1081. });
  1082. const anyPromise = page.getAnnotations({
  1083. intent: "any"
  1084. }).then(function (data) {
  1085. expect(data.length).toEqual(4);
  1086. });
  1087. const displayPromise = page.getAnnotations({
  1088. intent: "display"
  1089. }).then(function (data) {
  1090. expect(data.length).toEqual(4);
  1091. });
  1092. const printPromise = page.getAnnotations({
  1093. intent: "print"
  1094. }).then(function (data) {
  1095. expect(data.length).toEqual(4);
  1096. });
  1097. await Promise.all([defaultPromise, anyPromise, displayPromise, printPromise]);
  1098. });
  1099. it("gets annotations containing relative URLs (bug 766086)", async function () {
  1100. const filename = "bug766086.pdf";
  1101. const defaultLoadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(filename));
  1102. const defaultPromise = defaultLoadingTask.promise.then(function (pdfDoc) {
  1103. return pdfDoc.getPage(1).then(function (pdfPage) {
  1104. return pdfPage.getAnnotations();
  1105. });
  1106. });
  1107. const docBaseUrlLoadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(filename, {
  1108. docBaseUrl: "http://www.example.com/test/pdfs/qwerty.pdf"
  1109. }));
  1110. const docBaseUrlPromise = docBaseUrlLoadingTask.promise.then(function (pdfDoc) {
  1111. return pdfDoc.getPage(1).then(function (pdfPage) {
  1112. return pdfPage.getAnnotations();
  1113. });
  1114. });
  1115. const invalidDocBaseUrlLoadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(filename, {
  1116. docBaseUrl: "qwerty.pdf"
  1117. }));
  1118. const invalidDocBaseUrlPromise = invalidDocBaseUrlLoadingTask.promise.then(function (pdfDoc) {
  1119. return pdfDoc.getPage(1).then(function (pdfPage) {
  1120. return pdfPage.getAnnotations();
  1121. });
  1122. });
  1123. const [defaultAnnotations, docBaseUrlAnnotations, invalidDocBaseUrlAnnotations] = await Promise.all([defaultPromise, docBaseUrlPromise, invalidDocBaseUrlPromise]);
  1124. expect(defaultAnnotations[0].url).toBeUndefined();
  1125. expect(defaultAnnotations[0].unsafeUrl).toEqual("../../0021/002156/215675E.pdf#15");
  1126. expect(docBaseUrlAnnotations[0].url).toEqual("http://www.example.com/0021/002156/215675E.pdf#15");
  1127. expect(docBaseUrlAnnotations[0].unsafeUrl).toEqual("../../0021/002156/215675E.pdf#15");
  1128. expect(invalidDocBaseUrlAnnotations[0].url).toBeUndefined();
  1129. expect(invalidDocBaseUrlAnnotations[0].unsafeUrl).toEqual("../../0021/002156/215675E.pdf#15");
  1130. await Promise.all([defaultLoadingTask.destroy(), docBaseUrlLoadingTask.destroy(), invalidDocBaseUrlLoadingTask.destroy()]);
  1131. });
  1132. it("gets text content", async function () {
  1133. const defaultPromise = page.getTextContent();
  1134. const parametersPromise = page.getTextContent({
  1135. normalizeWhitespace: true,
  1136. disableCombineTextItems: true
  1137. });
  1138. const data = await Promise.all([defaultPromise, parametersPromise]);
  1139. expect(!!data[0].items).toEqual(true);
  1140. expect(data[0].items.length).toEqual(12);
  1141. expect(!!data[0].styles).toEqual(true);
  1142. expect(!!data[1].items).toEqual(true);
  1143. expect(data[1].items.length).toEqual(7);
  1144. expect(!!data[1].styles).toEqual(true);
  1145. });
  1146. it("gets text content, with correct properties (issue 8276)", async function () {
  1147. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("issue8276_reduced.pdf"));
  1148. const pdfDoc = await loadingTask.promise;
  1149. const pdfPage = await pdfDoc.getPage(1);
  1150. const {
  1151. items,
  1152. styles
  1153. } = await pdfPage.getTextContent();
  1154. expect(items.length).toEqual(1);
  1155. const fontName = items[0].fontName;
  1156. expect(Object.keys(styles)).toEqual([fontName]);
  1157. expect(items[0]).toEqual({
  1158. dir: "ltr",
  1159. fontName,
  1160. height: 18,
  1161. str: "Issue 8276",
  1162. transform: [18, 0, 0, 18, 441.81, 708.4499999999999],
  1163. width: 77.49,
  1164. hasEOL: false
  1165. });
  1166. expect(styles[fontName]).toEqual({
  1167. fontFamily: "serif",
  1168. ascent: NaN,
  1169. descent: NaN,
  1170. vertical: false
  1171. });
  1172. await loadingTask.destroy();
  1173. });
  1174. it("gets empty structure tree", async function () {
  1175. const tree = await page.getStructTree();
  1176. expect(tree).toEqual(null);
  1177. });
  1178. it("gets simple structure tree", async function () {
  1179. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("structure_simple.pdf"));
  1180. const pdfDoc = await loadingTask.promise;
  1181. const pdfPage = await pdfDoc.getPage(1);
  1182. const tree = await pdfPage.getStructTree();
  1183. expect(tree).toEqual({
  1184. role: "Root",
  1185. children: [{
  1186. role: "Document",
  1187. children: [{
  1188. role: "H1",
  1189. children: [{
  1190. role: "NonStruct",
  1191. children: [{
  1192. type: "content",
  1193. id: "page2R_mcid0"
  1194. }]
  1195. }]
  1196. }, {
  1197. role: "P",
  1198. children: [{
  1199. role: "NonStruct",
  1200. children: [{
  1201. type: "content",
  1202. id: "page2R_mcid1"
  1203. }]
  1204. }]
  1205. }, {
  1206. role: "H2",
  1207. children: [{
  1208. role: "NonStruct",
  1209. children: [{
  1210. type: "content",
  1211. id: "page2R_mcid2"
  1212. }]
  1213. }]
  1214. }, {
  1215. role: "P",
  1216. children: [{
  1217. role: "NonStruct",
  1218. children: [{
  1219. type: "content",
  1220. id: "page2R_mcid3"
  1221. }]
  1222. }]
  1223. }]
  1224. }]
  1225. });
  1226. await loadingTask.destroy();
  1227. });
  1228. it("gets operator list", async function () {
  1229. const operatorList = await page.getOperatorList();
  1230. expect(operatorList.fnArray.length).toBeGreaterThan(100);
  1231. expect(operatorList.argsArray.length).toBeGreaterThan(100);
  1232. expect(operatorList.lastChunk).toEqual(true);
  1233. });
  1234. it("gets operatorList with JPEG image (issue 4888)", async function () {
  1235. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("cmykjpeg.pdf"));
  1236. const pdfDoc = await loadingTask.promise;
  1237. const pdfPage = await pdfDoc.getPage(1);
  1238. const operatorList = await pdfPage.getOperatorList();
  1239. const imgIndex = operatorList.fnArray.indexOf(_util.OPS.paintImageXObject);
  1240. const imgArgs = operatorList.argsArray[imgIndex];
  1241. const {
  1242. data
  1243. } = pdfPage.objs.get(imgArgs[0]);
  1244. expect(data instanceof Uint8ClampedArray).toEqual(true);
  1245. expect(data.length).toEqual(90000);
  1246. await loadingTask.destroy();
  1247. });
  1248. it("gets operatorList, from corrupt PDF file (issue 8702), " + "with/without `stopAtErrors` set", async function () {
  1249. const loadingTask1 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("issue8702.pdf", {
  1250. stopAtErrors: false
  1251. }));
  1252. const loadingTask2 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("issue8702.pdf", {
  1253. stopAtErrors: true
  1254. }));
  1255. const result1 = loadingTask1.promise.then(pdfDoc => {
  1256. return pdfDoc.getPage(1).then(pdfPage => {
  1257. return pdfPage.getOperatorList().then(opList => {
  1258. expect(opList.fnArray.length).toBeGreaterThan(100);
  1259. expect(opList.argsArray.length).toBeGreaterThan(100);
  1260. expect(opList.lastChunk).toEqual(true);
  1261. return loadingTask1.destroy();
  1262. });
  1263. });
  1264. });
  1265. const result2 = loadingTask2.promise.then(pdfDoc => {
  1266. return pdfDoc.getPage(1).then(pdfPage => {
  1267. return pdfPage.getOperatorList().then(opList => {
  1268. expect(opList.fnArray.length).toEqual(0);
  1269. expect(opList.argsArray.length).toEqual(0);
  1270. expect(opList.lastChunk).toEqual(true);
  1271. return loadingTask2.destroy();
  1272. });
  1273. });
  1274. });
  1275. await Promise.all([result1, result2]);
  1276. });
  1277. it("gets operator list, containing Annotation-operatorLists", async function () {
  1278. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("annotation-line.pdf"));
  1279. const pdfDoc = await loadingTask.promise;
  1280. const pdfPage = await pdfDoc.getPage(1);
  1281. const operatorList = await pdfPage.getOperatorList();
  1282. expect(operatorList.fnArray.length).toBeGreaterThan(20);
  1283. expect(operatorList.argsArray.length).toBeGreaterThan(20);
  1284. expect(operatorList.lastChunk).toEqual(true);
  1285. expect(operatorList.fnArray.includes(_util.OPS.beginAnnotation)).toEqual(true);
  1286. expect(operatorList.fnArray.includes(_util.OPS.endAnnotation)).toEqual(true);
  1287. await loadingTask.destroy();
  1288. });
  1289. it("gets operator list, with `annotationMode`-option", async function () {
  1290. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("evaljs.pdf"));
  1291. const pdfDoc = await loadingTask.promise;
  1292. const pdfPage = await pdfDoc.getPage(2);
  1293. pdfDoc.annotationStorage.setValue("30R", {
  1294. value: "test"
  1295. });
  1296. pdfDoc.annotationStorage.setValue("31R", {
  1297. value: true
  1298. });
  1299. const opListAnnotDisable = await pdfPage.getOperatorList({
  1300. annotationMode: _util.AnnotationMode.DISABLE
  1301. });
  1302. expect(opListAnnotDisable.fnArray.length).toEqual(0);
  1303. expect(opListAnnotDisable.argsArray.length).toEqual(0);
  1304. expect(opListAnnotDisable.lastChunk).toEqual(true);
  1305. const opListAnnotEnable = await pdfPage.getOperatorList({
  1306. annotationMode: _util.AnnotationMode.ENABLE
  1307. });
  1308. expect(opListAnnotEnable.fnArray.length).toBeGreaterThan(150);
  1309. expect(opListAnnotEnable.argsArray.length).toBeGreaterThan(150);
  1310. expect(opListAnnotEnable.lastChunk).toEqual(true);
  1311. const opListAnnotEnableForms = await pdfPage.getOperatorList({
  1312. annotationMode: _util.AnnotationMode.ENABLE_FORMS
  1313. });
  1314. expect(opListAnnotEnableForms.fnArray.length).toBeGreaterThan(40);
  1315. expect(opListAnnotEnableForms.argsArray.length).toBeGreaterThan(40);
  1316. expect(opListAnnotEnableForms.lastChunk).toEqual(true);
  1317. const opListAnnotEnableStorage = await pdfPage.getOperatorList({
  1318. annotationMode: _util.AnnotationMode.ENABLE_STORAGE
  1319. });
  1320. expect(opListAnnotEnableStorage.fnArray.length).toBeGreaterThan(170);
  1321. expect(opListAnnotEnableStorage.argsArray.length).toBeGreaterThan(170);
  1322. expect(opListAnnotEnableStorage.lastChunk).toEqual(true);
  1323. expect(opListAnnotDisable.fnArray.length).toBeLessThan(opListAnnotEnableForms.fnArray.length);
  1324. expect(opListAnnotEnableForms.fnArray.length).toBeLessThan(opListAnnotEnable.fnArray.length);
  1325. expect(opListAnnotEnable.fnArray.length).toBeLessThan(opListAnnotEnableStorage.fnArray.length);
  1326. await loadingTask.destroy();
  1327. });
  1328. it("gets document stats after parsing page", async function () {
  1329. const stats = await page.getOperatorList().then(function () {
  1330. return pdfDocument.getStats();
  1331. });
  1332. const expectedStreamTypes = {};
  1333. expectedStreamTypes[_util.StreamType.FLATE] = true;
  1334. const expectedFontTypes = {};
  1335. expectedFontTypes[_util.FontType.TYPE1STANDARD] = true;
  1336. expectedFontTypes[_util.FontType.CIDFONTTYPE2] = true;
  1337. expect(stats).toEqual({
  1338. streamTypes: expectedStreamTypes,
  1339. fontTypes: expectedFontTypes
  1340. });
  1341. });
  1342. it("gets page stats after parsing page, without `pdfBug` set", async function () {
  1343. await page.getOperatorList();
  1344. expect(page.stats).toEqual(null);
  1345. });
  1346. it("gets page stats after parsing page, with `pdfBug` set", async function () {
  1347. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(basicApiFileName, {
  1348. pdfBug: true
  1349. }));
  1350. const pdfDoc = await loadingTask.promise;
  1351. const pdfPage = await pdfDoc.getPage(1);
  1352. await pdfPage.getOperatorList();
  1353. const stats = pdfPage.stats;
  1354. expect(stats instanceof _display_utils.StatTimer).toEqual(true);
  1355. expect(stats.times.length).toEqual(1);
  1356. const [statEntry] = stats.times;
  1357. expect(statEntry.name).toEqual("Page Request");
  1358. expect(statEntry.end - statEntry.start).toBeGreaterThanOrEqual(0);
  1359. await loadingTask.destroy();
  1360. });
  1361. it("gets page stats after rendering page, with `pdfBug` set", async function () {
  1362. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(basicApiFileName, {
  1363. pdfBug: true
  1364. }));
  1365. const pdfDoc = await loadingTask.promise;
  1366. const pdfPage = await pdfDoc.getPage(1);
  1367. const viewport = pdfPage.getViewport({
  1368. scale: 1
  1369. });
  1370. const canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height);
  1371. const renderTask = pdfPage.render({
  1372. canvasContext: canvasAndCtx.context,
  1373. canvasFactory: CanvasFactory,
  1374. viewport
  1375. });
  1376. expect(renderTask instanceof _api.RenderTask).toEqual(true);
  1377. await renderTask.promise;
  1378. const stats = pdfPage.stats;
  1379. expect(stats instanceof _display_utils.StatTimer).toEqual(true);
  1380. expect(stats.times.length).toEqual(3);
  1381. const [statEntryOne, statEntryTwo, statEntryThree] = stats.times;
  1382. expect(statEntryOne.name).toEqual("Page Request");
  1383. expect(statEntryOne.end - statEntryOne.start).toBeGreaterThanOrEqual(0);
  1384. expect(statEntryTwo.name).toEqual("Rendering");
  1385. expect(statEntryTwo.end - statEntryTwo.start).toBeGreaterThan(0);
  1386. expect(statEntryThree.name).toEqual("Overall");
  1387. expect(statEntryThree.end - statEntryThree.start).toBeGreaterThan(0);
  1388. CanvasFactory.destroy(canvasAndCtx);
  1389. await loadingTask.destroy();
  1390. });
  1391. it("cancels rendering of page", async function () {
  1392. const viewport = page.getViewport({
  1393. scale: 1
  1394. });
  1395. const canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height);
  1396. const renderTask = page.render({
  1397. canvasContext: canvasAndCtx.context,
  1398. canvasFactory: CanvasFactory,
  1399. viewport
  1400. });
  1401. expect(renderTask instanceof _api.RenderTask).toEqual(true);
  1402. renderTask.cancel();
  1403. try {
  1404. await renderTask.promise;
  1405. expect(false).toEqual(true);
  1406. } catch (reason) {
  1407. expect(reason instanceof _display_utils.RenderingCancelledException).toEqual(true);
  1408. expect(reason.message).toEqual("Rendering cancelled, page 1");
  1409. expect(reason.type).toEqual("canvas");
  1410. }
  1411. CanvasFactory.destroy(canvasAndCtx);
  1412. });
  1413. it("re-render page, using the same canvas, after cancelling rendering", async function () {
  1414. const viewport = page.getViewport({
  1415. scale: 1
  1416. });
  1417. const canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height);
  1418. const renderTask = page.render({
  1419. canvasContext: canvasAndCtx.context,
  1420. canvasFactory: CanvasFactory,
  1421. viewport
  1422. });
  1423. expect(renderTask instanceof _api.RenderTask).toEqual(true);
  1424. renderTask.cancel();
  1425. try {
  1426. await renderTask.promise;
  1427. expect(false).toEqual(true);
  1428. } catch (reason) {
  1429. expect(reason instanceof _display_utils.RenderingCancelledException).toEqual(true);
  1430. }
  1431. const reRenderTask = page.render({
  1432. canvasContext: canvasAndCtx.context,
  1433. canvasFactory: CanvasFactory,
  1434. viewport
  1435. });
  1436. expect(reRenderTask instanceof _api.RenderTask).toEqual(true);
  1437. await reRenderTask.promise;
  1438. CanvasFactory.destroy(canvasAndCtx);
  1439. });
  1440. it("multiple render() on the same canvas", async function () {
  1441. const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig();
  1442. const viewport = page.getViewport({
  1443. scale: 1
  1444. });
  1445. const canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height);
  1446. const renderTask1 = page.render({
  1447. canvasContext: canvasAndCtx.context,
  1448. canvasFactory: CanvasFactory,
  1449. viewport,
  1450. optionalContentConfigPromise
  1451. });
  1452. expect(renderTask1 instanceof _api.RenderTask).toEqual(true);
  1453. const renderTask2 = page.render({
  1454. canvasContext: canvasAndCtx.context,
  1455. canvasFactory: CanvasFactory,
  1456. viewport,
  1457. optionalContentConfigPromise
  1458. });
  1459. expect(renderTask2 instanceof _api.RenderTask).toEqual(true);
  1460. await Promise.all([renderTask1.promise, renderTask2.promise.then(() => {
  1461. expect(false).toEqual(true);
  1462. }, reason => {
  1463. expect(/multiple render\(\)/.test(reason.message)).toEqual(true);
  1464. })]);
  1465. });
  1466. it("cleans up document resources after rendering of page", async function () {
  1467. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)(basicApiFileName));
  1468. const pdfDoc = await loadingTask.promise;
  1469. const pdfPage = await pdfDoc.getPage(1);
  1470. const viewport = pdfPage.getViewport({
  1471. scale: 1
  1472. });
  1473. const canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height);
  1474. const renderTask = pdfPage.render({
  1475. canvasContext: canvasAndCtx.context,
  1476. canvasFactory: CanvasFactory,
  1477. viewport
  1478. });
  1479. expect(renderTask instanceof _api.RenderTask).toEqual(true);
  1480. await renderTask.promise;
  1481. await pdfDoc.cleanup();
  1482. expect(true).toEqual(true);
  1483. CanvasFactory.destroy(canvasAndCtx);
  1484. await loadingTask.destroy();
  1485. });
  1486. it("cleans up document resources during rendering of page", async function () {
  1487. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("tracemonkey.pdf"));
  1488. const pdfDoc = await loadingTask.promise;
  1489. const pdfPage = await pdfDoc.getPage(1);
  1490. const viewport = pdfPage.getViewport({
  1491. scale: 1
  1492. });
  1493. const canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height);
  1494. const renderTask = pdfPage.render({
  1495. canvasContext: canvasAndCtx.context,
  1496. canvasFactory: CanvasFactory,
  1497. viewport
  1498. });
  1499. expect(renderTask instanceof _api.RenderTask).toEqual(true);
  1500. renderTask.onContinue = function (cont) {
  1501. waitSome(cont);
  1502. };
  1503. try {
  1504. await pdfDoc.cleanup();
  1505. expect(false).toEqual(true);
  1506. } catch (reason) {
  1507. expect(reason instanceof Error).toEqual(true);
  1508. expect(reason.message).toEqual("startCleanup: Page 1 is currently rendering.");
  1509. }
  1510. await renderTask.promise;
  1511. CanvasFactory.destroy(canvasAndCtx);
  1512. await loadingTask.destroy();
  1513. });
  1514. it("caches image resources at the document/page level as expected (issue 11878)", async function () {
  1515. const {
  1516. NUM_PAGES_THRESHOLD
  1517. } = _image_utils.GlobalImageCache,
  1518. EXPECTED_WIDTH = 2550,
  1519. EXPECTED_HEIGHT = 3300;
  1520. const loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)("issue11878.pdf"));
  1521. const pdfDoc = await loadingTask.promise;
  1522. let firstImgData = null;
  1523. for (let i = 1; i <= pdfDoc.numPages; i++) {
  1524. const pdfPage = await pdfDoc.getPage(i);
  1525. const opList = await pdfPage.getOperatorList();
  1526. const {
  1527. commonObjs,
  1528. objs
  1529. } = pdfPage;
  1530. const imgIndex = opList.fnArray.indexOf(_util.OPS.paintImageXObject);
  1531. const [objId, width, height] = opList.argsArray[imgIndex];
  1532. if (i < NUM_PAGES_THRESHOLD) {
  1533. expect(objId).toEqual(`img_p${i - 1}_1`);
  1534. expect(objs.has(objId)).toEqual(true);
  1535. expect(commonObjs.has(objId)).toEqual(false);
  1536. } else {
  1537. expect(objId).toEqual(`g_${loadingTask.docId}_img_p${NUM_PAGES_THRESHOLD - 1}_1`);
  1538. expect(objs.has(objId)).toEqual(false);
  1539. expect(commonObjs.has(objId)).toEqual(true);
  1540. }
  1541. expect(width).toEqual(EXPECTED_WIDTH);
  1542. expect(height).toEqual(EXPECTED_HEIGHT);
  1543. if (i === 1) {
  1544. firstImgData = objs.get(objId);
  1545. expect(firstImgData.width).toEqual(EXPECTED_WIDTH);
  1546. expect(firstImgData.height).toEqual(EXPECTED_HEIGHT);
  1547. expect(firstImgData.kind).toEqual(_util.ImageKind.RGB_24BPP);
  1548. expect(firstImgData.data instanceof Uint8ClampedArray).toEqual(true);
  1549. expect(firstImgData.data.length).toEqual(25245000);
  1550. } else {
  1551. const objsPool = i >= NUM_PAGES_THRESHOLD ? commonObjs : objs;
  1552. const currentImgData = objsPool.get(objId);
  1553. expect(currentImgData.width).toEqual(firstImgData.width);
  1554. expect(currentImgData.height).toEqual(firstImgData.height);
  1555. expect(currentImgData.kind).toEqual(firstImgData.kind);
  1556. expect(currentImgData.data instanceof Uint8ClampedArray).toEqual(true);
  1557. expect(currentImgData.data.every((value, index) => {
  1558. return value === firstImgData.data[index];
  1559. })).toEqual(true);
  1560. }
  1561. }
  1562. await loadingTask.destroy();
  1563. firstImgData = null;
  1564. });
  1565. });
  1566. describe("Multiple `getDocument` instances", function () {
  1567. const pdf1 = (0, _test_utils.buildGetDocumentParams)("tracemonkey.pdf");
  1568. const pdf2 = (0, _test_utils.buildGetDocumentParams)("TAMReview.pdf");
  1569. const pdf3 = (0, _test_utils.buildGetDocumentParams)("issue6068.pdf");
  1570. const loadingTasks = [];
  1571. async function renderPDF(filename) {
  1572. const loadingTask = (0, _api.getDocument)(filename);
  1573. loadingTasks.push(loadingTask);
  1574. const pdf = await loadingTask.promise;
  1575. const page = await pdf.getPage(1);
  1576. const viewport = page.getViewport({
  1577. scale: 1.2
  1578. });
  1579. const canvasAndCtx = CanvasFactory.create(viewport.width, viewport.height);
  1580. const renderTask = page.render({
  1581. canvasContext: canvasAndCtx.context,
  1582. canvasFactory: CanvasFactory,
  1583. viewport
  1584. });
  1585. await renderTask.promise;
  1586. const data = canvasAndCtx.canvas.toDataURL();
  1587. CanvasFactory.destroy(canvasAndCtx);
  1588. return data;
  1589. }
  1590. afterEach(async function () {
  1591. const destroyPromises = loadingTasks.map(function (loadingTask) {
  1592. return loadingTask.destroy();
  1593. });
  1594. await Promise.all(destroyPromises);
  1595. });
  1596. it("should correctly render PDFs in parallel", async function () {
  1597. let baseline1, baseline2, baseline3;
  1598. const promiseDone = renderPDF(pdf1).then(function (data1) {
  1599. baseline1 = data1;
  1600. return renderPDF(pdf2);
  1601. }).then(function (data2) {
  1602. baseline2 = data2;
  1603. return renderPDF(pdf3);
  1604. }).then(function (data3) {
  1605. baseline3 = data3;
  1606. return Promise.all([renderPDF(pdf1), renderPDF(pdf2), renderPDF(pdf3)]);
  1607. }).then(function (dataUrls) {
  1608. expect(dataUrls[0]).toEqual(baseline1);
  1609. expect(dataUrls[1]).toEqual(baseline2);
  1610. expect(dataUrls[2]).toEqual(baseline3);
  1611. return true;
  1612. });
  1613. await promiseDone;
  1614. });
  1615. });
  1616. describe("PDFDataRangeTransport", function () {
  1617. let dataPromise;
  1618. beforeAll(function () {
  1619. const fileName = "tracemonkey.pdf";
  1620. dataPromise = _test_utils.DefaultFileReaderFactory.fetch({
  1621. path: _test_utils.TEST_PDFS_PATH + fileName
  1622. });
  1623. });
  1624. afterAll(function () {
  1625. dataPromise = null;
  1626. });
  1627. it("should fetch document info and page using ranges", async function () {
  1628. const initialDataLength = 4000;
  1629. let fetches = 0;
  1630. const data = await dataPromise;
  1631. const initialData = data.subarray(0, initialDataLength);
  1632. const transport = new _api.PDFDataRangeTransport(data.length, initialData);
  1633. transport.requestDataRange = function (begin, end) {
  1634. fetches++;
  1635. waitSome(function () {
  1636. transport.onDataProgress(4000);
  1637. transport.onDataRange(begin, data.subarray(begin, end));
  1638. });
  1639. };
  1640. const loadingTask = (0, _api.getDocument)(transport);
  1641. const pdfDocument = await loadingTask.promise;
  1642. expect(pdfDocument.numPages).toEqual(14);
  1643. const pdfPage = await pdfDocument.getPage(10);
  1644. expect(pdfPage.rotate).toEqual(0);
  1645. expect(fetches).toBeGreaterThan(2);
  1646. await loadingTask.destroy();
  1647. });
  1648. it("should fetch document info and page using range and streaming", async function () {
  1649. const initialDataLength = 4000;
  1650. let fetches = 0;
  1651. const data = await dataPromise;
  1652. const initialData = data.subarray(0, initialDataLength);
  1653. const transport = new _api.PDFDataRangeTransport(data.length, initialData);
  1654. transport.requestDataRange = function (begin, end) {
  1655. fetches++;
  1656. if (fetches === 1) {
  1657. transport.onDataProgressiveRead(data.subarray(initialDataLength));
  1658. }
  1659. waitSome(function () {
  1660. transport.onDataRange(begin, data.subarray(begin, end));
  1661. });
  1662. };
  1663. const loadingTask = (0, _api.getDocument)(transport);
  1664. const pdfDocument = await loadingTask.promise;
  1665. expect(pdfDocument.numPages).toEqual(14);
  1666. const pdfPage = await pdfDocument.getPage(10);
  1667. expect(pdfPage.rotate).toEqual(0);
  1668. expect(fetches).toEqual(1);
  1669. await new Promise(resolve => {
  1670. waitSome(resolve);
  1671. });
  1672. await loadingTask.destroy();
  1673. });
  1674. it("should fetch document info and page, without range, " + "using complete initialData", async function () {
  1675. let fetches = 0;
  1676. const data = await dataPromise;
  1677. const transport = new _api.PDFDataRangeTransport(data.length, data, true);
  1678. transport.requestDataRange = function (begin, end) {
  1679. fetches++;
  1680. };
  1681. const loadingTask = (0, _api.getDocument)({
  1682. disableRange: true,
  1683. range: transport
  1684. });
  1685. const pdfDocument = await loadingTask.promise;
  1686. expect(pdfDocument.numPages).toEqual(14);
  1687. const pdfPage = await pdfDocument.getPage(10);
  1688. expect(pdfPage.rotate).toEqual(0);
  1689. expect(fetches).toEqual(0);
  1690. await loadingTask.destroy();
  1691. });
  1692. });
  1693. });