evaluator.js 97 KB

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