catalog.js 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354
  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 {
  980. ignoreErrors
  981. } = this.pdfManager.evaluatorOptions;
  982. const queue = [{
  983. currentNode: this.toplevelPagesDict,
  984. posInKids: 0
  985. }];
  986. const visitedNodes = new _primitives.RefSet();
  987. const pagesRef = this._catDict.getRaw("Pages");
  988. if (pagesRef instanceof _primitives.Ref) {
  989. visitedNodes.put(pagesRef);
  990. }
  991. const map = new Map(),
  992. xref = this.xref,
  993. pageIndexCache = this.pageIndexCache;
  994. let pageIndex = 0;
  995. function addPageDict(pageDict, pageRef) {
  996. if (pageRef && !pageIndexCache.has(pageRef)) {
  997. pageIndexCache.put(pageRef, pageIndex);
  998. }
  999. map.set(pageIndex++, [pageDict, pageRef]);
  1000. }
  1001. function addPageError(error) {
  1002. if (error instanceof _core_utils.XRefEntryException && !recoveryMode) {
  1003. throw error;
  1004. }
  1005. if (recoveryMode && ignoreErrors && pageIndex === 0) {
  1006. (0, _util.warn)(`getAllPageDicts - Skipping invalid first page: "${error}".`);
  1007. error = _primitives.Dict.empty;
  1008. }
  1009. map.set(pageIndex++, [error, null]);
  1010. }
  1011. while (queue.length > 0) {
  1012. const queueItem = queue.at(-1);
  1013. const {
  1014. currentNode,
  1015. posInKids
  1016. } = queueItem;
  1017. let kids = currentNode.getRaw("Kids");
  1018. if (kids instanceof _primitives.Ref) {
  1019. try {
  1020. kids = await xref.fetchAsync(kids);
  1021. } catch (ex) {
  1022. addPageError(ex);
  1023. break;
  1024. }
  1025. }
  1026. if (!Array.isArray(kids)) {
  1027. addPageError(new _util.FormatError("Page dictionary kids object is not an array."));
  1028. break;
  1029. }
  1030. if (posInKids >= kids.length) {
  1031. queue.pop();
  1032. continue;
  1033. }
  1034. const kidObj = kids[posInKids];
  1035. let obj;
  1036. if (kidObj instanceof _primitives.Ref) {
  1037. if (visitedNodes.has(kidObj)) {
  1038. addPageError(new _util.FormatError("Pages tree contains circular reference."));
  1039. break;
  1040. }
  1041. visitedNodes.put(kidObj);
  1042. try {
  1043. obj = await xref.fetchAsync(kidObj);
  1044. } catch (ex) {
  1045. addPageError(ex);
  1046. break;
  1047. }
  1048. } else {
  1049. obj = kidObj;
  1050. }
  1051. if (!(obj instanceof _primitives.Dict)) {
  1052. addPageError(new _util.FormatError("Page dictionary kid reference points to wrong type of object."));
  1053. break;
  1054. }
  1055. let type = obj.getRaw("Type");
  1056. if (type instanceof _primitives.Ref) {
  1057. try {
  1058. type = await xref.fetchAsync(type);
  1059. } catch (ex) {
  1060. addPageError(ex);
  1061. break;
  1062. }
  1063. }
  1064. if ((0, _primitives.isName)(type, "Page") || !obj.has("Kids")) {
  1065. addPageDict(obj, kidObj instanceof _primitives.Ref ? kidObj : null);
  1066. } else {
  1067. queue.push({
  1068. currentNode: obj,
  1069. posInKids: 0
  1070. });
  1071. }
  1072. queueItem.posInKids++;
  1073. }
  1074. return map;
  1075. }
  1076. getPageIndex(pageRef) {
  1077. const cachedPageIndex = this.pageIndexCache.get(pageRef);
  1078. if (cachedPageIndex !== undefined) {
  1079. return Promise.resolve(cachedPageIndex);
  1080. }
  1081. const xref = this.xref;
  1082. function pagesBeforeRef(kidRef) {
  1083. let total = 0,
  1084. parentRef;
  1085. return xref.fetchAsync(kidRef).then(function (node) {
  1086. if ((0, _primitives.isRefsEqual)(kidRef, pageRef) && !(0, _primitives.isDict)(node, "Page") && !(node instanceof _primitives.Dict && !node.has("Type") && node.has("Contents"))) {
  1087. throw new _util.FormatError("The reference does not point to a /Page dictionary.");
  1088. }
  1089. if (!node) {
  1090. return null;
  1091. }
  1092. if (!(node instanceof _primitives.Dict)) {
  1093. throw new _util.FormatError("Node must be a dictionary.");
  1094. }
  1095. parentRef = node.getRaw("Parent");
  1096. return node.getAsync("Parent");
  1097. }).then(function (parent) {
  1098. if (!parent) {
  1099. return null;
  1100. }
  1101. if (!(parent instanceof _primitives.Dict)) {
  1102. throw new _util.FormatError("Parent must be a dictionary.");
  1103. }
  1104. return parent.getAsync("Kids");
  1105. }).then(function (kids) {
  1106. if (!kids) {
  1107. return null;
  1108. }
  1109. const kidPromises = [];
  1110. let found = false;
  1111. for (const kid of kids) {
  1112. if (!(kid instanceof _primitives.Ref)) {
  1113. throw new _util.FormatError("Kid must be a reference.");
  1114. }
  1115. if ((0, _primitives.isRefsEqual)(kid, kidRef)) {
  1116. found = true;
  1117. break;
  1118. }
  1119. kidPromises.push(xref.fetchAsync(kid).then(function (obj) {
  1120. if (!(obj instanceof _primitives.Dict)) {
  1121. throw new _util.FormatError("Kid node must be a dictionary.");
  1122. }
  1123. if (obj.has("Count")) {
  1124. total += obj.get("Count");
  1125. } else {
  1126. total++;
  1127. }
  1128. }));
  1129. }
  1130. if (!found) {
  1131. throw new _util.FormatError("Kid reference not found in parent's kids.");
  1132. }
  1133. return Promise.all(kidPromises).then(function () {
  1134. return [total, parentRef];
  1135. });
  1136. });
  1137. }
  1138. let total = 0;
  1139. const next = ref => pagesBeforeRef(ref).then(args => {
  1140. if (!args) {
  1141. this.pageIndexCache.put(pageRef, total);
  1142. return total;
  1143. }
  1144. const [count, parentRef] = args;
  1145. total += count;
  1146. return next(parentRef);
  1147. });
  1148. return next(pageRef);
  1149. }
  1150. get baseUrl() {
  1151. const uri = this._catDict.get("URI");
  1152. if (uri instanceof _primitives.Dict) {
  1153. const base = uri.get("Base");
  1154. if (typeof base === "string") {
  1155. const absoluteUrl = (0, _util.createValidAbsoluteUrl)(base, null, {
  1156. tryConvertEncoding: true
  1157. });
  1158. if (absoluteUrl) {
  1159. return (0, _util.shadow)(this, "baseUrl", absoluteUrl.href);
  1160. }
  1161. }
  1162. }
  1163. return (0, _util.shadow)(this, "baseUrl", null);
  1164. }
  1165. static parseDestDictionary(params) {
  1166. const destDict = params.destDict;
  1167. if (!(destDict instanceof _primitives.Dict)) {
  1168. (0, _util.warn)("parseDestDictionary: `destDict` must be a dictionary.");
  1169. return;
  1170. }
  1171. const resultObj = params.resultObj;
  1172. if (typeof resultObj !== "object") {
  1173. (0, _util.warn)("parseDestDictionary: `resultObj` must be an object.");
  1174. return;
  1175. }
  1176. const docBaseUrl = params.docBaseUrl || null;
  1177. const docAttachments = params.docAttachments || null;
  1178. let action = destDict.get("A"),
  1179. url,
  1180. dest;
  1181. if (!(action instanceof _primitives.Dict)) {
  1182. if (destDict.has("Dest")) {
  1183. action = destDict.get("Dest");
  1184. } else {
  1185. action = destDict.get("AA");
  1186. if (action instanceof _primitives.Dict) {
  1187. if (action.has("D")) {
  1188. action = action.get("D");
  1189. } else if (action.has("U")) {
  1190. action = action.get("U");
  1191. }
  1192. }
  1193. }
  1194. }
  1195. if (action instanceof _primitives.Dict) {
  1196. const actionType = action.get("S");
  1197. if (!(actionType instanceof _primitives.Name)) {
  1198. (0, _util.warn)("parseDestDictionary: Invalid type in Action dictionary.");
  1199. return;
  1200. }
  1201. const actionName = actionType.name;
  1202. switch (actionName) {
  1203. case "ResetForm":
  1204. const flags = action.get("Flags");
  1205. const include = ((typeof flags === "number" ? flags : 0) & 1) === 0;
  1206. const fields = [];
  1207. const refs = [];
  1208. for (const obj of action.get("Fields") || []) {
  1209. if (obj instanceof _primitives.Ref) {
  1210. refs.push(obj.toString());
  1211. } else if (typeof obj === "string") {
  1212. fields.push((0, _util.stringToPDFString)(obj));
  1213. }
  1214. }
  1215. resultObj.resetForm = {
  1216. fields,
  1217. refs,
  1218. include
  1219. };
  1220. break;
  1221. case "URI":
  1222. url = action.get("URI");
  1223. if (url instanceof _primitives.Name) {
  1224. url = "/" + url.name;
  1225. }
  1226. break;
  1227. case "GoTo":
  1228. dest = action.get("D");
  1229. break;
  1230. case "Launch":
  1231. case "GoToR":
  1232. const urlDict = action.get("F");
  1233. if (urlDict instanceof _primitives.Dict) {
  1234. url = urlDict.get("F") || null;
  1235. } else if (typeof urlDict === "string") {
  1236. url = urlDict;
  1237. }
  1238. let remoteDest = action.get("D");
  1239. if (remoteDest) {
  1240. if (remoteDest instanceof _primitives.Name) {
  1241. remoteDest = remoteDest.name;
  1242. }
  1243. if (typeof url === "string") {
  1244. const baseUrl = url.split("#")[0];
  1245. if (typeof remoteDest === "string") {
  1246. url = baseUrl + "#" + remoteDest;
  1247. } else if (Array.isArray(remoteDest)) {
  1248. url = baseUrl + "#" + JSON.stringify(remoteDest);
  1249. }
  1250. }
  1251. }
  1252. const newWindow = action.get("NewWindow");
  1253. if (typeof newWindow === "boolean") {
  1254. resultObj.newWindow = newWindow;
  1255. }
  1256. break;
  1257. case "GoToE":
  1258. const target = action.get("T");
  1259. let attachment;
  1260. if (docAttachments && target instanceof _primitives.Dict) {
  1261. const relationship = target.get("R");
  1262. const name = target.get("N");
  1263. if ((0, _primitives.isName)(relationship, "C") && typeof name === "string") {
  1264. attachment = docAttachments[(0, _util.stringToPDFString)(name)];
  1265. }
  1266. }
  1267. if (attachment) {
  1268. resultObj.attachment = attachment;
  1269. } else {
  1270. (0, _util.warn)(`parseDestDictionary - unimplemented "GoToE" action.`);
  1271. }
  1272. break;
  1273. case "Named":
  1274. const namedAction = action.get("N");
  1275. if (namedAction instanceof _primitives.Name) {
  1276. resultObj.action = namedAction.name;
  1277. }
  1278. break;
  1279. case "SetOCGState":
  1280. const state = action.get("State");
  1281. const preserveRB = action.get("PreserveRB");
  1282. if (!Array.isArray(state) || state.length === 0) {
  1283. break;
  1284. }
  1285. const stateArr = [];
  1286. for (const elem of state) {
  1287. if (elem instanceof _primitives.Name) {
  1288. switch (elem.name) {
  1289. case "ON":
  1290. case "OFF":
  1291. case "Toggle":
  1292. stateArr.push(elem.name);
  1293. break;
  1294. }
  1295. } else if (elem instanceof _primitives.Ref) {
  1296. stateArr.push(elem.toString());
  1297. }
  1298. }
  1299. if (stateArr.length !== state.length) {
  1300. break;
  1301. }
  1302. resultObj.setOCGState = {
  1303. state: stateArr,
  1304. preserveRB: typeof preserveRB === "boolean" ? preserveRB : true
  1305. };
  1306. break;
  1307. case "JavaScript":
  1308. const jsAction = action.get("JS");
  1309. let js;
  1310. if (jsAction instanceof _base_stream.BaseStream) {
  1311. js = jsAction.getString();
  1312. } else if (typeof jsAction === "string") {
  1313. js = jsAction;
  1314. }
  1315. const jsURL = js && (0, _core_utils.recoverJsURL)((0, _util.stringToPDFString)(js));
  1316. if (jsURL) {
  1317. url = jsURL.url;
  1318. resultObj.newWindow = jsURL.newWindow;
  1319. break;
  1320. }
  1321. default:
  1322. if (actionName === "JavaScript" || actionName === "SubmitForm") {
  1323. break;
  1324. }
  1325. (0, _util.warn)(`parseDestDictionary - unsupported action: "${actionName}".`);
  1326. break;
  1327. }
  1328. } else if (destDict.has("Dest")) {
  1329. dest = destDict.get("Dest");
  1330. }
  1331. if (typeof url === "string") {
  1332. const absoluteUrl = (0, _util.createValidAbsoluteUrl)(url, docBaseUrl, {
  1333. addDefaultProtocol: true,
  1334. tryConvertEncoding: true
  1335. });
  1336. if (absoluteUrl) {
  1337. resultObj.url = absoluteUrl.href;
  1338. }
  1339. resultObj.unsafeUrl = url;
  1340. }
  1341. if (dest) {
  1342. if (dest instanceof _primitives.Name) {
  1343. dest = dest.name;
  1344. }
  1345. if (typeof dest === "string") {
  1346. resultObj.dest = (0, _util.stringToPDFString)(dest);
  1347. } else if (Array.isArray(dest)) {
  1348. resultObj.dest = dest;
  1349. }
  1350. }
  1351. }
  1352. }
  1353. exports.Catalog = Catalog;