2
0

evaluator.js 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742
  1. /* Copyright 2017 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. 'use strict';
  16. Object.defineProperty(exports, "__esModule", {
  17. value: true
  18. });
  19. exports.PartialEvaluator = undefined;
  20. var _util = require('../shared/util');
  21. var _cmap = require('./cmap');
  22. var _stream = require('./stream');
  23. var _primitives = require('./primitives');
  24. var _fonts = require('./fonts');
  25. var _encodings = require('./encodings');
  26. var _unicode = require('./unicode');
  27. var _standard_fonts = require('./standard_fonts');
  28. var _pattern = require('./pattern');
  29. var _parser = require('./parser');
  30. var _bidi = require('./bidi');
  31. var _colorspace = require('./colorspace');
  32. var _glyphlist = require('./glyphlist');
  33. var _metrics = require('./metrics');
  34. var _function = require('./function');
  35. var _murmurhash = require('./murmurhash3');
  36. var _operator_list = require('./operator_list');
  37. var _image = require('./image');
  38. var PartialEvaluator = function PartialEvaluatorClosure() {
  39. var DefaultPartialEvaluatorOptions = {
  40. forceDataSchema: false,
  41. maxImageSize: -1,
  42. disableFontFace: false,
  43. nativeImageDecoderSupport: _util.NativeImageDecoding.DECODE,
  44. ignoreErrors: false,
  45. isEvalSupported: true
  46. };
  47. function NativeImageDecoder(_ref) {
  48. var xref = _ref.xref,
  49. resources = _ref.resources,
  50. handler = _ref.handler,
  51. _ref$forceDataSchema = _ref.forceDataSchema,
  52. forceDataSchema = _ref$forceDataSchema === undefined ? false : _ref$forceDataSchema,
  53. pdfFunctionFactory = _ref.pdfFunctionFactory;
  54. this.xref = xref;
  55. this.resources = resources;
  56. this.handler = handler;
  57. this.forceDataSchema = forceDataSchema;
  58. this.pdfFunctionFactory = pdfFunctionFactory;
  59. }
  60. NativeImageDecoder.prototype = {
  61. canDecode: function canDecode(image) {
  62. return image instanceof _stream.JpegStream && NativeImageDecoder.isDecodable(image, this.xref, this.resources, this.pdfFunctionFactory);
  63. },
  64. decode: function decode(image) {
  65. var dict = image.dict;
  66. var colorSpace = dict.get('ColorSpace', 'CS');
  67. colorSpace = _colorspace.ColorSpace.parse(colorSpace, this.xref, this.resources, this.pdfFunctionFactory);
  68. var numComps = colorSpace.numComps;
  69. var decodePromise = this.handler.sendWithPromise('JpegDecode', [image.getIR(this.forceDataSchema), numComps]);
  70. return decodePromise.then(function (message) {
  71. var data = message.data;
  72. return new _stream.Stream(data, 0, data.length, image.dict);
  73. });
  74. }
  75. };
  76. NativeImageDecoder.isSupported = function (image, xref, res, pdfFunctionFactory) {
  77. var dict = image.dict;
  78. if (dict.has('DecodeParms') || dict.has('DP')) {
  79. return false;
  80. }
  81. var cs = _colorspace.ColorSpace.parse(dict.get('ColorSpace', 'CS'), xref, res, pdfFunctionFactory);
  82. return (cs.name === 'DeviceGray' || cs.name === 'DeviceRGB') && cs.isDefaultDecode(dict.getArray('Decode', 'D'));
  83. };
  84. NativeImageDecoder.isDecodable = function (image, xref, res, pdfFunctionFactory) {
  85. var dict = image.dict;
  86. if (dict.has('DecodeParms') || dict.has('DP')) {
  87. return false;
  88. }
  89. var cs = _colorspace.ColorSpace.parse(dict.get('ColorSpace', 'CS'), xref, res, pdfFunctionFactory);
  90. return (cs.numComps === 1 || cs.numComps === 3) && cs.isDefaultDecode(dict.getArray('Decode', 'D'));
  91. };
  92. function PartialEvaluator(_ref2) {
  93. var _this = this;
  94. var pdfManager = _ref2.pdfManager,
  95. xref = _ref2.xref,
  96. handler = _ref2.handler,
  97. pageIndex = _ref2.pageIndex,
  98. idFactory = _ref2.idFactory,
  99. fontCache = _ref2.fontCache,
  100. builtInCMapCache = _ref2.builtInCMapCache,
  101. _ref2$options = _ref2.options,
  102. options = _ref2$options === undefined ? null : _ref2$options,
  103. pdfFunctionFactory = _ref2.pdfFunctionFactory;
  104. this.pdfManager = pdfManager;
  105. this.xref = xref;
  106. this.handler = handler;
  107. this.pageIndex = pageIndex;
  108. this.idFactory = idFactory;
  109. this.fontCache = fontCache;
  110. this.builtInCMapCache = builtInCMapCache;
  111. this.options = options || DefaultPartialEvaluatorOptions;
  112. this.pdfFunctionFactory = pdfFunctionFactory;
  113. this.fetchBuiltInCMap = function (name) {
  114. var cachedCMap = _this.builtInCMapCache[name];
  115. if (cachedCMap) {
  116. return Promise.resolve(cachedCMap);
  117. }
  118. return _this.handler.sendWithPromise('FetchBuiltInCMap', { name: name }).then(function (data) {
  119. if (data.compressionType !== _util.CMapCompressionType.NONE) {
  120. _this.builtInCMapCache[name] = data;
  121. }
  122. return data;
  123. });
  124. };
  125. }
  126. var TIME_SLOT_DURATION_MS = 20;
  127. var CHECK_TIME_EVERY = 100;
  128. function TimeSlotManager() {
  129. this.reset();
  130. }
  131. TimeSlotManager.prototype = {
  132. check: function TimeSlotManager_check() {
  133. if (++this.checked < CHECK_TIME_EVERY) {
  134. return false;
  135. }
  136. this.checked = 0;
  137. return this.endTime <= Date.now();
  138. },
  139. reset: function TimeSlotManager_reset() {
  140. this.endTime = Date.now() + TIME_SLOT_DURATION_MS;
  141. this.checked = 0;
  142. }
  143. };
  144. function normalizeBlendMode(value) {
  145. if (!(0, _primitives.isName)(value)) {
  146. return 'source-over';
  147. }
  148. switch (value.name) {
  149. case 'Normal':
  150. case 'Compatible':
  151. return 'source-over';
  152. case 'Multiply':
  153. return 'multiply';
  154. case 'Screen':
  155. return 'screen';
  156. case 'Overlay':
  157. return 'overlay';
  158. case 'Darken':
  159. return 'darken';
  160. case 'Lighten':
  161. return 'lighten';
  162. case 'ColorDodge':
  163. return 'color-dodge';
  164. case 'ColorBurn':
  165. return 'color-burn';
  166. case 'HardLight':
  167. return 'hard-light';
  168. case 'SoftLight':
  169. return 'soft-light';
  170. case 'Difference':
  171. return 'difference';
  172. case 'Exclusion':
  173. return 'exclusion';
  174. case 'Hue':
  175. return 'hue';
  176. case 'Saturation':
  177. return 'saturation';
  178. case 'Color':
  179. return 'color';
  180. case 'Luminosity':
  181. return 'luminosity';
  182. }
  183. (0, _util.warn)('Unsupported blend mode: ' + value.name);
  184. return 'source-over';
  185. }
  186. var deferred = Promise.resolve();
  187. var TILING_PATTERN = 1,
  188. SHADING_PATTERN = 2;
  189. PartialEvaluator.prototype = {
  190. clone: function clone() {
  191. var newOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DefaultPartialEvaluatorOptions;
  192. var newEvaluator = Object.create(this);
  193. newEvaluator.options = newOptions;
  194. return newEvaluator;
  195. },
  196. hasBlendModes: function PartialEvaluator_hasBlendModes(resources) {
  197. if (!(0, _primitives.isDict)(resources)) {
  198. return false;
  199. }
  200. var processed = Object.create(null);
  201. if (resources.objId) {
  202. processed[resources.objId] = true;
  203. }
  204. var nodes = [resources],
  205. xref = this.xref;
  206. while (nodes.length) {
  207. var key, i, ii;
  208. var node = nodes.shift();
  209. var graphicStates = node.get('ExtGState');
  210. if ((0, _primitives.isDict)(graphicStates)) {
  211. var graphicStatesKeys = graphicStates.getKeys();
  212. for (i = 0, ii = graphicStatesKeys.length; i < ii; i++) {
  213. key = graphicStatesKeys[i];
  214. var graphicState = graphicStates.get(key);
  215. var bm = graphicState.get('BM');
  216. if ((0, _primitives.isName)(bm) && bm.name !== 'Normal') {
  217. return true;
  218. }
  219. }
  220. }
  221. var xObjects = node.get('XObject');
  222. if (!(0, _primitives.isDict)(xObjects)) {
  223. continue;
  224. }
  225. var xObjectsKeys = xObjects.getKeys();
  226. for (i = 0, ii = xObjectsKeys.length; i < ii; i++) {
  227. key = xObjectsKeys[i];
  228. var xObject = xObjects.getRaw(key);
  229. if ((0, _primitives.isRef)(xObject)) {
  230. if (processed[xObject.toString()]) {
  231. continue;
  232. }
  233. xObject = xref.fetch(xObject);
  234. }
  235. if (!(0, _primitives.isStream)(xObject)) {
  236. continue;
  237. }
  238. if (xObject.dict.objId) {
  239. if (processed[xObject.dict.objId]) {
  240. continue;
  241. }
  242. processed[xObject.dict.objId] = true;
  243. }
  244. var xResources = xObject.dict.get('Resources');
  245. if ((0, _primitives.isDict)(xResources) && (!xResources.objId || !processed[xResources.objId])) {
  246. nodes.push(xResources);
  247. if (xResources.objId) {
  248. processed[xResources.objId] = true;
  249. }
  250. }
  251. }
  252. }
  253. return false;
  254. },
  255. buildFormXObject: function PartialEvaluator_buildFormXObject(resources, xobj, smask, operatorList, task, initialState) {
  256. var dict = xobj.dict;
  257. var matrix = dict.getArray('Matrix');
  258. var bbox = dict.getArray('BBox');
  259. var group = dict.get('Group');
  260. if (group) {
  261. var groupOptions = {
  262. matrix: matrix,
  263. bbox: bbox,
  264. smask: smask,
  265. isolated: false,
  266. knockout: false
  267. };
  268. var groupSubtype = group.get('S');
  269. var colorSpace = null;
  270. if ((0, _primitives.isName)(groupSubtype, 'Transparency')) {
  271. groupOptions.isolated = group.get('I') || false;
  272. groupOptions.knockout = group.get('K') || false;
  273. if (group.has('CS')) {
  274. colorSpace = _colorspace.ColorSpace.parse(group.get('CS'), this.xref, resources, this.pdfFunctionFactory);
  275. }
  276. }
  277. if (smask && smask.backdrop) {
  278. colorSpace = colorSpace || _colorspace.ColorSpace.singletons.rgb;
  279. smask.backdrop = colorSpace.getRgb(smask.backdrop, 0);
  280. }
  281. operatorList.addOp(_util.OPS.beginGroup, [groupOptions]);
  282. }
  283. operatorList.addOp(_util.OPS.paintFormXObjectBegin, [matrix, bbox]);
  284. return this.getOperatorList({
  285. stream: xobj,
  286. task: task,
  287. resources: dict.get('Resources') || resources,
  288. operatorList: operatorList,
  289. initialState: initialState
  290. }).then(function () {
  291. operatorList.addOp(_util.OPS.paintFormXObjectEnd, []);
  292. if (group) {
  293. operatorList.addOp(_util.OPS.endGroup, [groupOptions]);
  294. }
  295. });
  296. },
  297. buildPaintImageXObject: function PartialEvaluator_buildPaintImageXObject(resources, image, inline, operatorList, cacheKey, imageCache) {
  298. var _this2 = this;
  299. var dict = image.dict;
  300. var w = dict.get('Width', 'W');
  301. var h = dict.get('Height', 'H');
  302. if (!(w && (0, _util.isNum)(w)) || !(h && (0, _util.isNum)(h))) {
  303. (0, _util.warn)('Image dimensions are missing, or not numbers.');
  304. return;
  305. }
  306. var maxImageSize = this.options.maxImageSize;
  307. if (maxImageSize !== -1 && w * h > maxImageSize) {
  308. (0, _util.warn)('Image exceeded maximum allowed size and was removed.');
  309. return;
  310. }
  311. var imageMask = dict.get('ImageMask', 'IM') || false;
  312. var imgData, args;
  313. if (imageMask) {
  314. var width = dict.get('Width', 'W');
  315. var height = dict.get('Height', 'H');
  316. var bitStrideLength = width + 7 >> 3;
  317. var imgArray = image.getBytes(bitStrideLength * height);
  318. var decode = dict.getArray('Decode', 'D');
  319. imgData = _image.PDFImage.createMask({
  320. imgArray: imgArray,
  321. width: width,
  322. height: height,
  323. imageIsFromDecodeStream: image instanceof _stream.DecodeStream,
  324. inverseDecode: !!decode && decode[0] > 0
  325. });
  326. imgData.cached = true;
  327. args = [imgData];
  328. operatorList.addOp(_util.OPS.paintImageMaskXObject, args);
  329. if (cacheKey) {
  330. imageCache[cacheKey] = {
  331. fn: _util.OPS.paintImageMaskXObject,
  332. args: args
  333. };
  334. }
  335. return;
  336. }
  337. var softMask = dict.get('SMask', 'SM') || false;
  338. var mask = dict.get('Mask') || false;
  339. var SMALL_IMAGE_DIMENSIONS = 200;
  340. if (inline && !softMask && !mask && !(image instanceof _stream.JpegStream) && w + h < SMALL_IMAGE_DIMENSIONS) {
  341. var imageObj = new _image.PDFImage({
  342. xref: this.xref,
  343. res: resources,
  344. image: image,
  345. pdfFunctionFactory: this.pdfFunctionFactory
  346. });
  347. imgData = imageObj.createImageData(true);
  348. operatorList.addOp(_util.OPS.paintInlineImageXObject, [imgData]);
  349. return;
  350. }
  351. var nativeImageDecoderSupport = this.options.nativeImageDecoderSupport;
  352. var objId = 'img_' + this.idFactory.createObjId();
  353. operatorList.addDependency(objId);
  354. args = [objId, w, h];
  355. if (nativeImageDecoderSupport !== _util.NativeImageDecoding.NONE && !softMask && !mask && image instanceof _stream.JpegStream && NativeImageDecoder.isSupported(image, this.xref, resources, this.pdfFunctionFactory)) {
  356. operatorList.addOp(_util.OPS.paintJpegXObject, args);
  357. this.handler.send('obj', [objId, this.pageIndex, 'JpegStream', image.getIR(this.options.forceDataSchema)]);
  358. if (cacheKey) {
  359. imageCache[cacheKey] = {
  360. fn: _util.OPS.paintJpegXObject,
  361. args: args
  362. };
  363. }
  364. return;
  365. }
  366. var nativeImageDecoder = null;
  367. if (nativeImageDecoderSupport === _util.NativeImageDecoding.DECODE && (image instanceof _stream.JpegStream || mask instanceof _stream.JpegStream || softMask instanceof _stream.JpegStream)) {
  368. nativeImageDecoder = new NativeImageDecoder({
  369. xref: this.xref,
  370. resources: resources,
  371. handler: this.handler,
  372. forceDataSchema: this.options.forceDataSchema,
  373. pdfFunctionFactory: this.pdfFunctionFactory
  374. });
  375. }
  376. _image.PDFImage.buildImage({
  377. handler: this.handler,
  378. xref: this.xref,
  379. res: resources,
  380. image: image,
  381. nativeDecoder: nativeImageDecoder,
  382. pdfFunctionFactory: this.pdfFunctionFactory
  383. }).then(function (imageObj) {
  384. var imgData = imageObj.createImageData(false);
  385. _this2.handler.send('obj', [objId, _this2.pageIndex, 'Image', imgData], [imgData.data.buffer]);
  386. }).catch(function (reason) {
  387. (0, _util.warn)('Unable to decode image: ' + reason);
  388. _this2.handler.send('obj', [objId, _this2.pageIndex, 'Image', null]);
  389. });
  390. operatorList.addOp(_util.OPS.paintImageXObject, args);
  391. if (cacheKey) {
  392. imageCache[cacheKey] = {
  393. fn: _util.OPS.paintImageXObject,
  394. args: args
  395. };
  396. }
  397. },
  398. handleSMask: function PartialEvaluator_handleSmask(smask, resources, operatorList, task, stateManager) {
  399. var smaskContent = smask.get('G');
  400. var smaskOptions = {
  401. subtype: smask.get('S').name,
  402. backdrop: smask.get('BC')
  403. };
  404. var transferObj = smask.get('TR');
  405. if ((0, _function.isPDFFunction)(transferObj)) {
  406. var transferFn = this.pdfFunctionFactory.create(transferObj);
  407. var transferMap = new Uint8Array(256);
  408. var tmp = new Float32Array(1);
  409. for (var i = 0; i < 256; i++) {
  410. tmp[0] = i / 255;
  411. transferFn(tmp, 0, tmp, 0);
  412. transferMap[i] = tmp[0] * 255 | 0;
  413. }
  414. smaskOptions.transferMap = transferMap;
  415. }
  416. return this.buildFormXObject(resources, smaskContent, smaskOptions, operatorList, task, stateManager.state.clone());
  417. },
  418. handleTilingType: function handleTilingType(fn, args, resources, pattern, patternDict, operatorList, task) {
  419. var _this3 = this;
  420. var tilingOpList = new _operator_list.OperatorList();
  421. var resourcesArray = [patternDict.get('Resources'), resources];
  422. var patternResources = _primitives.Dict.merge(this.xref, resourcesArray);
  423. return this.getOperatorList({
  424. stream: pattern,
  425. task: task,
  426. resources: patternResources,
  427. operatorList: tilingOpList
  428. }).then(function () {
  429. return (0, _pattern.getTilingPatternIR)({
  430. fnArray: tilingOpList.fnArray,
  431. argsArray: tilingOpList.argsArray
  432. }, patternDict, args);
  433. }).then(function (tilingPatternIR) {
  434. operatorList.addDependencies(tilingOpList.dependencies);
  435. operatorList.addOp(fn, tilingPatternIR);
  436. }, function (reason) {
  437. if (_this3.options.ignoreErrors) {
  438. _this3.handler.send('UnsupportedFeature', { featureId: _util.UNSUPPORTED_FEATURES.unknown });
  439. (0, _util.warn)('handleTilingType - ignoring pattern: "' + reason + '".');
  440. return;
  441. }
  442. throw reason;
  443. });
  444. },
  445. handleSetFont: function PartialEvaluator_handleSetFont(resources, fontArgs, fontRef, operatorList, task, state) {
  446. var _this4 = this;
  447. var fontName;
  448. if (fontArgs) {
  449. fontArgs = fontArgs.slice();
  450. fontName = fontArgs[0].name;
  451. }
  452. return this.loadFont(fontName, fontRef, resources).then(function (translated) {
  453. if (!translated.font.isType3Font) {
  454. return translated;
  455. }
  456. return translated.loadType3Data(_this4, resources, operatorList, task).then(function () {
  457. return translated;
  458. }).catch(function (reason) {
  459. _this4.handler.send('UnsupportedFeature', { featureId: _util.UNSUPPORTED_FEATURES.font });
  460. return new TranslatedFont('g_font_error', new _fonts.ErrorFont('Type3 font load error: ' + reason), translated.font);
  461. });
  462. }).then(function (translated) {
  463. state.font = translated.font;
  464. translated.send(_this4.handler);
  465. return translated.loadedName;
  466. });
  467. },
  468. handleText: function PartialEvaluator_handleText(chars, state) {
  469. var _this5 = this;
  470. var font = state.font;
  471. var glyphs = font.charsToGlyphs(chars);
  472. var isAddToPathSet = !!(state.textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
  473. if (font.data && (isAddToPathSet || this.options.disableFontFace)) {
  474. var buildPath = function buildPath(fontChar) {
  475. if (!font.renderer.hasBuiltPath(fontChar)) {
  476. var path = font.renderer.getPathJs(fontChar);
  477. _this5.handler.send('commonobj', [font.loadedName + '_path_' + fontChar, 'FontPath', path]);
  478. }
  479. };
  480. for (var i = 0, ii = glyphs.length; i < ii; i++) {
  481. var glyph = glyphs[i];
  482. buildPath(glyph.fontChar);
  483. var accent = glyph.accent;
  484. if (accent && accent.fontChar) {
  485. buildPath(accent.fontChar);
  486. }
  487. }
  488. }
  489. return glyphs;
  490. },
  491. setGState: function PartialEvaluator_setGState(resources, gState, operatorList, task, stateManager) {
  492. var _this6 = this;
  493. var gStateObj = [];
  494. var gStateKeys = gState.getKeys();
  495. var promise = Promise.resolve();
  496. var _loop = function _loop() {
  497. var key = gStateKeys[i];
  498. var value = gState.get(key);
  499. switch (key) {
  500. case 'Type':
  501. break;
  502. case 'LW':
  503. case 'LC':
  504. case 'LJ':
  505. case 'ML':
  506. case 'D':
  507. case 'RI':
  508. case 'FL':
  509. case 'CA':
  510. case 'ca':
  511. gStateObj.push([key, value]);
  512. break;
  513. case 'Font':
  514. promise = promise.then(function () {
  515. return _this6.handleSetFont(resources, null, value[0], operatorList, task, stateManager.state).then(function (loadedName) {
  516. operatorList.addDependency(loadedName);
  517. gStateObj.push([key, [loadedName, value[1]]]);
  518. });
  519. });
  520. break;
  521. case 'BM':
  522. gStateObj.push([key, normalizeBlendMode(value)]);
  523. break;
  524. case 'SMask':
  525. if ((0, _primitives.isName)(value, 'None')) {
  526. gStateObj.push([key, false]);
  527. break;
  528. }
  529. if ((0, _primitives.isDict)(value)) {
  530. promise = promise.then(function () {
  531. return _this6.handleSMask(value, resources, operatorList, task, stateManager);
  532. });
  533. gStateObj.push([key, true]);
  534. } else {
  535. (0, _util.warn)('Unsupported SMask type');
  536. }
  537. break;
  538. case 'OP':
  539. case 'op':
  540. case 'OPM':
  541. case 'BG':
  542. case 'BG2':
  543. case 'UCR':
  544. case 'UCR2':
  545. case 'TR':
  546. case 'TR2':
  547. case 'HT':
  548. case 'SM':
  549. case 'SA':
  550. case 'AIS':
  551. case 'TK':
  552. (0, _util.info)('graphic state operator ' + key);
  553. break;
  554. default:
  555. (0, _util.info)('Unknown graphic state operator ' + key);
  556. break;
  557. }
  558. };
  559. for (var i = 0, ii = gStateKeys.length; i < ii; i++) {
  560. _loop();
  561. }
  562. return promise.then(function () {
  563. if (gStateObj.length > 0) {
  564. operatorList.addOp(_util.OPS.setGState, [gStateObj]);
  565. }
  566. });
  567. },
  568. loadFont: function PartialEvaluator_loadFont(fontName, font, resources) {
  569. var _this7 = this;
  570. function errorFont() {
  571. return Promise.resolve(new TranslatedFont('g_font_error', new _fonts.ErrorFont('Font ' + fontName + ' is not available'), font));
  572. }
  573. var fontRef,
  574. xref = this.xref;
  575. if (font) {
  576. if (!(0, _primitives.isRef)(font)) {
  577. throw new Error('The "font" object should be a reference.');
  578. }
  579. fontRef = font;
  580. } else {
  581. var fontRes = resources.get('Font');
  582. if (fontRes) {
  583. fontRef = fontRes.getRaw(fontName);
  584. } else {
  585. (0, _util.warn)('fontRes not available');
  586. return errorFont();
  587. }
  588. }
  589. if (!fontRef) {
  590. (0, _util.warn)('fontRef not available');
  591. return errorFont();
  592. }
  593. if (this.fontCache.has(fontRef)) {
  594. return this.fontCache.get(fontRef);
  595. }
  596. font = xref.fetchIfRef(fontRef);
  597. if (!(0, _primitives.isDict)(font)) {
  598. return errorFont();
  599. }
  600. if (font.translated) {
  601. return font.translated;
  602. }
  603. var fontCapability = (0, _util.createPromiseCapability)();
  604. var preEvaluatedFont = this.preEvaluateFont(font);
  605. var descriptor = preEvaluatedFont.descriptor;
  606. var fontRefIsRef = (0, _primitives.isRef)(fontRef),
  607. fontID;
  608. if (fontRefIsRef) {
  609. fontID = fontRef.toString();
  610. }
  611. if ((0, _primitives.isDict)(descriptor)) {
  612. if (!descriptor.fontAliases) {
  613. descriptor.fontAliases = Object.create(null);
  614. }
  615. var fontAliases = descriptor.fontAliases;
  616. var hash = preEvaluatedFont.hash;
  617. if (fontAliases[hash]) {
  618. var aliasFontRef = fontAliases[hash].aliasRef;
  619. if (fontRefIsRef && aliasFontRef && this.fontCache.has(aliasFontRef)) {
  620. this.fontCache.putAlias(fontRef, aliasFontRef);
  621. return this.fontCache.get(fontRef);
  622. }
  623. } else {
  624. fontAliases[hash] = { fontID: _fonts.Font.getFontID() };
  625. }
  626. if (fontRefIsRef) {
  627. fontAliases[hash].aliasRef = fontRef;
  628. }
  629. fontID = fontAliases[hash].fontID;
  630. }
  631. if (fontRefIsRef) {
  632. this.fontCache.put(fontRef, fontCapability.promise);
  633. } else {
  634. if (!fontID) {
  635. fontID = this.idFactory.createObjId();
  636. }
  637. this.fontCache.put('id_' + fontID, fontCapability.promise);
  638. }
  639. (0, _util.assert)(fontID, 'The "fontID" must be defined.');
  640. font.loadedName = 'g_' + this.pdfManager.docId + '_f' + fontID;
  641. font.translated = fontCapability.promise;
  642. var translatedPromise;
  643. try {
  644. translatedPromise = this.translateFont(preEvaluatedFont);
  645. } catch (e) {
  646. translatedPromise = Promise.reject(e);
  647. }
  648. translatedPromise.then(function (translatedFont) {
  649. if (translatedFont.fontType !== undefined) {
  650. var xrefFontStats = xref.stats.fontTypes;
  651. xrefFontStats[translatedFont.fontType] = true;
  652. }
  653. fontCapability.resolve(new TranslatedFont(font.loadedName, translatedFont, font));
  654. }).catch(function (reason) {
  655. _this7.handler.send('UnsupportedFeature', { featureId: _util.UNSUPPORTED_FEATURES.font });
  656. try {
  657. var descriptor = preEvaluatedFont.descriptor;
  658. var fontFile3 = descriptor && descriptor.get('FontFile3');
  659. var subtype = fontFile3 && fontFile3.get('Subtype');
  660. var fontType = (0, _fonts.getFontType)(preEvaluatedFont.type, subtype && subtype.name);
  661. var xrefFontStats = xref.stats.fontTypes;
  662. xrefFontStats[fontType] = true;
  663. } catch (ex) {}
  664. fontCapability.resolve(new TranslatedFont(font.loadedName, new _fonts.ErrorFont(reason instanceof Error ? reason.message : reason), font));
  665. });
  666. return fontCapability.promise;
  667. },
  668. buildPath: function PartialEvaluator_buildPath(operatorList, fn, args) {
  669. var lastIndex = operatorList.length - 1;
  670. if (!args) {
  671. args = [];
  672. }
  673. if (lastIndex < 0 || operatorList.fnArray[lastIndex] !== _util.OPS.constructPath) {
  674. operatorList.addOp(_util.OPS.constructPath, [[fn], args]);
  675. } else {
  676. var opArgs = operatorList.argsArray[lastIndex];
  677. opArgs[0].push(fn);
  678. Array.prototype.push.apply(opArgs[1], args);
  679. }
  680. },
  681. handleColorN: function PartialEvaluator_handleColorN(operatorList, fn, args, cs, patterns, resources, task) {
  682. var patternName = args[args.length - 1];
  683. var pattern;
  684. if ((0, _primitives.isName)(patternName) && (pattern = patterns.get(patternName.name))) {
  685. var dict = (0, _primitives.isStream)(pattern) ? pattern.dict : pattern;
  686. var typeNum = dict.get('PatternType');
  687. if (typeNum === TILING_PATTERN) {
  688. var color = cs.base ? cs.base.getRgb(args, 0) : null;
  689. return this.handleTilingType(fn, color, resources, pattern, dict, operatorList, task);
  690. } else if (typeNum === SHADING_PATTERN) {
  691. var shading = dict.get('Shading');
  692. var matrix = dict.getArray('Matrix');
  693. pattern = _pattern.Pattern.parseShading(shading, matrix, this.xref, resources, this.handler, this.pdfFunctionFactory);
  694. operatorList.addOp(fn, pattern.getIR());
  695. return Promise.resolve();
  696. }
  697. return Promise.reject(new Error('Unknown PatternType: ' + typeNum));
  698. }
  699. operatorList.addOp(fn, args);
  700. return Promise.resolve();
  701. },
  702. getOperatorList: function getOperatorList(_ref3) {
  703. var _this8 = this;
  704. var stream = _ref3.stream,
  705. task = _ref3.task,
  706. resources = _ref3.resources,
  707. operatorList = _ref3.operatorList,
  708. _ref3$initialState = _ref3.initialState,
  709. initialState = _ref3$initialState === undefined ? null : _ref3$initialState;
  710. resources = resources || _primitives.Dict.empty;
  711. initialState = initialState || new EvalState();
  712. if (!operatorList) {
  713. throw new Error('getOperatorList: missing "operatorList" parameter');
  714. }
  715. var self = this;
  716. var xref = this.xref;
  717. var imageCache = Object.create(null);
  718. var xobjs = resources.get('XObject') || _primitives.Dict.empty;
  719. var patterns = resources.get('Pattern') || _primitives.Dict.empty;
  720. var stateManager = new StateManager(initialState);
  721. var preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);
  722. var timeSlotManager = new TimeSlotManager();
  723. function closePendingRestoreOPS(argument) {
  724. for (var i = 0, ii = preprocessor.savedStatesDepth; i < ii; i++) {
  725. operatorList.addOp(_util.OPS.restore, []);
  726. }
  727. }
  728. return new Promise(function promiseBody(resolve, reject) {
  729. var next = function next(promise) {
  730. promise.then(function () {
  731. try {
  732. promiseBody(resolve, reject);
  733. } catch (ex) {
  734. reject(ex);
  735. }
  736. }, reject);
  737. };
  738. task.ensureNotTerminated();
  739. timeSlotManager.reset();
  740. var stop,
  741. operation = {},
  742. i,
  743. ii,
  744. cs;
  745. while (!(stop = timeSlotManager.check())) {
  746. operation.args = null;
  747. if (!preprocessor.read(operation)) {
  748. break;
  749. }
  750. var args = operation.args;
  751. var fn = operation.fn;
  752. switch (fn | 0) {
  753. case _util.OPS.paintXObject:
  754. var name = args[0].name;
  755. if (name && imageCache[name] !== undefined) {
  756. operatorList.addOp(imageCache[name].fn, imageCache[name].args);
  757. args = null;
  758. continue;
  759. }
  760. next(new Promise(function (resolveXObject, rejectXObject) {
  761. if (!name) {
  762. throw new _util.FormatError('XObject must be referred to by name.');
  763. }
  764. var xobj = xobjs.get(name);
  765. if (!xobj) {
  766. operatorList.addOp(fn, args);
  767. resolveXObject();
  768. return;
  769. }
  770. if (!(0, _primitives.isStream)(xobj)) {
  771. throw new _util.FormatError('XObject should be a stream');
  772. }
  773. var type = xobj.dict.get('Subtype');
  774. if (!(0, _primitives.isName)(type)) {
  775. throw new _util.FormatError('XObject should have a Name subtype');
  776. }
  777. if (type.name === 'Form') {
  778. stateManager.save();
  779. self.buildFormXObject(resources, xobj, null, operatorList, task, stateManager.state.clone()).then(function () {
  780. stateManager.restore();
  781. resolveXObject();
  782. }, rejectXObject);
  783. return;
  784. } else if (type.name === 'Image') {
  785. self.buildPaintImageXObject(resources, xobj, false, operatorList, name, imageCache);
  786. } else if (type.name === 'PS') {
  787. (0, _util.info)('Ignored XObject subtype PS');
  788. } else {
  789. throw new _util.FormatError('Unhandled XObject subtype ' + type.name);
  790. }
  791. resolveXObject();
  792. }).catch(function (reason) {
  793. if (self.options.ignoreErrors) {
  794. self.handler.send('UnsupportedFeature', { featureId: _util.UNSUPPORTED_FEATURES.unknown });
  795. (0, _util.warn)('getOperatorList - ignoring XObject: "' + reason + '".');
  796. return;
  797. }
  798. throw reason;
  799. }));
  800. return;
  801. case _util.OPS.setFont:
  802. var fontSize = args[1];
  803. next(self.handleSetFont(resources, args, null, operatorList, task, stateManager.state).then(function (loadedName) {
  804. operatorList.addDependency(loadedName);
  805. operatorList.addOp(_util.OPS.setFont, [loadedName, fontSize]);
  806. }));
  807. return;
  808. case _util.OPS.endInlineImage:
  809. var cacheKey = args[0].cacheKey;
  810. if (cacheKey) {
  811. var cacheEntry = imageCache[cacheKey];
  812. if (cacheEntry !== undefined) {
  813. operatorList.addOp(cacheEntry.fn, cacheEntry.args);
  814. args = null;
  815. continue;
  816. }
  817. }
  818. self.buildPaintImageXObject(resources, args[0], true, operatorList, cacheKey, imageCache);
  819. args = null;
  820. continue;
  821. case _util.OPS.showText:
  822. args[0] = self.handleText(args[0], stateManager.state);
  823. break;
  824. case _util.OPS.showSpacedText:
  825. var arr = args[0];
  826. var combinedGlyphs = [];
  827. var arrLength = arr.length;
  828. var state = stateManager.state;
  829. for (i = 0; i < arrLength; ++i) {
  830. var arrItem = arr[i];
  831. if ((0, _util.isString)(arrItem)) {
  832. Array.prototype.push.apply(combinedGlyphs, self.handleText(arrItem, state));
  833. } else if ((0, _util.isNum)(arrItem)) {
  834. combinedGlyphs.push(arrItem);
  835. }
  836. }
  837. args[0] = combinedGlyphs;
  838. fn = _util.OPS.showText;
  839. break;
  840. case _util.OPS.nextLineShowText:
  841. operatorList.addOp(_util.OPS.nextLine);
  842. args[0] = self.handleText(args[0], stateManager.state);
  843. fn = _util.OPS.showText;
  844. break;
  845. case _util.OPS.nextLineSetSpacingShowText:
  846. operatorList.addOp(_util.OPS.nextLine);
  847. operatorList.addOp(_util.OPS.setWordSpacing, [args.shift()]);
  848. operatorList.addOp(_util.OPS.setCharSpacing, [args.shift()]);
  849. args[0] = self.handleText(args[0], stateManager.state);
  850. fn = _util.OPS.showText;
  851. break;
  852. case _util.OPS.setTextRenderingMode:
  853. stateManager.state.textRenderingMode = args[0];
  854. break;
  855. case _util.OPS.setFillColorSpace:
  856. stateManager.state.fillColorSpace = _colorspace.ColorSpace.parse(args[0], xref, resources, self.pdfFunctionFactory);
  857. continue;
  858. case _util.OPS.setStrokeColorSpace:
  859. stateManager.state.strokeColorSpace = _colorspace.ColorSpace.parse(args[0], xref, resources, self.pdfFunctionFactory);
  860. continue;
  861. case _util.OPS.setFillColor:
  862. cs = stateManager.state.fillColorSpace;
  863. args = cs.getRgb(args, 0);
  864. fn = _util.OPS.setFillRGBColor;
  865. break;
  866. case _util.OPS.setStrokeColor:
  867. cs = stateManager.state.strokeColorSpace;
  868. args = cs.getRgb(args, 0);
  869. fn = _util.OPS.setStrokeRGBColor;
  870. break;
  871. case _util.OPS.setFillGray:
  872. stateManager.state.fillColorSpace = _colorspace.ColorSpace.singletons.gray;
  873. args = _colorspace.ColorSpace.singletons.gray.getRgb(args, 0);
  874. fn = _util.OPS.setFillRGBColor;
  875. break;
  876. case _util.OPS.setStrokeGray:
  877. stateManager.state.strokeColorSpace = _colorspace.ColorSpace.singletons.gray;
  878. args = _colorspace.ColorSpace.singletons.gray.getRgb(args, 0);
  879. fn = _util.OPS.setStrokeRGBColor;
  880. break;
  881. case _util.OPS.setFillCMYKColor:
  882. stateManager.state.fillColorSpace = _colorspace.ColorSpace.singletons.cmyk;
  883. args = _colorspace.ColorSpace.singletons.cmyk.getRgb(args, 0);
  884. fn = _util.OPS.setFillRGBColor;
  885. break;
  886. case _util.OPS.setStrokeCMYKColor:
  887. stateManager.state.strokeColorSpace = _colorspace.ColorSpace.singletons.cmyk;
  888. args = _colorspace.ColorSpace.singletons.cmyk.getRgb(args, 0);
  889. fn = _util.OPS.setStrokeRGBColor;
  890. break;
  891. case _util.OPS.setFillRGBColor:
  892. stateManager.state.fillColorSpace = _colorspace.ColorSpace.singletons.rgb;
  893. args = _colorspace.ColorSpace.singletons.rgb.getRgb(args, 0);
  894. break;
  895. case _util.OPS.setStrokeRGBColor:
  896. stateManager.state.strokeColorSpace = _colorspace.ColorSpace.singletons.rgb;
  897. args = _colorspace.ColorSpace.singletons.rgb.getRgb(args, 0);
  898. break;
  899. case _util.OPS.setFillColorN:
  900. cs = stateManager.state.fillColorSpace;
  901. if (cs.name === 'Pattern') {
  902. next(self.handleColorN(operatorList, _util.OPS.setFillColorN, args, cs, patterns, resources, task));
  903. return;
  904. }
  905. args = cs.getRgb(args, 0);
  906. fn = _util.OPS.setFillRGBColor;
  907. break;
  908. case _util.OPS.setStrokeColorN:
  909. cs = stateManager.state.strokeColorSpace;
  910. if (cs.name === 'Pattern') {
  911. next(self.handleColorN(operatorList, _util.OPS.setStrokeColorN, args, cs, patterns, resources, task));
  912. return;
  913. }
  914. args = cs.getRgb(args, 0);
  915. fn = _util.OPS.setStrokeRGBColor;
  916. break;
  917. case _util.OPS.shadingFill:
  918. var shadingRes = resources.get('Shading');
  919. if (!shadingRes) {
  920. throw new _util.FormatError('No shading resource found');
  921. }
  922. var shading = shadingRes.get(args[0].name);
  923. if (!shading) {
  924. throw new _util.FormatError('No shading object found');
  925. }
  926. var shadingFill = _pattern.Pattern.parseShading(shading, null, xref, resources, self.handler, self.pdfFunctionFactory);
  927. var patternIR = shadingFill.getIR();
  928. args = [patternIR];
  929. fn = _util.OPS.shadingFill;
  930. break;
  931. case _util.OPS.setGState:
  932. var dictName = args[0];
  933. var extGState = resources.get('ExtGState');
  934. if (!(0, _primitives.isDict)(extGState) || !extGState.has(dictName.name)) {
  935. break;
  936. }
  937. var gState = extGState.get(dictName.name);
  938. next(self.setGState(resources, gState, operatorList, task, stateManager));
  939. return;
  940. case _util.OPS.moveTo:
  941. case _util.OPS.lineTo:
  942. case _util.OPS.curveTo:
  943. case _util.OPS.curveTo2:
  944. case _util.OPS.curveTo3:
  945. case _util.OPS.closePath:
  946. self.buildPath(operatorList, fn, args);
  947. continue;
  948. case _util.OPS.rectangle:
  949. self.buildPath(operatorList, fn, args);
  950. continue;
  951. case _util.OPS.markPoint:
  952. case _util.OPS.markPointProps:
  953. case _util.OPS.beginMarkedContent:
  954. case _util.OPS.beginMarkedContentProps:
  955. case _util.OPS.endMarkedContent:
  956. case _util.OPS.beginCompat:
  957. case _util.OPS.endCompat:
  958. continue;
  959. default:
  960. if (args !== null) {
  961. for (i = 0, ii = args.length; i < ii; i++) {
  962. if (args[i] instanceof _primitives.Dict) {
  963. break;
  964. }
  965. }
  966. if (i < ii) {
  967. (0, _util.warn)('getOperatorList - ignoring operator: ' + fn);
  968. continue;
  969. }
  970. }
  971. }
  972. operatorList.addOp(fn, args);
  973. }
  974. if (stop) {
  975. next(deferred);
  976. return;
  977. }
  978. closePendingRestoreOPS();
  979. resolve();
  980. }).catch(function (reason) {
  981. if (_this8.options.ignoreErrors) {
  982. _this8.handler.send('UnsupportedFeature', { featureId: _util.UNSUPPORTED_FEATURES.unknown });
  983. (0, _util.warn)('getOperatorList - ignoring errors during task: ' + task.name);
  984. closePendingRestoreOPS();
  985. return;
  986. }
  987. throw reason;
  988. });
  989. },
  990. getTextContent: function getTextContent(_ref4) {
  991. var _this9 = this;
  992. var stream = _ref4.stream,
  993. task = _ref4.task,
  994. resources = _ref4.resources,
  995. _ref4$stateManager = _ref4.stateManager,
  996. stateManager = _ref4$stateManager === undefined ? null : _ref4$stateManager,
  997. _ref4$normalizeWhites = _ref4.normalizeWhitespace,
  998. normalizeWhitespace = _ref4$normalizeWhites === undefined ? false : _ref4$normalizeWhites,
  999. _ref4$combineTextItem = _ref4.combineTextItems,
  1000. combineTextItems = _ref4$combineTextItem === undefined ? false : _ref4$combineTextItem,
  1001. sink = _ref4.sink,
  1002. _ref4$seenStyles = _ref4.seenStyles,
  1003. seenStyles = _ref4$seenStyles === undefined ? Object.create(null) : _ref4$seenStyles;
  1004. resources = resources || _primitives.Dict.empty;
  1005. stateManager = stateManager || new StateManager(new TextState());
  1006. var WhitespaceRegexp = /\s/g;
  1007. var textContent = {
  1008. items: [],
  1009. styles: Object.create(null)
  1010. };
  1011. var textContentItem = {
  1012. initialized: false,
  1013. str: [],
  1014. width: 0,
  1015. height: 0,
  1016. vertical: false,
  1017. lastAdvanceWidth: 0,
  1018. lastAdvanceHeight: 0,
  1019. textAdvanceScale: 0,
  1020. spaceWidth: 0,
  1021. fakeSpaceMin: Infinity,
  1022. fakeMultiSpaceMin: Infinity,
  1023. fakeMultiSpaceMax: -0,
  1024. textRunBreakAllowed: false,
  1025. transform: null,
  1026. fontName: null
  1027. };
  1028. var SPACE_FACTOR = 0.3;
  1029. var MULTI_SPACE_FACTOR = 1.5;
  1030. var MULTI_SPACE_FACTOR_MAX = 4;
  1031. var self = this;
  1032. var xref = this.xref;
  1033. var xobjs = null;
  1034. var skipEmptyXObjs = Object.create(null);
  1035. var preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);
  1036. var textState;
  1037. function ensureTextContentItem() {
  1038. if (textContentItem.initialized) {
  1039. return textContentItem;
  1040. }
  1041. var font = textState.font;
  1042. if (!(font.loadedName in seenStyles)) {
  1043. seenStyles[font.loadedName] = true;
  1044. textContent.styles[font.loadedName] = {
  1045. fontFamily: font.fallbackName,
  1046. ascent: font.ascent,
  1047. descent: font.descent,
  1048. vertical: font.vertical
  1049. };
  1050. }
  1051. textContentItem.fontName = font.loadedName;
  1052. var tsm = [textState.fontSize * textState.textHScale, 0, 0, textState.fontSize, 0, textState.textRise];
  1053. if (font.isType3Font && textState.fontMatrix !== _util.FONT_IDENTITY_MATRIX && textState.fontSize === 1) {
  1054. var glyphHeight = font.bbox[3] - font.bbox[1];
  1055. if (glyphHeight > 0) {
  1056. glyphHeight = glyphHeight * textState.fontMatrix[3];
  1057. tsm[3] *= glyphHeight;
  1058. }
  1059. }
  1060. var trm = _util.Util.transform(textState.ctm, _util.Util.transform(textState.textMatrix, tsm));
  1061. textContentItem.transform = trm;
  1062. if (!font.vertical) {
  1063. textContentItem.width = 0;
  1064. textContentItem.height = Math.sqrt(trm[2] * trm[2] + trm[3] * trm[3]);
  1065. textContentItem.vertical = false;
  1066. } else {
  1067. textContentItem.width = Math.sqrt(trm[0] * trm[0] + trm[1] * trm[1]);
  1068. textContentItem.height = 0;
  1069. textContentItem.vertical = true;
  1070. }
  1071. var a = textState.textLineMatrix[0];
  1072. var b = textState.textLineMatrix[1];
  1073. var scaleLineX = Math.sqrt(a * a + b * b);
  1074. a = textState.ctm[0];
  1075. b = textState.ctm[1];
  1076. var scaleCtmX = Math.sqrt(a * a + b * b);
  1077. textContentItem.textAdvanceScale = scaleCtmX * scaleLineX;
  1078. textContentItem.lastAdvanceWidth = 0;
  1079. textContentItem.lastAdvanceHeight = 0;
  1080. var spaceWidth = font.spaceWidth / 1000 * textState.fontSize;
  1081. if (spaceWidth) {
  1082. textContentItem.spaceWidth = spaceWidth;
  1083. textContentItem.fakeSpaceMin = spaceWidth * SPACE_FACTOR;
  1084. textContentItem.fakeMultiSpaceMin = spaceWidth * MULTI_SPACE_FACTOR;
  1085. textContentItem.fakeMultiSpaceMax = spaceWidth * MULTI_SPACE_FACTOR_MAX;
  1086. textContentItem.textRunBreakAllowed = !font.isMonospace;
  1087. } else {
  1088. textContentItem.spaceWidth = 0;
  1089. textContentItem.fakeSpaceMin = Infinity;
  1090. textContentItem.fakeMultiSpaceMin = Infinity;
  1091. textContentItem.fakeMultiSpaceMax = 0;
  1092. textContentItem.textRunBreakAllowed = false;
  1093. }
  1094. textContentItem.initialized = true;
  1095. return textContentItem;
  1096. }
  1097. function replaceWhitespace(str) {
  1098. var i = 0,
  1099. ii = str.length,
  1100. code;
  1101. while (i < ii && (code = str.charCodeAt(i)) >= 0x20 && code <= 0x7F) {
  1102. i++;
  1103. }
  1104. return i < ii ? str.replace(WhitespaceRegexp, ' ') : str;
  1105. }
  1106. function runBidiTransform(textChunk) {
  1107. var str = textChunk.str.join('');
  1108. var bidiResult = (0, _bidi.bidi)(str, -1, textChunk.vertical);
  1109. return {
  1110. str: normalizeWhitespace ? replaceWhitespace(bidiResult.str) : bidiResult.str,
  1111. dir: bidiResult.dir,
  1112. width: textChunk.width,
  1113. height: textChunk.height,
  1114. transform: textChunk.transform,
  1115. fontName: textChunk.fontName
  1116. };
  1117. }
  1118. function handleSetFont(fontName, fontRef) {
  1119. return self.loadFont(fontName, fontRef, resources).then(function (translated) {
  1120. textState.font = translated.font;
  1121. textState.fontMatrix = translated.font.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  1122. });
  1123. }
  1124. function buildTextContentItem(chars) {
  1125. var font = textState.font;
  1126. var textChunk = ensureTextContentItem();
  1127. var width = 0;
  1128. var height = 0;
  1129. var glyphs = font.charsToGlyphs(chars);
  1130. for (var i = 0; i < glyphs.length; i++) {
  1131. var glyph = glyphs[i];
  1132. var glyphWidth = null;
  1133. if (font.vertical && glyph.vmetric) {
  1134. glyphWidth = glyph.vmetric[0];
  1135. } else {
  1136. glyphWidth = glyph.width;
  1137. }
  1138. var glyphUnicode = glyph.unicode;
  1139. var NormalizedUnicodes = (0, _unicode.getNormalizedUnicodes)();
  1140. if (NormalizedUnicodes[glyphUnicode] !== undefined) {
  1141. glyphUnicode = NormalizedUnicodes[glyphUnicode];
  1142. }
  1143. glyphUnicode = (0, _unicode.reverseIfRtl)(glyphUnicode);
  1144. var charSpacing = textState.charSpacing;
  1145. if (glyph.isSpace) {
  1146. var wordSpacing = textState.wordSpacing;
  1147. charSpacing += wordSpacing;
  1148. if (wordSpacing > 0) {
  1149. addFakeSpaces(wordSpacing, textChunk.str);
  1150. }
  1151. }
  1152. var tx = 0;
  1153. var ty = 0;
  1154. if (!font.vertical) {
  1155. var w0 = glyphWidth * textState.fontMatrix[0];
  1156. tx = (w0 * textState.fontSize + charSpacing) * textState.textHScale;
  1157. width += tx;
  1158. } else {
  1159. var w1 = glyphWidth * textState.fontMatrix[0];
  1160. ty = w1 * textState.fontSize + charSpacing;
  1161. height += ty;
  1162. }
  1163. textState.translateTextMatrix(tx, ty);
  1164. textChunk.str.push(glyphUnicode);
  1165. }
  1166. if (!font.vertical) {
  1167. textChunk.lastAdvanceWidth = width;
  1168. textChunk.width += width;
  1169. } else {
  1170. textChunk.lastAdvanceHeight = height;
  1171. textChunk.height += Math.abs(height);
  1172. }
  1173. return textChunk;
  1174. }
  1175. function addFakeSpaces(width, strBuf) {
  1176. if (width < textContentItem.fakeSpaceMin) {
  1177. return;
  1178. }
  1179. if (width < textContentItem.fakeMultiSpaceMin) {
  1180. strBuf.push(' ');
  1181. return;
  1182. }
  1183. var fakeSpaces = Math.round(width / textContentItem.spaceWidth);
  1184. while (fakeSpaces-- > 0) {
  1185. strBuf.push(' ');
  1186. }
  1187. }
  1188. function flushTextContentItem() {
  1189. if (!textContentItem.initialized) {
  1190. return;
  1191. }
  1192. textContentItem.width *= textContentItem.textAdvanceScale;
  1193. textContentItem.height *= textContentItem.textAdvanceScale;
  1194. textContent.items.push(runBidiTransform(textContentItem));
  1195. textContentItem.initialized = false;
  1196. textContentItem.str.length = 0;
  1197. }
  1198. function enqueueChunk() {
  1199. var length = textContent.items.length;
  1200. if (length > 0) {
  1201. sink.enqueue(textContent, length);
  1202. textContent.items = [];
  1203. textContent.styles = Object.create(null);
  1204. }
  1205. }
  1206. var timeSlotManager = new TimeSlotManager();
  1207. return new Promise(function promiseBody(resolve, reject) {
  1208. var next = function next(promise) {
  1209. enqueueChunk();
  1210. Promise.all([promise, sink.ready]).then(function () {
  1211. try {
  1212. promiseBody(resolve, reject);
  1213. } catch (ex) {
  1214. reject(ex);
  1215. }
  1216. }, reject);
  1217. };
  1218. task.ensureNotTerminated();
  1219. timeSlotManager.reset();
  1220. var stop,
  1221. operation = {},
  1222. args = [];
  1223. while (!(stop = timeSlotManager.check())) {
  1224. args.length = 0;
  1225. operation.args = args;
  1226. if (!preprocessor.read(operation)) {
  1227. break;
  1228. }
  1229. textState = stateManager.state;
  1230. var fn = operation.fn;
  1231. args = operation.args;
  1232. var advance, diff;
  1233. switch (fn | 0) {
  1234. case _util.OPS.setFont:
  1235. var fontNameArg = args[0].name,
  1236. fontSizeArg = args[1];
  1237. if (textState.font && fontNameArg === textState.fontName && fontSizeArg === textState.fontSize) {
  1238. break;
  1239. }
  1240. flushTextContentItem();
  1241. textState.fontName = fontNameArg;
  1242. textState.fontSize = fontSizeArg;
  1243. next(handleSetFont(fontNameArg, null));
  1244. return;
  1245. case _util.OPS.setTextRise:
  1246. flushTextContentItem();
  1247. textState.textRise = args[0];
  1248. break;
  1249. case _util.OPS.setHScale:
  1250. flushTextContentItem();
  1251. textState.textHScale = args[0] / 100;
  1252. break;
  1253. case _util.OPS.setLeading:
  1254. flushTextContentItem();
  1255. textState.leading = args[0];
  1256. break;
  1257. case _util.OPS.moveText:
  1258. var isSameTextLine = !textState.font ? false : (textState.font.vertical ? args[0] : args[1]) === 0;
  1259. advance = args[0] - args[1];
  1260. if (combineTextItems && isSameTextLine && textContentItem.initialized && advance > 0 && advance <= textContentItem.fakeMultiSpaceMax) {
  1261. textState.translateTextLineMatrix(args[0], args[1]);
  1262. textContentItem.width += args[0] - textContentItem.lastAdvanceWidth;
  1263. textContentItem.height += args[1] - textContentItem.lastAdvanceHeight;
  1264. diff = args[0] - textContentItem.lastAdvanceWidth - (args[1] - textContentItem.lastAdvanceHeight);
  1265. addFakeSpaces(diff, textContentItem.str);
  1266. break;
  1267. }
  1268. flushTextContentItem();
  1269. textState.translateTextLineMatrix(args[0], args[1]);
  1270. textState.textMatrix = textState.textLineMatrix.slice();
  1271. break;
  1272. case _util.OPS.setLeadingMoveText:
  1273. flushTextContentItem();
  1274. textState.leading = -args[1];
  1275. textState.translateTextLineMatrix(args[0], args[1]);
  1276. textState.textMatrix = textState.textLineMatrix.slice();
  1277. break;
  1278. case _util.OPS.nextLine:
  1279. flushTextContentItem();
  1280. textState.carriageReturn();
  1281. break;
  1282. case _util.OPS.setTextMatrix:
  1283. advance = textState.calcTextLineMatrixAdvance(args[0], args[1], args[2], args[3], args[4], args[5]);
  1284. if (combineTextItems && advance !== null && textContentItem.initialized && advance.value > 0 && advance.value <= textContentItem.fakeMultiSpaceMax) {
  1285. textState.translateTextLineMatrix(advance.width, advance.height);
  1286. textContentItem.width += advance.width - textContentItem.lastAdvanceWidth;
  1287. textContentItem.height += advance.height - textContentItem.lastAdvanceHeight;
  1288. diff = advance.width - textContentItem.lastAdvanceWidth - (advance.height - textContentItem.lastAdvanceHeight);
  1289. addFakeSpaces(diff, textContentItem.str);
  1290. break;
  1291. }
  1292. flushTextContentItem();
  1293. textState.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  1294. textState.setTextLineMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  1295. break;
  1296. case _util.OPS.setCharSpacing:
  1297. textState.charSpacing = args[0];
  1298. break;
  1299. case _util.OPS.setWordSpacing:
  1300. textState.wordSpacing = args[0];
  1301. break;
  1302. case _util.OPS.beginText:
  1303. flushTextContentItem();
  1304. textState.textMatrix = _util.IDENTITY_MATRIX.slice();
  1305. textState.textLineMatrix = _util.IDENTITY_MATRIX.slice();
  1306. break;
  1307. case _util.OPS.showSpacedText:
  1308. var items = args[0];
  1309. var offset;
  1310. for (var j = 0, jj = items.length; j < jj; j++) {
  1311. if (typeof items[j] === 'string') {
  1312. buildTextContentItem(items[j]);
  1313. } else if ((0, _util.isNum)(items[j])) {
  1314. ensureTextContentItem();
  1315. advance = items[j] * textState.fontSize / 1000;
  1316. var breakTextRun = false;
  1317. if (textState.font.vertical) {
  1318. offset = advance;
  1319. textState.translateTextMatrix(0, offset);
  1320. breakTextRun = textContentItem.textRunBreakAllowed && advance > textContentItem.fakeMultiSpaceMax;
  1321. if (!breakTextRun) {
  1322. textContentItem.height += offset;
  1323. }
  1324. } else {
  1325. advance = -advance;
  1326. offset = advance * textState.textHScale;
  1327. textState.translateTextMatrix(offset, 0);
  1328. breakTextRun = textContentItem.textRunBreakAllowed && advance > textContentItem.fakeMultiSpaceMax;
  1329. if (!breakTextRun) {
  1330. textContentItem.width += offset;
  1331. }
  1332. }
  1333. if (breakTextRun) {
  1334. flushTextContentItem();
  1335. } else if (advance > 0) {
  1336. addFakeSpaces(advance, textContentItem.str);
  1337. }
  1338. }
  1339. }
  1340. break;
  1341. case _util.OPS.showText:
  1342. buildTextContentItem(args[0]);
  1343. break;
  1344. case _util.OPS.nextLineShowText:
  1345. flushTextContentItem();
  1346. textState.carriageReturn();
  1347. buildTextContentItem(args[0]);
  1348. break;
  1349. case _util.OPS.nextLineSetSpacingShowText:
  1350. flushTextContentItem();
  1351. textState.wordSpacing = args[0];
  1352. textState.charSpacing = args[1];
  1353. textState.carriageReturn();
  1354. buildTextContentItem(args[2]);
  1355. break;
  1356. case _util.OPS.paintXObject:
  1357. flushTextContentItem();
  1358. if (!xobjs) {
  1359. xobjs = resources.get('XObject') || _primitives.Dict.empty;
  1360. }
  1361. var name = args[0].name;
  1362. if (name && skipEmptyXObjs[name] !== undefined) {
  1363. break;
  1364. }
  1365. next(new Promise(function (resolveXObject, rejectXObject) {
  1366. if (!name) {
  1367. throw new _util.FormatError('XObject must be referred to by name.');
  1368. }
  1369. var xobj = xobjs.get(name);
  1370. if (!xobj) {
  1371. resolveXObject();
  1372. return;
  1373. }
  1374. if (!(0, _primitives.isStream)(xobj)) {
  1375. throw new _util.FormatError('XObject should be a stream');
  1376. }
  1377. var type = xobj.dict.get('Subtype');
  1378. if (!(0, _primitives.isName)(type)) {
  1379. throw new _util.FormatError('XObject should have a Name subtype');
  1380. }
  1381. if (type.name !== 'Form') {
  1382. skipEmptyXObjs[name] = true;
  1383. resolveXObject();
  1384. return;
  1385. }
  1386. var currentState = stateManager.state.clone();
  1387. var xObjStateManager = new StateManager(currentState);
  1388. var matrix = xobj.dict.getArray('Matrix');
  1389. if (Array.isArray(matrix) && matrix.length === 6) {
  1390. xObjStateManager.transform(matrix);
  1391. }
  1392. enqueueChunk();
  1393. var sinkWrapper = {
  1394. enqueueInvoked: false,
  1395. enqueue: function enqueue(chunk, size) {
  1396. this.enqueueInvoked = true;
  1397. sink.enqueue(chunk, size);
  1398. },
  1399. get desiredSize() {
  1400. return sink.desiredSize;
  1401. },
  1402. get ready() {
  1403. return sink.ready;
  1404. }
  1405. };
  1406. self.getTextContent({
  1407. stream: xobj,
  1408. task: task,
  1409. resources: xobj.dict.get('Resources') || resources,
  1410. stateManager: xObjStateManager,
  1411. normalizeWhitespace: normalizeWhitespace,
  1412. combineTextItems: combineTextItems,
  1413. sink: sinkWrapper,
  1414. seenStyles: seenStyles
  1415. }).then(function () {
  1416. if (!sinkWrapper.enqueueInvoked) {
  1417. skipEmptyXObjs[name] = true;
  1418. }
  1419. resolveXObject();
  1420. }, rejectXObject);
  1421. }).catch(function (reason) {
  1422. if (reason instanceof _util.AbortException) {
  1423. return;
  1424. }
  1425. if (self.options.ignoreErrors) {
  1426. (0, _util.warn)('getTextContent - ignoring XObject: "' + reason + '".');
  1427. return;
  1428. }
  1429. throw reason;
  1430. }));
  1431. return;
  1432. case _util.OPS.setGState:
  1433. flushTextContentItem();
  1434. var dictName = args[0];
  1435. var extGState = resources.get('ExtGState');
  1436. if (!(0, _primitives.isDict)(extGState) || !(0, _primitives.isName)(dictName)) {
  1437. break;
  1438. }
  1439. var gState = extGState.get(dictName.name);
  1440. if (!(0, _primitives.isDict)(gState)) {
  1441. break;
  1442. }
  1443. var gStateFont = gState.get('Font');
  1444. if (gStateFont) {
  1445. textState.fontName = null;
  1446. textState.fontSize = gStateFont[1];
  1447. next(handleSetFont(null, gStateFont[0]));
  1448. return;
  1449. }
  1450. break;
  1451. }
  1452. if (textContent.items.length >= sink.desiredSize) {
  1453. stop = true;
  1454. break;
  1455. }
  1456. }
  1457. if (stop) {
  1458. next(deferred);
  1459. return;
  1460. }
  1461. flushTextContentItem();
  1462. enqueueChunk();
  1463. resolve();
  1464. }).catch(function (reason) {
  1465. if (reason instanceof _util.AbortException) {
  1466. return;
  1467. }
  1468. if (_this9.options.ignoreErrors) {
  1469. (0, _util.warn)('getTextContent - ignoring errors during task: ' + task.name);
  1470. flushTextContentItem();
  1471. enqueueChunk();
  1472. return;
  1473. }
  1474. throw reason;
  1475. });
  1476. },
  1477. extractDataStructures: function PartialEvaluator_extractDataStructures(dict, baseDict, properties) {
  1478. var _this10 = this;
  1479. var xref = this.xref;
  1480. var toUnicode = dict.get('ToUnicode') || baseDict.get('ToUnicode');
  1481. var toUnicodePromise = toUnicode ? this.readToUnicode(toUnicode) : Promise.resolve(undefined);
  1482. if (properties.composite) {
  1483. var cidSystemInfo = dict.get('CIDSystemInfo');
  1484. if ((0, _primitives.isDict)(cidSystemInfo)) {
  1485. properties.cidSystemInfo = {
  1486. registry: cidSystemInfo.get('Registry'),
  1487. ordering: cidSystemInfo.get('Ordering'),
  1488. supplement: cidSystemInfo.get('Supplement')
  1489. };
  1490. }
  1491. var cidToGidMap = dict.get('CIDToGIDMap');
  1492. if ((0, _primitives.isStream)(cidToGidMap)) {
  1493. properties.cidToGidMap = this.readCidToGidMap(cidToGidMap);
  1494. }
  1495. }
  1496. var differences = [];
  1497. var baseEncodingName = null;
  1498. var encoding;
  1499. if (dict.has('Encoding')) {
  1500. encoding = dict.get('Encoding');
  1501. if ((0, _primitives.isDict)(encoding)) {
  1502. baseEncodingName = encoding.get('BaseEncoding');
  1503. baseEncodingName = (0, _primitives.isName)(baseEncodingName) ? baseEncodingName.name : null;
  1504. if (encoding.has('Differences')) {
  1505. var diffEncoding = encoding.get('Differences');
  1506. var index = 0;
  1507. for (var j = 0, jj = diffEncoding.length; j < jj; j++) {
  1508. var data = xref.fetchIfRef(diffEncoding[j]);
  1509. if ((0, _util.isNum)(data)) {
  1510. index = data;
  1511. } else if ((0, _primitives.isName)(data)) {
  1512. differences[index++] = data.name;
  1513. } else {
  1514. throw new _util.FormatError('Invalid entry in \'Differences\' array: ' + data);
  1515. }
  1516. }
  1517. }
  1518. } else if ((0, _primitives.isName)(encoding)) {
  1519. baseEncodingName = encoding.name;
  1520. } else {
  1521. throw new _util.FormatError('Encoding is not a Name nor a Dict');
  1522. }
  1523. if (baseEncodingName !== 'MacRomanEncoding' && baseEncodingName !== 'MacExpertEncoding' && baseEncodingName !== 'WinAnsiEncoding') {
  1524. baseEncodingName = null;
  1525. }
  1526. }
  1527. if (baseEncodingName) {
  1528. properties.defaultEncoding = (0, _encodings.getEncoding)(baseEncodingName).slice();
  1529. } else {
  1530. var isSymbolicFont = !!(properties.flags & _fonts.FontFlags.Symbolic);
  1531. var isNonsymbolicFont = !!(properties.flags & _fonts.FontFlags.Nonsymbolic);
  1532. encoding = _encodings.StandardEncoding;
  1533. if (properties.type === 'TrueType' && !isNonsymbolicFont) {
  1534. encoding = _encodings.WinAnsiEncoding;
  1535. }
  1536. if (isSymbolicFont) {
  1537. encoding = _encodings.MacRomanEncoding;
  1538. if (!properties.file) {
  1539. if (/Symbol/i.test(properties.name)) {
  1540. encoding = _encodings.SymbolSetEncoding;
  1541. } else if (/Dingbats/i.test(properties.name)) {
  1542. encoding = _encodings.ZapfDingbatsEncoding;
  1543. }
  1544. }
  1545. }
  1546. properties.defaultEncoding = encoding;
  1547. }
  1548. properties.differences = differences;
  1549. properties.baseEncodingName = baseEncodingName;
  1550. properties.hasEncoding = !!baseEncodingName || differences.length > 0;
  1551. properties.dict = dict;
  1552. return toUnicodePromise.then(function (toUnicode) {
  1553. properties.toUnicode = toUnicode;
  1554. return _this10.buildToUnicode(properties);
  1555. }).then(function (toUnicode) {
  1556. properties.toUnicode = toUnicode;
  1557. return properties;
  1558. });
  1559. },
  1560. buildToUnicode: function PartialEvaluator_buildToUnicode(properties) {
  1561. properties.hasIncludedToUnicodeMap = !!properties.toUnicode && properties.toUnicode.length > 0;
  1562. if (properties.hasIncludedToUnicodeMap) {
  1563. return Promise.resolve(properties.toUnicode);
  1564. }
  1565. var toUnicode, charcode, glyphName;
  1566. if (!properties.composite) {
  1567. toUnicode = [];
  1568. var encoding = properties.defaultEncoding.slice();
  1569. var baseEncodingName = properties.baseEncodingName;
  1570. var differences = properties.differences;
  1571. for (charcode in differences) {
  1572. glyphName = differences[charcode];
  1573. if (glyphName === '.notdef') {
  1574. continue;
  1575. }
  1576. encoding[charcode] = glyphName;
  1577. }
  1578. var glyphsUnicodeMap = (0, _glyphlist.getGlyphsUnicode)();
  1579. for (charcode in encoding) {
  1580. glyphName = encoding[charcode];
  1581. if (glyphName === '') {
  1582. continue;
  1583. } else if (glyphsUnicodeMap[glyphName] === undefined) {
  1584. var code = 0;
  1585. switch (glyphName[0]) {
  1586. case 'G':
  1587. if (glyphName.length === 3) {
  1588. code = parseInt(glyphName.substr(1), 16);
  1589. }
  1590. break;
  1591. case 'g':
  1592. if (glyphName.length === 5) {
  1593. code = parseInt(glyphName.substr(1), 16);
  1594. }
  1595. break;
  1596. case 'C':
  1597. case 'c':
  1598. if (glyphName.length >= 3) {
  1599. code = +glyphName.substr(1);
  1600. }
  1601. break;
  1602. default:
  1603. var unicode = (0, _unicode.getUnicodeForGlyph)(glyphName, glyphsUnicodeMap);
  1604. if (unicode !== -1) {
  1605. code = unicode;
  1606. }
  1607. }
  1608. if (code) {
  1609. if (baseEncodingName && code === +charcode) {
  1610. var baseEncoding = (0, _encodings.getEncoding)(baseEncodingName);
  1611. if (baseEncoding && (glyphName = baseEncoding[charcode])) {
  1612. toUnicode[charcode] = String.fromCharCode(glyphsUnicodeMap[glyphName]);
  1613. continue;
  1614. }
  1615. }
  1616. toUnicode[charcode] = String.fromCharCode(code);
  1617. }
  1618. continue;
  1619. }
  1620. toUnicode[charcode] = String.fromCharCode(glyphsUnicodeMap[glyphName]);
  1621. }
  1622. return Promise.resolve(new _fonts.ToUnicodeMap(toUnicode));
  1623. }
  1624. if (properties.composite && (properties.cMap.builtInCMap && !(properties.cMap instanceof _cmap.IdentityCMap) || properties.cidSystemInfo.registry === 'Adobe' && (properties.cidSystemInfo.ordering === 'GB1' || properties.cidSystemInfo.ordering === 'CNS1' || properties.cidSystemInfo.ordering === 'Japan1' || properties.cidSystemInfo.ordering === 'Korea1'))) {
  1625. var registry = properties.cidSystemInfo.registry;
  1626. var ordering = properties.cidSystemInfo.ordering;
  1627. var ucs2CMapName = _primitives.Name.get(registry + '-' + ordering + '-UCS2');
  1628. return _cmap.CMapFactory.create({
  1629. encoding: ucs2CMapName,
  1630. fetchBuiltInCMap: this.fetchBuiltInCMap,
  1631. useCMap: null
  1632. }).then(function (ucs2CMap) {
  1633. var cMap = properties.cMap;
  1634. toUnicode = [];
  1635. cMap.forEach(function (charcode, cid) {
  1636. if (cid > 0xffff) {
  1637. throw new _util.FormatError('Max size of CID is 65,535');
  1638. }
  1639. var ucs2 = ucs2CMap.lookup(cid);
  1640. if (ucs2) {
  1641. toUnicode[charcode] = String.fromCharCode((ucs2.charCodeAt(0) << 8) + ucs2.charCodeAt(1));
  1642. }
  1643. });
  1644. return new _fonts.ToUnicodeMap(toUnicode);
  1645. });
  1646. }
  1647. return Promise.resolve(new _fonts.IdentityToUnicodeMap(properties.firstChar, properties.lastChar));
  1648. },
  1649. readToUnicode: function PartialEvaluator_readToUnicode(toUnicode) {
  1650. var cmapObj = toUnicode;
  1651. if ((0, _primitives.isName)(cmapObj)) {
  1652. return _cmap.CMapFactory.create({
  1653. encoding: cmapObj,
  1654. fetchBuiltInCMap: this.fetchBuiltInCMap,
  1655. useCMap: null
  1656. }).then(function (cmap) {
  1657. if (cmap instanceof _cmap.IdentityCMap) {
  1658. return new _fonts.IdentityToUnicodeMap(0, 0xFFFF);
  1659. }
  1660. return new _fonts.ToUnicodeMap(cmap.getMap());
  1661. });
  1662. } else if ((0, _primitives.isStream)(cmapObj)) {
  1663. return _cmap.CMapFactory.create({
  1664. encoding: cmapObj,
  1665. fetchBuiltInCMap: this.fetchBuiltInCMap,
  1666. useCMap: null
  1667. }).then(function (cmap) {
  1668. if (cmap instanceof _cmap.IdentityCMap) {
  1669. return new _fonts.IdentityToUnicodeMap(0, 0xFFFF);
  1670. }
  1671. var map = new Array(cmap.length);
  1672. cmap.forEach(function (charCode, token) {
  1673. var str = [];
  1674. for (var k = 0; k < token.length; k += 2) {
  1675. var w1 = token.charCodeAt(k) << 8 | token.charCodeAt(k + 1);
  1676. if ((w1 & 0xF800) !== 0xD800) {
  1677. str.push(w1);
  1678. continue;
  1679. }
  1680. k += 2;
  1681. var w2 = token.charCodeAt(k) << 8 | token.charCodeAt(k + 1);
  1682. str.push(((w1 & 0x3ff) << 10) + (w2 & 0x3ff) + 0x10000);
  1683. }
  1684. map[charCode] = String.fromCharCode.apply(String, str);
  1685. });
  1686. return new _fonts.ToUnicodeMap(map);
  1687. });
  1688. }
  1689. return Promise.resolve(null);
  1690. },
  1691. readCidToGidMap: function PartialEvaluator_readCidToGidMap(cidToGidStream) {
  1692. var glyphsData = cidToGidStream.getBytes();
  1693. var result = [];
  1694. for (var j = 0, jj = glyphsData.length; j < jj; j++) {
  1695. var glyphID = glyphsData[j++] << 8 | glyphsData[j];
  1696. if (glyphID === 0) {
  1697. continue;
  1698. }
  1699. var code = j >> 1;
  1700. result[code] = glyphID;
  1701. }
  1702. return result;
  1703. },
  1704. extractWidths: function PartialEvaluator_extractWidths(dict, descriptor, properties) {
  1705. var xref = this.xref;
  1706. var glyphsWidths = [];
  1707. var defaultWidth = 0;
  1708. var glyphsVMetrics = [];
  1709. var defaultVMetrics;
  1710. var i, ii, j, jj, start, code, widths;
  1711. if (properties.composite) {
  1712. defaultWidth = dict.has('DW') ? dict.get('DW') : 1000;
  1713. widths = dict.get('W');
  1714. if (widths) {
  1715. for (i = 0, ii = widths.length; i < ii; i++) {
  1716. start = xref.fetchIfRef(widths[i++]);
  1717. code = xref.fetchIfRef(widths[i]);
  1718. if (Array.isArray(code)) {
  1719. for (j = 0, jj = code.length; j < jj; j++) {
  1720. glyphsWidths[start++] = xref.fetchIfRef(code[j]);
  1721. }
  1722. } else {
  1723. var width = xref.fetchIfRef(widths[++i]);
  1724. for (j = start; j <= code; j++) {
  1725. glyphsWidths[j] = width;
  1726. }
  1727. }
  1728. }
  1729. }
  1730. if (properties.vertical) {
  1731. var vmetrics = dict.getArray('DW2') || [880, -1000];
  1732. defaultVMetrics = [vmetrics[1], defaultWidth * 0.5, vmetrics[0]];
  1733. vmetrics = dict.get('W2');
  1734. if (vmetrics) {
  1735. for (i = 0, ii = vmetrics.length; i < ii; i++) {
  1736. start = xref.fetchIfRef(vmetrics[i++]);
  1737. code = xref.fetchIfRef(vmetrics[i]);
  1738. if (Array.isArray(code)) {
  1739. for (j = 0, jj = code.length; j < jj; j++) {
  1740. glyphsVMetrics[start++] = [xref.fetchIfRef(code[j++]), xref.fetchIfRef(code[j++]), xref.fetchIfRef(code[j])];
  1741. }
  1742. } else {
  1743. var vmetric = [xref.fetchIfRef(vmetrics[++i]), xref.fetchIfRef(vmetrics[++i]), xref.fetchIfRef(vmetrics[++i])];
  1744. for (j = start; j <= code; j++) {
  1745. glyphsVMetrics[j] = vmetric;
  1746. }
  1747. }
  1748. }
  1749. }
  1750. }
  1751. } else {
  1752. var firstChar = properties.firstChar;
  1753. widths = dict.get('Widths');
  1754. if (widths) {
  1755. j = firstChar;
  1756. for (i = 0, ii = widths.length; i < ii; i++) {
  1757. glyphsWidths[j++] = xref.fetchIfRef(widths[i]);
  1758. }
  1759. defaultWidth = parseFloat(descriptor.get('MissingWidth')) || 0;
  1760. } else {
  1761. var baseFontName = dict.get('BaseFont');
  1762. if ((0, _primitives.isName)(baseFontName)) {
  1763. var metrics = this.getBaseFontMetrics(baseFontName.name);
  1764. glyphsWidths = this.buildCharCodeToWidth(metrics.widths, properties);
  1765. defaultWidth = metrics.defaultWidth;
  1766. }
  1767. }
  1768. }
  1769. var isMonospace = true;
  1770. var firstWidth = defaultWidth;
  1771. for (var glyph in glyphsWidths) {
  1772. var glyphWidth = glyphsWidths[glyph];
  1773. if (!glyphWidth) {
  1774. continue;
  1775. }
  1776. if (!firstWidth) {
  1777. firstWidth = glyphWidth;
  1778. continue;
  1779. }
  1780. if (firstWidth !== glyphWidth) {
  1781. isMonospace = false;
  1782. break;
  1783. }
  1784. }
  1785. if (isMonospace) {
  1786. properties.flags |= _fonts.FontFlags.FixedPitch;
  1787. }
  1788. properties.defaultWidth = defaultWidth;
  1789. properties.widths = glyphsWidths;
  1790. properties.defaultVMetrics = defaultVMetrics;
  1791. properties.vmetrics = glyphsVMetrics;
  1792. },
  1793. isSerifFont: function PartialEvaluator_isSerifFont(baseFontName) {
  1794. var fontNameWoStyle = baseFontName.split('-')[0];
  1795. return fontNameWoStyle in (0, _standard_fonts.getSerifFonts)() || fontNameWoStyle.search(/serif/gi) !== -1;
  1796. },
  1797. getBaseFontMetrics: function PartialEvaluator_getBaseFontMetrics(name) {
  1798. var defaultWidth = 0;
  1799. var widths = [];
  1800. var monospace = false;
  1801. var stdFontMap = (0, _standard_fonts.getStdFontMap)();
  1802. var lookupName = stdFontMap[name] || name;
  1803. var Metrics = (0, _metrics.getMetrics)();
  1804. if (!(lookupName in Metrics)) {
  1805. if (this.isSerifFont(name)) {
  1806. lookupName = 'Times-Roman';
  1807. } else {
  1808. lookupName = 'Helvetica';
  1809. }
  1810. }
  1811. var glyphWidths = Metrics[lookupName];
  1812. if ((0, _util.isNum)(glyphWidths)) {
  1813. defaultWidth = glyphWidths;
  1814. monospace = true;
  1815. } else {
  1816. widths = glyphWidths();
  1817. }
  1818. return {
  1819. defaultWidth: defaultWidth,
  1820. monospace: monospace,
  1821. widths: widths
  1822. };
  1823. },
  1824. buildCharCodeToWidth: function PartialEvaluator_bulildCharCodeToWidth(widthsByGlyphName, properties) {
  1825. var widths = Object.create(null);
  1826. var differences = properties.differences;
  1827. var encoding = properties.defaultEncoding;
  1828. for (var charCode = 0; charCode < 256; charCode++) {
  1829. if (charCode in differences && widthsByGlyphName[differences[charCode]]) {
  1830. widths[charCode] = widthsByGlyphName[differences[charCode]];
  1831. continue;
  1832. }
  1833. if (charCode in encoding && widthsByGlyphName[encoding[charCode]]) {
  1834. widths[charCode] = widthsByGlyphName[encoding[charCode]];
  1835. continue;
  1836. }
  1837. }
  1838. return widths;
  1839. },
  1840. preEvaluateFont: function PartialEvaluator_preEvaluateFont(dict) {
  1841. var baseDict = dict;
  1842. var type = dict.get('Subtype');
  1843. if (!(0, _primitives.isName)(type)) {
  1844. throw new _util.FormatError('invalid font Subtype');
  1845. }
  1846. var composite = false;
  1847. var uint8array;
  1848. if (type.name === 'Type0') {
  1849. var df = dict.get('DescendantFonts');
  1850. if (!df) {
  1851. throw new _util.FormatError('Descendant fonts are not specified');
  1852. }
  1853. dict = Array.isArray(df) ? this.xref.fetchIfRef(df[0]) : df;
  1854. type = dict.get('Subtype');
  1855. if (!(0, _primitives.isName)(type)) {
  1856. throw new _util.FormatError('invalid font Subtype');
  1857. }
  1858. composite = true;
  1859. }
  1860. var descriptor = dict.get('FontDescriptor');
  1861. if (descriptor) {
  1862. var hash = new _murmurhash.MurmurHash3_64();
  1863. var encoding = baseDict.getRaw('Encoding');
  1864. if ((0, _primitives.isName)(encoding)) {
  1865. hash.update(encoding.name);
  1866. } else if ((0, _primitives.isRef)(encoding)) {
  1867. hash.update(encoding.toString());
  1868. } else if ((0, _primitives.isDict)(encoding)) {
  1869. var keys = encoding.getKeys();
  1870. for (var i = 0, ii = keys.length; i < ii; i++) {
  1871. var entry = encoding.getRaw(keys[i]);
  1872. if ((0, _primitives.isName)(entry)) {
  1873. hash.update(entry.name);
  1874. } else if ((0, _primitives.isRef)(entry)) {
  1875. hash.update(entry.toString());
  1876. } else if (Array.isArray(entry)) {
  1877. var diffLength = entry.length,
  1878. diffBuf = new Array(diffLength);
  1879. for (var j = 0; j < diffLength; j++) {
  1880. var diffEntry = entry[j];
  1881. if ((0, _primitives.isName)(diffEntry)) {
  1882. diffBuf[j] = diffEntry.name;
  1883. } else if ((0, _util.isNum)(diffEntry) || (0, _primitives.isRef)(diffEntry)) {
  1884. diffBuf[j] = diffEntry.toString();
  1885. }
  1886. }
  1887. hash.update(diffBuf.join());
  1888. }
  1889. }
  1890. }
  1891. var toUnicode = dict.get('ToUnicode') || baseDict.get('ToUnicode');
  1892. if ((0, _primitives.isStream)(toUnicode)) {
  1893. var stream = toUnicode.str || toUnicode;
  1894. uint8array = stream.buffer ? new Uint8Array(stream.buffer.buffer, 0, stream.bufferLength) : new Uint8Array(stream.bytes.buffer, stream.start, stream.end - stream.start);
  1895. hash.update(uint8array);
  1896. } else if ((0, _primitives.isName)(toUnicode)) {
  1897. hash.update(toUnicode.name);
  1898. }
  1899. var widths = dict.get('Widths') || baseDict.get('Widths');
  1900. if (widths) {
  1901. uint8array = new Uint8Array(new Uint32Array(widths).buffer);
  1902. hash.update(uint8array);
  1903. }
  1904. }
  1905. return {
  1906. descriptor: descriptor,
  1907. dict: dict,
  1908. baseDict: baseDict,
  1909. composite: composite,
  1910. type: type.name,
  1911. hash: hash ? hash.hexdigest() : ''
  1912. };
  1913. },
  1914. translateFont: function PartialEvaluator_translateFont(preEvaluatedFont) {
  1915. var _this11 = this;
  1916. var baseDict = preEvaluatedFont.baseDict;
  1917. var dict = preEvaluatedFont.dict;
  1918. var composite = preEvaluatedFont.composite;
  1919. var descriptor = preEvaluatedFont.descriptor;
  1920. var type = preEvaluatedFont.type;
  1921. var maxCharIndex = composite ? 0xFFFF : 0xFF;
  1922. var properties;
  1923. if (!descriptor) {
  1924. if (type === 'Type3') {
  1925. descriptor = new _primitives.Dict(null);
  1926. descriptor.set('FontName', _primitives.Name.get(type));
  1927. descriptor.set('FontBBox', dict.getArray('FontBBox'));
  1928. } else {
  1929. var baseFontName = dict.get('BaseFont');
  1930. if (!(0, _primitives.isName)(baseFontName)) {
  1931. throw new _util.FormatError('Base font is not specified');
  1932. }
  1933. baseFontName = baseFontName.name.replace(/[,_]/g, '-');
  1934. var metrics = this.getBaseFontMetrics(baseFontName);
  1935. var fontNameWoStyle = baseFontName.split('-')[0];
  1936. var flags = (this.isSerifFont(fontNameWoStyle) ? _fonts.FontFlags.Serif : 0) | (metrics.monospace ? _fonts.FontFlags.FixedPitch : 0) | ((0, _standard_fonts.getSymbolsFonts)()[fontNameWoStyle] ? _fonts.FontFlags.Symbolic : _fonts.FontFlags.Nonsymbolic);
  1937. properties = {
  1938. type: type,
  1939. name: baseFontName,
  1940. widths: metrics.widths,
  1941. defaultWidth: metrics.defaultWidth,
  1942. flags: flags,
  1943. firstChar: 0,
  1944. lastChar: maxCharIndex
  1945. };
  1946. return this.extractDataStructures(dict, dict, properties).then(function (properties) {
  1947. properties.widths = _this11.buildCharCodeToWidth(metrics.widths, properties);
  1948. return new _fonts.Font(baseFontName, null, properties);
  1949. });
  1950. }
  1951. }
  1952. var firstChar = dict.get('FirstChar') || 0;
  1953. var lastChar = dict.get('LastChar') || maxCharIndex;
  1954. var fontName = descriptor.get('FontName');
  1955. var baseFont = dict.get('BaseFont');
  1956. if ((0, _util.isString)(fontName)) {
  1957. fontName = _primitives.Name.get(fontName);
  1958. }
  1959. if ((0, _util.isString)(baseFont)) {
  1960. baseFont = _primitives.Name.get(baseFont);
  1961. }
  1962. if (type !== 'Type3') {
  1963. var fontNameStr = fontName && fontName.name;
  1964. var baseFontStr = baseFont && baseFont.name;
  1965. if (fontNameStr !== baseFontStr) {
  1966. (0, _util.info)('The FontDescriptor\'s FontName is "' + fontNameStr + '" but should be the same as the Font\'s BaseFont "' + baseFontStr + '"');
  1967. if (fontNameStr && baseFontStr && baseFontStr.indexOf(fontNameStr) === 0) {
  1968. fontName = baseFont;
  1969. }
  1970. }
  1971. }
  1972. fontName = fontName || baseFont;
  1973. if (!(0, _primitives.isName)(fontName)) {
  1974. throw new _util.FormatError('invalid font name');
  1975. }
  1976. var fontFile = descriptor.get('FontFile', 'FontFile2', 'FontFile3');
  1977. if (fontFile) {
  1978. if (fontFile.dict) {
  1979. var subtype = fontFile.dict.get('Subtype');
  1980. if (subtype) {
  1981. subtype = subtype.name;
  1982. }
  1983. var length1 = fontFile.dict.get('Length1');
  1984. var length2 = fontFile.dict.get('Length2');
  1985. var length3 = fontFile.dict.get('Length3');
  1986. }
  1987. }
  1988. properties = {
  1989. type: type,
  1990. name: fontName.name,
  1991. subtype: subtype,
  1992. file: fontFile,
  1993. length1: length1,
  1994. length2: length2,
  1995. length3: length3,
  1996. loadedName: baseDict.loadedName,
  1997. composite: composite,
  1998. wideChars: composite,
  1999. fixedPitch: false,
  2000. fontMatrix: dict.getArray('FontMatrix') || _util.FONT_IDENTITY_MATRIX,
  2001. firstChar: firstChar || 0,
  2002. lastChar: lastChar || maxCharIndex,
  2003. bbox: descriptor.getArray('FontBBox'),
  2004. ascent: descriptor.get('Ascent'),
  2005. descent: descriptor.get('Descent'),
  2006. xHeight: descriptor.get('XHeight'),
  2007. capHeight: descriptor.get('CapHeight'),
  2008. flags: descriptor.get('Flags'),
  2009. italicAngle: descriptor.get('ItalicAngle'),
  2010. isType3Font: false
  2011. };
  2012. var cMapPromise;
  2013. if (composite) {
  2014. var cidEncoding = baseDict.get('Encoding');
  2015. if ((0, _primitives.isName)(cidEncoding)) {
  2016. properties.cidEncoding = cidEncoding.name;
  2017. }
  2018. cMapPromise = _cmap.CMapFactory.create({
  2019. encoding: cidEncoding,
  2020. fetchBuiltInCMap: this.fetchBuiltInCMap,
  2021. useCMap: null
  2022. }).then(function (cMap) {
  2023. properties.cMap = cMap;
  2024. properties.vertical = properties.cMap.vertical;
  2025. });
  2026. } else {
  2027. cMapPromise = Promise.resolve(undefined);
  2028. }
  2029. return cMapPromise.then(function () {
  2030. return _this11.extractDataStructures(dict, baseDict, properties);
  2031. }).then(function (properties) {
  2032. _this11.extractWidths(dict, descriptor, properties);
  2033. if (type === 'Type3') {
  2034. properties.isType3Font = true;
  2035. }
  2036. return new _fonts.Font(fontName.name, fontFile, properties);
  2037. });
  2038. }
  2039. };
  2040. return PartialEvaluator;
  2041. }();
  2042. var TranslatedFont = function TranslatedFontClosure() {
  2043. function TranslatedFont(loadedName, font, dict) {
  2044. this.loadedName = loadedName;
  2045. this.font = font;
  2046. this.dict = dict;
  2047. this.type3Loaded = null;
  2048. this.sent = false;
  2049. }
  2050. TranslatedFont.prototype = {
  2051. send: function send(handler) {
  2052. if (this.sent) {
  2053. return;
  2054. }
  2055. var fontData = this.font.exportData();
  2056. handler.send('commonobj', [this.loadedName, 'Font', fontData]);
  2057. this.sent = true;
  2058. },
  2059. loadType3Data: function loadType3Data(evaluator, resources, parentOperatorList, task) {
  2060. if (!this.font.isType3Font) {
  2061. throw new Error('Must be a Type3 font.');
  2062. }
  2063. if (this.type3Loaded) {
  2064. return this.type3Loaded;
  2065. }
  2066. var type3Options = Object.create(evaluator.options);
  2067. type3Options.ignoreErrors = false;
  2068. var type3Evaluator = evaluator.clone(type3Options);
  2069. var translatedFont = this.font;
  2070. var loadCharProcsPromise = Promise.resolve();
  2071. var charProcs = this.dict.get('CharProcs');
  2072. var fontResources = this.dict.get('Resources') || resources;
  2073. var charProcKeys = charProcs.getKeys();
  2074. var charProcOperatorList = Object.create(null);
  2075. var _loop2 = function _loop2() {
  2076. var key = charProcKeys[i];
  2077. loadCharProcsPromise = loadCharProcsPromise.then(function () {
  2078. var glyphStream = charProcs.get(key);
  2079. var operatorList = new _operator_list.OperatorList();
  2080. return type3Evaluator.getOperatorList({
  2081. stream: glyphStream,
  2082. task: task,
  2083. resources: fontResources,
  2084. operatorList: operatorList
  2085. }).then(function () {
  2086. charProcOperatorList[key] = operatorList.getIR();
  2087. parentOperatorList.addDependencies(operatorList.dependencies);
  2088. }).catch(function (reason) {
  2089. (0, _util.warn)('Type3 font resource "' + key + '" is not available.');
  2090. var operatorList = new _operator_list.OperatorList();
  2091. charProcOperatorList[key] = operatorList.getIR();
  2092. });
  2093. });
  2094. };
  2095. for (var i = 0, n = charProcKeys.length; i < n; ++i) {
  2096. _loop2();
  2097. }
  2098. this.type3Loaded = loadCharProcsPromise.then(function () {
  2099. translatedFont.charProcOperatorList = charProcOperatorList;
  2100. });
  2101. return this.type3Loaded;
  2102. }
  2103. };
  2104. return TranslatedFont;
  2105. }();
  2106. var StateManager = function StateManagerClosure() {
  2107. function StateManager(initialState) {
  2108. this.state = initialState;
  2109. this.stateStack = [];
  2110. }
  2111. StateManager.prototype = {
  2112. save: function save() {
  2113. var old = this.state;
  2114. this.stateStack.push(this.state);
  2115. this.state = old.clone();
  2116. },
  2117. restore: function restore() {
  2118. var prev = this.stateStack.pop();
  2119. if (prev) {
  2120. this.state = prev;
  2121. }
  2122. },
  2123. transform: function transform(args) {
  2124. this.state.ctm = _util.Util.transform(this.state.ctm, args);
  2125. }
  2126. };
  2127. return StateManager;
  2128. }();
  2129. var TextState = function TextStateClosure() {
  2130. function TextState() {
  2131. this.ctm = new Float32Array(_util.IDENTITY_MATRIX);
  2132. this.fontName = null;
  2133. this.fontSize = 0;
  2134. this.font = null;
  2135. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  2136. this.textMatrix = _util.IDENTITY_MATRIX.slice();
  2137. this.textLineMatrix = _util.IDENTITY_MATRIX.slice();
  2138. this.charSpacing = 0;
  2139. this.wordSpacing = 0;
  2140. this.leading = 0;
  2141. this.textHScale = 1;
  2142. this.textRise = 0;
  2143. }
  2144. TextState.prototype = {
  2145. setTextMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {
  2146. var m = this.textMatrix;
  2147. m[0] = a;
  2148. m[1] = b;
  2149. m[2] = c;
  2150. m[3] = d;
  2151. m[4] = e;
  2152. m[5] = f;
  2153. },
  2154. setTextLineMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {
  2155. var m = this.textLineMatrix;
  2156. m[0] = a;
  2157. m[1] = b;
  2158. m[2] = c;
  2159. m[3] = d;
  2160. m[4] = e;
  2161. m[5] = f;
  2162. },
  2163. translateTextMatrix: function TextState_translateTextMatrix(x, y) {
  2164. var m = this.textMatrix;
  2165. m[4] = m[0] * x + m[2] * y + m[4];
  2166. m[5] = m[1] * x + m[3] * y + m[5];
  2167. },
  2168. translateTextLineMatrix: function TextState_translateTextMatrix(x, y) {
  2169. var m = this.textLineMatrix;
  2170. m[4] = m[0] * x + m[2] * y + m[4];
  2171. m[5] = m[1] * x + m[3] * y + m[5];
  2172. },
  2173. calcTextLineMatrixAdvance: function TextState_calcTextLineMatrixAdvance(a, b, c, d, e, f) {
  2174. var font = this.font;
  2175. if (!font) {
  2176. return null;
  2177. }
  2178. var m = this.textLineMatrix;
  2179. if (!(a === m[0] && b === m[1] && c === m[2] && d === m[3])) {
  2180. return null;
  2181. }
  2182. var txDiff = e - m[4],
  2183. tyDiff = f - m[5];
  2184. if (font.vertical && txDiff !== 0 || !font.vertical && tyDiff !== 0) {
  2185. return null;
  2186. }
  2187. var tx,
  2188. ty,
  2189. denominator = a * d - b * c;
  2190. if (font.vertical) {
  2191. tx = -tyDiff * c / denominator;
  2192. ty = tyDiff * a / denominator;
  2193. } else {
  2194. tx = txDiff * d / denominator;
  2195. ty = -txDiff * b / denominator;
  2196. }
  2197. return {
  2198. width: tx,
  2199. height: ty,
  2200. value: font.vertical ? ty : tx
  2201. };
  2202. },
  2203. calcRenderMatrix: function TextState_calcRendeMatrix(ctm) {
  2204. var tsm = [this.fontSize * this.textHScale, 0, 0, this.fontSize, 0, this.textRise];
  2205. return _util.Util.transform(ctm, _util.Util.transform(this.textMatrix, tsm));
  2206. },
  2207. carriageReturn: function TextState_carriageReturn() {
  2208. this.translateTextLineMatrix(0, -this.leading);
  2209. this.textMatrix = this.textLineMatrix.slice();
  2210. },
  2211. clone: function TextState_clone() {
  2212. var clone = Object.create(this);
  2213. clone.textMatrix = this.textMatrix.slice();
  2214. clone.textLineMatrix = this.textLineMatrix.slice();
  2215. clone.fontMatrix = this.fontMatrix.slice();
  2216. return clone;
  2217. }
  2218. };
  2219. return TextState;
  2220. }();
  2221. var EvalState = function EvalStateClosure() {
  2222. function EvalState() {
  2223. this.ctm = new Float32Array(_util.IDENTITY_MATRIX);
  2224. this.font = null;
  2225. this.textRenderingMode = _util.TextRenderingMode.FILL;
  2226. this.fillColorSpace = _colorspace.ColorSpace.singletons.gray;
  2227. this.strokeColorSpace = _colorspace.ColorSpace.singletons.gray;
  2228. }
  2229. EvalState.prototype = {
  2230. clone: function CanvasExtraState_clone() {
  2231. return Object.create(this);
  2232. }
  2233. };
  2234. return EvalState;
  2235. }();
  2236. var EvaluatorPreprocessor = function EvaluatorPreprocessorClosure() {
  2237. var getOPMap = (0, _util.getLookupTableFactory)(function (t) {
  2238. t['w'] = {
  2239. id: _util.OPS.setLineWidth,
  2240. numArgs: 1,
  2241. variableArgs: false
  2242. };
  2243. t['J'] = {
  2244. id: _util.OPS.setLineCap,
  2245. numArgs: 1,
  2246. variableArgs: false
  2247. };
  2248. t['j'] = {
  2249. id: _util.OPS.setLineJoin,
  2250. numArgs: 1,
  2251. variableArgs: false
  2252. };
  2253. t['M'] = {
  2254. id: _util.OPS.setMiterLimit,
  2255. numArgs: 1,
  2256. variableArgs: false
  2257. };
  2258. t['d'] = {
  2259. id: _util.OPS.setDash,
  2260. numArgs: 2,
  2261. variableArgs: false
  2262. };
  2263. t['ri'] = {
  2264. id: _util.OPS.setRenderingIntent,
  2265. numArgs: 1,
  2266. variableArgs: false
  2267. };
  2268. t['i'] = {
  2269. id: _util.OPS.setFlatness,
  2270. numArgs: 1,
  2271. variableArgs: false
  2272. };
  2273. t['gs'] = {
  2274. id: _util.OPS.setGState,
  2275. numArgs: 1,
  2276. variableArgs: false
  2277. };
  2278. t['q'] = {
  2279. id: _util.OPS.save,
  2280. numArgs: 0,
  2281. variableArgs: false
  2282. };
  2283. t['Q'] = {
  2284. id: _util.OPS.restore,
  2285. numArgs: 0,
  2286. variableArgs: false
  2287. };
  2288. t['cm'] = {
  2289. id: _util.OPS.transform,
  2290. numArgs: 6,
  2291. variableArgs: false
  2292. };
  2293. t['m'] = {
  2294. id: _util.OPS.moveTo,
  2295. numArgs: 2,
  2296. variableArgs: false
  2297. };
  2298. t['l'] = {
  2299. id: _util.OPS.lineTo,
  2300. numArgs: 2,
  2301. variableArgs: false
  2302. };
  2303. t['c'] = {
  2304. id: _util.OPS.curveTo,
  2305. numArgs: 6,
  2306. variableArgs: false
  2307. };
  2308. t['v'] = {
  2309. id: _util.OPS.curveTo2,
  2310. numArgs: 4,
  2311. variableArgs: false
  2312. };
  2313. t['y'] = {
  2314. id: _util.OPS.curveTo3,
  2315. numArgs: 4,
  2316. variableArgs: false
  2317. };
  2318. t['h'] = {
  2319. id: _util.OPS.closePath,
  2320. numArgs: 0,
  2321. variableArgs: false
  2322. };
  2323. t['re'] = {
  2324. id: _util.OPS.rectangle,
  2325. numArgs: 4,
  2326. variableArgs: false
  2327. };
  2328. t['S'] = {
  2329. id: _util.OPS.stroke,
  2330. numArgs: 0,
  2331. variableArgs: false
  2332. };
  2333. t['s'] = {
  2334. id: _util.OPS.closeStroke,
  2335. numArgs: 0,
  2336. variableArgs: false
  2337. };
  2338. t['f'] = {
  2339. id: _util.OPS.fill,
  2340. numArgs: 0,
  2341. variableArgs: false
  2342. };
  2343. t['F'] = {
  2344. id: _util.OPS.fill,
  2345. numArgs: 0,
  2346. variableArgs: false
  2347. };
  2348. t['f*'] = {
  2349. id: _util.OPS.eoFill,
  2350. numArgs: 0,
  2351. variableArgs: false
  2352. };
  2353. t['B'] = {
  2354. id: _util.OPS.fillStroke,
  2355. numArgs: 0,
  2356. variableArgs: false
  2357. };
  2358. t['B*'] = {
  2359. id: _util.OPS.eoFillStroke,
  2360. numArgs: 0,
  2361. variableArgs: false
  2362. };
  2363. t['b'] = {
  2364. id: _util.OPS.closeFillStroke,
  2365. numArgs: 0,
  2366. variableArgs: false
  2367. };
  2368. t['b*'] = {
  2369. id: _util.OPS.closeEOFillStroke,
  2370. numArgs: 0,
  2371. variableArgs: false
  2372. };
  2373. t['n'] = {
  2374. id: _util.OPS.endPath,
  2375. numArgs: 0,
  2376. variableArgs: false
  2377. };
  2378. t['W'] = {
  2379. id: _util.OPS.clip,
  2380. numArgs: 0,
  2381. variableArgs: false
  2382. };
  2383. t['W*'] = {
  2384. id: _util.OPS.eoClip,
  2385. numArgs: 0,
  2386. variableArgs: false
  2387. };
  2388. t['BT'] = {
  2389. id: _util.OPS.beginText,
  2390. numArgs: 0,
  2391. variableArgs: false
  2392. };
  2393. t['ET'] = {
  2394. id: _util.OPS.endText,
  2395. numArgs: 0,
  2396. variableArgs: false
  2397. };
  2398. t['Tc'] = {
  2399. id: _util.OPS.setCharSpacing,
  2400. numArgs: 1,
  2401. variableArgs: false
  2402. };
  2403. t['Tw'] = {
  2404. id: _util.OPS.setWordSpacing,
  2405. numArgs: 1,
  2406. variableArgs: false
  2407. };
  2408. t['Tz'] = {
  2409. id: _util.OPS.setHScale,
  2410. numArgs: 1,
  2411. variableArgs: false
  2412. };
  2413. t['TL'] = {
  2414. id: _util.OPS.setLeading,
  2415. numArgs: 1,
  2416. variableArgs: false
  2417. };
  2418. t['Tf'] = {
  2419. id: _util.OPS.setFont,
  2420. numArgs: 2,
  2421. variableArgs: false
  2422. };
  2423. t['Tr'] = {
  2424. id: _util.OPS.setTextRenderingMode,
  2425. numArgs: 1,
  2426. variableArgs: false
  2427. };
  2428. t['Ts'] = {
  2429. id: _util.OPS.setTextRise,
  2430. numArgs: 1,
  2431. variableArgs: false
  2432. };
  2433. t['Td'] = {
  2434. id: _util.OPS.moveText,
  2435. numArgs: 2,
  2436. variableArgs: false
  2437. };
  2438. t['TD'] = {
  2439. id: _util.OPS.setLeadingMoveText,
  2440. numArgs: 2,
  2441. variableArgs: false
  2442. };
  2443. t['Tm'] = {
  2444. id: _util.OPS.setTextMatrix,
  2445. numArgs: 6,
  2446. variableArgs: false
  2447. };
  2448. t['T*'] = {
  2449. id: _util.OPS.nextLine,
  2450. numArgs: 0,
  2451. variableArgs: false
  2452. };
  2453. t['Tj'] = {
  2454. id: _util.OPS.showText,
  2455. numArgs: 1,
  2456. variableArgs: false
  2457. };
  2458. t['TJ'] = {
  2459. id: _util.OPS.showSpacedText,
  2460. numArgs: 1,
  2461. variableArgs: false
  2462. };
  2463. t['\''] = {
  2464. id: _util.OPS.nextLineShowText,
  2465. numArgs: 1,
  2466. variableArgs: false
  2467. };
  2468. t['"'] = {
  2469. id: _util.OPS.nextLineSetSpacingShowText,
  2470. numArgs: 3,
  2471. variableArgs: false
  2472. };
  2473. t['d0'] = {
  2474. id: _util.OPS.setCharWidth,
  2475. numArgs: 2,
  2476. variableArgs: false
  2477. };
  2478. t['d1'] = {
  2479. id: _util.OPS.setCharWidthAndBounds,
  2480. numArgs: 6,
  2481. variableArgs: false
  2482. };
  2483. t['CS'] = {
  2484. id: _util.OPS.setStrokeColorSpace,
  2485. numArgs: 1,
  2486. variableArgs: false
  2487. };
  2488. t['cs'] = {
  2489. id: _util.OPS.setFillColorSpace,
  2490. numArgs: 1,
  2491. variableArgs: false
  2492. };
  2493. t['SC'] = {
  2494. id: _util.OPS.setStrokeColor,
  2495. numArgs: 4,
  2496. variableArgs: true
  2497. };
  2498. t['SCN'] = {
  2499. id: _util.OPS.setStrokeColorN,
  2500. numArgs: 33,
  2501. variableArgs: true
  2502. };
  2503. t['sc'] = {
  2504. id: _util.OPS.setFillColor,
  2505. numArgs: 4,
  2506. variableArgs: true
  2507. };
  2508. t['scn'] = {
  2509. id: _util.OPS.setFillColorN,
  2510. numArgs: 33,
  2511. variableArgs: true
  2512. };
  2513. t['G'] = {
  2514. id: _util.OPS.setStrokeGray,
  2515. numArgs: 1,
  2516. variableArgs: false
  2517. };
  2518. t['g'] = {
  2519. id: _util.OPS.setFillGray,
  2520. numArgs: 1,
  2521. variableArgs: false
  2522. };
  2523. t['RG'] = {
  2524. id: _util.OPS.setStrokeRGBColor,
  2525. numArgs: 3,
  2526. variableArgs: false
  2527. };
  2528. t['rg'] = {
  2529. id: _util.OPS.setFillRGBColor,
  2530. numArgs: 3,
  2531. variableArgs: false
  2532. };
  2533. t['K'] = {
  2534. id: _util.OPS.setStrokeCMYKColor,
  2535. numArgs: 4,
  2536. variableArgs: false
  2537. };
  2538. t['k'] = {
  2539. id: _util.OPS.setFillCMYKColor,
  2540. numArgs: 4,
  2541. variableArgs: false
  2542. };
  2543. t['sh'] = {
  2544. id: _util.OPS.shadingFill,
  2545. numArgs: 1,
  2546. variableArgs: false
  2547. };
  2548. t['BI'] = {
  2549. id: _util.OPS.beginInlineImage,
  2550. numArgs: 0,
  2551. variableArgs: false
  2552. };
  2553. t['ID'] = {
  2554. id: _util.OPS.beginImageData,
  2555. numArgs: 0,
  2556. variableArgs: false
  2557. };
  2558. t['EI'] = {
  2559. id: _util.OPS.endInlineImage,
  2560. numArgs: 1,
  2561. variableArgs: false
  2562. };
  2563. t['Do'] = {
  2564. id: _util.OPS.paintXObject,
  2565. numArgs: 1,
  2566. variableArgs: false
  2567. };
  2568. t['MP'] = {
  2569. id: _util.OPS.markPoint,
  2570. numArgs: 1,
  2571. variableArgs: false
  2572. };
  2573. t['DP'] = {
  2574. id: _util.OPS.markPointProps,
  2575. numArgs: 2,
  2576. variableArgs: false
  2577. };
  2578. t['BMC'] = {
  2579. id: _util.OPS.beginMarkedContent,
  2580. numArgs: 1,
  2581. variableArgs: false
  2582. };
  2583. t['BDC'] = {
  2584. id: _util.OPS.beginMarkedContentProps,
  2585. numArgs: 2,
  2586. variableArgs: false
  2587. };
  2588. t['EMC'] = {
  2589. id: _util.OPS.endMarkedContent,
  2590. numArgs: 0,
  2591. variableArgs: false
  2592. };
  2593. t['BX'] = {
  2594. id: _util.OPS.beginCompat,
  2595. numArgs: 0,
  2596. variableArgs: false
  2597. };
  2598. t['EX'] = {
  2599. id: _util.OPS.endCompat,
  2600. numArgs: 0,
  2601. variableArgs: false
  2602. };
  2603. t['BM'] = null;
  2604. t['BD'] = null;
  2605. t['true'] = null;
  2606. t['fa'] = null;
  2607. t['fal'] = null;
  2608. t['fals'] = null;
  2609. t['false'] = null;
  2610. t['nu'] = null;
  2611. t['nul'] = null;
  2612. t['null'] = null;
  2613. });
  2614. function EvaluatorPreprocessor(stream, xref, stateManager) {
  2615. this.opMap = getOPMap();
  2616. this.parser = new _parser.Parser(new _parser.Lexer(stream, this.opMap), false, xref);
  2617. this.stateManager = stateManager;
  2618. this.nonProcessedArgs = [];
  2619. }
  2620. EvaluatorPreprocessor.prototype = {
  2621. get savedStatesDepth() {
  2622. return this.stateManager.stateStack.length;
  2623. },
  2624. read: function EvaluatorPreprocessor_read(operation) {
  2625. var args = operation.args;
  2626. while (true) {
  2627. var obj = this.parser.getObj();
  2628. if ((0, _primitives.isCmd)(obj)) {
  2629. var cmd = obj.cmd;
  2630. var opSpec = this.opMap[cmd];
  2631. if (!opSpec) {
  2632. (0, _util.warn)('Unknown command "' + cmd + '"');
  2633. continue;
  2634. }
  2635. var fn = opSpec.id;
  2636. var numArgs = opSpec.numArgs;
  2637. var argsLength = args !== null ? args.length : 0;
  2638. if (!opSpec.variableArgs) {
  2639. if (argsLength !== numArgs) {
  2640. var nonProcessedArgs = this.nonProcessedArgs;
  2641. while (argsLength > numArgs) {
  2642. nonProcessedArgs.push(args.shift());
  2643. argsLength--;
  2644. }
  2645. while (argsLength < numArgs && nonProcessedArgs.length !== 0) {
  2646. if (args === null) {
  2647. args = [];
  2648. }
  2649. args.unshift(nonProcessedArgs.pop());
  2650. argsLength++;
  2651. }
  2652. }
  2653. if (argsLength < numArgs) {
  2654. (0, _util.warn)('Skipping command ' + fn + ': expected ' + numArgs + ' args, but received ' + argsLength + ' args.');
  2655. if (args !== null) {
  2656. args.length = 0;
  2657. }
  2658. continue;
  2659. }
  2660. } else if (argsLength > numArgs) {
  2661. (0, _util.info)('Command ' + fn + ': expected [0,' + numArgs + '] args, but received ' + argsLength + ' args.');
  2662. }
  2663. this.preprocessCommand(fn, args);
  2664. operation.fn = fn;
  2665. operation.args = args;
  2666. return true;
  2667. }
  2668. if ((0, _primitives.isEOF)(obj)) {
  2669. return false;
  2670. }
  2671. if (obj !== null) {
  2672. if (args === null) {
  2673. args = [];
  2674. }
  2675. args.push(obj);
  2676. if (args.length > 33) {
  2677. throw new _util.FormatError('Too many arguments');
  2678. }
  2679. }
  2680. }
  2681. },
  2682. preprocessCommand: function EvaluatorPreprocessor_preprocessCommand(fn, args) {
  2683. switch (fn | 0) {
  2684. case _util.OPS.save:
  2685. this.stateManager.save();
  2686. break;
  2687. case _util.OPS.restore:
  2688. this.stateManager.restore();
  2689. break;
  2690. case _util.OPS.transform:
  2691. this.stateManager.transform(args);
  2692. break;
  2693. }
  2694. }
  2695. };
  2696. return EvaluatorPreprocessor;
  2697. }();
  2698. exports.PartialEvaluator = PartialEvaluator;