catalog.js 38 KB

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