pdf_document_properties.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2019 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.PDFDocumentProperties = void 0;
  27. var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
  28. var _pdf = require("../pdf");
  29. var _ui_utils = require("./ui_utils");
  30. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  31. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
  32. function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
  33. function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
  34. function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
  35. function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
  36. function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
  37. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  38. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  39. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  40. var DEFAULT_FIELD_CONTENT = '-';
  41. var NON_METRIC_LOCALES = ['en-us', 'en-lr', 'my'];
  42. var US_PAGE_NAMES = {
  43. '8.5x11': 'Letter',
  44. '8.5x14': 'Legal'
  45. };
  46. var METRIC_PAGE_NAMES = {
  47. '297x420': 'A3',
  48. '210x297': 'A4'
  49. };
  50. function getPageName(size, isPortrait, pageNames) {
  51. var width = isPortrait ? size.width : size.height;
  52. var height = isPortrait ? size.height : size.width;
  53. return pageNames["".concat(width, "x").concat(height)];
  54. }
  55. var PDFDocumentProperties =
  56. /*#__PURE__*/
  57. function () {
  58. function PDFDocumentProperties(_ref, overlayManager, eventBus) {
  59. var _this = this;
  60. var overlayName = _ref.overlayName,
  61. fields = _ref.fields,
  62. container = _ref.container,
  63. closeButton = _ref.closeButton;
  64. var l10n = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : _ui_utils.NullL10n;
  65. _classCallCheck(this, PDFDocumentProperties);
  66. this.overlayName = overlayName;
  67. this.fields = fields;
  68. this.container = container;
  69. this.overlayManager = overlayManager;
  70. this.l10n = l10n;
  71. this._reset();
  72. if (closeButton) {
  73. closeButton.addEventListener('click', this.close.bind(this));
  74. }
  75. this.overlayManager.register(this.overlayName, this.container, this.close.bind(this));
  76. if (eventBus) {
  77. eventBus.on('pagechanging', function (evt) {
  78. _this._currentPageNumber = evt.pageNumber;
  79. });
  80. eventBus.on('rotationchanging', function (evt) {
  81. _this._pagesRotation = evt.pagesRotation;
  82. });
  83. }
  84. this._isNonMetricLocale = true;
  85. l10n.getLanguage().then(function (locale) {
  86. _this._isNonMetricLocale = NON_METRIC_LOCALES.includes(locale);
  87. });
  88. }
  89. _createClass(PDFDocumentProperties, [{
  90. key: "open",
  91. value: function open() {
  92. var _this2 = this;
  93. var freezeFieldData = function freezeFieldData(data) {
  94. Object.defineProperty(_this2, 'fieldData', {
  95. value: Object.freeze(data),
  96. writable: false,
  97. enumerable: true,
  98. configurable: true
  99. });
  100. };
  101. Promise.all([this.overlayManager.open(this.overlayName), this._dataAvailableCapability.promise]).then(function () {
  102. var currentPageNumber = _this2._currentPageNumber;
  103. var pagesRotation = _this2._pagesRotation;
  104. if (_this2.fieldData && currentPageNumber === _this2.fieldData['_currentPageNumber'] && pagesRotation === _this2.fieldData['_pagesRotation']) {
  105. _this2._updateUI();
  106. return;
  107. }
  108. _this2.pdfDocument.getMetadata().then(function (_ref2) {
  109. var info = _ref2.info,
  110. metadata = _ref2.metadata,
  111. contentDispositionFilename = _ref2.contentDispositionFilename;
  112. return Promise.all([info, metadata, contentDispositionFilename || (0, _ui_utils.getPDFFileNameFromURL)(_this2.url || ''), _this2._parseFileSize(_this2.maybeFileSize), _this2._parseDate(info.CreationDate), _this2._parseDate(info.ModDate), _this2.pdfDocument.getPage(currentPageNumber).then(function (pdfPage) {
  113. return _this2._parsePageSize((0, _ui_utils.getPageSizeInches)(pdfPage), pagesRotation);
  114. }), _this2._parseLinearization(info.IsLinearized)]);
  115. }).then(function (_ref3) {
  116. var _ref4 = _slicedToArray(_ref3, 8),
  117. info = _ref4[0],
  118. metadata = _ref4[1],
  119. fileName = _ref4[2],
  120. fileSize = _ref4[3],
  121. creationDate = _ref4[4],
  122. modDate = _ref4[5],
  123. pageSize = _ref4[6],
  124. isLinearized = _ref4[7];
  125. freezeFieldData({
  126. 'fileName': fileName,
  127. 'fileSize': fileSize,
  128. 'title': info.Title,
  129. 'author': info.Author,
  130. 'subject': info.Subject,
  131. 'keywords': info.Keywords,
  132. 'creationDate': creationDate,
  133. 'modificationDate': modDate,
  134. 'creator': info.Creator,
  135. 'producer': info.Producer,
  136. 'version': info.PDFFormatVersion,
  137. 'pageCount': _this2.pdfDocument.numPages,
  138. 'pageSize': pageSize,
  139. 'linearized': isLinearized,
  140. '_currentPageNumber': currentPageNumber,
  141. '_pagesRotation': pagesRotation
  142. });
  143. _this2._updateUI();
  144. return _this2.pdfDocument.getDownloadInfo();
  145. }).then(function (_ref5) {
  146. var length = _ref5.length;
  147. _this2.maybeFileSize = length;
  148. return _this2._parseFileSize(length);
  149. }).then(function (fileSize) {
  150. if (fileSize === _this2.fieldData['fileSize']) {
  151. return;
  152. }
  153. var data = Object.assign(Object.create(null), _this2.fieldData);
  154. data['fileSize'] = fileSize;
  155. freezeFieldData(data);
  156. _this2._updateUI();
  157. });
  158. });
  159. }
  160. }, {
  161. key: "close",
  162. value: function close() {
  163. this.overlayManager.close(this.overlayName);
  164. }
  165. }, {
  166. key: "setDocument",
  167. value: function setDocument(pdfDocument) {
  168. var url = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  169. if (this.pdfDocument) {
  170. this._reset();
  171. this._updateUI(true);
  172. }
  173. if (!pdfDocument) {
  174. return;
  175. }
  176. this.pdfDocument = pdfDocument;
  177. this.url = url;
  178. this._dataAvailableCapability.resolve();
  179. }
  180. }, {
  181. key: "setFileSize",
  182. value: function setFileSize(fileSize) {
  183. if (Number.isInteger(fileSize) && fileSize > 0) {
  184. this.maybeFileSize = fileSize;
  185. }
  186. }
  187. }, {
  188. key: "_reset",
  189. value: function _reset() {
  190. this.pdfDocument = null;
  191. this.url = null;
  192. this.maybeFileSize = 0;
  193. delete this.fieldData;
  194. this._dataAvailableCapability = (0, _pdf.createPromiseCapability)();
  195. this._currentPageNumber = 1;
  196. this._pagesRotation = 0;
  197. }
  198. }, {
  199. key: "_updateUI",
  200. value: function _updateUI() {
  201. var reset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  202. if (reset || !this.fieldData) {
  203. for (var id in this.fields) {
  204. this.fields[id].textContent = DEFAULT_FIELD_CONTENT;
  205. }
  206. return;
  207. }
  208. if (this.overlayManager.active !== this.overlayName) {
  209. return;
  210. }
  211. for (var _id in this.fields) {
  212. var content = this.fieldData[_id];
  213. this.fields[_id].textContent = content || content === 0 ? content : DEFAULT_FIELD_CONTENT;
  214. }
  215. }
  216. }, {
  217. key: "_parseFileSize",
  218. value: function () {
  219. var _parseFileSize2 = _asyncToGenerator(
  220. /*#__PURE__*/
  221. _regenerator["default"].mark(function _callee() {
  222. var fileSize,
  223. kb,
  224. _args = arguments;
  225. return _regenerator["default"].wrap(function _callee$(_context) {
  226. while (1) {
  227. switch (_context.prev = _context.next) {
  228. case 0:
  229. fileSize = _args.length > 0 && _args[0] !== undefined ? _args[0] : 0;
  230. kb = fileSize / 1024;
  231. if (kb) {
  232. _context.next = 6;
  233. break;
  234. }
  235. return _context.abrupt("return", undefined);
  236. case 6:
  237. if (!(kb < 1024)) {
  238. _context.next = 8;
  239. break;
  240. }
  241. return _context.abrupt("return", this.l10n.get('document_properties_kb', {
  242. size_kb: (+kb.toPrecision(3)).toLocaleString(),
  243. size_b: fileSize.toLocaleString()
  244. }, '{{size_kb}} KB ({{size_b}} bytes)'));
  245. case 8:
  246. return _context.abrupt("return", this.l10n.get('document_properties_mb', {
  247. size_mb: (+(kb / 1024).toPrecision(3)).toLocaleString(),
  248. size_b: fileSize.toLocaleString()
  249. }, '{{size_mb}} MB ({{size_b}} bytes)'));
  250. case 9:
  251. case "end":
  252. return _context.stop();
  253. }
  254. }
  255. }, _callee, this);
  256. }));
  257. function _parseFileSize() {
  258. return _parseFileSize2.apply(this, arguments);
  259. }
  260. return _parseFileSize;
  261. }()
  262. }, {
  263. key: "_parsePageSize",
  264. value: function () {
  265. var _parsePageSize2 = _asyncToGenerator(
  266. /*#__PURE__*/
  267. _regenerator["default"].mark(function _callee2(pageSizeInches, pagesRotation) {
  268. var _this3 = this;
  269. var isPortrait, sizeInches, sizeMillimeters, pageName, name, exactMillimeters, intMillimeters;
  270. return _regenerator["default"].wrap(function _callee2$(_context2) {
  271. while (1) {
  272. switch (_context2.prev = _context2.next) {
  273. case 0:
  274. if (pageSizeInches) {
  275. _context2.next = 2;
  276. break;
  277. }
  278. return _context2.abrupt("return", undefined);
  279. case 2:
  280. if (pagesRotation % 180 !== 0) {
  281. pageSizeInches = {
  282. width: pageSizeInches.height,
  283. height: pageSizeInches.width
  284. };
  285. }
  286. isPortrait = (0, _ui_utils.isPortraitOrientation)(pageSizeInches);
  287. sizeInches = {
  288. width: Math.round(pageSizeInches.width * 100) / 100,
  289. height: Math.round(pageSizeInches.height * 100) / 100
  290. };
  291. sizeMillimeters = {
  292. width: Math.round(pageSizeInches.width * 25.4 * 10) / 10,
  293. height: Math.round(pageSizeInches.height * 25.4 * 10) / 10
  294. };
  295. pageName = null;
  296. name = getPageName(sizeInches, isPortrait, US_PAGE_NAMES) || getPageName(sizeMillimeters, isPortrait, METRIC_PAGE_NAMES);
  297. if (!name && !(Number.isInteger(sizeMillimeters.width) && Number.isInteger(sizeMillimeters.height))) {
  298. exactMillimeters = {
  299. width: pageSizeInches.width * 25.4,
  300. height: pageSizeInches.height * 25.4
  301. };
  302. intMillimeters = {
  303. width: Math.round(sizeMillimeters.width),
  304. height: Math.round(sizeMillimeters.height)
  305. };
  306. if (Math.abs(exactMillimeters.width - intMillimeters.width) < 0.1 && Math.abs(exactMillimeters.height - intMillimeters.height) < 0.1) {
  307. name = getPageName(intMillimeters, isPortrait, METRIC_PAGE_NAMES);
  308. if (name) {
  309. sizeInches = {
  310. width: Math.round(intMillimeters.width / 25.4 * 100) / 100,
  311. height: Math.round(intMillimeters.height / 25.4 * 100) / 100
  312. };
  313. sizeMillimeters = intMillimeters;
  314. }
  315. }
  316. }
  317. if (name) {
  318. pageName = this.l10n.get('document_properties_page_size_name_' + name.toLowerCase(), null, name);
  319. }
  320. return _context2.abrupt("return", Promise.all([this._isNonMetricLocale ? sizeInches : sizeMillimeters, this.l10n.get('document_properties_page_size_unit_' + (this._isNonMetricLocale ? 'inches' : 'millimeters'), null, this._isNonMetricLocale ? 'in' : 'mm'), pageName, this.l10n.get('document_properties_page_size_orientation_' + (isPortrait ? 'portrait' : 'landscape'), null, isPortrait ? 'portrait' : 'landscape')]).then(function (_ref6) {
  321. var _ref7 = _slicedToArray(_ref6, 4),
  322. _ref7$ = _ref7[0],
  323. width = _ref7$.width,
  324. height = _ref7$.height,
  325. unit = _ref7[1],
  326. name = _ref7[2],
  327. orientation = _ref7[3];
  328. return _this3.l10n.get('document_properties_page_size_dimension_' + (name ? 'name_' : '') + 'string', {
  329. width: width.toLocaleString(),
  330. height: height.toLocaleString(),
  331. unit: unit,
  332. name: name,
  333. orientation: orientation
  334. }, '{{width}} × {{height}} {{unit}} (' + (name ? '{{name}}, ' : '') + '{{orientation}})');
  335. }));
  336. case 11:
  337. case "end":
  338. return _context2.stop();
  339. }
  340. }
  341. }, _callee2, this);
  342. }));
  343. function _parsePageSize(_x, _x2) {
  344. return _parsePageSize2.apply(this, arguments);
  345. }
  346. return _parsePageSize;
  347. }()
  348. }, {
  349. key: "_parseDate",
  350. value: function () {
  351. var _parseDate2 = _asyncToGenerator(
  352. /*#__PURE__*/
  353. _regenerator["default"].mark(function _callee3(inputDate) {
  354. var dateObject;
  355. return _regenerator["default"].wrap(function _callee3$(_context3) {
  356. while (1) {
  357. switch (_context3.prev = _context3.next) {
  358. case 0:
  359. dateObject = _pdf.PDFDateString.toDateObject(inputDate);
  360. if (dateObject) {
  361. _context3.next = 3;
  362. break;
  363. }
  364. return _context3.abrupt("return", undefined);
  365. case 3:
  366. return _context3.abrupt("return", this.l10n.get('document_properties_date_string', {
  367. date: dateObject.toLocaleDateString(),
  368. time: dateObject.toLocaleTimeString()
  369. }, '{{date}}, {{time}}'));
  370. case 4:
  371. case "end":
  372. return _context3.stop();
  373. }
  374. }
  375. }, _callee3, this);
  376. }));
  377. function _parseDate(_x3) {
  378. return _parseDate2.apply(this, arguments);
  379. }
  380. return _parseDate;
  381. }()
  382. }, {
  383. key: "_parseLinearization",
  384. value: function _parseLinearization(isLinearized) {
  385. return this.l10n.get('document_properties_linearized_' + (isLinearized ? 'yes' : 'no'), null, isLinearized ? 'Yes' : 'No');
  386. }
  387. }]);
  388. return PDFDocumentProperties;
  389. }();
  390. exports.PDFDocumentProperties = PDFDocumentProperties;