2
0

evaluator.js 110 KB

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