evaluator.js 112 KB

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