evaluator.js 111 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114
  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 (_this9.options.ignoreErrors) {
  1434. (0, _util.warn)('getTextContent - ignoring errors during task: ' + task.name);
  1435. flushTextContentItem();
  1436. enqueueChunk();
  1437. return;
  1438. }
  1439. throw reason;
  1440. });
  1441. },
  1442. extractDataStructures: function PartialEvaluator_extractDataStructures(dict, baseDict, properties) {
  1443. var _this10 = this;
  1444. var xref = this.xref;
  1445. var toUnicode = dict.get('ToUnicode') || baseDict.get('ToUnicode');
  1446. var toUnicodePromise = toUnicode ? this.readToUnicode(toUnicode) : Promise.resolve(undefined);
  1447. if (properties.composite) {
  1448. var cidSystemInfo = dict.get('CIDSystemInfo');
  1449. if ((0, _primitives.isDict)(cidSystemInfo)) {
  1450. properties.cidSystemInfo = {
  1451. registry: cidSystemInfo.get('Registry'),
  1452. ordering: cidSystemInfo.get('Ordering'),
  1453. supplement: cidSystemInfo.get('Supplement')
  1454. };
  1455. }
  1456. var cidToGidMap = dict.get('CIDToGIDMap');
  1457. if ((0, _primitives.isStream)(cidToGidMap)) {
  1458. properties.cidToGidMap = this.readCidToGidMap(cidToGidMap);
  1459. }
  1460. }
  1461. var differences = [];
  1462. var baseEncodingName = null;
  1463. var encoding;
  1464. if (dict.has('Encoding')) {
  1465. encoding = dict.get('Encoding');
  1466. if ((0, _primitives.isDict)(encoding)) {
  1467. baseEncodingName = encoding.get('BaseEncoding');
  1468. baseEncodingName = (0, _primitives.isName)(baseEncodingName) ? baseEncodingName.name : null;
  1469. if (encoding.has('Differences')) {
  1470. var diffEncoding = encoding.get('Differences');
  1471. var index = 0;
  1472. for (var j = 0, jj = diffEncoding.length; j < jj; j++) {
  1473. var data = xref.fetchIfRef(diffEncoding[j]);
  1474. if ((0, _util.isNum)(data)) {
  1475. index = data;
  1476. } else if ((0, _primitives.isName)(data)) {
  1477. differences[index++] = data.name;
  1478. } else {
  1479. throw new _util.FormatError('Invalid entry in \'Differences\' array: ' + data);
  1480. }
  1481. }
  1482. }
  1483. } else if ((0, _primitives.isName)(encoding)) {
  1484. baseEncodingName = encoding.name;
  1485. } else {
  1486. throw new _util.FormatError('Encoding is not a Name nor a Dict');
  1487. }
  1488. if (baseEncodingName !== 'MacRomanEncoding' && baseEncodingName !== 'MacExpertEncoding' && baseEncodingName !== 'WinAnsiEncoding') {
  1489. baseEncodingName = null;
  1490. }
  1491. }
  1492. if (baseEncodingName) {
  1493. properties.defaultEncoding = (0, _encodings.getEncoding)(baseEncodingName).slice();
  1494. } else {
  1495. var isSymbolicFont = !!(properties.flags & _fonts.FontFlags.Symbolic);
  1496. var isNonsymbolicFont = !!(properties.flags & _fonts.FontFlags.Nonsymbolic);
  1497. encoding = _encodings.StandardEncoding;
  1498. if (properties.type === 'TrueType' && !isNonsymbolicFont) {
  1499. encoding = _encodings.WinAnsiEncoding;
  1500. }
  1501. if (isSymbolicFont) {
  1502. encoding = _encodings.MacRomanEncoding;
  1503. if (!properties.file) {
  1504. if (/Symbol/i.test(properties.name)) {
  1505. encoding = _encodings.SymbolSetEncoding;
  1506. } else if (/Dingbats/i.test(properties.name)) {
  1507. encoding = _encodings.ZapfDingbatsEncoding;
  1508. }
  1509. }
  1510. }
  1511. properties.defaultEncoding = encoding;
  1512. }
  1513. properties.differences = differences;
  1514. properties.baseEncodingName = baseEncodingName;
  1515. properties.hasEncoding = !!baseEncodingName || differences.length > 0;
  1516. properties.dict = dict;
  1517. return toUnicodePromise.then(function (toUnicode) {
  1518. properties.toUnicode = toUnicode;
  1519. return _this10.buildToUnicode(properties);
  1520. }).then(function (toUnicode) {
  1521. properties.toUnicode = toUnicode;
  1522. return properties;
  1523. });
  1524. },
  1525. buildToUnicode: function PartialEvaluator_buildToUnicode(properties) {
  1526. properties.hasIncludedToUnicodeMap = !!properties.toUnicode && properties.toUnicode.length > 0;
  1527. if (properties.hasIncludedToUnicodeMap) {
  1528. return Promise.resolve(properties.toUnicode);
  1529. }
  1530. var toUnicode, charcode, glyphName;
  1531. if (!properties.composite) {
  1532. toUnicode = [];
  1533. var encoding = properties.defaultEncoding.slice();
  1534. var baseEncodingName = properties.baseEncodingName;
  1535. var differences = properties.differences;
  1536. for (charcode in differences) {
  1537. glyphName = differences[charcode];
  1538. if (glyphName === '.notdef') {
  1539. continue;
  1540. }
  1541. encoding[charcode] = glyphName;
  1542. }
  1543. var glyphsUnicodeMap = (0, _glyphlist.getGlyphsUnicode)();
  1544. for (charcode in encoding) {
  1545. glyphName = encoding[charcode];
  1546. if (glyphName === '') {
  1547. continue;
  1548. } else if (glyphsUnicodeMap[glyphName] === undefined) {
  1549. var code = 0;
  1550. switch (glyphName[0]) {
  1551. case 'G':
  1552. if (glyphName.length === 3) {
  1553. code = parseInt(glyphName.substr(1), 16);
  1554. }
  1555. break;
  1556. case 'g':
  1557. if (glyphName.length === 5) {
  1558. code = parseInt(glyphName.substr(1), 16);
  1559. }
  1560. break;
  1561. case 'C':
  1562. case 'c':
  1563. if (glyphName.length >= 3) {
  1564. code = +glyphName.substr(1);
  1565. }
  1566. break;
  1567. default:
  1568. var unicode = (0, _unicode.getUnicodeForGlyph)(glyphName, glyphsUnicodeMap);
  1569. if (unicode !== -1) {
  1570. code = unicode;
  1571. }
  1572. }
  1573. if (code) {
  1574. if (baseEncodingName && code === +charcode) {
  1575. var baseEncoding = (0, _encodings.getEncoding)(baseEncodingName);
  1576. if (baseEncoding && (glyphName = baseEncoding[charcode])) {
  1577. toUnicode[charcode] = String.fromCharCode(glyphsUnicodeMap[glyphName]);
  1578. continue;
  1579. }
  1580. }
  1581. toUnicode[charcode] = String.fromCharCode(code);
  1582. }
  1583. continue;
  1584. }
  1585. toUnicode[charcode] = String.fromCharCode(glyphsUnicodeMap[glyphName]);
  1586. }
  1587. return Promise.resolve(new _fonts.ToUnicodeMap(toUnicode));
  1588. }
  1589. 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'))) {
  1590. var registry = properties.cidSystemInfo.registry;
  1591. var ordering = properties.cidSystemInfo.ordering;
  1592. var ucs2CMapName = _primitives.Name.get(registry + '-' + ordering + '-UCS2');
  1593. return _cmap.CMapFactory.create({
  1594. encoding: ucs2CMapName,
  1595. fetchBuiltInCMap: this.fetchBuiltInCMap,
  1596. useCMap: null
  1597. }).then(function (ucs2CMap) {
  1598. var cMap = properties.cMap;
  1599. toUnicode = [];
  1600. cMap.forEach(function (charcode, cid) {
  1601. if (cid > 0xffff) {
  1602. throw new _util.FormatError('Max size of CID is 65,535');
  1603. }
  1604. var ucs2 = ucs2CMap.lookup(cid);
  1605. if (ucs2) {
  1606. toUnicode[charcode] = String.fromCharCode((ucs2.charCodeAt(0) << 8) + ucs2.charCodeAt(1));
  1607. }
  1608. });
  1609. return new _fonts.ToUnicodeMap(toUnicode);
  1610. });
  1611. }
  1612. return Promise.resolve(new _fonts.IdentityToUnicodeMap(properties.firstChar, properties.lastChar));
  1613. },
  1614. readToUnicode: function PartialEvaluator_readToUnicode(toUnicode) {
  1615. var cmapObj = toUnicode;
  1616. if ((0, _primitives.isName)(cmapObj)) {
  1617. return _cmap.CMapFactory.create({
  1618. encoding: cmapObj,
  1619. fetchBuiltInCMap: this.fetchBuiltInCMap,
  1620. useCMap: null
  1621. }).then(function (cmap) {
  1622. if (cmap instanceof _cmap.IdentityCMap) {
  1623. return new _fonts.IdentityToUnicodeMap(0, 0xFFFF);
  1624. }
  1625. return new _fonts.ToUnicodeMap(cmap.getMap());
  1626. });
  1627. } else if ((0, _primitives.isStream)(cmapObj)) {
  1628. return _cmap.CMapFactory.create({
  1629. encoding: cmapObj,
  1630. fetchBuiltInCMap: this.fetchBuiltInCMap,
  1631. useCMap: null
  1632. }).then(function (cmap) {
  1633. if (cmap instanceof _cmap.IdentityCMap) {
  1634. return new _fonts.IdentityToUnicodeMap(0, 0xFFFF);
  1635. }
  1636. var map = new Array(cmap.length);
  1637. cmap.forEach(function (charCode, token) {
  1638. var str = [];
  1639. for (var k = 0; k < token.length; k += 2) {
  1640. var w1 = token.charCodeAt(k) << 8 | token.charCodeAt(k + 1);
  1641. if ((w1 & 0xF800) !== 0xD800) {
  1642. str.push(w1);
  1643. continue;
  1644. }
  1645. k += 2;
  1646. var w2 = token.charCodeAt(k) << 8 | token.charCodeAt(k + 1);
  1647. str.push(((w1 & 0x3ff) << 10) + (w2 & 0x3ff) + 0x10000);
  1648. }
  1649. map[charCode] = String.fromCharCode.apply(String, str);
  1650. });
  1651. return new _fonts.ToUnicodeMap(map);
  1652. });
  1653. }
  1654. return Promise.resolve(null);
  1655. },
  1656. readCidToGidMap: function PartialEvaluator_readCidToGidMap(cidToGidStream) {
  1657. var glyphsData = cidToGidStream.getBytes();
  1658. var result = [];
  1659. for (var j = 0, jj = glyphsData.length; j < jj; j++) {
  1660. var glyphID = glyphsData[j++] << 8 | glyphsData[j];
  1661. if (glyphID === 0) {
  1662. continue;
  1663. }
  1664. var code = j >> 1;
  1665. result[code] = glyphID;
  1666. }
  1667. return result;
  1668. },
  1669. extractWidths: function PartialEvaluator_extractWidths(dict, descriptor, properties) {
  1670. var xref = this.xref;
  1671. var glyphsWidths = [];
  1672. var defaultWidth = 0;
  1673. var glyphsVMetrics = [];
  1674. var defaultVMetrics;
  1675. var i, ii, j, jj, start, code, widths;
  1676. if (properties.composite) {
  1677. defaultWidth = dict.get('DW') || 1000;
  1678. widths = dict.get('W');
  1679. if (widths) {
  1680. for (i = 0, ii = widths.length; i < ii; i++) {
  1681. start = xref.fetchIfRef(widths[i++]);
  1682. code = xref.fetchIfRef(widths[i]);
  1683. if ((0, _util.isArray)(code)) {
  1684. for (j = 0, jj = code.length; j < jj; j++) {
  1685. glyphsWidths[start++] = xref.fetchIfRef(code[j]);
  1686. }
  1687. } else {
  1688. var width = xref.fetchIfRef(widths[++i]);
  1689. for (j = start; j <= code; j++) {
  1690. glyphsWidths[j] = width;
  1691. }
  1692. }
  1693. }
  1694. }
  1695. if (properties.vertical) {
  1696. var vmetrics = dict.getArray('DW2') || [880, -1000];
  1697. defaultVMetrics = [vmetrics[1], defaultWidth * 0.5, vmetrics[0]];
  1698. vmetrics = dict.get('W2');
  1699. if (vmetrics) {
  1700. for (i = 0, ii = vmetrics.length; i < ii; i++) {
  1701. start = xref.fetchIfRef(vmetrics[i++]);
  1702. code = xref.fetchIfRef(vmetrics[i]);
  1703. if ((0, _util.isArray)(code)) {
  1704. for (j = 0, jj = code.length; j < jj; j++) {
  1705. glyphsVMetrics[start++] = [xref.fetchIfRef(code[j++]), xref.fetchIfRef(code[j++]), xref.fetchIfRef(code[j])];
  1706. }
  1707. } else {
  1708. var vmetric = [xref.fetchIfRef(vmetrics[++i]), xref.fetchIfRef(vmetrics[++i]), xref.fetchIfRef(vmetrics[++i])];
  1709. for (j = start; j <= code; j++) {
  1710. glyphsVMetrics[j] = vmetric;
  1711. }
  1712. }
  1713. }
  1714. }
  1715. }
  1716. } else {
  1717. var firstChar = properties.firstChar;
  1718. widths = dict.get('Widths');
  1719. if (widths) {
  1720. j = firstChar;
  1721. for (i = 0, ii = widths.length; i < ii; i++) {
  1722. glyphsWidths[j++] = xref.fetchIfRef(widths[i]);
  1723. }
  1724. defaultWidth = parseFloat(descriptor.get('MissingWidth')) || 0;
  1725. } else {
  1726. var baseFontName = dict.get('BaseFont');
  1727. if ((0, _primitives.isName)(baseFontName)) {
  1728. var metrics = this.getBaseFontMetrics(baseFontName.name);
  1729. glyphsWidths = this.buildCharCodeToWidth(metrics.widths, properties);
  1730. defaultWidth = metrics.defaultWidth;
  1731. }
  1732. }
  1733. }
  1734. var isMonospace = true;
  1735. var firstWidth = defaultWidth;
  1736. for (var glyph in glyphsWidths) {
  1737. var glyphWidth = glyphsWidths[glyph];
  1738. if (!glyphWidth) {
  1739. continue;
  1740. }
  1741. if (!firstWidth) {
  1742. firstWidth = glyphWidth;
  1743. continue;
  1744. }
  1745. if (firstWidth !== glyphWidth) {
  1746. isMonospace = false;
  1747. break;
  1748. }
  1749. }
  1750. if (isMonospace) {
  1751. properties.flags |= _fonts.FontFlags.FixedPitch;
  1752. }
  1753. properties.defaultWidth = defaultWidth;
  1754. properties.widths = glyphsWidths;
  1755. properties.defaultVMetrics = defaultVMetrics;
  1756. properties.vmetrics = glyphsVMetrics;
  1757. },
  1758. isSerifFont: function PartialEvaluator_isSerifFont(baseFontName) {
  1759. var fontNameWoStyle = baseFontName.split('-')[0];
  1760. return fontNameWoStyle in (0, _standard_fonts.getSerifFonts)() || fontNameWoStyle.search(/serif/gi) !== -1;
  1761. },
  1762. getBaseFontMetrics: function PartialEvaluator_getBaseFontMetrics(name) {
  1763. var defaultWidth = 0;
  1764. var widths = [];
  1765. var monospace = false;
  1766. var stdFontMap = (0, _standard_fonts.getStdFontMap)();
  1767. var lookupName = stdFontMap[name] || name;
  1768. var Metrics = (0, _metrics.getMetrics)();
  1769. if (!(lookupName in Metrics)) {
  1770. if (this.isSerifFont(name)) {
  1771. lookupName = 'Times-Roman';
  1772. } else {
  1773. lookupName = 'Helvetica';
  1774. }
  1775. }
  1776. var glyphWidths = Metrics[lookupName];
  1777. if ((0, _util.isNum)(glyphWidths)) {
  1778. defaultWidth = glyphWidths;
  1779. monospace = true;
  1780. } else {
  1781. widths = glyphWidths();
  1782. }
  1783. return {
  1784. defaultWidth: defaultWidth,
  1785. monospace: monospace,
  1786. widths: widths
  1787. };
  1788. },
  1789. buildCharCodeToWidth: function PartialEvaluator_bulildCharCodeToWidth(widthsByGlyphName, properties) {
  1790. var widths = Object.create(null);
  1791. var differences = properties.differences;
  1792. var encoding = properties.defaultEncoding;
  1793. for (var charCode = 0; charCode < 256; charCode++) {
  1794. if (charCode in differences && widthsByGlyphName[differences[charCode]]) {
  1795. widths[charCode] = widthsByGlyphName[differences[charCode]];
  1796. continue;
  1797. }
  1798. if (charCode in encoding && widthsByGlyphName[encoding[charCode]]) {
  1799. widths[charCode] = widthsByGlyphName[encoding[charCode]];
  1800. continue;
  1801. }
  1802. }
  1803. return widths;
  1804. },
  1805. preEvaluateFont: function PartialEvaluator_preEvaluateFont(dict) {
  1806. var baseDict = dict;
  1807. var type = dict.get('Subtype');
  1808. if (!(0, _primitives.isName)(type)) {
  1809. throw new _util.FormatError('invalid font Subtype');
  1810. }
  1811. var composite = false;
  1812. var uint8array;
  1813. if (type.name === 'Type0') {
  1814. var df = dict.get('DescendantFonts');
  1815. if (!df) {
  1816. throw new _util.FormatError('Descendant fonts are not specified');
  1817. }
  1818. dict = (0, _util.isArray)(df) ? this.xref.fetchIfRef(df[0]) : df;
  1819. type = dict.get('Subtype');
  1820. if (!(0, _primitives.isName)(type)) {
  1821. throw new _util.FormatError('invalid font Subtype');
  1822. }
  1823. composite = true;
  1824. }
  1825. var descriptor = dict.get('FontDescriptor');
  1826. if (descriptor) {
  1827. var hash = new _murmurhash.MurmurHash3_64();
  1828. var encoding = baseDict.getRaw('Encoding');
  1829. if ((0, _primitives.isName)(encoding)) {
  1830. hash.update(encoding.name);
  1831. } else if ((0, _primitives.isRef)(encoding)) {
  1832. hash.update(encoding.toString());
  1833. } else if ((0, _primitives.isDict)(encoding)) {
  1834. var keys = encoding.getKeys();
  1835. for (var i = 0, ii = keys.length; i < ii; i++) {
  1836. var entry = encoding.getRaw(keys[i]);
  1837. if ((0, _primitives.isName)(entry)) {
  1838. hash.update(entry.name);
  1839. } else if ((0, _primitives.isRef)(entry)) {
  1840. hash.update(entry.toString());
  1841. } else if ((0, _util.isArray)(entry)) {
  1842. var diffLength = entry.length,
  1843. diffBuf = new Array(diffLength);
  1844. for (var j = 0; j < diffLength; j++) {
  1845. var diffEntry = entry[j];
  1846. if ((0, _primitives.isName)(diffEntry)) {
  1847. diffBuf[j] = diffEntry.name;
  1848. } else if ((0, _util.isNum)(diffEntry) || (0, _primitives.isRef)(diffEntry)) {
  1849. diffBuf[j] = diffEntry.toString();
  1850. }
  1851. }
  1852. hash.update(diffBuf.join());
  1853. }
  1854. }
  1855. }
  1856. var toUnicode = dict.get('ToUnicode') || baseDict.get('ToUnicode');
  1857. if ((0, _primitives.isStream)(toUnicode)) {
  1858. var stream = toUnicode.str || toUnicode;
  1859. uint8array = stream.buffer ? new Uint8Array(stream.buffer.buffer, 0, stream.bufferLength) : new Uint8Array(stream.bytes.buffer, stream.start, stream.end - stream.start);
  1860. hash.update(uint8array);
  1861. } else if ((0, _primitives.isName)(toUnicode)) {
  1862. hash.update(toUnicode.name);
  1863. }
  1864. var widths = dict.get('Widths') || baseDict.get('Widths');
  1865. if (widths) {
  1866. uint8array = new Uint8Array(new Uint32Array(widths).buffer);
  1867. hash.update(uint8array);
  1868. }
  1869. }
  1870. return {
  1871. descriptor: descriptor,
  1872. dict: dict,
  1873. baseDict: baseDict,
  1874. composite: composite,
  1875. type: type.name,
  1876. hash: hash ? hash.hexdigest() : ''
  1877. };
  1878. },
  1879. translateFont: function PartialEvaluator_translateFont(preEvaluatedFont) {
  1880. var _this11 = this;
  1881. var baseDict = preEvaluatedFont.baseDict;
  1882. var dict = preEvaluatedFont.dict;
  1883. var composite = preEvaluatedFont.composite;
  1884. var descriptor = preEvaluatedFont.descriptor;
  1885. var type = preEvaluatedFont.type;
  1886. var maxCharIndex = composite ? 0xFFFF : 0xFF;
  1887. var properties;
  1888. if (!descriptor) {
  1889. if (type === 'Type3') {
  1890. descriptor = new _primitives.Dict(null);
  1891. descriptor.set('FontName', _primitives.Name.get(type));
  1892. descriptor.set('FontBBox', dict.getArray('FontBBox'));
  1893. } else {
  1894. var baseFontName = dict.get('BaseFont');
  1895. if (!(0, _primitives.isName)(baseFontName)) {
  1896. throw new _util.FormatError('Base font is not specified');
  1897. }
  1898. baseFontName = baseFontName.name.replace(/[,_]/g, '-');
  1899. var metrics = this.getBaseFontMetrics(baseFontName);
  1900. var fontNameWoStyle = baseFontName.split('-')[0];
  1901. 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);
  1902. properties = {
  1903. type: type,
  1904. name: baseFontName,
  1905. widths: metrics.widths,
  1906. defaultWidth: metrics.defaultWidth,
  1907. flags: flags,
  1908. firstChar: 0,
  1909. lastChar: maxCharIndex
  1910. };
  1911. return this.extractDataStructures(dict, dict, properties).then(function (properties) {
  1912. properties.widths = _this11.buildCharCodeToWidth(metrics.widths, properties);
  1913. return new _fonts.Font(baseFontName, null, properties);
  1914. });
  1915. }
  1916. }
  1917. var firstChar = dict.get('FirstChar') || 0;
  1918. var lastChar = dict.get('LastChar') || maxCharIndex;
  1919. var fontName = descriptor.get('FontName');
  1920. var baseFont = dict.get('BaseFont');
  1921. if ((0, _util.isString)(fontName)) {
  1922. fontName = _primitives.Name.get(fontName);
  1923. }
  1924. if ((0, _util.isString)(baseFont)) {
  1925. baseFont = _primitives.Name.get(baseFont);
  1926. }
  1927. if (type !== 'Type3') {
  1928. var fontNameStr = fontName && fontName.name;
  1929. var baseFontStr = baseFont && baseFont.name;
  1930. if (fontNameStr !== baseFontStr) {
  1931. (0, _util.info)('The FontDescriptor\'s FontName is "' + fontNameStr + '" but should be the same as the Font\'s BaseFont "' + baseFontStr + '"');
  1932. if (fontNameStr && baseFontStr && baseFontStr.indexOf(fontNameStr) === 0) {
  1933. fontName = baseFont;
  1934. }
  1935. }
  1936. }
  1937. fontName = fontName || baseFont;
  1938. if (!(0, _primitives.isName)(fontName)) {
  1939. throw new _util.FormatError('invalid font name');
  1940. }
  1941. var fontFile = descriptor.get('FontFile', 'FontFile2', 'FontFile3');
  1942. if (fontFile) {
  1943. if (fontFile.dict) {
  1944. var subtype = fontFile.dict.get('Subtype');
  1945. if (subtype) {
  1946. subtype = subtype.name;
  1947. }
  1948. var length1 = fontFile.dict.get('Length1');
  1949. var length2 = fontFile.dict.get('Length2');
  1950. var length3 = fontFile.dict.get('Length3');
  1951. }
  1952. }
  1953. properties = {
  1954. type: type,
  1955. name: fontName.name,
  1956. subtype: subtype,
  1957. file: fontFile,
  1958. length1: length1,
  1959. length2: length2,
  1960. length3: length3,
  1961. loadedName: baseDict.loadedName,
  1962. composite: composite,
  1963. wideChars: composite,
  1964. fixedPitch: false,
  1965. fontMatrix: dict.getArray('FontMatrix') || _util.FONT_IDENTITY_MATRIX,
  1966. firstChar: firstChar || 0,
  1967. lastChar: lastChar || maxCharIndex,
  1968. bbox: descriptor.getArray('FontBBox'),
  1969. ascent: descriptor.get('Ascent'),
  1970. descent: descriptor.get('Descent'),
  1971. xHeight: descriptor.get('XHeight'),
  1972. capHeight: descriptor.get('CapHeight'),
  1973. flags: descriptor.get('Flags'),
  1974. italicAngle: descriptor.get('ItalicAngle'),
  1975. coded: false
  1976. };
  1977. var cMapPromise;
  1978. if (composite) {
  1979. var cidEncoding = baseDict.get('Encoding');
  1980. if ((0, _primitives.isName)(cidEncoding)) {
  1981. properties.cidEncoding = cidEncoding.name;
  1982. }
  1983. cMapPromise = _cmap.CMapFactory.create({
  1984. encoding: cidEncoding,
  1985. fetchBuiltInCMap: this.fetchBuiltInCMap,
  1986. useCMap: null
  1987. }).then(function (cMap) {
  1988. properties.cMap = cMap;
  1989. properties.vertical = properties.cMap.vertical;
  1990. });
  1991. } else {
  1992. cMapPromise = Promise.resolve(undefined);
  1993. }
  1994. return cMapPromise.then(function () {
  1995. return _this11.extractDataStructures(dict, baseDict, properties);
  1996. }).then(function (properties) {
  1997. _this11.extractWidths(dict, descriptor, properties);
  1998. if (type === 'Type3') {
  1999. properties.isType3Font = true;
  2000. }
  2001. return new _fonts.Font(fontName.name, fontFile, properties);
  2002. });
  2003. }
  2004. };
  2005. return PartialEvaluator;
  2006. }();
  2007. var TranslatedFont = function TranslatedFontClosure() {
  2008. function TranslatedFont(loadedName, font, dict) {
  2009. this.loadedName = loadedName;
  2010. this.font = font;
  2011. this.dict = dict;
  2012. this.type3Loaded = null;
  2013. this.sent = false;
  2014. }
  2015. TranslatedFont.prototype = {
  2016. send: function send(handler) {
  2017. if (this.sent) {
  2018. return;
  2019. }
  2020. var fontData = this.font.exportData();
  2021. handler.send('commonobj', [this.loadedName, 'Font', fontData]);
  2022. this.sent = true;
  2023. },
  2024. loadType3Data: function loadType3Data(evaluator, resources, parentOperatorList, task) {
  2025. if (!this.font.isType3Font) {
  2026. throw new Error('Must be a Type3 font.');
  2027. }
  2028. if (this.type3Loaded) {
  2029. return this.type3Loaded;
  2030. }
  2031. var type3Options = Object.create(evaluator.options);
  2032. type3Options.ignoreErrors = false;
  2033. var type3Evaluator = evaluator.clone(type3Options);
  2034. var translatedFont = this.font;
  2035. var loadCharProcsPromise = Promise.resolve();
  2036. var charProcs = this.dict.get('CharProcs');
  2037. var fontResources = this.dict.get('Resources') || resources;
  2038. var charProcKeys = charProcs.getKeys();
  2039. var charProcOperatorList = Object.create(null);
  2040. var _loop2 = function _loop2() {
  2041. var key = charProcKeys[i];
  2042. loadCharProcsPromise = loadCharProcsPromise.then(function () {
  2043. var glyphStream = charProcs.get(key);
  2044. var operatorList = new OperatorList();
  2045. return type3Evaluator.getOperatorList({
  2046. stream: glyphStream,
  2047. task: task,
  2048. resources: fontResources,
  2049. operatorList: operatorList
  2050. }).then(function () {
  2051. charProcOperatorList[key] = operatorList.getIR();
  2052. parentOperatorList.addDependencies(operatorList.dependencies);
  2053. }).catch(function (reason) {
  2054. (0, _util.warn)('Type3 font resource "' + key + '" is not available.');
  2055. var operatorList = new OperatorList();
  2056. charProcOperatorList[key] = operatorList.getIR();
  2057. });
  2058. });
  2059. };
  2060. for (var i = 0, n = charProcKeys.length; i < n; ++i) {
  2061. _loop2();
  2062. }
  2063. this.type3Loaded = loadCharProcsPromise.then(function () {
  2064. translatedFont.charProcOperatorList = charProcOperatorList;
  2065. });
  2066. return this.type3Loaded;
  2067. }
  2068. };
  2069. return TranslatedFont;
  2070. }();
  2071. var OperatorList = function OperatorListClosure() {
  2072. var CHUNK_SIZE = 1000;
  2073. var CHUNK_SIZE_ABOUT = CHUNK_SIZE - 5;
  2074. function getTransfers(queue) {
  2075. var transfers = [];
  2076. var fnArray = queue.fnArray,
  2077. argsArray = queue.argsArray;
  2078. for (var i = 0, ii = queue.length; i < ii; i++) {
  2079. switch (fnArray[i]) {
  2080. case _util.OPS.paintInlineImageXObject:
  2081. case _util.OPS.paintInlineImageXObjectGroup:
  2082. case _util.OPS.paintImageMaskXObject:
  2083. var arg = argsArray[i][0];
  2084. if (!arg.cached) {
  2085. transfers.push(arg.data.buffer);
  2086. }
  2087. break;
  2088. }
  2089. }
  2090. return transfers;
  2091. }
  2092. function OperatorList(intent, messageHandler, pageIndex) {
  2093. this.messageHandler = messageHandler;
  2094. this.fnArray = [];
  2095. this.argsArray = [];
  2096. this.dependencies = Object.create(null);
  2097. this._totalLength = 0;
  2098. this.pageIndex = pageIndex;
  2099. this.intent = intent;
  2100. }
  2101. OperatorList.prototype = {
  2102. get length() {
  2103. return this.argsArray.length;
  2104. },
  2105. get totalLength() {
  2106. return this._totalLength + this.length;
  2107. },
  2108. addOp: function addOp(fn, args) {
  2109. this.fnArray.push(fn);
  2110. this.argsArray.push(args);
  2111. if (this.messageHandler) {
  2112. if (this.fnArray.length >= CHUNK_SIZE) {
  2113. this.flush();
  2114. } else if (this.fnArray.length >= CHUNK_SIZE_ABOUT && (fn === _util.OPS.restore || fn === _util.OPS.endText)) {
  2115. this.flush();
  2116. }
  2117. }
  2118. },
  2119. addDependency: function addDependency(dependency) {
  2120. if (dependency in this.dependencies) {
  2121. return;
  2122. }
  2123. this.dependencies[dependency] = true;
  2124. this.addOp(_util.OPS.dependency, [dependency]);
  2125. },
  2126. addDependencies: function addDependencies(dependencies) {
  2127. for (var key in dependencies) {
  2128. this.addDependency(key);
  2129. }
  2130. },
  2131. addOpList: function addOpList(opList) {
  2132. _util.Util.extendObj(this.dependencies, opList.dependencies);
  2133. for (var i = 0, ii = opList.length; i < ii; i++) {
  2134. this.addOp(opList.fnArray[i], opList.argsArray[i]);
  2135. }
  2136. },
  2137. getIR: function getIR() {
  2138. return {
  2139. fnArray: this.fnArray,
  2140. argsArray: this.argsArray,
  2141. length: this.length
  2142. };
  2143. },
  2144. flush: function flush(lastChunk) {
  2145. if (this.intent !== 'oplist') {
  2146. new QueueOptimizer().optimize(this);
  2147. }
  2148. var transfers = getTransfers(this);
  2149. var length = this.length;
  2150. this._totalLength += length;
  2151. this.messageHandler.send('RenderPageChunk', {
  2152. operatorList: {
  2153. fnArray: this.fnArray,
  2154. argsArray: this.argsArray,
  2155. lastChunk: lastChunk,
  2156. length: length
  2157. },
  2158. pageIndex: this.pageIndex,
  2159. intent: this.intent
  2160. }, transfers);
  2161. this.dependencies = Object.create(null);
  2162. this.fnArray.length = 0;
  2163. this.argsArray.length = 0;
  2164. }
  2165. };
  2166. return OperatorList;
  2167. }();
  2168. var StateManager = function StateManagerClosure() {
  2169. function StateManager(initialState) {
  2170. this.state = initialState;
  2171. this.stateStack = [];
  2172. }
  2173. StateManager.prototype = {
  2174. save: function save() {
  2175. var old = this.state;
  2176. this.stateStack.push(this.state);
  2177. this.state = old.clone();
  2178. },
  2179. restore: function restore() {
  2180. var prev = this.stateStack.pop();
  2181. if (prev) {
  2182. this.state = prev;
  2183. }
  2184. },
  2185. transform: function transform(args) {
  2186. this.state.ctm = _util.Util.transform(this.state.ctm, args);
  2187. }
  2188. };
  2189. return StateManager;
  2190. }();
  2191. var TextState = function TextStateClosure() {
  2192. function TextState() {
  2193. this.ctm = new Float32Array(_util.IDENTITY_MATRIX);
  2194. this.fontName = null;
  2195. this.fontSize = 0;
  2196. this.font = null;
  2197. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  2198. this.textMatrix = _util.IDENTITY_MATRIX.slice();
  2199. this.textLineMatrix = _util.IDENTITY_MATRIX.slice();
  2200. this.charSpacing = 0;
  2201. this.wordSpacing = 0;
  2202. this.leading = 0;
  2203. this.textHScale = 1;
  2204. this.textRise = 0;
  2205. }
  2206. TextState.prototype = {
  2207. setTextMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {
  2208. var m = this.textMatrix;
  2209. m[0] = a;
  2210. m[1] = b;
  2211. m[2] = c;
  2212. m[3] = d;
  2213. m[4] = e;
  2214. m[5] = f;
  2215. },
  2216. setTextLineMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {
  2217. var m = this.textLineMatrix;
  2218. m[0] = a;
  2219. m[1] = b;
  2220. m[2] = c;
  2221. m[3] = d;
  2222. m[4] = e;
  2223. m[5] = f;
  2224. },
  2225. translateTextMatrix: function TextState_translateTextMatrix(x, y) {
  2226. var m = this.textMatrix;
  2227. m[4] = m[0] * x + m[2] * y + m[4];
  2228. m[5] = m[1] * x + m[3] * y + m[5];
  2229. },
  2230. translateTextLineMatrix: function TextState_translateTextMatrix(x, y) {
  2231. var m = this.textLineMatrix;
  2232. m[4] = m[0] * x + m[2] * y + m[4];
  2233. m[5] = m[1] * x + m[3] * y + m[5];
  2234. },
  2235. calcTextLineMatrixAdvance: function TextState_calcTextLineMatrixAdvance(a, b, c, d, e, f) {
  2236. var font = this.font;
  2237. if (!font) {
  2238. return null;
  2239. }
  2240. var m = this.textLineMatrix;
  2241. if (!(a === m[0] && b === m[1] && c === m[2] && d === m[3])) {
  2242. return null;
  2243. }
  2244. var txDiff = e - m[4],
  2245. tyDiff = f - m[5];
  2246. if (font.vertical && txDiff !== 0 || !font.vertical && tyDiff !== 0) {
  2247. return null;
  2248. }
  2249. var tx,
  2250. ty,
  2251. denominator = a * d - b * c;
  2252. if (font.vertical) {
  2253. tx = -tyDiff * c / denominator;
  2254. ty = tyDiff * a / denominator;
  2255. } else {
  2256. tx = txDiff * d / denominator;
  2257. ty = -txDiff * b / denominator;
  2258. }
  2259. return {
  2260. width: tx,
  2261. height: ty,
  2262. value: font.vertical ? ty : tx
  2263. };
  2264. },
  2265. calcRenderMatrix: function TextState_calcRendeMatrix(ctm) {
  2266. var tsm = [this.fontSize * this.textHScale, 0, 0, this.fontSize, 0, this.textRise];
  2267. return _util.Util.transform(ctm, _util.Util.transform(this.textMatrix, tsm));
  2268. },
  2269. carriageReturn: function TextState_carriageReturn() {
  2270. this.translateTextLineMatrix(0, -this.leading);
  2271. this.textMatrix = this.textLineMatrix.slice();
  2272. },
  2273. clone: function TextState_clone() {
  2274. var clone = Object.create(this);
  2275. clone.textMatrix = this.textMatrix.slice();
  2276. clone.textLineMatrix = this.textLineMatrix.slice();
  2277. clone.fontMatrix = this.fontMatrix.slice();
  2278. return clone;
  2279. }
  2280. };
  2281. return TextState;
  2282. }();
  2283. var EvalState = function EvalStateClosure() {
  2284. function EvalState() {
  2285. this.ctm = new Float32Array(_util.IDENTITY_MATRIX);
  2286. this.font = null;
  2287. this.textRenderingMode = _util.TextRenderingMode.FILL;
  2288. this.fillColorSpace = _colorspace.ColorSpace.singletons.gray;
  2289. this.strokeColorSpace = _colorspace.ColorSpace.singletons.gray;
  2290. }
  2291. EvalState.prototype = {
  2292. clone: function CanvasExtraState_clone() {
  2293. return Object.create(this);
  2294. }
  2295. };
  2296. return EvalState;
  2297. }();
  2298. var EvaluatorPreprocessor = function EvaluatorPreprocessorClosure() {
  2299. var getOPMap = (0, _util.getLookupTableFactory)(function (t) {
  2300. t['w'] = {
  2301. id: _util.OPS.setLineWidth,
  2302. numArgs: 1,
  2303. variableArgs: false
  2304. };
  2305. t['J'] = {
  2306. id: _util.OPS.setLineCap,
  2307. numArgs: 1,
  2308. variableArgs: false
  2309. };
  2310. t['j'] = {
  2311. id: _util.OPS.setLineJoin,
  2312. numArgs: 1,
  2313. variableArgs: false
  2314. };
  2315. t['M'] = {
  2316. id: _util.OPS.setMiterLimit,
  2317. numArgs: 1,
  2318. variableArgs: false
  2319. };
  2320. t['d'] = {
  2321. id: _util.OPS.setDash,
  2322. numArgs: 2,
  2323. variableArgs: false
  2324. };
  2325. t['ri'] = {
  2326. id: _util.OPS.setRenderingIntent,
  2327. numArgs: 1,
  2328. variableArgs: false
  2329. };
  2330. t['i'] = {
  2331. id: _util.OPS.setFlatness,
  2332. numArgs: 1,
  2333. variableArgs: false
  2334. };
  2335. t['gs'] = {
  2336. id: _util.OPS.setGState,
  2337. numArgs: 1,
  2338. variableArgs: false
  2339. };
  2340. t['q'] = {
  2341. id: _util.OPS.save,
  2342. numArgs: 0,
  2343. variableArgs: false
  2344. };
  2345. t['Q'] = {
  2346. id: _util.OPS.restore,
  2347. numArgs: 0,
  2348. variableArgs: false
  2349. };
  2350. t['cm'] = {
  2351. id: _util.OPS.transform,
  2352. numArgs: 6,
  2353. variableArgs: false
  2354. };
  2355. t['m'] = {
  2356. id: _util.OPS.moveTo,
  2357. numArgs: 2,
  2358. variableArgs: false
  2359. };
  2360. t['l'] = {
  2361. id: _util.OPS.lineTo,
  2362. numArgs: 2,
  2363. variableArgs: false
  2364. };
  2365. t['c'] = {
  2366. id: _util.OPS.curveTo,
  2367. numArgs: 6,
  2368. variableArgs: false
  2369. };
  2370. t['v'] = {
  2371. id: _util.OPS.curveTo2,
  2372. numArgs: 4,
  2373. variableArgs: false
  2374. };
  2375. t['y'] = {
  2376. id: _util.OPS.curveTo3,
  2377. numArgs: 4,
  2378. variableArgs: false
  2379. };
  2380. t['h'] = {
  2381. id: _util.OPS.closePath,
  2382. numArgs: 0,
  2383. variableArgs: false
  2384. };
  2385. t['re'] = {
  2386. id: _util.OPS.rectangle,
  2387. numArgs: 4,
  2388. variableArgs: false
  2389. };
  2390. t['S'] = {
  2391. id: _util.OPS.stroke,
  2392. numArgs: 0,
  2393. variableArgs: false
  2394. };
  2395. t['s'] = {
  2396. id: _util.OPS.closeStroke,
  2397. numArgs: 0,
  2398. variableArgs: false
  2399. };
  2400. t['f'] = {
  2401. id: _util.OPS.fill,
  2402. numArgs: 0,
  2403. variableArgs: false
  2404. };
  2405. t['F'] = {
  2406. id: _util.OPS.fill,
  2407. numArgs: 0,
  2408. variableArgs: false
  2409. };
  2410. t['f*'] = {
  2411. id: _util.OPS.eoFill,
  2412. numArgs: 0,
  2413. variableArgs: false
  2414. };
  2415. t['B'] = {
  2416. id: _util.OPS.fillStroke,
  2417. numArgs: 0,
  2418. variableArgs: false
  2419. };
  2420. t['B*'] = {
  2421. id: _util.OPS.eoFillStroke,
  2422. numArgs: 0,
  2423. variableArgs: false
  2424. };
  2425. t['b'] = {
  2426. id: _util.OPS.closeFillStroke,
  2427. numArgs: 0,
  2428. variableArgs: false
  2429. };
  2430. t['b*'] = {
  2431. id: _util.OPS.closeEOFillStroke,
  2432. numArgs: 0,
  2433. variableArgs: false
  2434. };
  2435. t['n'] = {
  2436. id: _util.OPS.endPath,
  2437. numArgs: 0,
  2438. variableArgs: false
  2439. };
  2440. t['W'] = {
  2441. id: _util.OPS.clip,
  2442. numArgs: 0,
  2443. variableArgs: false
  2444. };
  2445. t['W*'] = {
  2446. id: _util.OPS.eoClip,
  2447. numArgs: 0,
  2448. variableArgs: false
  2449. };
  2450. t['BT'] = {
  2451. id: _util.OPS.beginText,
  2452. numArgs: 0,
  2453. variableArgs: false
  2454. };
  2455. t['ET'] = {
  2456. id: _util.OPS.endText,
  2457. numArgs: 0,
  2458. variableArgs: false
  2459. };
  2460. t['Tc'] = {
  2461. id: _util.OPS.setCharSpacing,
  2462. numArgs: 1,
  2463. variableArgs: false
  2464. };
  2465. t['Tw'] = {
  2466. id: _util.OPS.setWordSpacing,
  2467. numArgs: 1,
  2468. variableArgs: false
  2469. };
  2470. t['Tz'] = {
  2471. id: _util.OPS.setHScale,
  2472. numArgs: 1,
  2473. variableArgs: false
  2474. };
  2475. t['TL'] = {
  2476. id: _util.OPS.setLeading,
  2477. numArgs: 1,
  2478. variableArgs: false
  2479. };
  2480. t['Tf'] = {
  2481. id: _util.OPS.setFont,
  2482. numArgs: 2,
  2483. variableArgs: false
  2484. };
  2485. t['Tr'] = {
  2486. id: _util.OPS.setTextRenderingMode,
  2487. numArgs: 1,
  2488. variableArgs: false
  2489. };
  2490. t['Ts'] = {
  2491. id: _util.OPS.setTextRise,
  2492. numArgs: 1,
  2493. variableArgs: false
  2494. };
  2495. t['Td'] = {
  2496. id: _util.OPS.moveText,
  2497. numArgs: 2,
  2498. variableArgs: false
  2499. };
  2500. t['TD'] = {
  2501. id: _util.OPS.setLeadingMoveText,
  2502. numArgs: 2,
  2503. variableArgs: false
  2504. };
  2505. t['Tm'] = {
  2506. id: _util.OPS.setTextMatrix,
  2507. numArgs: 6,
  2508. variableArgs: false
  2509. };
  2510. t['T*'] = {
  2511. id: _util.OPS.nextLine,
  2512. numArgs: 0,
  2513. variableArgs: false
  2514. };
  2515. t['Tj'] = {
  2516. id: _util.OPS.showText,
  2517. numArgs: 1,
  2518. variableArgs: false
  2519. };
  2520. t['TJ'] = {
  2521. id: _util.OPS.showSpacedText,
  2522. numArgs: 1,
  2523. variableArgs: false
  2524. };
  2525. t['\''] = {
  2526. id: _util.OPS.nextLineShowText,
  2527. numArgs: 1,
  2528. variableArgs: false
  2529. };
  2530. t['"'] = {
  2531. id: _util.OPS.nextLineSetSpacingShowText,
  2532. numArgs: 3,
  2533. variableArgs: false
  2534. };
  2535. t['d0'] = {
  2536. id: _util.OPS.setCharWidth,
  2537. numArgs: 2,
  2538. variableArgs: false
  2539. };
  2540. t['d1'] = {
  2541. id: _util.OPS.setCharWidthAndBounds,
  2542. numArgs: 6,
  2543. variableArgs: false
  2544. };
  2545. t['CS'] = {
  2546. id: _util.OPS.setStrokeColorSpace,
  2547. numArgs: 1,
  2548. variableArgs: false
  2549. };
  2550. t['cs'] = {
  2551. id: _util.OPS.setFillColorSpace,
  2552. numArgs: 1,
  2553. variableArgs: false
  2554. };
  2555. t['SC'] = {
  2556. id: _util.OPS.setStrokeColor,
  2557. numArgs: 4,
  2558. variableArgs: true
  2559. };
  2560. t['SCN'] = {
  2561. id: _util.OPS.setStrokeColorN,
  2562. numArgs: 33,
  2563. variableArgs: true
  2564. };
  2565. t['sc'] = {
  2566. id: _util.OPS.setFillColor,
  2567. numArgs: 4,
  2568. variableArgs: true
  2569. };
  2570. t['scn'] = {
  2571. id: _util.OPS.setFillColorN,
  2572. numArgs: 33,
  2573. variableArgs: true
  2574. };
  2575. t['G'] = {
  2576. id: _util.OPS.setStrokeGray,
  2577. numArgs: 1,
  2578. variableArgs: false
  2579. };
  2580. t['g'] = {
  2581. id: _util.OPS.setFillGray,
  2582. numArgs: 1,
  2583. variableArgs: false
  2584. };
  2585. t['RG'] = {
  2586. id: _util.OPS.setStrokeRGBColor,
  2587. numArgs: 3,
  2588. variableArgs: false
  2589. };
  2590. t['rg'] = {
  2591. id: _util.OPS.setFillRGBColor,
  2592. numArgs: 3,
  2593. variableArgs: false
  2594. };
  2595. t['K'] = {
  2596. id: _util.OPS.setStrokeCMYKColor,
  2597. numArgs: 4,
  2598. variableArgs: false
  2599. };
  2600. t['k'] = {
  2601. id: _util.OPS.setFillCMYKColor,
  2602. numArgs: 4,
  2603. variableArgs: false
  2604. };
  2605. t['sh'] = {
  2606. id: _util.OPS.shadingFill,
  2607. numArgs: 1,
  2608. variableArgs: false
  2609. };
  2610. t['BI'] = {
  2611. id: _util.OPS.beginInlineImage,
  2612. numArgs: 0,
  2613. variableArgs: false
  2614. };
  2615. t['ID'] = {
  2616. id: _util.OPS.beginImageData,
  2617. numArgs: 0,
  2618. variableArgs: false
  2619. };
  2620. t['EI'] = {
  2621. id: _util.OPS.endInlineImage,
  2622. numArgs: 1,
  2623. variableArgs: false
  2624. };
  2625. t['Do'] = {
  2626. id: _util.OPS.paintXObject,
  2627. numArgs: 1,
  2628. variableArgs: false
  2629. };
  2630. t['MP'] = {
  2631. id: _util.OPS.markPoint,
  2632. numArgs: 1,
  2633. variableArgs: false
  2634. };
  2635. t['DP'] = {
  2636. id: _util.OPS.markPointProps,
  2637. numArgs: 2,
  2638. variableArgs: false
  2639. };
  2640. t['BMC'] = {
  2641. id: _util.OPS.beginMarkedContent,
  2642. numArgs: 1,
  2643. variableArgs: false
  2644. };
  2645. t['BDC'] = {
  2646. id: _util.OPS.beginMarkedContentProps,
  2647. numArgs: 2,
  2648. variableArgs: false
  2649. };
  2650. t['EMC'] = {
  2651. id: _util.OPS.endMarkedContent,
  2652. numArgs: 0,
  2653. variableArgs: false
  2654. };
  2655. t['BX'] = {
  2656. id: _util.OPS.beginCompat,
  2657. numArgs: 0,
  2658. variableArgs: false
  2659. };
  2660. t['EX'] = {
  2661. id: _util.OPS.endCompat,
  2662. numArgs: 0,
  2663. variableArgs: false
  2664. };
  2665. t['BM'] = null;
  2666. t['BD'] = null;
  2667. t['true'] = null;
  2668. t['fa'] = null;
  2669. t['fal'] = null;
  2670. t['fals'] = null;
  2671. t['false'] = null;
  2672. t['nu'] = null;
  2673. t['nul'] = null;
  2674. t['null'] = null;
  2675. });
  2676. function EvaluatorPreprocessor(stream, xref, stateManager) {
  2677. this.opMap = getOPMap();
  2678. this.parser = new _parser.Parser(new _parser.Lexer(stream, this.opMap), false, xref);
  2679. this.stateManager = stateManager;
  2680. this.nonProcessedArgs = [];
  2681. }
  2682. EvaluatorPreprocessor.prototype = {
  2683. get savedStatesDepth() {
  2684. return this.stateManager.stateStack.length;
  2685. },
  2686. read: function EvaluatorPreprocessor_read(operation) {
  2687. var args = operation.args;
  2688. while (true) {
  2689. var obj = this.parser.getObj();
  2690. if ((0, _primitives.isCmd)(obj)) {
  2691. var cmd = obj.cmd;
  2692. var opSpec = this.opMap[cmd];
  2693. if (!opSpec) {
  2694. (0, _util.warn)('Unknown command "' + cmd + '"');
  2695. continue;
  2696. }
  2697. var fn = opSpec.id;
  2698. var numArgs = opSpec.numArgs;
  2699. var argsLength = args !== null ? args.length : 0;
  2700. if (!opSpec.variableArgs) {
  2701. if (argsLength !== numArgs) {
  2702. var nonProcessedArgs = this.nonProcessedArgs;
  2703. while (argsLength > numArgs) {
  2704. nonProcessedArgs.push(args.shift());
  2705. argsLength--;
  2706. }
  2707. while (argsLength < numArgs && nonProcessedArgs.length !== 0) {
  2708. if (args === null) {
  2709. args = [];
  2710. }
  2711. args.unshift(nonProcessedArgs.pop());
  2712. argsLength++;
  2713. }
  2714. }
  2715. if (argsLength < numArgs) {
  2716. (0, _util.warn)('Skipping command ' + fn + ': expected ' + numArgs + ' args, but received ' + argsLength + ' args.');
  2717. if (args !== null) {
  2718. args.length = 0;
  2719. }
  2720. continue;
  2721. }
  2722. } else if (argsLength > numArgs) {
  2723. (0, _util.info)('Command ' + fn + ': expected [0,' + numArgs + '] args, but received ' + argsLength + ' args.');
  2724. }
  2725. this.preprocessCommand(fn, args);
  2726. operation.fn = fn;
  2727. operation.args = args;
  2728. return true;
  2729. }
  2730. if ((0, _primitives.isEOF)(obj)) {
  2731. return false;
  2732. }
  2733. if (obj !== null) {
  2734. if (args === null) {
  2735. args = [];
  2736. }
  2737. args.push(obj);
  2738. if (args.length > 33) {
  2739. throw new _util.FormatError('Too many arguments');
  2740. }
  2741. }
  2742. }
  2743. },
  2744. preprocessCommand: function EvaluatorPreprocessor_preprocessCommand(fn, args) {
  2745. switch (fn | 0) {
  2746. case _util.OPS.save:
  2747. this.stateManager.save();
  2748. break;
  2749. case _util.OPS.restore:
  2750. this.stateManager.restore();
  2751. break;
  2752. case _util.OPS.transform:
  2753. this.stateManager.transform(args);
  2754. break;
  2755. }
  2756. }
  2757. };
  2758. return EvaluatorPreprocessor;
  2759. }();
  2760. var QueueOptimizer = function QueueOptimizerClosure() {
  2761. function addState(parentState, pattern, fn) {
  2762. var state = parentState;
  2763. for (var i = 0, ii = pattern.length - 1; i < ii; i++) {
  2764. var item = pattern[i];
  2765. state = state[item] || (state[item] = []);
  2766. }
  2767. state[pattern[pattern.length - 1]] = fn;
  2768. }
  2769. function handlePaintSolidColorImageMask(iFirstSave, count, fnArray, argsArray) {
  2770. var iFirstPIMXO = iFirstSave + 2;
  2771. for (var i = 0; i < count; i++) {
  2772. var arg = argsArray[iFirstPIMXO + 4 * i];
  2773. var imageMask = arg.length === 1 && arg[0];
  2774. if (imageMask && imageMask.width === 1 && imageMask.height === 1 && (!imageMask.data.length || imageMask.data.length === 1 && imageMask.data[0] === 0)) {
  2775. fnArray[iFirstPIMXO + 4 * i] = _util.OPS.paintSolidColorImageMask;
  2776. continue;
  2777. }
  2778. break;
  2779. }
  2780. return count - i;
  2781. }
  2782. var InitialState = [];
  2783. addState(InitialState, [_util.OPS.save, _util.OPS.transform, _util.OPS.paintInlineImageXObject, _util.OPS.restore], function foundInlineImageGroup(context) {
  2784. var MIN_IMAGES_IN_INLINE_IMAGES_BLOCK = 10;
  2785. var MAX_IMAGES_IN_INLINE_IMAGES_BLOCK = 200;
  2786. var MAX_WIDTH = 1000;
  2787. var IMAGE_PADDING = 1;
  2788. var fnArray = context.fnArray,
  2789. argsArray = context.argsArray;
  2790. var curr = context.iCurr;
  2791. var iFirstSave = curr - 3;
  2792. var iFirstTransform = curr - 2;
  2793. var iFirstPIIXO = curr - 1;
  2794. var i = iFirstSave + 4;
  2795. var ii = fnArray.length;
  2796. while (i + 3 < ii) {
  2797. if (fnArray[i] !== _util.OPS.save || fnArray[i + 1] !== _util.OPS.transform || fnArray[i + 2] !== _util.OPS.paintInlineImageXObject || fnArray[i + 3] !== _util.OPS.restore) {
  2798. break;
  2799. }
  2800. i += 4;
  2801. }
  2802. var count = Math.min((i - iFirstSave) / 4, MAX_IMAGES_IN_INLINE_IMAGES_BLOCK);
  2803. if (count < MIN_IMAGES_IN_INLINE_IMAGES_BLOCK) {
  2804. return i;
  2805. }
  2806. var maxX = 0;
  2807. var map = [],
  2808. maxLineHeight = 0;
  2809. var currentX = IMAGE_PADDING,
  2810. currentY = IMAGE_PADDING;
  2811. var q;
  2812. for (q = 0; q < count; q++) {
  2813. var transform = argsArray[iFirstTransform + (q << 2)];
  2814. var img = argsArray[iFirstPIIXO + (q << 2)][0];
  2815. if (currentX + img.width > MAX_WIDTH) {
  2816. maxX = Math.max(maxX, currentX);
  2817. currentY += maxLineHeight + 2 * IMAGE_PADDING;
  2818. currentX = 0;
  2819. maxLineHeight = 0;
  2820. }
  2821. map.push({
  2822. transform: transform,
  2823. x: currentX,
  2824. y: currentY,
  2825. w: img.width,
  2826. h: img.height
  2827. });
  2828. currentX += img.width + 2 * IMAGE_PADDING;
  2829. maxLineHeight = Math.max(maxLineHeight, img.height);
  2830. }
  2831. var imgWidth = Math.max(maxX, currentX) + IMAGE_PADDING;
  2832. var imgHeight = currentY + maxLineHeight + IMAGE_PADDING;
  2833. var imgData = new Uint8Array(imgWidth * imgHeight * 4);
  2834. var imgRowSize = imgWidth << 2;
  2835. for (q = 0; q < count; q++) {
  2836. var data = argsArray[iFirstPIIXO + (q << 2)][0].data;
  2837. var rowSize = map[q].w << 2;
  2838. var dataOffset = 0;
  2839. var offset = map[q].x + map[q].y * imgWidth << 2;
  2840. imgData.set(data.subarray(0, rowSize), offset - imgRowSize);
  2841. for (var k = 0, kk = map[q].h; k < kk; k++) {
  2842. imgData.set(data.subarray(dataOffset, dataOffset + rowSize), offset);
  2843. dataOffset += rowSize;
  2844. offset += imgRowSize;
  2845. }
  2846. imgData.set(data.subarray(dataOffset - rowSize, dataOffset), offset);
  2847. while (offset >= 0) {
  2848. data[offset - 4] = data[offset];
  2849. data[offset - 3] = data[offset + 1];
  2850. data[offset - 2] = data[offset + 2];
  2851. data[offset - 1] = data[offset + 3];
  2852. data[offset + rowSize] = data[offset + rowSize - 4];
  2853. data[offset + rowSize + 1] = data[offset + rowSize - 3];
  2854. data[offset + rowSize + 2] = data[offset + rowSize - 2];
  2855. data[offset + rowSize + 3] = data[offset + rowSize - 1];
  2856. offset -= imgRowSize;
  2857. }
  2858. }
  2859. fnArray.splice(iFirstSave, count * 4, _util.OPS.paintInlineImageXObjectGroup);
  2860. argsArray.splice(iFirstSave, count * 4, [{
  2861. width: imgWidth,
  2862. height: imgHeight,
  2863. kind: _util.ImageKind.RGBA_32BPP,
  2864. data: imgData
  2865. }, map]);
  2866. return iFirstSave + 1;
  2867. });
  2868. addState(InitialState, [_util.OPS.save, _util.OPS.transform, _util.OPS.paintImageMaskXObject, _util.OPS.restore], function foundImageMaskGroup(context) {
  2869. var MIN_IMAGES_IN_MASKS_BLOCK = 10;
  2870. var MAX_IMAGES_IN_MASKS_BLOCK = 100;
  2871. var MAX_SAME_IMAGES_IN_MASKS_BLOCK = 1000;
  2872. var fnArray = context.fnArray,
  2873. argsArray = context.argsArray;
  2874. var curr = context.iCurr;
  2875. var iFirstSave = curr - 3;
  2876. var iFirstTransform = curr - 2;
  2877. var iFirstPIMXO = curr - 1;
  2878. var i = iFirstSave + 4;
  2879. var ii = fnArray.length;
  2880. while (i + 3 < ii) {
  2881. if (fnArray[i] !== _util.OPS.save || fnArray[i + 1] !== _util.OPS.transform || fnArray[i + 2] !== _util.OPS.paintImageMaskXObject || fnArray[i + 3] !== _util.OPS.restore) {
  2882. break;
  2883. }
  2884. i += 4;
  2885. }
  2886. var count = (i - iFirstSave) / 4;
  2887. count = handlePaintSolidColorImageMask(iFirstSave, count, fnArray, argsArray);
  2888. if (count < MIN_IMAGES_IN_MASKS_BLOCK) {
  2889. return i;
  2890. }
  2891. var q;
  2892. var isSameImage = false;
  2893. var iTransform, transformArgs;
  2894. var firstPIMXOArg0 = argsArray[iFirstPIMXO][0];
  2895. if (argsArray[iFirstTransform][1] === 0 && argsArray[iFirstTransform][2] === 0) {
  2896. isSameImage = true;
  2897. var firstTransformArg0 = argsArray[iFirstTransform][0];
  2898. var firstTransformArg3 = argsArray[iFirstTransform][3];
  2899. iTransform = iFirstTransform + 4;
  2900. var iPIMXO = iFirstPIMXO + 4;
  2901. for (q = 1; q < count; q++, iTransform += 4, iPIMXO += 4) {
  2902. transformArgs = argsArray[iTransform];
  2903. if (argsArray[iPIMXO][0] !== firstPIMXOArg0 || transformArgs[0] !== firstTransformArg0 || transformArgs[1] !== 0 || transformArgs[2] !== 0 || transformArgs[3] !== firstTransformArg3) {
  2904. if (q < MIN_IMAGES_IN_MASKS_BLOCK) {
  2905. isSameImage = false;
  2906. } else {
  2907. count = q;
  2908. }
  2909. break;
  2910. }
  2911. }
  2912. }
  2913. if (isSameImage) {
  2914. count = Math.min(count, MAX_SAME_IMAGES_IN_MASKS_BLOCK);
  2915. var positions = new Float32Array(count * 2);
  2916. iTransform = iFirstTransform;
  2917. for (q = 0; q < count; q++, iTransform += 4) {
  2918. transformArgs = argsArray[iTransform];
  2919. positions[q << 1] = transformArgs[4];
  2920. positions[(q << 1) + 1] = transformArgs[5];
  2921. }
  2922. fnArray.splice(iFirstSave, count * 4, _util.OPS.paintImageMaskXObjectRepeat);
  2923. argsArray.splice(iFirstSave, count * 4, [firstPIMXOArg0, firstTransformArg0, firstTransformArg3, positions]);
  2924. } else {
  2925. count = Math.min(count, MAX_IMAGES_IN_MASKS_BLOCK);
  2926. var images = [];
  2927. for (q = 0; q < count; q++) {
  2928. transformArgs = argsArray[iFirstTransform + (q << 2)];
  2929. var maskParams = argsArray[iFirstPIMXO + (q << 2)][0];
  2930. images.push({
  2931. data: maskParams.data,
  2932. width: maskParams.width,
  2933. height: maskParams.height,
  2934. transform: transformArgs
  2935. });
  2936. }
  2937. fnArray.splice(iFirstSave, count * 4, _util.OPS.paintImageMaskXObjectGroup);
  2938. argsArray.splice(iFirstSave, count * 4, [images]);
  2939. }
  2940. return iFirstSave + 1;
  2941. });
  2942. addState(InitialState, [_util.OPS.save, _util.OPS.transform, _util.OPS.paintImageXObject, _util.OPS.restore], function (context) {
  2943. var MIN_IMAGES_IN_BLOCK = 3;
  2944. var MAX_IMAGES_IN_BLOCK = 1000;
  2945. var fnArray = context.fnArray,
  2946. argsArray = context.argsArray;
  2947. var curr = context.iCurr;
  2948. var iFirstSave = curr - 3;
  2949. var iFirstTransform = curr - 2;
  2950. var iFirstPIXO = curr - 1;
  2951. var iFirstRestore = curr;
  2952. if (argsArray[iFirstTransform][1] !== 0 || argsArray[iFirstTransform][2] !== 0) {
  2953. return iFirstRestore + 1;
  2954. }
  2955. var firstPIXOArg0 = argsArray[iFirstPIXO][0];
  2956. var firstTransformArg0 = argsArray[iFirstTransform][0];
  2957. var firstTransformArg3 = argsArray[iFirstTransform][3];
  2958. var i = iFirstSave + 4;
  2959. var ii = fnArray.length;
  2960. while (i + 3 < ii) {
  2961. if (fnArray[i] !== _util.OPS.save || fnArray[i + 1] !== _util.OPS.transform || fnArray[i + 2] !== _util.OPS.paintImageXObject || fnArray[i + 3] !== _util.OPS.restore) {
  2962. break;
  2963. }
  2964. if (argsArray[i + 1][0] !== firstTransformArg0 || argsArray[i + 1][1] !== 0 || argsArray[i + 1][2] !== 0 || argsArray[i + 1][3] !== firstTransformArg3) {
  2965. break;
  2966. }
  2967. if (argsArray[i + 2][0] !== firstPIXOArg0) {
  2968. break;
  2969. }
  2970. i += 4;
  2971. }
  2972. var count = Math.min((i - iFirstSave) / 4, MAX_IMAGES_IN_BLOCK);
  2973. if (count < MIN_IMAGES_IN_BLOCK) {
  2974. return i;
  2975. }
  2976. var positions = new Float32Array(count * 2);
  2977. var iTransform = iFirstTransform;
  2978. for (var q = 0; q < count; q++, iTransform += 4) {
  2979. var transformArgs = argsArray[iTransform];
  2980. positions[q << 1] = transformArgs[4];
  2981. positions[(q << 1) + 1] = transformArgs[5];
  2982. }
  2983. var args = [firstPIXOArg0, firstTransformArg0, firstTransformArg3, positions];
  2984. fnArray.splice(iFirstSave, count * 4, _util.OPS.paintImageXObjectRepeat);
  2985. argsArray.splice(iFirstSave, count * 4, args);
  2986. return iFirstSave + 1;
  2987. });
  2988. addState(InitialState, [_util.OPS.beginText, _util.OPS.setFont, _util.OPS.setTextMatrix, _util.OPS.showText, _util.OPS.endText], function (context) {
  2989. var MIN_CHARS_IN_BLOCK = 3;
  2990. var MAX_CHARS_IN_BLOCK = 1000;
  2991. var fnArray = context.fnArray,
  2992. argsArray = context.argsArray;
  2993. var curr = context.iCurr;
  2994. var iFirstBeginText = curr - 4;
  2995. var iFirstSetFont = curr - 3;
  2996. var iFirstSetTextMatrix = curr - 2;
  2997. var iFirstShowText = curr - 1;
  2998. var iFirstEndText = curr;
  2999. var firstSetFontArg0 = argsArray[iFirstSetFont][0];
  3000. var firstSetFontArg1 = argsArray[iFirstSetFont][1];
  3001. var i = iFirstBeginText + 5;
  3002. var ii = fnArray.length;
  3003. while (i + 4 < ii) {
  3004. 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) {
  3005. break;
  3006. }
  3007. if (argsArray[i + 1][0] !== firstSetFontArg0 || argsArray[i + 1][1] !== firstSetFontArg1) {
  3008. break;
  3009. }
  3010. i += 5;
  3011. }
  3012. var count = Math.min((i - iFirstBeginText) / 5, MAX_CHARS_IN_BLOCK);
  3013. if (count < MIN_CHARS_IN_BLOCK) {
  3014. return i;
  3015. }
  3016. var iFirst = iFirstBeginText;
  3017. 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) {
  3018. count++;
  3019. iFirst -= 5;
  3020. }
  3021. var iEndText = iFirst + 4;
  3022. for (var q = 1; q < count; q++) {
  3023. fnArray.splice(iEndText, 3);
  3024. argsArray.splice(iEndText, 3);
  3025. iEndText += 2;
  3026. }
  3027. return iEndText + 1;
  3028. });
  3029. function QueueOptimizer() {}
  3030. QueueOptimizer.prototype = {
  3031. optimize: function QueueOptimizer_optimize(queue) {
  3032. var fnArray = queue.fnArray,
  3033. argsArray = queue.argsArray;
  3034. var context = {
  3035. iCurr: 0,
  3036. fnArray: fnArray,
  3037. argsArray: argsArray
  3038. };
  3039. var state;
  3040. var i = 0,
  3041. ii = fnArray.length;
  3042. while (i < ii) {
  3043. state = (state || InitialState)[fnArray[i]];
  3044. if (typeof state === 'function') {
  3045. context.iCurr = i;
  3046. i = state(context);
  3047. state = undefined;
  3048. ii = context.fnArray.length;
  3049. } else {
  3050. i++;
  3051. }
  3052. }
  3053. }
  3054. };
  3055. return QueueOptimizer;
  3056. }();
  3057. exports.OperatorList = OperatorList;
  3058. exports.PartialEvaluator = PartialEvaluator;