瀏覽代碼

[FIX] check mimetype and convert into accepts data

Gogs 6 年之前
父節點
當前提交
23d4053e95
共有 3 個文件被更改,包括 245 次插入160 次删除
  1. 27 11
      static/lib/js/pdf.js
  2. 208 138
      static/lib/js/pdf.worker.js
  3. 10 11
      static/src/js/main.js

+ 27 - 11
static/lib/js/pdf.js

@@ -123,8 +123,8 @@ return /******/ (function(modules) { // webpackBootstrap
 "use strict";
 
 
-var pdfjsVersion = '2.0.690';
-var pdfjsBuild = '7e139776';
+var pdfjsVersion = '2.0.752';
+var pdfjsBuild = '13b98746';
 var pdfjsSharedUtil = __w_pdfjs_require__(1);
 var pdfjsDisplayAPI = __w_pdfjs_require__(118);
 var pdfjsDisplayTextLayer = __w_pdfjs_require__(130);
@@ -7598,7 +7598,7 @@ function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
   }
   return worker.messageHandler.sendWithPromise('GetDocRequest', {
     docId: docId,
-    apiVersion: '2.0.690',
+    apiVersion: '2.0.752',
     source: {
       data: source.data,
       url: source.url,
@@ -9045,8 +9045,8 @@ var InternalRenderTask = function InternalRenderTaskClosure() {
 }();
 var version, build;
 {
-  exports.version = version = '2.0.690';
-  exports.build = build = '7e139776';
+  exports.version = version = '2.0.752';
+  exports.build = build = '13b98746';
 }
 exports.getDocument = getDocument;
 exports.LoopbackPort = LoopbackPort;
@@ -12872,6 +12872,9 @@ var SimpleXMLParser = function (_XMLParserBase) {
       var _currentFragment = _slicedToArray(this._currentFragment, 1),
           documentElement = _currentFragment[0];
 
+      if (!documentElement) {
+        return undefined;
+      }
       return { documentElement: documentElement };
     }
   }, {
@@ -16551,6 +16554,12 @@ var PDFNodeStreamFullReader = function (_BaseFullReader) {
     var _this5 = _possibleConstructorReturn(this, (PDFNodeStreamFullReader.__proto__ || Object.getPrototypeOf(PDFNodeStreamFullReader)).call(this, stream));
 
     var handleResponse = function handleResponse(response) {
+      if (response.statusCode === 404) {
+        var error = new _util.MissingPDFException('Missing PDF "' + _this5._url + '".');
+        _this5._storedError = error;
+        _this5._headersCapability.reject(error);
+        return;
+      }
       _this5._headersCapability.resolve();
       _this5._setReadableStream(response);
       var getResponseHeader = function getResponseHeader(name) {
@@ -16604,15 +16613,19 @@ var PDFNodeStreamRangeReader = function (_BaseRangeReader) {
       _this6._httpHeaders[property] = value;
     }
     _this6._httpHeaders['Range'] = 'bytes=' + start + '-' + (end - 1);
+    var handleResponse = function handleResponse(response) {
+      if (response.statusCode === 404) {
+        var error = new _util.MissingPDFException('Missing PDF "' + _this6._url + '".');
+        _this6._storedError = error;
+        return;
+      }
+      _this6._setReadableStream(response);
+    };
     _this6._request = null;
     if (_this6._url.protocol === 'http:') {
-      _this6._request = http.request(createRequestOptions(_this6._url, _this6._httpHeaders), function (response) {
-        _this6._setReadableStream(response);
-      });
+      _this6._request = http.request(createRequestOptions(_this6._url, _this6._httpHeaders), handleResponse);
     } else {
-      _this6._request = https.request(createRequestOptions(_this6._url, _this6._httpHeaders), function (response) {
-        _this6._setReadableStream(response);
-      });
+      _this6._request = https.request(createRequestOptions(_this6._url, _this6._httpHeaders), handleResponse);
     }
     _this6._request.on('error', function (reason) {
       _this6._storedError = reason;
@@ -16638,6 +16651,9 @@ var PDFNodeStreamFsFullReader = function (_BaseFullReader2) {
     }
     fs.lstat(path, function (error, stat) {
       if (error) {
+        if (error.code === 'ENOENT') {
+          error = new _util.MissingPDFException('Missing PDF "' + path + '".');
+        }
         _this7._storedError = error;
         _this7._headersCapability.reject(error);
         return;

+ 208 - 138
static/lib/js/pdf.worker.js

@@ -123,8 +123,8 @@ return /******/ (function(modules) { // webpackBootstrap
 "use strict";
 
 
-var pdfjsVersion = '2.0.690';
-var pdfjsBuild = '7e139776';
+var pdfjsVersion = '2.0.752';
+var pdfjsBuild = '13b98746';
 var pdfjsCoreWorker = __w_pdfjs_require__(1);
 exports.WorkerMessageHandler = pdfjsCoreWorker.WorkerMessageHandler;
 
@@ -339,7 +339,7 @@ var WorkerMessageHandler = {
     var cancelXHRs = null;
     var WorkerTasks = [];
     var apiVersion = docParams.apiVersion;
-    var workerVersion = '2.0.690';
+    var workerVersion = '2.0.752';
     if (apiVersion !== workerVersion) {
       throw new Error('The API version "' + apiVersion + '" does not match ' + ('the Worker version "' + workerVersion + '".'));
     }
@@ -8673,12 +8673,12 @@ exports.PDFDocument = exports.Page = undefined;
 
 var _slicedToArray = function () { function sliceIterator(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"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
 
+var _util = __w_pdfjs_require__(2);
+
 var _obj = __w_pdfjs_require__(122);
 
 var _primitives = __w_pdfjs_require__(123);
 
-var _util = __w_pdfjs_require__(2);
-
 var _stream = __w_pdfjs_require__(125);
 
 var _annotation = __w_pdfjs_require__(137);
@@ -8979,6 +8979,7 @@ var PDFDocument = function PDFDocumentClosure() {
       xref: this.xref,
       isEvalSupported: evaluatorOptions.isEvalSupported
     });
+    this._pagePromises = [];
   }
   function find(stream, needle, limit, backwards) {
     var pos = stream.pos;
@@ -9000,19 +9001,15 @@ var PDFDocument = function PDFDocumentClosure() {
     return true;
   }
   var DocumentInfoValidators = {
-    get entries() {
-      return (0, _util.shadow)(this, 'entries', {
-        Title: _util.isString,
-        Author: _util.isString,
-        Subject: _util.isString,
-        Keywords: _util.isString,
-        Creator: _util.isString,
-        Producer: _util.isString,
-        CreationDate: _util.isString,
-        ModDate: _util.isString,
-        Trapped: _primitives.isName
-      });
-    }
+    Title: _util.isString,
+    Author: _util.isString,
+    Subject: _util.isString,
+    Keywords: _util.isString,
+    Creator: _util.isString,
+    Producer: _util.isString,
+    CreationDate: _util.isString,
+    ModDate: _util.isString,
+    Trapped: _primitives.isName
   };
   PDFDocument.prototype = {
     parse: function PDFDocument_parse(recoveryMode) {
@@ -9040,15 +9037,13 @@ var PDFDocument = function PDFDocumentClosure() {
     },
     get linearization() {
       var linearization = null;
-      if (this.stream.length) {
-        try {
-          linearization = _parser.Linearization.create(this.stream);
-        } catch (err) {
-          if (err instanceof _util.MissingDataException) {
-            throw err;
-          }
-          (0, _util.info)(err);
+      try {
+        linearization = _parser.Linearization.create(this.stream);
+      } catch (err) {
+        if (err instanceof _util.MissingDataException) {
+          throw err;
         }
+        (0, _util.info)(err);
       }
       return (0, _util.shadow)(this, 'linearization', linearization);
     },
@@ -9125,24 +9120,8 @@ var PDFDocument = function PDFDocumentClosure() {
       this.xref.setStartXRef(startXRef);
     },
     setup: function PDFDocument_setup(recoveryMode) {
-      var _this4 = this;
-
       this.xref.parse(recoveryMode);
-      var pageFactory = {
-        createPage: function createPage(pageIndex, dict, ref, fontCache, builtInCMapCache) {
-          return new Page({
-            pdfManager: _this4.pdfManager,
-            xref: _this4.xref,
-            pageIndex: pageIndex,
-            pageDict: dict,
-            ref: ref,
-            fontCache: fontCache,
-            builtInCMapCache: builtInCMapCache,
-            pdfFunctionFactory: _this4.pdfFunctionFactory
-          });
-        }
-      };
-      this.catalog = new _obj.Catalog(this.pdfManager, this.xref, pageFactory);
+      this.catalog = new _obj.Catalog(this.pdfManager, this.xref);
     },
     get numPages() {
       var linearization = this.linearization;
@@ -9152,10 +9131,11 @@ var PDFDocument = function PDFDocumentClosure() {
     get documentInfo() {
       var docInfo = {
         PDFFormatVersion: this.pdfFormatVersion,
+        IsLinearized: !!this.linearization,
         IsAcroFormPresent: !!this.acroForm,
         IsXFAPresent: !!this.xfa
       };
-      var infoDict;
+      var infoDict = void 0;
       try {
         infoDict = this.xref.trailer.get('Info');
       } catch (err) {
@@ -9164,12 +9144,11 @@ var PDFDocument = function PDFDocumentClosure() {
         }
         (0, _util.info)('The document information dictionary is invalid.');
       }
-      if (infoDict) {
-        var validEntries = DocumentInfoValidators.entries;
-        for (var key in validEntries) {
+      if ((0, _primitives.isDict)(infoDict)) {
+        for (var key in DocumentInfoValidators) {
           if (infoDict.has(key)) {
             var value = infoDict.get(key);
-            if (validEntries[key](value)) {
+            if (DocumentInfoValidators[key](value)) {
               docInfo[key] = typeof value !== 'string' ? value : (0, _util.stringToPDFString)(value);
             } else {
               (0, _util.info)('Bad value in document info for "' + key + '"');
@@ -9198,9 +9177,53 @@ var PDFDocument = function PDFDocumentClosure() {
       }
       return (0, _util.shadow)(this, 'fingerprint', fileID);
     },
-    getPage: function PDFDocument_getPage(pageIndex) {
-      return this.catalog.getPage(pageIndex);
+    _getLinearizationPage: function _getLinearizationPage(pageIndex) {
+      var catalog = this.catalog,
+          linearization = this.linearization;
+
+      (0, _util.assert)(linearization && linearization.pageFirst === pageIndex);
+      var ref = new _primitives.Ref(linearization.objectNumberFirst, 0);
+      return this.xref.fetchAsync(ref).then(function (obj) {
+        if ((0, _primitives.isDict)(obj, 'Page') || (0, _primitives.isDict)(obj) && !obj.has('Type') && obj.has('Contents')) {
+          if (ref && !catalog.pageKidsCountCache.has(ref)) {
+            catalog.pageKidsCountCache.put(ref, 1);
+          }
+          return [obj, ref];
+        }
+        throw new _util.FormatError('The Linearization dictionary doesn\'t point ' + 'to a valid Page dictionary.');
+      }).catch(function (reason) {
+        (0, _util.info)(reason);
+        return catalog.getPageDict(pageIndex);
+      });
+    },
+    getPage: function getPage(pageIndex) {
+      var _this4 = this;
+
+      if (this._pagePromises[pageIndex] !== undefined) {
+        return this._pagePromises[pageIndex];
+      }
+      var catalog = this.catalog,
+          linearization = this.linearization;
+
+      var promise = linearization && linearization.pageFirst === pageIndex ? this._getLinearizationPage(pageIndex) : catalog.getPageDict(pageIndex);
+      return this._pagePromises[pageIndex] = promise.then(function (_ref10) {
+        var _ref11 = _slicedToArray(_ref10, 2),
+            pageDict = _ref11[0],
+            ref = _ref11[1];
+
+        return new Page({
+          pdfManager: _this4.pdfManager,
+          xref: _this4.xref,
+          pageIndex: pageIndex,
+          pageDict: pageDict,
+          ref: ref,
+          fontCache: catalog.fontCache,
+          builtInCMapCache: catalog.builtInCMapCache,
+          pdfFunctionFactory: _this4.pdfFunctionFactory
+        });
+      });
     },
+
     cleanup: function PDFDocument_cleanup() {
       return this.catalog.cleanup();
     }
@@ -9226,8 +9249,6 @@ var _createClass = function () { function defineProperties(target, props) { for
 
 var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
 
-var _slicedToArray = function () { function sliceIterator(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"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
-
 var _util = __w_pdfjs_require__(2);
 
 var _primitives = __w_pdfjs_require__(123);
@@ -9247,7 +9268,7 @@ function _inherits(subClass, superClass) { if (typeof superClass !== "function"
 function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
 
 var Catalog = function CatalogClosure() {
-  function Catalog(pdfManager, xref, pageFactory) {
+  function Catalog(pdfManager, xref) {
     this.pdfManager = pdfManager;
     this.xref = xref;
     this.catDict = xref.getCatalogObj();
@@ -9255,10 +9276,8 @@ var Catalog = function CatalogClosure() {
       throw new _util.FormatError('catalog object is not a dictionary');
     }
     this.fontCache = new _primitives.RefSetCache();
-    this.builtInCMapCache = Object.create(null);
+    this.builtInCMapCache = new Map();
     this.pageKidsCountCache = new _primitives.RefSetCache();
-    this.pageFactory = pageFactory;
-    this.pagePromises = [];
   }
   Catalog.prototype = {
     get metadata() {
@@ -9636,23 +9655,9 @@ var Catalog = function CatalogClosure() {
           delete font.translated;
         }
         _this.fontCache.clear();
-        _this.builtInCMapCache = Object.create(null);
+        _this.builtInCMapCache.clear();
       });
     },
-    getPage: function Catalog_getPage(pageIndex) {
-      var _this2 = this;
-
-      if (!(pageIndex in this.pagePromises)) {
-        this.pagePromises[pageIndex] = this.getPageDict(pageIndex).then(function (_ref) {
-          var _ref2 = _slicedToArray(_ref, 2),
-              dict = _ref2[0],
-              ref = _ref2[1];
-
-          return _this2.pageFactory.createPage(pageIndex, dict, ref, _this2.fontCache, _this2.builtInCMapCache);
-        });
-      }
-      return this.pagePromises[pageIndex];
-    },
     getPageDict: function Catalog_getPageDict(pageIndex) {
       var capability = (0, _util.createPromiseCapability)();
       var nodesToVisit = [this.catDict.getRaw('Pages')];
@@ -10775,7 +10780,7 @@ var ObjectLoader = function () {
       return this.capability.promise;
     },
     _walk: function _walk(nodesToVisit) {
-      var _this5 = this;
+      var _this4 = this;
 
       var nodesToRevisit = [];
       var pendingRequests = [];
@@ -10823,10 +10828,10 @@ var ObjectLoader = function () {
           for (var _i3 = 0, _ii3 = nodesToRevisit.length; _i3 < _ii3; _i3++) {
             var node = nodesToRevisit[_i3];
             if ((0, _primitives.isRef)(node)) {
-              _this5.refSet.remove(node);
+              _this4.refSet.remove(node);
             }
           }
-          _this5._walk(nodesToRevisit);
+          _this4._walk(nodesToRevisit);
         }, this.capability.reject);
         return;
       }
@@ -12190,6 +12195,7 @@ var StringStream = function StringStreamClosure() {
 var DecodeStream = function DecodeStreamClosure() {
   var emptyBuffer = new Uint8Array(0);
   function DecodeStream(maybeMinBufferLength) {
+    this._rawMinBufferLength = maybeMinBufferLength || 0;
     this.pos = 0;
     this.bufferLength = 0;
     this.eof = false;
@@ -12313,7 +12319,16 @@ var DecodeStream = function DecodeStreamClosure() {
 var StreamsSequenceStream = function StreamsSequenceStreamClosure() {
   function StreamsSequenceStream(streams) {
     this.streams = streams;
-    DecodeStream.call(this, null);
+    var maybeLength = 0;
+    for (var i = 0, ii = streams.length; i < ii; i++) {
+      var stream = streams[i];
+      if (stream instanceof DecodeStream) {
+        maybeLength += stream._rawMinBufferLength;
+      } else {
+        maybeLength += stream.length;
+      }
+    }
+    DecodeStream.call(this, maybeLength);
   }
   StreamsSequenceStream.prototype = Object.create(DecodeStream.prototype);
   StreamsSequenceStream.prototype.readBlock = function streamSequenceStreamReadBlock() {
@@ -21120,11 +21135,6 @@ var CalRGBCS = function CalRGBCSClosure() {
       (0, _util.info)('Invalid Gamma [' + this.GR + ', ' + this.GG + ', ' + this.GB + '] for ' + this.name + ', falling back to default');
       this.GR = this.GG = this.GB = 1;
     }
-    if (this.MXA < 0 || this.MYA < 0 || this.MZA < 0 || this.MXB < 0 || this.MYB < 0 || this.MZB < 0 || this.MXC < 0 || this.MYC < 0 || this.MZC < 0) {
-      (0, _util.info)('Invalid Matrix for ' + this.name + ' [' + this.MXA + ', ' + this.MYA + ', ' + this.MZA + this.MXB + ', ' + this.MYB + ', ' + this.MZB + this.MXC + ', ' + this.MYC + ', ' + this.MZC + '], falling back to default');
-      this.MXA = this.MYB = this.MZC = 1;
-      this.MXB = this.MYA = this.MZA = this.MXC = this.MYC = this.MZB = 0;
-    }
   }
   function matrixProduct(a, b, result) {
     result[0] = a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
@@ -21949,7 +21959,7 @@ var ButtonWidgetAnnotation = function (_WidgetAnnotation2) {
     _this4.data.radioButton = _this4.hasFieldFlag(_util.AnnotationFieldFlag.RADIO) && !_this4.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
     _this4.data.pushButton = _this4.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
     if (_this4.data.checkBox) {
-      _this4._processCheckBox();
+      _this4._processCheckBox(params);
     } else if (_this4.data.radioButton) {
       _this4._processRadioButton(params);
     } else if (_this4.data.pushButton) {
@@ -21962,11 +21972,24 @@ var ButtonWidgetAnnotation = function (_WidgetAnnotation2) {
 
   _createClass(ButtonWidgetAnnotation, [{
     key: '_processCheckBox',
-    value: function _processCheckBox() {
-      if (!(0, _primitives.isName)(this.data.fieldValue)) {
+    value: function _processCheckBox(params) {
+      if ((0, _primitives.isName)(this.data.fieldValue)) {
+        this.data.fieldValue = this.data.fieldValue.name;
+      }
+      var customAppearance = params.dict.get('AP');
+      if (!(0, _primitives.isDict)(customAppearance)) {
         return;
       }
-      this.data.fieldValue = this.data.fieldValue.name;
+      var exportValueOptionsDict = customAppearance.get('D');
+      if (!(0, _primitives.isDict)(exportValueOptionsDict)) {
+        return;
+      }
+      var exportValues = exportValueOptionsDict.getKeys();
+      var hasCorrectOptionCount = exportValues.length === 2;
+      if (!hasCorrectOptionCount) {
+        return;
+      }
+      this.data.exportValue = exportValues[0] === 'Off' ? exportValues[1] : exportValues[0];
     }
   }, {
     key: '_processRadioButton',
@@ -22981,13 +23004,12 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
     this.options = options || DefaultPartialEvaluatorOptions;
     this.pdfFunctionFactory = pdfFunctionFactory;
     this.fetchBuiltInCMap = function (name) {
-      var cachedCMap = _this.builtInCMapCache[name];
-      if (cachedCMap) {
-        return Promise.resolve(cachedCMap);
+      if (_this.builtInCMapCache.has(name)) {
+        return Promise.resolve(_this.builtInCMapCache.get(name));
       }
       return _this.handler.sendWithPromise('FetchBuiltInCMap', { name: name }).then(function (data) {
         if (data.compressionType !== _util.CMapCompressionType.NONE) {
-          _this.builtInCMapCache[name] = data;
+          _this.builtInCMapCache.set(name, data);
         }
         return data;
       });
@@ -24411,8 +24433,8 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
         var cidSystemInfo = dict.get('CIDSystemInfo');
         if ((0, _primitives.isDict)(cidSystemInfo)) {
           properties.cidSystemInfo = {
-            registry: cidSystemInfo.get('Registry'),
-            ordering: cidSystemInfo.get('Ordering'),
+            registry: (0, _util.stringToPDFString)(cidSystemInfo.get('Registry')),
+            ordering: (0, _util.stringToPDFString)(cidSystemInfo.get('Ordering')),
             supplement: cidSystemInfo.get('Supplement')
           };
         }
@@ -26437,6 +26459,8 @@ Object.defineProperty(exports, "__esModule", {
 });
 exports.getFontType = exports.ProblematicCharRanges = exports.IdentityToUnicodeMap = exports.ToUnicodeMap = exports.FontFlags = exports.Font = exports.ErrorFont = exports.PRIVATE_USE_OFFSET_END = exports.PRIVATE_USE_OFFSET_START = exports.SEAC_ANALYSIS_ENABLED = undefined;
 
+var _slicedToArray = function () { function sliceIterator(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"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
+
 var _util = __w_pdfjs_require__(2);
 
 var _cff_parser = __w_pdfjs_require__(142);
@@ -26451,6 +26475,8 @@ var _unicode = __w_pdfjs_require__(147);
 
 var _font_renderer = __w_pdfjs_require__(148);
 
+var _cmap = __w_pdfjs_require__(140);
+
 var _stream = __w_pdfjs_require__(125);
 
 var _type1_parser = __w_pdfjs_require__(149);
@@ -26792,31 +26818,16 @@ var Font = function FontClosure() {
       this.fallbackToSystemFont();
       return;
     }
-    if (subtype === 'Type1C') {
-      if (type !== 'Type1' && type !== 'MMType1') {
-        if (isTrueTypeFile(file)) {
-          subtype = 'TrueType';
-        } else {
-          type = 'Type1';
-        }
-      } else if (isOpenTypeFile(file)) {
-        subtype = 'OpenType';
-      }
-    }
-    if (subtype === 'CIDFontType0C' && type !== 'CIDFontType0') {
-      type = 'CIDFontType0';
-    }
-    if (type === 'CIDFontType0') {
-      if (isType1File(file)) {
-        subtype = 'CIDFontType0';
-      } else if (isOpenTypeFile(file)) {
-        subtype = 'OpenType';
-      } else {
-        subtype = 'CIDFontType0C';
-      }
-    }
-    if (subtype === 'OpenType' && type !== 'OpenType') {
-      type = 'OpenType';
+
+    var _getFontFileType = getFontFileType(file, properties);
+
+    var _getFontFileType2 = _slicedToArray(_getFontFileType, 2);
+
+    type = _getFontFileType2[0];
+    subtype = _getFontFileType2[1];
+
+    if (type !== this.type || subtype !== this.subtype) {
+      (0, _util.info)('Inconsistent font file Type/SubType, expected: ' + (this.type + '/' + this.subtype + ' but found: ' + type + '/' + subtype + '.'));
     }
     try {
       var data;
@@ -26844,9 +26855,6 @@ var Font = function FontClosure() {
           throw new _util.FormatError('Font ' + type + ' is not supported');
       }
     } catch (e) {
-      if (!(e instanceof _util.FormatError)) {
-        throw e;
-      }
       (0, _util.warn)(e);
       this.fallbackToSystemFont();
       return;
@@ -26890,7 +26898,7 @@ var Font = function FontClosure() {
   }
   function isTrueTypeFile(file) {
     var header = file.peekBytes(4);
-    return (0, _util.readUint32)(header, 0) === 0x00010000;
+    return (0, _util.readUint32)(header, 0) === 0x00010000 || (0, _util.bytesToString)(header) === 'true';
   }
   function isTrueTypeCollectionFile(file) {
     var header = file.peekBytes(4);
@@ -26910,6 +26918,55 @@ var Font = function FontClosure() {
     }
     return false;
   }
+  function isCFFFile(file) {
+    var header = file.peekBytes(4);
+    if (header[0] >= 1 && header[3] >= 1 && header[3] <= 4) {
+      return true;
+    }
+    return false;
+  }
+  function getFontFileType(file, _ref) {
+    var type = _ref.type,
+        subtype = _ref.subtype,
+        composite = _ref.composite;
+
+    var fileType = void 0,
+        fileSubtype = void 0;
+    if (isTrueTypeFile(file) || isTrueTypeCollectionFile(file)) {
+      if (composite) {
+        fileType = 'CIDFontType2';
+      } else {
+        fileType = 'TrueType';
+      }
+    } else if (isOpenTypeFile(file)) {
+      if (composite) {
+        fileType = 'CIDFontType2';
+      } else {
+        fileType = 'OpenType';
+      }
+    } else if (isType1File(file)) {
+      if (composite) {
+        fileType = 'CIDFontType0';
+      } else if (type === 'MMType1') {
+        fileType = 'MMType1';
+      } else {
+        fileType = 'Type1';
+      }
+    } else if (isCFFFile(file)) {
+      if (composite) {
+        fileType = 'CIDFontType0';
+        fileSubtype = 'CIDFontType0C';
+      } else {
+        fileType = 'Type1';
+        fileSubtype = 'Type1C';
+      }
+    } else {
+      (0, _util.warn)('getFontFileType: Unable to detect correct font file Type/Subtype.');
+      fileType = type;
+      fileSubtype = subtype;
+    }
+    return [fileType, fileSubtype];
+  }
   function buildToFontChar(encoding, glyphsUnicodeMap, differences) {
     var toFontChar = [],
         unicode;
@@ -28154,7 +28211,8 @@ var Font = function FontClosure() {
           cffFile = void 0;
       var isTrueType = !tables['CFF '];
       if (!isTrueType) {
-        if (header.version === 'OTTO' && !(properties.composite && properties.cidToGidMap) || !tables['head'] || !tables['hhea'] || !tables['maxp'] || !tables['post']) {
+        var isComposite = properties.composite && ((properties.cidToGidMap || []).length > 0 || !(properties.cMap instanceof _cmap.IdentityCMap));
+        if (header.version === 'OTTO' && !isComposite || !tables['head'] || !tables['hhea'] || !tables['maxp'] || !tables['post']) {
           cffFile = new _stream.Stream(tables['CFF '].data);
           cff = new CFFFont(cffFile, properties);
           adjustWidths(properties);
@@ -44637,24 +44695,36 @@ var PDFImage = function PDFImageClosure() {
 
     this.image = image;
     var dict = image.dict;
-    if (dict.has('Filter')) {
-      var filter = dict.get('Filter').name;
-      if (filter === 'JPXDecode') {
-        var jpxImage = new _jpx.JpxImage();
-        jpxImage.parseImageProperties(image.stream);
-        image.stream.reset();
-        image.bitsPerComponent = jpxImage.bitsPerComponent;
-        image.numComps = jpxImage.componentsCount;
-      } else if (filter === 'JBIG2Decode') {
-        image.bitsPerComponent = 1;
-        image.numComps = 1;
-      }
-    }
-    this.width = dict.get('Width', 'W');
-    this.height = dict.get('Height', 'H');
-    if (this.width < 1 || this.height < 1) {
-      throw new _util.FormatError('Invalid image width: ' + this.width + ' or ' + ('height: ' + this.height));
+    var filter = dict.get('Filter');
+    if ((0, _primitives.isName)(filter)) {
+      switch (filter.name) {
+        case 'JPXDecode':
+          var jpxImage = new _jpx.JpxImage();
+          jpxImage.parseImageProperties(image.stream);
+          image.stream.reset();
+          image.width = jpxImage.width;
+          image.height = jpxImage.height;
+          image.bitsPerComponent = jpxImage.bitsPerComponent;
+          image.numComps = jpxImage.componentsCount;
+          break;
+        case 'JBIG2Decode':
+          image.bitsPerComponent = 1;
+          image.numComps = 1;
+          break;
+      }
+    }
+    var width = dict.get('Width', 'W');
+    var height = dict.get('Height', 'H');
+    if (Number.isInteger(image.width) && image.width > 0 && Number.isInteger(image.height) && image.height > 0 && (image.width !== width || image.height !== height)) {
+      (0, _util.warn)('PDFImage - using the Width/Height of the image data, ' + 'rather than the image dictionary.');
+      width = image.width;
+      height = image.height;
     }
+    if (width < 1 || height < 1) {
+      throw new _util.FormatError('Invalid image width: ' + width + ' or ' + ('height: ' + height));
+    }
+    this.width = width;
+    this.height = height;
     this.interpolate = dict.get('Interpolate', 'I') || false;
     this.imageMask = dict.get('ImageMask', 'IM') || false;
     this.matte = dict.get('Matte') || false;
@@ -44685,7 +44755,7 @@ var PDFImage = function PDFImageClosure() {
             colorSpace = _primitives.Name.get('DeviceCMYK');
             break;
           default:
-            throw new Error('JPX images with ' + this.numComps + ' ' + 'color components not supported.');
+            throw new Error('JPX images with ' + image.numComps + ' ' + 'color components not supported.');
         }
       }
       var resources = isInline ? res : null;

+ 10 - 11
static/src/js/main.js

@@ -3,8 +3,6 @@ window.pdfjsLib.GlobalWorkerOptions.workerSrc = '/printer_bridge/static/lib/js/p
 // Tools
 openerp.pdfJs = window.pdfjsLib || _.noop();
 openerp.printJs = window.printJS || _.noop();
-openerp.html2canvas = window.html2canvas || _.noop();
-openerp.html2pdf = window.html2pdf || _.noop();
 
 /**
  * 
@@ -400,27 +398,28 @@ openerp.printer_bridge = function (instance, local) {
 
             var matchMimeType = this.source.match(/data:[a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+.*,/);
 
-            if (matchMimeType) {
-                if (this.source.startsWith('data:application/pdf;base64,')) {
-                    this.source = {
-                        data: this.source.replace(matchMimeType[0], '')
-                    };
-                }
+            if (matchMimeType && this.source.startsWith('data:application/pdf;base64,')) {
+                this.source = this.source.replace(matchMimeType[0], '');
             }
 
             try {
-                atob(this.source.data || this.source);
+                this.source = {
+                    data: atob(this.source)
+                }
             } catch (e) {
                 instance.webclient.crashmanager.show_message('Unknown data format');
                 return;
             }
 
+            instance.web.blockUI();
             var self = this;
 
-            instance.web.blockUI();
-            instance.pdfJs.getDocument(self.source.data || self.source).then(function (pdf) {
+            instance.pdfJs.getDocument(this.source).then(function (pdf) {
                 self.pdf = pdf;
                 self.render_widget();
+            }).catch(function (error) {
+                instance.web.unblockUI();
+                instance.webclient.crashmanager.show_message(error);
             });
         },
         render_widget: function () {