document.js 35 KB

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