evaluator.js 106 KB

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