evaluator.js 111 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117
  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. if (args[0].code) {
  720. break;
  721. }
  722. var name = args[0].name;
  723. if (!name) {
  724. (0, _util.warn)('XObject must be referred to by name.');
  725. continue;
  726. }
  727. if (imageCache[name] !== undefined) {
  728. operatorList.addOp(imageCache[name].fn, imageCache[name].args);
  729. args = null;
  730. continue;
  731. }
  732. var xobj = xobjs.get(name);
  733. if (xobj) {
  734. if (!(0, _primitives.isStream)(xobj)) {
  735. throw new _util.FormatError('XObject should be a stream');
  736. }
  737. var type = xobj.dict.get('Subtype');
  738. if (!(0, _primitives.isName)(type)) {
  739. throw new _util.FormatError('XObject should have a Name subtype');
  740. }
  741. if (type.name === 'Form') {
  742. stateManager.save();
  743. next(self.buildFormXObject(resources, xobj, null, operatorList, task, stateManager.state.clone()).then(function () {
  744. stateManager.restore();
  745. }));
  746. return;
  747. } else if (type.name === 'Image') {
  748. self.buildPaintImageXObject(resources, xobj, false, operatorList, name, imageCache);
  749. args = null;
  750. continue;
  751. } else if (type.name === 'PS') {
  752. (0, _util.info)('Ignored XObject subtype PS');
  753. continue;
  754. } else {
  755. throw new _util.FormatError('Unhandled XObject subtype ' + type.name);
  756. }
  757. }
  758. break;
  759. case _util.OPS.setFont:
  760. var fontSize = args[1];
  761. next(self.handleSetFont(resources, args, null, operatorList, task, stateManager.state).then(function (loadedName) {
  762. operatorList.addDependency(loadedName);
  763. operatorList.addOp(_util.OPS.setFont, [loadedName, fontSize]);
  764. }));
  765. return;
  766. case _util.OPS.endInlineImage:
  767. var cacheKey = args[0].cacheKey;
  768. if (cacheKey) {
  769. var cacheEntry = imageCache[cacheKey];
  770. if (cacheEntry !== undefined) {
  771. operatorList.addOp(cacheEntry.fn, cacheEntry.args);
  772. args = null;
  773. continue;
  774. }
  775. }
  776. self.buildPaintImageXObject(resources, args[0], true, operatorList, cacheKey, imageCache);
  777. args = null;
  778. continue;
  779. case _util.OPS.showText:
  780. args[0] = self.handleText(args[0], stateManager.state);
  781. break;
  782. case _util.OPS.showSpacedText:
  783. var arr = args[0];
  784. var combinedGlyphs = [];
  785. var arrLength = arr.length;
  786. var state = stateManager.state;
  787. for (i = 0; i < arrLength; ++i) {
  788. var arrItem = arr[i];
  789. if ((0, _util.isString)(arrItem)) {
  790. Array.prototype.push.apply(combinedGlyphs, self.handleText(arrItem, state));
  791. } else if ((0, _util.isNum)(arrItem)) {
  792. combinedGlyphs.push(arrItem);
  793. }
  794. }
  795. args[0] = combinedGlyphs;
  796. fn = _util.OPS.showText;
  797. break;
  798. case _util.OPS.nextLineShowText:
  799. operatorList.addOp(_util.OPS.nextLine);
  800. args[0] = self.handleText(args[0], stateManager.state);
  801. fn = _util.OPS.showText;
  802. break;
  803. case _util.OPS.nextLineSetSpacingShowText:
  804. operatorList.addOp(_util.OPS.nextLine);
  805. operatorList.addOp(_util.OPS.setWordSpacing, [args.shift()]);
  806. operatorList.addOp(_util.OPS.setCharSpacing, [args.shift()]);
  807. args[0] = self.handleText(args[0], stateManager.state);
  808. fn = _util.OPS.showText;
  809. break;
  810. case _util.OPS.setTextRenderingMode:
  811. stateManager.state.textRenderingMode = args[0];
  812. break;
  813. case _util.OPS.setFillColorSpace:
  814. stateManager.state.fillColorSpace = _colorspace.ColorSpace.parse(args[0], xref, resources);
  815. continue;
  816. case _util.OPS.setStrokeColorSpace:
  817. stateManager.state.strokeColorSpace = _colorspace.ColorSpace.parse(args[0], xref, resources);
  818. continue;
  819. case _util.OPS.setFillColor:
  820. cs = stateManager.state.fillColorSpace;
  821. args = cs.getRgb(args, 0);
  822. fn = _util.OPS.setFillRGBColor;
  823. break;
  824. case _util.OPS.setStrokeColor:
  825. cs = stateManager.state.strokeColorSpace;
  826. args = cs.getRgb(args, 0);
  827. fn = _util.OPS.setStrokeRGBColor;
  828. break;
  829. case _util.OPS.setFillGray:
  830. stateManager.state.fillColorSpace = _colorspace.ColorSpace.singletons.gray;
  831. args = _colorspace.ColorSpace.singletons.gray.getRgb(args, 0);
  832. fn = _util.OPS.setFillRGBColor;
  833. break;
  834. case _util.OPS.setStrokeGray:
  835. stateManager.state.strokeColorSpace = _colorspace.ColorSpace.singletons.gray;
  836. args = _colorspace.ColorSpace.singletons.gray.getRgb(args, 0);
  837. fn = _util.OPS.setStrokeRGBColor;
  838. break;
  839. case _util.OPS.setFillCMYKColor:
  840. stateManager.state.fillColorSpace = _colorspace.ColorSpace.singletons.cmyk;
  841. args = _colorspace.ColorSpace.singletons.cmyk.getRgb(args, 0);
  842. fn = _util.OPS.setFillRGBColor;
  843. break;
  844. case _util.OPS.setStrokeCMYKColor:
  845. stateManager.state.strokeColorSpace = _colorspace.ColorSpace.singletons.cmyk;
  846. args = _colorspace.ColorSpace.singletons.cmyk.getRgb(args, 0);
  847. fn = _util.OPS.setStrokeRGBColor;
  848. break;
  849. case _util.OPS.setFillRGBColor:
  850. stateManager.state.fillColorSpace = _colorspace.ColorSpace.singletons.rgb;
  851. args = _colorspace.ColorSpace.singletons.rgb.getRgb(args, 0);
  852. break;
  853. case _util.OPS.setStrokeRGBColor:
  854. stateManager.state.strokeColorSpace = _colorspace.ColorSpace.singletons.rgb;
  855. args = _colorspace.ColorSpace.singletons.rgb.getRgb(args, 0);
  856. break;
  857. case _util.OPS.setFillColorN:
  858. cs = stateManager.state.fillColorSpace;
  859. if (cs.name === 'Pattern') {
  860. next(self.handleColorN(operatorList, _util.OPS.setFillColorN, args, cs, patterns, resources, task));
  861. return;
  862. }
  863. args = cs.getRgb(args, 0);
  864. fn = _util.OPS.setFillRGBColor;
  865. break;
  866. case _util.OPS.setStrokeColorN:
  867. cs = stateManager.state.strokeColorSpace;
  868. if (cs.name === 'Pattern') {
  869. next(self.handleColorN(operatorList, _util.OPS.setStrokeColorN, args, cs, patterns, resources, task));
  870. return;
  871. }
  872. args = cs.getRgb(args, 0);
  873. fn = _util.OPS.setStrokeRGBColor;
  874. break;
  875. case _util.OPS.shadingFill:
  876. var shadingRes = resources.get('Shading');
  877. if (!shadingRes) {
  878. throw new _util.FormatError('No shading resource found');
  879. }
  880. var shading = shadingRes.get(args[0].name);
  881. if (!shading) {
  882. throw new _util.FormatError('No shading object found');
  883. }
  884. var shadingFill = _pattern.Pattern.parseShading(shading, null, xref, resources, self.handler);
  885. var patternIR = shadingFill.getIR();
  886. args = [patternIR];
  887. fn = _util.OPS.shadingFill;
  888. break;
  889. case _util.OPS.setGState:
  890. var dictName = args[0];
  891. var extGState = resources.get('ExtGState');
  892. if (!(0, _primitives.isDict)(extGState) || !extGState.has(dictName.name)) {
  893. break;
  894. }
  895. var gState = extGState.get(dictName.name);
  896. next(self.setGState(resources, gState, operatorList, task, stateManager));
  897. return;
  898. case _util.OPS.moveTo:
  899. case _util.OPS.lineTo:
  900. case _util.OPS.curveTo:
  901. case _util.OPS.curveTo2:
  902. case _util.OPS.curveTo3:
  903. case _util.OPS.closePath:
  904. self.buildPath(operatorList, fn, args);
  905. continue;
  906. case _util.OPS.rectangle:
  907. self.buildPath(operatorList, fn, args);
  908. continue;
  909. case _util.OPS.markPoint:
  910. case _util.OPS.markPointProps:
  911. case _util.OPS.beginMarkedContent:
  912. case _util.OPS.beginMarkedContentProps:
  913. case _util.OPS.endMarkedContent:
  914. case _util.OPS.beginCompat:
  915. case _util.OPS.endCompat:
  916. continue;
  917. default:
  918. if (args !== null) {
  919. for (i = 0, ii = args.length; i < ii; i++) {
  920. if (args[i] instanceof _primitives.Dict) {
  921. break;
  922. }
  923. }
  924. if (i < ii) {
  925. (0, _util.warn)('getOperatorList - ignoring operator: ' + fn);
  926. continue;
  927. }
  928. }
  929. }
  930. operatorList.addOp(fn, args);
  931. }
  932. if (stop) {
  933. next(deferred);
  934. return;
  935. }
  936. closePendingRestoreOPS();
  937. resolve();
  938. }).catch(function (reason) {
  939. if (_this8.options.ignoreErrors) {
  940. _this8.handler.send('UnsupportedFeature', { featureId: _util.UNSUPPORTED_FEATURES.unknown });
  941. (0, _util.warn)('getOperatorList - ignoring errors during task: ' + task.name);
  942. closePendingRestoreOPS();
  943. return;
  944. }
  945. throw reason;
  946. });
  947. },
  948. getTextContent: function getTextContent(_ref3) {
  949. var _this9 = this;
  950. var stream = _ref3.stream,
  951. task = _ref3.task,
  952. resources = _ref3.resources,
  953. _ref3$stateManager = _ref3.stateManager,
  954. stateManager = _ref3$stateManager === undefined ? null : _ref3$stateManager,
  955. _ref3$normalizeWhites = _ref3.normalizeWhitespace,
  956. normalizeWhitespace = _ref3$normalizeWhites === undefined ? false : _ref3$normalizeWhites,
  957. _ref3$combineTextItem = _ref3.combineTextItems,
  958. combineTextItems = _ref3$combineTextItem === undefined ? false : _ref3$combineTextItem,
  959. sink = _ref3.sink,
  960. _ref3$seenStyles = _ref3.seenStyles,
  961. seenStyles = _ref3$seenStyles === undefined ? Object.create(null) : _ref3$seenStyles;
  962. resources = resources || _primitives.Dict.empty;
  963. stateManager = stateManager || new StateManager(new TextState());
  964. var WhitespaceRegexp = /\s/g;
  965. var textContent = {
  966. items: [],
  967. styles: Object.create(null)
  968. };
  969. var textContentItem = {
  970. initialized: false,
  971. str: [],
  972. width: 0,
  973. height: 0,
  974. vertical: false,
  975. lastAdvanceWidth: 0,
  976. lastAdvanceHeight: 0,
  977. textAdvanceScale: 0,
  978. spaceWidth: 0,
  979. fakeSpaceMin: Infinity,
  980. fakeMultiSpaceMin: Infinity,
  981. fakeMultiSpaceMax: -0,
  982. textRunBreakAllowed: false,
  983. transform: null,
  984. fontName: null
  985. };
  986. var SPACE_FACTOR = 0.3;
  987. var MULTI_SPACE_FACTOR = 1.5;
  988. var MULTI_SPACE_FACTOR_MAX = 4;
  989. var self = this;
  990. var xref = this.xref;
  991. var xobjs = null;
  992. var skipEmptyXObjs = Object.create(null);
  993. var preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);
  994. var textState;
  995. function ensureTextContentItem() {
  996. if (textContentItem.initialized) {
  997. return textContentItem;
  998. }
  999. var font = textState.font;
  1000. if (!(font.loadedName in seenStyles)) {
  1001. seenStyles[font.loadedName] = true;
  1002. textContent.styles[font.loadedName] = {
  1003. fontFamily: font.fallbackName,
  1004. ascent: font.ascent,
  1005. descent: font.descent,
  1006. vertical: font.vertical
  1007. };
  1008. }
  1009. textContentItem.fontName = font.loadedName;
  1010. var tsm = [textState.fontSize * textState.textHScale, 0, 0, textState.fontSize, 0, textState.textRise];
  1011. if (font.isType3Font && textState.fontMatrix !== _util.FONT_IDENTITY_MATRIX && textState.fontSize === 1) {
  1012. var glyphHeight = font.bbox[3] - font.bbox[1];
  1013. if (glyphHeight > 0) {
  1014. glyphHeight = glyphHeight * textState.fontMatrix[3];
  1015. tsm[3] *= glyphHeight;
  1016. }
  1017. }
  1018. var trm = _util.Util.transform(textState.ctm, _util.Util.transform(textState.textMatrix, tsm));
  1019. textContentItem.transform = trm;
  1020. if (!font.vertical) {
  1021. textContentItem.width = 0;
  1022. textContentItem.height = Math.sqrt(trm[2] * trm[2] + trm[3] * trm[3]);
  1023. textContentItem.vertical = false;
  1024. } else {
  1025. textContentItem.width = Math.sqrt(trm[0] * trm[0] + trm[1] * trm[1]);
  1026. textContentItem.height = 0;
  1027. textContentItem.vertical = true;
  1028. }
  1029. var a = textState.textLineMatrix[0];
  1030. var b = textState.textLineMatrix[1];
  1031. var scaleLineX = Math.sqrt(a * a + b * b);
  1032. a = textState.ctm[0];
  1033. b = textState.ctm[1];
  1034. var scaleCtmX = Math.sqrt(a * a + b * b);
  1035. textContentItem.textAdvanceScale = scaleCtmX * scaleLineX;
  1036. textContentItem.lastAdvanceWidth = 0;
  1037. textContentItem.lastAdvanceHeight = 0;
  1038. var spaceWidth = font.spaceWidth / 1000 * textState.fontSize;
  1039. if (spaceWidth) {
  1040. textContentItem.spaceWidth = spaceWidth;
  1041. textContentItem.fakeSpaceMin = spaceWidth * SPACE_FACTOR;
  1042. textContentItem.fakeMultiSpaceMin = spaceWidth * MULTI_SPACE_FACTOR;
  1043. textContentItem.fakeMultiSpaceMax = spaceWidth * MULTI_SPACE_FACTOR_MAX;
  1044. textContentItem.textRunBreakAllowed = !font.isMonospace;
  1045. } else {
  1046. textContentItem.spaceWidth = 0;
  1047. textContentItem.fakeSpaceMin = Infinity;
  1048. textContentItem.fakeMultiSpaceMin = Infinity;
  1049. textContentItem.fakeMultiSpaceMax = 0;
  1050. textContentItem.textRunBreakAllowed = false;
  1051. }
  1052. textContentItem.initialized = true;
  1053. return textContentItem;
  1054. }
  1055. function replaceWhitespace(str) {
  1056. var i = 0,
  1057. ii = str.length,
  1058. code;
  1059. while (i < ii && (code = str.charCodeAt(i)) >= 0x20 && code <= 0x7F) {
  1060. i++;
  1061. }
  1062. return i < ii ? str.replace(WhitespaceRegexp, ' ') : str;
  1063. }
  1064. function runBidiTransform(textChunk) {
  1065. var str = textChunk.str.join('');
  1066. var bidiResult = (0, _bidi.bidi)(str, -1, textChunk.vertical);
  1067. return {
  1068. str: normalizeWhitespace ? replaceWhitespace(bidiResult.str) : bidiResult.str,
  1069. dir: bidiResult.dir,
  1070. width: textChunk.width,
  1071. height: textChunk.height,
  1072. transform: textChunk.transform,
  1073. fontName: textChunk.fontName
  1074. };
  1075. }
  1076. function handleSetFont(fontName, fontRef) {
  1077. return self.loadFont(fontName, fontRef, resources).then(function (translated) {
  1078. textState.font = translated.font;
  1079. textState.fontMatrix = translated.font.fontMatrix || _util.FONT_IDENTITY_MATRIX;
  1080. });
  1081. }
  1082. function buildTextContentItem(chars) {
  1083. var font = textState.font;
  1084. var textChunk = ensureTextContentItem();
  1085. var width = 0;
  1086. var height = 0;
  1087. var glyphs = font.charsToGlyphs(chars);
  1088. for (var i = 0; i < glyphs.length; i++) {
  1089. var glyph = glyphs[i];
  1090. var glyphWidth = null;
  1091. if (font.vertical && glyph.vmetric) {
  1092. glyphWidth = glyph.vmetric[0];
  1093. } else {
  1094. glyphWidth = glyph.width;
  1095. }
  1096. var glyphUnicode = glyph.unicode;
  1097. var NormalizedUnicodes = (0, _unicode.getNormalizedUnicodes)();
  1098. if (NormalizedUnicodes[glyphUnicode] !== undefined) {
  1099. glyphUnicode = NormalizedUnicodes[glyphUnicode];
  1100. }
  1101. glyphUnicode = (0, _unicode.reverseIfRtl)(glyphUnicode);
  1102. var charSpacing = textState.charSpacing;
  1103. if (glyph.isSpace) {
  1104. var wordSpacing = textState.wordSpacing;
  1105. charSpacing += wordSpacing;
  1106. if (wordSpacing > 0) {
  1107. addFakeSpaces(wordSpacing, textChunk.str);
  1108. }
  1109. }
  1110. var tx = 0;
  1111. var ty = 0;
  1112. if (!font.vertical) {
  1113. var w0 = glyphWidth * textState.fontMatrix[0];
  1114. tx = (w0 * textState.fontSize + charSpacing) * textState.textHScale;
  1115. width += tx;
  1116. } else {
  1117. var w1 = glyphWidth * textState.fontMatrix[0];
  1118. ty = w1 * textState.fontSize + charSpacing;
  1119. height += ty;
  1120. }
  1121. textState.translateTextMatrix(tx, ty);
  1122. textChunk.str.push(glyphUnicode);
  1123. }
  1124. if (!font.vertical) {
  1125. textChunk.lastAdvanceWidth = width;
  1126. textChunk.width += width;
  1127. } else {
  1128. textChunk.lastAdvanceHeight = height;
  1129. textChunk.height += Math.abs(height);
  1130. }
  1131. return textChunk;
  1132. }
  1133. function addFakeSpaces(width, strBuf) {
  1134. if (width < textContentItem.fakeSpaceMin) {
  1135. return;
  1136. }
  1137. if (width < textContentItem.fakeMultiSpaceMin) {
  1138. strBuf.push(' ');
  1139. return;
  1140. }
  1141. var fakeSpaces = Math.round(width / textContentItem.spaceWidth);
  1142. while (fakeSpaces-- > 0) {
  1143. strBuf.push(' ');
  1144. }
  1145. }
  1146. function flushTextContentItem() {
  1147. if (!textContentItem.initialized) {
  1148. return;
  1149. }
  1150. textContentItem.width *= textContentItem.textAdvanceScale;
  1151. textContentItem.height *= textContentItem.textAdvanceScale;
  1152. textContent.items.push(runBidiTransform(textContentItem));
  1153. textContentItem.initialized = false;
  1154. textContentItem.str.length = 0;
  1155. }
  1156. function enqueueChunk() {
  1157. var length = textContent.items.length;
  1158. if (length > 0) {
  1159. sink.enqueue(textContent, length);
  1160. textContent.items = [];
  1161. textContent.styles = Object.create(null);
  1162. }
  1163. }
  1164. var timeSlotManager = new TimeSlotManager();
  1165. return new Promise(function promiseBody(resolve, reject) {
  1166. var next = function next(promise) {
  1167. enqueueChunk();
  1168. Promise.all([promise, sink.ready]).then(function () {
  1169. try {
  1170. promiseBody(resolve, reject);
  1171. } catch (ex) {
  1172. reject(ex);
  1173. }
  1174. }, reject);
  1175. };
  1176. task.ensureNotTerminated();
  1177. timeSlotManager.reset();
  1178. var stop,
  1179. operation = {},
  1180. args = [];
  1181. while (!(stop = timeSlotManager.check())) {
  1182. args.length = 0;
  1183. operation.args = args;
  1184. if (!preprocessor.read(operation)) {
  1185. break;
  1186. }
  1187. textState = stateManager.state;
  1188. var fn = operation.fn;
  1189. args = operation.args;
  1190. var advance, diff;
  1191. var fontNameArg, fontSizeArg;
  1192. var isSameTextLine;
  1193. var items;
  1194. var offset;
  1195. var j, jj;
  1196. var breakTextRun;
  1197. var name;
  1198. var xobj;
  1199. var type;
  1200. var currentState;
  1201. var xObjStateManager;
  1202. var matrix;
  1203. var dictName;
  1204. var extGState;
  1205. var gState;
  1206. var gStateFont;
  1207. var _ret2 = function () {
  1208. switch (fn | 0) {
  1209. case _util.OPS.setFont:
  1210. fontNameArg = args[0].name;
  1211. fontSizeArg = args[1];
  1212. if (textState.font && fontNameArg === textState.fontName && fontSizeArg === textState.fontSize) {
  1213. break;
  1214. }
  1215. flushTextContentItem();
  1216. textState.fontName = fontNameArg;
  1217. textState.fontSize = fontSizeArg;
  1218. next(handleSetFont(fontNameArg, null));
  1219. return {
  1220. v: void 0
  1221. };
  1222. case _util.OPS.setTextRise:
  1223. flushTextContentItem();
  1224. textState.textRise = args[0];
  1225. break;
  1226. case _util.OPS.setHScale:
  1227. flushTextContentItem();
  1228. textState.textHScale = args[0] / 100;
  1229. break;
  1230. case _util.OPS.setLeading:
  1231. flushTextContentItem();
  1232. textState.leading = args[0];
  1233. break;
  1234. case _util.OPS.moveText:
  1235. isSameTextLine = !textState.font ? false : (textState.font.vertical ? args[0] : args[1]) === 0;
  1236. advance = args[0] - args[1];
  1237. if (combineTextItems && isSameTextLine && textContentItem.initialized && advance > 0 && advance <= textContentItem.fakeMultiSpaceMax) {
  1238. textState.translateTextLineMatrix(args[0], args[1]);
  1239. textContentItem.width += args[0] - textContentItem.lastAdvanceWidth;
  1240. textContentItem.height += args[1] - textContentItem.lastAdvanceHeight;
  1241. diff = args[0] - textContentItem.lastAdvanceWidth - (args[1] - textContentItem.lastAdvanceHeight);
  1242. addFakeSpaces(diff, textContentItem.str);
  1243. break;
  1244. }
  1245. flushTextContentItem();
  1246. textState.translateTextLineMatrix(args[0], args[1]);
  1247. textState.textMatrix = textState.textLineMatrix.slice();
  1248. break;
  1249. case _util.OPS.setLeadingMoveText:
  1250. flushTextContentItem();
  1251. textState.leading = -args[1];
  1252. textState.translateTextLineMatrix(args[0], args[1]);
  1253. textState.textMatrix = textState.textLineMatrix.slice();
  1254. break;
  1255. case _util.OPS.nextLine:
  1256. flushTextContentItem();
  1257. textState.carriageReturn();
  1258. break;
  1259. case _util.OPS.setTextMatrix:
  1260. advance = textState.calcTextLineMatrixAdvance(args[0], args[1], args[2], args[3], args[4], args[5]);
  1261. if (combineTextItems && advance !== null && textContentItem.initialized && advance.value > 0 && advance.value <= textContentItem.fakeMultiSpaceMax) {
  1262. textState.translateTextLineMatrix(advance.width, advance.height);
  1263. textContentItem.width += advance.width - textContentItem.lastAdvanceWidth;
  1264. textContentItem.height += advance.height - textContentItem.lastAdvanceHeight;
  1265. diff = advance.width - textContentItem.lastAdvanceWidth - (advance.height - textContentItem.lastAdvanceHeight);
  1266. addFakeSpaces(diff, textContentItem.str);
  1267. break;
  1268. }
  1269. flushTextContentItem();
  1270. textState.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  1271. textState.setTextLineMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  1272. break;
  1273. case _util.OPS.setCharSpacing:
  1274. textState.charSpacing = args[0];
  1275. break;
  1276. case _util.OPS.setWordSpacing:
  1277. textState.wordSpacing = args[0];
  1278. break;
  1279. case _util.OPS.beginText:
  1280. flushTextContentItem();
  1281. textState.textMatrix = _util.IDENTITY_MATRIX.slice();
  1282. textState.textLineMatrix = _util.IDENTITY_MATRIX.slice();
  1283. break;
  1284. case _util.OPS.showSpacedText:
  1285. items = args[0];
  1286. for (j = 0, jj = items.length; j < jj; j++) {
  1287. if (typeof items[j] === 'string') {
  1288. buildTextContentItem(items[j]);
  1289. } else if ((0, _util.isNum)(items[j])) {
  1290. ensureTextContentItem();
  1291. advance = items[j] * textState.fontSize / 1000;
  1292. breakTextRun = false;
  1293. if (textState.font.vertical) {
  1294. offset = advance;
  1295. textState.translateTextMatrix(0, offset);
  1296. breakTextRun = textContentItem.textRunBreakAllowed && advance > textContentItem.fakeMultiSpaceMax;
  1297. if (!breakTextRun) {
  1298. textContentItem.height += offset;
  1299. }
  1300. } else {
  1301. advance = -advance;
  1302. offset = advance * textState.textHScale;
  1303. textState.translateTextMatrix(offset, 0);
  1304. breakTextRun = textContentItem.textRunBreakAllowed && advance > textContentItem.fakeMultiSpaceMax;
  1305. if (!breakTextRun) {
  1306. textContentItem.width += offset;
  1307. }
  1308. }
  1309. if (breakTextRun) {
  1310. flushTextContentItem();
  1311. } else if (advance > 0) {
  1312. addFakeSpaces(advance, textContentItem.str);
  1313. }
  1314. }
  1315. }
  1316. break;
  1317. case _util.OPS.showText:
  1318. buildTextContentItem(args[0]);
  1319. break;
  1320. case _util.OPS.nextLineShowText:
  1321. flushTextContentItem();
  1322. textState.carriageReturn();
  1323. buildTextContentItem(args[0]);
  1324. break;
  1325. case _util.OPS.nextLineSetSpacingShowText:
  1326. flushTextContentItem();
  1327. textState.wordSpacing = args[0];
  1328. textState.charSpacing = args[1];
  1329. textState.carriageReturn();
  1330. buildTextContentItem(args[2]);
  1331. break;
  1332. case _util.OPS.paintXObject:
  1333. flushTextContentItem();
  1334. if (args[0].code) {
  1335. break;
  1336. }
  1337. if (!xobjs) {
  1338. xobjs = resources.get('XObject') || _primitives.Dict.empty;
  1339. }
  1340. name = args[0].name;
  1341. if (name in skipEmptyXObjs) {
  1342. break;
  1343. }
  1344. xobj = xobjs.get(name);
  1345. if (!xobj) {
  1346. break;
  1347. }
  1348. if (!(0, _primitives.isStream)(xobj)) {
  1349. throw new _util.FormatError('XObject should be a stream');
  1350. }
  1351. type = xobj.dict.get('Subtype');
  1352. if (!(0, _primitives.isName)(type)) {
  1353. throw new _util.FormatError('XObject should have a Name subtype');
  1354. }
  1355. if (type.name !== 'Form') {
  1356. skipEmptyXObjs[name] = true;
  1357. break;
  1358. }
  1359. currentState = stateManager.state.clone();
  1360. xObjStateManager = new StateManager(currentState);
  1361. matrix = xobj.dict.getArray('Matrix');
  1362. if ((0, _util.isArray)(matrix) && matrix.length === 6) {
  1363. xObjStateManager.transform(matrix);
  1364. }
  1365. enqueueChunk();
  1366. var sinkWrapper = {
  1367. enqueueInvoked: false,
  1368. enqueue: function enqueue(chunk, size) {
  1369. this.enqueueInvoked = true;
  1370. sink.enqueue(chunk, size);
  1371. },
  1372. get desiredSize() {
  1373. return sink.desiredSize;
  1374. },
  1375. get ready() {
  1376. return sink.ready;
  1377. }
  1378. };
  1379. next(self.getTextContent({
  1380. stream: xobj,
  1381. task: task,
  1382. resources: xobj.dict.get('Resources') || resources,
  1383. stateManager: xObjStateManager,
  1384. normalizeWhitespace: normalizeWhitespace,
  1385. combineTextItems: combineTextItems,
  1386. sink: sinkWrapper,
  1387. seenStyles: seenStyles
  1388. }).then(function () {
  1389. if (!sinkWrapper.enqueueInvoked) {
  1390. skipEmptyXObjs[name] = true;
  1391. }
  1392. }));
  1393. return {
  1394. v: void 0
  1395. };
  1396. case _util.OPS.setGState:
  1397. flushTextContentItem();
  1398. dictName = args[0];
  1399. extGState = resources.get('ExtGState');
  1400. if (!(0, _primitives.isDict)(extGState) || !(0, _primitives.isName)(dictName)) {
  1401. break;
  1402. }
  1403. gState = extGState.get(dictName.name);
  1404. if (!(0, _primitives.isDict)(gState)) {
  1405. break;
  1406. }
  1407. gStateFont = gState.get('Font');
  1408. if (gStateFont) {
  1409. textState.fontName = null;
  1410. textState.fontSize = gStateFont[1];
  1411. next(handleSetFont(null, gStateFont[0]));
  1412. return {
  1413. v: void 0
  1414. };
  1415. }
  1416. break;
  1417. }
  1418. }();
  1419. if ((typeof _ret2 === 'undefined' ? 'undefined' : _typeof(_ret2)) === "object") return _ret2.v;
  1420. if (textContent.items.length >= sink.desiredSize) {
  1421. stop = true;
  1422. break;
  1423. }
  1424. }
  1425. if (stop) {
  1426. next(deferred);
  1427. return;
  1428. }
  1429. flushTextContentItem();
  1430. enqueueChunk();
  1431. resolve();
  1432. }).catch(function (reason) {
  1433. if (reason instanceof _util.AbortException) {
  1434. return;
  1435. }
  1436. if (_this9.options.ignoreErrors) {
  1437. (0, _util.warn)('getTextContent - ignoring errors during task: ' + task.name);
  1438. flushTextContentItem();
  1439. enqueueChunk();
  1440. return;
  1441. }
  1442. throw reason;
  1443. });
  1444. },
  1445. extractDataStructures: function PartialEvaluator_extractDataStructures(dict, baseDict, properties) {
  1446. var _this10 = this;
  1447. var xref = this.xref;
  1448. var toUnicode = dict.get('ToUnicode') || baseDict.get('ToUnicode');
  1449. var toUnicodePromise = toUnicode ? this.readToUnicode(toUnicode) : Promise.resolve(undefined);
  1450. if (properties.composite) {
  1451. var cidSystemInfo = dict.get('CIDSystemInfo');
  1452. if ((0, _primitives.isDict)(cidSystemInfo)) {
  1453. properties.cidSystemInfo = {
  1454. registry: cidSystemInfo.get('Registry'),
  1455. ordering: cidSystemInfo.get('Ordering'),
  1456. supplement: cidSystemInfo.get('Supplement')
  1457. };
  1458. }
  1459. var cidToGidMap = dict.get('CIDToGIDMap');
  1460. if ((0, _primitives.isStream)(cidToGidMap)) {
  1461. properties.cidToGidMap = this.readCidToGidMap(cidToGidMap);
  1462. }
  1463. }
  1464. var differences = [];
  1465. var baseEncodingName = null;
  1466. var encoding;
  1467. if (dict.has('Encoding')) {
  1468. encoding = dict.get('Encoding');
  1469. if ((0, _primitives.isDict)(encoding)) {
  1470. baseEncodingName = encoding.get('BaseEncoding');
  1471. baseEncodingName = (0, _primitives.isName)(baseEncodingName) ? baseEncodingName.name : null;
  1472. if (encoding.has('Differences')) {
  1473. var diffEncoding = encoding.get('Differences');
  1474. var index = 0;
  1475. for (var j = 0, jj = diffEncoding.length; j < jj; j++) {
  1476. var data = xref.fetchIfRef(diffEncoding[j]);
  1477. if ((0, _util.isNum)(data)) {
  1478. index = data;
  1479. } else if ((0, _primitives.isName)(data)) {
  1480. differences[index++] = data.name;
  1481. } else {
  1482. throw new _util.FormatError('Invalid entry in \'Differences\' array: ' + data);
  1483. }
  1484. }
  1485. }
  1486. } else if ((0, _primitives.isName)(encoding)) {
  1487. baseEncodingName = encoding.name;
  1488. } else {
  1489. throw new _util.FormatError('Encoding is not a Name nor a Dict');
  1490. }
  1491. if (baseEncodingName !== 'MacRomanEncoding' && baseEncodingName !== 'MacExpertEncoding' && baseEncodingName !== 'WinAnsiEncoding') {
  1492. baseEncodingName = null;
  1493. }
  1494. }
  1495. if (baseEncodingName) {
  1496. properties.defaultEncoding = (0, _encodings.getEncoding)(baseEncodingName).slice();
  1497. } else {
  1498. var isSymbolicFont = !!(properties.flags & _fonts.FontFlags.Symbolic);
  1499. var isNonsymbolicFont = !!(properties.flags & _fonts.FontFlags.Nonsymbolic);
  1500. encoding = _encodings.StandardEncoding;
  1501. if (properties.type === 'TrueType' && !isNonsymbolicFont) {
  1502. encoding = _encodings.WinAnsiEncoding;
  1503. }
  1504. if (isSymbolicFont) {
  1505. encoding = _encodings.MacRomanEncoding;
  1506. if (!properties.file) {
  1507. if (/Symbol/i.test(properties.name)) {
  1508. encoding = _encodings.SymbolSetEncoding;
  1509. } else if (/Dingbats/i.test(properties.name)) {
  1510. encoding = _encodings.ZapfDingbatsEncoding;
  1511. }
  1512. }
  1513. }
  1514. properties.defaultEncoding = encoding;
  1515. }
  1516. properties.differences = differences;
  1517. properties.baseEncodingName = baseEncodingName;
  1518. properties.hasEncoding = !!baseEncodingName || differences.length > 0;
  1519. properties.dict = dict;
  1520. return toUnicodePromise.then(function (toUnicode) {
  1521. properties.toUnicode = toUnicode;
  1522. return _this10.buildToUnicode(properties);
  1523. }).then(function (toUnicode) {
  1524. properties.toUnicode = toUnicode;
  1525. return properties;
  1526. });
  1527. },
  1528. buildToUnicode: function PartialEvaluator_buildToUnicode(properties) {
  1529. properties.hasIncludedToUnicodeMap = !!properties.toUnicode && properties.toUnicode.length > 0;
  1530. if (properties.hasIncludedToUnicodeMap) {
  1531. return Promise.resolve(properties.toUnicode);
  1532. }
  1533. var toUnicode, charcode, glyphName;
  1534. if (!properties.composite) {
  1535. toUnicode = [];
  1536. var encoding = properties.defaultEncoding.slice();
  1537. var baseEncodingName = properties.baseEncodingName;
  1538. var differences = properties.differences;
  1539. for (charcode in differences) {
  1540. glyphName = differences[charcode];
  1541. if (glyphName === '.notdef') {
  1542. continue;
  1543. }
  1544. encoding[charcode] = glyphName;
  1545. }
  1546. var glyphsUnicodeMap = (0, _glyphlist.getGlyphsUnicode)();
  1547. for (charcode in encoding) {
  1548. glyphName = encoding[charcode];
  1549. if (glyphName === '') {
  1550. continue;
  1551. } else if (glyphsUnicodeMap[glyphName] === undefined) {
  1552. var code = 0;
  1553. switch (glyphName[0]) {
  1554. case 'G':
  1555. if (glyphName.length === 3) {
  1556. code = parseInt(glyphName.substr(1), 16);
  1557. }
  1558. break;
  1559. case 'g':
  1560. if (glyphName.length === 5) {
  1561. code = parseInt(glyphName.substr(1), 16);
  1562. }
  1563. break;
  1564. case 'C':
  1565. case 'c':
  1566. if (glyphName.length >= 3) {
  1567. code = +glyphName.substr(1);
  1568. }
  1569. break;
  1570. default:
  1571. var unicode = (0, _unicode.getUnicodeForGlyph)(glyphName, glyphsUnicodeMap);
  1572. if (unicode !== -1) {
  1573. code = unicode;
  1574. }
  1575. }
  1576. if (code) {
  1577. if (baseEncodingName && code === +charcode) {
  1578. var baseEncoding = (0, _encodings.getEncoding)(baseEncodingName);
  1579. if (baseEncoding && (glyphName = baseEncoding[charcode])) {
  1580. toUnicode[charcode] = String.fromCharCode(glyphsUnicodeMap[glyphName]);
  1581. continue;
  1582. }
  1583. }
  1584. toUnicode[charcode] = String.fromCharCode(code);
  1585. }
  1586. continue;
  1587. }
  1588. toUnicode[charcode] = String.fromCharCode(glyphsUnicodeMap[glyphName]);
  1589. }
  1590. return Promise.resolve(new _fonts.ToUnicodeMap(toUnicode));
  1591. }
  1592. 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'))) {
  1593. var registry = properties.cidSystemInfo.registry;
  1594. var ordering = properties.cidSystemInfo.ordering;
  1595. var ucs2CMapName = _primitives.Name.get(registry + '-' + ordering + '-UCS2');
  1596. return _cmap.CMapFactory.create({
  1597. encoding: ucs2CMapName,
  1598. fetchBuiltInCMap: this.fetchBuiltInCMap,
  1599. useCMap: null
  1600. }).then(function (ucs2CMap) {
  1601. var cMap = properties.cMap;
  1602. toUnicode = [];
  1603. cMap.forEach(function (charcode, cid) {
  1604. if (cid > 0xffff) {
  1605. throw new _util.FormatError('Max size of CID is 65,535');
  1606. }
  1607. var ucs2 = ucs2CMap.lookup(cid);
  1608. if (ucs2) {
  1609. toUnicode[charcode] = String.fromCharCode((ucs2.charCodeAt(0) << 8) + ucs2.charCodeAt(1));
  1610. }
  1611. });
  1612. return new _fonts.ToUnicodeMap(toUnicode);
  1613. });
  1614. }
  1615. return Promise.resolve(new _fonts.IdentityToUnicodeMap(properties.firstChar, properties.lastChar));
  1616. },
  1617. readToUnicode: function PartialEvaluator_readToUnicode(toUnicode) {
  1618. var cmapObj = toUnicode;
  1619. if ((0, _primitives.isName)(cmapObj)) {
  1620. return _cmap.CMapFactory.create({
  1621. encoding: cmapObj,
  1622. fetchBuiltInCMap: this.fetchBuiltInCMap,
  1623. useCMap: null
  1624. }).then(function (cmap) {
  1625. if (cmap instanceof _cmap.IdentityCMap) {
  1626. return new _fonts.IdentityToUnicodeMap(0, 0xFFFF);
  1627. }
  1628. return new _fonts.ToUnicodeMap(cmap.getMap());
  1629. });
  1630. } else if ((0, _primitives.isStream)(cmapObj)) {
  1631. return _cmap.CMapFactory.create({
  1632. encoding: cmapObj,
  1633. fetchBuiltInCMap: this.fetchBuiltInCMap,
  1634. useCMap: null
  1635. }).then(function (cmap) {
  1636. if (cmap instanceof _cmap.IdentityCMap) {
  1637. return new _fonts.IdentityToUnicodeMap(0, 0xFFFF);
  1638. }
  1639. var map = new Array(cmap.length);
  1640. cmap.forEach(function (charCode, token) {
  1641. var str = [];
  1642. for (var k = 0; k < token.length; k += 2) {
  1643. var w1 = token.charCodeAt(k) << 8 | token.charCodeAt(k + 1);
  1644. if ((w1 & 0xF800) !== 0xD800) {
  1645. str.push(w1);
  1646. continue;
  1647. }
  1648. k += 2;
  1649. var w2 = token.charCodeAt(k) << 8 | token.charCodeAt(k + 1);
  1650. str.push(((w1 & 0x3ff) << 10) + (w2 & 0x3ff) + 0x10000);
  1651. }
  1652. map[charCode] = String.fromCharCode.apply(String, str);
  1653. });
  1654. return new _fonts.ToUnicodeMap(map);
  1655. });
  1656. }
  1657. return Promise.resolve(null);
  1658. },
  1659. readCidToGidMap: function PartialEvaluator_readCidToGidMap(cidToGidStream) {
  1660. var glyphsData = cidToGidStream.getBytes();
  1661. var result = [];
  1662. for (var j = 0, jj = glyphsData.length; j < jj; j++) {
  1663. var glyphID = glyphsData[j++] << 8 | glyphsData[j];
  1664. if (glyphID === 0) {
  1665. continue;
  1666. }
  1667. var code = j >> 1;
  1668. result[code] = glyphID;
  1669. }
  1670. return result;
  1671. },
  1672. extractWidths: function PartialEvaluator_extractWidths(dict, descriptor, properties) {
  1673. var xref = this.xref;
  1674. var glyphsWidths = [];
  1675. var defaultWidth = 0;
  1676. var glyphsVMetrics = [];
  1677. var defaultVMetrics;
  1678. var i, ii, j, jj, start, code, widths;
  1679. if (properties.composite) {
  1680. defaultWidth = dict.get('DW') || 1000;
  1681. widths = dict.get('W');
  1682. if (widths) {
  1683. for (i = 0, ii = widths.length; i < ii; i++) {
  1684. start = xref.fetchIfRef(widths[i++]);
  1685. code = xref.fetchIfRef(widths[i]);
  1686. if ((0, _util.isArray)(code)) {
  1687. for (j = 0, jj = code.length; j < jj; j++) {
  1688. glyphsWidths[start++] = xref.fetchIfRef(code[j]);
  1689. }
  1690. } else {
  1691. var width = xref.fetchIfRef(widths[++i]);
  1692. for (j = start; j <= code; j++) {
  1693. glyphsWidths[j] = width;
  1694. }
  1695. }
  1696. }
  1697. }
  1698. if (properties.vertical) {
  1699. var vmetrics = dict.getArray('DW2') || [880, -1000];
  1700. defaultVMetrics = [vmetrics[1], defaultWidth * 0.5, vmetrics[0]];
  1701. vmetrics = dict.get('W2');
  1702. if (vmetrics) {
  1703. for (i = 0, ii = vmetrics.length; i < ii; i++) {
  1704. start = xref.fetchIfRef(vmetrics[i++]);
  1705. code = xref.fetchIfRef(vmetrics[i]);
  1706. if ((0, _util.isArray)(code)) {
  1707. for (j = 0, jj = code.length; j < jj; j++) {
  1708. glyphsVMetrics[start++] = [xref.fetchIfRef(code[j++]), xref.fetchIfRef(code[j++]), xref.fetchIfRef(code[j])];
  1709. }
  1710. } else {
  1711. var vmetric = [xref.fetchIfRef(vmetrics[++i]), xref.fetchIfRef(vmetrics[++i]), xref.fetchIfRef(vmetrics[++i])];
  1712. for (j = start; j <= code; j++) {
  1713. glyphsVMetrics[j] = vmetric;
  1714. }
  1715. }
  1716. }
  1717. }
  1718. }
  1719. } else {
  1720. var firstChar = properties.firstChar;
  1721. widths = dict.get('Widths');
  1722. if (widths) {
  1723. j = firstChar;
  1724. for (i = 0, ii = widths.length; i < ii; i++) {
  1725. glyphsWidths[j++] = xref.fetchIfRef(widths[i]);
  1726. }
  1727. defaultWidth = parseFloat(descriptor.get('MissingWidth')) || 0;
  1728. } else {
  1729. var baseFontName = dict.get('BaseFont');
  1730. if ((0, _primitives.isName)(baseFontName)) {
  1731. var metrics = this.getBaseFontMetrics(baseFontName.name);
  1732. glyphsWidths = this.buildCharCodeToWidth(metrics.widths, properties);
  1733. defaultWidth = metrics.defaultWidth;
  1734. }
  1735. }
  1736. }
  1737. var isMonospace = true;
  1738. var firstWidth = defaultWidth;
  1739. for (var glyph in glyphsWidths) {
  1740. var glyphWidth = glyphsWidths[glyph];
  1741. if (!glyphWidth) {
  1742. continue;
  1743. }
  1744. if (!firstWidth) {
  1745. firstWidth = glyphWidth;
  1746. continue;
  1747. }
  1748. if (firstWidth !== glyphWidth) {
  1749. isMonospace = false;
  1750. break;
  1751. }
  1752. }
  1753. if (isMonospace) {
  1754. properties.flags |= _fonts.FontFlags.FixedPitch;
  1755. }
  1756. properties.defaultWidth = defaultWidth;
  1757. properties.widths = glyphsWidths;
  1758. properties.defaultVMetrics = defaultVMetrics;
  1759. properties.vmetrics = glyphsVMetrics;
  1760. },
  1761. isSerifFont: function PartialEvaluator_isSerifFont(baseFontName) {
  1762. var fontNameWoStyle = baseFontName.split('-')[0];
  1763. return fontNameWoStyle in (0, _standard_fonts.getSerifFonts)() || fontNameWoStyle.search(/serif/gi) !== -1;
  1764. },
  1765. getBaseFontMetrics: function PartialEvaluator_getBaseFontMetrics(name) {
  1766. var defaultWidth = 0;
  1767. var widths = [];
  1768. var monospace = false;
  1769. var stdFontMap = (0, _standard_fonts.getStdFontMap)();
  1770. var lookupName = stdFontMap[name] || name;
  1771. var Metrics = (0, _metrics.getMetrics)();
  1772. if (!(lookupName in Metrics)) {
  1773. if (this.isSerifFont(name)) {
  1774. lookupName = 'Times-Roman';
  1775. } else {
  1776. lookupName = 'Helvetica';
  1777. }
  1778. }
  1779. var glyphWidths = Metrics[lookupName];
  1780. if ((0, _util.isNum)(glyphWidths)) {
  1781. defaultWidth = glyphWidths;
  1782. monospace = true;
  1783. } else {
  1784. widths = glyphWidths();
  1785. }
  1786. return {
  1787. defaultWidth: defaultWidth,
  1788. monospace: monospace,
  1789. widths: widths
  1790. };
  1791. },
  1792. buildCharCodeToWidth: function PartialEvaluator_bulildCharCodeToWidth(widthsByGlyphName, properties) {
  1793. var widths = Object.create(null);
  1794. var differences = properties.differences;
  1795. var encoding = properties.defaultEncoding;
  1796. for (var charCode = 0; charCode < 256; charCode++) {
  1797. if (charCode in differences && widthsByGlyphName[differences[charCode]]) {
  1798. widths[charCode] = widthsByGlyphName[differences[charCode]];
  1799. continue;
  1800. }
  1801. if (charCode in encoding && widthsByGlyphName[encoding[charCode]]) {
  1802. widths[charCode] = widthsByGlyphName[encoding[charCode]];
  1803. continue;
  1804. }
  1805. }
  1806. return widths;
  1807. },
  1808. preEvaluateFont: function PartialEvaluator_preEvaluateFont(dict) {
  1809. var baseDict = dict;
  1810. var type = dict.get('Subtype');
  1811. if (!(0, _primitives.isName)(type)) {
  1812. throw new _util.FormatError('invalid font Subtype');
  1813. }
  1814. var composite = false;
  1815. var uint8array;
  1816. if (type.name === 'Type0') {
  1817. var df = dict.get('DescendantFonts');
  1818. if (!df) {
  1819. throw new _util.FormatError('Descendant fonts are not specified');
  1820. }
  1821. dict = (0, _util.isArray)(df) ? this.xref.fetchIfRef(df[0]) : df;
  1822. type = dict.get('Subtype');
  1823. if (!(0, _primitives.isName)(type)) {
  1824. throw new _util.FormatError('invalid font Subtype');
  1825. }
  1826. composite = true;
  1827. }
  1828. var descriptor = dict.get('FontDescriptor');
  1829. if (descriptor) {
  1830. var hash = new _murmurhash.MurmurHash3_64();
  1831. var encoding = baseDict.getRaw('Encoding');
  1832. if ((0, _primitives.isName)(encoding)) {
  1833. hash.update(encoding.name);
  1834. } else if ((0, _primitives.isRef)(encoding)) {
  1835. hash.update(encoding.toString());
  1836. } else if ((0, _primitives.isDict)(encoding)) {
  1837. var keys = encoding.getKeys();
  1838. for (var i = 0, ii = keys.length; i < ii; i++) {
  1839. var entry = encoding.getRaw(keys[i]);
  1840. if ((0, _primitives.isName)(entry)) {
  1841. hash.update(entry.name);
  1842. } else if ((0, _primitives.isRef)(entry)) {
  1843. hash.update(entry.toString());
  1844. } else if ((0, _util.isArray)(entry)) {
  1845. var diffLength = entry.length,
  1846. diffBuf = new Array(diffLength);
  1847. for (var j = 0; j < diffLength; j++) {
  1848. var diffEntry = entry[j];
  1849. if ((0, _primitives.isName)(diffEntry)) {
  1850. diffBuf[j] = diffEntry.name;
  1851. } else if ((0, _util.isNum)(diffEntry) || (0, _primitives.isRef)(diffEntry)) {
  1852. diffBuf[j] = diffEntry.toString();
  1853. }
  1854. }
  1855. hash.update(diffBuf.join());
  1856. }
  1857. }
  1858. }
  1859. var toUnicode = dict.get('ToUnicode') || baseDict.get('ToUnicode');
  1860. if ((0, _primitives.isStream)(toUnicode)) {
  1861. var stream = toUnicode.str || toUnicode;
  1862. uint8array = stream.buffer ? new Uint8Array(stream.buffer.buffer, 0, stream.bufferLength) : new Uint8Array(stream.bytes.buffer, stream.start, stream.end - stream.start);
  1863. hash.update(uint8array);
  1864. } else if ((0, _primitives.isName)(toUnicode)) {
  1865. hash.update(toUnicode.name);
  1866. }
  1867. var widths = dict.get('Widths') || baseDict.get('Widths');
  1868. if (widths) {
  1869. uint8array = new Uint8Array(new Uint32Array(widths).buffer);
  1870. hash.update(uint8array);
  1871. }
  1872. }
  1873. return {
  1874. descriptor: descriptor,
  1875. dict: dict,
  1876. baseDict: baseDict,
  1877. composite: composite,
  1878. type: type.name,
  1879. hash: hash ? hash.hexdigest() : ''
  1880. };
  1881. },
  1882. translateFont: function PartialEvaluator_translateFont(preEvaluatedFont) {
  1883. var _this11 = this;
  1884. var baseDict = preEvaluatedFont.baseDict;
  1885. var dict = preEvaluatedFont.dict;
  1886. var composite = preEvaluatedFont.composite;
  1887. var descriptor = preEvaluatedFont.descriptor;
  1888. var type = preEvaluatedFont.type;
  1889. var maxCharIndex = composite ? 0xFFFF : 0xFF;
  1890. var properties;
  1891. if (!descriptor) {
  1892. if (type === 'Type3') {
  1893. descriptor = new _primitives.Dict(null);
  1894. descriptor.set('FontName', _primitives.Name.get(type));
  1895. descriptor.set('FontBBox', dict.getArray('FontBBox'));
  1896. } else {
  1897. var baseFontName = dict.get('BaseFont');
  1898. if (!(0, _primitives.isName)(baseFontName)) {
  1899. throw new _util.FormatError('Base font is not specified');
  1900. }
  1901. baseFontName = baseFontName.name.replace(/[,_]/g, '-');
  1902. var metrics = this.getBaseFontMetrics(baseFontName);
  1903. var fontNameWoStyle = baseFontName.split('-')[0];
  1904. 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);
  1905. properties = {
  1906. type: type,
  1907. name: baseFontName,
  1908. widths: metrics.widths,
  1909. defaultWidth: metrics.defaultWidth,
  1910. flags: flags,
  1911. firstChar: 0,
  1912. lastChar: maxCharIndex
  1913. };
  1914. return this.extractDataStructures(dict, dict, properties).then(function (properties) {
  1915. properties.widths = _this11.buildCharCodeToWidth(metrics.widths, properties);
  1916. return new _fonts.Font(baseFontName, null, properties);
  1917. });
  1918. }
  1919. }
  1920. var firstChar = dict.get('FirstChar') || 0;
  1921. var lastChar = dict.get('LastChar') || maxCharIndex;
  1922. var fontName = descriptor.get('FontName');
  1923. var baseFont = dict.get('BaseFont');
  1924. if ((0, _util.isString)(fontName)) {
  1925. fontName = _primitives.Name.get(fontName);
  1926. }
  1927. if ((0, _util.isString)(baseFont)) {
  1928. baseFont = _primitives.Name.get(baseFont);
  1929. }
  1930. if (type !== 'Type3') {
  1931. var fontNameStr = fontName && fontName.name;
  1932. var baseFontStr = baseFont && baseFont.name;
  1933. if (fontNameStr !== baseFontStr) {
  1934. (0, _util.info)('The FontDescriptor\'s FontName is "' + fontNameStr + '" but should be the same as the Font\'s BaseFont "' + baseFontStr + '"');
  1935. if (fontNameStr && baseFontStr && baseFontStr.indexOf(fontNameStr) === 0) {
  1936. fontName = baseFont;
  1937. }
  1938. }
  1939. }
  1940. fontName = fontName || baseFont;
  1941. if (!(0, _primitives.isName)(fontName)) {
  1942. throw new _util.FormatError('invalid font name');
  1943. }
  1944. var fontFile = descriptor.get('FontFile', 'FontFile2', 'FontFile3');
  1945. if (fontFile) {
  1946. if (fontFile.dict) {
  1947. var subtype = fontFile.dict.get('Subtype');
  1948. if (subtype) {
  1949. subtype = subtype.name;
  1950. }
  1951. var length1 = fontFile.dict.get('Length1');
  1952. var length2 = fontFile.dict.get('Length2');
  1953. var length3 = fontFile.dict.get('Length3');
  1954. }
  1955. }
  1956. properties = {
  1957. type: type,
  1958. name: fontName.name,
  1959. subtype: subtype,
  1960. file: fontFile,
  1961. length1: length1,
  1962. length2: length2,
  1963. length3: length3,
  1964. loadedName: baseDict.loadedName,
  1965. composite: composite,
  1966. wideChars: composite,
  1967. fixedPitch: false,
  1968. fontMatrix: dict.getArray('FontMatrix') || _util.FONT_IDENTITY_MATRIX,
  1969. firstChar: firstChar || 0,
  1970. lastChar: lastChar || maxCharIndex,
  1971. bbox: descriptor.getArray('FontBBox'),
  1972. ascent: descriptor.get('Ascent'),
  1973. descent: descriptor.get('Descent'),
  1974. xHeight: descriptor.get('XHeight'),
  1975. capHeight: descriptor.get('CapHeight'),
  1976. flags: descriptor.get('Flags'),
  1977. italicAngle: descriptor.get('ItalicAngle'),
  1978. coded: false
  1979. };
  1980. var cMapPromise;
  1981. if (composite) {
  1982. var cidEncoding = baseDict.get('Encoding');
  1983. if ((0, _primitives.isName)(cidEncoding)) {
  1984. properties.cidEncoding = cidEncoding.name;
  1985. }
  1986. cMapPromise = _cmap.CMapFactory.create({
  1987. encoding: cidEncoding,
  1988. fetchBuiltInCMap: this.fetchBuiltInCMap,
  1989. useCMap: null
  1990. }).then(function (cMap) {
  1991. properties.cMap = cMap;
  1992. properties.vertical = properties.cMap.vertical;
  1993. });
  1994. } else {
  1995. cMapPromise = Promise.resolve(undefined);
  1996. }
  1997. return cMapPromise.then(function () {
  1998. return _this11.extractDataStructures(dict, baseDict, properties);
  1999. }).then(function (properties) {
  2000. _this11.extractWidths(dict, descriptor, properties);
  2001. if (type === 'Type3') {
  2002. properties.isType3Font = true;
  2003. }
  2004. return new _fonts.Font(fontName.name, fontFile, properties);
  2005. });
  2006. }
  2007. };
  2008. return PartialEvaluator;
  2009. }();
  2010. var TranslatedFont = function TranslatedFontClosure() {
  2011. function TranslatedFont(loadedName, font, dict) {
  2012. this.loadedName = loadedName;
  2013. this.font = font;
  2014. this.dict = dict;
  2015. this.type3Loaded = null;
  2016. this.sent = false;
  2017. }
  2018. TranslatedFont.prototype = {
  2019. send: function send(handler) {
  2020. if (this.sent) {
  2021. return;
  2022. }
  2023. var fontData = this.font.exportData();
  2024. handler.send('commonobj', [this.loadedName, 'Font', fontData]);
  2025. this.sent = true;
  2026. },
  2027. loadType3Data: function loadType3Data(evaluator, resources, parentOperatorList, task) {
  2028. if (!this.font.isType3Font) {
  2029. throw new Error('Must be a Type3 font.');
  2030. }
  2031. if (this.type3Loaded) {
  2032. return this.type3Loaded;
  2033. }
  2034. var type3Options = Object.create(evaluator.options);
  2035. type3Options.ignoreErrors = false;
  2036. var type3Evaluator = evaluator.clone(type3Options);
  2037. var translatedFont = this.font;
  2038. var loadCharProcsPromise = Promise.resolve();
  2039. var charProcs = this.dict.get('CharProcs');
  2040. var fontResources = this.dict.get('Resources') || resources;
  2041. var charProcKeys = charProcs.getKeys();
  2042. var charProcOperatorList = Object.create(null);
  2043. var _loop2 = function _loop2() {
  2044. var key = charProcKeys[i];
  2045. loadCharProcsPromise = loadCharProcsPromise.then(function () {
  2046. var glyphStream = charProcs.get(key);
  2047. var operatorList = new OperatorList();
  2048. return type3Evaluator.getOperatorList({
  2049. stream: glyphStream,
  2050. task: task,
  2051. resources: fontResources,
  2052. operatorList: operatorList
  2053. }).then(function () {
  2054. charProcOperatorList[key] = operatorList.getIR();
  2055. parentOperatorList.addDependencies(operatorList.dependencies);
  2056. }).catch(function (reason) {
  2057. (0, _util.warn)('Type3 font resource "' + key + '" is not available.');
  2058. var operatorList = new OperatorList();
  2059. charProcOperatorList[key] = operatorList.getIR();
  2060. });
  2061. });
  2062. };
  2063. for (var i = 0, n = charProcKeys.length; i < n; ++i) {
  2064. _loop2();
  2065. }
  2066. this.type3Loaded = loadCharProcsPromise.then(function () {
  2067. translatedFont.charProcOperatorList = charProcOperatorList;
  2068. });
  2069. return this.type3Loaded;
  2070. }
  2071. };
  2072. return TranslatedFont;
  2073. }();
  2074. var OperatorList = function OperatorListClosure() {
  2075. var CHUNK_SIZE = 1000;
  2076. var CHUNK_SIZE_ABOUT = CHUNK_SIZE - 5;
  2077. function getTransfers(queue) {
  2078. var transfers = [];
  2079. var fnArray = queue.fnArray,
  2080. argsArray = queue.argsArray;
  2081. for (var i = 0, ii = queue.length; i < ii; i++) {
  2082. switch (fnArray[i]) {
  2083. case _util.OPS.paintInlineImageXObject:
  2084. case _util.OPS.paintInlineImageXObjectGroup:
  2085. case _util.OPS.paintImageMaskXObject:
  2086. var arg = argsArray[i][0];
  2087. if (!arg.cached) {
  2088. transfers.push(arg.data.buffer);
  2089. }
  2090. break;
  2091. }
  2092. }
  2093. return transfers;
  2094. }
  2095. function OperatorList(intent, messageHandler, pageIndex) {
  2096. this.messageHandler = messageHandler;
  2097. this.fnArray = [];
  2098. this.argsArray = [];
  2099. this.dependencies = Object.create(null);
  2100. this._totalLength = 0;
  2101. this.pageIndex = pageIndex;
  2102. this.intent = intent;
  2103. }
  2104. OperatorList.prototype = {
  2105. get length() {
  2106. return this.argsArray.length;
  2107. },
  2108. get totalLength() {
  2109. return this._totalLength + this.length;
  2110. },
  2111. addOp: function addOp(fn, args) {
  2112. this.fnArray.push(fn);
  2113. this.argsArray.push(args);
  2114. if (this.messageHandler) {
  2115. if (this.fnArray.length >= CHUNK_SIZE) {
  2116. this.flush();
  2117. } else if (this.fnArray.length >= CHUNK_SIZE_ABOUT && (fn === _util.OPS.restore || fn === _util.OPS.endText)) {
  2118. this.flush();
  2119. }
  2120. }
  2121. },
  2122. addDependency: function addDependency(dependency) {
  2123. if (dependency in this.dependencies) {
  2124. return;
  2125. }
  2126. this.dependencies[dependency] = true;
  2127. this.addOp(_util.OPS.dependency, [dependency]);
  2128. },
  2129. addDependencies: function addDependencies(dependencies) {
  2130. for (var key in dependencies) {
  2131. this.addDependency(key);
  2132. }
  2133. },
  2134. addOpList: function addOpList(opList) {
  2135. _util.Util.extendObj(this.dependencies, opList.dependencies);
  2136. for (var i = 0, ii = opList.length; i < ii; i++) {
  2137. this.addOp(opList.fnArray[i], opList.argsArray[i]);
  2138. }
  2139. },
  2140. getIR: function getIR() {
  2141. return {
  2142. fnArray: this.fnArray,
  2143. argsArray: this.argsArray,
  2144. length: this.length
  2145. };
  2146. },
  2147. flush: function flush(lastChunk) {
  2148. if (this.intent !== 'oplist') {
  2149. new QueueOptimizer().optimize(this);
  2150. }
  2151. var transfers = getTransfers(this);
  2152. var length = this.length;
  2153. this._totalLength += length;
  2154. this.messageHandler.send('RenderPageChunk', {
  2155. operatorList: {
  2156. fnArray: this.fnArray,
  2157. argsArray: this.argsArray,
  2158. lastChunk: lastChunk,
  2159. length: length
  2160. },
  2161. pageIndex: this.pageIndex,
  2162. intent: this.intent
  2163. }, transfers);
  2164. this.dependencies = Object.create(null);
  2165. this.fnArray.length = 0;
  2166. this.argsArray.length = 0;
  2167. }
  2168. };
  2169. return OperatorList;
  2170. }();
  2171. var StateManager = function StateManagerClosure() {
  2172. function StateManager(initialState) {
  2173. this.state = initialState;
  2174. this.stateStack = [];
  2175. }
  2176. StateManager.prototype = {
  2177. save: function save() {
  2178. var old = this.state;
  2179. this.stateStack.push(this.state);
  2180. this.state = old.clone();
  2181. },
  2182. restore: function restore() {
  2183. var prev = this.stateStack.pop();
  2184. if (prev) {
  2185. this.state = prev;
  2186. }
  2187. },
  2188. transform: function transform(args) {
  2189. this.state.ctm = _util.Util.transform(this.state.ctm, args);
  2190. }
  2191. };
  2192. return StateManager;
  2193. }();
  2194. var TextState = function TextStateClosure() {
  2195. function TextState() {
  2196. this.ctm = new Float32Array(_util.IDENTITY_MATRIX);
  2197. this.fontName = null;
  2198. this.fontSize = 0;
  2199. this.font = null;
  2200. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  2201. this.textMatrix = _util.IDENTITY_MATRIX.slice();
  2202. this.textLineMatrix = _util.IDENTITY_MATRIX.slice();
  2203. this.charSpacing = 0;
  2204. this.wordSpacing = 0;
  2205. this.leading = 0;
  2206. this.textHScale = 1;
  2207. this.textRise = 0;
  2208. }
  2209. TextState.prototype = {
  2210. setTextMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {
  2211. var m = this.textMatrix;
  2212. m[0] = a;
  2213. m[1] = b;
  2214. m[2] = c;
  2215. m[3] = d;
  2216. m[4] = e;
  2217. m[5] = f;
  2218. },
  2219. setTextLineMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {
  2220. var m = this.textLineMatrix;
  2221. m[0] = a;
  2222. m[1] = b;
  2223. m[2] = c;
  2224. m[3] = d;
  2225. m[4] = e;
  2226. m[5] = f;
  2227. },
  2228. translateTextMatrix: function TextState_translateTextMatrix(x, y) {
  2229. var m = this.textMatrix;
  2230. m[4] = m[0] * x + m[2] * y + m[4];
  2231. m[5] = m[1] * x + m[3] * y + m[5];
  2232. },
  2233. translateTextLineMatrix: function TextState_translateTextMatrix(x, y) {
  2234. var m = this.textLineMatrix;
  2235. m[4] = m[0] * x + m[2] * y + m[4];
  2236. m[5] = m[1] * x + m[3] * y + m[5];
  2237. },
  2238. calcTextLineMatrixAdvance: function TextState_calcTextLineMatrixAdvance(a, b, c, d, e, f) {
  2239. var font = this.font;
  2240. if (!font) {
  2241. return null;
  2242. }
  2243. var m = this.textLineMatrix;
  2244. if (!(a === m[0] && b === m[1] && c === m[2] && d === m[3])) {
  2245. return null;
  2246. }
  2247. var txDiff = e - m[4],
  2248. tyDiff = f - m[5];
  2249. if (font.vertical && txDiff !== 0 || !font.vertical && tyDiff !== 0) {
  2250. return null;
  2251. }
  2252. var tx,
  2253. ty,
  2254. denominator = a * d - b * c;
  2255. if (font.vertical) {
  2256. tx = -tyDiff * c / denominator;
  2257. ty = tyDiff * a / denominator;
  2258. } else {
  2259. tx = txDiff * d / denominator;
  2260. ty = -txDiff * b / denominator;
  2261. }
  2262. return {
  2263. width: tx,
  2264. height: ty,
  2265. value: font.vertical ? ty : tx
  2266. };
  2267. },
  2268. calcRenderMatrix: function TextState_calcRendeMatrix(ctm) {
  2269. var tsm = [this.fontSize * this.textHScale, 0, 0, this.fontSize, 0, this.textRise];
  2270. return _util.Util.transform(ctm, _util.Util.transform(this.textMatrix, tsm));
  2271. },
  2272. carriageReturn: function TextState_carriageReturn() {
  2273. this.translateTextLineMatrix(0, -this.leading);
  2274. this.textMatrix = this.textLineMatrix.slice();
  2275. },
  2276. clone: function TextState_clone() {
  2277. var clone = Object.create(this);
  2278. clone.textMatrix = this.textMatrix.slice();
  2279. clone.textLineMatrix = this.textLineMatrix.slice();
  2280. clone.fontMatrix = this.fontMatrix.slice();
  2281. return clone;
  2282. }
  2283. };
  2284. return TextState;
  2285. }();
  2286. var EvalState = function EvalStateClosure() {
  2287. function EvalState() {
  2288. this.ctm = new Float32Array(_util.IDENTITY_MATRIX);
  2289. this.font = null;
  2290. this.textRenderingMode = _util.TextRenderingMode.FILL;
  2291. this.fillColorSpace = _colorspace.ColorSpace.singletons.gray;
  2292. this.strokeColorSpace = _colorspace.ColorSpace.singletons.gray;
  2293. }
  2294. EvalState.prototype = {
  2295. clone: function CanvasExtraState_clone() {
  2296. return Object.create(this);
  2297. }
  2298. };
  2299. return EvalState;
  2300. }();
  2301. var EvaluatorPreprocessor = function EvaluatorPreprocessorClosure() {
  2302. var getOPMap = (0, _util.getLookupTableFactory)(function (t) {
  2303. t['w'] = {
  2304. id: _util.OPS.setLineWidth,
  2305. numArgs: 1,
  2306. variableArgs: false
  2307. };
  2308. t['J'] = {
  2309. id: _util.OPS.setLineCap,
  2310. numArgs: 1,
  2311. variableArgs: false
  2312. };
  2313. t['j'] = {
  2314. id: _util.OPS.setLineJoin,
  2315. numArgs: 1,
  2316. variableArgs: false
  2317. };
  2318. t['M'] = {
  2319. id: _util.OPS.setMiterLimit,
  2320. numArgs: 1,
  2321. variableArgs: false
  2322. };
  2323. t['d'] = {
  2324. id: _util.OPS.setDash,
  2325. numArgs: 2,
  2326. variableArgs: false
  2327. };
  2328. t['ri'] = {
  2329. id: _util.OPS.setRenderingIntent,
  2330. numArgs: 1,
  2331. variableArgs: false
  2332. };
  2333. t['i'] = {
  2334. id: _util.OPS.setFlatness,
  2335. numArgs: 1,
  2336. variableArgs: false
  2337. };
  2338. t['gs'] = {
  2339. id: _util.OPS.setGState,
  2340. numArgs: 1,
  2341. variableArgs: false
  2342. };
  2343. t['q'] = {
  2344. id: _util.OPS.save,
  2345. numArgs: 0,
  2346. variableArgs: false
  2347. };
  2348. t['Q'] = {
  2349. id: _util.OPS.restore,
  2350. numArgs: 0,
  2351. variableArgs: false
  2352. };
  2353. t['cm'] = {
  2354. id: _util.OPS.transform,
  2355. numArgs: 6,
  2356. variableArgs: false
  2357. };
  2358. t['m'] = {
  2359. id: _util.OPS.moveTo,
  2360. numArgs: 2,
  2361. variableArgs: false
  2362. };
  2363. t['l'] = {
  2364. id: _util.OPS.lineTo,
  2365. numArgs: 2,
  2366. variableArgs: false
  2367. };
  2368. t['c'] = {
  2369. id: _util.OPS.curveTo,
  2370. numArgs: 6,
  2371. variableArgs: false
  2372. };
  2373. t['v'] = {
  2374. id: _util.OPS.curveTo2,
  2375. numArgs: 4,
  2376. variableArgs: false
  2377. };
  2378. t['y'] = {
  2379. id: _util.OPS.curveTo3,
  2380. numArgs: 4,
  2381. variableArgs: false
  2382. };
  2383. t['h'] = {
  2384. id: _util.OPS.closePath,
  2385. numArgs: 0,
  2386. variableArgs: false
  2387. };
  2388. t['re'] = {
  2389. id: _util.OPS.rectangle,
  2390. numArgs: 4,
  2391. variableArgs: false
  2392. };
  2393. t['S'] = {
  2394. id: _util.OPS.stroke,
  2395. numArgs: 0,
  2396. variableArgs: false
  2397. };
  2398. t['s'] = {
  2399. id: _util.OPS.closeStroke,
  2400. numArgs: 0,
  2401. variableArgs: false
  2402. };
  2403. t['f'] = {
  2404. id: _util.OPS.fill,
  2405. numArgs: 0,
  2406. variableArgs: false
  2407. };
  2408. t['F'] = {
  2409. id: _util.OPS.fill,
  2410. numArgs: 0,
  2411. variableArgs: false
  2412. };
  2413. t['f*'] = {
  2414. id: _util.OPS.eoFill,
  2415. numArgs: 0,
  2416. variableArgs: false
  2417. };
  2418. t['B'] = {
  2419. id: _util.OPS.fillStroke,
  2420. numArgs: 0,
  2421. variableArgs: false
  2422. };
  2423. t['B*'] = {
  2424. id: _util.OPS.eoFillStroke,
  2425. numArgs: 0,
  2426. variableArgs: false
  2427. };
  2428. t['b'] = {
  2429. id: _util.OPS.closeFillStroke,
  2430. numArgs: 0,
  2431. variableArgs: false
  2432. };
  2433. t['b*'] = {
  2434. id: _util.OPS.closeEOFillStroke,
  2435. numArgs: 0,
  2436. variableArgs: false
  2437. };
  2438. t['n'] = {
  2439. id: _util.OPS.endPath,
  2440. numArgs: 0,
  2441. variableArgs: false
  2442. };
  2443. t['W'] = {
  2444. id: _util.OPS.clip,
  2445. numArgs: 0,
  2446. variableArgs: false
  2447. };
  2448. t['W*'] = {
  2449. id: _util.OPS.eoClip,
  2450. numArgs: 0,
  2451. variableArgs: false
  2452. };
  2453. t['BT'] = {
  2454. id: _util.OPS.beginText,
  2455. numArgs: 0,
  2456. variableArgs: false
  2457. };
  2458. t['ET'] = {
  2459. id: _util.OPS.endText,
  2460. numArgs: 0,
  2461. variableArgs: false
  2462. };
  2463. t['Tc'] = {
  2464. id: _util.OPS.setCharSpacing,
  2465. numArgs: 1,
  2466. variableArgs: false
  2467. };
  2468. t['Tw'] = {
  2469. id: _util.OPS.setWordSpacing,
  2470. numArgs: 1,
  2471. variableArgs: false
  2472. };
  2473. t['Tz'] = {
  2474. id: _util.OPS.setHScale,
  2475. numArgs: 1,
  2476. variableArgs: false
  2477. };
  2478. t['TL'] = {
  2479. id: _util.OPS.setLeading,
  2480. numArgs: 1,
  2481. variableArgs: false
  2482. };
  2483. t['Tf'] = {
  2484. id: _util.OPS.setFont,
  2485. numArgs: 2,
  2486. variableArgs: false
  2487. };
  2488. t['Tr'] = {
  2489. id: _util.OPS.setTextRenderingMode,
  2490. numArgs: 1,
  2491. variableArgs: false
  2492. };
  2493. t['Ts'] = {
  2494. id: _util.OPS.setTextRise,
  2495. numArgs: 1,
  2496. variableArgs: false
  2497. };
  2498. t['Td'] = {
  2499. id: _util.OPS.moveText,
  2500. numArgs: 2,
  2501. variableArgs: false
  2502. };
  2503. t['TD'] = {
  2504. id: _util.OPS.setLeadingMoveText,
  2505. numArgs: 2,
  2506. variableArgs: false
  2507. };
  2508. t['Tm'] = {
  2509. id: _util.OPS.setTextMatrix,
  2510. numArgs: 6,
  2511. variableArgs: false
  2512. };
  2513. t['T*'] = {
  2514. id: _util.OPS.nextLine,
  2515. numArgs: 0,
  2516. variableArgs: false
  2517. };
  2518. t['Tj'] = {
  2519. id: _util.OPS.showText,
  2520. numArgs: 1,
  2521. variableArgs: false
  2522. };
  2523. t['TJ'] = {
  2524. id: _util.OPS.showSpacedText,
  2525. numArgs: 1,
  2526. variableArgs: false
  2527. };
  2528. t['\''] = {
  2529. id: _util.OPS.nextLineShowText,
  2530. numArgs: 1,
  2531. variableArgs: false
  2532. };
  2533. t['"'] = {
  2534. id: _util.OPS.nextLineSetSpacingShowText,
  2535. numArgs: 3,
  2536. variableArgs: false
  2537. };
  2538. t['d0'] = {
  2539. id: _util.OPS.setCharWidth,
  2540. numArgs: 2,
  2541. variableArgs: false
  2542. };
  2543. t['d1'] = {
  2544. id: _util.OPS.setCharWidthAndBounds,
  2545. numArgs: 6,
  2546. variableArgs: false
  2547. };
  2548. t['CS'] = {
  2549. id: _util.OPS.setStrokeColorSpace,
  2550. numArgs: 1,
  2551. variableArgs: false
  2552. };
  2553. t['cs'] = {
  2554. id: _util.OPS.setFillColorSpace,
  2555. numArgs: 1,
  2556. variableArgs: false
  2557. };
  2558. t['SC'] = {
  2559. id: _util.OPS.setStrokeColor,
  2560. numArgs: 4,
  2561. variableArgs: true
  2562. };
  2563. t['SCN'] = {
  2564. id: _util.OPS.setStrokeColorN,
  2565. numArgs: 33,
  2566. variableArgs: true
  2567. };
  2568. t['sc'] = {
  2569. id: _util.OPS.setFillColor,
  2570. numArgs: 4,
  2571. variableArgs: true
  2572. };
  2573. t['scn'] = {
  2574. id: _util.OPS.setFillColorN,
  2575. numArgs: 33,
  2576. variableArgs: true
  2577. };
  2578. t['G'] = {
  2579. id: _util.OPS.setStrokeGray,
  2580. numArgs: 1,
  2581. variableArgs: false
  2582. };
  2583. t['g'] = {
  2584. id: _util.OPS.setFillGray,
  2585. numArgs: 1,
  2586. variableArgs: false
  2587. };
  2588. t['RG'] = {
  2589. id: _util.OPS.setStrokeRGBColor,
  2590. numArgs: 3,
  2591. variableArgs: false
  2592. };
  2593. t['rg'] = {
  2594. id: _util.OPS.setFillRGBColor,
  2595. numArgs: 3,
  2596. variableArgs: false
  2597. };
  2598. t['K'] = {
  2599. id: _util.OPS.setStrokeCMYKColor,
  2600. numArgs: 4,
  2601. variableArgs: false
  2602. };
  2603. t['k'] = {
  2604. id: _util.OPS.setFillCMYKColor,
  2605. numArgs: 4,
  2606. variableArgs: false
  2607. };
  2608. t['sh'] = {
  2609. id: _util.OPS.shadingFill,
  2610. numArgs: 1,
  2611. variableArgs: false
  2612. };
  2613. t['BI'] = {
  2614. id: _util.OPS.beginInlineImage,
  2615. numArgs: 0,
  2616. variableArgs: false
  2617. };
  2618. t['ID'] = {
  2619. id: _util.OPS.beginImageData,
  2620. numArgs: 0,
  2621. variableArgs: false
  2622. };
  2623. t['EI'] = {
  2624. id: _util.OPS.endInlineImage,
  2625. numArgs: 1,
  2626. variableArgs: false
  2627. };
  2628. t['Do'] = {
  2629. id: _util.OPS.paintXObject,
  2630. numArgs: 1,
  2631. variableArgs: false
  2632. };
  2633. t['MP'] = {
  2634. id: _util.OPS.markPoint,
  2635. numArgs: 1,
  2636. variableArgs: false
  2637. };
  2638. t['DP'] = {
  2639. id: _util.OPS.markPointProps,
  2640. numArgs: 2,
  2641. variableArgs: false
  2642. };
  2643. t['BMC'] = {
  2644. id: _util.OPS.beginMarkedContent,
  2645. numArgs: 1,
  2646. variableArgs: false
  2647. };
  2648. t['BDC'] = {
  2649. id: _util.OPS.beginMarkedContentProps,
  2650. numArgs: 2,
  2651. variableArgs: false
  2652. };
  2653. t['EMC'] = {
  2654. id: _util.OPS.endMarkedContent,
  2655. numArgs: 0,
  2656. variableArgs: false
  2657. };
  2658. t['BX'] = {
  2659. id: _util.OPS.beginCompat,
  2660. numArgs: 0,
  2661. variableArgs: false
  2662. };
  2663. t['EX'] = {
  2664. id: _util.OPS.endCompat,
  2665. numArgs: 0,
  2666. variableArgs: false
  2667. };
  2668. t['BM'] = null;
  2669. t['BD'] = null;
  2670. t['true'] = null;
  2671. t['fa'] = null;
  2672. t['fal'] = null;
  2673. t['fals'] = null;
  2674. t['false'] = null;
  2675. t['nu'] = null;
  2676. t['nul'] = null;
  2677. t['null'] = null;
  2678. });
  2679. function EvaluatorPreprocessor(stream, xref, stateManager) {
  2680. this.opMap = getOPMap();
  2681. this.parser = new _parser.Parser(new _parser.Lexer(stream, this.opMap), false, xref);
  2682. this.stateManager = stateManager;
  2683. this.nonProcessedArgs = [];
  2684. }
  2685. EvaluatorPreprocessor.prototype = {
  2686. get savedStatesDepth() {
  2687. return this.stateManager.stateStack.length;
  2688. },
  2689. read: function EvaluatorPreprocessor_read(operation) {
  2690. var args = operation.args;
  2691. while (true) {
  2692. var obj = this.parser.getObj();
  2693. if ((0, _primitives.isCmd)(obj)) {
  2694. var cmd = obj.cmd;
  2695. var opSpec = this.opMap[cmd];
  2696. if (!opSpec) {
  2697. (0, _util.warn)('Unknown command "' + cmd + '"');
  2698. continue;
  2699. }
  2700. var fn = opSpec.id;
  2701. var numArgs = opSpec.numArgs;
  2702. var argsLength = args !== null ? args.length : 0;
  2703. if (!opSpec.variableArgs) {
  2704. if (argsLength !== numArgs) {
  2705. var nonProcessedArgs = this.nonProcessedArgs;
  2706. while (argsLength > numArgs) {
  2707. nonProcessedArgs.push(args.shift());
  2708. argsLength--;
  2709. }
  2710. while (argsLength < numArgs && nonProcessedArgs.length !== 0) {
  2711. if (args === null) {
  2712. args = [];
  2713. }
  2714. args.unshift(nonProcessedArgs.pop());
  2715. argsLength++;
  2716. }
  2717. }
  2718. if (argsLength < numArgs) {
  2719. (0, _util.warn)('Skipping command ' + fn + ': expected ' + numArgs + ' args, but received ' + argsLength + ' args.');
  2720. if (args !== null) {
  2721. args.length = 0;
  2722. }
  2723. continue;
  2724. }
  2725. } else if (argsLength > numArgs) {
  2726. (0, _util.info)('Command ' + fn + ': expected [0,' + numArgs + '] args, but received ' + argsLength + ' args.');
  2727. }
  2728. this.preprocessCommand(fn, args);
  2729. operation.fn = fn;
  2730. operation.args = args;
  2731. return true;
  2732. }
  2733. if ((0, _primitives.isEOF)(obj)) {
  2734. return false;
  2735. }
  2736. if (obj !== null) {
  2737. if (args === null) {
  2738. args = [];
  2739. }
  2740. args.push(obj);
  2741. if (args.length > 33) {
  2742. throw new _util.FormatError('Too many arguments');
  2743. }
  2744. }
  2745. }
  2746. },
  2747. preprocessCommand: function EvaluatorPreprocessor_preprocessCommand(fn, args) {
  2748. switch (fn | 0) {
  2749. case _util.OPS.save:
  2750. this.stateManager.save();
  2751. break;
  2752. case _util.OPS.restore:
  2753. this.stateManager.restore();
  2754. break;
  2755. case _util.OPS.transform:
  2756. this.stateManager.transform(args);
  2757. break;
  2758. }
  2759. }
  2760. };
  2761. return EvaluatorPreprocessor;
  2762. }();
  2763. var QueueOptimizer = function QueueOptimizerClosure() {
  2764. function addState(parentState, pattern, fn) {
  2765. var state = parentState;
  2766. for (var i = 0, ii = pattern.length - 1; i < ii; i++) {
  2767. var item = pattern[i];
  2768. state = state[item] || (state[item] = []);
  2769. }
  2770. state[pattern[pattern.length - 1]] = fn;
  2771. }
  2772. function handlePaintSolidColorImageMask(iFirstSave, count, fnArray, argsArray) {
  2773. var iFirstPIMXO = iFirstSave + 2;
  2774. for (var i = 0; i < count; i++) {
  2775. var arg = argsArray[iFirstPIMXO + 4 * i];
  2776. var imageMask = arg.length === 1 && arg[0];
  2777. if (imageMask && imageMask.width === 1 && imageMask.height === 1 && (!imageMask.data.length || imageMask.data.length === 1 && imageMask.data[0] === 0)) {
  2778. fnArray[iFirstPIMXO + 4 * i] = _util.OPS.paintSolidColorImageMask;
  2779. continue;
  2780. }
  2781. break;
  2782. }
  2783. return count - i;
  2784. }
  2785. var InitialState = [];
  2786. addState(InitialState, [_util.OPS.save, _util.OPS.transform, _util.OPS.paintInlineImageXObject, _util.OPS.restore], function foundInlineImageGroup(context) {
  2787. var MIN_IMAGES_IN_INLINE_IMAGES_BLOCK = 10;
  2788. var MAX_IMAGES_IN_INLINE_IMAGES_BLOCK = 200;
  2789. var MAX_WIDTH = 1000;
  2790. var IMAGE_PADDING = 1;
  2791. var fnArray = context.fnArray,
  2792. argsArray = context.argsArray;
  2793. var curr = context.iCurr;
  2794. var iFirstSave = curr - 3;
  2795. var iFirstTransform = curr - 2;
  2796. var iFirstPIIXO = curr - 1;
  2797. var i = iFirstSave + 4;
  2798. var ii = fnArray.length;
  2799. while (i + 3 < ii) {
  2800. if (fnArray[i] !== _util.OPS.save || fnArray[i + 1] !== _util.OPS.transform || fnArray[i + 2] !== _util.OPS.paintInlineImageXObject || fnArray[i + 3] !== _util.OPS.restore) {
  2801. break;
  2802. }
  2803. i += 4;
  2804. }
  2805. var count = Math.min((i - iFirstSave) / 4, MAX_IMAGES_IN_INLINE_IMAGES_BLOCK);
  2806. if (count < MIN_IMAGES_IN_INLINE_IMAGES_BLOCK) {
  2807. return i;
  2808. }
  2809. var maxX = 0;
  2810. var map = [],
  2811. maxLineHeight = 0;
  2812. var currentX = IMAGE_PADDING,
  2813. currentY = IMAGE_PADDING;
  2814. var q;
  2815. for (q = 0; q < count; q++) {
  2816. var transform = argsArray[iFirstTransform + (q << 2)];
  2817. var img = argsArray[iFirstPIIXO + (q << 2)][0];
  2818. if (currentX + img.width > MAX_WIDTH) {
  2819. maxX = Math.max(maxX, currentX);
  2820. currentY += maxLineHeight + 2 * IMAGE_PADDING;
  2821. currentX = 0;
  2822. maxLineHeight = 0;
  2823. }
  2824. map.push({
  2825. transform: transform,
  2826. x: currentX,
  2827. y: currentY,
  2828. w: img.width,
  2829. h: img.height
  2830. });
  2831. currentX += img.width + 2 * IMAGE_PADDING;
  2832. maxLineHeight = Math.max(maxLineHeight, img.height);
  2833. }
  2834. var imgWidth = Math.max(maxX, currentX) + IMAGE_PADDING;
  2835. var imgHeight = currentY + maxLineHeight + IMAGE_PADDING;
  2836. var imgData = new Uint8Array(imgWidth * imgHeight * 4);
  2837. var imgRowSize = imgWidth << 2;
  2838. for (q = 0; q < count; q++) {
  2839. var data = argsArray[iFirstPIIXO + (q << 2)][0].data;
  2840. var rowSize = map[q].w << 2;
  2841. var dataOffset = 0;
  2842. var offset = map[q].x + map[q].y * imgWidth << 2;
  2843. imgData.set(data.subarray(0, rowSize), offset - imgRowSize);
  2844. for (var k = 0, kk = map[q].h; k < kk; k++) {
  2845. imgData.set(data.subarray(dataOffset, dataOffset + rowSize), offset);
  2846. dataOffset += rowSize;
  2847. offset += imgRowSize;
  2848. }
  2849. imgData.set(data.subarray(dataOffset - rowSize, dataOffset), offset);
  2850. while (offset >= 0) {
  2851. data[offset - 4] = data[offset];
  2852. data[offset - 3] = data[offset + 1];
  2853. data[offset - 2] = data[offset + 2];
  2854. data[offset - 1] = data[offset + 3];
  2855. data[offset + rowSize] = data[offset + rowSize - 4];
  2856. data[offset + rowSize + 1] = data[offset + rowSize - 3];
  2857. data[offset + rowSize + 2] = data[offset + rowSize - 2];
  2858. data[offset + rowSize + 3] = data[offset + rowSize - 1];
  2859. offset -= imgRowSize;
  2860. }
  2861. }
  2862. fnArray.splice(iFirstSave, count * 4, _util.OPS.paintInlineImageXObjectGroup);
  2863. argsArray.splice(iFirstSave, count * 4, [{
  2864. width: imgWidth,
  2865. height: imgHeight,
  2866. kind: _util.ImageKind.RGBA_32BPP,
  2867. data: imgData
  2868. }, map]);
  2869. return iFirstSave + 1;
  2870. });
  2871. addState(InitialState, [_util.OPS.save, _util.OPS.transform, _util.OPS.paintImageMaskXObject, _util.OPS.restore], function foundImageMaskGroup(context) {
  2872. var MIN_IMAGES_IN_MASKS_BLOCK = 10;
  2873. var MAX_IMAGES_IN_MASKS_BLOCK = 100;
  2874. var MAX_SAME_IMAGES_IN_MASKS_BLOCK = 1000;
  2875. var fnArray = context.fnArray,
  2876. argsArray = context.argsArray;
  2877. var curr = context.iCurr;
  2878. var iFirstSave = curr - 3;
  2879. var iFirstTransform = curr - 2;
  2880. var iFirstPIMXO = curr - 1;
  2881. var i = iFirstSave + 4;
  2882. var ii = fnArray.length;
  2883. while (i + 3 < ii) {
  2884. if (fnArray[i] !== _util.OPS.save || fnArray[i + 1] !== _util.OPS.transform || fnArray[i + 2] !== _util.OPS.paintImageMaskXObject || fnArray[i + 3] !== _util.OPS.restore) {
  2885. break;
  2886. }
  2887. i += 4;
  2888. }
  2889. var count = (i - iFirstSave) / 4;
  2890. count = handlePaintSolidColorImageMask(iFirstSave, count, fnArray, argsArray);
  2891. if (count < MIN_IMAGES_IN_MASKS_BLOCK) {
  2892. return i;
  2893. }
  2894. var q;
  2895. var isSameImage = false;
  2896. var iTransform, transformArgs;
  2897. var firstPIMXOArg0 = argsArray[iFirstPIMXO][0];
  2898. if (argsArray[iFirstTransform][1] === 0 && argsArray[iFirstTransform][2] === 0) {
  2899. isSameImage = true;
  2900. var firstTransformArg0 = argsArray[iFirstTransform][0];
  2901. var firstTransformArg3 = argsArray[iFirstTransform][3];
  2902. iTransform = iFirstTransform + 4;
  2903. var iPIMXO = iFirstPIMXO + 4;
  2904. for (q = 1; q < count; q++, iTransform += 4, iPIMXO += 4) {
  2905. transformArgs = argsArray[iTransform];
  2906. if (argsArray[iPIMXO][0] !== firstPIMXOArg0 || transformArgs[0] !== firstTransformArg0 || transformArgs[1] !== 0 || transformArgs[2] !== 0 || transformArgs[3] !== firstTransformArg3) {
  2907. if (q < MIN_IMAGES_IN_MASKS_BLOCK) {
  2908. isSameImage = false;
  2909. } else {
  2910. count = q;
  2911. }
  2912. break;
  2913. }
  2914. }
  2915. }
  2916. if (isSameImage) {
  2917. count = Math.min(count, MAX_SAME_IMAGES_IN_MASKS_BLOCK);
  2918. var positions = new Float32Array(count * 2);
  2919. iTransform = iFirstTransform;
  2920. for (q = 0; q < count; q++, iTransform += 4) {
  2921. transformArgs = argsArray[iTransform];
  2922. positions[q << 1] = transformArgs[4];
  2923. positions[(q << 1) + 1] = transformArgs[5];
  2924. }
  2925. fnArray.splice(iFirstSave, count * 4, _util.OPS.paintImageMaskXObjectRepeat);
  2926. argsArray.splice(iFirstSave, count * 4, [firstPIMXOArg0, firstTransformArg0, firstTransformArg3, positions]);
  2927. } else {
  2928. count = Math.min(count, MAX_IMAGES_IN_MASKS_BLOCK);
  2929. var images = [];
  2930. for (q = 0; q < count; q++) {
  2931. transformArgs = argsArray[iFirstTransform + (q << 2)];
  2932. var maskParams = argsArray[iFirstPIMXO + (q << 2)][0];
  2933. images.push({
  2934. data: maskParams.data,
  2935. width: maskParams.width,
  2936. height: maskParams.height,
  2937. transform: transformArgs
  2938. });
  2939. }
  2940. fnArray.splice(iFirstSave, count * 4, _util.OPS.paintImageMaskXObjectGroup);
  2941. argsArray.splice(iFirstSave, count * 4, [images]);
  2942. }
  2943. return iFirstSave + 1;
  2944. });
  2945. addState(InitialState, [_util.OPS.save, _util.OPS.transform, _util.OPS.paintImageXObject, _util.OPS.restore], function (context) {
  2946. var MIN_IMAGES_IN_BLOCK = 3;
  2947. var MAX_IMAGES_IN_BLOCK = 1000;
  2948. var fnArray = context.fnArray,
  2949. argsArray = context.argsArray;
  2950. var curr = context.iCurr;
  2951. var iFirstSave = curr - 3;
  2952. var iFirstTransform = curr - 2;
  2953. var iFirstPIXO = curr - 1;
  2954. var iFirstRestore = curr;
  2955. if (argsArray[iFirstTransform][1] !== 0 || argsArray[iFirstTransform][2] !== 0) {
  2956. return iFirstRestore + 1;
  2957. }
  2958. var firstPIXOArg0 = argsArray[iFirstPIXO][0];
  2959. var firstTransformArg0 = argsArray[iFirstTransform][0];
  2960. var firstTransformArg3 = argsArray[iFirstTransform][3];
  2961. var i = iFirstSave + 4;
  2962. var ii = fnArray.length;
  2963. while (i + 3 < ii) {
  2964. if (fnArray[i] !== _util.OPS.save || fnArray[i + 1] !== _util.OPS.transform || fnArray[i + 2] !== _util.OPS.paintImageXObject || fnArray[i + 3] !== _util.OPS.restore) {
  2965. break;
  2966. }
  2967. if (argsArray[i + 1][0] !== firstTransformArg0 || argsArray[i + 1][1] !== 0 || argsArray[i + 1][2] !== 0 || argsArray[i + 1][3] !== firstTransformArg3) {
  2968. break;
  2969. }
  2970. if (argsArray[i + 2][0] !== firstPIXOArg0) {
  2971. break;
  2972. }
  2973. i += 4;
  2974. }
  2975. var count = Math.min((i - iFirstSave) / 4, MAX_IMAGES_IN_BLOCK);
  2976. if (count < MIN_IMAGES_IN_BLOCK) {
  2977. return i;
  2978. }
  2979. var positions = new Float32Array(count * 2);
  2980. var iTransform = iFirstTransform;
  2981. for (var q = 0; q < count; q++, iTransform += 4) {
  2982. var transformArgs = argsArray[iTransform];
  2983. positions[q << 1] = transformArgs[4];
  2984. positions[(q << 1) + 1] = transformArgs[5];
  2985. }
  2986. var args = [firstPIXOArg0, firstTransformArg0, firstTransformArg3, positions];
  2987. fnArray.splice(iFirstSave, count * 4, _util.OPS.paintImageXObjectRepeat);
  2988. argsArray.splice(iFirstSave, count * 4, args);
  2989. return iFirstSave + 1;
  2990. });
  2991. addState(InitialState, [_util.OPS.beginText, _util.OPS.setFont, _util.OPS.setTextMatrix, _util.OPS.showText, _util.OPS.endText], function (context) {
  2992. var MIN_CHARS_IN_BLOCK = 3;
  2993. var MAX_CHARS_IN_BLOCK = 1000;
  2994. var fnArray = context.fnArray,
  2995. argsArray = context.argsArray;
  2996. var curr = context.iCurr;
  2997. var iFirstBeginText = curr - 4;
  2998. var iFirstSetFont = curr - 3;
  2999. var iFirstSetTextMatrix = curr - 2;
  3000. var iFirstShowText = curr - 1;
  3001. var iFirstEndText = curr;
  3002. var firstSetFontArg0 = argsArray[iFirstSetFont][0];
  3003. var firstSetFontArg1 = argsArray[iFirstSetFont][1];
  3004. var i = iFirstBeginText + 5;
  3005. var ii = fnArray.length;
  3006. while (i + 4 < ii) {
  3007. 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) {
  3008. break;
  3009. }
  3010. if (argsArray[i + 1][0] !== firstSetFontArg0 || argsArray[i + 1][1] !== firstSetFontArg1) {
  3011. break;
  3012. }
  3013. i += 5;
  3014. }
  3015. var count = Math.min((i - iFirstBeginText) / 5, MAX_CHARS_IN_BLOCK);
  3016. if (count < MIN_CHARS_IN_BLOCK) {
  3017. return i;
  3018. }
  3019. var iFirst = iFirstBeginText;
  3020. 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) {
  3021. count++;
  3022. iFirst -= 5;
  3023. }
  3024. var iEndText = iFirst + 4;
  3025. for (var q = 1; q < count; q++) {
  3026. fnArray.splice(iEndText, 3);
  3027. argsArray.splice(iEndText, 3);
  3028. iEndText += 2;
  3029. }
  3030. return iEndText + 1;
  3031. });
  3032. function QueueOptimizer() {}
  3033. QueueOptimizer.prototype = {
  3034. optimize: function QueueOptimizer_optimize(queue) {
  3035. var fnArray = queue.fnArray,
  3036. argsArray = queue.argsArray;
  3037. var context = {
  3038. iCurr: 0,
  3039. fnArray: fnArray,
  3040. argsArray: argsArray
  3041. };
  3042. var state;
  3043. var i = 0,
  3044. ii = fnArray.length;
  3045. while (i < ii) {
  3046. state = (state || InitialState)[fnArray[i]];
  3047. if (typeof state === 'function') {
  3048. context.iCurr = i;
  3049. i = state(context);
  3050. state = undefined;
  3051. ii = context.fnArray.length;
  3052. } else {
  3053. i++;
  3054. }
  3055. }
  3056. }
  3057. };
  3058. return QueueOptimizer;
  3059. }();
  3060. exports.OperatorList = OperatorList;
  3061. exports.PartialEvaluator = PartialEvaluator;