evaluator.js 104 KB

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