catalog.js 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2022 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.Catalog = void 0;
  27. var _core_utils = require("./core_utils.js");
  28. var _util = require("../shared/util.js");
  29. var _primitives = require("./primitives.js");
  30. var _name_number_tree = require("./name_number_tree.js");
  31. var _base_stream = require("./base_stream.js");
  32. var _cleanup_helper = require("./cleanup_helper.js");
  33. var _colorspace = require("./colorspace.js");
  34. var _file_spec = require("./file_spec.js");
  35. var _image_utils = require("./image_utils.js");
  36. var _metadata_parser = require("./metadata_parser.js");
  37. var _struct_tree = require("./struct_tree.js");
  38. function fetchDestination(dest) {
  39. if (dest instanceof _primitives.Dict) {
  40. dest = dest.get("D");
  41. }
  42. return Array.isArray(dest) ? dest : null;
  43. }
  44. class Catalog {
  45. constructor(pdfManager, xref) {
  46. this.pdfManager = pdfManager;
  47. this.xref = xref;
  48. this._catDict = xref.getCatalogObj();
  49. if (!(this._catDict instanceof _primitives.Dict)) {
  50. throw new _util.FormatError("Catalog object is not a dictionary.");
  51. }
  52. this.toplevelPagesDict;
  53. this._actualNumPages = null;
  54. this.fontCache = new _primitives.RefSetCache();
  55. this.builtInCMapCache = new Map();
  56. this.standardFontDataCache = new Map();
  57. this.globalImageCache = new _image_utils.GlobalImageCache();
  58. this.pageKidsCountCache = new _primitives.RefSetCache();
  59. this.pageIndexCache = new _primitives.RefSetCache();
  60. this.nonBlendModesSet = new _primitives.RefSet();
  61. }
  62. get version() {
  63. const version = this._catDict.get("Version");
  64. if (version instanceof _primitives.Name) {
  65. if (_core_utils.PDF_VERSION_REGEXP.test(version.name)) {
  66. return (0, _util.shadow)(this, "version", version.name);
  67. }
  68. (0, _util.warn)(`Invalid PDF catalog version: ${version.name}`);
  69. }
  70. return (0, _util.shadow)(this, "version", null);
  71. }
  72. get lang() {
  73. const lang = this._catDict.get("Lang");
  74. return (0, _util.shadow)(this, "lang", typeof lang === "string" ? (0, _util.stringToPDFString)(lang) : null);
  75. }
  76. get needsRendering() {
  77. const needsRendering = this._catDict.get("NeedsRendering");
  78. return (0, _util.shadow)(this, "needsRendering", typeof needsRendering === "boolean" ? needsRendering : false);
  79. }
  80. get collection() {
  81. let collection = null;
  82. try {
  83. const obj = this._catDict.get("Collection");
  84. if (obj instanceof _primitives.Dict && obj.size > 0) {
  85. collection = obj;
  86. }
  87. } catch (ex) {
  88. if (ex instanceof _core_utils.MissingDataException) {
  89. throw ex;
  90. }
  91. (0, _util.info)("Cannot fetch Collection entry; assuming no collection is present.");
  92. }
  93. return (0, _util.shadow)(this, "collection", collection);
  94. }
  95. get acroForm() {
  96. let acroForm = null;
  97. try {
  98. const obj = this._catDict.get("AcroForm");
  99. if (obj instanceof _primitives.Dict && obj.size > 0) {
  100. acroForm = obj;
  101. }
  102. } catch (ex) {
  103. if (ex instanceof _core_utils.MissingDataException) {
  104. throw ex;
  105. }
  106. (0, _util.info)("Cannot fetch AcroForm entry; assuming no forms are present.");
  107. }
  108. return (0, _util.shadow)(this, "acroForm", acroForm);
  109. }
  110. get acroFormRef() {
  111. const value = this._catDict.getRaw("AcroForm");
  112. return (0, _util.shadow)(this, "acroFormRef", value instanceof _primitives.Ref ? value : null);
  113. }
  114. get metadata() {
  115. const streamRef = this._catDict.getRaw("Metadata");
  116. if (!(streamRef instanceof _primitives.Ref)) {
  117. return (0, _util.shadow)(this, "metadata", null);
  118. }
  119. let metadata = null;
  120. try {
  121. const suppressEncryption = !(this.xref.encrypt && this.xref.encrypt.encryptMetadata);
  122. const stream = this.xref.fetch(streamRef, suppressEncryption);
  123. if (stream instanceof _base_stream.BaseStream && stream.dict instanceof _primitives.Dict) {
  124. const type = stream.dict.get("Type");
  125. const subtype = stream.dict.get("Subtype");
  126. if ((0, _primitives.isName)(type, "Metadata") && (0, _primitives.isName)(subtype, "XML")) {
  127. const data = (0, _util.stringToUTF8String)(stream.getString());
  128. if (data) {
  129. metadata = new _metadata_parser.MetadataParser(data).serializable;
  130. }
  131. }
  132. }
  133. } catch (ex) {
  134. if (ex instanceof _core_utils.MissingDataException) {
  135. throw ex;
  136. }
  137. (0, _util.info)(`Skipping invalid Metadata: "${ex}".`);
  138. }
  139. return (0, _util.shadow)(this, "metadata", metadata);
  140. }
  141. get markInfo() {
  142. let markInfo = null;
  143. try {
  144. markInfo = this._readMarkInfo();
  145. } catch (ex) {
  146. if (ex instanceof _core_utils.MissingDataException) {
  147. throw ex;
  148. }
  149. (0, _util.warn)("Unable to read mark info.");
  150. }
  151. return (0, _util.shadow)(this, "markInfo", markInfo);
  152. }
  153. _readMarkInfo() {
  154. const obj = this._catDict.get("MarkInfo");
  155. if (!(obj instanceof _primitives.Dict)) {
  156. return null;
  157. }
  158. const markInfo = {
  159. Marked: false,
  160. UserProperties: false,
  161. Suspects: false
  162. };
  163. for (const key in markInfo) {
  164. const value = obj.get(key);
  165. if (typeof value === "boolean") {
  166. markInfo[key] = value;
  167. }
  168. }
  169. return markInfo;
  170. }
  171. get structTreeRoot() {
  172. let structTree = null;
  173. try {
  174. structTree = this._readStructTreeRoot();
  175. } catch (ex) {
  176. if (ex instanceof _core_utils.MissingDataException) {
  177. throw ex;
  178. }
  179. (0, _util.warn)("Unable read to structTreeRoot info.");
  180. }
  181. return (0, _util.shadow)(this, "structTreeRoot", structTree);
  182. }
  183. _readStructTreeRoot() {
  184. const obj = this._catDict.get("StructTreeRoot");
  185. if (!(obj instanceof _primitives.Dict)) {
  186. return null;
  187. }
  188. const root = new _struct_tree.StructTreeRoot(obj);
  189. root.init();
  190. return root;
  191. }
  192. get toplevelPagesDict() {
  193. const pagesObj = this._catDict.get("Pages");
  194. if (!(pagesObj instanceof _primitives.Dict)) {
  195. throw new _util.FormatError("Invalid top-level pages dictionary.");
  196. }
  197. return (0, _util.shadow)(this, "toplevelPagesDict", pagesObj);
  198. }
  199. get documentOutline() {
  200. let obj = null;
  201. try {
  202. obj = this._readDocumentOutline();
  203. } catch (ex) {
  204. if (ex instanceof _core_utils.MissingDataException) {
  205. throw ex;
  206. }
  207. (0, _util.warn)("Unable to read document outline.");
  208. }
  209. return (0, _util.shadow)(this, "documentOutline", obj);
  210. }
  211. _readDocumentOutline() {
  212. let obj = this._catDict.get("Outlines");
  213. if (!(obj instanceof _primitives.Dict)) {
  214. return null;
  215. }
  216. obj = obj.getRaw("First");
  217. if (!(obj instanceof _primitives.Ref)) {
  218. return null;
  219. }
  220. const root = {
  221. items: []
  222. };
  223. const queue = [{
  224. obj,
  225. parent: root
  226. }];
  227. const processed = new _primitives.RefSet();
  228. processed.put(obj);
  229. const xref = this.xref,
  230. blackColor = new Uint8ClampedArray(3);
  231. while (queue.length > 0) {
  232. const i = queue.shift();
  233. const outlineDict = xref.fetchIfRef(i.obj);
  234. if (outlineDict === null) {
  235. continue;
  236. }
  237. if (!outlineDict.has("Title")) {
  238. throw new _util.FormatError("Invalid outline item encountered.");
  239. }
  240. const data = {
  241. url: null,
  242. dest: null,
  243. action: null
  244. };
  245. Catalog.parseDestDictionary({
  246. destDict: outlineDict,
  247. resultObj: data,
  248. docBaseUrl: this.pdfManager.docBaseUrl,
  249. docAttachments: this.attachments
  250. });
  251. const title = outlineDict.get("Title");
  252. const flags = outlineDict.get("F") || 0;
  253. const color = outlineDict.getArray("C");
  254. const count = outlineDict.get("Count");
  255. let rgbColor = blackColor;
  256. if (Array.isArray(color) && color.length === 3 && (color[0] !== 0 || color[1] !== 0 || color[2] !== 0)) {
  257. rgbColor = _colorspace.ColorSpace.singletons.rgb.getRgb(color, 0);
  258. }
  259. const outlineItem = {
  260. action: data.action,
  261. attachment: data.attachment,
  262. dest: data.dest,
  263. url: data.url,
  264. unsafeUrl: data.unsafeUrl,
  265. newWindow: data.newWindow,
  266. setOCGState: data.setOCGState,
  267. title: (0, _util.stringToPDFString)(title),
  268. color: rgbColor,
  269. count: Number.isInteger(count) ? count : undefined,
  270. bold: !!(flags & 2),
  271. italic: !!(flags & 1),
  272. items: []
  273. };
  274. i.parent.items.push(outlineItem);
  275. obj = outlineDict.getRaw("First");
  276. if (obj instanceof _primitives.Ref && !processed.has(obj)) {
  277. queue.push({
  278. obj,
  279. parent: outlineItem
  280. });
  281. processed.put(obj);
  282. }
  283. obj = outlineDict.getRaw("Next");
  284. if (obj instanceof _primitives.Ref && !processed.has(obj)) {
  285. queue.push({
  286. obj,
  287. parent: i.parent
  288. });
  289. processed.put(obj);
  290. }
  291. }
  292. return root.items.length > 0 ? root.items : null;
  293. }
  294. get permissions() {
  295. let permissions = null;
  296. try {
  297. permissions = this._readPermissions();
  298. } catch (ex) {
  299. if (ex instanceof _core_utils.MissingDataException) {
  300. throw ex;
  301. }
  302. (0, _util.warn)("Unable to read permissions.");
  303. }
  304. return (0, _util.shadow)(this, "permissions", permissions);
  305. }
  306. _readPermissions() {
  307. const encrypt = this.xref.trailer.get("Encrypt");
  308. if (!(encrypt instanceof _primitives.Dict)) {
  309. return null;
  310. }
  311. let flags = encrypt.get("P");
  312. if (typeof flags !== "number") {
  313. return null;
  314. }
  315. flags += 2 ** 32;
  316. const permissions = [];
  317. for (const key in _util.PermissionFlag) {
  318. const value = _util.PermissionFlag[key];
  319. if (flags & value) {
  320. permissions.push(value);
  321. }
  322. }
  323. return permissions;
  324. }
  325. get optionalContentConfig() {
  326. let config = null;
  327. try {
  328. const properties = this._catDict.get("OCProperties");
  329. if (!properties) {
  330. return (0, _util.shadow)(this, "optionalContentConfig", null);
  331. }
  332. const defaultConfig = properties.get("D");
  333. if (!defaultConfig) {
  334. return (0, _util.shadow)(this, "optionalContentConfig", null);
  335. }
  336. const groupsData = properties.get("OCGs");
  337. if (!Array.isArray(groupsData)) {
  338. return (0, _util.shadow)(this, "optionalContentConfig", null);
  339. }
  340. const groups = [];
  341. const groupRefs = [];
  342. for (const groupRef of groupsData) {
  343. if (!(groupRef instanceof _primitives.Ref)) {
  344. continue;
  345. }
  346. groupRefs.push(groupRef);
  347. const group = this.xref.fetchIfRef(groupRef);
  348. groups.push({
  349. id: groupRef.toString(),
  350. name: typeof group.get("Name") === "string" ? (0, _util.stringToPDFString)(group.get("Name")) : null,
  351. intent: typeof group.get("Intent") === "string" ? (0, _util.stringToPDFString)(group.get("Intent")) : null
  352. });
  353. }
  354. config = this._readOptionalContentConfig(defaultConfig, groupRefs);
  355. config.groups = groups;
  356. } catch (ex) {
  357. if (ex instanceof _core_utils.MissingDataException) {
  358. throw ex;
  359. }
  360. (0, _util.warn)(`Unable to read optional content config: ${ex}`);
  361. }
  362. return (0, _util.shadow)(this, "optionalContentConfig", config);
  363. }
  364. _readOptionalContentConfig(config, contentGroupRefs) {
  365. function parseOnOff(refs) {
  366. const onParsed = [];
  367. if (Array.isArray(refs)) {
  368. for (const value of refs) {
  369. if (!(value instanceof _primitives.Ref)) {
  370. continue;
  371. }
  372. if (contentGroupRefs.includes(value)) {
  373. onParsed.push(value.toString());
  374. }
  375. }
  376. }
  377. return onParsed;
  378. }
  379. function parseOrder(refs, nestedLevels = 0) {
  380. if (!Array.isArray(refs)) {
  381. return null;
  382. }
  383. const order = [];
  384. for (const value of refs) {
  385. if (value instanceof _primitives.Ref && contentGroupRefs.includes(value)) {
  386. parsedOrderRefs.put(value);
  387. order.push(value.toString());
  388. continue;
  389. }
  390. const nestedOrder = parseNestedOrder(value, nestedLevels);
  391. if (nestedOrder) {
  392. order.push(nestedOrder);
  393. }
  394. }
  395. if (nestedLevels > 0) {
  396. return order;
  397. }
  398. const hiddenGroups = [];
  399. for (const groupRef of contentGroupRefs) {
  400. if (parsedOrderRefs.has(groupRef)) {
  401. continue;
  402. }
  403. hiddenGroups.push(groupRef.toString());
  404. }
  405. if (hiddenGroups.length) {
  406. order.push({
  407. name: null,
  408. order: hiddenGroups
  409. });
  410. }
  411. return order;
  412. }
  413. function parseNestedOrder(ref, nestedLevels) {
  414. if (++nestedLevels > MAX_NESTED_LEVELS) {
  415. (0, _util.warn)("parseNestedOrder - reached MAX_NESTED_LEVELS.");
  416. return null;
  417. }
  418. const value = xref.fetchIfRef(ref);
  419. if (!Array.isArray(value)) {
  420. return null;
  421. }
  422. const nestedName = xref.fetchIfRef(value[0]);
  423. if (typeof nestedName !== "string") {
  424. return null;
  425. }
  426. const nestedOrder = parseOrder(value.slice(1), nestedLevels);
  427. if (!nestedOrder || !nestedOrder.length) {
  428. return null;
  429. }
  430. return {
  431. name: (0, _util.stringToPDFString)(nestedName),
  432. order: nestedOrder
  433. };
  434. }
  435. const xref = this.xref,
  436. parsedOrderRefs = new _primitives.RefSet(),
  437. MAX_NESTED_LEVELS = 10;
  438. return {
  439. name: typeof config.get("Name") === "string" ? (0, _util.stringToPDFString)(config.get("Name")) : null,
  440. creator: typeof config.get("Creator") === "string" ? (0, _util.stringToPDFString)(config.get("Creator")) : null,
  441. baseState: config.get("BaseState") instanceof _primitives.Name ? config.get("BaseState").name : null,
  442. on: parseOnOff(config.get("ON")),
  443. off: parseOnOff(config.get("OFF")),
  444. order: parseOrder(config.get("Order")),
  445. groups: null
  446. };
  447. }
  448. setActualNumPages(num = null) {
  449. this._actualNumPages = num;
  450. }
  451. get hasActualNumPages() {
  452. return this._actualNumPages !== null;
  453. }
  454. get _pagesCount() {
  455. const obj = this.toplevelPagesDict.get("Count");
  456. if (!Number.isInteger(obj)) {
  457. throw new _util.FormatError("Page count in top-level pages dictionary is not an integer.");
  458. }
  459. return (0, _util.shadow)(this, "_pagesCount", obj);
  460. }
  461. get numPages() {
  462. return this.hasActualNumPages ? this._actualNumPages : this._pagesCount;
  463. }
  464. get destinations() {
  465. const obj = this._readDests(),
  466. dests = Object.create(null);
  467. if (obj instanceof _name_number_tree.NameTree) {
  468. for (const [key, value] of obj.getAll()) {
  469. const dest = fetchDestination(value);
  470. if (dest) {
  471. dests[(0, _util.stringToPDFString)(key)] = dest;
  472. }
  473. }
  474. } else if (obj instanceof _primitives.Dict) {
  475. obj.forEach(function (key, value) {
  476. const dest = fetchDestination(value);
  477. if (dest) {
  478. dests[key] = dest;
  479. }
  480. });
  481. }
  482. return (0, _util.shadow)(this, "destinations", dests);
  483. }
  484. getDestination(id) {
  485. const obj = this._readDests();
  486. if (obj instanceof _name_number_tree.NameTree) {
  487. const dest = fetchDestination(obj.get(id));
  488. if (dest) {
  489. return dest;
  490. }
  491. const allDest = this.destinations[id];
  492. if (allDest) {
  493. (0, _util.warn)(`Found "${id}" at an incorrect position in the NameTree.`);
  494. return allDest;
  495. }
  496. } else if (obj instanceof _primitives.Dict) {
  497. const dest = fetchDestination(obj.get(id));
  498. if (dest) {
  499. return dest;
  500. }
  501. }
  502. return null;
  503. }
  504. _readDests() {
  505. const obj = this._catDict.get("Names");
  506. if (obj && obj.has("Dests")) {
  507. return new _name_number_tree.NameTree(obj.getRaw("Dests"), this.xref);
  508. } else if (this._catDict.has("Dests")) {
  509. return this._catDict.get("Dests");
  510. }
  511. return undefined;
  512. }
  513. get pageLabels() {
  514. let obj = null;
  515. try {
  516. obj = this._readPageLabels();
  517. } catch (ex) {
  518. if (ex instanceof _core_utils.MissingDataException) {
  519. throw ex;
  520. }
  521. (0, _util.warn)("Unable to read page labels.");
  522. }
  523. return (0, _util.shadow)(this, "pageLabels", obj);
  524. }
  525. _readPageLabels() {
  526. const obj = this._catDict.getRaw("PageLabels");
  527. if (!obj) {
  528. return null;
  529. }
  530. const pageLabels = new Array(this.numPages);
  531. let style = null,
  532. prefix = "";
  533. const numberTree = new _name_number_tree.NumberTree(obj, this.xref);
  534. const nums = numberTree.getAll();
  535. let currentLabel = "",
  536. currentIndex = 1;
  537. for (let i = 0, ii = this.numPages; i < ii; i++) {
  538. const labelDict = nums.get(i);
  539. if (labelDict !== undefined) {
  540. if (!(labelDict instanceof _primitives.Dict)) {
  541. throw new _util.FormatError("PageLabel is not a dictionary.");
  542. }
  543. if (labelDict.has("Type") && !(0, _primitives.isName)(labelDict.get("Type"), "PageLabel")) {
  544. throw new _util.FormatError("Invalid type in PageLabel dictionary.");
  545. }
  546. if (labelDict.has("S")) {
  547. const s = labelDict.get("S");
  548. if (!(s instanceof _primitives.Name)) {
  549. throw new _util.FormatError("Invalid style in PageLabel dictionary.");
  550. }
  551. style = s.name;
  552. } else {
  553. style = null;
  554. }
  555. if (labelDict.has("P")) {
  556. const p = labelDict.get("P");
  557. if (typeof p !== "string") {
  558. throw new _util.FormatError("Invalid prefix in PageLabel dictionary.");
  559. }
  560. prefix = (0, _util.stringToPDFString)(p);
  561. } else {
  562. prefix = "";
  563. }
  564. if (labelDict.has("St")) {
  565. const st = labelDict.get("St");
  566. if (!(Number.isInteger(st) && st >= 1)) {
  567. throw new _util.FormatError("Invalid start in PageLabel dictionary.");
  568. }
  569. currentIndex = st;
  570. } else {
  571. currentIndex = 1;
  572. }
  573. }
  574. switch (style) {
  575. case "D":
  576. currentLabel = currentIndex;
  577. break;
  578. case "R":
  579. case "r":
  580. currentLabel = (0, _core_utils.toRomanNumerals)(currentIndex, style === "r");
  581. break;
  582. case "A":
  583. case "a":
  584. const LIMIT = 26;
  585. const A_UPPER_CASE = 0x41,
  586. A_LOWER_CASE = 0x61;
  587. const baseCharCode = style === "a" ? A_LOWER_CASE : A_UPPER_CASE;
  588. const letterIndex = currentIndex - 1;
  589. const character = String.fromCharCode(baseCharCode + letterIndex % LIMIT);
  590. currentLabel = character.repeat(Math.floor(letterIndex / LIMIT) + 1);
  591. break;
  592. default:
  593. if (style) {
  594. throw new _util.FormatError(`Invalid style "${style}" in PageLabel dictionary.`);
  595. }
  596. currentLabel = "";
  597. }
  598. pageLabels[i] = prefix + currentLabel;
  599. currentIndex++;
  600. }
  601. return pageLabels;
  602. }
  603. get pageLayout() {
  604. const obj = this._catDict.get("PageLayout");
  605. let pageLayout = "";
  606. if (obj instanceof _primitives.Name) {
  607. switch (obj.name) {
  608. case "SinglePage":
  609. case "OneColumn":
  610. case "TwoColumnLeft":
  611. case "TwoColumnRight":
  612. case "TwoPageLeft":
  613. case "TwoPageRight":
  614. pageLayout = obj.name;
  615. }
  616. }
  617. return (0, _util.shadow)(this, "pageLayout", pageLayout);
  618. }
  619. get pageMode() {
  620. const obj = this._catDict.get("PageMode");
  621. let pageMode = "UseNone";
  622. if (obj instanceof _primitives.Name) {
  623. switch (obj.name) {
  624. case "UseNone":
  625. case "UseOutlines":
  626. case "UseThumbs":
  627. case "FullScreen":
  628. case "UseOC":
  629. case "UseAttachments":
  630. pageMode = obj.name;
  631. }
  632. }
  633. return (0, _util.shadow)(this, "pageMode", pageMode);
  634. }
  635. get viewerPreferences() {
  636. const obj = this._catDict.get("ViewerPreferences");
  637. if (!(obj instanceof _primitives.Dict)) {
  638. return (0, _util.shadow)(this, "viewerPreferences", null);
  639. }
  640. let prefs = null;
  641. for (const key of obj.getKeys()) {
  642. const value = obj.get(key);
  643. let prefValue;
  644. switch (key) {
  645. case "HideToolbar":
  646. case "HideMenubar":
  647. case "HideWindowUI":
  648. case "FitWindow":
  649. case "CenterWindow":
  650. case "DisplayDocTitle":
  651. case "PickTrayByPDFSize":
  652. if (typeof value === "boolean") {
  653. prefValue = value;
  654. }
  655. break;
  656. case "NonFullScreenPageMode":
  657. if (value instanceof _primitives.Name) {
  658. switch (value.name) {
  659. case "UseNone":
  660. case "UseOutlines":
  661. case "UseThumbs":
  662. case "UseOC":
  663. prefValue = value.name;
  664. break;
  665. default:
  666. prefValue = "UseNone";
  667. }
  668. }
  669. break;
  670. case "Direction":
  671. if (value instanceof _primitives.Name) {
  672. switch (value.name) {
  673. case "L2R":
  674. case "R2L":
  675. prefValue = value.name;
  676. break;
  677. default:
  678. prefValue = "L2R";
  679. }
  680. }
  681. break;
  682. case "ViewArea":
  683. case "ViewClip":
  684. case "PrintArea":
  685. case "PrintClip":
  686. if (value instanceof _primitives.Name) {
  687. switch (value.name) {
  688. case "MediaBox":
  689. case "CropBox":
  690. case "BleedBox":
  691. case "TrimBox":
  692. case "ArtBox":
  693. prefValue = value.name;
  694. break;
  695. default:
  696. prefValue = "CropBox";
  697. }
  698. }
  699. break;
  700. case "PrintScaling":
  701. if (value instanceof _primitives.Name) {
  702. switch (value.name) {
  703. case "None":
  704. case "AppDefault":
  705. prefValue = value.name;
  706. break;
  707. default:
  708. prefValue = "AppDefault";
  709. }
  710. }
  711. break;
  712. case "Duplex":
  713. if (value instanceof _primitives.Name) {
  714. switch (value.name) {
  715. case "Simplex":
  716. case "DuplexFlipShortEdge":
  717. case "DuplexFlipLongEdge":
  718. prefValue = value.name;
  719. break;
  720. default:
  721. prefValue = "None";
  722. }
  723. }
  724. break;
  725. case "PrintPageRange":
  726. if (Array.isArray(value) && value.length % 2 === 0) {
  727. const isValid = value.every((page, i, arr) => {
  728. return Number.isInteger(page) && page > 0 && (i === 0 || page >= arr[i - 1]) && page <= this.numPages;
  729. });
  730. if (isValid) {
  731. prefValue = value;
  732. }
  733. }
  734. break;
  735. case "NumCopies":
  736. if (Number.isInteger(value) && value > 0) {
  737. prefValue = value;
  738. }
  739. break;
  740. default:
  741. (0, _util.warn)(`Ignoring non-standard key in ViewerPreferences: ${key}.`);
  742. continue;
  743. }
  744. if (prefValue === undefined) {
  745. (0, _util.warn)(`Bad value, for key "${key}", in ViewerPreferences: ${value}.`);
  746. continue;
  747. }
  748. if (!prefs) {
  749. prefs = Object.create(null);
  750. }
  751. prefs[key] = prefValue;
  752. }
  753. return (0, _util.shadow)(this, "viewerPreferences", prefs);
  754. }
  755. get openAction() {
  756. const obj = this._catDict.get("OpenAction");
  757. const openAction = Object.create(null);
  758. if (obj instanceof _primitives.Dict) {
  759. const destDict = new _primitives.Dict(this.xref);
  760. destDict.set("A", obj);
  761. const resultObj = {
  762. url: null,
  763. dest: null,
  764. action: null
  765. };
  766. Catalog.parseDestDictionary({
  767. destDict,
  768. resultObj
  769. });
  770. if (Array.isArray(resultObj.dest)) {
  771. openAction.dest = resultObj.dest;
  772. } else if (resultObj.action) {
  773. openAction.action = resultObj.action;
  774. }
  775. } else if (Array.isArray(obj)) {
  776. openAction.dest = obj;
  777. }
  778. return (0, _util.shadow)(this, "openAction", (0, _util.objectSize)(openAction) > 0 ? openAction : null);
  779. }
  780. get attachments() {
  781. const obj = this._catDict.get("Names");
  782. let attachments = null;
  783. if (obj instanceof _primitives.Dict && obj.has("EmbeddedFiles")) {
  784. const nameTree = new _name_number_tree.NameTree(obj.getRaw("EmbeddedFiles"), this.xref);
  785. for (const [key, value] of nameTree.getAll()) {
  786. const fs = new _file_spec.FileSpec(value, this.xref);
  787. if (!attachments) {
  788. attachments = Object.create(null);
  789. }
  790. attachments[(0, _util.stringToPDFString)(key)] = fs.serializable;
  791. }
  792. }
  793. return (0, _util.shadow)(this, "attachments", attachments);
  794. }
  795. get xfaImages() {
  796. const obj = this._catDict.get("Names");
  797. let xfaImages = null;
  798. if (obj instanceof _primitives.Dict && obj.has("XFAImages")) {
  799. const nameTree = new _name_number_tree.NameTree(obj.getRaw("XFAImages"), this.xref);
  800. for (const [key, value] of nameTree.getAll()) {
  801. if (!xfaImages) {
  802. xfaImages = new _primitives.Dict(this.xref);
  803. }
  804. xfaImages.set((0, _util.stringToPDFString)(key), value);
  805. }
  806. }
  807. return (0, _util.shadow)(this, "xfaImages", xfaImages);
  808. }
  809. _collectJavaScript() {
  810. const obj = this._catDict.get("Names");
  811. let javaScript = null;
  812. function appendIfJavaScriptDict(name, jsDict) {
  813. if (!(jsDict instanceof _primitives.Dict)) {
  814. return;
  815. }
  816. if (!(0, _primitives.isName)(jsDict.get("S"), "JavaScript")) {
  817. return;
  818. }
  819. let js = jsDict.get("JS");
  820. if (js instanceof _base_stream.BaseStream) {
  821. js = js.getString();
  822. } else if (typeof js !== "string") {
  823. return;
  824. }
  825. if (javaScript === null) {
  826. javaScript = new Map();
  827. }
  828. js = (0, _util.stringToPDFString)(js).replace(/\u0000/g, "");
  829. javaScript.set(name, js);
  830. }
  831. if (obj instanceof _primitives.Dict && obj.has("JavaScript")) {
  832. const nameTree = new _name_number_tree.NameTree(obj.getRaw("JavaScript"), this.xref);
  833. for (const [key, value] of nameTree.getAll()) {
  834. appendIfJavaScriptDict((0, _util.stringToPDFString)(key), value);
  835. }
  836. }
  837. const openAction = this._catDict.get("OpenAction");
  838. if (openAction) {
  839. appendIfJavaScriptDict("OpenAction", openAction);
  840. }
  841. return javaScript;
  842. }
  843. get javaScript() {
  844. const javaScript = this._collectJavaScript();
  845. return (0, _util.shadow)(this, "javaScript", javaScript ? [...javaScript.values()] : null);
  846. }
  847. get jsActions() {
  848. const javaScript = this._collectJavaScript();
  849. let actions = (0, _core_utils.collectActions)(this.xref, this._catDict, _util.DocumentActionEventType);
  850. if (javaScript) {
  851. if (!actions) {
  852. actions = Object.create(null);
  853. }
  854. for (const [key, val] of javaScript) {
  855. if (key in actions) {
  856. actions[key].push(val);
  857. } else {
  858. actions[key] = [val];
  859. }
  860. }
  861. }
  862. return (0, _util.shadow)(this, "jsActions", actions);
  863. }
  864. async fontFallback(id, handler) {
  865. const translatedFonts = await Promise.all(this.fontCache);
  866. for (const translatedFont of translatedFonts) {
  867. if (translatedFont.loadedName === id) {
  868. translatedFont.fallback(handler);
  869. return;
  870. }
  871. }
  872. }
  873. async cleanup(manuallyTriggered = false) {
  874. (0, _cleanup_helper.clearGlobalCaches)();
  875. this.globalImageCache.clear(manuallyTriggered);
  876. this.pageKidsCountCache.clear();
  877. this.pageIndexCache.clear();
  878. this.nonBlendModesSet.clear();
  879. const translatedFonts = await Promise.all(this.fontCache);
  880. for (const {
  881. dict
  882. } of translatedFonts) {
  883. delete dict.cacheKey;
  884. }
  885. this.fontCache.clear();
  886. this.builtInCMapCache.clear();
  887. this.standardFontDataCache.clear();
  888. }
  889. async getPageDict(pageIndex) {
  890. const nodesToVisit = [this.toplevelPagesDict];
  891. const visitedNodes = new _primitives.RefSet();
  892. const pagesRef = this._catDict.getRaw("Pages");
  893. if (pagesRef instanceof _primitives.Ref) {
  894. visitedNodes.put(pagesRef);
  895. }
  896. const xref = this.xref,
  897. pageKidsCountCache = this.pageKidsCountCache,
  898. pageIndexCache = this.pageIndexCache;
  899. let currentPageIndex = 0;
  900. while (nodesToVisit.length) {
  901. const currentNode = nodesToVisit.pop();
  902. if (currentNode instanceof _primitives.Ref) {
  903. const count = pageKidsCountCache.get(currentNode);
  904. if (count >= 0 && currentPageIndex + count <= pageIndex) {
  905. currentPageIndex += count;
  906. continue;
  907. }
  908. if (visitedNodes.has(currentNode)) {
  909. throw new _util.FormatError("Pages tree contains circular reference.");
  910. }
  911. visitedNodes.put(currentNode);
  912. const obj = await xref.fetchAsync(currentNode);
  913. if (obj instanceof _primitives.Dict) {
  914. let type = obj.getRaw("Type");
  915. if (type instanceof _primitives.Ref) {
  916. type = await xref.fetchAsync(type);
  917. }
  918. if ((0, _primitives.isName)(type, "Page") || !obj.has("Kids")) {
  919. if (!pageKidsCountCache.has(currentNode)) {
  920. pageKidsCountCache.put(currentNode, 1);
  921. }
  922. if (!pageIndexCache.has(currentNode)) {
  923. pageIndexCache.put(currentNode, currentPageIndex);
  924. }
  925. if (currentPageIndex === pageIndex) {
  926. return [obj, currentNode];
  927. }
  928. currentPageIndex++;
  929. continue;
  930. }
  931. }
  932. nodesToVisit.push(obj);
  933. continue;
  934. }
  935. if (!(currentNode instanceof _primitives.Dict)) {
  936. throw new _util.FormatError("Page dictionary kid reference points to wrong type of object.");
  937. }
  938. const {
  939. objId
  940. } = currentNode;
  941. let count = currentNode.getRaw("Count");
  942. if (count instanceof _primitives.Ref) {
  943. count = await xref.fetchAsync(count);
  944. }
  945. if (Number.isInteger(count) && count >= 0) {
  946. if (objId && !pageKidsCountCache.has(objId)) {
  947. pageKidsCountCache.put(objId, count);
  948. }
  949. if (currentPageIndex + count <= pageIndex) {
  950. currentPageIndex += count;
  951. continue;
  952. }
  953. }
  954. let kids = currentNode.getRaw("Kids");
  955. if (kids instanceof _primitives.Ref) {
  956. kids = await xref.fetchAsync(kids);
  957. }
  958. if (!Array.isArray(kids)) {
  959. let type = currentNode.getRaw("Type");
  960. if (type instanceof _primitives.Ref) {
  961. type = await xref.fetchAsync(type);
  962. }
  963. if ((0, _primitives.isName)(type, "Page") || !currentNode.has("Kids")) {
  964. if (currentPageIndex === pageIndex) {
  965. return [currentNode, null];
  966. }
  967. currentPageIndex++;
  968. continue;
  969. }
  970. throw new _util.FormatError("Page dictionary kids object is not an array.");
  971. }
  972. for (let last = kids.length - 1; last >= 0; last--) {
  973. nodesToVisit.push(kids[last]);
  974. }
  975. }
  976. throw new Error(`Page index ${pageIndex} not found.`);
  977. }
  978. async getAllPageDicts(recoveryMode = false) {
  979. const queue = [{
  980. currentNode: this.toplevelPagesDict,
  981. posInKids: 0
  982. }];
  983. const visitedNodes = new _primitives.RefSet();
  984. const pagesRef = this._catDict.getRaw("Pages");
  985. if (pagesRef instanceof _primitives.Ref) {
  986. visitedNodes.put(pagesRef);
  987. }
  988. const map = new Map(),
  989. xref = this.xref,
  990. pageIndexCache = this.pageIndexCache;
  991. let pageIndex = 0;
  992. function addPageDict(pageDict, pageRef) {
  993. if (pageRef && !pageIndexCache.has(pageRef)) {
  994. pageIndexCache.put(pageRef, pageIndex);
  995. }
  996. map.set(pageIndex++, [pageDict, pageRef]);
  997. }
  998. function addPageError(error) {
  999. if (error instanceof _core_utils.XRefEntryException && !recoveryMode) {
  1000. throw error;
  1001. }
  1002. map.set(pageIndex++, [error, null]);
  1003. }
  1004. while (queue.length > 0) {
  1005. const queueItem = queue.at(-1);
  1006. const {
  1007. currentNode,
  1008. posInKids
  1009. } = queueItem;
  1010. let kids = currentNode.getRaw("Kids");
  1011. if (kids instanceof _primitives.Ref) {
  1012. try {
  1013. kids = await xref.fetchAsync(kids);
  1014. } catch (ex) {
  1015. addPageError(ex);
  1016. break;
  1017. }
  1018. }
  1019. if (!Array.isArray(kids)) {
  1020. addPageError(new _util.FormatError("Page dictionary kids object is not an array."));
  1021. break;
  1022. }
  1023. if (posInKids >= kids.length) {
  1024. queue.pop();
  1025. continue;
  1026. }
  1027. const kidObj = kids[posInKids];
  1028. let obj;
  1029. if (kidObj instanceof _primitives.Ref) {
  1030. if (visitedNodes.has(kidObj)) {
  1031. addPageError(new _util.FormatError("Pages tree contains circular reference."));
  1032. break;
  1033. }
  1034. visitedNodes.put(kidObj);
  1035. try {
  1036. obj = await xref.fetchAsync(kidObj);
  1037. } catch (ex) {
  1038. addPageError(ex);
  1039. break;
  1040. }
  1041. } else {
  1042. obj = kidObj;
  1043. }
  1044. if (!(obj instanceof _primitives.Dict)) {
  1045. addPageError(new _util.FormatError("Page dictionary kid reference points to wrong type of object."));
  1046. break;
  1047. }
  1048. let type = obj.getRaw("Type");
  1049. if (type instanceof _primitives.Ref) {
  1050. try {
  1051. type = await xref.fetchAsync(type);
  1052. } catch (ex) {
  1053. addPageError(ex);
  1054. break;
  1055. }
  1056. }
  1057. if ((0, _primitives.isName)(type, "Page") || !obj.has("Kids")) {
  1058. addPageDict(obj, kidObj instanceof _primitives.Ref ? kidObj : null);
  1059. } else {
  1060. queue.push({
  1061. currentNode: obj,
  1062. posInKids: 0
  1063. });
  1064. }
  1065. queueItem.posInKids++;
  1066. }
  1067. return map;
  1068. }
  1069. getPageIndex(pageRef) {
  1070. const cachedPageIndex = this.pageIndexCache.get(pageRef);
  1071. if (cachedPageIndex !== undefined) {
  1072. return Promise.resolve(cachedPageIndex);
  1073. }
  1074. const xref = this.xref;
  1075. function pagesBeforeRef(kidRef) {
  1076. let total = 0,
  1077. parentRef;
  1078. return xref.fetchAsync(kidRef).then(function (node) {
  1079. if ((0, _primitives.isRefsEqual)(kidRef, pageRef) && !(0, _primitives.isDict)(node, "Page") && !(node instanceof _primitives.Dict && !node.has("Type") && node.has("Contents"))) {
  1080. throw new _util.FormatError("The reference does not point to a /Page dictionary.");
  1081. }
  1082. if (!node) {
  1083. return null;
  1084. }
  1085. if (!(node instanceof _primitives.Dict)) {
  1086. throw new _util.FormatError("Node must be a dictionary.");
  1087. }
  1088. parentRef = node.getRaw("Parent");
  1089. return node.getAsync("Parent");
  1090. }).then(function (parent) {
  1091. if (!parent) {
  1092. return null;
  1093. }
  1094. if (!(parent instanceof _primitives.Dict)) {
  1095. throw new _util.FormatError("Parent must be a dictionary.");
  1096. }
  1097. return parent.getAsync("Kids");
  1098. }).then(function (kids) {
  1099. if (!kids) {
  1100. return null;
  1101. }
  1102. const kidPromises = [];
  1103. let found = false;
  1104. for (const kid of kids) {
  1105. if (!(kid instanceof _primitives.Ref)) {
  1106. throw new _util.FormatError("Kid must be a reference.");
  1107. }
  1108. if ((0, _primitives.isRefsEqual)(kid, kidRef)) {
  1109. found = true;
  1110. break;
  1111. }
  1112. kidPromises.push(xref.fetchAsync(kid).then(function (obj) {
  1113. if (!(obj instanceof _primitives.Dict)) {
  1114. throw new _util.FormatError("Kid node must be a dictionary.");
  1115. }
  1116. if (obj.has("Count")) {
  1117. total += obj.get("Count");
  1118. } else {
  1119. total++;
  1120. }
  1121. }));
  1122. }
  1123. if (!found) {
  1124. throw new _util.FormatError("Kid reference not found in parent's kids.");
  1125. }
  1126. return Promise.all(kidPromises).then(function () {
  1127. return [total, parentRef];
  1128. });
  1129. });
  1130. }
  1131. let total = 0;
  1132. const next = ref => pagesBeforeRef(ref).then(args => {
  1133. if (!args) {
  1134. this.pageIndexCache.put(pageRef, total);
  1135. return total;
  1136. }
  1137. const [count, parentRef] = args;
  1138. total += count;
  1139. return next(parentRef);
  1140. });
  1141. return next(pageRef);
  1142. }
  1143. get baseUrl() {
  1144. const uri = this._catDict.get("URI");
  1145. if (uri instanceof _primitives.Dict) {
  1146. const base = uri.get("Base");
  1147. if (typeof base === "string") {
  1148. const absoluteUrl = (0, _util.createValidAbsoluteUrl)(base, null, {
  1149. tryConvertEncoding: true
  1150. });
  1151. if (absoluteUrl) {
  1152. return (0, _util.shadow)(this, "baseUrl", absoluteUrl.href);
  1153. }
  1154. }
  1155. }
  1156. return (0, _util.shadow)(this, "baseUrl", null);
  1157. }
  1158. static parseDestDictionary(params) {
  1159. const destDict = params.destDict;
  1160. if (!(destDict instanceof _primitives.Dict)) {
  1161. (0, _util.warn)("parseDestDictionary: `destDict` must be a dictionary.");
  1162. return;
  1163. }
  1164. const resultObj = params.resultObj;
  1165. if (typeof resultObj !== "object") {
  1166. (0, _util.warn)("parseDestDictionary: `resultObj` must be an object.");
  1167. return;
  1168. }
  1169. const docBaseUrl = params.docBaseUrl || null;
  1170. const docAttachments = params.docAttachments || null;
  1171. let action = destDict.get("A"),
  1172. url,
  1173. dest;
  1174. if (!(action instanceof _primitives.Dict)) {
  1175. if (destDict.has("Dest")) {
  1176. action = destDict.get("Dest");
  1177. } else {
  1178. action = destDict.get("AA");
  1179. if (action instanceof _primitives.Dict) {
  1180. if (action.has("D")) {
  1181. action = action.get("D");
  1182. } else if (action.has("U")) {
  1183. action = action.get("U");
  1184. }
  1185. }
  1186. }
  1187. }
  1188. if (action instanceof _primitives.Dict) {
  1189. const actionType = action.get("S");
  1190. if (!(actionType instanceof _primitives.Name)) {
  1191. (0, _util.warn)("parseDestDictionary: Invalid type in Action dictionary.");
  1192. return;
  1193. }
  1194. const actionName = actionType.name;
  1195. switch (actionName) {
  1196. case "ResetForm":
  1197. const flags = action.get("Flags");
  1198. const include = ((typeof flags === "number" ? flags : 0) & 1) === 0;
  1199. const fields = [];
  1200. const refs = [];
  1201. for (const obj of action.get("Fields") || []) {
  1202. if (obj instanceof _primitives.Ref) {
  1203. refs.push(obj.toString());
  1204. } else if (typeof obj === "string") {
  1205. fields.push((0, _util.stringToPDFString)(obj));
  1206. }
  1207. }
  1208. resultObj.resetForm = {
  1209. fields,
  1210. refs,
  1211. include
  1212. };
  1213. break;
  1214. case "URI":
  1215. url = action.get("URI");
  1216. if (url instanceof _primitives.Name) {
  1217. url = "/" + url.name;
  1218. }
  1219. break;
  1220. case "GoTo":
  1221. dest = action.get("D");
  1222. break;
  1223. case "Launch":
  1224. case "GoToR":
  1225. const urlDict = action.get("F");
  1226. if (urlDict instanceof _primitives.Dict) {
  1227. url = urlDict.get("F") || null;
  1228. } else if (typeof urlDict === "string") {
  1229. url = urlDict;
  1230. }
  1231. let remoteDest = action.get("D");
  1232. if (remoteDest) {
  1233. if (remoteDest instanceof _primitives.Name) {
  1234. remoteDest = remoteDest.name;
  1235. }
  1236. if (typeof url === "string") {
  1237. const baseUrl = url.split("#")[0];
  1238. if (typeof remoteDest === "string") {
  1239. url = baseUrl + "#" + remoteDest;
  1240. } else if (Array.isArray(remoteDest)) {
  1241. url = baseUrl + "#" + JSON.stringify(remoteDest);
  1242. }
  1243. }
  1244. }
  1245. const newWindow = action.get("NewWindow");
  1246. if (typeof newWindow === "boolean") {
  1247. resultObj.newWindow = newWindow;
  1248. }
  1249. break;
  1250. case "GoToE":
  1251. const target = action.get("T");
  1252. let attachment;
  1253. if (docAttachments && target instanceof _primitives.Dict) {
  1254. const relationship = target.get("R");
  1255. const name = target.get("N");
  1256. if ((0, _primitives.isName)(relationship, "C") && typeof name === "string") {
  1257. attachment = docAttachments[(0, _util.stringToPDFString)(name)];
  1258. }
  1259. }
  1260. if (attachment) {
  1261. resultObj.attachment = attachment;
  1262. } else {
  1263. (0, _util.warn)(`parseDestDictionary - unimplemented "GoToE" action.`);
  1264. }
  1265. break;
  1266. case "Named":
  1267. const namedAction = action.get("N");
  1268. if (namedAction instanceof _primitives.Name) {
  1269. resultObj.action = namedAction.name;
  1270. }
  1271. break;
  1272. case "SetOCGState":
  1273. const state = action.get("State");
  1274. const preserveRB = action.get("PreserveRB");
  1275. if (!Array.isArray(state) || state.length === 0) {
  1276. break;
  1277. }
  1278. const stateArr = [];
  1279. for (const elem of state) {
  1280. if (elem instanceof _primitives.Name) {
  1281. switch (elem.name) {
  1282. case "ON":
  1283. case "OFF":
  1284. case "Toggle":
  1285. stateArr.push(elem.name);
  1286. break;
  1287. }
  1288. } else if (elem instanceof _primitives.Ref) {
  1289. stateArr.push(elem.toString());
  1290. }
  1291. }
  1292. if (stateArr.length !== state.length) {
  1293. break;
  1294. }
  1295. resultObj.setOCGState = {
  1296. state: stateArr,
  1297. preserveRB: typeof preserveRB === "boolean" ? preserveRB : true
  1298. };
  1299. break;
  1300. case "JavaScript":
  1301. const jsAction = action.get("JS");
  1302. let js;
  1303. if (jsAction instanceof _base_stream.BaseStream) {
  1304. js = jsAction.getString();
  1305. } else if (typeof jsAction === "string") {
  1306. js = jsAction;
  1307. }
  1308. const jsURL = js && (0, _core_utils.recoverJsURL)((0, _util.stringToPDFString)(js));
  1309. if (jsURL) {
  1310. url = jsURL.url;
  1311. resultObj.newWindow = jsURL.newWindow;
  1312. break;
  1313. }
  1314. default:
  1315. if (actionName === "JavaScript" || actionName === "SubmitForm") {
  1316. break;
  1317. }
  1318. (0, _util.warn)(`parseDestDictionary - unsupported action: "${actionName}".`);
  1319. break;
  1320. }
  1321. } else if (destDict.has("Dest")) {
  1322. dest = destDict.get("Dest");
  1323. }
  1324. if (typeof url === "string") {
  1325. const absoluteUrl = (0, _util.createValidAbsoluteUrl)(url, docBaseUrl, {
  1326. addDefaultProtocol: true,
  1327. tryConvertEncoding: true
  1328. });
  1329. if (absoluteUrl) {
  1330. resultObj.url = absoluteUrl.href;
  1331. }
  1332. resultObj.unsafeUrl = url;
  1333. }
  1334. if (dest) {
  1335. if (dest instanceof _primitives.Name) {
  1336. dest = dest.name;
  1337. }
  1338. if (typeof dest === "string") {
  1339. resultObj.dest = (0, _util.stringToPDFString)(dest);
  1340. } else if (Array.isArray(dest)) {
  1341. resultObj.dest = dest;
  1342. }
  1343. }
  1344. }
  1345. }
  1346. exports.Catalog = Catalog;