obj.js 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2020 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * Javascript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.FileSpec = exports.XRef = exports.ObjectLoader = exports.Catalog = void 0;
  27. var _util = require("../shared/util.js");
  28. var _primitives = require("./primitives.js");
  29. var _parser = require("./parser.js");
  30. var _core_utils = require("./core_utils.js");
  31. var _crypto = require("./crypto.js");
  32. var _colorspace = require("./colorspace.js");
  33. function fetchDestination(dest) {
  34. return (0, _primitives.isDict)(dest) ? dest.get("D") : dest;
  35. }
  36. class Catalog {
  37. constructor(pdfManager, xref) {
  38. this.pdfManager = pdfManager;
  39. this.xref = xref;
  40. this.catDict = xref.getCatalogObj();
  41. if (!(0, _primitives.isDict)(this.catDict)) {
  42. throw new _util.FormatError("Catalog object is not a dictionary.");
  43. }
  44. this.fontCache = new _primitives.RefSetCache();
  45. this.builtInCMapCache = new Map();
  46. this.pageKidsCountCache = new _primitives.RefSetCache();
  47. }
  48. get metadata() {
  49. const streamRef = this.catDict.getRaw("Metadata");
  50. if (!(0, _primitives.isRef)(streamRef)) {
  51. return (0, _util.shadow)(this, "metadata", null);
  52. }
  53. const suppressEncryption = !(this.xref.encrypt && this.xref.encrypt.encryptMetadata);
  54. const stream = this.xref.fetch(streamRef, suppressEncryption);
  55. let metadata;
  56. if (stream && (0, _primitives.isDict)(stream.dict)) {
  57. const type = stream.dict.get("Type");
  58. const subtype = stream.dict.get("Subtype");
  59. if ((0, _primitives.isName)(type, "Metadata") && (0, _primitives.isName)(subtype, "XML")) {
  60. try {
  61. metadata = (0, _util.stringToUTF8String)((0, _util.bytesToString)(stream.getBytes()));
  62. } catch (e) {
  63. if (e instanceof _core_utils.MissingDataException) {
  64. throw e;
  65. }
  66. (0, _util.info)("Skipping invalid metadata.");
  67. }
  68. }
  69. }
  70. return (0, _util.shadow)(this, "metadata", metadata);
  71. }
  72. get toplevelPagesDict() {
  73. const pagesObj = this.catDict.get("Pages");
  74. if (!(0, _primitives.isDict)(pagesObj)) {
  75. throw new _util.FormatError("Invalid top-level pages dictionary.");
  76. }
  77. return (0, _util.shadow)(this, "toplevelPagesDict", pagesObj);
  78. }
  79. get documentOutline() {
  80. let obj = null;
  81. try {
  82. obj = this._readDocumentOutline();
  83. } catch (ex) {
  84. if (ex instanceof _core_utils.MissingDataException) {
  85. throw ex;
  86. }
  87. (0, _util.warn)("Unable to read document outline.");
  88. }
  89. return (0, _util.shadow)(this, "documentOutline", obj);
  90. }
  91. _readDocumentOutline() {
  92. let obj = this.catDict.get("Outlines");
  93. if (!(0, _primitives.isDict)(obj)) {
  94. return null;
  95. }
  96. obj = obj.getRaw("First");
  97. if (!(0, _primitives.isRef)(obj)) {
  98. return null;
  99. }
  100. const root = {
  101. items: []
  102. };
  103. const queue = [{
  104. obj,
  105. parent: root
  106. }];
  107. const processed = new _primitives.RefSet();
  108. processed.put(obj);
  109. const xref = this.xref,
  110. blackColor = new Uint8ClampedArray(3);
  111. while (queue.length > 0) {
  112. const i = queue.shift();
  113. const outlineDict = xref.fetchIfRef(i.obj);
  114. if (outlineDict === null) {
  115. continue;
  116. }
  117. if (!outlineDict.has("Title")) {
  118. throw new _util.FormatError("Invalid outline item encountered.");
  119. }
  120. const data = {
  121. url: null,
  122. dest: null
  123. };
  124. Catalog.parseDestDictionary({
  125. destDict: outlineDict,
  126. resultObj: data,
  127. docBaseUrl: this.pdfManager.docBaseUrl
  128. });
  129. const title = outlineDict.get("Title");
  130. const flags = outlineDict.get("F") || 0;
  131. const color = outlineDict.getArray("C");
  132. const count = outlineDict.get("Count");
  133. let rgbColor = blackColor;
  134. if (Array.isArray(color) && color.length === 3 && (color[0] !== 0 || color[1] !== 0 || color[2] !== 0)) {
  135. rgbColor = _colorspace.ColorSpace.singletons.rgb.getRgb(color, 0);
  136. }
  137. const outlineItem = {
  138. dest: data.dest,
  139. url: data.url,
  140. unsafeUrl: data.unsafeUrl,
  141. newWindow: data.newWindow,
  142. title: (0, _util.stringToPDFString)(title),
  143. color: rgbColor,
  144. count: Number.isInteger(count) ? count : undefined,
  145. bold: !!(flags & 2),
  146. italic: !!(flags & 1),
  147. items: []
  148. };
  149. i.parent.items.push(outlineItem);
  150. obj = outlineDict.getRaw("First");
  151. if ((0, _primitives.isRef)(obj) && !processed.has(obj)) {
  152. queue.push({
  153. obj,
  154. parent: outlineItem
  155. });
  156. processed.put(obj);
  157. }
  158. obj = outlineDict.getRaw("Next");
  159. if ((0, _primitives.isRef)(obj) && !processed.has(obj)) {
  160. queue.push({
  161. obj,
  162. parent: i.parent
  163. });
  164. processed.put(obj);
  165. }
  166. }
  167. return root.items.length > 0 ? root.items : null;
  168. }
  169. get permissions() {
  170. let permissions = null;
  171. try {
  172. permissions = this._readPermissions();
  173. } catch (ex) {
  174. if (ex instanceof _core_utils.MissingDataException) {
  175. throw ex;
  176. }
  177. (0, _util.warn)("Unable to read permissions.");
  178. }
  179. return (0, _util.shadow)(this, "permissions", permissions);
  180. }
  181. _readPermissions() {
  182. const encrypt = this.xref.trailer.get("Encrypt");
  183. if (!(0, _primitives.isDict)(encrypt)) {
  184. return null;
  185. }
  186. let flags = encrypt.get("P");
  187. if (!(0, _util.isNum)(flags)) {
  188. return null;
  189. }
  190. flags += 2 ** 32;
  191. const permissions = [];
  192. for (const key in _util.PermissionFlag) {
  193. const value = _util.PermissionFlag[key];
  194. if (flags & value) {
  195. permissions.push(value);
  196. }
  197. }
  198. return permissions;
  199. }
  200. get numPages() {
  201. const obj = this.toplevelPagesDict.get("Count");
  202. if (!Number.isInteger(obj)) {
  203. throw new _util.FormatError("Page count in top-level pages dictionary is not an integer.");
  204. }
  205. return (0, _util.shadow)(this, "numPages", obj);
  206. }
  207. get destinations() {
  208. const obj = this._readDests(),
  209. dests = Object.create(null);
  210. if (obj instanceof NameTree) {
  211. const names = obj.getAll();
  212. for (const name in names) {
  213. dests[name] = fetchDestination(names[name]);
  214. }
  215. } else if (obj instanceof _primitives.Dict) {
  216. obj.forEach(function (key, value) {
  217. if (value) {
  218. dests[key] = fetchDestination(value);
  219. }
  220. });
  221. }
  222. return (0, _util.shadow)(this, "destinations", dests);
  223. }
  224. getDestination(destinationId) {
  225. const obj = this._readDests();
  226. if (obj instanceof NameTree || obj instanceof _primitives.Dict) {
  227. return fetchDestination(obj.get(destinationId) || null);
  228. }
  229. return null;
  230. }
  231. _readDests() {
  232. const obj = this.catDict.get("Names");
  233. if (obj && obj.has("Dests")) {
  234. return new NameTree(obj.getRaw("Dests"), this.xref);
  235. } else if (this.catDict.has("Dests")) {
  236. return this.catDict.get("Dests");
  237. }
  238. return undefined;
  239. }
  240. get pageLabels() {
  241. let obj = null;
  242. try {
  243. obj = this._readPageLabels();
  244. } catch (ex) {
  245. if (ex instanceof _core_utils.MissingDataException) {
  246. throw ex;
  247. }
  248. (0, _util.warn)("Unable to read page labels.");
  249. }
  250. return (0, _util.shadow)(this, "pageLabels", obj);
  251. }
  252. _readPageLabels() {
  253. const obj = this.catDict.getRaw("PageLabels");
  254. if (!obj) {
  255. return null;
  256. }
  257. const pageLabels = new Array(this.numPages);
  258. let style = null,
  259. prefix = "";
  260. const numberTree = new NumberTree(obj, this.xref);
  261. const nums = numberTree.getAll();
  262. let currentLabel = "",
  263. currentIndex = 1;
  264. for (let i = 0, ii = this.numPages; i < ii; i++) {
  265. if (i in nums) {
  266. const labelDict = nums[i];
  267. if (!(0, _primitives.isDict)(labelDict)) {
  268. throw new _util.FormatError("PageLabel is not a dictionary.");
  269. }
  270. if (labelDict.has("Type") && !(0, _primitives.isName)(labelDict.get("Type"), "PageLabel")) {
  271. throw new _util.FormatError("Invalid type in PageLabel dictionary.");
  272. }
  273. if (labelDict.has("S")) {
  274. const s = labelDict.get("S");
  275. if (!(0, _primitives.isName)(s)) {
  276. throw new _util.FormatError("Invalid style in PageLabel dictionary.");
  277. }
  278. style = s.name;
  279. } else {
  280. style = null;
  281. }
  282. if (labelDict.has("P")) {
  283. const p = labelDict.get("P");
  284. if (!(0, _util.isString)(p)) {
  285. throw new _util.FormatError("Invalid prefix in PageLabel dictionary.");
  286. }
  287. prefix = (0, _util.stringToPDFString)(p);
  288. } else {
  289. prefix = "";
  290. }
  291. if (labelDict.has("St")) {
  292. const st = labelDict.get("St");
  293. if (!(Number.isInteger(st) && st >= 1)) {
  294. throw new _util.FormatError("Invalid start in PageLabel dictionary.");
  295. }
  296. currentIndex = st;
  297. } else {
  298. currentIndex = 1;
  299. }
  300. }
  301. switch (style) {
  302. case "D":
  303. currentLabel = currentIndex;
  304. break;
  305. case "R":
  306. case "r":
  307. currentLabel = (0, _core_utils.toRomanNumerals)(currentIndex, style === "r");
  308. break;
  309. case "A":
  310. case "a":
  311. const LIMIT = 26;
  312. const A_UPPER_CASE = 0x41,
  313. A_LOWER_CASE = 0x61;
  314. const baseCharCode = style === "a" ? A_LOWER_CASE : A_UPPER_CASE;
  315. const letterIndex = currentIndex - 1;
  316. const character = String.fromCharCode(baseCharCode + letterIndex % LIMIT);
  317. const charBuf = [];
  318. for (let j = 0, jj = letterIndex / LIMIT | 0; j <= jj; j++) {
  319. charBuf.push(character);
  320. }
  321. currentLabel = charBuf.join("");
  322. break;
  323. default:
  324. if (style) {
  325. throw new _util.FormatError(`Invalid style "${style}" in PageLabel dictionary.`);
  326. }
  327. currentLabel = "";
  328. }
  329. pageLabels[i] = prefix + currentLabel;
  330. currentIndex++;
  331. }
  332. return pageLabels;
  333. }
  334. get pageLayout() {
  335. const obj = this.catDict.get("PageLayout");
  336. let pageLayout = "";
  337. if ((0, _primitives.isName)(obj)) {
  338. switch (obj.name) {
  339. case "SinglePage":
  340. case "OneColumn":
  341. case "TwoColumnLeft":
  342. case "TwoColumnRight":
  343. case "TwoPageLeft":
  344. case "TwoPageRight":
  345. pageLayout = obj.name;
  346. }
  347. }
  348. return (0, _util.shadow)(this, "pageLayout", pageLayout);
  349. }
  350. get pageMode() {
  351. const obj = this.catDict.get("PageMode");
  352. let pageMode = "UseNone";
  353. if ((0, _primitives.isName)(obj)) {
  354. switch (obj.name) {
  355. case "UseNone":
  356. case "UseOutlines":
  357. case "UseThumbs":
  358. case "FullScreen":
  359. case "UseOC":
  360. case "UseAttachments":
  361. pageMode = obj.name;
  362. }
  363. }
  364. return (0, _util.shadow)(this, "pageMode", pageMode);
  365. }
  366. get viewerPreferences() {
  367. const ViewerPreferencesValidators = {
  368. HideToolbar: _util.isBool,
  369. HideMenubar: _util.isBool,
  370. HideWindowUI: _util.isBool,
  371. FitWindow: _util.isBool,
  372. CenterWindow: _util.isBool,
  373. DisplayDocTitle: _util.isBool,
  374. NonFullScreenPageMode: _primitives.isName,
  375. Direction: _primitives.isName,
  376. ViewArea: _primitives.isName,
  377. ViewClip: _primitives.isName,
  378. PrintArea: _primitives.isName,
  379. PrintClip: _primitives.isName,
  380. PrintScaling: _primitives.isName,
  381. Duplex: _primitives.isName,
  382. PickTrayByPDFSize: _util.isBool,
  383. PrintPageRange: Array.isArray,
  384. NumCopies: Number.isInteger
  385. };
  386. const obj = this.catDict.get("ViewerPreferences");
  387. const prefs = Object.create(null);
  388. if ((0, _primitives.isDict)(obj)) {
  389. for (const key in ViewerPreferencesValidators) {
  390. if (!obj.has(key)) {
  391. continue;
  392. }
  393. const value = obj.get(key);
  394. if (!ViewerPreferencesValidators[key](value)) {
  395. (0, _util.info)(`Bad value in ViewerPreferences for "${key}".`);
  396. continue;
  397. }
  398. let prefValue;
  399. switch (key) {
  400. case "NonFullScreenPageMode":
  401. switch (value.name) {
  402. case "UseNone":
  403. case "UseOutlines":
  404. case "UseThumbs":
  405. case "UseOC":
  406. prefValue = value.name;
  407. break;
  408. default:
  409. prefValue = "UseNone";
  410. }
  411. break;
  412. case "Direction":
  413. switch (value.name) {
  414. case "L2R":
  415. case "R2L":
  416. prefValue = value.name;
  417. break;
  418. default:
  419. prefValue = "L2R";
  420. }
  421. break;
  422. case "ViewArea":
  423. case "ViewClip":
  424. case "PrintArea":
  425. case "PrintClip":
  426. switch (value.name) {
  427. case "MediaBox":
  428. case "CropBox":
  429. case "BleedBox":
  430. case "TrimBox":
  431. case "ArtBox":
  432. prefValue = value.name;
  433. break;
  434. default:
  435. prefValue = "CropBox";
  436. }
  437. break;
  438. case "PrintScaling":
  439. switch (value.name) {
  440. case "None":
  441. case "AppDefault":
  442. prefValue = value.name;
  443. break;
  444. default:
  445. prefValue = "AppDefault";
  446. }
  447. break;
  448. case "Duplex":
  449. switch (value.name) {
  450. case "Simplex":
  451. case "DuplexFlipShortEdge":
  452. case "DuplexFlipLongEdge":
  453. prefValue = value.name;
  454. break;
  455. default:
  456. prefValue = "None";
  457. }
  458. break;
  459. case "PrintPageRange":
  460. const length = value.length;
  461. if (length % 2 !== 0) {
  462. break;
  463. }
  464. const isValid = value.every((page, i, arr) => {
  465. return Number.isInteger(page) && page > 0 && (i === 0 || page >= arr[i - 1]) && page <= this.numPages;
  466. });
  467. if (isValid) {
  468. prefValue = value;
  469. }
  470. break;
  471. case "NumCopies":
  472. if (value > 0) {
  473. prefValue = value;
  474. }
  475. break;
  476. default:
  477. (0, _util.assert)(typeof value === "boolean");
  478. prefValue = value;
  479. }
  480. if (prefValue !== undefined) {
  481. prefs[key] = prefValue;
  482. } else {
  483. (0, _util.info)(`Bad value in ViewerPreferences for "${key}".`);
  484. }
  485. }
  486. }
  487. return (0, _util.shadow)(this, "viewerPreferences", prefs);
  488. }
  489. get openAction() {
  490. const obj = this.catDict.get("OpenAction");
  491. let openAction = null;
  492. if ((0, _primitives.isDict)(obj)) {
  493. const destDict = new _primitives.Dict(this.xref);
  494. destDict.set("A", obj);
  495. const resultObj = {
  496. url: null,
  497. dest: null,
  498. action: null
  499. };
  500. Catalog.parseDestDictionary({
  501. destDict,
  502. resultObj
  503. });
  504. if (Array.isArray(resultObj.dest)) {
  505. if (!openAction) {
  506. openAction = Object.create(null);
  507. }
  508. openAction.dest = resultObj.dest;
  509. } else if (resultObj.action) {
  510. if (!openAction) {
  511. openAction = Object.create(null);
  512. }
  513. openAction.action = resultObj.action;
  514. }
  515. } else if (Array.isArray(obj)) {
  516. if (!openAction) {
  517. openAction = Object.create(null);
  518. }
  519. openAction.dest = obj;
  520. }
  521. return (0, _util.shadow)(this, "openAction", openAction);
  522. }
  523. get attachments() {
  524. const obj = this.catDict.get("Names");
  525. let attachments = null;
  526. if (obj && obj.has("EmbeddedFiles")) {
  527. const nameTree = new NameTree(obj.getRaw("EmbeddedFiles"), this.xref);
  528. const names = nameTree.getAll();
  529. for (const name in names) {
  530. const fs = new FileSpec(names[name], this.xref);
  531. if (!attachments) {
  532. attachments = Object.create(null);
  533. }
  534. attachments[(0, _util.stringToPDFString)(name)] = fs.serializable;
  535. }
  536. }
  537. return (0, _util.shadow)(this, "attachments", attachments);
  538. }
  539. get javaScript() {
  540. const obj = this.catDict.get("Names");
  541. let javaScript = null;
  542. function appendIfJavaScriptDict(jsDict) {
  543. const type = jsDict.get("S");
  544. if (!(0, _primitives.isName)(type, "JavaScript")) {
  545. return;
  546. }
  547. let js = jsDict.get("JS");
  548. if ((0, _primitives.isStream)(js)) {
  549. js = (0, _util.bytesToString)(js.getBytes());
  550. } else if (!(0, _util.isString)(js)) {
  551. return;
  552. }
  553. if (!javaScript) {
  554. javaScript = [];
  555. }
  556. javaScript.push((0, _util.stringToPDFString)(js));
  557. }
  558. if (obj && obj.has("JavaScript")) {
  559. const nameTree = new NameTree(obj.getRaw("JavaScript"), this.xref);
  560. const names = nameTree.getAll();
  561. for (const name in names) {
  562. const jsDict = names[name];
  563. if ((0, _primitives.isDict)(jsDict)) {
  564. appendIfJavaScriptDict(jsDict);
  565. }
  566. }
  567. }
  568. const openAction = this.catDict.get("OpenAction");
  569. if ((0, _primitives.isDict)(openAction) && (0, _primitives.isName)(openAction.get("S"), "JavaScript")) {
  570. appendIfJavaScriptDict(openAction);
  571. }
  572. return (0, _util.shadow)(this, "javaScript", javaScript);
  573. }
  574. fontFallback(id, handler) {
  575. const promises = [];
  576. this.fontCache.forEach(function (promise) {
  577. promises.push(promise);
  578. });
  579. return Promise.all(promises).then(translatedFonts => {
  580. for (const translatedFont of translatedFonts) {
  581. if (translatedFont.loadedName === id) {
  582. translatedFont.fallback(handler);
  583. return;
  584. }
  585. }
  586. });
  587. }
  588. cleanup() {
  589. (0, _primitives.clearPrimitiveCaches)();
  590. this.pageKidsCountCache.clear();
  591. const promises = [];
  592. this.fontCache.forEach(function (promise) {
  593. promises.push(promise);
  594. });
  595. return Promise.all(promises).then(translatedFonts => {
  596. for (const {
  597. dict
  598. } of translatedFonts) {
  599. delete dict.translated;
  600. }
  601. this.fontCache.clear();
  602. this.builtInCMapCache.clear();
  603. });
  604. }
  605. getPageDict(pageIndex) {
  606. const capability = (0, _util.createPromiseCapability)();
  607. const nodesToVisit = [this.catDict.getRaw("Pages")];
  608. const visitedNodes = new _primitives.RefSet();
  609. const xref = this.xref,
  610. pageKidsCountCache = this.pageKidsCountCache;
  611. let count,
  612. currentPageIndex = 0;
  613. function next() {
  614. while (nodesToVisit.length) {
  615. const currentNode = nodesToVisit.pop();
  616. if ((0, _primitives.isRef)(currentNode)) {
  617. count = pageKidsCountCache.get(currentNode);
  618. if (count > 0 && currentPageIndex + count < pageIndex) {
  619. currentPageIndex += count;
  620. continue;
  621. }
  622. if (visitedNodes.has(currentNode)) {
  623. capability.reject(new _util.FormatError("Pages tree contains circular reference."));
  624. return;
  625. }
  626. visitedNodes.put(currentNode);
  627. xref.fetchAsync(currentNode).then(function (obj) {
  628. if ((0, _primitives.isDict)(obj, "Page") || (0, _primitives.isDict)(obj) && !obj.has("Kids")) {
  629. if (pageIndex === currentPageIndex) {
  630. if (currentNode && !pageKidsCountCache.has(currentNode)) {
  631. pageKidsCountCache.put(currentNode, 1);
  632. }
  633. capability.resolve([obj, currentNode]);
  634. } else {
  635. currentPageIndex++;
  636. next();
  637. }
  638. return;
  639. }
  640. nodesToVisit.push(obj);
  641. next();
  642. }, capability.reject);
  643. return;
  644. }
  645. if (!(0, _primitives.isDict)(currentNode)) {
  646. capability.reject(new _util.FormatError("Page dictionary kid reference points to wrong type of object."));
  647. return;
  648. }
  649. count = currentNode.get("Count");
  650. if (Number.isInteger(count) && count >= 0) {
  651. const objId = currentNode.objId;
  652. if (objId && !pageKidsCountCache.has(objId)) {
  653. pageKidsCountCache.put(objId, count);
  654. }
  655. if (currentPageIndex + count <= pageIndex) {
  656. currentPageIndex += count;
  657. continue;
  658. }
  659. }
  660. const kids = currentNode.get("Kids");
  661. if (!Array.isArray(kids)) {
  662. if ((0, _primitives.isName)(currentNode.get("Type"), "Page") || !currentNode.has("Type") && currentNode.has("Contents")) {
  663. if (currentPageIndex === pageIndex) {
  664. capability.resolve([currentNode, null]);
  665. return;
  666. }
  667. currentPageIndex++;
  668. continue;
  669. }
  670. capability.reject(new _util.FormatError("Page dictionary kids object is not an array."));
  671. return;
  672. }
  673. for (let last = kids.length - 1; last >= 0; last--) {
  674. nodesToVisit.push(kids[last]);
  675. }
  676. }
  677. capability.reject(new Error(`Page index ${pageIndex} not found.`));
  678. }
  679. next();
  680. return capability.promise;
  681. }
  682. getPageIndex(pageRef) {
  683. const xref = this.xref;
  684. function pagesBeforeRef(kidRef) {
  685. let total = 0,
  686. parentRef;
  687. return xref.fetchAsync(kidRef).then(function (node) {
  688. if ((0, _primitives.isRefsEqual)(kidRef, pageRef) && !(0, _primitives.isDict)(node, "Page") && !((0, _primitives.isDict)(node) && !node.has("Type") && node.has("Contents"))) {
  689. throw new _util.FormatError("The reference does not point to a /Page dictionary.");
  690. }
  691. if (!node) {
  692. return null;
  693. }
  694. if (!(0, _primitives.isDict)(node)) {
  695. throw new _util.FormatError("Node must be a dictionary.");
  696. }
  697. parentRef = node.getRaw("Parent");
  698. return node.getAsync("Parent");
  699. }).then(function (parent) {
  700. if (!parent) {
  701. return null;
  702. }
  703. if (!(0, _primitives.isDict)(parent)) {
  704. throw new _util.FormatError("Parent must be a dictionary.");
  705. }
  706. return parent.getAsync("Kids");
  707. }).then(function (kids) {
  708. if (!kids) {
  709. return null;
  710. }
  711. const kidPromises = [];
  712. let found = false;
  713. for (let i = 0, ii = kids.length; i < ii; i++) {
  714. const kid = kids[i];
  715. if (!(0, _primitives.isRef)(kid)) {
  716. throw new _util.FormatError("Kid must be a reference.");
  717. }
  718. if ((0, _primitives.isRefsEqual)(kid, kidRef)) {
  719. found = true;
  720. break;
  721. }
  722. kidPromises.push(xref.fetchAsync(kid).then(function (kid) {
  723. if (!(0, _primitives.isDict)(kid)) {
  724. throw new _util.FormatError("Kid node must be a dictionary.");
  725. }
  726. if (kid.has("Count")) {
  727. total += kid.get("Count");
  728. } else {
  729. total++;
  730. }
  731. }));
  732. }
  733. if (!found) {
  734. throw new _util.FormatError("Kid reference not found in parent's kids.");
  735. }
  736. return Promise.all(kidPromises).then(function () {
  737. return [total, parentRef];
  738. });
  739. });
  740. }
  741. let total = 0;
  742. function next(ref) {
  743. return pagesBeforeRef(ref).then(function (args) {
  744. if (!args) {
  745. return total;
  746. }
  747. const [count, parentRef] = args;
  748. total += count;
  749. return next(parentRef);
  750. });
  751. }
  752. return next(pageRef);
  753. }
  754. static parseDestDictionary(params) {
  755. function addDefaultProtocolToUrl(url) {
  756. return url.startsWith("www.") ? `http://${url}` : url;
  757. }
  758. function tryConvertUrlEncoding(url) {
  759. try {
  760. return (0, _util.stringToUTF8String)(url);
  761. } catch (e) {
  762. return url;
  763. }
  764. }
  765. const destDict = params.destDict;
  766. if (!(0, _primitives.isDict)(destDict)) {
  767. (0, _util.warn)("parseDestDictionary: `destDict` must be a dictionary.");
  768. return;
  769. }
  770. const resultObj = params.resultObj;
  771. if (typeof resultObj !== "object") {
  772. (0, _util.warn)("parseDestDictionary: `resultObj` must be an object.");
  773. return;
  774. }
  775. const docBaseUrl = params.docBaseUrl || null;
  776. let action = destDict.get("A"),
  777. url,
  778. dest;
  779. if (!(0, _primitives.isDict)(action) && destDict.has("Dest")) {
  780. action = destDict.get("Dest");
  781. }
  782. if ((0, _primitives.isDict)(action)) {
  783. const actionType = action.get("S");
  784. if (!(0, _primitives.isName)(actionType)) {
  785. (0, _util.warn)("parseDestDictionary: Invalid type in Action dictionary.");
  786. return;
  787. }
  788. const actionName = actionType.name;
  789. switch (actionName) {
  790. case "URI":
  791. url = action.get("URI");
  792. if ((0, _primitives.isName)(url)) {
  793. url = "/" + url.name;
  794. } else if ((0, _util.isString)(url)) {
  795. url = addDefaultProtocolToUrl(url);
  796. }
  797. break;
  798. case "GoTo":
  799. dest = action.get("D");
  800. break;
  801. case "Launch":
  802. case "GoToR":
  803. const urlDict = action.get("F");
  804. if ((0, _primitives.isDict)(urlDict)) {
  805. url = urlDict.get("F") || null;
  806. } else if ((0, _util.isString)(urlDict)) {
  807. url = urlDict;
  808. }
  809. let remoteDest = action.get("D");
  810. if (remoteDest) {
  811. if ((0, _primitives.isName)(remoteDest)) {
  812. remoteDest = remoteDest.name;
  813. }
  814. if ((0, _util.isString)(url)) {
  815. const baseUrl = url.split("#")[0];
  816. if ((0, _util.isString)(remoteDest)) {
  817. url = baseUrl + "#" + remoteDest;
  818. } else if (Array.isArray(remoteDest)) {
  819. url = baseUrl + "#" + JSON.stringify(remoteDest);
  820. }
  821. }
  822. }
  823. const newWindow = action.get("NewWindow");
  824. if ((0, _util.isBool)(newWindow)) {
  825. resultObj.newWindow = newWindow;
  826. }
  827. break;
  828. case "Named":
  829. const namedAction = action.get("N");
  830. if ((0, _primitives.isName)(namedAction)) {
  831. resultObj.action = namedAction.name;
  832. }
  833. break;
  834. case "JavaScript":
  835. const jsAction = action.get("JS");
  836. let js;
  837. if ((0, _primitives.isStream)(jsAction)) {
  838. js = (0, _util.bytesToString)(jsAction.getBytes());
  839. } else if ((0, _util.isString)(jsAction)) {
  840. js = jsAction;
  841. }
  842. if (js) {
  843. const URL_OPEN_METHODS = ["app.launchURL", "window.open"];
  844. const regex = new RegExp("^\\s*(" + URL_OPEN_METHODS.join("|").split(".").join("\\.") + ")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))", "i");
  845. const jsUrl = regex.exec((0, _util.stringToPDFString)(js));
  846. if (jsUrl && jsUrl[2]) {
  847. url = jsUrl[2];
  848. if (jsUrl[3] === "true" && jsUrl[1] === "app.launchURL") {
  849. resultObj.newWindow = true;
  850. }
  851. break;
  852. }
  853. }
  854. default:
  855. (0, _util.warn)(`parseDestDictionary: unsupported action type "${actionName}".`);
  856. break;
  857. }
  858. } else if (destDict.has("Dest")) {
  859. dest = destDict.get("Dest");
  860. }
  861. if ((0, _util.isString)(url)) {
  862. url = tryConvertUrlEncoding(url);
  863. const absoluteUrl = (0, _util.createValidAbsoluteUrl)(url, docBaseUrl);
  864. if (absoluteUrl) {
  865. resultObj.url = absoluteUrl.href;
  866. }
  867. resultObj.unsafeUrl = url;
  868. }
  869. if (dest) {
  870. if ((0, _primitives.isName)(dest)) {
  871. dest = dest.name;
  872. }
  873. if ((0, _util.isString)(dest) || Array.isArray(dest)) {
  874. resultObj.dest = dest;
  875. }
  876. }
  877. }
  878. }
  879. exports.Catalog = Catalog;
  880. var XRef = function XRefClosure() {
  881. function XRef(stream, pdfManager) {
  882. this.stream = stream;
  883. this.pdfManager = pdfManager;
  884. this.entries = [];
  885. this.xrefstms = Object.create(null);
  886. this._cacheMap = new Map();
  887. this.stats = {
  888. streamTypes: Object.create(null),
  889. fontTypes: Object.create(null)
  890. };
  891. }
  892. XRef.prototype = {
  893. setStartXRef: function XRef_setStartXRef(startXRef) {
  894. this.startXRefQueue = [startXRef];
  895. },
  896. parse: function XRef_parse(recoveryMode) {
  897. var trailerDict;
  898. if (!recoveryMode) {
  899. trailerDict = this.readXRef();
  900. } else {
  901. (0, _util.warn)("Indexing all PDF objects");
  902. trailerDict = this.indexObjects();
  903. }
  904. trailerDict.assignXref(this);
  905. this.trailer = trailerDict;
  906. let encrypt;
  907. try {
  908. encrypt = trailerDict.get("Encrypt");
  909. } catch (ex) {
  910. if (ex instanceof _core_utils.MissingDataException) {
  911. throw ex;
  912. }
  913. (0, _util.warn)(`XRef.parse - Invalid "Encrypt" reference: "${ex}".`);
  914. }
  915. if ((0, _primitives.isDict)(encrypt)) {
  916. var ids = trailerDict.get("ID");
  917. var fileId = ids && ids.length ? ids[0] : "";
  918. encrypt.suppressEncryption = true;
  919. this.encrypt = new _crypto.CipherTransformFactory(encrypt, fileId, this.pdfManager.password);
  920. }
  921. let root;
  922. try {
  923. root = trailerDict.get("Root");
  924. } catch (ex) {
  925. if (ex instanceof _core_utils.MissingDataException) {
  926. throw ex;
  927. }
  928. (0, _util.warn)(`XRef.parse - Invalid "Root" reference: "${ex}".`);
  929. }
  930. if ((0, _primitives.isDict)(root) && root.has("Pages")) {
  931. this.root = root;
  932. } else {
  933. if (!recoveryMode) {
  934. throw new _core_utils.XRefParseException();
  935. }
  936. throw new _util.FormatError("Invalid root reference");
  937. }
  938. },
  939. processXRefTable: function XRef_processXRefTable(parser) {
  940. if (!("tableState" in this)) {
  941. this.tableState = {
  942. entryNum: 0,
  943. streamPos: parser.lexer.stream.pos,
  944. parserBuf1: parser.buf1,
  945. parserBuf2: parser.buf2
  946. };
  947. }
  948. var obj = this.readXRefTable(parser);
  949. if (!(0, _primitives.isCmd)(obj, "trailer")) {
  950. throw new _util.FormatError("Invalid XRef table: could not find trailer dictionary");
  951. }
  952. var dict = parser.getObj();
  953. if (!(0, _primitives.isDict)(dict) && dict.dict) {
  954. dict = dict.dict;
  955. }
  956. if (!(0, _primitives.isDict)(dict)) {
  957. throw new _util.FormatError("Invalid XRef table: could not parse trailer dictionary");
  958. }
  959. delete this.tableState;
  960. return dict;
  961. },
  962. readXRefTable: function XRef_readXRefTable(parser) {
  963. var stream = parser.lexer.stream;
  964. var tableState = this.tableState;
  965. stream.pos = tableState.streamPos;
  966. parser.buf1 = tableState.parserBuf1;
  967. parser.buf2 = tableState.parserBuf2;
  968. var obj;
  969. while (true) {
  970. if (!("firstEntryNum" in tableState) || !("entryCount" in tableState)) {
  971. if ((0, _primitives.isCmd)(obj = parser.getObj(), "trailer")) {
  972. break;
  973. }
  974. tableState.firstEntryNum = obj;
  975. tableState.entryCount = parser.getObj();
  976. }
  977. var first = tableState.firstEntryNum;
  978. var count = tableState.entryCount;
  979. if (!Number.isInteger(first) || !Number.isInteger(count)) {
  980. throw new _util.FormatError("Invalid XRef table: wrong types in subsection header");
  981. }
  982. for (var i = tableState.entryNum; i < count; i++) {
  983. tableState.streamPos = stream.pos;
  984. tableState.entryNum = i;
  985. tableState.parserBuf1 = parser.buf1;
  986. tableState.parserBuf2 = parser.buf2;
  987. var entry = {};
  988. entry.offset = parser.getObj();
  989. entry.gen = parser.getObj();
  990. var type = parser.getObj();
  991. if (type instanceof _primitives.Cmd) {
  992. switch (type.cmd) {
  993. case "f":
  994. entry.free = true;
  995. break;
  996. case "n":
  997. entry.uncompressed = true;
  998. break;
  999. }
  1000. }
  1001. if (!Number.isInteger(entry.offset) || !Number.isInteger(entry.gen) || !(entry.free || entry.uncompressed)) {
  1002. throw new _util.FormatError(`Invalid entry in XRef subsection: ${first}, ${count}`);
  1003. }
  1004. if (i === 0 && entry.free && first === 1) {
  1005. first = 0;
  1006. }
  1007. if (!this.entries[i + first]) {
  1008. this.entries[i + first] = entry;
  1009. }
  1010. }
  1011. tableState.entryNum = 0;
  1012. tableState.streamPos = stream.pos;
  1013. tableState.parserBuf1 = parser.buf1;
  1014. tableState.parserBuf2 = parser.buf2;
  1015. delete tableState.firstEntryNum;
  1016. delete tableState.entryCount;
  1017. }
  1018. if (this.entries[0] && !this.entries[0].free) {
  1019. throw new _util.FormatError("Invalid XRef table: unexpected first object");
  1020. }
  1021. return obj;
  1022. },
  1023. processXRefStream: function XRef_processXRefStream(stream) {
  1024. if (!("streamState" in this)) {
  1025. var streamParameters = stream.dict;
  1026. var byteWidths = streamParameters.get("W");
  1027. var range = streamParameters.get("Index");
  1028. if (!range) {
  1029. range = [0, streamParameters.get("Size")];
  1030. }
  1031. this.streamState = {
  1032. entryRanges: range,
  1033. byteWidths,
  1034. entryNum: 0,
  1035. streamPos: stream.pos
  1036. };
  1037. }
  1038. this.readXRefStream(stream);
  1039. delete this.streamState;
  1040. return stream.dict;
  1041. },
  1042. readXRefStream: function XRef_readXRefStream(stream) {
  1043. var i, j;
  1044. var streamState = this.streamState;
  1045. stream.pos = streamState.streamPos;
  1046. var byteWidths = streamState.byteWidths;
  1047. var typeFieldWidth = byteWidths[0];
  1048. var offsetFieldWidth = byteWidths[1];
  1049. var generationFieldWidth = byteWidths[2];
  1050. var entryRanges = streamState.entryRanges;
  1051. while (entryRanges.length > 0) {
  1052. var first = entryRanges[0];
  1053. var n = entryRanges[1];
  1054. if (!Number.isInteger(first) || !Number.isInteger(n)) {
  1055. throw new _util.FormatError(`Invalid XRef range fields: ${first}, ${n}`);
  1056. }
  1057. if (!Number.isInteger(typeFieldWidth) || !Number.isInteger(offsetFieldWidth) || !Number.isInteger(generationFieldWidth)) {
  1058. throw new _util.FormatError(`Invalid XRef entry fields length: ${first}, ${n}`);
  1059. }
  1060. for (i = streamState.entryNum; i < n; ++i) {
  1061. streamState.entryNum = i;
  1062. streamState.streamPos = stream.pos;
  1063. var type = 0,
  1064. offset = 0,
  1065. generation = 0;
  1066. for (j = 0; j < typeFieldWidth; ++j) {
  1067. type = type << 8 | stream.getByte();
  1068. }
  1069. if (typeFieldWidth === 0) {
  1070. type = 1;
  1071. }
  1072. for (j = 0; j < offsetFieldWidth; ++j) {
  1073. offset = offset << 8 | stream.getByte();
  1074. }
  1075. for (j = 0; j < generationFieldWidth; ++j) {
  1076. generation = generation << 8 | stream.getByte();
  1077. }
  1078. var entry = {};
  1079. entry.offset = offset;
  1080. entry.gen = generation;
  1081. switch (type) {
  1082. case 0:
  1083. entry.free = true;
  1084. break;
  1085. case 1:
  1086. entry.uncompressed = true;
  1087. break;
  1088. case 2:
  1089. break;
  1090. default:
  1091. throw new _util.FormatError(`Invalid XRef entry type: ${type}`);
  1092. }
  1093. if (!this.entries[first + i]) {
  1094. this.entries[first + i] = entry;
  1095. }
  1096. }
  1097. streamState.entryNum = 0;
  1098. streamState.streamPos = stream.pos;
  1099. entryRanges.splice(0, 2);
  1100. }
  1101. },
  1102. indexObjects: function XRef_indexObjects() {
  1103. var TAB = 0x9,
  1104. LF = 0xa,
  1105. CR = 0xd,
  1106. SPACE = 0x20;
  1107. var PERCENT = 0x25,
  1108. LT = 0x3c;
  1109. function readToken(data, offset) {
  1110. var token = "",
  1111. ch = data[offset];
  1112. while (ch !== LF && ch !== CR && ch !== LT) {
  1113. if (++offset >= data.length) {
  1114. break;
  1115. }
  1116. token += String.fromCharCode(ch);
  1117. ch = data[offset];
  1118. }
  1119. return token;
  1120. }
  1121. function skipUntil(data, offset, what) {
  1122. var length = what.length,
  1123. dataLength = data.length;
  1124. var skipped = 0;
  1125. while (offset < dataLength) {
  1126. var i = 0;
  1127. while (i < length && data[offset + i] === what[i]) {
  1128. ++i;
  1129. }
  1130. if (i >= length) {
  1131. break;
  1132. }
  1133. offset++;
  1134. skipped++;
  1135. }
  1136. return skipped;
  1137. }
  1138. var objRegExp = /^(\d+)\s+(\d+)\s+obj\b/;
  1139. const endobjRegExp = /\bendobj[\b\s]$/;
  1140. const nestedObjRegExp = /\s+(\d+\s+\d+\s+obj[\b\s<])$/;
  1141. const CHECK_CONTENT_LENGTH = 25;
  1142. var trailerBytes = new Uint8Array([116, 114, 97, 105, 108, 101, 114]);
  1143. var startxrefBytes = new Uint8Array([115, 116, 97, 114, 116, 120, 114, 101, 102]);
  1144. const objBytes = new Uint8Array([111, 98, 106]);
  1145. var xrefBytes = new Uint8Array([47, 88, 82, 101, 102]);
  1146. this.entries.length = 0;
  1147. var stream = this.stream;
  1148. stream.pos = 0;
  1149. var buffer = stream.getBytes();
  1150. var position = stream.start,
  1151. length = buffer.length;
  1152. var trailers = [],
  1153. xrefStms = [];
  1154. while (position < length) {
  1155. var ch = buffer[position];
  1156. if (ch === TAB || ch === LF || ch === CR || ch === SPACE) {
  1157. ++position;
  1158. continue;
  1159. }
  1160. if (ch === PERCENT) {
  1161. do {
  1162. ++position;
  1163. if (position >= length) {
  1164. break;
  1165. }
  1166. ch = buffer[position];
  1167. } while (ch !== LF && ch !== CR);
  1168. continue;
  1169. }
  1170. var token = readToken(buffer, position);
  1171. var m;
  1172. if (token.startsWith("xref") && (token.length === 4 || /\s/.test(token[4]))) {
  1173. position += skipUntil(buffer, position, trailerBytes);
  1174. trailers.push(position);
  1175. position += skipUntil(buffer, position, startxrefBytes);
  1176. } else if (m = objRegExp.exec(token)) {
  1177. const num = m[1] | 0,
  1178. gen = m[2] | 0;
  1179. if (!this.entries[num] || this.entries[num].gen === gen) {
  1180. this.entries[num] = {
  1181. offset: position - stream.start,
  1182. gen,
  1183. uncompressed: true
  1184. };
  1185. }
  1186. let contentLength,
  1187. startPos = position + token.length;
  1188. while (startPos < buffer.length) {
  1189. const endPos = startPos + skipUntil(buffer, startPos, objBytes) + 4;
  1190. contentLength = endPos - position;
  1191. const checkPos = Math.max(endPos - CHECK_CONTENT_LENGTH, startPos);
  1192. const tokenStr = (0, _util.bytesToString)(buffer.subarray(checkPos, endPos));
  1193. if (endobjRegExp.test(tokenStr)) {
  1194. break;
  1195. } else {
  1196. const objToken = nestedObjRegExp.exec(tokenStr);
  1197. if (objToken && objToken[1]) {
  1198. (0, _util.warn)('indexObjects: Found new "obj" inside of another "obj", ' + 'caused by missing "endobj" -- trying to recover.');
  1199. contentLength -= objToken[1].length;
  1200. break;
  1201. }
  1202. }
  1203. startPos = endPos;
  1204. }
  1205. const content = buffer.subarray(position, position + contentLength);
  1206. var xrefTagOffset = skipUntil(content, 0, xrefBytes);
  1207. if (xrefTagOffset < contentLength && content[xrefTagOffset + 5] < 64) {
  1208. xrefStms.push(position - stream.start);
  1209. this.xrefstms[position - stream.start] = 1;
  1210. }
  1211. position += contentLength;
  1212. } else if (token.startsWith("trailer") && (token.length === 7 || /\s/.test(token[7]))) {
  1213. trailers.push(position);
  1214. position += skipUntil(buffer, position, startxrefBytes);
  1215. } else {
  1216. position += token.length + 1;
  1217. }
  1218. }
  1219. var i, ii;
  1220. for (i = 0, ii = xrefStms.length; i < ii; ++i) {
  1221. this.startXRefQueue.push(xrefStms[i]);
  1222. this.readXRef(true);
  1223. }
  1224. let trailerDict;
  1225. for (i = 0, ii = trailers.length; i < ii; ++i) {
  1226. stream.pos = trailers[i];
  1227. const parser = new _parser.Parser({
  1228. lexer: new _parser.Lexer(stream),
  1229. xref: this,
  1230. allowStreams: true,
  1231. recoveryMode: true
  1232. });
  1233. var obj = parser.getObj();
  1234. if (!(0, _primitives.isCmd)(obj, "trailer")) {
  1235. continue;
  1236. }
  1237. const dict = parser.getObj();
  1238. if (!(0, _primitives.isDict)(dict)) {
  1239. continue;
  1240. }
  1241. let rootDict;
  1242. try {
  1243. rootDict = dict.get("Root");
  1244. } catch (ex) {
  1245. if (ex instanceof _core_utils.MissingDataException) {
  1246. throw ex;
  1247. }
  1248. continue;
  1249. }
  1250. if (!(0, _primitives.isDict)(rootDict) || !rootDict.has("Pages")) {
  1251. continue;
  1252. }
  1253. if (dict.has("ID")) {
  1254. return dict;
  1255. }
  1256. trailerDict = dict;
  1257. }
  1258. if (trailerDict) {
  1259. return trailerDict;
  1260. }
  1261. throw new _util.InvalidPDFException("Invalid PDF structure.");
  1262. },
  1263. readXRef: function XRef_readXRef(recoveryMode) {
  1264. var stream = this.stream;
  1265. const startXRefParsedCache = Object.create(null);
  1266. try {
  1267. while (this.startXRefQueue.length) {
  1268. var startXRef = this.startXRefQueue[0];
  1269. if (startXRefParsedCache[startXRef]) {
  1270. (0, _util.warn)("readXRef - skipping XRef table since it was already parsed.");
  1271. this.startXRefQueue.shift();
  1272. continue;
  1273. }
  1274. startXRefParsedCache[startXRef] = true;
  1275. stream.pos = startXRef + stream.start;
  1276. const parser = new _parser.Parser({
  1277. lexer: new _parser.Lexer(stream),
  1278. xref: this,
  1279. allowStreams: true
  1280. });
  1281. var obj = parser.getObj();
  1282. var dict;
  1283. if ((0, _primitives.isCmd)(obj, "xref")) {
  1284. dict = this.processXRefTable(parser);
  1285. if (!this.topDict) {
  1286. this.topDict = dict;
  1287. }
  1288. obj = dict.get("XRefStm");
  1289. if (Number.isInteger(obj)) {
  1290. var pos = obj;
  1291. if (!(pos in this.xrefstms)) {
  1292. this.xrefstms[pos] = 1;
  1293. this.startXRefQueue.push(pos);
  1294. }
  1295. }
  1296. } else if (Number.isInteger(obj)) {
  1297. if (!Number.isInteger(parser.getObj()) || !(0, _primitives.isCmd)(parser.getObj(), "obj") || !(0, _primitives.isStream)(obj = parser.getObj())) {
  1298. throw new _util.FormatError("Invalid XRef stream");
  1299. }
  1300. dict = this.processXRefStream(obj);
  1301. if (!this.topDict) {
  1302. this.topDict = dict;
  1303. }
  1304. if (!dict) {
  1305. throw new _util.FormatError("Failed to read XRef stream");
  1306. }
  1307. } else {
  1308. throw new _util.FormatError("Invalid XRef stream header");
  1309. }
  1310. obj = dict.get("Prev");
  1311. if (Number.isInteger(obj)) {
  1312. this.startXRefQueue.push(obj);
  1313. } else if ((0, _primitives.isRef)(obj)) {
  1314. this.startXRefQueue.push(obj.num);
  1315. }
  1316. this.startXRefQueue.shift();
  1317. }
  1318. return this.topDict;
  1319. } catch (e) {
  1320. if (e instanceof _core_utils.MissingDataException) {
  1321. throw e;
  1322. }
  1323. (0, _util.info)("(while reading XRef): " + e);
  1324. }
  1325. if (recoveryMode) {
  1326. return undefined;
  1327. }
  1328. throw new _core_utils.XRefParseException();
  1329. },
  1330. getEntry: function XRef_getEntry(i) {
  1331. var xrefEntry = this.entries[i];
  1332. if (xrefEntry && !xrefEntry.free && xrefEntry.offset) {
  1333. return xrefEntry;
  1334. }
  1335. return null;
  1336. },
  1337. fetchIfRef: function XRef_fetchIfRef(obj, suppressEncryption) {
  1338. if (obj instanceof _primitives.Ref) {
  1339. return this.fetch(obj, suppressEncryption);
  1340. }
  1341. return obj;
  1342. },
  1343. fetch: function XRef_fetch(ref, suppressEncryption) {
  1344. if (!(ref instanceof _primitives.Ref)) {
  1345. throw new Error("ref object is not a reference");
  1346. }
  1347. const num = ref.num;
  1348. const cacheEntry = this._cacheMap.get(num);
  1349. if (cacheEntry !== undefined) {
  1350. if (cacheEntry instanceof _primitives.Dict && !cacheEntry.objId) {
  1351. cacheEntry.objId = ref.toString();
  1352. }
  1353. return cacheEntry;
  1354. }
  1355. let xrefEntry = this.getEntry(num);
  1356. if (xrefEntry === null) {
  1357. this._cacheMap.set(num, xrefEntry);
  1358. return xrefEntry;
  1359. }
  1360. if (xrefEntry.uncompressed) {
  1361. xrefEntry = this.fetchUncompressed(ref, xrefEntry, suppressEncryption);
  1362. } else {
  1363. xrefEntry = this.fetchCompressed(ref, xrefEntry, suppressEncryption);
  1364. }
  1365. if ((0, _primitives.isDict)(xrefEntry)) {
  1366. xrefEntry.objId = ref.toString();
  1367. } else if ((0, _primitives.isStream)(xrefEntry)) {
  1368. xrefEntry.dict.objId = ref.toString();
  1369. }
  1370. return xrefEntry;
  1371. },
  1372. fetchUncompressed(ref, xrefEntry, suppressEncryption = false) {
  1373. var gen = ref.gen;
  1374. var num = ref.num;
  1375. if (xrefEntry.gen !== gen) {
  1376. throw new _core_utils.XRefEntryException(`Inconsistent generation in XRef: ${ref}`);
  1377. }
  1378. var stream = this.stream.makeSubStream(xrefEntry.offset + this.stream.start);
  1379. const parser = new _parser.Parser({
  1380. lexer: new _parser.Lexer(stream),
  1381. xref: this,
  1382. allowStreams: true
  1383. });
  1384. var obj1 = parser.getObj();
  1385. var obj2 = parser.getObj();
  1386. var obj3 = parser.getObj();
  1387. if (obj1 !== num || obj2 !== gen || !(obj3 instanceof _primitives.Cmd)) {
  1388. throw new _core_utils.XRefEntryException(`Bad (uncompressed) XRef entry: ${ref}`);
  1389. }
  1390. if (obj3.cmd !== "obj") {
  1391. if (obj3.cmd.startsWith("obj")) {
  1392. num = parseInt(obj3.cmd.substring(3), 10);
  1393. if (!Number.isNaN(num)) {
  1394. return num;
  1395. }
  1396. }
  1397. throw new _core_utils.XRefEntryException(`Bad (uncompressed) XRef entry: ${ref}`);
  1398. }
  1399. if (this.encrypt && !suppressEncryption) {
  1400. xrefEntry = parser.getObj(this.encrypt.createCipherTransform(num, gen));
  1401. } else {
  1402. xrefEntry = parser.getObj();
  1403. }
  1404. if (!(0, _primitives.isStream)(xrefEntry)) {
  1405. this._cacheMap.set(num, xrefEntry);
  1406. }
  1407. return xrefEntry;
  1408. },
  1409. fetchCompressed(ref, xrefEntry, suppressEncryption = false) {
  1410. const tableOffset = xrefEntry.offset;
  1411. const stream = this.fetch(_primitives.Ref.get(tableOffset, 0));
  1412. if (!(0, _primitives.isStream)(stream)) {
  1413. throw new _util.FormatError("bad ObjStm stream");
  1414. }
  1415. const first = stream.dict.get("First");
  1416. const n = stream.dict.get("N");
  1417. if (!Number.isInteger(first) || !Number.isInteger(n)) {
  1418. throw new _util.FormatError("invalid first and n parameters for ObjStm stream");
  1419. }
  1420. const parser = new _parser.Parser({
  1421. lexer: new _parser.Lexer(stream),
  1422. xref: this,
  1423. allowStreams: true
  1424. });
  1425. const nums = new Array(n);
  1426. for (let i = 0; i < n; ++i) {
  1427. const num = parser.getObj();
  1428. if (!Number.isInteger(num)) {
  1429. throw new _util.FormatError(`invalid object number in the ObjStm stream: ${num}`);
  1430. }
  1431. const offset = parser.getObj();
  1432. if (!Number.isInteger(offset)) {
  1433. throw new _util.FormatError(`invalid object offset in the ObjStm stream: ${offset}`);
  1434. }
  1435. nums[i] = num;
  1436. }
  1437. const entries = new Array(n);
  1438. for (let i = 0; i < n; ++i) {
  1439. const obj = parser.getObj();
  1440. entries[i] = obj;
  1441. if (parser.buf1 instanceof _primitives.Cmd && parser.buf1.cmd === "endobj") {
  1442. parser.shift();
  1443. }
  1444. if ((0, _primitives.isStream)(obj)) {
  1445. continue;
  1446. }
  1447. const num = nums[i],
  1448. entry = this.entries[num];
  1449. if (entry && entry.offset === tableOffset && entry.gen === i) {
  1450. this._cacheMap.set(num, obj);
  1451. }
  1452. }
  1453. xrefEntry = entries[xrefEntry.gen];
  1454. if (xrefEntry === undefined) {
  1455. throw new _core_utils.XRefEntryException(`Bad (compressed) XRef entry: ${ref}`);
  1456. }
  1457. return xrefEntry;
  1458. },
  1459. async fetchIfRefAsync(obj, suppressEncryption) {
  1460. if (obj instanceof _primitives.Ref) {
  1461. return this.fetchAsync(obj, suppressEncryption);
  1462. }
  1463. return obj;
  1464. },
  1465. async fetchAsync(ref, suppressEncryption) {
  1466. try {
  1467. return this.fetch(ref, suppressEncryption);
  1468. } catch (ex) {
  1469. if (!(ex instanceof _core_utils.MissingDataException)) {
  1470. throw ex;
  1471. }
  1472. await this.pdfManager.requestRange(ex.begin, ex.end);
  1473. return this.fetchAsync(ref, suppressEncryption);
  1474. }
  1475. },
  1476. getCatalogObj: function XRef_getCatalogObj() {
  1477. return this.root;
  1478. }
  1479. };
  1480. return XRef;
  1481. }();
  1482. exports.XRef = XRef;
  1483. class NameOrNumberTree {
  1484. constructor(root, xref, type) {
  1485. if (this.constructor === NameOrNumberTree) {
  1486. (0, _util.unreachable)("Cannot initialize NameOrNumberTree.");
  1487. }
  1488. this.root = root;
  1489. this.xref = xref;
  1490. this._type = type;
  1491. }
  1492. getAll() {
  1493. const dict = Object.create(null);
  1494. if (!this.root) {
  1495. return dict;
  1496. }
  1497. const xref = this.xref;
  1498. const processed = new _primitives.RefSet();
  1499. processed.put(this.root);
  1500. const queue = [this.root];
  1501. while (queue.length > 0) {
  1502. const obj = xref.fetchIfRef(queue.shift());
  1503. if (!(0, _primitives.isDict)(obj)) {
  1504. continue;
  1505. }
  1506. if (obj.has("Kids")) {
  1507. const kids = obj.get("Kids");
  1508. for (let i = 0, ii = kids.length; i < ii; i++) {
  1509. const kid = kids[i];
  1510. if (processed.has(kid)) {
  1511. throw new _util.FormatError(`Duplicate entry in "${this._type}" tree.`);
  1512. }
  1513. queue.push(kid);
  1514. processed.put(kid);
  1515. }
  1516. continue;
  1517. }
  1518. const entries = obj.get(this._type);
  1519. if (Array.isArray(entries)) {
  1520. for (let i = 0, ii = entries.length; i < ii; i += 2) {
  1521. dict[xref.fetchIfRef(entries[i])] = xref.fetchIfRef(entries[i + 1]);
  1522. }
  1523. }
  1524. }
  1525. return dict;
  1526. }
  1527. get(key) {
  1528. if (!this.root) {
  1529. return null;
  1530. }
  1531. const xref = this.xref;
  1532. let kidsOrEntries = xref.fetchIfRef(this.root);
  1533. let loopCount = 0;
  1534. const MAX_LEVELS = 10;
  1535. while (kidsOrEntries.has("Kids")) {
  1536. if (++loopCount > MAX_LEVELS) {
  1537. (0, _util.warn)(`Search depth limit reached for "${this._type}" tree.`);
  1538. return null;
  1539. }
  1540. const kids = kidsOrEntries.get("Kids");
  1541. if (!Array.isArray(kids)) {
  1542. return null;
  1543. }
  1544. let l = 0,
  1545. r = kids.length - 1;
  1546. while (l <= r) {
  1547. const m = l + r >> 1;
  1548. const kid = xref.fetchIfRef(kids[m]);
  1549. const limits = kid.get("Limits");
  1550. if (key < xref.fetchIfRef(limits[0])) {
  1551. r = m - 1;
  1552. } else if (key > xref.fetchIfRef(limits[1])) {
  1553. l = m + 1;
  1554. } else {
  1555. kidsOrEntries = xref.fetchIfRef(kids[m]);
  1556. break;
  1557. }
  1558. }
  1559. if (l > r) {
  1560. return null;
  1561. }
  1562. }
  1563. const entries = kidsOrEntries.get(this._type);
  1564. if (Array.isArray(entries)) {
  1565. let l = 0,
  1566. r = entries.length - 2;
  1567. while (l <= r) {
  1568. const tmp = l + r >> 1,
  1569. m = tmp + (tmp & 1);
  1570. const currentKey = xref.fetchIfRef(entries[m]);
  1571. if (key < currentKey) {
  1572. r = m - 2;
  1573. } else if (key > currentKey) {
  1574. l = m + 2;
  1575. } else {
  1576. return xref.fetchIfRef(entries[m + 1]);
  1577. }
  1578. }
  1579. (0, _util.info)(`Falling back to an exhaustive search, for key "${key}", ` + `in "${this._type}" tree.`);
  1580. for (let m = 0, mm = entries.length; m < mm; m += 2) {
  1581. const currentKey = xref.fetchIfRef(entries[m]);
  1582. if (currentKey === key) {
  1583. (0, _util.warn)(`The "${key}" key was found at an incorrect, ` + `i.e. out-of-order, position in "${this._type}" tree.`);
  1584. return xref.fetchIfRef(entries[m + 1]);
  1585. }
  1586. }
  1587. }
  1588. return null;
  1589. }
  1590. }
  1591. class NameTree extends NameOrNumberTree {
  1592. constructor(root, xref) {
  1593. super(root, xref, "Names");
  1594. }
  1595. }
  1596. class NumberTree extends NameOrNumberTree {
  1597. constructor(root, xref) {
  1598. super(root, xref, "Nums");
  1599. }
  1600. }
  1601. var FileSpec = function FileSpecClosure() {
  1602. function FileSpec(root, xref) {
  1603. if (!root || !(0, _primitives.isDict)(root)) {
  1604. return;
  1605. }
  1606. this.xref = xref;
  1607. this.root = root;
  1608. if (root.has("FS")) {
  1609. this.fs = root.get("FS");
  1610. }
  1611. this.description = root.has("Desc") ? (0, _util.stringToPDFString)(root.get("Desc")) : "";
  1612. if (root.has("RF")) {
  1613. (0, _util.warn)("Related file specifications are not supported");
  1614. }
  1615. this.contentAvailable = true;
  1616. if (!root.has("EF")) {
  1617. this.contentAvailable = false;
  1618. (0, _util.warn)("Non-embedded file specifications are not supported");
  1619. }
  1620. }
  1621. function pickPlatformItem(dict) {
  1622. if (dict.has("UF")) {
  1623. return dict.get("UF");
  1624. } else if (dict.has("F")) {
  1625. return dict.get("F");
  1626. } else if (dict.has("Unix")) {
  1627. return dict.get("Unix");
  1628. } else if (dict.has("Mac")) {
  1629. return dict.get("Mac");
  1630. } else if (dict.has("DOS")) {
  1631. return dict.get("DOS");
  1632. }
  1633. return null;
  1634. }
  1635. FileSpec.prototype = {
  1636. get filename() {
  1637. if (!this._filename && this.root) {
  1638. var filename = pickPlatformItem(this.root) || "unnamed";
  1639. this._filename = (0, _util.stringToPDFString)(filename).replace(/\\\\/g, "\\").replace(/\\\//g, "/").replace(/\\/g, "/");
  1640. }
  1641. return this._filename;
  1642. },
  1643. get content() {
  1644. if (!this.contentAvailable) {
  1645. return null;
  1646. }
  1647. if (!this.contentRef && this.root) {
  1648. this.contentRef = pickPlatformItem(this.root.get("EF"));
  1649. }
  1650. var content = null;
  1651. if (this.contentRef) {
  1652. var xref = this.xref;
  1653. var fileObj = xref.fetchIfRef(this.contentRef);
  1654. if (fileObj && (0, _primitives.isStream)(fileObj)) {
  1655. content = fileObj.getBytes();
  1656. } else {
  1657. (0, _util.warn)("Embedded file specification points to non-existing/invalid " + "content");
  1658. }
  1659. } else {
  1660. (0, _util.warn)("Embedded file specification does not have a content");
  1661. }
  1662. return content;
  1663. },
  1664. get serializable() {
  1665. return {
  1666. filename: this.filename,
  1667. content: this.content
  1668. };
  1669. }
  1670. };
  1671. return FileSpec;
  1672. }();
  1673. exports.FileSpec = FileSpec;
  1674. const ObjectLoader = function () {
  1675. function mayHaveChildren(value) {
  1676. return value instanceof _primitives.Ref || value instanceof _primitives.Dict || Array.isArray(value) || (0, _primitives.isStream)(value);
  1677. }
  1678. function addChildren(node, nodesToVisit) {
  1679. if (node instanceof _primitives.Dict || (0, _primitives.isStream)(node)) {
  1680. const dict = node instanceof _primitives.Dict ? node : node.dict;
  1681. const dictKeys = dict.getKeys();
  1682. for (let i = 0, ii = dictKeys.length; i < ii; i++) {
  1683. const rawValue = dict.getRaw(dictKeys[i]);
  1684. if (mayHaveChildren(rawValue)) {
  1685. nodesToVisit.push(rawValue);
  1686. }
  1687. }
  1688. } else if (Array.isArray(node)) {
  1689. for (let i = 0, ii = node.length; i < ii; i++) {
  1690. const value = node[i];
  1691. if (mayHaveChildren(value)) {
  1692. nodesToVisit.push(value);
  1693. }
  1694. }
  1695. }
  1696. }
  1697. function ObjectLoader(dict, keys, xref) {
  1698. this.dict = dict;
  1699. this.keys = keys;
  1700. this.xref = xref;
  1701. this.refSet = null;
  1702. }
  1703. ObjectLoader.prototype = {
  1704. async load() {
  1705. if (!this.xref.stream.allChunksLoaded || this.xref.stream.allChunksLoaded()) {
  1706. return undefined;
  1707. }
  1708. const {
  1709. keys,
  1710. dict
  1711. } = this;
  1712. this.refSet = new _primitives.RefSet();
  1713. const nodesToVisit = [];
  1714. for (let i = 0, ii = keys.length; i < ii; i++) {
  1715. const rawValue = dict.getRaw(keys[i]);
  1716. if (rawValue !== undefined) {
  1717. nodesToVisit.push(rawValue);
  1718. }
  1719. }
  1720. return this._walk(nodesToVisit);
  1721. },
  1722. async _walk(nodesToVisit) {
  1723. const nodesToRevisit = [];
  1724. const pendingRequests = [];
  1725. while (nodesToVisit.length) {
  1726. let currentNode = nodesToVisit.pop();
  1727. if (currentNode instanceof _primitives.Ref) {
  1728. if (this.refSet.has(currentNode)) {
  1729. continue;
  1730. }
  1731. try {
  1732. this.refSet.put(currentNode);
  1733. currentNode = this.xref.fetch(currentNode);
  1734. } catch (ex) {
  1735. if (!(ex instanceof _core_utils.MissingDataException)) {
  1736. throw ex;
  1737. }
  1738. nodesToRevisit.push(currentNode);
  1739. pendingRequests.push({
  1740. begin: ex.begin,
  1741. end: ex.end
  1742. });
  1743. }
  1744. }
  1745. if (currentNode && currentNode.getBaseStreams) {
  1746. const baseStreams = currentNode.getBaseStreams();
  1747. let foundMissingData = false;
  1748. for (let i = 0, ii = baseStreams.length; i < ii; i++) {
  1749. const stream = baseStreams[i];
  1750. if (stream.allChunksLoaded && !stream.allChunksLoaded()) {
  1751. foundMissingData = true;
  1752. pendingRequests.push({
  1753. begin: stream.start,
  1754. end: stream.end
  1755. });
  1756. }
  1757. }
  1758. if (foundMissingData) {
  1759. nodesToRevisit.push(currentNode);
  1760. }
  1761. }
  1762. addChildren(currentNode, nodesToVisit);
  1763. }
  1764. if (pendingRequests.length) {
  1765. await this.xref.stream.manager.requestRanges(pendingRequests);
  1766. for (let i = 0, ii = nodesToRevisit.length; i < ii; i++) {
  1767. const node = nodesToRevisit[i];
  1768. if (node instanceof _primitives.Ref) {
  1769. this.refSet.remove(node);
  1770. }
  1771. }
  1772. return this._walk(nodesToRevisit);
  1773. }
  1774. this.refSet = null;
  1775. return undefined;
  1776. }
  1777. };
  1778. return ObjectLoader;
  1779. }();
  1780. exports.ObjectLoader = ObjectLoader;