2
0

evaluator.js 112 KB

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