api_spec.js 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380
  1. /* Copyright 2017 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. import {
  16. AnnotationMode,
  17. AnnotationType,
  18. createPromiseCapability,
  19. FontType,
  20. ImageKind,
  21. InvalidPDFException,
  22. MissingPDFException,
  23. OPS,
  24. PasswordException,
  25. PasswordResponses,
  26. PermissionFlag,
  27. StreamType,
  28. UnknownErrorException,
  29. } from "../../src/shared/util.js";
  30. import {
  31. buildGetDocumentParams,
  32. DefaultFileReaderFactory,
  33. TEST_PDFS_PATH,
  34. } from "./test_utils.js";
  35. import {
  36. DefaultCanvasFactory,
  37. getDocument,
  38. PDFDataRangeTransport,
  39. PDFDocumentLoadingTask,
  40. PDFDocumentProxy,
  41. PDFPageProxy,
  42. PDFWorker,
  43. PDFWorkerUtil,
  44. RenderTask,
  45. } from "../../src/display/api.js";
  46. import {
  47. PageViewport,
  48. RenderingCancelledException,
  49. StatTimer,
  50. } from "../../src/display/display_utils.js";
  51. import { AnnotationStorage } from "../../src/display/annotation_storage.js";
  52. import { AutoPrintRegExp } from "../../web/ui_utils.js";
  53. import { GlobalImageCache } from "../../src/core/image_utils.js";
  54. import { GlobalWorkerOptions } from "../../src/display/worker_options.js";
  55. import { isNodeJS } from "../../src/shared/is_node.js";
  56. import { Metadata } from "../../src/display/metadata.js";
  57. describe("api", function () {
  58. const basicApiFileName = "basicapi.pdf";
  59. const basicApiFileLength = 105779; // bytes
  60. const basicApiGetDocumentParams = buildGetDocumentParams(basicApiFileName);
  61. let CanvasFactory;
  62. beforeAll(function () {
  63. CanvasFactory = new DefaultCanvasFactory();
  64. });
  65. afterAll(function () {
  66. CanvasFactory = null;
  67. });
  68. function waitSome(callback) {
  69. const WAIT_TIMEOUT = 10;
  70. setTimeout(function () {
  71. callback();
  72. }, WAIT_TIMEOUT);
  73. }
  74. function mergeText(items) {
  75. return items
  76. .map(chunk => (chunk.str ?? "") + (chunk.hasEOL ? "\n" : ""))
  77. .join("");
  78. }
  79. describe("getDocument", function () {
  80. it("creates pdf doc from URL-string", async function () {
  81. const urlStr = TEST_PDFS_PATH + basicApiFileName;
  82. const loadingTask = getDocument(urlStr);
  83. expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
  84. const pdfDocument = await loadingTask.promise;
  85. expect(typeof urlStr).toEqual("string");
  86. expect(pdfDocument instanceof PDFDocumentProxy).toEqual(true);
  87. expect(pdfDocument.numPages).toEqual(3);
  88. await loadingTask.destroy();
  89. });
  90. it("creates pdf doc from URL-object", async function () {
  91. if (isNodeJS) {
  92. pending("window.location is not supported in Node.js.");
  93. }
  94. const urlObj = new URL(
  95. TEST_PDFS_PATH + basicApiFileName,
  96. window.location
  97. );
  98. const loadingTask = getDocument(urlObj);
  99. expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
  100. const pdfDocument = await loadingTask.promise;
  101. expect(urlObj instanceof URL).toEqual(true);
  102. expect(pdfDocument instanceof PDFDocumentProxy).toEqual(true);
  103. expect(pdfDocument.numPages).toEqual(3);
  104. await loadingTask.destroy();
  105. });
  106. it("creates pdf doc from URL", async function () {
  107. const loadingTask = getDocument(basicApiGetDocumentParams);
  108. expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
  109. const progressReportedCapability = createPromiseCapability();
  110. // Attach the callback that is used to report loading progress;
  111. // similarly to how viewer.js works.
  112. loadingTask.onProgress = function (progressData) {
  113. if (!progressReportedCapability.settled) {
  114. progressReportedCapability.resolve(progressData);
  115. }
  116. };
  117. const data = await Promise.all([
  118. progressReportedCapability.promise,
  119. loadingTask.promise,
  120. ]);
  121. expect(data[0].loaded / data[0].total >= 0).toEqual(true);
  122. expect(data[1] instanceof PDFDocumentProxy).toEqual(true);
  123. expect(loadingTask).toEqual(data[1].loadingTask);
  124. await loadingTask.destroy();
  125. });
  126. it("creates pdf doc from URL and aborts before worker initialized", async function () {
  127. const loadingTask = getDocument(basicApiGetDocumentParams);
  128. expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
  129. const destroyed = loadingTask.destroy();
  130. try {
  131. await loadingTask.promise;
  132. // Shouldn't get here.
  133. expect(false).toEqual(true);
  134. } catch (reason) {
  135. expect(true).toEqual(true);
  136. await destroyed;
  137. }
  138. });
  139. it("creates pdf doc from URL and aborts loading after worker initialized", async function () {
  140. const loadingTask = getDocument(basicApiGetDocumentParams);
  141. expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
  142. // This can be somewhat random -- we cannot guarantee perfect
  143. // 'Terminate' message to the worker before/after setting up pdfManager.
  144. const destroyed = loadingTask._worker.promise.then(function () {
  145. return loadingTask.destroy();
  146. });
  147. await destroyed;
  148. expect(true).toEqual(true);
  149. });
  150. it("creates pdf doc from TypedArray", async function () {
  151. const typedArrayPdf = await DefaultFileReaderFactory.fetch({
  152. path: TEST_PDFS_PATH + basicApiFileName,
  153. });
  154. // Sanity check to make sure that we fetched the entire PDF file.
  155. expect(typedArrayPdf instanceof Uint8Array).toEqual(true);
  156. expect(typedArrayPdf.length).toEqual(basicApiFileLength);
  157. const loadingTask = getDocument(typedArrayPdf);
  158. expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
  159. const progressReportedCapability = createPromiseCapability();
  160. loadingTask.onProgress = function (data) {
  161. progressReportedCapability.resolve(data);
  162. };
  163. const data = await Promise.all([
  164. loadingTask.promise,
  165. progressReportedCapability.promise,
  166. ]);
  167. expect(data[0] instanceof PDFDocumentProxy).toEqual(true);
  168. expect(data[1].loaded / data[1].total).toEqual(1);
  169. await loadingTask.destroy();
  170. });
  171. it("creates pdf doc from ArrayBuffer", async function () {
  172. const { buffer: arrayBufferPdf } = await DefaultFileReaderFactory.fetch({
  173. path: TEST_PDFS_PATH + basicApiFileName,
  174. });
  175. // Sanity check to make sure that we fetched the entire PDF file.
  176. expect(arrayBufferPdf instanceof ArrayBuffer).toEqual(true);
  177. expect(arrayBufferPdf.byteLength).toEqual(basicApiFileLength);
  178. const loadingTask = getDocument(arrayBufferPdf);
  179. expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
  180. const progressReportedCapability = createPromiseCapability();
  181. loadingTask.onProgress = function (data) {
  182. progressReportedCapability.resolve(data);
  183. };
  184. const data = await Promise.all([
  185. loadingTask.promise,
  186. progressReportedCapability.promise,
  187. ]);
  188. expect(data[0] instanceof PDFDocumentProxy).toEqual(true);
  189. expect(data[1].loaded / data[1].total).toEqual(1);
  190. await loadingTask.destroy();
  191. });
  192. it("creates pdf doc from invalid PDF file", async function () {
  193. // A severely corrupt PDF file (even Adobe Reader fails to open it).
  194. const loadingTask = getDocument(buildGetDocumentParams("bug1020226.pdf"));
  195. expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
  196. try {
  197. await loadingTask.promise;
  198. // Shouldn't get here.
  199. expect(false).toEqual(true);
  200. } catch (reason) {
  201. expect(reason instanceof InvalidPDFException).toEqual(true);
  202. expect(reason.message).toEqual("Invalid PDF structure.");
  203. }
  204. await loadingTask.destroy();
  205. });
  206. it("creates pdf doc from non-existent URL", async function () {
  207. if (!isNodeJS) {
  208. // Re-enable in https://github.com/mozilla/pdf.js/issues/13061.
  209. pending("Fails intermittently on Linux in browsers.");
  210. }
  211. const loadingTask = getDocument(
  212. buildGetDocumentParams("non-existent.pdf")
  213. );
  214. expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
  215. try {
  216. await loadingTask.promise;
  217. // Shouldn't get here.
  218. expect(false).toEqual(true);
  219. } catch (reason) {
  220. expect(reason instanceof MissingPDFException).toEqual(true);
  221. }
  222. await loadingTask.destroy();
  223. });
  224. it("creates pdf doc from PDF file protected with user and owner password", async function () {
  225. const loadingTask = getDocument(buildGetDocumentParams("pr6531_1.pdf"));
  226. expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
  227. const passwordNeededCapability = createPromiseCapability();
  228. const passwordIncorrectCapability = createPromiseCapability();
  229. // Attach the callback that is used to request a password;
  230. // similarly to how the default viewer handles passwords.
  231. loadingTask.onPassword = function (updatePassword, reason) {
  232. if (
  233. reason === PasswordResponses.NEED_PASSWORD &&
  234. !passwordNeededCapability.settled
  235. ) {
  236. passwordNeededCapability.resolve();
  237. updatePassword("qwerty"); // Provide an incorrect password.
  238. return;
  239. }
  240. if (
  241. reason === PasswordResponses.INCORRECT_PASSWORD &&
  242. !passwordIncorrectCapability.settled
  243. ) {
  244. passwordIncorrectCapability.resolve();
  245. updatePassword("asdfasdf"); // Provide the correct password.
  246. return;
  247. }
  248. // Shouldn't get here.
  249. expect(false).toEqual(true);
  250. };
  251. const data = await Promise.all([
  252. passwordNeededCapability.promise,
  253. passwordIncorrectCapability.promise,
  254. loadingTask.promise,
  255. ]);
  256. expect(data[2] instanceof PDFDocumentProxy).toEqual(true);
  257. await loadingTask.destroy();
  258. });
  259. it("creates pdf doc from PDF file protected with only a user password", async function () {
  260. const filename = "pr6531_2.pdf";
  261. const passwordNeededLoadingTask = getDocument(
  262. buildGetDocumentParams(filename, {
  263. password: "",
  264. })
  265. );
  266. expect(
  267. passwordNeededLoadingTask instanceof PDFDocumentLoadingTask
  268. ).toEqual(true);
  269. const result1 = passwordNeededLoadingTask.promise.then(
  270. function () {
  271. // Shouldn't get here.
  272. expect(false).toEqual(true);
  273. return Promise.reject(new Error("loadingTask should be rejected"));
  274. },
  275. function (data) {
  276. expect(data instanceof PasswordException).toEqual(true);
  277. expect(data.code).toEqual(PasswordResponses.NEED_PASSWORD);
  278. return passwordNeededLoadingTask.destroy();
  279. }
  280. );
  281. const passwordIncorrectLoadingTask = getDocument(
  282. buildGetDocumentParams(filename, {
  283. password: "qwerty",
  284. })
  285. );
  286. expect(
  287. passwordIncorrectLoadingTask instanceof PDFDocumentLoadingTask
  288. ).toEqual(true);
  289. const result2 = passwordIncorrectLoadingTask.promise.then(
  290. function () {
  291. // Shouldn't get here.
  292. expect(false).toEqual(true);
  293. return Promise.reject(new Error("loadingTask should be rejected"));
  294. },
  295. function (data) {
  296. expect(data instanceof PasswordException).toEqual(true);
  297. expect(data.code).toEqual(PasswordResponses.INCORRECT_PASSWORD);
  298. return passwordIncorrectLoadingTask.destroy();
  299. }
  300. );
  301. const passwordAcceptedLoadingTask = getDocument(
  302. buildGetDocumentParams(filename, {
  303. password: "asdfasdf",
  304. })
  305. );
  306. expect(
  307. passwordAcceptedLoadingTask instanceof PDFDocumentLoadingTask
  308. ).toEqual(true);
  309. const result3 = passwordAcceptedLoadingTask.promise.then(function (data) {
  310. expect(data instanceof PDFDocumentProxy).toEqual(true);
  311. return passwordAcceptedLoadingTask.destroy();
  312. });
  313. await Promise.all([result1, result2, result3]);
  314. });
  315. it(
  316. "creates pdf doc from password protected PDF file and aborts/throws " +
  317. "in the onPassword callback (issue 7806)",
  318. async function () {
  319. const filename = "issue3371.pdf";
  320. const passwordNeededLoadingTask = getDocument(
  321. buildGetDocumentParams(filename)
  322. );
  323. expect(
  324. passwordNeededLoadingTask instanceof PDFDocumentLoadingTask
  325. ).toEqual(true);
  326. const passwordIncorrectLoadingTask = getDocument(
  327. buildGetDocumentParams(filename, {
  328. password: "qwerty",
  329. })
  330. );
  331. expect(
  332. passwordIncorrectLoadingTask instanceof PDFDocumentLoadingTask
  333. ).toEqual(true);
  334. let passwordNeededDestroyed;
  335. passwordNeededLoadingTask.onPassword = function (callback, reason) {
  336. if (reason === PasswordResponses.NEED_PASSWORD) {
  337. passwordNeededDestroyed = passwordNeededLoadingTask.destroy();
  338. return;
  339. }
  340. // Shouldn't get here.
  341. expect(false).toEqual(true);
  342. };
  343. const result1 = passwordNeededLoadingTask.promise.then(
  344. function () {
  345. // Shouldn't get here.
  346. expect(false).toEqual(true);
  347. return Promise.reject(new Error("loadingTask should be rejected"));
  348. },
  349. function (reason) {
  350. expect(reason instanceof PasswordException).toEqual(true);
  351. expect(reason.code).toEqual(PasswordResponses.NEED_PASSWORD);
  352. return passwordNeededDestroyed;
  353. }
  354. );
  355. passwordIncorrectLoadingTask.onPassword = function (callback, reason) {
  356. if (reason === PasswordResponses.INCORRECT_PASSWORD) {
  357. throw new Error("Incorrect password");
  358. }
  359. // Shouldn't get here.
  360. expect(false).toEqual(true);
  361. };
  362. const result2 = passwordIncorrectLoadingTask.promise.then(
  363. function () {
  364. // Shouldn't get here.
  365. expect(false).toEqual(true);
  366. return Promise.reject(new Error("loadingTask should be rejected"));
  367. },
  368. function (reason) {
  369. expect(reason instanceof PasswordException).toEqual(true);
  370. expect(reason.code).toEqual(PasswordResponses.INCORRECT_PASSWORD);
  371. return passwordIncorrectLoadingTask.destroy();
  372. }
  373. );
  374. await Promise.all([result1, result2]);
  375. }
  376. );
  377. it(
  378. "creates pdf doc from password protected PDF file and passes an Error " +
  379. "(asynchronously) to the onPassword callback (bug 1754421)",
  380. async function () {
  381. const loadingTask = getDocument(
  382. buildGetDocumentParams("issue3371.pdf")
  383. );
  384. expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
  385. // Attach the callback that is used to request a password;
  386. // similarly to how the default viewer handles passwords.
  387. loadingTask.onPassword = function (updatePassword, reason) {
  388. waitSome(() => {
  389. updatePassword(new Error("Should reject the loadingTask."));
  390. });
  391. };
  392. await loadingTask.promise.then(
  393. function () {
  394. // Shouldn't get here.
  395. expect(false).toEqual(true);
  396. },
  397. function (reason) {
  398. expect(reason instanceof PasswordException).toEqual(true);
  399. expect(reason.code).toEqual(PasswordResponses.NEED_PASSWORD);
  400. }
  401. );
  402. await loadingTask.destroy();
  403. }
  404. );
  405. it("creates pdf doc from empty TypedArray", async function () {
  406. const loadingTask = getDocument(new Uint8Array(0));
  407. expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
  408. try {
  409. await loadingTask.promise;
  410. // Shouldn't get here.
  411. expect(false).toEqual(true);
  412. } catch (reason) {
  413. expect(reason instanceof InvalidPDFException).toEqual(true);
  414. expect(reason.message).toEqual(
  415. "The PDF file is empty, i.e. its size is zero bytes."
  416. );
  417. }
  418. await loadingTask.destroy();
  419. });
  420. it("checks that `docId`s are unique and increasing", async function () {
  421. const loadingTask1 = getDocument(basicApiGetDocumentParams);
  422. expect(loadingTask1 instanceof PDFDocumentLoadingTask).toEqual(true);
  423. await loadingTask1.promise;
  424. const docId1 = loadingTask1.docId;
  425. const loadingTask2 = getDocument(basicApiGetDocumentParams);
  426. expect(loadingTask2 instanceof PDFDocumentLoadingTask).toEqual(true);
  427. await loadingTask2.promise;
  428. const docId2 = loadingTask2.docId;
  429. expect(docId1).not.toEqual(docId2);
  430. const docIdRegExp = /^d(\d+)$/,
  431. docNum1 = docIdRegExp.exec(docId1)?.[1],
  432. docNum2 = docIdRegExp.exec(docId2)?.[1];
  433. expect(+docNum1).toBeLessThan(+docNum2);
  434. await Promise.all([loadingTask1.destroy(), loadingTask2.destroy()]);
  435. });
  436. it("creates pdf doc from PDF file with bad XRef entry", async function () {
  437. // A corrupt PDF file, where the XRef table have (some) bogus entries.
  438. const loadingTask = getDocument(
  439. buildGetDocumentParams("PDFBOX-4352-0.pdf", {
  440. rangeChunkSize: 100,
  441. })
  442. );
  443. expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
  444. const pdfDocument = await loadingTask.promise;
  445. expect(pdfDocument.numPages).toEqual(1);
  446. const page = await pdfDocument.getPage(1);
  447. expect(page instanceof PDFPageProxy).toEqual(true);
  448. const opList = await page.getOperatorList();
  449. expect(opList.fnArray.length).toEqual(0);
  450. expect(opList.argsArray.length).toEqual(0);
  451. expect(opList.lastChunk).toEqual(true);
  452. expect(opList.separateAnnots).toEqual(null);
  453. await loadingTask.destroy();
  454. });
  455. it("creates pdf doc from PDF file with bad XRef header", async function () {
  456. const loadingTask = getDocument(
  457. buildGetDocumentParams("GHOSTSCRIPT-698804-1-fuzzed.pdf")
  458. );
  459. expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
  460. const pdfDocument = await loadingTask.promise;
  461. expect(pdfDocument.numPages).toEqual(1);
  462. const page = await pdfDocument.getPage(1);
  463. expect(page instanceof PDFPageProxy).toEqual(true);
  464. const opList = await page.getOperatorList();
  465. expect(opList.fnArray.length).toEqual(0);
  466. expect(opList.argsArray.length).toEqual(0);
  467. expect(opList.lastChunk).toEqual(true);
  468. expect(opList.separateAnnots).toEqual(null);
  469. await loadingTask.destroy();
  470. });
  471. it("creates pdf doc from PDF file with bad XRef byteWidths", async function () {
  472. // A corrupt PDF file, where the XRef /W-array have (some) bogus entries.
  473. const loadingTask = getDocument(
  474. buildGetDocumentParams("REDHAT-1531897-0.pdf")
  475. );
  476. expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
  477. try {
  478. await loadingTask.promise;
  479. // Shouldn't get here.
  480. expect(false).toEqual(true);
  481. } catch (reason) {
  482. expect(reason instanceof InvalidPDFException).toEqual(true);
  483. expect(reason.message).toEqual("Invalid PDF structure.");
  484. }
  485. await loadingTask.destroy();
  486. });
  487. it("creates pdf doc from PDF file with inaccessible /Pages tree", async function () {
  488. const loadingTask = getDocument(
  489. buildGetDocumentParams("poppler-395-0-fuzzed.pdf")
  490. );
  491. expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
  492. try {
  493. await loadingTask.promise;
  494. // Shouldn't get here.
  495. expect(false).toEqual(true);
  496. } catch (reason) {
  497. expect(reason instanceof InvalidPDFException).toEqual(true);
  498. expect(reason.message).toEqual("Invalid Root reference.");
  499. }
  500. await loadingTask.destroy();
  501. });
  502. it("creates pdf doc from PDF files, with bad /Pages tree /Count", async function () {
  503. const loadingTask1 = getDocument(
  504. buildGetDocumentParams("poppler-67295-0.pdf")
  505. );
  506. const loadingTask2 = getDocument(
  507. buildGetDocumentParams("poppler-85140-0.pdf")
  508. );
  509. const loadingTask3 = getDocument(
  510. buildGetDocumentParams("poppler-85140-0.pdf", { stopAtErrors: true })
  511. );
  512. expect(loadingTask1 instanceof PDFDocumentLoadingTask).toEqual(true);
  513. expect(loadingTask2 instanceof PDFDocumentLoadingTask).toEqual(true);
  514. expect(loadingTask3 instanceof PDFDocumentLoadingTask).toEqual(true);
  515. const pdfDocument1 = await loadingTask1.promise;
  516. const pdfDocument2 = await loadingTask2.promise;
  517. const pdfDocument3 = await loadingTask3.promise;
  518. expect(pdfDocument1.numPages).toEqual(1);
  519. expect(pdfDocument2.numPages).toEqual(1);
  520. expect(pdfDocument3.numPages).toEqual(1);
  521. const pageA = await pdfDocument1.getPage(1);
  522. expect(pageA instanceof PDFPageProxy).toEqual(true);
  523. const opListA = await pageA.getOperatorList();
  524. expect(opListA.fnArray.length).toBeGreaterThan(5);
  525. expect(opListA.argsArray.length).toBeGreaterThan(5);
  526. expect(opListA.lastChunk).toEqual(true);
  527. expect(opListA.separateAnnots).toEqual(null);
  528. const pageB = await pdfDocument2.getPage(1);
  529. expect(pageB instanceof PDFPageProxy).toEqual(true);
  530. const opListB = await pageB.getOperatorList();
  531. expect(opListB.fnArray.length).toBe(0);
  532. expect(opListB.argsArray.length).toBe(0);
  533. expect(opListB.lastChunk).toEqual(true);
  534. expect(opListB.separateAnnots).toEqual(null);
  535. try {
  536. await pdfDocument3.getPage(1);
  537. // Shouldn't get here.
  538. expect(false).toEqual(true);
  539. } catch (reason) {
  540. expect(reason instanceof UnknownErrorException).toEqual(true);
  541. expect(reason.message).toEqual("Bad (uncompressed) XRef entry: 3R");
  542. }
  543. await Promise.all([
  544. loadingTask1.destroy(),
  545. loadingTask2.destroy(),
  546. loadingTask3.destroy(),
  547. ]);
  548. });
  549. it("creates pdf doc from PDF files, with circular references", async function () {
  550. const loadingTask1 = getDocument(
  551. buildGetDocumentParams("poppler-91414-0-53.pdf")
  552. );
  553. const loadingTask2 = getDocument(
  554. buildGetDocumentParams("poppler-91414-0-54.pdf")
  555. );
  556. expect(loadingTask1 instanceof PDFDocumentLoadingTask).toEqual(true);
  557. expect(loadingTask2 instanceof PDFDocumentLoadingTask).toEqual(true);
  558. const pdfDocument1 = await loadingTask1.promise;
  559. const pdfDocument2 = await loadingTask2.promise;
  560. expect(pdfDocument1.numPages).toEqual(1);
  561. expect(pdfDocument2.numPages).toEqual(1);
  562. const pageA = await pdfDocument1.getPage(1);
  563. const pageB = await pdfDocument2.getPage(1);
  564. expect(pageA instanceof PDFPageProxy).toEqual(true);
  565. expect(pageB instanceof PDFPageProxy).toEqual(true);
  566. for (const opList of [
  567. await pageA.getOperatorList(),
  568. await pageB.getOperatorList(),
  569. ]) {
  570. expect(opList.fnArray.length).toBeGreaterThan(5);
  571. expect(opList.argsArray.length).toBeGreaterThan(5);
  572. expect(opList.lastChunk).toEqual(true);
  573. expect(opList.separateAnnots).toEqual(null);
  574. }
  575. await Promise.all([loadingTask1.destroy(), loadingTask2.destroy()]);
  576. });
  577. it("creates pdf doc from PDF files, with bad /Pages tree /Kids entries", async function () {
  578. const loadingTask1 = getDocument(
  579. buildGetDocumentParams("poppler-742-0-fuzzed.pdf")
  580. );
  581. const loadingTask2 = getDocument(
  582. buildGetDocumentParams("poppler-937-0-fuzzed.pdf")
  583. );
  584. expect(loadingTask1 instanceof PDFDocumentLoadingTask).toEqual(true);
  585. expect(loadingTask2 instanceof PDFDocumentLoadingTask).toEqual(true);
  586. const pdfDocument1 = await loadingTask1.promise;
  587. const pdfDocument2 = await loadingTask2.promise;
  588. expect(pdfDocument1.numPages).toEqual(1);
  589. expect(pdfDocument2.numPages).toEqual(1);
  590. try {
  591. await pdfDocument1.getPage(1);
  592. // Shouldn't get here.
  593. expect(false).toEqual(true);
  594. } catch (reason) {
  595. expect(reason instanceof UnknownErrorException).toEqual(true);
  596. expect(reason.message).toEqual("Illegal character: 41");
  597. }
  598. try {
  599. await pdfDocument2.getPage(1);
  600. // Shouldn't get here.
  601. expect(false).toEqual(true);
  602. } catch (reason) {
  603. expect(reason instanceof UnknownErrorException).toEqual(true);
  604. expect(reason.message).toEqual("End of file inside array.");
  605. }
  606. await Promise.all([loadingTask1.destroy(), loadingTask2.destroy()]);
  607. });
  608. it("creates pdf doc from PDF file with bad /Resources entry", async function () {
  609. const loadingTask = getDocument(buildGetDocumentParams("issue15150.pdf"));
  610. expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
  611. const pdfDocument = await loadingTask.promise;
  612. expect(pdfDocument.numPages).toEqual(1);
  613. const page = await pdfDocument.getPage(1);
  614. expect(page instanceof PDFPageProxy).toEqual(true);
  615. const opList = await page.getOperatorList();
  616. expect(opList.fnArray).toEqual([
  617. OPS.setLineWidth,
  618. OPS.setStrokeRGBColor,
  619. OPS.constructPath,
  620. OPS.closeStroke,
  621. ]);
  622. expect(opList.argsArray).toEqual([
  623. [0.5],
  624. new Uint8ClampedArray([255, 0, 0]),
  625. [
  626. [OPS.moveTo, OPS.lineTo],
  627. [0, 9.75, 0.5, 9.75],
  628. [0, 0.5, 9.75, 9.75],
  629. ],
  630. null,
  631. ]);
  632. expect(opList.lastChunk).toEqual(true);
  633. await loadingTask.destroy();
  634. });
  635. it("creates pdf doc from PDF file, with incomplete trailer", async function () {
  636. const loadingTask = getDocument(buildGetDocumentParams("issue15590.pdf"));
  637. expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
  638. const pdfDocument = await loadingTask.promise;
  639. expect(pdfDocument.numPages).toEqual(1);
  640. const jsActions = await pdfDocument.getJSActions();
  641. expect(jsActions).toEqual({
  642. OpenAction: ["func=function(){app.alert(1)};func();"],
  643. });
  644. const page = await pdfDocument.getPage(1);
  645. expect(page instanceof PDFPageProxy).toEqual(true);
  646. await loadingTask.destroy();
  647. });
  648. });
  649. describe("PDFWorker", function () {
  650. it("worker created or destroyed", async function () {
  651. if (isNodeJS) {
  652. pending("Worker is not supported in Node.js.");
  653. }
  654. const worker = new PDFWorker({ name: "test1" });
  655. await worker.promise;
  656. expect(worker.name).toEqual("test1");
  657. expect(!!worker.port).toEqual(true);
  658. expect(worker.destroyed).toEqual(false);
  659. expect(!!worker._webWorker).toEqual(true);
  660. expect(worker.port === worker._webWorker).toEqual(true);
  661. worker.destroy();
  662. expect(!!worker.port).toEqual(false);
  663. expect(worker.destroyed).toEqual(true);
  664. });
  665. it("worker created or destroyed by getDocument", async function () {
  666. if (isNodeJS) {
  667. pending("Worker is not supported in Node.js.");
  668. }
  669. const loadingTask = getDocument(basicApiGetDocumentParams);
  670. let worker;
  671. loadingTask.promise.then(function () {
  672. worker = loadingTask._worker;
  673. expect(!!worker).toEqual(true);
  674. });
  675. const destroyPromise = loadingTask.promise.then(function () {
  676. return loadingTask.destroy();
  677. });
  678. await destroyPromise;
  679. const destroyedWorker = loadingTask._worker;
  680. expect(!!destroyedWorker).toEqual(false);
  681. expect(worker.destroyed).toEqual(true);
  682. });
  683. it("worker created and can be used in getDocument", async function () {
  684. if (isNodeJS) {
  685. pending("Worker is not supported in Node.js.");
  686. }
  687. const worker = new PDFWorker({ name: "test1" });
  688. const loadingTask = getDocument(
  689. buildGetDocumentParams(basicApiFileName, {
  690. worker,
  691. })
  692. );
  693. loadingTask.promise.then(function () {
  694. const docWorker = loadingTask._worker;
  695. expect(!!docWorker).toEqual(false);
  696. // checking is the same port is used in the MessageHandler
  697. const messageHandlerPort = loadingTask._transport.messageHandler.comObj;
  698. expect(messageHandlerPort === worker.port).toEqual(true);
  699. });
  700. const destroyPromise = loadingTask.promise.then(function () {
  701. return loadingTask.destroy();
  702. });
  703. await destroyPromise;
  704. expect(worker.destroyed).toEqual(false);
  705. worker.destroy();
  706. });
  707. it("creates more than one worker", async function () {
  708. if (isNodeJS) {
  709. pending("Worker is not supported in Node.js.");
  710. }
  711. const worker1 = new PDFWorker({ name: "test1" });
  712. const worker2 = new PDFWorker({ name: "test2" });
  713. const worker3 = new PDFWorker({ name: "test3" });
  714. await Promise.all([worker1.promise, worker2.promise, worker3.promise]);
  715. expect(
  716. worker1.port !== worker2.port &&
  717. worker1.port !== worker3.port &&
  718. worker2.port !== worker3.port
  719. ).toEqual(true);
  720. worker1.destroy();
  721. worker2.destroy();
  722. worker3.destroy();
  723. });
  724. it("gets current workerSrc", function () {
  725. if (isNodeJS) {
  726. pending("Worker is not supported in Node.js.");
  727. }
  728. const workerSrc = PDFWorker.workerSrc;
  729. expect(typeof workerSrc).toEqual("string");
  730. expect(workerSrc).toEqual(GlobalWorkerOptions.workerSrc);
  731. });
  732. });
  733. describe("PDFDocument", function () {
  734. let pdfLoadingTask, pdfDocument;
  735. beforeAll(async function () {
  736. pdfLoadingTask = getDocument(basicApiGetDocumentParams);
  737. pdfDocument = await pdfLoadingTask.promise;
  738. });
  739. afterAll(async function () {
  740. await pdfLoadingTask.destroy();
  741. });
  742. it("gets number of pages", function () {
  743. expect(pdfDocument.numPages).toEqual(3);
  744. });
  745. it("gets fingerprints", function () {
  746. expect(pdfDocument.fingerprints).toEqual([
  747. "ea8b35919d6279a369e835bde778611b",
  748. null,
  749. ]);
  750. });
  751. it("gets fingerprints, from modified document", async function () {
  752. const loadingTask = getDocument(
  753. buildGetDocumentParams("annotation-tx.pdf")
  754. );
  755. const pdfDoc = await loadingTask.promise;
  756. expect(pdfDoc.fingerprints).toEqual([
  757. "3ebd77c320274649a68f10dbf3b9f882",
  758. "e7087346aa4b4ae0911c1f1643b57345",
  759. ]);
  760. await loadingTask.destroy();
  761. });
  762. it("gets page", async function () {
  763. const data = await pdfDocument.getPage(1);
  764. expect(data instanceof PDFPageProxy).toEqual(true);
  765. expect(data.pageNumber).toEqual(1);
  766. });
  767. it("gets non-existent page", async function () {
  768. const pageNumbers = [
  769. /* outOfRange = */ 100,
  770. /* nonInteger = */ 2.5,
  771. /* nonNumber = */ "1",
  772. ];
  773. for (const pageNumber of pageNumbers) {
  774. try {
  775. await pdfDocument.getPage(pageNumber);
  776. // Shouldn't get here.
  777. expect(false).toEqual(true);
  778. } catch (reason) {
  779. expect(reason instanceof Error).toEqual(true);
  780. expect(reason.message).toEqual("Invalid page request.");
  781. }
  782. }
  783. });
  784. it("gets page, from /Pages tree with circular reference", async function () {
  785. const loadingTask = getDocument(
  786. buildGetDocumentParams("Pages-tree-refs.pdf")
  787. );
  788. const page1 = loadingTask.promise.then(function (pdfDoc) {
  789. return pdfDoc.getPage(1).then(
  790. function (pdfPage) {
  791. expect(pdfPage instanceof PDFPageProxy).toEqual(true);
  792. expect(pdfPage.ref).toEqual({ num: 6, gen: 0 });
  793. },
  794. function (reason) {
  795. throw new Error("shall not fail for valid page");
  796. }
  797. );
  798. });
  799. const page2 = loadingTask.promise.then(function (pdfDoc) {
  800. return pdfDoc.getPage(2).then(
  801. function (pdfPage) {
  802. throw new Error("shall fail for invalid page");
  803. },
  804. function (reason) {
  805. expect(reason instanceof UnknownErrorException).toEqual(true);
  806. expect(reason.message).toEqual(
  807. "Pages tree contains circular reference."
  808. );
  809. }
  810. );
  811. });
  812. await Promise.all([page1, page2]);
  813. await loadingTask.destroy();
  814. });
  815. it("gets page multiple time, with working caches", async function () {
  816. const promiseA = pdfDocument.getPage(1);
  817. const promiseB = pdfDocument.getPage(1);
  818. expect(promiseA instanceof Promise).toEqual(true);
  819. expect(promiseA).toBe(promiseB);
  820. const pageA = await promiseA;
  821. const pageB = await promiseB;
  822. expect(pageA instanceof PDFPageProxy).toEqual(true);
  823. expect(pageA).toBe(pageB);
  824. });
  825. it("gets page index", async function () {
  826. const ref = { num: 17, gen: 0 }; // Reference to second page.
  827. const pageIndex = await pdfDocument.getPageIndex(ref);
  828. expect(pageIndex).toEqual(1);
  829. });
  830. it("gets invalid page index", async function () {
  831. const pageRefs = [
  832. /* fontRef = */ { num: 3, gen: 0 },
  833. /* invalidRef = */ { num: -1, gen: 0 },
  834. /* nonRef = */ "qwerty",
  835. /* nullRef = */ null,
  836. ];
  837. const expectedErrors = [
  838. {
  839. exception: UnknownErrorException,
  840. message: "The reference does not point to a /Page dictionary.",
  841. },
  842. { exception: Error, message: "Invalid pageIndex request." },
  843. { exception: Error, message: "Invalid pageIndex request." },
  844. { exception: Error, message: "Invalid pageIndex request." },
  845. ];
  846. for (let i = 0, ii = pageRefs.length; i < ii; i++) {
  847. try {
  848. await pdfDocument.getPageIndex(pageRefs[i]);
  849. // Shouldn't get here.
  850. expect(false).toEqual(true);
  851. } catch (reason) {
  852. const { exception, message } = expectedErrors[i];
  853. expect(reason instanceof exception).toEqual(true);
  854. expect(reason.message).toEqual(message);
  855. }
  856. }
  857. });
  858. it("gets destinations, from /Dests dictionary", async function () {
  859. const destinations = await pdfDocument.getDestinations();
  860. expect(destinations).toEqual({
  861. chapter1: [{ gen: 0, num: 17 }, { name: "XYZ" }, 0, 841.89, null],
  862. });
  863. });
  864. it("gets a destination, from /Dests dictionary", async function () {
  865. const destination = await pdfDocument.getDestination("chapter1");
  866. expect(destination).toEqual([
  867. { gen: 0, num: 17 },
  868. { name: "XYZ" },
  869. 0,
  870. 841.89,
  871. null,
  872. ]);
  873. });
  874. it("gets a non-existent destination, from /Dests dictionary", async function () {
  875. const destination = await pdfDocument.getDestination(
  876. "non-existent-named-destination"
  877. );
  878. expect(destination).toEqual(null);
  879. });
  880. it("gets destinations, from /Names (NameTree) dictionary", async function () {
  881. const loadingTask = getDocument(buildGetDocumentParams("issue6204.pdf"));
  882. const pdfDoc = await loadingTask.promise;
  883. const destinations = await pdfDoc.getDestinations();
  884. expect(destinations).toEqual({
  885. "Page.1": [{ num: 1, gen: 0 }, { name: "XYZ" }, 0, 375, null],
  886. "Page.2": [{ num: 6, gen: 0 }, { name: "XYZ" }, 0, 375, null],
  887. });
  888. await loadingTask.destroy();
  889. });
  890. it("gets a destination, from /Names (NameTree) dictionary", async function () {
  891. const loadingTask = getDocument(buildGetDocumentParams("issue6204.pdf"));
  892. const pdfDoc = await loadingTask.promise;
  893. const destination = await pdfDoc.getDestination("Page.1");
  894. expect(destination).toEqual([
  895. { num: 1, gen: 0 },
  896. { name: "XYZ" },
  897. 0,
  898. 375,
  899. null,
  900. ]);
  901. await loadingTask.destroy();
  902. });
  903. it("gets a non-existent destination, from /Names (NameTree) dictionary", async function () {
  904. const loadingTask = getDocument(buildGetDocumentParams("issue6204.pdf"));
  905. const pdfDoc = await loadingTask.promise;
  906. const destination = await pdfDoc.getDestination(
  907. "non-existent-named-destination"
  908. );
  909. expect(destination).toEqual(null);
  910. await loadingTask.destroy();
  911. });
  912. it("gets a destination, from out-of-order /Names (NameTree) dictionary (issue 10272)", async function () {
  913. if (isNodeJS) {
  914. pending("Linked test-cases are not supported in Node.js.");
  915. }
  916. const loadingTask = getDocument(buildGetDocumentParams("issue10272.pdf"));
  917. const pdfDoc = await loadingTask.promise;
  918. const destination = await pdfDoc.getDestination("link_1");
  919. expect(destination).toEqual([
  920. { num: 17, gen: 0 },
  921. { name: "XYZ" },
  922. 69,
  923. 125,
  924. 0,
  925. ]);
  926. await loadingTask.destroy();
  927. });
  928. it("gets a destination, from /Names (NameTree) dictionary with keys using PDFDocEncoding (issue 14847)", async function () {
  929. const loadingTask = getDocument(buildGetDocumentParams("issue14847.pdf"));
  930. const pdfDoc = await loadingTask.promise;
  931. const destination = await pdfDoc.getDestination("index");
  932. expect(destination).toEqual([
  933. { num: 10, gen: 0 },
  934. { name: "XYZ" },
  935. 85.039,
  936. 728.504,
  937. null,
  938. ]);
  939. await loadingTask.destroy();
  940. });
  941. it("gets non-string destination", async function () {
  942. let numberPromise = pdfDocument.getDestination(4.3);
  943. let booleanPromise = pdfDocument.getDestination(true);
  944. let arrayPromise = pdfDocument.getDestination([
  945. { num: 17, gen: 0 },
  946. { name: "XYZ" },
  947. 0,
  948. 841.89,
  949. null,
  950. ]);
  951. numberPromise = numberPromise.then(
  952. function () {
  953. throw new Error("shall fail for non-string destination.");
  954. },
  955. function (reason) {
  956. expect(reason instanceof Error).toEqual(true);
  957. }
  958. );
  959. booleanPromise = booleanPromise.then(
  960. function () {
  961. throw new Error("shall fail for non-string destination.");
  962. },
  963. function (reason) {
  964. expect(reason instanceof Error).toEqual(true);
  965. }
  966. );
  967. arrayPromise = arrayPromise.then(
  968. function () {
  969. throw new Error("shall fail for non-string destination.");
  970. },
  971. function (reason) {
  972. expect(reason instanceof Error).toEqual(true);
  973. }
  974. );
  975. await Promise.all([numberPromise, booleanPromise, arrayPromise]);
  976. });
  977. it("gets non-existent page labels", async function () {
  978. const pageLabels = await pdfDocument.getPageLabels();
  979. expect(pageLabels).toEqual(null);
  980. });
  981. it("gets page labels", async function () {
  982. // PageLabels with Roman/Arabic numerals.
  983. const loadingTask0 = getDocument(buildGetDocumentParams("bug793632.pdf"));
  984. const promise0 = loadingTask0.promise.then(function (pdfDoc) {
  985. return pdfDoc.getPageLabels();
  986. });
  987. // PageLabels with only a label prefix.
  988. const loadingTask1 = getDocument(buildGetDocumentParams("issue1453.pdf"));
  989. const promise1 = loadingTask1.promise.then(function (pdfDoc) {
  990. return pdfDoc.getPageLabels();
  991. });
  992. // PageLabels identical to standard page numbering.
  993. const loadingTask2 = getDocument(buildGetDocumentParams("rotation.pdf"));
  994. const promise2 = loadingTask2.promise.then(function (pdfDoc) {
  995. return pdfDoc.getPageLabels();
  996. });
  997. // PageLabels with bad "Prefix" entries.
  998. const loadingTask3 = getDocument(
  999. buildGetDocumentParams("bad-PageLabels.pdf")
  1000. );
  1001. const promise3 = loadingTask3.promise.then(function (pdfDoc) {
  1002. return pdfDoc.getPageLabels();
  1003. });
  1004. const pageLabels = await Promise.all([
  1005. promise0,
  1006. promise1,
  1007. promise2,
  1008. promise3,
  1009. ]);
  1010. expect(pageLabels[0]).toEqual(["i", "ii", "iii", "1"]);
  1011. expect(pageLabels[1]).toEqual(["Front Page1"]);
  1012. expect(pageLabels[2]).toEqual(["1", "2"]);
  1013. expect(pageLabels[3]).toEqual(["X3"]);
  1014. await Promise.all([
  1015. loadingTask0.destroy(),
  1016. loadingTask1.destroy(),
  1017. loadingTask2.destroy(),
  1018. loadingTask3.destroy(),
  1019. ]);
  1020. });
  1021. it("gets default page layout", async function () {
  1022. const loadingTask = getDocument(
  1023. buildGetDocumentParams("tracemonkey.pdf")
  1024. );
  1025. const pdfDoc = await loadingTask.promise;
  1026. const pageLayout = await pdfDoc.getPageLayout();
  1027. expect(pageLayout).toEqual("");
  1028. await loadingTask.destroy();
  1029. });
  1030. it("gets non-default page layout", async function () {
  1031. const pageLayout = await pdfDocument.getPageLayout();
  1032. expect(pageLayout).toEqual("SinglePage");
  1033. });
  1034. it("gets default page mode", async function () {
  1035. const loadingTask = getDocument(
  1036. buildGetDocumentParams("tracemonkey.pdf")
  1037. );
  1038. const pdfDoc = await loadingTask.promise;
  1039. const pageMode = await pdfDoc.getPageMode();
  1040. expect(pageMode).toEqual("UseNone");
  1041. await loadingTask.destroy();
  1042. });
  1043. it("gets non-default page mode", async function () {
  1044. const pageMode = await pdfDocument.getPageMode();
  1045. expect(pageMode).toEqual("UseOutlines");
  1046. });
  1047. it("gets default viewer preferences", async function () {
  1048. const loadingTask = getDocument(
  1049. buildGetDocumentParams("tracemonkey.pdf")
  1050. );
  1051. const pdfDoc = await loadingTask.promise;
  1052. const prefs = await pdfDoc.getViewerPreferences();
  1053. expect(prefs).toEqual(null);
  1054. await loadingTask.destroy();
  1055. });
  1056. it("gets non-default viewer preferences", async function () {
  1057. const prefs = await pdfDocument.getViewerPreferences();
  1058. expect(prefs).toEqual({ Direction: "L2R" });
  1059. });
  1060. it("gets default open action", async function () {
  1061. const loadingTask = getDocument(
  1062. buildGetDocumentParams("tracemonkey.pdf")
  1063. );
  1064. const pdfDoc = await loadingTask.promise;
  1065. const openAction = await pdfDoc.getOpenAction();
  1066. expect(openAction).toEqual(null);
  1067. await loadingTask.destroy();
  1068. });
  1069. it("gets non-default open action (with destination)", async function () {
  1070. const openAction = await pdfDocument.getOpenAction();
  1071. expect(openAction.dest).toEqual([
  1072. { num: 15, gen: 0 },
  1073. { name: "FitH" },
  1074. null,
  1075. ]);
  1076. expect(openAction.action).toBeUndefined();
  1077. });
  1078. it("gets non-default open action (with Print action)", async function () {
  1079. // PDF document with "Print" Named action in the OpenAction dictionary.
  1080. const loadingTask1 = getDocument(
  1081. buildGetDocumentParams("bug1001080.pdf")
  1082. );
  1083. // PDF document with "Print" Named action in the OpenAction dictionary,
  1084. // but the OpenAction dictionary is missing the `Type` entry.
  1085. const loadingTask2 = getDocument(
  1086. buildGetDocumentParams("issue11442_reduced.pdf")
  1087. );
  1088. const promise1 = loadingTask1.promise
  1089. .then(function (pdfDoc) {
  1090. return pdfDoc.getOpenAction();
  1091. })
  1092. .then(function (openAction) {
  1093. expect(openAction.dest).toBeUndefined();
  1094. expect(openAction.action).toEqual("Print");
  1095. return loadingTask1.destroy();
  1096. });
  1097. const promise2 = loadingTask2.promise
  1098. .then(function (pdfDoc) {
  1099. return pdfDoc.getOpenAction();
  1100. })
  1101. .then(function (openAction) {
  1102. expect(openAction.dest).toBeUndefined();
  1103. expect(openAction.action).toEqual("Print");
  1104. return loadingTask2.destroy();
  1105. });
  1106. await Promise.all([promise1, promise2]);
  1107. });
  1108. it("gets non-existent attachments", async function () {
  1109. const attachments = await pdfDocument.getAttachments();
  1110. expect(attachments).toEqual(null);
  1111. });
  1112. it("gets attachments", async function () {
  1113. const loadingTask = getDocument(buildGetDocumentParams("attachment.pdf"));
  1114. const pdfDoc = await loadingTask.promise;
  1115. const attachments = await pdfDoc.getAttachments();
  1116. const attachment = attachments["foo.txt"];
  1117. expect(attachment.filename).toEqual("foo.txt");
  1118. expect(attachment.content).toEqual(
  1119. new Uint8Array([98, 97, 114, 32, 98, 97, 122, 32, 10])
  1120. );
  1121. await loadingTask.destroy();
  1122. });
  1123. it("gets javascript", async function () {
  1124. const javascript = await pdfDocument.getJavaScript();
  1125. expect(javascript).toEqual(null);
  1126. });
  1127. it("gets javascript with printing instructions (JS action)", async function () {
  1128. // PDF document with "JavaScript" action in the OpenAction dictionary.
  1129. const loadingTask = getDocument(buildGetDocumentParams("issue6106.pdf"));
  1130. const pdfDoc = await loadingTask.promise;
  1131. const javascript = await pdfDoc.getJavaScript();
  1132. expect(javascript).toEqual([
  1133. "this.print({bUI:true,bSilent:false,bShrinkToFit:true});",
  1134. ]);
  1135. expect(javascript[0]).toMatch(AutoPrintRegExp);
  1136. await loadingTask.destroy();
  1137. });
  1138. it("gets hasJSActions, in document without javaScript", async function () {
  1139. const hasJSActions = await pdfDocument.hasJSActions();
  1140. expect(hasJSActions).toEqual(false);
  1141. });
  1142. it("gets hasJSActions, in document with javaScript", async function () {
  1143. const loadingTask = getDocument(
  1144. buildGetDocumentParams("doc_actions.pdf")
  1145. );
  1146. const pdfDoc = await loadingTask.promise;
  1147. const hasJSActions = await pdfDoc.hasJSActions();
  1148. expect(hasJSActions).toEqual(true);
  1149. await loadingTask.destroy();
  1150. });
  1151. it("gets non-existent JSActions", async function () {
  1152. const jsActions = await pdfDocument.getJSActions();
  1153. expect(jsActions).toEqual(null);
  1154. });
  1155. it("gets JSActions", async function () {
  1156. // PDF document with "JavaScript" action in the OpenAction dictionary.
  1157. const loadingTask = getDocument(
  1158. buildGetDocumentParams("doc_actions.pdf")
  1159. );
  1160. const pdfDoc = await loadingTask.promise;
  1161. const docActions = await pdfDoc.getJSActions();
  1162. const page1 = await pdfDoc.getPage(1);
  1163. const page1Actions = await page1.getJSActions();
  1164. const page3 = await pdfDoc.getPage(3);
  1165. const page3Actions = await page3.getJSActions();
  1166. expect(docActions).toEqual({
  1167. DidPrint: [`this.getField("Text2").value = "DidPrint";`],
  1168. DidSave: [`this.getField("Text2").value = "DidSave";`],
  1169. WillClose: [`this.getField("Text1").value = "WillClose";`],
  1170. WillPrint: [`this.getField("Text1").value = "WillPrint";`],
  1171. WillSave: [`this.getField("Text1").value = "WillSave";`],
  1172. });
  1173. expect(page1Actions).toEqual({
  1174. PageOpen: [`this.getField("Text1").value = "PageOpen 1";`],
  1175. PageClose: [`this.getField("Text2").value = "PageClose 1";`],
  1176. });
  1177. expect(page3Actions).toEqual({
  1178. PageOpen: [`this.getField("Text5").value = "PageOpen 3";`],
  1179. PageClose: [`this.getField("Text6").value = "PageClose 3";`],
  1180. });
  1181. await loadingTask.destroy();
  1182. });
  1183. it("gets non-existent fieldObjects", async function () {
  1184. const fieldObjects = await pdfDocument.getFieldObjects();
  1185. expect(fieldObjects).toEqual(null);
  1186. });
  1187. it("gets fieldObjects", async function () {
  1188. const loadingTask = getDocument(buildGetDocumentParams("js-authors.pdf"));
  1189. const pdfDoc = await loadingTask.promise;
  1190. const fieldObjects = await pdfDoc.getFieldObjects();
  1191. expect(fieldObjects).toEqual({
  1192. Text1: [
  1193. {
  1194. id: "25R",
  1195. value: "",
  1196. defaultValue: "",
  1197. multiline: false,
  1198. password: false,
  1199. charLimit: 0,
  1200. comb: false,
  1201. editable: true,
  1202. hidden: false,
  1203. name: "Text1",
  1204. rect: [24.1789, 719.66, 432.22, 741.66],
  1205. actions: null,
  1206. page: 0,
  1207. strokeColor: null,
  1208. fillColor: null,
  1209. rotation: 0,
  1210. type: "text",
  1211. },
  1212. ],
  1213. Button1: [
  1214. {
  1215. id: "26R",
  1216. value: "Off",
  1217. defaultValue: null,
  1218. exportValues: undefined,
  1219. editable: true,
  1220. name: "Button1",
  1221. rect: [455.436, 719.678, 527.436, 739.678],
  1222. hidden: false,
  1223. actions: {
  1224. Action: [
  1225. `this.getField("Text1").value = this.info.authors.join("::");`,
  1226. ],
  1227. },
  1228. page: 0,
  1229. strokeColor: null,
  1230. fillColor: new Uint8ClampedArray([192, 192, 192]),
  1231. rotation: 0,
  1232. type: "button",
  1233. },
  1234. ],
  1235. });
  1236. await loadingTask.destroy();
  1237. });
  1238. it("gets non-existent calculationOrder", async function () {
  1239. const calculationOrder = await pdfDocument.getCalculationOrderIds();
  1240. expect(calculationOrder).toEqual(null);
  1241. });
  1242. it("gets calculationOrder", async function () {
  1243. if (isNodeJS) {
  1244. pending("Linked test-cases are not supported in Node.js.");
  1245. }
  1246. const loadingTask = getDocument(buildGetDocumentParams("issue13132.pdf"));
  1247. const pdfDoc = await loadingTask.promise;
  1248. const calculationOrder = await pdfDoc.getCalculationOrderIds();
  1249. expect(calculationOrder).toEqual([
  1250. "319R",
  1251. "320R",
  1252. "321R",
  1253. "322R",
  1254. "323R",
  1255. "324R",
  1256. "325R",
  1257. "326R",
  1258. "327R",
  1259. "328R",
  1260. "329R",
  1261. "330R",
  1262. "331R",
  1263. "332R",
  1264. "333R",
  1265. "334R",
  1266. "335R",
  1267. ]);
  1268. await loadingTask.destroy();
  1269. });
  1270. it("gets non-existent outline", async function () {
  1271. const loadingTask = getDocument(
  1272. buildGetDocumentParams("tracemonkey.pdf")
  1273. );
  1274. const pdfDoc = await loadingTask.promise;
  1275. const outline = await pdfDoc.getOutline();
  1276. expect(outline).toEqual(null);
  1277. await loadingTask.destroy();
  1278. });
  1279. it("gets outline", async function () {
  1280. const outline = await pdfDocument.getOutline();
  1281. // Two top level entries.
  1282. expect(Array.isArray(outline)).toEqual(true);
  1283. expect(outline.length).toEqual(2);
  1284. // Make sure some basic attributes are set.
  1285. const outlineItem = outline[1];
  1286. expect(outlineItem.title).toEqual("Chapter 1");
  1287. expect(Array.isArray(outlineItem.dest)).toEqual(true);
  1288. expect(outlineItem.url).toEqual(null);
  1289. expect(outlineItem.unsafeUrl).toBeUndefined();
  1290. expect(outlineItem.newWindow).toBeUndefined();
  1291. expect(outlineItem.bold).toEqual(true);
  1292. expect(outlineItem.italic).toEqual(false);
  1293. expect(outlineItem.color).toEqual(new Uint8ClampedArray([0, 64, 128]));
  1294. expect(outlineItem.items.length).toEqual(1);
  1295. expect(outlineItem.items[0].title).toEqual("Paragraph 1.1");
  1296. });
  1297. it("gets outline containing a URL", async function () {
  1298. const loadingTask = getDocument(buildGetDocumentParams("issue3214.pdf"));
  1299. const pdfDoc = await loadingTask.promise;
  1300. const outline = await pdfDoc.getOutline();
  1301. expect(Array.isArray(outline)).toEqual(true);
  1302. expect(outline.length).toEqual(5);
  1303. const outlineItemTwo = outline[2];
  1304. expect(typeof outlineItemTwo.title).toEqual("string");
  1305. expect(outlineItemTwo.dest).toEqual(null);
  1306. expect(outlineItemTwo.url).toEqual("http://google.com/");
  1307. expect(outlineItemTwo.unsafeUrl).toEqual("http://google.com");
  1308. expect(outlineItemTwo.newWindow).toBeUndefined();
  1309. const outlineItemOne = outline[1];
  1310. expect(outlineItemOne.bold).toEqual(false);
  1311. expect(outlineItemOne.italic).toEqual(true);
  1312. expect(outlineItemOne.color).toEqual(new Uint8ClampedArray([0, 0, 0]));
  1313. await loadingTask.destroy();
  1314. });
  1315. it("gets outline, with dest-strings using PDFDocEncoding (issue 14864)", async function () {
  1316. if (isNodeJS) {
  1317. pending("Linked test-cases are not supported in Node.js.");
  1318. }
  1319. const loadingTask = getDocument(buildGetDocumentParams("issue14864.pdf"));
  1320. const pdfDoc = await loadingTask.promise;
  1321. const outline = await pdfDoc.getOutline();
  1322. expect(Array.isArray(outline)).toEqual(true);
  1323. expect(outline.length).toEqual(6);
  1324. expect(outline[4]).toEqual({
  1325. action: null,
  1326. attachment: undefined,
  1327. dest: "Händel -- Halle🎆lujah",
  1328. url: null,
  1329. unsafeUrl: undefined,
  1330. newWindow: undefined,
  1331. setOCGState: undefined,
  1332. title: "Händel -- Halle🎆lujah",
  1333. color: new Uint8ClampedArray([0, 0, 0]),
  1334. count: undefined,
  1335. bold: false,
  1336. italic: false,
  1337. items: [],
  1338. });
  1339. await loadingTask.destroy();
  1340. });
  1341. it("gets outline, with named-actions (issue 15367)", async function () {
  1342. const loadingTask = getDocument(buildGetDocumentParams("issue15367.pdf"));
  1343. const pdfDoc = await loadingTask.promise;
  1344. const outline = await pdfDoc.getOutline();
  1345. expect(Array.isArray(outline)).toEqual(true);
  1346. expect(outline.length).toEqual(4);
  1347. expect(outline[1]).toEqual({
  1348. action: "PrevPage",
  1349. attachment: undefined,
  1350. dest: null,
  1351. url: null,
  1352. unsafeUrl: undefined,
  1353. newWindow: undefined,
  1354. setOCGState: undefined,
  1355. title: "Previous Page",
  1356. color: new Uint8ClampedArray([0, 0, 0]),
  1357. count: undefined,
  1358. bold: false,
  1359. italic: false,
  1360. items: [],
  1361. });
  1362. await loadingTask.destroy();
  1363. });
  1364. it("gets outline, with SetOCGState-actions (issue 15372)", async function () {
  1365. const loadingTask = getDocument(buildGetDocumentParams("issue15372.pdf"));
  1366. const pdfDoc = await loadingTask.promise;
  1367. const outline = await pdfDoc.getOutline();
  1368. expect(Array.isArray(outline)).toEqual(true);
  1369. expect(outline.length).toEqual(1);
  1370. expect(outline[0]).toEqual({
  1371. action: null,
  1372. attachment: undefined,
  1373. dest: null,
  1374. url: null,
  1375. unsafeUrl: undefined,
  1376. newWindow: undefined,
  1377. setOCGState: { state: ["OFF", "ON", "50R"], preserveRB: false },
  1378. title: "Display Layer",
  1379. color: new Uint8ClampedArray([0, 0, 0]),
  1380. count: undefined,
  1381. bold: false,
  1382. italic: false,
  1383. items: [],
  1384. });
  1385. await loadingTask.destroy();
  1386. });
  1387. it("gets outline with non-displayable chars", async function () {
  1388. const loadingTask = getDocument(buildGetDocumentParams("issue14267.pdf"));
  1389. const pdfDoc = await loadingTask.promise;
  1390. const outline = await pdfDoc.getOutline();
  1391. expect(Array.isArray(outline)).toEqual(true);
  1392. expect(outline.length).toEqual(1);
  1393. const outlineItem = outline[0];
  1394. expect(outlineItem.title).toEqual("hello\x11world");
  1395. await loadingTask.destroy();
  1396. });
  1397. it("gets non-existent permissions", async function () {
  1398. const permissions = await pdfDocument.getPermissions();
  1399. expect(permissions).toEqual(null);
  1400. });
  1401. it("gets permissions", async function () {
  1402. // Editing not allowed.
  1403. const loadingTask0 = getDocument(
  1404. buildGetDocumentParams("issue9972-1.pdf")
  1405. );
  1406. const promise0 = loadingTask0.promise.then(function (pdfDoc) {
  1407. return pdfDoc.getPermissions();
  1408. });
  1409. // Printing not allowed.
  1410. const loadingTask1 = getDocument(
  1411. buildGetDocumentParams("issue9972-2.pdf")
  1412. );
  1413. const promise1 = loadingTask1.promise.then(function (pdfDoc) {
  1414. return pdfDoc.getPermissions();
  1415. });
  1416. // Copying not allowed.
  1417. const loadingTask2 = getDocument(
  1418. buildGetDocumentParams("issue9972-3.pdf")
  1419. );
  1420. const promise2 = loadingTask2.promise.then(function (pdfDoc) {
  1421. return pdfDoc.getPermissions();
  1422. });
  1423. const totalPermissionCount = Object.keys(PermissionFlag).length;
  1424. const permissions = await Promise.all([promise0, promise1, promise2]);
  1425. expect(permissions[0].length).toEqual(totalPermissionCount - 1);
  1426. expect(
  1427. permissions[0].includes(PermissionFlag.MODIFY_CONTENTS)
  1428. ).toBeFalsy();
  1429. expect(permissions[1].length).toEqual(totalPermissionCount - 2);
  1430. expect(permissions[1].includes(PermissionFlag.PRINT)).toBeFalsy();
  1431. expect(
  1432. permissions[1].includes(PermissionFlag.PRINT_HIGH_QUALITY)
  1433. ).toBeFalsy();
  1434. expect(permissions[2].length).toEqual(totalPermissionCount - 1);
  1435. expect(permissions[2].includes(PermissionFlag.COPY)).toBeFalsy();
  1436. await Promise.all([
  1437. loadingTask0.destroy(),
  1438. loadingTask1.destroy(),
  1439. loadingTask2.destroy(),
  1440. ]);
  1441. });
  1442. it("gets metadata", async function () {
  1443. const { info, metadata, contentDispositionFilename, contentLength } =
  1444. await pdfDocument.getMetadata();
  1445. expect(info.Title).toEqual("Basic API Test");
  1446. // Custom, non-standard, information dictionary entries.
  1447. expect(info.Custom).toEqual(undefined);
  1448. // The following are PDF.js specific, non-standard, properties.
  1449. expect(info.PDFFormatVersion).toEqual("1.7");
  1450. expect(info.Language).toEqual("en");
  1451. expect(info.EncryptFilterName).toEqual(null);
  1452. expect(info.IsLinearized).toEqual(false);
  1453. expect(info.IsAcroFormPresent).toEqual(false);
  1454. expect(info.IsXFAPresent).toEqual(false);
  1455. expect(info.IsCollectionPresent).toEqual(false);
  1456. expect(info.IsSignaturesPresent).toEqual(false);
  1457. expect(metadata instanceof Metadata).toEqual(true);
  1458. expect(metadata.get("dc:title")).toEqual("Basic API Test");
  1459. expect(contentDispositionFilename).toEqual(null);
  1460. expect(contentLength).toEqual(basicApiFileLength);
  1461. });
  1462. it("gets metadata, with custom info dict entries", async function () {
  1463. const loadingTask = getDocument(
  1464. buildGetDocumentParams("tracemonkey.pdf")
  1465. );
  1466. const pdfDoc = await loadingTask.promise;
  1467. const { info, metadata, contentDispositionFilename, contentLength } =
  1468. await pdfDoc.getMetadata();
  1469. expect(info.Creator).toEqual("TeX");
  1470. expect(info.Producer).toEqual("pdfeTeX-1.21a");
  1471. expect(info.CreationDate).toEqual("D:20090401163925-07'00'");
  1472. // Custom, non-standard, information dictionary entries.
  1473. const custom = info.Custom;
  1474. expect(typeof custom === "object" && custom !== null).toEqual(true);
  1475. expect(custom["PTEX.Fullbanner"]).toEqual(
  1476. "This is pdfeTeX, " +
  1477. "Version 3.141592-1.21a-2.2 (Web2C 7.5.4) kpathsea version 3.5.6"
  1478. );
  1479. // The following are PDF.js specific, non-standard, properties.
  1480. expect(info.PDFFormatVersion).toEqual("1.4");
  1481. expect(info.Language).toEqual(null);
  1482. expect(info.EncryptFilterName).toEqual(null);
  1483. expect(info.IsLinearized).toEqual(false);
  1484. expect(info.IsAcroFormPresent).toEqual(false);
  1485. expect(info.IsXFAPresent).toEqual(false);
  1486. expect(info.IsCollectionPresent).toEqual(false);
  1487. expect(info.IsSignaturesPresent).toEqual(false);
  1488. expect(metadata).toEqual(null);
  1489. expect(contentDispositionFilename).toEqual(null);
  1490. expect(contentLength).toEqual(1016315);
  1491. await loadingTask.destroy();
  1492. });
  1493. it("gets metadata, with missing PDF header (bug 1606566)", async function () {
  1494. const loadingTask = getDocument(buildGetDocumentParams("bug1606566.pdf"));
  1495. const pdfDoc = await loadingTask.promise;
  1496. const { info, metadata, contentDispositionFilename, contentLength } =
  1497. await pdfDoc.getMetadata();
  1498. // Custom, non-standard, information dictionary entries.
  1499. expect(info.Custom).toEqual(undefined);
  1500. // The following are PDF.js specific, non-standard, properties.
  1501. expect(info.PDFFormatVersion).toEqual(null);
  1502. expect(info.Language).toEqual(null);
  1503. expect(info.EncryptFilterName).toEqual(null);
  1504. expect(info.IsLinearized).toEqual(false);
  1505. expect(info.IsAcroFormPresent).toEqual(false);
  1506. expect(info.IsXFAPresent).toEqual(false);
  1507. expect(info.IsCollectionPresent).toEqual(false);
  1508. expect(info.IsSignaturesPresent).toEqual(false);
  1509. expect(metadata).toEqual(null);
  1510. expect(contentDispositionFilename).toEqual(null);
  1511. expect(contentLength).toEqual(624);
  1512. await loadingTask.destroy();
  1513. });
  1514. it("gets metadata, with corrupt /Metadata XRef entry", async function () {
  1515. const loadingTask = getDocument(
  1516. buildGetDocumentParams("PDFBOX-3148-2-fuzzed.pdf")
  1517. );
  1518. const pdfDoc = await loadingTask.promise;
  1519. const { info, metadata, contentDispositionFilename, contentLength } =
  1520. await pdfDoc.getMetadata();
  1521. // Custom, non-standard, information dictionary entries.
  1522. expect(info.Custom).toEqual(undefined);
  1523. // The following are PDF.js specific, non-standard, properties.
  1524. expect(info.PDFFormatVersion).toEqual("1.6");
  1525. expect(info.Language).toEqual(null);
  1526. expect(info.EncryptFilterName).toEqual(null);
  1527. expect(info.IsLinearized).toEqual(false);
  1528. expect(info.IsAcroFormPresent).toEqual(true);
  1529. expect(info.IsXFAPresent).toEqual(false);
  1530. expect(info.IsCollectionPresent).toEqual(false);
  1531. expect(info.IsSignaturesPresent).toEqual(false);
  1532. expect(metadata).toEqual(null);
  1533. expect(contentDispositionFilename).toEqual(null);
  1534. expect(contentLength).toEqual(244351);
  1535. await loadingTask.destroy();
  1536. });
  1537. it("gets markInfo", async function () {
  1538. const loadingTask = getDocument(
  1539. buildGetDocumentParams("annotation-line.pdf")
  1540. );
  1541. const pdfDoc = await loadingTask.promise;
  1542. const markInfo = await pdfDoc.getMarkInfo();
  1543. expect(markInfo.Marked).toEqual(true);
  1544. expect(markInfo.UserProperties).toEqual(false);
  1545. expect(markInfo.Suspects).toEqual(false);
  1546. });
  1547. it("gets data", async function () {
  1548. const data = await pdfDocument.getData();
  1549. expect(data instanceof Uint8Array).toEqual(true);
  1550. expect(data.length).toEqual(basicApiFileLength);
  1551. });
  1552. it("gets download info", async function () {
  1553. const downloadInfo = await pdfDocument.getDownloadInfo();
  1554. expect(downloadInfo).toEqual({ length: basicApiFileLength });
  1555. });
  1556. it("gets document stats", async function () {
  1557. const stats = pdfDocument.stats;
  1558. expect(stats).toEqual(null);
  1559. });
  1560. it("cleans up document resources", async function () {
  1561. await pdfDocument.cleanup();
  1562. expect(true).toEqual(true);
  1563. });
  1564. it("checks that fingerprints are unique", async function () {
  1565. const loadingTask1 = getDocument(
  1566. buildGetDocumentParams("issue4436r.pdf")
  1567. );
  1568. const loadingTask2 = getDocument(buildGetDocumentParams("issue4575.pdf"));
  1569. const data = await Promise.all([
  1570. loadingTask1.promise,
  1571. loadingTask2.promise,
  1572. ]);
  1573. const fingerprints1 = data[0].fingerprints;
  1574. const fingerprints2 = data[1].fingerprints;
  1575. expect(fingerprints1).not.toEqual(fingerprints2);
  1576. expect(fingerprints1).toEqual(["657428c0628e329f9a281fb6d2d092d4", null]);
  1577. expect(fingerprints2).toEqual(["04c7126b34a46b6d4d6e7a1eff7edcb6", null]);
  1578. await Promise.all([loadingTask1.destroy(), loadingTask2.destroy()]);
  1579. });
  1580. it("write a value in an annotation, save the pdf and load it", async function () {
  1581. let loadingTask = getDocument(buildGetDocumentParams("evaljs.pdf"));
  1582. let pdfDoc = await loadingTask.promise;
  1583. const value = "Hello World";
  1584. pdfDoc.annotationStorage.setValue("55R", { value });
  1585. const data = await pdfDoc.saveDocument();
  1586. await loadingTask.destroy();
  1587. loadingTask = getDocument(data);
  1588. pdfDoc = await loadingTask.promise;
  1589. const pdfPage = await pdfDoc.getPage(1);
  1590. const annotations = await pdfPage.getAnnotations();
  1591. const field = annotations.find(annotation => annotation.id === "55R");
  1592. expect(!!field).toEqual(true);
  1593. expect(field.fieldValue).toEqual(value);
  1594. await loadingTask.destroy();
  1595. });
  1596. describe("Cross-origin", function () {
  1597. let loadingTask;
  1598. function _checkCanLoad(expectSuccess, filename, options) {
  1599. if (isNodeJS) {
  1600. pending("Cannot simulate cross-origin requests in Node.js");
  1601. }
  1602. const params = buildGetDocumentParams(filename, options);
  1603. const url = new URL(params.url);
  1604. if (url.hostname === "localhost") {
  1605. url.hostname = "127.0.0.1";
  1606. } else if (params.url.hostname === "127.0.0.1") {
  1607. url.hostname = "localhost";
  1608. } else {
  1609. pending("Can only run cross-origin test on localhost!");
  1610. }
  1611. params.url = url.href;
  1612. loadingTask = getDocument(params);
  1613. return loadingTask.promise
  1614. .then(function (pdf) {
  1615. return pdf.destroy();
  1616. })
  1617. .then(
  1618. function () {
  1619. expect(expectSuccess).toEqual(true);
  1620. },
  1621. function (error) {
  1622. if (expectSuccess) {
  1623. // For ease of debugging.
  1624. expect(error).toEqual("There should not be any error");
  1625. }
  1626. expect(expectSuccess).toEqual(false);
  1627. }
  1628. );
  1629. }
  1630. function testCanLoad(filename, options) {
  1631. return _checkCanLoad(true, filename, options);
  1632. }
  1633. function testCannotLoad(filename, options) {
  1634. return _checkCanLoad(false, filename, options);
  1635. }
  1636. afterEach(async function () {
  1637. if (loadingTask && !loadingTask.destroyed) {
  1638. await loadingTask.destroy();
  1639. }
  1640. });
  1641. it("server disallows cors", async function () {
  1642. await testCannotLoad("basicapi.pdf");
  1643. });
  1644. it("server allows cors without credentials, default withCredentials", async function () {
  1645. await testCanLoad("basicapi.pdf?cors=withoutCredentials");
  1646. });
  1647. it("server allows cors without credentials, and withCredentials=false", async function () {
  1648. await testCanLoad("basicapi.pdf?cors=withoutCredentials", {
  1649. withCredentials: false,
  1650. });
  1651. });
  1652. it("server allows cors without credentials, but withCredentials=true", async function () {
  1653. await testCannotLoad("basicapi.pdf?cors=withoutCredentials", {
  1654. withCredentials: true,
  1655. });
  1656. });
  1657. it("server allows cors with credentials, and withCredentials=true", async function () {
  1658. await testCanLoad("basicapi.pdf?cors=withCredentials", {
  1659. withCredentials: true,
  1660. });
  1661. });
  1662. it("server allows cors with credentials, and withCredentials=false", async function () {
  1663. // The server supports even more than we need, so if the previous tests
  1664. // pass, then this should pass for sure.
  1665. // The only case where this test fails is when the server does not reply
  1666. // with the Access-Control-Allow-Origin header.
  1667. await testCanLoad("basicapi.pdf?cors=withCredentials", {
  1668. withCredentials: false,
  1669. });
  1670. });
  1671. });
  1672. });
  1673. describe("Page", function () {
  1674. let pdfLoadingTask, pdfDocument, page;
  1675. beforeAll(async function () {
  1676. pdfLoadingTask = getDocument(basicApiGetDocumentParams);
  1677. pdfDocument = await pdfLoadingTask.promise;
  1678. page = await pdfDocument.getPage(1);
  1679. });
  1680. afterAll(async function () {
  1681. await pdfLoadingTask.destroy();
  1682. });
  1683. it("gets page number", function () {
  1684. expect(page.pageNumber).toEqual(1);
  1685. });
  1686. it("gets rotate", function () {
  1687. expect(page.rotate).toEqual(0);
  1688. });
  1689. it("gets ref", function () {
  1690. expect(page.ref).toEqual({ num: 15, gen: 0 });
  1691. });
  1692. it("gets userUnit", function () {
  1693. expect(page.userUnit).toEqual(1.0);
  1694. });
  1695. it("gets view", function () {
  1696. expect(page.view).toEqual([0, 0, 595.28, 841.89]);
  1697. });
  1698. it("gets view, with empty/invalid bounding boxes", async function () {
  1699. const viewLoadingTask = getDocument(
  1700. buildGetDocumentParams("boundingBox_invalid.pdf")
  1701. );
  1702. const pdfDoc = await viewLoadingTask.promise;
  1703. const numPages = pdfDoc.numPages;
  1704. expect(numPages).toEqual(3);
  1705. const viewPromises = [];
  1706. for (let i = 0; i < numPages; i++) {
  1707. viewPromises[i] = pdfDoc.getPage(i + 1).then(pdfPage => {
  1708. return pdfPage.view;
  1709. });
  1710. }
  1711. const [page1, page2, page3] = await Promise.all(viewPromises);
  1712. expect(page1).toEqual([0, 0, 612, 792]);
  1713. expect(page2).toEqual([0, 0, 800, 600]);
  1714. expect(page3).toEqual([0, 0, 600, 800]);
  1715. await viewLoadingTask.destroy();
  1716. });
  1717. it("gets viewport", function () {
  1718. const viewport = page.getViewport({ scale: 1.5, rotation: 90 });
  1719. expect(viewport instanceof PageViewport).toEqual(true);
  1720. expect(viewport.viewBox).toEqual(page.view);
  1721. expect(viewport.scale).toEqual(1.5);
  1722. expect(viewport.rotation).toEqual(90);
  1723. expect(viewport.transform).toEqual([0, 1.5, 1.5, 0, 0, 0]);
  1724. expect(viewport.width).toEqual(1262.835);
  1725. expect(viewport.height).toEqual(892.92);
  1726. });
  1727. it('gets viewport with "offsetX/offsetY" arguments', function () {
  1728. const viewport = page.getViewport({
  1729. scale: 1,
  1730. rotation: 0,
  1731. offsetX: 100,
  1732. offsetY: -100,
  1733. });
  1734. expect(viewport instanceof PageViewport).toEqual(true);
  1735. expect(viewport.transform).toEqual([1, 0, 0, -1, 100, 741.89]);
  1736. });
  1737. it('gets viewport respecting "dontFlip" argument', function () {
  1738. const scale = 1,
  1739. rotation = 0;
  1740. const viewport = page.getViewport({ scale, rotation });
  1741. expect(viewport instanceof PageViewport).toEqual(true);
  1742. const dontFlipViewport = page.getViewport({
  1743. scale,
  1744. rotation,
  1745. dontFlip: true,
  1746. });
  1747. expect(dontFlipViewport instanceof PageViewport).toEqual(true);
  1748. expect(dontFlipViewport).not.toEqual(viewport);
  1749. expect(dontFlipViewport).toEqual(viewport.clone({ dontFlip: true }));
  1750. expect(viewport.transform).toEqual([1, 0, 0, -1, 0, 841.89]);
  1751. expect(dontFlipViewport.transform).toEqual([1, 0, -0, 1, 0, 0]);
  1752. });
  1753. it("gets viewport with invalid rotation", function () {
  1754. expect(function () {
  1755. page.getViewport({ scale: 1, rotation: 45 });
  1756. }).toThrow(
  1757. new Error(
  1758. "PageViewport: Invalid rotation, must be a multiple of 90 degrees."
  1759. )
  1760. );
  1761. });
  1762. it("gets annotations", async function () {
  1763. const defaultPromise = page.getAnnotations().then(function (data) {
  1764. expect(data.length).toEqual(4);
  1765. });
  1766. const anyPromise = page
  1767. .getAnnotations({ intent: "any" })
  1768. .then(function (data) {
  1769. expect(data.length).toEqual(4);
  1770. });
  1771. const displayPromise = page
  1772. .getAnnotations({ intent: "display" })
  1773. .then(function (data) {
  1774. expect(data.length).toEqual(4);
  1775. });
  1776. const printPromise = page
  1777. .getAnnotations({ intent: "print" })
  1778. .then(function (data) {
  1779. expect(data.length).toEqual(4);
  1780. });
  1781. await Promise.all([
  1782. defaultPromise,
  1783. anyPromise,
  1784. displayPromise,
  1785. printPromise,
  1786. ]);
  1787. });
  1788. it("gets annotations containing relative URLs (bug 766086)", async function () {
  1789. const filename = "bug766086.pdf";
  1790. const defaultLoadingTask = getDocument(buildGetDocumentParams(filename));
  1791. const defaultPromise = defaultLoadingTask.promise.then(function (pdfDoc) {
  1792. return pdfDoc.getPage(1).then(function (pdfPage) {
  1793. return pdfPage.getAnnotations();
  1794. });
  1795. });
  1796. const docBaseUrlLoadingTask = getDocument(
  1797. buildGetDocumentParams(filename, {
  1798. docBaseUrl: "http://www.example.com/test/pdfs/qwerty.pdf",
  1799. })
  1800. );
  1801. const docBaseUrlPromise = docBaseUrlLoadingTask.promise.then(function (
  1802. pdfDoc
  1803. ) {
  1804. return pdfDoc.getPage(1).then(function (pdfPage) {
  1805. return pdfPage.getAnnotations();
  1806. });
  1807. });
  1808. const invalidDocBaseUrlLoadingTask = getDocument(
  1809. buildGetDocumentParams(filename, {
  1810. docBaseUrl: "qwerty.pdf",
  1811. })
  1812. );
  1813. const invalidDocBaseUrlPromise =
  1814. invalidDocBaseUrlLoadingTask.promise.then(function (pdfDoc) {
  1815. return pdfDoc.getPage(1).then(function (pdfPage) {
  1816. return pdfPage.getAnnotations();
  1817. });
  1818. });
  1819. const [
  1820. defaultAnnotations,
  1821. docBaseUrlAnnotations,
  1822. invalidDocBaseUrlAnnotations,
  1823. ] = await Promise.all([
  1824. defaultPromise,
  1825. docBaseUrlPromise,
  1826. invalidDocBaseUrlPromise,
  1827. ]);
  1828. expect(defaultAnnotations[0].url).toBeUndefined();
  1829. expect(defaultAnnotations[0].unsafeUrl).toEqual(
  1830. "../../0021/002156/215675E.pdf#15"
  1831. );
  1832. expect(docBaseUrlAnnotations[0].url).toEqual(
  1833. "http://www.example.com/0021/002156/215675E.pdf#15"
  1834. );
  1835. expect(docBaseUrlAnnotations[0].unsafeUrl).toEqual(
  1836. "../../0021/002156/215675E.pdf#15"
  1837. );
  1838. expect(invalidDocBaseUrlAnnotations[0].url).toBeUndefined();
  1839. expect(invalidDocBaseUrlAnnotations[0].unsafeUrl).toEqual(
  1840. "../../0021/002156/215675E.pdf#15"
  1841. );
  1842. await Promise.all([
  1843. defaultLoadingTask.destroy(),
  1844. docBaseUrlLoadingTask.destroy(),
  1845. invalidDocBaseUrlLoadingTask.destroy(),
  1846. ]);
  1847. });
  1848. it("gets annotations containing GoToE action (issue 8844)", async function () {
  1849. const loadingTask = getDocument(buildGetDocumentParams("issue8844.pdf"));
  1850. const pdfDoc = await loadingTask.promise;
  1851. const pdfPage = await pdfDoc.getPage(1);
  1852. const annotations = await pdfPage.getAnnotations();
  1853. expect(annotations.length).toEqual(1);
  1854. expect(annotations[0].annotationType).toEqual(AnnotationType.LINK);
  1855. const { filename, content } = annotations[0].attachment;
  1856. expect(filename).toEqual("man.pdf");
  1857. expect(content instanceof Uint8Array).toEqual(true);
  1858. expect(content.length).toEqual(4508);
  1859. await loadingTask.destroy();
  1860. });
  1861. it("gets text content", async function () {
  1862. const defaultPromise = page.getTextContent();
  1863. const parametersPromise = page.getTextContent({
  1864. disableCombineTextItems: true,
  1865. });
  1866. const data = await Promise.all([defaultPromise, parametersPromise]);
  1867. expect(!!data[0].items).toEqual(true);
  1868. expect(data[0].items.length).toEqual(15);
  1869. expect(!!data[0].styles).toEqual(true);
  1870. const page1 = mergeText(data[0].items);
  1871. expect(page1).toEqual(`Table Of Content
  1872. Chapter 1 .......................................................... 2
  1873. Paragraph 1.1 ...................................................... 3
  1874. page 1 / 3`);
  1875. expect(!!data[1].items).toEqual(true);
  1876. expect(data[1].items.length).toEqual(6);
  1877. expect(!!data[1].styles).toEqual(true);
  1878. });
  1879. it("gets text content, with correct properties (issue 8276)", async function () {
  1880. const loadingTask = getDocument(
  1881. buildGetDocumentParams("issue8276_reduced.pdf")
  1882. );
  1883. const pdfDoc = await loadingTask.promise;
  1884. const pdfPage = await pdfDoc.getPage(1);
  1885. const { items, styles } = await pdfPage.getTextContent();
  1886. expect(items.length).toEqual(1);
  1887. // Font name will be a random object id.
  1888. const fontName = items[0].fontName;
  1889. expect(Object.keys(styles)).toEqual([fontName]);
  1890. expect(items[0]).toEqual({
  1891. dir: "ltr",
  1892. fontName,
  1893. height: 18,
  1894. str: "Issue 8276",
  1895. transform: [18, 0, 0, 18, 441.81, 708.4499999999999],
  1896. width: 77.49,
  1897. hasEOL: false,
  1898. });
  1899. expect(styles[fontName]).toEqual({
  1900. fontFamily: "serif",
  1901. // `useSystemFonts` has a different value in web environments
  1902. // and in Node.js.
  1903. ascent: isNodeJS ? NaN : 0.683,
  1904. descent: isNodeJS ? NaN : -0.217,
  1905. vertical: false,
  1906. });
  1907. // Wait for font data to be loaded so we can check that the font names
  1908. // match.
  1909. await pdfPage.getOperatorList();
  1910. expect(pdfPage.commonObjs.has(fontName)).toEqual(true);
  1911. await loadingTask.destroy();
  1912. });
  1913. it("gets text content, with no extra spaces (issue 13226)", async function () {
  1914. const loadingTask = getDocument(buildGetDocumentParams("issue13226.pdf"));
  1915. const pdfDoc = await loadingTask.promise;
  1916. const pdfPage = await pdfDoc.getPage(1);
  1917. const { items } = await pdfPage.getTextContent();
  1918. const text = mergeText(items);
  1919. expect(text).toEqual(
  1920. "Mitarbeiterinnen und Mitarbeiter arbeiten in über 100 Ländern engagiert im Dienste"
  1921. );
  1922. await loadingTask.destroy();
  1923. });
  1924. it("gets text content, with merged spaces (issue 13201)", async function () {
  1925. const loadingTask = getDocument(buildGetDocumentParams("issue13201.pdf"));
  1926. const pdfDoc = await loadingTask.promise;
  1927. const pdfPage = await pdfDoc.getPage(1);
  1928. const { items } = await pdfPage.getTextContent();
  1929. const text = mergeText(items);
  1930. expect(
  1931. text.includes(
  1932. "Abstract. A purely peer-to-peer version of electronic cash would allow online"
  1933. )
  1934. ).toEqual(true);
  1935. expect(
  1936. text.includes(
  1937. "avoid mediating disputes. The cost of mediation increases transaction costs, limiting the"
  1938. )
  1939. ).toEqual(true);
  1940. expect(
  1941. text.includes(
  1942. "system is secure as long as honest nodes collectively control more CPU power than any"
  1943. )
  1944. ).toEqual(true);
  1945. await loadingTask.destroy();
  1946. });
  1947. it("gets text content, with no spaces between letters of words (issue 11913)", async function () {
  1948. const loadingTask = getDocument(buildGetDocumentParams("issue11913.pdf"));
  1949. const pdfDoc = await loadingTask.promise;
  1950. const pdfPage = await pdfDoc.getPage(1);
  1951. const { items } = await pdfPage.getTextContent();
  1952. const text = mergeText(items);
  1953. expect(
  1954. text.includes(
  1955. "1. The first of these cases arises from the tragic handicap which has blighted the life of the Plaintiff, and from the response of the"
  1956. )
  1957. ).toEqual(true);
  1958. expect(
  1959. text.includes(
  1960. "argued in this Court the appeal raises narrower, but important, issues which may be summarised as follows:-"
  1961. )
  1962. ).toEqual(true);
  1963. await loadingTask.destroy();
  1964. });
  1965. it("gets text content, with merged spaces (issue 10900)", async function () {
  1966. const loadingTask = getDocument(buildGetDocumentParams("issue10900.pdf"));
  1967. const pdfDoc = await loadingTask.promise;
  1968. const pdfPage = await pdfDoc.getPage(1);
  1969. const { items } = await pdfPage.getTextContent();
  1970. const text = mergeText(items);
  1971. expect(
  1972. text.includes(`3 3 3 3
  1973. 851.5 854.9 839.3 837.5
  1974. 633.6 727.8 789.9 796.2
  1975. 1,485.1 1,582.7 1,629.2 1,633.7
  1976. 114.2 121.7 125.3 130.7
  1977. 13.0x 13.0x 13.0x 12.5x`)
  1978. ).toEqual(true);
  1979. await loadingTask.destroy();
  1980. });
  1981. it("gets text content, with spaces (issue 10640)", async function () {
  1982. const loadingTask = getDocument(buildGetDocumentParams("issue10640.pdf"));
  1983. const pdfDoc = await loadingTask.promise;
  1984. const pdfPage = await pdfDoc.getPage(1);
  1985. const { items } = await pdfPage.getTextContent();
  1986. const text = mergeText(items);
  1987. expect(
  1988. text.includes(`Open Sans is a humanist sans serif typeface designed by Steve Matteson.
  1989. Open Sans was designed with an upright stress, open forms and a neu-
  1990. tral, yet friendly appearance. It was optimized for print, web, and mobile
  1991. interfaces, and has excellent legibility characteristics in its letterforms (see
  1992. figure \x81 on the following page). This font is available from the Google Font
  1993. Directory [\x81] as TrueType files licensed under the Apache License version \x82.\x80.
  1994. This package provides support for this font in LATEX. It includes Type \x81
  1995. versions of the fonts, converted for this package using FontForge from its
  1996. sources, for full support with Dvips.`)
  1997. ).toEqual(true);
  1998. await loadingTask.destroy();
  1999. });
  2000. it("gets text content, with negative spaces (bug 931481)", async function () {
  2001. if (isNodeJS) {
  2002. pending("Linked test-cases are not supported in Node.js.");
  2003. }
  2004. const loadingTask = getDocument(buildGetDocumentParams("bug931481.pdf"));
  2005. const pdfDoc = await loadingTask.promise;
  2006. const pdfPage = await pdfDoc.getPage(1);
  2007. const { items } = await pdfPage.getTextContent();
  2008. const text = mergeText(items);
  2009. expect(
  2010. text.includes(`Kathrin Nachbaur
  2011. Die promovierte Juristin ist 1979 in Graz geboren und aufgewachsen. Nach
  2012. erfolgreichem Studienabschluss mit Fokus auf Europarecht absolvierte sie ein
  2013. Praktikum bei Magna International in Kanada in der Human Resources Abteilung.
  2014. Anschliessend wurde sie geschult in Human Resources, Arbeitsrecht und
  2015. Kommunikation, währenddessen sie auch an ihrem Doktorat im Wirtschaftsrecht
  2016. arbeitete. Seither arbeitete sie bei Magna International als Projekt Manager in der
  2017. Innovationsabteilung. Seit 2009 ist sie Frank Stronachs Büroleiterin in Österreich und
  2018. Kanada. Zusätzlich ist sie seit 2012 Vice President, Business Development der
  2019. Stronach Group und Vizepräsidentin und Institutsleiterin des Stronach Institut für
  2020. sozialökonomische Gerechtigkeit.`)
  2021. ).toEqual(true);
  2022. await loadingTask.destroy();
  2023. });
  2024. it("gets text content, with invisible text marks (issue 9186)", async function () {
  2025. if (isNodeJS) {
  2026. pending("Linked test-cases are not supported in Node.js.");
  2027. }
  2028. const loadingTask = getDocument(buildGetDocumentParams("issue9186.pdf"));
  2029. const pdfDoc = await loadingTask.promise;
  2030. const pdfPage = await pdfDoc.getPage(1);
  2031. const { items } = await pdfPage.getTextContent();
  2032. const text = mergeText(items);
  2033. expect(
  2034. text.includes(`This Agreement (“Agreement”) is made as of this 25th day of January, 2017, by and
  2035. between EDWARD G. ATSINGER III, not individually but as sole Trustee of the ATSINGER
  2036. FAMILY TRUST /u/a dated October 31, 1980 as amended, and STUART W. EPPERSON, not
  2037. individually but solely as Trustee of the STUART W. EPPERSON REVOCABLE LIVING
  2038. TRUST /u/a dated January 14th 1993 as amended, collectively referred to herein as “Lessor”, and
  2039. Caron Broadcasting, Inc., an Ohio corporation (“Lessee”).`)
  2040. ).toEqual(true);
  2041. await loadingTask.destroy();
  2042. });
  2043. it("gets text content, with beginbfrange operator handled correctly (bug 1627427)", async function () {
  2044. const loadingTask = getDocument(
  2045. buildGetDocumentParams("bug1627427_reduced.pdf")
  2046. );
  2047. const pdfDoc = await loadingTask.promise;
  2048. const pdfPage = await pdfDoc.getPage(1);
  2049. const { items } = await pdfPage.getTextContent();
  2050. const text = mergeText(items);
  2051. expect(text).toEqual(
  2052. "침하게 흐린 품이 눈이 올 듯하더니 눈은 아니 오고 얼다가 만 비가 추"
  2053. );
  2054. await loadingTask.destroy();
  2055. });
  2056. it("gets text content, and check that out-of-page text is not present (bug 1755201)", async function () {
  2057. if (isNodeJS) {
  2058. pending("Linked test-cases are not supported in Node.js.");
  2059. }
  2060. const loadingTask = getDocument(buildGetDocumentParams("bug1755201.pdf"));
  2061. const pdfDoc = await loadingTask.promise;
  2062. const pdfPage = await pdfDoc.getPage(6);
  2063. const { items } = await pdfPage.getTextContent();
  2064. const text = mergeText(items);
  2065. expect(/win aisle/.test(text)).toEqual(false);
  2066. await loadingTask.destroy();
  2067. });
  2068. it("gets text content with or without includeMarkedContent, and compare (issue 15094)", async function () {
  2069. if (isNodeJS) {
  2070. pending("Linked test-cases are not supported in Node.js.");
  2071. }
  2072. const loadingTask = getDocument(buildGetDocumentParams("pdf.pdf"));
  2073. const pdfDoc = await loadingTask.promise;
  2074. const pdfPage = await pdfDoc.getPage(568);
  2075. let { items } = await pdfPage.getTextContent({
  2076. includeMarkedContent: false,
  2077. });
  2078. const textWithoutMC = mergeText(items);
  2079. ({ items } = await pdfPage.getTextContent({
  2080. includeMarkedContent: true,
  2081. }));
  2082. const textWithMC = mergeText(items);
  2083. expect(textWithoutMC).toEqual(textWithMC);
  2084. await loadingTask.destroy();
  2085. });
  2086. // TODO: Change this to a `text` reference test instead.
  2087. // Currently that doesn't work, since the `XMLSerializer` fails on
  2088. // the ASCII "control characters" found in the text-content.
  2089. it("gets text content with non-standard ligatures (issue issue15516)", async function () {
  2090. const loadingTask = getDocument(
  2091. buildGetDocumentParams("issue15516_reduced.pdf")
  2092. );
  2093. const pdfDoc = await loadingTask.promise;
  2094. const pdfPage = await pdfDoc.getPage(1);
  2095. const { items } = await pdfPage.getTextContent();
  2096. const text = mergeText(items);
  2097. expect(text).toEqual("ffi fi ffl ff fl \x07 \x08 Ý");
  2098. await loadingTask.destroy();
  2099. });
  2100. it("gets empty structure tree", async function () {
  2101. const tree = await page.getStructTree();
  2102. expect(tree).toEqual(null);
  2103. });
  2104. it("gets simple structure tree", async function () {
  2105. const loadingTask = getDocument(
  2106. buildGetDocumentParams("structure_simple.pdf")
  2107. );
  2108. const pdfDoc = await loadingTask.promise;
  2109. const pdfPage = await pdfDoc.getPage(1);
  2110. const tree = await pdfPage.getStructTree();
  2111. expect(tree).toEqual({
  2112. role: "Root",
  2113. children: [
  2114. {
  2115. role: "Document",
  2116. lang: "en-US",
  2117. children: [
  2118. {
  2119. role: "H1",
  2120. children: [
  2121. {
  2122. role: "NonStruct",
  2123. children: [{ type: "content", id: "page2R_mcid0" }],
  2124. },
  2125. ],
  2126. },
  2127. {
  2128. role: "P",
  2129. children: [
  2130. {
  2131. role: "NonStruct",
  2132. children: [{ type: "content", id: "page2R_mcid1" }],
  2133. },
  2134. ],
  2135. },
  2136. {
  2137. role: "H2",
  2138. children: [
  2139. {
  2140. role: "NonStruct",
  2141. children: [{ type: "content", id: "page2R_mcid2" }],
  2142. },
  2143. ],
  2144. },
  2145. {
  2146. role: "P",
  2147. children: [
  2148. {
  2149. role: "NonStruct",
  2150. children: [{ type: "content", id: "page2R_mcid3" }],
  2151. },
  2152. ],
  2153. },
  2154. ],
  2155. },
  2156. ],
  2157. });
  2158. await loadingTask.destroy();
  2159. });
  2160. it("gets operator list", async function () {
  2161. const operatorList = await page.getOperatorList();
  2162. expect(operatorList.fnArray.length).toBeGreaterThan(100);
  2163. expect(operatorList.argsArray.length).toBeGreaterThan(100);
  2164. expect(operatorList.lastChunk).toEqual(true);
  2165. expect(operatorList.separateAnnots).toEqual({
  2166. form: false,
  2167. canvas: false,
  2168. });
  2169. });
  2170. it("gets operatorList with JPEG image (issue 4888)", async function () {
  2171. const loadingTask = getDocument(buildGetDocumentParams("cmykjpeg.pdf"));
  2172. const pdfDoc = await loadingTask.promise;
  2173. const pdfPage = await pdfDoc.getPage(1);
  2174. const operatorList = await pdfPage.getOperatorList();
  2175. const imgIndex = operatorList.fnArray.indexOf(OPS.paintImageXObject);
  2176. const imgArgs = operatorList.argsArray[imgIndex];
  2177. const { data } = pdfPage.objs.get(imgArgs[0]);
  2178. expect(data instanceof Uint8ClampedArray).toEqual(true);
  2179. expect(data.length).toEqual(90000);
  2180. await loadingTask.destroy();
  2181. });
  2182. it(
  2183. "gets operatorList, from corrupt PDF file (issue 8702), " +
  2184. "with/without `stopAtErrors` set",
  2185. async function () {
  2186. const loadingTask1 = getDocument(
  2187. buildGetDocumentParams("issue8702.pdf", {
  2188. stopAtErrors: false, // The default value.
  2189. })
  2190. );
  2191. const loadingTask2 = getDocument(
  2192. buildGetDocumentParams("issue8702.pdf", {
  2193. stopAtErrors: true,
  2194. })
  2195. );
  2196. const result1 = loadingTask1.promise.then(pdfDoc => {
  2197. return pdfDoc.getPage(1).then(pdfPage => {
  2198. return pdfPage.getOperatorList().then(opList => {
  2199. expect(opList.fnArray.length).toBeGreaterThan(100);
  2200. expect(opList.argsArray.length).toBeGreaterThan(100);
  2201. expect(opList.lastChunk).toEqual(true);
  2202. expect(opList.separateAnnots).toEqual(null);
  2203. return loadingTask1.destroy();
  2204. });
  2205. });
  2206. });
  2207. const result2 = loadingTask2.promise.then(pdfDoc => {
  2208. return pdfDoc.getPage(1).then(pdfPage => {
  2209. return pdfPage.getOperatorList().then(opList => {
  2210. expect(opList.fnArray.length).toEqual(0);
  2211. expect(opList.argsArray.length).toEqual(0);
  2212. expect(opList.lastChunk).toEqual(true);
  2213. expect(opList.separateAnnots).toEqual(null);
  2214. return loadingTask2.destroy();
  2215. });
  2216. });
  2217. });
  2218. await Promise.all([result1, result2]);
  2219. }
  2220. );
  2221. it("gets operator list, containing Annotation-operatorLists", async function () {
  2222. const loadingTask = getDocument(
  2223. buildGetDocumentParams("annotation-line.pdf")
  2224. );
  2225. const pdfDoc = await loadingTask.promise;
  2226. const pdfPage = await pdfDoc.getPage(1);
  2227. const operatorList = await pdfPage.getOperatorList();
  2228. expect(operatorList.fnArray.length).toBeGreaterThan(20);
  2229. expect(operatorList.argsArray.length).toBeGreaterThan(20);
  2230. expect(operatorList.lastChunk).toEqual(true);
  2231. expect(operatorList.separateAnnots).toEqual({
  2232. form: false,
  2233. canvas: false,
  2234. });
  2235. // The `getOperatorList` method, similar to the `render` method,
  2236. // is supposed to include any existing Annotation-operatorLists.
  2237. expect(operatorList.fnArray.includes(OPS.beginAnnotation)).toEqual(true);
  2238. expect(operatorList.fnArray.includes(OPS.endAnnotation)).toEqual(true);
  2239. await loadingTask.destroy();
  2240. });
  2241. it("gets operator list, with `annotationMode`-option", async function () {
  2242. const loadingTask = getDocument(buildGetDocumentParams("evaljs.pdf"));
  2243. const pdfDoc = await loadingTask.promise;
  2244. const pdfPage = await pdfDoc.getPage(2);
  2245. pdfDoc.annotationStorage.setValue("30R", { value: "test" });
  2246. pdfDoc.annotationStorage.setValue("31R", { value: true });
  2247. const opListAnnotDisable = await pdfPage.getOperatorList({
  2248. annotationMode: AnnotationMode.DISABLE,
  2249. });
  2250. expect(opListAnnotDisable.fnArray.length).toEqual(0);
  2251. expect(opListAnnotDisable.argsArray.length).toEqual(0);
  2252. expect(opListAnnotDisable.lastChunk).toEqual(true);
  2253. expect(opListAnnotDisable.separateAnnots).toEqual(null);
  2254. const opListAnnotEnable = await pdfPage.getOperatorList({
  2255. annotationMode: AnnotationMode.ENABLE,
  2256. });
  2257. expect(opListAnnotEnable.fnArray.length).toBeGreaterThan(140);
  2258. expect(opListAnnotEnable.argsArray.length).toBeGreaterThan(140);
  2259. expect(opListAnnotEnable.lastChunk).toEqual(true);
  2260. expect(opListAnnotEnable.separateAnnots).toEqual({
  2261. form: false,
  2262. canvas: true,
  2263. });
  2264. let firstAnnotIndex = opListAnnotEnable.fnArray.indexOf(
  2265. OPS.beginAnnotation
  2266. );
  2267. let isUsingOwnCanvas = opListAnnotEnable.argsArray[firstAnnotIndex][4];
  2268. expect(isUsingOwnCanvas).toEqual(false);
  2269. const opListAnnotEnableForms = await pdfPage.getOperatorList({
  2270. annotationMode: AnnotationMode.ENABLE_FORMS,
  2271. });
  2272. expect(opListAnnotEnableForms.fnArray.length).toBeGreaterThan(30);
  2273. expect(opListAnnotEnableForms.argsArray.length).toBeGreaterThan(30);
  2274. expect(opListAnnotEnableForms.lastChunk).toEqual(true);
  2275. expect(opListAnnotEnableForms.separateAnnots).toEqual({
  2276. form: true,
  2277. canvas: true,
  2278. });
  2279. firstAnnotIndex = opListAnnotEnableForms.fnArray.indexOf(
  2280. OPS.beginAnnotation
  2281. );
  2282. isUsingOwnCanvas = opListAnnotEnableForms.argsArray[firstAnnotIndex][4];
  2283. expect(isUsingOwnCanvas).toEqual(true);
  2284. const opListAnnotEnableStorage = await pdfPage.getOperatorList({
  2285. annotationMode: AnnotationMode.ENABLE_STORAGE,
  2286. });
  2287. expect(opListAnnotEnableStorage.fnArray.length).toBeGreaterThan(170);
  2288. expect(opListAnnotEnableStorage.argsArray.length).toBeGreaterThan(170);
  2289. expect(opListAnnotEnableStorage.lastChunk).toEqual(true);
  2290. expect(opListAnnotEnableStorage.separateAnnots).toEqual({
  2291. form: false,
  2292. canvas: true,
  2293. });
  2294. firstAnnotIndex = opListAnnotEnableStorage.fnArray.indexOf(
  2295. OPS.beginAnnotation
  2296. );
  2297. isUsingOwnCanvas = opListAnnotEnableStorage.argsArray[firstAnnotIndex][4];
  2298. expect(isUsingOwnCanvas).toEqual(false);
  2299. // Sanity check to ensure that the `annotationMode` is correctly applied.
  2300. expect(opListAnnotDisable.fnArray.length).toBeLessThan(
  2301. opListAnnotEnableForms.fnArray.length
  2302. );
  2303. expect(opListAnnotEnableForms.fnArray.length).toBeLessThan(
  2304. opListAnnotEnable.fnArray.length
  2305. );
  2306. expect(opListAnnotEnable.fnArray.length).toBeLessThan(
  2307. opListAnnotEnableStorage.fnArray.length
  2308. );
  2309. await loadingTask.destroy();
  2310. });
  2311. it("gets operatorList, with page resources containing corrupt /CCITTFaxDecode data", async function () {
  2312. const loadingTask = getDocument(
  2313. buildGetDocumentParams("poppler-90-0-fuzzed.pdf")
  2314. );
  2315. expect(loadingTask instanceof PDFDocumentLoadingTask).toEqual(true);
  2316. const pdfDoc = await loadingTask.promise;
  2317. expect(pdfDoc.numPages).toEqual(16);
  2318. const pdfPage = await pdfDoc.getPage(6);
  2319. expect(pdfPage instanceof PDFPageProxy).toEqual(true);
  2320. const opList = await pdfPage.getOperatorList();
  2321. expect(opList.fnArray.length).toBeGreaterThan(25);
  2322. expect(opList.argsArray.length).toBeGreaterThan(25);
  2323. expect(opList.lastChunk).toEqual(true);
  2324. await loadingTask.destroy();
  2325. });
  2326. it("gets document stats after parsing page", async function () {
  2327. await page.getOperatorList();
  2328. const stats = pdfDocument.stats;
  2329. const expectedStreamTypes = {
  2330. [StreamType.FLATE]: true,
  2331. };
  2332. const expectedFontTypes = {
  2333. [FontType.TYPE1STANDARD]: true,
  2334. [FontType.CIDFONTTYPE2]: true,
  2335. };
  2336. expect(stats).toEqual({
  2337. streamTypes: expectedStreamTypes,
  2338. fontTypes: expectedFontTypes,
  2339. });
  2340. });
  2341. it("gets page stats after parsing page, without `pdfBug` set", async function () {
  2342. await page.getOperatorList();
  2343. expect(page.stats).toEqual(null);
  2344. });
  2345. it("gets page stats after parsing page, with `pdfBug` set", async function () {
  2346. const loadingTask = getDocument(
  2347. buildGetDocumentParams(basicApiFileName, { pdfBug: true })
  2348. );
  2349. const pdfDoc = await loadingTask.promise;
  2350. const pdfPage = await pdfDoc.getPage(1);
  2351. await pdfPage.getOperatorList();
  2352. const stats = pdfPage.stats;
  2353. expect(stats instanceof StatTimer).toEqual(true);
  2354. expect(stats.times.length).toEqual(1);
  2355. const [statEntry] = stats.times;
  2356. expect(statEntry.name).toEqual("Page Request");
  2357. expect(statEntry.end - statEntry.start).toBeGreaterThanOrEqual(0);
  2358. await loadingTask.destroy();
  2359. });
  2360. it("gets page stats after rendering page, with `pdfBug` set", async function () {
  2361. const loadingTask = getDocument(
  2362. buildGetDocumentParams(basicApiFileName, { pdfBug: true })
  2363. );
  2364. const pdfDoc = await loadingTask.promise;
  2365. const pdfPage = await pdfDoc.getPage(1);
  2366. const viewport = pdfPage.getViewport({ scale: 1 });
  2367. expect(viewport instanceof PageViewport).toEqual(true);
  2368. const canvasAndCtx = CanvasFactory.create(
  2369. viewport.width,
  2370. viewport.height
  2371. );
  2372. const renderTask = pdfPage.render({
  2373. canvasContext: canvasAndCtx.context,
  2374. canvasFactory: CanvasFactory,
  2375. viewport,
  2376. });
  2377. expect(renderTask instanceof RenderTask).toEqual(true);
  2378. await renderTask.promise;
  2379. expect(renderTask.separateAnnots).toEqual(false);
  2380. const { stats } = pdfPage;
  2381. expect(stats instanceof StatTimer).toEqual(true);
  2382. expect(stats.times.length).toEqual(3);
  2383. const [statEntryOne, statEntryTwo, statEntryThree] = stats.times;
  2384. expect(statEntryOne.name).toEqual("Page Request");
  2385. expect(statEntryOne.end - statEntryOne.start).toBeGreaterThanOrEqual(0);
  2386. expect(statEntryTwo.name).toEqual("Rendering");
  2387. expect(statEntryTwo.end - statEntryTwo.start).toBeGreaterThan(0);
  2388. expect(statEntryThree.name).toEqual("Overall");
  2389. expect(statEntryThree.end - statEntryThree.start).toBeGreaterThan(0);
  2390. CanvasFactory.destroy(canvasAndCtx);
  2391. await loadingTask.destroy();
  2392. });
  2393. it("cancels rendering of page", async function () {
  2394. const viewport = page.getViewport({ scale: 1 });
  2395. expect(viewport instanceof PageViewport).toEqual(true);
  2396. const canvasAndCtx = CanvasFactory.create(
  2397. viewport.width,
  2398. viewport.height
  2399. );
  2400. const renderTask = page.render({
  2401. canvasContext: canvasAndCtx.context,
  2402. canvasFactory: CanvasFactory,
  2403. viewport,
  2404. });
  2405. expect(renderTask instanceof RenderTask).toEqual(true);
  2406. renderTask.cancel();
  2407. try {
  2408. await renderTask.promise;
  2409. // Shouldn't get here.
  2410. expect(false).toEqual(true);
  2411. } catch (reason) {
  2412. expect(reason instanceof RenderingCancelledException).toEqual(true);
  2413. expect(reason.message).toEqual("Rendering cancelled, page 1");
  2414. expect(reason.type).toEqual("canvas");
  2415. expect(reason.extraDelay).toEqual(0);
  2416. }
  2417. CanvasFactory.destroy(canvasAndCtx);
  2418. });
  2419. it("re-render page, using the same canvas, after cancelling rendering", async function () {
  2420. const viewport = page.getViewport({ scale: 1 });
  2421. expect(viewport instanceof PageViewport).toEqual(true);
  2422. const canvasAndCtx = CanvasFactory.create(
  2423. viewport.width,
  2424. viewport.height
  2425. );
  2426. const renderTask = page.render({
  2427. canvasContext: canvasAndCtx.context,
  2428. canvasFactory: CanvasFactory,
  2429. viewport,
  2430. });
  2431. expect(renderTask instanceof RenderTask).toEqual(true);
  2432. renderTask.cancel();
  2433. try {
  2434. await renderTask.promise;
  2435. // Shouldn't get here.
  2436. expect(false).toEqual(true);
  2437. } catch (reason) {
  2438. expect(reason instanceof RenderingCancelledException).toEqual(true);
  2439. }
  2440. const reRenderTask = page.render({
  2441. canvasContext: canvasAndCtx.context,
  2442. canvasFactory: CanvasFactory,
  2443. viewport,
  2444. });
  2445. expect(reRenderTask instanceof RenderTask).toEqual(true);
  2446. await reRenderTask.promise;
  2447. expect(reRenderTask.separateAnnots).toEqual(false);
  2448. CanvasFactory.destroy(canvasAndCtx);
  2449. });
  2450. it("multiple render() on the same canvas", async function () {
  2451. const optionalContentConfigPromise =
  2452. pdfDocument.getOptionalContentConfig();
  2453. const viewport = page.getViewport({ scale: 1 });
  2454. expect(viewport instanceof PageViewport).toEqual(true);
  2455. const canvasAndCtx = CanvasFactory.create(
  2456. viewport.width,
  2457. viewport.height
  2458. );
  2459. const renderTask1 = page.render({
  2460. canvasContext: canvasAndCtx.context,
  2461. canvasFactory: CanvasFactory,
  2462. viewport,
  2463. optionalContentConfigPromise,
  2464. });
  2465. expect(renderTask1 instanceof RenderTask).toEqual(true);
  2466. const renderTask2 = page.render({
  2467. canvasContext: canvasAndCtx.context,
  2468. canvasFactory: CanvasFactory,
  2469. viewport,
  2470. optionalContentConfigPromise,
  2471. });
  2472. expect(renderTask2 instanceof RenderTask).toEqual(true);
  2473. await Promise.all([
  2474. renderTask1.promise,
  2475. renderTask2.promise.then(
  2476. () => {
  2477. // Shouldn't get here.
  2478. expect(false).toEqual(true);
  2479. },
  2480. reason => {
  2481. // It fails because we are already using this canvas.
  2482. expect(/multiple render\(\)/.test(reason.message)).toEqual(true);
  2483. }
  2484. ),
  2485. ]);
  2486. });
  2487. it("cleans up document resources after rendering of page", async function () {
  2488. const loadingTask = getDocument(buildGetDocumentParams(basicApiFileName));
  2489. const pdfDoc = await loadingTask.promise;
  2490. const pdfPage = await pdfDoc.getPage(1);
  2491. const viewport = pdfPage.getViewport({ scale: 1 });
  2492. expect(viewport instanceof PageViewport).toEqual(true);
  2493. const canvasAndCtx = CanvasFactory.create(
  2494. viewport.width,
  2495. viewport.height
  2496. );
  2497. const renderTask = pdfPage.render({
  2498. canvasContext: canvasAndCtx.context,
  2499. canvasFactory: CanvasFactory,
  2500. viewport,
  2501. });
  2502. expect(renderTask instanceof RenderTask).toEqual(true);
  2503. await renderTask.promise;
  2504. expect(renderTask.separateAnnots).toEqual(false);
  2505. await pdfDoc.cleanup();
  2506. expect(true).toEqual(true);
  2507. CanvasFactory.destroy(canvasAndCtx);
  2508. await loadingTask.destroy();
  2509. });
  2510. it("cleans up document resources during rendering of page", async function () {
  2511. const loadingTask = getDocument(
  2512. buildGetDocumentParams("tracemonkey.pdf")
  2513. );
  2514. const pdfDoc = await loadingTask.promise;
  2515. const pdfPage = await pdfDoc.getPage(1);
  2516. const viewport = pdfPage.getViewport({ scale: 1 });
  2517. expect(viewport instanceof PageViewport).toEqual(true);
  2518. const canvasAndCtx = CanvasFactory.create(
  2519. viewport.width,
  2520. viewport.height
  2521. );
  2522. const renderTask = pdfPage.render({
  2523. canvasContext: canvasAndCtx.context,
  2524. canvasFactory: CanvasFactory,
  2525. viewport,
  2526. });
  2527. expect(renderTask instanceof RenderTask).toEqual(true);
  2528. // Ensure that clean-up runs during rendering.
  2529. renderTask.onContinue = function (cont) {
  2530. waitSome(cont);
  2531. };
  2532. try {
  2533. await pdfDoc.cleanup();
  2534. // Shouldn't get here.
  2535. expect(false).toEqual(true);
  2536. } catch (reason) {
  2537. expect(reason instanceof Error).toEqual(true);
  2538. expect(reason.message).toEqual(
  2539. "startCleanup: Page 1 is currently rendering."
  2540. );
  2541. }
  2542. await renderTask.promise;
  2543. expect(renderTask.separateAnnots).toEqual(false);
  2544. CanvasFactory.destroy(canvasAndCtx);
  2545. await loadingTask.destroy();
  2546. });
  2547. it("caches image resources at the document/page level as expected (issue 11878)", async function () {
  2548. const { NUM_PAGES_THRESHOLD } = GlobalImageCache,
  2549. EXPECTED_WIDTH = 2550,
  2550. EXPECTED_HEIGHT = 3300;
  2551. const loadingTask = getDocument(buildGetDocumentParams("issue11878.pdf"));
  2552. const pdfDoc = await loadingTask.promise;
  2553. let firstImgData = null;
  2554. for (let i = 1; i <= pdfDoc.numPages; i++) {
  2555. const pdfPage = await pdfDoc.getPage(i);
  2556. const opList = await pdfPage.getOperatorList();
  2557. const { commonObjs, objs } = pdfPage;
  2558. const imgIndex = opList.fnArray.indexOf(OPS.paintImageXObject);
  2559. const [objId, width, height] = opList.argsArray[imgIndex];
  2560. if (i < NUM_PAGES_THRESHOLD) {
  2561. expect(objId).toEqual(`img_p${i - 1}_1`);
  2562. expect(objs.has(objId)).toEqual(true);
  2563. expect(commonObjs.has(objId)).toEqual(false);
  2564. } else {
  2565. expect(objId).toEqual(
  2566. `g_${loadingTask.docId}_img_p${NUM_PAGES_THRESHOLD - 1}_1`
  2567. );
  2568. expect(objs.has(objId)).toEqual(false);
  2569. expect(commonObjs.has(objId)).toEqual(true);
  2570. }
  2571. expect(width).toEqual(EXPECTED_WIDTH);
  2572. expect(height).toEqual(EXPECTED_HEIGHT);
  2573. // Ensure that the actual image data is identical for all pages.
  2574. if (i === 1) {
  2575. firstImgData = objs.get(objId);
  2576. expect(firstImgData.width).toEqual(EXPECTED_WIDTH);
  2577. expect(firstImgData.height).toEqual(EXPECTED_HEIGHT);
  2578. expect(firstImgData.kind).toEqual(ImageKind.RGB_24BPP);
  2579. expect(firstImgData.data instanceof Uint8ClampedArray).toEqual(true);
  2580. expect(firstImgData.data.length).toEqual(25245000);
  2581. } else {
  2582. const objsPool = i >= NUM_PAGES_THRESHOLD ? commonObjs : objs;
  2583. const currentImgData = objsPool.get(objId);
  2584. expect(currentImgData.width).toEqual(firstImgData.width);
  2585. expect(currentImgData.height).toEqual(firstImgData.height);
  2586. expect(currentImgData.kind).toEqual(firstImgData.kind);
  2587. expect(currentImgData.data instanceof Uint8ClampedArray).toEqual(
  2588. true
  2589. );
  2590. expect(
  2591. currentImgData.data.every((value, index) => {
  2592. return value === firstImgData.data[index];
  2593. })
  2594. ).toEqual(true);
  2595. }
  2596. }
  2597. await loadingTask.destroy();
  2598. firstImgData = null;
  2599. });
  2600. it("render for printing, with `printAnnotationStorage` set", async function () {
  2601. async function getPrintData(printAnnotationStorage = null) {
  2602. const canvasAndCtx = CanvasFactory.create(
  2603. viewport.width,
  2604. viewport.height
  2605. );
  2606. const renderTask = pdfPage.render({
  2607. canvasContext: canvasAndCtx.context,
  2608. canvasFactory: CanvasFactory,
  2609. viewport,
  2610. intent: "print",
  2611. annotationMode: AnnotationMode.ENABLE_STORAGE,
  2612. printAnnotationStorage,
  2613. });
  2614. await renderTask.promise;
  2615. expect(renderTask.separateAnnots).toEqual(false);
  2616. const printData = canvasAndCtx.canvas.toDataURL();
  2617. CanvasFactory.destroy(canvasAndCtx);
  2618. return printData;
  2619. }
  2620. const loadingTask = getDocument(
  2621. buildGetDocumentParams("annotation-tx.pdf")
  2622. );
  2623. const pdfDoc = await loadingTask.promise;
  2624. const pdfPage = await pdfDoc.getPage(1);
  2625. const viewport = pdfPage.getViewport({ scale: 1 });
  2626. // Update the contents of the form-field.
  2627. const { annotationStorage } = pdfDoc;
  2628. annotationStorage.setValue("22R", { value: "Hello World" });
  2629. // Render for printing, with default parameters.
  2630. const printOriginalData = await getPrintData();
  2631. // Get the *frozen* print-storage for use during printing.
  2632. const printAnnotationStorage = annotationStorage.print;
  2633. // Update the contents of the form-field again.
  2634. annotationStorage.setValue("22R", { value: "Printing again..." });
  2635. const annotationHash = AnnotationStorage.getHash(
  2636. annotationStorage.serializable
  2637. );
  2638. const printAnnotationHash = AnnotationStorage.getHash(
  2639. printAnnotationStorage.serializable
  2640. );
  2641. // Sanity check to ensure that the print-storage didn't change,
  2642. // after the form-field was updated.
  2643. expect(printAnnotationHash).not.toEqual(annotationHash);
  2644. // Render for printing again, after updating the form-field,
  2645. // with default parameters.
  2646. const printAgainData = await getPrintData();
  2647. // Render for printing again, after updating the form-field,
  2648. // with `printAnnotationStorage` set.
  2649. const printStorageData = await getPrintData(printAnnotationStorage);
  2650. // Ensure that printing again, with default parameters,
  2651. // actually uses the "new" form-field data.
  2652. expect(printAgainData).not.toEqual(printOriginalData);
  2653. // Finally ensure that printing, with `printAnnotationStorage` set,
  2654. // still uses the "previous" form-field data.
  2655. expect(printStorageData).toEqual(printOriginalData);
  2656. await loadingTask.destroy();
  2657. });
  2658. });
  2659. describe("Multiple `getDocument` instances", function () {
  2660. // Regression test for https://github.com/mozilla/pdf.js/issues/6205
  2661. // A PDF using the Helvetica font.
  2662. const pdf1 = buildGetDocumentParams("tracemonkey.pdf");
  2663. // A PDF using the Times font.
  2664. const pdf2 = buildGetDocumentParams("TAMReview.pdf");
  2665. // A PDF using the Arial font.
  2666. const pdf3 = buildGetDocumentParams("issue6068.pdf");
  2667. const loadingTasks = [];
  2668. // Render the first page of the given PDF file.
  2669. // Fulfills the promise with the base64-encoded version of the PDF.
  2670. async function renderPDF(filename) {
  2671. const loadingTask = getDocument(filename);
  2672. loadingTasks.push(loadingTask);
  2673. const pdf = await loadingTask.promise;
  2674. const page = await pdf.getPage(1);
  2675. const viewport = page.getViewport({ scale: 1.2 });
  2676. expect(viewport instanceof PageViewport).toEqual(true);
  2677. const canvasAndCtx = CanvasFactory.create(
  2678. viewport.width,
  2679. viewport.height
  2680. );
  2681. const renderTask = page.render({
  2682. canvasContext: canvasAndCtx.context,
  2683. canvasFactory: CanvasFactory,
  2684. viewport,
  2685. });
  2686. await renderTask.promise;
  2687. expect(renderTask.separateAnnots).toEqual(false);
  2688. const data = canvasAndCtx.canvas.toDataURL();
  2689. CanvasFactory.destroy(canvasAndCtx);
  2690. return data;
  2691. }
  2692. afterEach(async function () {
  2693. // Issue 6205 reported an issue with font rendering, so clear the loaded
  2694. // fonts so that we can see whether loading PDFs in parallel does not
  2695. // cause any issues with the rendered fonts.
  2696. const destroyPromises = loadingTasks.map(function (loadingTask) {
  2697. return loadingTask.destroy();
  2698. });
  2699. await Promise.all(destroyPromises);
  2700. });
  2701. it("should correctly render PDFs in parallel", async function () {
  2702. let baseline1, baseline2, baseline3;
  2703. const promiseDone = renderPDF(pdf1)
  2704. .then(function (data1) {
  2705. baseline1 = data1;
  2706. return renderPDF(pdf2);
  2707. })
  2708. .then(function (data2) {
  2709. baseline2 = data2;
  2710. return renderPDF(pdf3);
  2711. })
  2712. .then(function (data3) {
  2713. baseline3 = data3;
  2714. return Promise.all([
  2715. renderPDF(pdf1),
  2716. renderPDF(pdf2),
  2717. renderPDF(pdf3),
  2718. ]);
  2719. })
  2720. .then(function (dataUrls) {
  2721. expect(dataUrls[0]).toEqual(baseline1);
  2722. expect(dataUrls[1]).toEqual(baseline2);
  2723. expect(dataUrls[2]).toEqual(baseline3);
  2724. return true;
  2725. });
  2726. await promiseDone;
  2727. });
  2728. });
  2729. describe("PDFDataRangeTransport", function () {
  2730. let dataPromise;
  2731. beforeAll(function () {
  2732. const fileName = "tracemonkey.pdf";
  2733. dataPromise = DefaultFileReaderFactory.fetch({
  2734. path: TEST_PDFS_PATH + fileName,
  2735. });
  2736. });
  2737. afterAll(function () {
  2738. dataPromise = null;
  2739. });
  2740. it("should fetch document info and page using ranges", async function () {
  2741. const initialDataLength = 4000;
  2742. let fetches = 0;
  2743. const data = await dataPromise;
  2744. const initialData = data.subarray(0, initialDataLength);
  2745. const transport = new PDFDataRangeTransport(data.length, initialData);
  2746. transport.requestDataRange = function (begin, end) {
  2747. fetches++;
  2748. waitSome(function () {
  2749. transport.onDataProgress(4000);
  2750. transport.onDataRange(begin, data.subarray(begin, end));
  2751. });
  2752. };
  2753. const loadingTask = getDocument(transport);
  2754. const pdfDocument = await loadingTask.promise;
  2755. expect(pdfDocument.numPages).toEqual(14);
  2756. const pdfPage = await pdfDocument.getPage(10);
  2757. expect(pdfPage.rotate).toEqual(0);
  2758. expect(fetches).toBeGreaterThan(2);
  2759. await loadingTask.destroy();
  2760. });
  2761. it("should fetch document info and page using range and streaming", async function () {
  2762. const initialDataLength = 4000;
  2763. let fetches = 0;
  2764. const data = await dataPromise;
  2765. const initialData = data.subarray(0, initialDataLength);
  2766. const transport = new PDFDataRangeTransport(data.length, initialData);
  2767. transport.requestDataRange = function (begin, end) {
  2768. fetches++;
  2769. if (fetches === 1) {
  2770. // Send rest of the data on first range request.
  2771. transport.onDataProgressiveRead(data.subarray(initialDataLength));
  2772. }
  2773. waitSome(function () {
  2774. transport.onDataRange(begin, data.subarray(begin, end));
  2775. });
  2776. };
  2777. const loadingTask = getDocument(transport);
  2778. const pdfDocument = await loadingTask.promise;
  2779. expect(pdfDocument.numPages).toEqual(14);
  2780. const pdfPage = await pdfDocument.getPage(10);
  2781. expect(pdfPage.rotate).toEqual(0);
  2782. expect(fetches).toEqual(1);
  2783. await new Promise(resolve => {
  2784. waitSome(resolve);
  2785. });
  2786. await loadingTask.destroy();
  2787. });
  2788. it(
  2789. "should fetch document info and page, without range, " +
  2790. "using complete initialData",
  2791. async function () {
  2792. let fetches = 0;
  2793. const data = await dataPromise;
  2794. const transport = new PDFDataRangeTransport(
  2795. data.length,
  2796. data,
  2797. /* progressiveDone = */ true
  2798. );
  2799. transport.requestDataRange = function (begin, end) {
  2800. fetches++;
  2801. };
  2802. const loadingTask = getDocument({
  2803. disableRange: true,
  2804. range: transport,
  2805. });
  2806. const pdfDocument = await loadingTask.promise;
  2807. expect(pdfDocument.numPages).toEqual(14);
  2808. const pdfPage = await pdfDocument.getPage(10);
  2809. expect(pdfPage.rotate).toEqual(0);
  2810. expect(fetches).toEqual(0);
  2811. await loadingTask.destroy();
  2812. }
  2813. );
  2814. });
  2815. describe("PDFWorkerUtil", function () {
  2816. describe("isSameOrigin", function () {
  2817. const { isSameOrigin } = PDFWorkerUtil;
  2818. it("handles invalid base URLs", function () {
  2819. // The base URL is not valid.
  2820. expect(isSameOrigin("/foo", "/bar")).toEqual(false);
  2821. // The base URL has no origin.
  2822. expect(isSameOrigin("blob:foo", "/bar")).toEqual(false);
  2823. });
  2824. it("correctly checks if the origin of both URLs matches", function () {
  2825. expect(
  2826. isSameOrigin(
  2827. "https://www.mozilla.org/foo",
  2828. "https://www.mozilla.org/bar"
  2829. )
  2830. ).toEqual(true);
  2831. expect(
  2832. isSameOrigin(
  2833. "https://www.mozilla.org/foo",
  2834. "https://www.example.com/bar"
  2835. )
  2836. ).toEqual(false);
  2837. });
  2838. });
  2839. });
  2840. });