2
0

document.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  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.Page = exports.PDFDocument = void 0;
  27. var _util = require("../shared/util.js");
  28. var _primitives = require("./primitives.js");
  29. var _core_utils = require("./core_utils.js");
  30. var _xfa_fonts = require("./xfa_fonts.js");
  31. var _stream = require("./stream.js");
  32. var _annotation = require("./annotation.js");
  33. var _base_stream = require("./base_stream.js");
  34. var _crypto = require("./crypto.js");
  35. var _catalog = require("./catalog.js");
  36. var _parser = require("./parser.js");
  37. var _object_loader = require("./object_loader.js");
  38. var _operator_list = require("./operator_list.js");
  39. var _evaluator = require("./evaluator.js");
  40. var _decode_stream = require("./decode_stream.js");
  41. var _struct_tree = require("./struct_tree.js");
  42. var _factory = require("./xfa/factory.js");
  43. var _xref = require("./xref.js");
  44. const DEFAULT_USER_UNIT = 1.0;
  45. const LETTER_SIZE_MEDIABOX = [0, 0, 612, 792];
  46. class Page {
  47. constructor({
  48. pdfManager,
  49. xref,
  50. pageIndex,
  51. pageDict,
  52. ref,
  53. globalIdFactory,
  54. fontCache,
  55. builtInCMapCache,
  56. standardFontDataCache,
  57. globalImageCache,
  58. nonBlendModesSet,
  59. xfaFactory
  60. }) {
  61. this.pdfManager = pdfManager;
  62. this.pageIndex = pageIndex;
  63. this.pageDict = pageDict;
  64. this.xref = xref;
  65. this.ref = ref;
  66. this.fontCache = fontCache;
  67. this.builtInCMapCache = builtInCMapCache;
  68. this.standardFontDataCache = standardFontDataCache;
  69. this.globalImageCache = globalImageCache;
  70. this.nonBlendModesSet = nonBlendModesSet;
  71. this.evaluatorOptions = pdfManager.evaluatorOptions;
  72. this.resourcesPromise = null;
  73. this.xfaFactory = xfaFactory;
  74. const idCounters = {
  75. obj: 0
  76. };
  77. this._localIdFactory = class extends globalIdFactory {
  78. static createObjId() {
  79. return `p${pageIndex}_${++idCounters.obj}`;
  80. }
  81. static getPageObjId() {
  82. return `page${ref.toString()}`;
  83. }
  84. };
  85. }
  86. _getInheritableProperty(key, getArray = false) {
  87. const value = (0, _core_utils.getInheritableProperty)({
  88. dict: this.pageDict,
  89. key,
  90. getArray,
  91. stopWhenFound: false
  92. });
  93. if (!Array.isArray(value)) {
  94. return value;
  95. }
  96. if (value.length === 1 || !(0, _primitives.isDict)(value[0])) {
  97. return value[0];
  98. }
  99. return _primitives.Dict.merge({
  100. xref: this.xref,
  101. dictArray: value
  102. });
  103. }
  104. get content() {
  105. return this.pageDict.getArray("Contents");
  106. }
  107. get resources() {
  108. return (0, _util.shadow)(this, "resources", this._getInheritableProperty("Resources") || _primitives.Dict.empty);
  109. }
  110. _getBoundingBox(name) {
  111. if (this.xfaData) {
  112. return this.xfaData.bbox;
  113. }
  114. const box = this._getInheritableProperty(name, true);
  115. if (Array.isArray(box) && box.length === 4) {
  116. if (box[2] - box[0] !== 0 && box[3] - box[1] !== 0) {
  117. return box;
  118. }
  119. (0, _util.warn)(`Empty /${name} entry.`);
  120. }
  121. return null;
  122. }
  123. get mediaBox() {
  124. return (0, _util.shadow)(this, "mediaBox", this._getBoundingBox("MediaBox") || LETTER_SIZE_MEDIABOX);
  125. }
  126. get cropBox() {
  127. return (0, _util.shadow)(this, "cropBox", this._getBoundingBox("CropBox") || this.mediaBox);
  128. }
  129. get userUnit() {
  130. let obj = this.pageDict.get("UserUnit");
  131. if (!(0, _util.isNum)(obj) || obj <= 0) {
  132. obj = DEFAULT_USER_UNIT;
  133. }
  134. return (0, _util.shadow)(this, "userUnit", obj);
  135. }
  136. get view() {
  137. const {
  138. cropBox,
  139. mediaBox
  140. } = this;
  141. let view;
  142. if (cropBox === mediaBox || (0, _util.isArrayEqual)(cropBox, mediaBox)) {
  143. view = mediaBox;
  144. } else {
  145. const box = _util.Util.intersect(cropBox, mediaBox);
  146. if (box && box[2] - box[0] !== 0 && box[3] - box[1] !== 0) {
  147. view = box;
  148. } else {
  149. (0, _util.warn)("Empty /CropBox and /MediaBox intersection.");
  150. }
  151. }
  152. return (0, _util.shadow)(this, "view", view || mediaBox);
  153. }
  154. get rotate() {
  155. let rotate = this._getInheritableProperty("Rotate") || 0;
  156. if (rotate % 90 !== 0) {
  157. rotate = 0;
  158. } else if (rotate >= 360) {
  159. rotate %= 360;
  160. } else if (rotate < 0) {
  161. rotate = (rotate % 360 + 360) % 360;
  162. }
  163. return (0, _util.shadow)(this, "rotate", rotate);
  164. }
  165. _onSubStreamError(handler, reason, objId) {
  166. if (this.evaluatorOptions.ignoreErrors) {
  167. handler.send("UnsupportedFeature", {
  168. featureId: _util.UNSUPPORTED_FEATURES.errorContentSubStream
  169. });
  170. (0, _util.warn)(`getContentStream - ignoring sub-stream (${objId}): "${reason}".`);
  171. return;
  172. }
  173. throw reason;
  174. }
  175. getContentStream(handler) {
  176. return this.pdfManager.ensure(this, "content").then(content => {
  177. if (content instanceof _base_stream.BaseStream) {
  178. return content;
  179. }
  180. if (Array.isArray(content)) {
  181. return new _decode_stream.StreamsSequenceStream(content, this._onSubStreamError.bind(this, handler));
  182. }
  183. return new _stream.NullStream();
  184. });
  185. }
  186. get xfaData() {
  187. return (0, _util.shadow)(this, "xfaData", this.xfaFactory ? {
  188. bbox: this.xfaFactory.getBoundingBox(this.pageIndex)
  189. } : null);
  190. }
  191. save(handler, task, annotationStorage) {
  192. const partialEvaluator = new _evaluator.PartialEvaluator({
  193. xref: this.xref,
  194. handler,
  195. pageIndex: this.pageIndex,
  196. idFactory: this._localIdFactory,
  197. fontCache: this.fontCache,
  198. builtInCMapCache: this.builtInCMapCache,
  199. standardFontDataCache: this.standardFontDataCache,
  200. globalImageCache: this.globalImageCache,
  201. options: this.evaluatorOptions
  202. });
  203. return this._parsedAnnotations.then(function (annotations) {
  204. const newRefsPromises = [];
  205. for (const annotation of annotations) {
  206. if (!annotation.mustBePrinted(annotationStorage)) {
  207. continue;
  208. }
  209. newRefsPromises.push(annotation.save(partialEvaluator, task, annotationStorage).catch(function (reason) {
  210. (0, _util.warn)("save - ignoring annotation data during " + `"${task.name}" task: "${reason}".`);
  211. return null;
  212. }));
  213. }
  214. return Promise.all(newRefsPromises);
  215. });
  216. }
  217. loadResources(keys) {
  218. if (!this.resourcesPromise) {
  219. this.resourcesPromise = this.pdfManager.ensure(this, "resources");
  220. }
  221. return this.resourcesPromise.then(() => {
  222. const objectLoader = new _object_loader.ObjectLoader(this.resources, keys, this.xref);
  223. return objectLoader.load();
  224. });
  225. }
  226. getOperatorList({
  227. handler,
  228. sink,
  229. task,
  230. intent,
  231. cacheKey,
  232. annotationStorage = null
  233. }) {
  234. const contentStreamPromise = this.getContentStream(handler);
  235. const resourcesPromise = this.loadResources(["ColorSpace", "ExtGState", "Font", "Pattern", "Properties", "Shading", "XObject"]);
  236. const partialEvaluator = new _evaluator.PartialEvaluator({
  237. xref: this.xref,
  238. handler,
  239. pageIndex: this.pageIndex,
  240. idFactory: this._localIdFactory,
  241. fontCache: this.fontCache,
  242. builtInCMapCache: this.builtInCMapCache,
  243. standardFontDataCache: this.standardFontDataCache,
  244. globalImageCache: this.globalImageCache,
  245. options: this.evaluatorOptions
  246. });
  247. const dataPromises = Promise.all([contentStreamPromise, resourcesPromise]);
  248. const pageListPromise = dataPromises.then(([contentStream]) => {
  249. const opList = new _operator_list.OperatorList(intent, sink);
  250. handler.send("StartRenderPage", {
  251. transparency: partialEvaluator.hasBlendModes(this.resources, this.nonBlendModesSet),
  252. pageIndex: this.pageIndex,
  253. cacheKey
  254. });
  255. return partialEvaluator.getOperatorList({
  256. stream: contentStream,
  257. task,
  258. resources: this.resources,
  259. operatorList: opList
  260. }).then(function () {
  261. return opList;
  262. });
  263. });
  264. return Promise.all([pageListPromise, this._parsedAnnotations]).then(function ([pageOpList, annotations]) {
  265. if (annotations.length === 0 || intent & _util.RenderingIntentFlag.ANNOTATIONS_DISABLE) {
  266. pageOpList.flush(true);
  267. return {
  268. length: pageOpList.totalLength
  269. };
  270. }
  271. const renderForms = !!(intent & _util.RenderingIntentFlag.ANNOTATIONS_FORMS),
  272. intentAny = !!(intent & _util.RenderingIntentFlag.ANY),
  273. intentDisplay = !!(intent & _util.RenderingIntentFlag.DISPLAY),
  274. intentPrint = !!(intent & _util.RenderingIntentFlag.PRINT);
  275. const opListPromises = [];
  276. for (const annotation of annotations) {
  277. if (intentAny || intentDisplay && annotation.mustBeViewed(annotationStorage) || intentPrint && annotation.mustBePrinted(annotationStorage)) {
  278. opListPromises.push(annotation.getOperatorList(partialEvaluator, task, intent, renderForms, annotationStorage).catch(function (reason) {
  279. (0, _util.warn)("getOperatorList - ignoring annotation data during " + `"${task.name}" task: "${reason}".`);
  280. return null;
  281. }));
  282. }
  283. }
  284. return Promise.all(opListPromises).then(function (opLists) {
  285. pageOpList.addOp(_util.OPS.beginAnnotations, []);
  286. for (const opList of opLists) {
  287. pageOpList.addOpList(opList);
  288. }
  289. pageOpList.addOp(_util.OPS.endAnnotations, []);
  290. pageOpList.flush(true);
  291. return {
  292. length: pageOpList.totalLength
  293. };
  294. });
  295. });
  296. }
  297. extractTextContent({
  298. handler,
  299. task,
  300. normalizeWhitespace,
  301. includeMarkedContent,
  302. sink,
  303. combineTextItems
  304. }) {
  305. const contentStreamPromise = this.getContentStream(handler);
  306. const resourcesPromise = this.loadResources(["ExtGState", "Font", "Properties", "XObject"]);
  307. const dataPromises = Promise.all([contentStreamPromise, resourcesPromise]);
  308. return dataPromises.then(([contentStream]) => {
  309. const partialEvaluator = new _evaluator.PartialEvaluator({
  310. xref: this.xref,
  311. handler,
  312. pageIndex: this.pageIndex,
  313. idFactory: this._localIdFactory,
  314. fontCache: this.fontCache,
  315. builtInCMapCache: this.builtInCMapCache,
  316. standardFontDataCache: this.standardFontDataCache,
  317. globalImageCache: this.globalImageCache,
  318. options: this.evaluatorOptions
  319. });
  320. return partialEvaluator.getTextContent({
  321. stream: contentStream,
  322. task,
  323. resources: this.resources,
  324. normalizeWhitespace,
  325. includeMarkedContent,
  326. combineTextItems,
  327. sink
  328. });
  329. });
  330. }
  331. async getStructTree() {
  332. const structTreeRoot = await this.pdfManager.ensureCatalog("structTreeRoot");
  333. if (!structTreeRoot) {
  334. return null;
  335. }
  336. const structTree = await this.pdfManager.ensure(this, "_parseStructTree", [structTreeRoot]);
  337. return structTree.serializable;
  338. }
  339. _parseStructTree(structTreeRoot) {
  340. const tree = new _struct_tree.StructTreePage(structTreeRoot, this.pageDict);
  341. tree.parse();
  342. return tree;
  343. }
  344. getAnnotationsData(intent) {
  345. return this._parsedAnnotations.then(function (annotations) {
  346. const annotationsData = [];
  347. if (annotations.length === 0) {
  348. return annotationsData;
  349. }
  350. const intentAny = !!(intent & _util.RenderingIntentFlag.ANY),
  351. intentDisplay = !!(intent & _util.RenderingIntentFlag.DISPLAY),
  352. intentPrint = !!(intent & _util.RenderingIntentFlag.PRINT);
  353. for (const annotation of annotations) {
  354. if (intentAny || intentDisplay && annotation.viewable || intentPrint && annotation.printable) {
  355. annotationsData.push(annotation.data);
  356. }
  357. }
  358. return annotationsData;
  359. });
  360. }
  361. get annotations() {
  362. const annots = this._getInheritableProperty("Annots");
  363. return (0, _util.shadow)(this, "annotations", Array.isArray(annots) ? annots : []);
  364. }
  365. get _parsedAnnotations() {
  366. const parsedAnnotations = this.pdfManager.ensure(this, "annotations").then(() => {
  367. const annotationPromises = [];
  368. for (const annotationRef of this.annotations) {
  369. annotationPromises.push(_annotation.AnnotationFactory.create(this.xref, annotationRef, this.pdfManager, this._localIdFactory, false).catch(function (reason) {
  370. (0, _util.warn)(`_parsedAnnotations: "${reason}".`);
  371. return null;
  372. }));
  373. }
  374. return Promise.all(annotationPromises).then(function (annotations) {
  375. return annotations.filter(annotation => !!annotation);
  376. });
  377. });
  378. return (0, _util.shadow)(this, "_parsedAnnotations", parsedAnnotations);
  379. }
  380. get jsActions() {
  381. const actions = (0, _core_utils.collectActions)(this.xref, this.pageDict, _util.PageActionEventType);
  382. return (0, _util.shadow)(this, "jsActions", actions);
  383. }
  384. }
  385. exports.Page = Page;
  386. const PDF_HEADER_SIGNATURE = new Uint8Array([0x25, 0x50, 0x44, 0x46, 0x2d]);
  387. const STARTXREF_SIGNATURE = new Uint8Array([0x73, 0x74, 0x61, 0x72, 0x74, 0x78, 0x72, 0x65, 0x66]);
  388. const ENDOBJ_SIGNATURE = new Uint8Array([0x65, 0x6e, 0x64, 0x6f, 0x62, 0x6a]);
  389. const FINGERPRINT_FIRST_BYTES = 1024;
  390. const EMPTY_FINGERPRINT = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
  391. const PDF_HEADER_VERSION_REGEXP = /^[1-9]\.\d$/;
  392. function find(stream, signature, limit = 1024, backwards = false) {
  393. const signatureLength = signature.length;
  394. const scanBytes = stream.peekBytes(limit);
  395. const scanLength = scanBytes.length - signatureLength;
  396. if (scanLength <= 0) {
  397. return false;
  398. }
  399. if (backwards) {
  400. const signatureEnd = signatureLength - 1;
  401. let pos = scanBytes.length - 1;
  402. while (pos >= signatureEnd) {
  403. let j = 0;
  404. while (j < signatureLength && scanBytes[pos - j] === signature[signatureEnd - j]) {
  405. j++;
  406. }
  407. if (j >= signatureLength) {
  408. stream.pos += pos - signatureEnd;
  409. return true;
  410. }
  411. pos--;
  412. }
  413. } else {
  414. let pos = 0;
  415. while (pos <= scanLength) {
  416. let j = 0;
  417. while (j < signatureLength && scanBytes[pos + j] === signature[j]) {
  418. j++;
  419. }
  420. if (j >= signatureLength) {
  421. stream.pos += pos;
  422. return true;
  423. }
  424. pos++;
  425. }
  426. }
  427. return false;
  428. }
  429. class PDFDocument {
  430. constructor(pdfManager, arg) {
  431. let stream;
  432. if ((0, _primitives.isStream)(arg)) {
  433. stream = arg;
  434. } else if ((0, _util.isArrayBuffer)(arg)) {
  435. stream = new _stream.Stream(arg);
  436. } else {
  437. throw new Error("PDFDocument: Unknown argument type");
  438. }
  439. if (stream.length <= 0) {
  440. throw new _util.InvalidPDFException("The PDF file is empty, i.e. its size is zero bytes.");
  441. }
  442. this.pdfManager = pdfManager;
  443. this.stream = stream;
  444. this.xref = new _xref.XRef(stream, pdfManager);
  445. this._pagePromises = new Map();
  446. this._version = null;
  447. const idCounters = {
  448. font: 0
  449. };
  450. this._globalIdFactory = class {
  451. static getDocId() {
  452. return `g_${pdfManager.docId}`;
  453. }
  454. static createFontId() {
  455. return `f${++idCounters.font}`;
  456. }
  457. static createObjId() {
  458. (0, _util.unreachable)("Abstract method `createObjId` called.");
  459. }
  460. static getPageObjId() {
  461. (0, _util.unreachable)("Abstract method `getPageObjId` called.");
  462. }
  463. };
  464. }
  465. parse(recoveryMode) {
  466. this.xref.parse(recoveryMode);
  467. this.catalog = new _catalog.Catalog(this.pdfManager, this.xref);
  468. if (this.catalog.version) {
  469. this._version = this.catalog.version;
  470. }
  471. }
  472. get linearization() {
  473. let linearization = null;
  474. try {
  475. linearization = _parser.Linearization.create(this.stream);
  476. } catch (err) {
  477. if (err instanceof _core_utils.MissingDataException) {
  478. throw err;
  479. }
  480. (0, _util.info)(err);
  481. }
  482. return (0, _util.shadow)(this, "linearization", linearization);
  483. }
  484. get startXRef() {
  485. const stream = this.stream;
  486. let startXRef = 0;
  487. if (this.linearization) {
  488. stream.reset();
  489. if (find(stream, ENDOBJ_SIGNATURE)) {
  490. startXRef = stream.pos + 6 - stream.start;
  491. }
  492. } else {
  493. const step = 1024;
  494. const startXRefLength = STARTXREF_SIGNATURE.length;
  495. let found = false,
  496. pos = stream.end;
  497. while (!found && pos > 0) {
  498. pos -= step - startXRefLength;
  499. if (pos < 0) {
  500. pos = 0;
  501. }
  502. stream.pos = pos;
  503. found = find(stream, STARTXREF_SIGNATURE, step, true);
  504. }
  505. if (found) {
  506. stream.skip(9);
  507. let ch;
  508. do {
  509. ch = stream.getByte();
  510. } while ((0, _core_utils.isWhiteSpace)(ch));
  511. let str = "";
  512. while (ch >= 0x20 && ch <= 0x39) {
  513. str += String.fromCharCode(ch);
  514. ch = stream.getByte();
  515. }
  516. startXRef = parseInt(str, 10);
  517. if (isNaN(startXRef)) {
  518. startXRef = 0;
  519. }
  520. }
  521. }
  522. return (0, _util.shadow)(this, "startXRef", startXRef);
  523. }
  524. checkHeader() {
  525. const stream = this.stream;
  526. stream.reset();
  527. if (!find(stream, PDF_HEADER_SIGNATURE)) {
  528. return;
  529. }
  530. stream.moveStart();
  531. const MAX_PDF_VERSION_LENGTH = 12;
  532. let version = "",
  533. ch;
  534. while ((ch = stream.getByte()) > 0x20) {
  535. if (version.length >= MAX_PDF_VERSION_LENGTH) {
  536. break;
  537. }
  538. version += String.fromCharCode(ch);
  539. }
  540. if (!this._version) {
  541. this._version = version.substring(5);
  542. }
  543. }
  544. parseStartXRef() {
  545. this.xref.setStartXRef(this.startXRef);
  546. }
  547. get numPages() {
  548. let num = 0;
  549. if (this.catalog.hasActualNumPages) {
  550. num = this.catalog.numPages;
  551. } else if (this.xfaFactory) {
  552. num = this.xfaFactory.getNumPages();
  553. } else if (this.linearization) {
  554. num = this.linearization.numPages;
  555. } else {
  556. num = this.catalog.numPages;
  557. }
  558. return (0, _util.shadow)(this, "numPages", num);
  559. }
  560. _hasOnlyDocumentSignatures(fields, recursionDepth = 0) {
  561. const RECURSION_LIMIT = 10;
  562. if (!Array.isArray(fields)) {
  563. return false;
  564. }
  565. return fields.every(field => {
  566. field = this.xref.fetchIfRef(field);
  567. if (!(field instanceof _primitives.Dict)) {
  568. return false;
  569. }
  570. if (field.has("Kids")) {
  571. if (++recursionDepth > RECURSION_LIMIT) {
  572. (0, _util.warn)("_hasOnlyDocumentSignatures: maximum recursion depth reached");
  573. return false;
  574. }
  575. return this._hasOnlyDocumentSignatures(field.get("Kids"), recursionDepth);
  576. }
  577. const isSignature = (0, _primitives.isName)(field.get("FT"), "Sig");
  578. const rectangle = field.get("Rect");
  579. const isInvisible = Array.isArray(rectangle) && rectangle.every(value => value === 0);
  580. return isSignature && isInvisible;
  581. });
  582. }
  583. get xfaData() {
  584. const acroForm = this.catalog.acroForm;
  585. if (!acroForm) {
  586. return null;
  587. }
  588. const xfa = acroForm.get("XFA");
  589. const entries = {
  590. "xdp:xdp": "",
  591. template: "",
  592. datasets: "",
  593. config: "",
  594. connectionSet: "",
  595. localeSet: "",
  596. stylesheet: "",
  597. "/xdp:xdp": ""
  598. };
  599. if ((0, _primitives.isStream)(xfa) && !xfa.isEmpty) {
  600. try {
  601. entries["xdp:xdp"] = (0, _util.stringToUTF8String)(xfa.getString());
  602. return entries;
  603. } catch (_) {
  604. (0, _util.warn)("XFA - Invalid utf-8 string.");
  605. return null;
  606. }
  607. }
  608. if (!Array.isArray(xfa) || xfa.length === 0) {
  609. return null;
  610. }
  611. for (let i = 0, ii = xfa.length; i < ii; i += 2) {
  612. let name;
  613. if (i === 0) {
  614. name = "xdp:xdp";
  615. } else if (i === ii - 2) {
  616. name = "/xdp:xdp";
  617. } else {
  618. name = xfa[i];
  619. }
  620. if (!entries.hasOwnProperty(name)) {
  621. continue;
  622. }
  623. const data = this.xref.fetchIfRef(xfa[i + 1]);
  624. if (!(0, _primitives.isStream)(data) || data.isEmpty) {
  625. continue;
  626. }
  627. try {
  628. entries[name] = (0, _util.stringToUTF8String)(data.getString());
  629. } catch (_) {
  630. (0, _util.warn)("XFA - Invalid utf-8 string.");
  631. return null;
  632. }
  633. }
  634. return entries;
  635. }
  636. get xfaFactory() {
  637. let data;
  638. if (this.pdfManager.enableXfa && this.catalog.needsRendering && this.formInfo.hasXfa && !this.formInfo.hasAcroForm) {
  639. data = this.xfaData;
  640. }
  641. return (0, _util.shadow)(this, "xfaFactory", data ? new _factory.XFAFactory(data) : null);
  642. }
  643. get isPureXfa() {
  644. return this.xfaFactory ? this.xfaFactory.isValid() : false;
  645. }
  646. get htmlForXfa() {
  647. return this.xfaFactory ? this.xfaFactory.getPages() : null;
  648. }
  649. async loadXfaImages() {
  650. const xfaImagesDict = await this.pdfManager.ensureCatalog("xfaImages");
  651. if (!xfaImagesDict) {
  652. return;
  653. }
  654. const keys = xfaImagesDict.getKeys();
  655. const objectLoader = new _object_loader.ObjectLoader(xfaImagesDict, keys, this.xref);
  656. await objectLoader.load();
  657. const xfaImages = new Map();
  658. for (const key of keys) {
  659. const stream = xfaImagesDict.get(key);
  660. if (!(0, _primitives.isStream)(stream)) {
  661. continue;
  662. }
  663. xfaImages.set(key, stream.getBytes());
  664. }
  665. this.xfaFactory.setImages(xfaImages);
  666. }
  667. async loadXfaFonts(handler, task) {
  668. const acroForm = await this.pdfManager.ensureCatalog("acroForm");
  669. if (!acroForm) {
  670. return;
  671. }
  672. const resources = await acroForm.getAsync("DR");
  673. if (!(resources instanceof _primitives.Dict)) {
  674. return;
  675. }
  676. const objectLoader = new _object_loader.ObjectLoader(resources, ["Font"], this.xref);
  677. await objectLoader.load();
  678. const fontRes = resources.get("Font");
  679. if (!(fontRes instanceof _primitives.Dict)) {
  680. return;
  681. }
  682. const options = Object.assign(Object.create(null), this.pdfManager.evaluatorOptions);
  683. options.useSystemFonts = false;
  684. const partialEvaluator = new _evaluator.PartialEvaluator({
  685. xref: this.xref,
  686. handler,
  687. pageIndex: -1,
  688. idFactory: this._globalIdFactory,
  689. fontCache: this.catalog.fontCache,
  690. builtInCMapCache: this.catalog.builtInCMapCache,
  691. standardFontDataCache: this.catalog.standardFontDataCache,
  692. options
  693. });
  694. const operatorList = new _operator_list.OperatorList();
  695. const pdfFonts = [];
  696. const initialState = {
  697. get font() {
  698. return pdfFonts[pdfFonts.length - 1];
  699. },
  700. set font(font) {
  701. pdfFonts.push(font);
  702. },
  703. clone() {
  704. return this;
  705. }
  706. };
  707. const fonts = new Map();
  708. fontRes.forEach((fontName, font) => {
  709. fonts.set(fontName, font);
  710. });
  711. const promises = [];
  712. for (const [fontName, font] of fonts) {
  713. const descriptor = font.get("FontDescriptor");
  714. if (!(descriptor instanceof _primitives.Dict)) {
  715. continue;
  716. }
  717. let fontFamily = descriptor.get("FontFamily");
  718. fontFamily = fontFamily.replace(/[ ]+(\d)/g, "$1");
  719. const fontWeight = descriptor.get("FontWeight");
  720. const italicAngle = -descriptor.get("ItalicAngle");
  721. const cssFontInfo = {
  722. fontFamily,
  723. fontWeight,
  724. italicAngle
  725. };
  726. if (!(0, _core_utils.validateCSSFont)(cssFontInfo)) {
  727. continue;
  728. }
  729. promises.push(partialEvaluator.handleSetFont(resources, [_primitives.Name.get(fontName), 1], null, operatorList, task, initialState, null, cssFontInfo).catch(function (reason) {
  730. (0, _util.warn)(`loadXfaFonts: "${reason}".`);
  731. return null;
  732. }));
  733. }
  734. await Promise.all(promises);
  735. const missingFonts = this.xfaFactory.setFonts(pdfFonts);
  736. if (!missingFonts) {
  737. return;
  738. }
  739. options.ignoreErrors = true;
  740. promises.length = 0;
  741. pdfFonts.length = 0;
  742. const reallyMissingFonts = new Set();
  743. for (const missing of missingFonts) {
  744. if (!(0, _xfa_fonts.getXfaFontName)(`${missing}-Regular`)) {
  745. reallyMissingFonts.add(missing);
  746. }
  747. }
  748. if (reallyMissingFonts.size) {
  749. missingFonts.push("PdfJS-Fallback");
  750. }
  751. for (const missing of missingFonts) {
  752. if (reallyMissingFonts.has(missing)) {
  753. continue;
  754. }
  755. for (const fontInfo of [{
  756. name: "Regular",
  757. fontWeight: 400,
  758. italicAngle: 0
  759. }, {
  760. name: "Bold",
  761. fontWeight: 700,
  762. italicAngle: 0
  763. }, {
  764. name: "Italic",
  765. fontWeight: 400,
  766. italicAngle: 12
  767. }, {
  768. name: "BoldItalic",
  769. fontWeight: 700,
  770. italicAngle: 12
  771. }]) {
  772. const name = `${missing}-${fontInfo.name}`;
  773. const dict = (0, _xfa_fonts.getXfaFontDict)(name);
  774. promises.push(partialEvaluator.handleSetFont(resources, [_primitives.Name.get(name), 1], null, operatorList, task, initialState, dict, {
  775. fontFamily: missing,
  776. fontWeight: fontInfo.fontWeight,
  777. italicAngle: fontInfo.italicAngle
  778. }).catch(function (reason) {
  779. (0, _util.warn)(`loadXfaFonts: "${reason}".`);
  780. return null;
  781. }));
  782. }
  783. }
  784. await Promise.all(promises);
  785. this.xfaFactory.appendFonts(pdfFonts, reallyMissingFonts);
  786. }
  787. async serializeXfaData(annotationStorage) {
  788. return this.xfaFactory ? this.xfaFactory.serializeData(annotationStorage) : null;
  789. }
  790. get formInfo() {
  791. const formInfo = {
  792. hasFields: false,
  793. hasAcroForm: false,
  794. hasXfa: false,
  795. hasSignatures: false
  796. };
  797. const acroForm = this.catalog.acroForm;
  798. if (!acroForm) {
  799. return (0, _util.shadow)(this, "formInfo", formInfo);
  800. }
  801. try {
  802. const fields = acroForm.get("Fields");
  803. const hasFields = Array.isArray(fields) && fields.length > 0;
  804. formInfo.hasFields = hasFields;
  805. const xfa = acroForm.get("XFA");
  806. formInfo.hasXfa = Array.isArray(xfa) && xfa.length > 0 || (0, _primitives.isStream)(xfa) && !xfa.isEmpty;
  807. const sigFlags = acroForm.get("SigFlags");
  808. const hasSignatures = !!(sigFlags & 0x1);
  809. const hasOnlyDocumentSignatures = hasSignatures && this._hasOnlyDocumentSignatures(fields);
  810. formInfo.hasAcroForm = hasFields && !hasOnlyDocumentSignatures;
  811. formInfo.hasSignatures = hasSignatures;
  812. } catch (ex) {
  813. if (ex instanceof _core_utils.MissingDataException) {
  814. throw ex;
  815. }
  816. (0, _util.warn)(`Cannot fetch form information: "${ex}".`);
  817. }
  818. return (0, _util.shadow)(this, "formInfo", formInfo);
  819. }
  820. get documentInfo() {
  821. const DocumentInfoValidators = {
  822. Title: _util.isString,
  823. Author: _util.isString,
  824. Subject: _util.isString,
  825. Keywords: _util.isString,
  826. Creator: _util.isString,
  827. Producer: _util.isString,
  828. CreationDate: _util.isString,
  829. ModDate: _util.isString,
  830. Trapped: _primitives.isName
  831. };
  832. let version = this._version;
  833. if (typeof version !== "string" || !PDF_HEADER_VERSION_REGEXP.test(version)) {
  834. (0, _util.warn)(`Invalid PDF header version number: ${version}`);
  835. version = null;
  836. }
  837. const docInfo = {
  838. PDFFormatVersion: version,
  839. Language: this.catalog.lang,
  840. EncryptFilterName: this.xref.encrypt ? this.xref.encrypt.filterName : null,
  841. IsLinearized: !!this.linearization,
  842. IsAcroFormPresent: this.formInfo.hasAcroForm,
  843. IsXFAPresent: this.formInfo.hasXfa,
  844. IsCollectionPresent: !!this.catalog.collection,
  845. IsSignaturesPresent: this.formInfo.hasSignatures
  846. };
  847. let infoDict;
  848. try {
  849. infoDict = this.xref.trailer.get("Info");
  850. } catch (err) {
  851. if (err instanceof _core_utils.MissingDataException) {
  852. throw err;
  853. }
  854. (0, _util.info)("The document information dictionary is invalid.");
  855. }
  856. if ((0, _primitives.isDict)(infoDict)) {
  857. for (const key of infoDict.getKeys()) {
  858. const value = infoDict.get(key);
  859. if (DocumentInfoValidators[key]) {
  860. if (DocumentInfoValidators[key](value)) {
  861. docInfo[key] = typeof value !== "string" ? value : (0, _util.stringToPDFString)(value);
  862. } else {
  863. (0, _util.info)(`Bad value in document info for "${key}".`);
  864. }
  865. } else if (typeof key === "string") {
  866. let customValue;
  867. if ((0, _util.isString)(value)) {
  868. customValue = (0, _util.stringToPDFString)(value);
  869. } else if ((0, _primitives.isName)(value) || (0, _util.isNum)(value) || (0, _util.isBool)(value)) {
  870. customValue = value;
  871. } else {
  872. (0, _util.info)(`Unsupported value in document info for (custom) "${key}".`);
  873. continue;
  874. }
  875. if (!docInfo.Custom) {
  876. docInfo.Custom = Object.create(null);
  877. }
  878. docInfo.Custom[key] = customValue;
  879. }
  880. }
  881. }
  882. return (0, _util.shadow)(this, "documentInfo", docInfo);
  883. }
  884. get fingerprints() {
  885. function validate(data) {
  886. return typeof data === "string" && data.length > 0 && data !== EMPTY_FINGERPRINT;
  887. }
  888. function hexString(hash) {
  889. const buf = [];
  890. for (let i = 0, ii = hash.length; i < ii; i++) {
  891. const hex = hash[i].toString(16);
  892. buf.push(hex.padStart(2, "0"));
  893. }
  894. return buf.join("");
  895. }
  896. const idArray = this.xref.trailer.get("ID");
  897. let hashOriginal, hashModified;
  898. if (Array.isArray(idArray) && validate(idArray[0])) {
  899. hashOriginal = (0, _util.stringToBytes)(idArray[0]);
  900. if (idArray[1] !== idArray[0] && validate(idArray[1])) {
  901. hashModified = (0, _util.stringToBytes)(idArray[1]);
  902. }
  903. } else {
  904. hashOriginal = (0, _crypto.calculateMD5)(this.stream.getByteRange(0, FINGERPRINT_FIRST_BYTES), 0, FINGERPRINT_FIRST_BYTES);
  905. }
  906. return (0, _util.shadow)(this, "fingerprints", [hexString(hashOriginal), hashModified ? hexString(hashModified) : null]);
  907. }
  908. async _getLinearizationPage(pageIndex) {
  909. const {
  910. catalog,
  911. linearization
  912. } = this;
  913. const ref = _primitives.Ref.get(linearization.objectNumberFirst, 0);
  914. try {
  915. const obj = await this.xref.fetchAsync(ref);
  916. if ((0, _primitives.isDict)(obj, "Page") || (0, _primitives.isDict)(obj) && !obj.has("Type") && obj.has("Contents")) {
  917. if (ref && !catalog.pageKidsCountCache.has(ref)) {
  918. catalog.pageKidsCountCache.put(ref, 1);
  919. }
  920. return [obj, ref];
  921. }
  922. throw new _util.FormatError("The Linearization dictionary doesn't point to a valid Page dictionary.");
  923. } catch (reason) {
  924. (0, _util.info)(reason);
  925. return catalog.getPageDict(pageIndex);
  926. }
  927. }
  928. getPage(pageIndex) {
  929. const cachedPromise = this._pagePromises.get(pageIndex);
  930. if (cachedPromise) {
  931. return cachedPromise;
  932. }
  933. const {
  934. catalog,
  935. linearization,
  936. xfaFactory
  937. } = this;
  938. let promise;
  939. if (xfaFactory) {
  940. promise = Promise.resolve([_primitives.Dict.empty, null]);
  941. } else if (linearization && linearization.pageFirst === pageIndex) {
  942. promise = this._getLinearizationPage(pageIndex);
  943. } else {
  944. promise = catalog.getPageDict(pageIndex);
  945. }
  946. promise = promise.then(([pageDict, ref]) => {
  947. return new Page({
  948. pdfManager: this.pdfManager,
  949. xref: this.xref,
  950. pageIndex,
  951. pageDict,
  952. ref,
  953. globalIdFactory: this._globalIdFactory,
  954. fontCache: catalog.fontCache,
  955. builtInCMapCache: catalog.builtInCMapCache,
  956. standardFontDataCache: catalog.standardFontDataCache,
  957. globalImageCache: catalog.globalImageCache,
  958. nonBlendModesSet: catalog.nonBlendModesSet,
  959. xfaFactory
  960. });
  961. });
  962. this._pagePromises.set(pageIndex, promise);
  963. return promise;
  964. }
  965. async checkFirstPage(recoveryMode = false) {
  966. if (recoveryMode) {
  967. return;
  968. }
  969. try {
  970. await this.getPage(0);
  971. } catch (reason) {
  972. if (reason instanceof _core_utils.XRefEntryException) {
  973. this._pagePromises.delete(0);
  974. await this.cleanup();
  975. throw new _core_utils.XRefParseException();
  976. }
  977. }
  978. }
  979. async checkLastPage(recoveryMode = false) {
  980. const {
  981. catalog,
  982. pdfManager
  983. } = this;
  984. catalog.setActualNumPages();
  985. let numPages;
  986. try {
  987. await Promise.all([pdfManager.ensureDoc("xfaFactory"), pdfManager.ensureDoc("linearization"), pdfManager.ensureCatalog("numPages")]);
  988. if (this.xfaFactory) {
  989. return;
  990. } else if (this.linearization) {
  991. numPages = this.linearization.numPages;
  992. } else {
  993. numPages = catalog.numPages;
  994. }
  995. if (!Number.isInteger(numPages)) {
  996. throw new _util.FormatError("Page count is not an integer.");
  997. } else if (numPages <= 1) {
  998. return;
  999. }
  1000. await this.getPage(numPages - 1);
  1001. } catch (reason) {
  1002. this._pagePromises.delete(numPages - 1);
  1003. await this.cleanup();
  1004. if (reason instanceof _core_utils.XRefEntryException && !recoveryMode) {
  1005. throw new _core_utils.XRefParseException();
  1006. }
  1007. (0, _util.warn)(`checkLastPage - invalid /Pages tree /Count: ${numPages}.`);
  1008. let pagesTree;
  1009. try {
  1010. pagesTree = await pdfManager.ensureCatalog("getAllPageDicts", [recoveryMode]);
  1011. } catch (reasonAll) {
  1012. if (reasonAll instanceof _core_utils.XRefEntryException && !recoveryMode) {
  1013. throw new _core_utils.XRefParseException();
  1014. }
  1015. catalog.setActualNumPages(1);
  1016. return;
  1017. }
  1018. for (const [pageIndex, [pageDict, ref]] of pagesTree) {
  1019. let promise;
  1020. if (pageDict instanceof Error) {
  1021. promise = Promise.reject(pageDict);
  1022. promise.catch(() => {});
  1023. } else {
  1024. promise = Promise.resolve(new Page({
  1025. pdfManager,
  1026. xref: this.xref,
  1027. pageIndex,
  1028. pageDict,
  1029. ref,
  1030. globalIdFactory: this._globalIdFactory,
  1031. fontCache: catalog.fontCache,
  1032. builtInCMapCache: catalog.builtInCMapCache,
  1033. standardFontDataCache: catalog.standardFontDataCache,
  1034. globalImageCache: catalog.globalImageCache,
  1035. nonBlendModesSet: catalog.nonBlendModesSet,
  1036. xfaFactory: null
  1037. }));
  1038. }
  1039. this._pagePromises.set(pageIndex, promise);
  1040. }
  1041. catalog.setActualNumPages(pagesTree.size);
  1042. }
  1043. }
  1044. fontFallback(id, handler) {
  1045. return this.catalog.fontFallback(id, handler);
  1046. }
  1047. async cleanup(manuallyTriggered = false) {
  1048. return this.catalog ? this.catalog.cleanup(manuallyTriggered) : (0, _primitives.clearPrimitiveCaches)();
  1049. }
  1050. _collectFieldObjects(name, fieldRef, promises) {
  1051. const field = this.xref.fetchIfRef(fieldRef);
  1052. if (field.has("T")) {
  1053. const partName = (0, _util.stringToPDFString)(field.get("T"));
  1054. if (name === "") {
  1055. name = partName;
  1056. } else {
  1057. name = `${name}.${partName}`;
  1058. }
  1059. }
  1060. if (!promises.has(name)) {
  1061. promises.set(name, []);
  1062. }
  1063. promises.get(name).push(_annotation.AnnotationFactory.create(this.xref, fieldRef, this.pdfManager, this._localIdFactory, true).then(annotation => annotation && annotation.getFieldObject()).catch(function (reason) {
  1064. (0, _util.warn)(`_collectFieldObjects: "${reason}".`);
  1065. return null;
  1066. }));
  1067. if (field.has("Kids")) {
  1068. const kids = field.get("Kids");
  1069. for (const kid of kids) {
  1070. this._collectFieldObjects(name, kid, promises);
  1071. }
  1072. }
  1073. }
  1074. get fieldObjects() {
  1075. if (!this.formInfo.hasFields) {
  1076. return (0, _util.shadow)(this, "fieldObjects", Promise.resolve(null));
  1077. }
  1078. const allFields = Object.create(null);
  1079. const fieldPromises = new Map();
  1080. for (const fieldRef of this.catalog.acroForm.get("Fields")) {
  1081. this._collectFieldObjects("", fieldRef, fieldPromises);
  1082. }
  1083. const allPromises = [];
  1084. for (const [name, promises] of fieldPromises) {
  1085. allPromises.push(Promise.all(promises).then(fields => {
  1086. fields = fields.filter(field => !!field);
  1087. if (fields.length > 0) {
  1088. allFields[name] = fields;
  1089. }
  1090. }));
  1091. }
  1092. return (0, _util.shadow)(this, "fieldObjects", Promise.all(allPromises).then(() => allFields));
  1093. }
  1094. get hasJSActions() {
  1095. const promise = this.pdfManager.ensureDoc("_parseHasJSActions");
  1096. return (0, _util.shadow)(this, "hasJSActions", promise);
  1097. }
  1098. async _parseHasJSActions() {
  1099. const [catalogJsActions, fieldObjects] = await Promise.all([this.pdfManager.ensureCatalog("jsActions"), this.pdfManager.ensureDoc("fieldObjects")]);
  1100. if (catalogJsActions) {
  1101. return true;
  1102. }
  1103. if (fieldObjects) {
  1104. return Object.values(fieldObjects).some(fieldObject => fieldObject.some(object => object.actions !== null));
  1105. }
  1106. return false;
  1107. }
  1108. get calculationOrderIds() {
  1109. const acroForm = this.catalog.acroForm;
  1110. if (!acroForm || !acroForm.has("CO")) {
  1111. return (0, _util.shadow)(this, "calculationOrderIds", null);
  1112. }
  1113. const calculationOrder = acroForm.get("CO");
  1114. if (!Array.isArray(calculationOrder) || calculationOrder.length === 0) {
  1115. return (0, _util.shadow)(this, "calculationOrderIds", null);
  1116. }
  1117. const ids = calculationOrder.filter(_primitives.isRef).map(ref => ref.toString());
  1118. if (ids.length === 0) {
  1119. return (0, _util.shadow)(this, "calculationOrderIds", null);
  1120. }
  1121. return (0, _util.shadow)(this, "calculationOrderIds", ids);
  1122. }
  1123. }
  1124. exports.PDFDocument = PDFDocument;