UNPKG

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