evaluator.js 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753
  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. _buildSimpleFontToUnicode: function _buildSimpleFontToUnicode(properties) {
  1562. (0, _util.assert)(!properties.composite, 'Must be a simple font.');
  1563. var toUnicode = [],
  1564. charcode = void 0,
  1565. glyphName = void 0;
  1566. var encoding = properties.defaultEncoding.slice();
  1567. var baseEncodingName = properties.baseEncodingName;
  1568. var differences = properties.differences;
  1569. for (charcode in differences) {
  1570. glyphName = differences[charcode];
  1571. if (glyphName === '.notdef') {
  1572. continue;
  1573. }
  1574. encoding[charcode] = glyphName;
  1575. }
  1576. var glyphsUnicodeMap = (0, _glyphlist.getGlyphsUnicode)();
  1577. for (charcode in encoding) {
  1578. glyphName = encoding[charcode];
  1579. if (glyphName === '') {
  1580. continue;
  1581. } else if (glyphsUnicodeMap[glyphName] === undefined) {
  1582. var code = 0;
  1583. switch (glyphName[0]) {
  1584. case 'G':
  1585. if (glyphName.length === 3) {
  1586. code = parseInt(glyphName.substr(1), 16);
  1587. }
  1588. break;
  1589. case 'g':
  1590. if (glyphName.length === 5) {
  1591. code = parseInt(glyphName.substr(1), 16);
  1592. }
  1593. break;
  1594. case 'C':
  1595. case 'c':
  1596. if (glyphName.length >= 3) {
  1597. code = +glyphName.substr(1);
  1598. }
  1599. break;
  1600. default:
  1601. var unicode = (0, _unicode.getUnicodeForGlyph)(glyphName, glyphsUnicodeMap);
  1602. if (unicode !== -1) {
  1603. code = unicode;
  1604. }
  1605. }
  1606. if (code) {
  1607. if (baseEncodingName && code === +charcode) {
  1608. var baseEncoding = (0, _encodings.getEncoding)(baseEncodingName);
  1609. if (baseEncoding && (glyphName = baseEncoding[charcode])) {
  1610. toUnicode[charcode] = String.fromCharCode(glyphsUnicodeMap[glyphName]);
  1611. continue;
  1612. }
  1613. }
  1614. toUnicode[charcode] = String.fromCharCode(code);
  1615. }
  1616. continue;
  1617. }
  1618. toUnicode[charcode] = String.fromCharCode(glyphsUnicodeMap[glyphName]);
  1619. }
  1620. return new _fonts.ToUnicodeMap(toUnicode);
  1621. },
  1622. buildToUnicode: function buildToUnicode(properties) {
  1623. properties.hasIncludedToUnicodeMap = !!properties.toUnicode && properties.toUnicode.length > 0;
  1624. if (properties.hasIncludedToUnicodeMap) {
  1625. if (!properties.composite && properties.hasEncoding) {
  1626. properties.fallbackToUnicode = this._buildSimpleFontToUnicode(properties);
  1627. }
  1628. return Promise.resolve(properties.toUnicode);
  1629. }
  1630. if (!properties.composite) {
  1631. return Promise.resolve(this._buildSimpleFontToUnicode(properties));
  1632. }
  1633. 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'))) {
  1634. var registry = properties.cidSystemInfo.registry;
  1635. var ordering = properties.cidSystemInfo.ordering;
  1636. var ucs2CMapName = _primitives.Name.get(registry + '-' + ordering + '-UCS2');
  1637. return _cmap.CMapFactory.create({
  1638. encoding: ucs2CMapName,
  1639. fetchBuiltInCMap: this.fetchBuiltInCMap,
  1640. useCMap: null
  1641. }).then(function (ucs2CMap) {
  1642. var cMap = properties.cMap;
  1643. var toUnicode = [];
  1644. cMap.forEach(function (charcode, cid) {
  1645. if (cid > 0xffff) {
  1646. throw new _util.FormatError('Max size of CID is 65,535');
  1647. }
  1648. var ucs2 = ucs2CMap.lookup(cid);
  1649. if (ucs2) {
  1650. toUnicode[charcode] = String.fromCharCode((ucs2.charCodeAt(0) << 8) + ucs2.charCodeAt(1));
  1651. }
  1652. });
  1653. return new _fonts.ToUnicodeMap(toUnicode);
  1654. });
  1655. }
  1656. return Promise.resolve(new _fonts.IdentityToUnicodeMap(properties.firstChar, properties.lastChar));
  1657. },
  1658. readToUnicode: function PartialEvaluator_readToUnicode(toUnicode) {
  1659. var cmapObj = toUnicode;
  1660. if ((0, _primitives.isName)(cmapObj)) {
  1661. return _cmap.CMapFactory.create({
  1662. encoding: cmapObj,
  1663. fetchBuiltInCMap: this.fetchBuiltInCMap,
  1664. useCMap: null
  1665. }).then(function (cmap) {
  1666. if (cmap instanceof _cmap.IdentityCMap) {
  1667. return new _fonts.IdentityToUnicodeMap(0, 0xFFFF);
  1668. }
  1669. return new _fonts.ToUnicodeMap(cmap.getMap());
  1670. });
  1671. } else if ((0, _primitives.isStream)(cmapObj)) {
  1672. return _cmap.CMapFactory.create({
  1673. encoding: cmapObj,
  1674. fetchBuiltInCMap: this.fetchBuiltInCMap,
  1675. useCMap: null
  1676. }).then(function (cmap) {
  1677. if (cmap instanceof _cmap.IdentityCMap) {
  1678. return new _fonts.IdentityToUnicodeMap(0, 0xFFFF);
  1679. }
  1680. var map = new Array(cmap.length);
  1681. cmap.forEach(function (charCode, token) {
  1682. var str = [];
  1683. for (var k = 0; k < token.length; k += 2) {
  1684. var w1 = token.charCodeAt(k) << 8 | token.charCodeAt(k + 1);
  1685. if ((w1 & 0xF800) !== 0xD800) {
  1686. str.push(w1);
  1687. continue;
  1688. }
  1689. k += 2;
  1690. var w2 = token.charCodeAt(k) << 8 | token.charCodeAt(k + 1);
  1691. str.push(((w1 & 0x3ff) << 10) + (w2 & 0x3ff) + 0x10000);
  1692. }
  1693. map[charCode] = String.fromCharCode.apply(String, str);
  1694. });
  1695. return new _fonts.ToUnicodeMap(map);
  1696. });
  1697. }
  1698. return Promise.resolve(null);
  1699. },
  1700. readCidToGidMap: function PartialEvaluator_readCidToGidMap(cidToGidStream) {
  1701. var glyphsData = cidToGidStream.getBytes();
  1702. var result = [];
  1703. for (var j = 0, jj = glyphsData.length; j < jj; j++) {
  1704. var glyphID = glyphsData[j++] << 8 | glyphsData[j];
  1705. if (glyphID === 0) {
  1706. continue;
  1707. }
  1708. var code = j >> 1;
  1709. result[code] = glyphID;
  1710. }
  1711. return result;
  1712. },
  1713. extractWidths: function PartialEvaluator_extractWidths(dict, descriptor, properties) {
  1714. var xref = this.xref;
  1715. var glyphsWidths = [];
  1716. var defaultWidth = 0;
  1717. var glyphsVMetrics = [];
  1718. var defaultVMetrics;
  1719. var i, ii, j, jj, start, code, widths;
  1720. if (properties.composite) {
  1721. defaultWidth = dict.has('DW') ? dict.get('DW') : 1000;
  1722. widths = dict.get('W');
  1723. if (widths) {
  1724. for (i = 0, ii = widths.length; i < ii; i++) {
  1725. start = xref.fetchIfRef(widths[i++]);
  1726. code = xref.fetchIfRef(widths[i]);
  1727. if (Array.isArray(code)) {
  1728. for (j = 0, jj = code.length; j < jj; j++) {
  1729. glyphsWidths[start++] = xref.fetchIfRef(code[j]);
  1730. }
  1731. } else {
  1732. var width = xref.fetchIfRef(widths[++i]);
  1733. for (j = start; j <= code; j++) {
  1734. glyphsWidths[j] = width;
  1735. }
  1736. }
  1737. }
  1738. }
  1739. if (properties.vertical) {
  1740. var vmetrics = dict.getArray('DW2') || [880, -1000];
  1741. defaultVMetrics = [vmetrics[1], defaultWidth * 0.5, vmetrics[0]];
  1742. vmetrics = dict.get('W2');
  1743. if (vmetrics) {
  1744. for (i = 0, ii = vmetrics.length; i < ii; i++) {
  1745. start = xref.fetchIfRef(vmetrics[i++]);
  1746. code = xref.fetchIfRef(vmetrics[i]);
  1747. if (Array.isArray(code)) {
  1748. for (j = 0, jj = code.length; j < jj; j++) {
  1749. glyphsVMetrics[start++] = [xref.fetchIfRef(code[j++]), xref.fetchIfRef(code[j++]), xref.fetchIfRef(code[j])];
  1750. }
  1751. } else {
  1752. var vmetric = [xref.fetchIfRef(vmetrics[++i]), xref.fetchIfRef(vmetrics[++i]), xref.fetchIfRef(vmetrics[++i])];
  1753. for (j = start; j <= code; j++) {
  1754. glyphsVMetrics[j] = vmetric;
  1755. }
  1756. }
  1757. }
  1758. }
  1759. }
  1760. } else {
  1761. var firstChar = properties.firstChar;
  1762. widths = dict.get('Widths');
  1763. if (widths) {
  1764. j = firstChar;
  1765. for (i = 0, ii = widths.length; i < ii; i++) {
  1766. glyphsWidths[j++] = xref.fetchIfRef(widths[i]);
  1767. }
  1768. defaultWidth = parseFloat(descriptor.get('MissingWidth')) || 0;
  1769. } else {
  1770. var baseFontName = dict.get('BaseFont');
  1771. if ((0, _primitives.isName)(baseFontName)) {
  1772. var metrics = this.getBaseFontMetrics(baseFontName.name);
  1773. glyphsWidths = this.buildCharCodeToWidth(metrics.widths, properties);
  1774. defaultWidth = metrics.defaultWidth;
  1775. }
  1776. }
  1777. }
  1778. var isMonospace = true;
  1779. var firstWidth = defaultWidth;
  1780. for (var glyph in glyphsWidths) {
  1781. var glyphWidth = glyphsWidths[glyph];
  1782. if (!glyphWidth) {
  1783. continue;
  1784. }
  1785. if (!firstWidth) {
  1786. firstWidth = glyphWidth;
  1787. continue;
  1788. }
  1789. if (firstWidth !== glyphWidth) {
  1790. isMonospace = false;
  1791. break;
  1792. }
  1793. }
  1794. if (isMonospace) {
  1795. properties.flags |= _fonts.FontFlags.FixedPitch;
  1796. }
  1797. properties.defaultWidth = defaultWidth;
  1798. properties.widths = glyphsWidths;
  1799. properties.defaultVMetrics = defaultVMetrics;
  1800. properties.vmetrics = glyphsVMetrics;
  1801. },
  1802. isSerifFont: function PartialEvaluator_isSerifFont(baseFontName) {
  1803. var fontNameWoStyle = baseFontName.split('-')[0];
  1804. return fontNameWoStyle in (0, _standard_fonts.getSerifFonts)() || fontNameWoStyle.search(/serif/gi) !== -1;
  1805. },
  1806. getBaseFontMetrics: function PartialEvaluator_getBaseFontMetrics(name) {
  1807. var defaultWidth = 0;
  1808. var widths = [];
  1809. var monospace = false;
  1810. var stdFontMap = (0, _standard_fonts.getStdFontMap)();
  1811. var lookupName = stdFontMap[name] || name;
  1812. var Metrics = (0, _metrics.getMetrics)();
  1813. if (!(lookupName in Metrics)) {
  1814. if (this.isSerifFont(name)) {
  1815. lookupName = 'Times-Roman';
  1816. } else {
  1817. lookupName = 'Helvetica';
  1818. }
  1819. }
  1820. var glyphWidths = Metrics[lookupName];
  1821. if ((0, _util.isNum)(glyphWidths)) {
  1822. defaultWidth = glyphWidths;
  1823. monospace = true;
  1824. } else {
  1825. widths = glyphWidths();
  1826. }
  1827. return {
  1828. defaultWidth: defaultWidth,
  1829. monospace: monospace,
  1830. widths: widths
  1831. };
  1832. },
  1833. buildCharCodeToWidth: function PartialEvaluator_bulildCharCodeToWidth(widthsByGlyphName, properties) {
  1834. var widths = Object.create(null);
  1835. var differences = properties.differences;
  1836. var encoding = properties.defaultEncoding;
  1837. for (var charCode = 0; charCode < 256; charCode++) {
  1838. if (charCode in differences && widthsByGlyphName[differences[charCode]]) {
  1839. widths[charCode] = widthsByGlyphName[differences[charCode]];
  1840. continue;
  1841. }
  1842. if (charCode in encoding && widthsByGlyphName[encoding[charCode]]) {
  1843. widths[charCode] = widthsByGlyphName[encoding[charCode]];
  1844. continue;
  1845. }
  1846. }
  1847. return widths;
  1848. },
  1849. preEvaluateFont: function PartialEvaluator_preEvaluateFont(dict) {
  1850. var baseDict = dict;
  1851. var type = dict.get('Subtype');
  1852. if (!(0, _primitives.isName)(type)) {
  1853. throw new _util.FormatError('invalid font Subtype');
  1854. }
  1855. var composite = false;
  1856. var uint8array;
  1857. if (type.name === 'Type0') {
  1858. var df = dict.get('DescendantFonts');
  1859. if (!df) {
  1860. throw new _util.FormatError('Descendant fonts are not specified');
  1861. }
  1862. dict = Array.isArray(df) ? this.xref.fetchIfRef(df[0]) : df;
  1863. type = dict.get('Subtype');
  1864. if (!(0, _primitives.isName)(type)) {
  1865. throw new _util.FormatError('invalid font Subtype');
  1866. }
  1867. composite = true;
  1868. }
  1869. var descriptor = dict.get('FontDescriptor');
  1870. if (descriptor) {
  1871. var hash = new _murmurhash.MurmurHash3_64();
  1872. var encoding = baseDict.getRaw('Encoding');
  1873. if ((0, _primitives.isName)(encoding)) {
  1874. hash.update(encoding.name);
  1875. } else if ((0, _primitives.isRef)(encoding)) {
  1876. hash.update(encoding.toString());
  1877. } else if ((0, _primitives.isDict)(encoding)) {
  1878. var keys = encoding.getKeys();
  1879. for (var i = 0, ii = keys.length; i < ii; i++) {
  1880. var entry = encoding.getRaw(keys[i]);
  1881. if ((0, _primitives.isName)(entry)) {
  1882. hash.update(entry.name);
  1883. } else if ((0, _primitives.isRef)(entry)) {
  1884. hash.update(entry.toString());
  1885. } else if (Array.isArray(entry)) {
  1886. var diffLength = entry.length,
  1887. diffBuf = new Array(diffLength);
  1888. for (var j = 0; j < diffLength; j++) {
  1889. var diffEntry = entry[j];
  1890. if ((0, _primitives.isName)(diffEntry)) {
  1891. diffBuf[j] = diffEntry.name;
  1892. } else if ((0, _util.isNum)(diffEntry) || (0, _primitives.isRef)(diffEntry)) {
  1893. diffBuf[j] = diffEntry.toString();
  1894. }
  1895. }
  1896. hash.update(diffBuf.join());
  1897. }
  1898. }
  1899. }
  1900. var toUnicode = dict.get('ToUnicode') || baseDict.get('ToUnicode');
  1901. if ((0, _primitives.isStream)(toUnicode)) {
  1902. var stream = toUnicode.str || toUnicode;
  1903. uint8array = stream.buffer ? new Uint8Array(stream.buffer.buffer, 0, stream.bufferLength) : new Uint8Array(stream.bytes.buffer, stream.start, stream.end - stream.start);
  1904. hash.update(uint8array);
  1905. } else if ((0, _primitives.isName)(toUnicode)) {
  1906. hash.update(toUnicode.name);
  1907. }
  1908. var widths = dict.get('Widths') || baseDict.get('Widths');
  1909. if (widths) {
  1910. uint8array = new Uint8Array(new Uint32Array(widths).buffer);
  1911. hash.update(uint8array);
  1912. }
  1913. }
  1914. return {
  1915. descriptor: descriptor,
  1916. dict: dict,
  1917. baseDict: baseDict,
  1918. composite: composite,
  1919. type: type.name,
  1920. hash: hash ? hash.hexdigest() : ''
  1921. };
  1922. },
  1923. translateFont: function PartialEvaluator_translateFont(preEvaluatedFont) {
  1924. var _this11 = this;
  1925. var baseDict = preEvaluatedFont.baseDict;
  1926. var dict = preEvaluatedFont.dict;
  1927. var composite = preEvaluatedFont.composite;
  1928. var descriptor = preEvaluatedFont.descriptor;
  1929. var type = preEvaluatedFont.type;
  1930. var maxCharIndex = composite ? 0xFFFF : 0xFF;
  1931. var properties;
  1932. if (!descriptor) {
  1933. if (type === 'Type3') {
  1934. descriptor = new _primitives.Dict(null);
  1935. descriptor.set('FontName', _primitives.Name.get(type));
  1936. descriptor.set('FontBBox', dict.getArray('FontBBox'));
  1937. } else {
  1938. var baseFontName = dict.get('BaseFont');
  1939. if (!(0, _primitives.isName)(baseFontName)) {
  1940. throw new _util.FormatError('Base font is not specified');
  1941. }
  1942. baseFontName = baseFontName.name.replace(/[,_]/g, '-');
  1943. var metrics = this.getBaseFontMetrics(baseFontName);
  1944. var fontNameWoStyle = baseFontName.split('-')[0];
  1945. 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);
  1946. properties = {
  1947. type: type,
  1948. name: baseFontName,
  1949. widths: metrics.widths,
  1950. defaultWidth: metrics.defaultWidth,
  1951. flags: flags,
  1952. firstChar: 0,
  1953. lastChar: maxCharIndex
  1954. };
  1955. return this.extractDataStructures(dict, dict, properties).then(function (properties) {
  1956. properties.widths = _this11.buildCharCodeToWidth(metrics.widths, properties);
  1957. return new _fonts.Font(baseFontName, null, properties);
  1958. });
  1959. }
  1960. }
  1961. var firstChar = dict.get('FirstChar') || 0;
  1962. var lastChar = dict.get('LastChar') || maxCharIndex;
  1963. var fontName = descriptor.get('FontName');
  1964. var baseFont = dict.get('BaseFont');
  1965. if ((0, _util.isString)(fontName)) {
  1966. fontName = _primitives.Name.get(fontName);
  1967. }
  1968. if ((0, _util.isString)(baseFont)) {
  1969. baseFont = _primitives.Name.get(baseFont);
  1970. }
  1971. if (type !== 'Type3') {
  1972. var fontNameStr = fontName && fontName.name;
  1973. var baseFontStr = baseFont && baseFont.name;
  1974. if (fontNameStr !== baseFontStr) {
  1975. (0, _util.info)('The FontDescriptor\'s FontName is "' + fontNameStr + '" but should be the same as the Font\'s BaseFont "' + baseFontStr + '"');
  1976. if (fontNameStr && baseFontStr && baseFontStr.indexOf(fontNameStr) === 0) {
  1977. fontName = baseFont;
  1978. }
  1979. }
  1980. }
  1981. fontName = fontName || baseFont;
  1982. if (!(0, _primitives.isName)(fontName)) {
  1983. throw new _util.FormatError('invalid font name');
  1984. }
  1985. var fontFile = descriptor.get('FontFile', 'FontFile2', 'FontFile3');
  1986. if (fontFile) {
  1987. if (fontFile.dict) {
  1988. var subtype = fontFile.dict.get('Subtype');
  1989. if (subtype) {
  1990. subtype = subtype.name;
  1991. }
  1992. var length1 = fontFile.dict.get('Length1');
  1993. var length2 = fontFile.dict.get('Length2');
  1994. var length3 = fontFile.dict.get('Length3');
  1995. }
  1996. }
  1997. properties = {
  1998. type: type,
  1999. name: fontName.name,
  2000. subtype: subtype,
  2001. file: fontFile,
  2002. length1: length1,
  2003. length2: length2,
  2004. length3: length3,
  2005. loadedName: baseDict.loadedName,
  2006. composite: composite,
  2007. wideChars: composite,
  2008. fixedPitch: false,
  2009. fontMatrix: dict.getArray('FontMatrix') || _util.FONT_IDENTITY_MATRIX,
  2010. firstChar: firstChar || 0,
  2011. lastChar: lastChar || maxCharIndex,
  2012. bbox: descriptor.getArray('FontBBox'),
  2013. ascent: descriptor.get('Ascent'),
  2014. descent: descriptor.get('Descent'),
  2015. xHeight: descriptor.get('XHeight'),
  2016. capHeight: descriptor.get('CapHeight'),
  2017. flags: descriptor.get('Flags'),
  2018. italicAngle: descriptor.get('ItalicAngle'),
  2019. isType3Font: false
  2020. };
  2021. var cMapPromise;
  2022. if (composite) {
  2023. var cidEncoding = baseDict.get('Encoding');
  2024. if ((0, _primitives.isName)(cidEncoding)) {
  2025. properties.cidEncoding = cidEncoding.name;
  2026. }
  2027. cMapPromise = _cmap.CMapFactory.create({
  2028. encoding: cidEncoding,
  2029. fetchBuiltInCMap: this.fetchBuiltInCMap,
  2030. useCMap: null
  2031. }).then(function (cMap) {
  2032. properties.cMap = cMap;
  2033. properties.vertical = properties.cMap.vertical;
  2034. });
  2035. } else {
  2036. cMapPromise = Promise.resolve(undefined);
  2037. }
  2038. return cMapPromise.then(function () {
  2039. return _this11.extractDataStructures(dict, baseDict, properties);
  2040. }).then(function (properties) {
  2041. _this11.extractWidths(dict, descriptor, properties);
  2042. if (type === 'Type3') {
  2043. properties.isType3Font = true;
  2044. }
  2045. return new _fonts.Font(fontName.name, fontFile, properties);
  2046. });
  2047. }
  2048. };
  2049. return PartialEvaluator;
  2050. }();
  2051. var TranslatedFont = function TranslatedFontClosure() {
  2052. function TranslatedFont(loadedName, font, dict) {
  2053. this.loadedName = loadedName;
  2054. this.font = font;
  2055. this.dict = dict;
  2056. this.type3Loaded = null;
  2057. this.sent = false;
  2058. }
  2059. TranslatedFont.prototype = {
  2060. send: function send(handler) {
  2061. if (this.sent) {
  2062. return;
  2063. }
  2064. var fontData = this.font.exportData();
  2065. handler.send('commonobj', [this.loadedName, 'Font', fontData]);
  2066. this.sent = true;
  2067. },
  2068. loadType3Data: function loadType3Data(evaluator, resources, parentOperatorList, task) {
  2069. if (!this.font.isType3Font) {
  2070. throw new Error('Must be a Type3 font.');
  2071. }
  2072. if (this.type3Loaded) {
  2073. return this.type3Loaded;
  2074. }
  2075. var type3Options = Object.create(evaluator.options);
  2076. type3Options.ignoreErrors = false;
  2077. var type3Evaluator = evaluator.clone(type3Options);
  2078. var translatedFont = this.font;
  2079. var loadCharProcsPromise = Promise.resolve();
  2080. var charProcs = this.dict.get('CharProcs');
  2081. var fontResources = this.dict.get('Resources') || resources;
  2082. var charProcKeys = charProcs.getKeys();
  2083. var charProcOperatorList = Object.create(null);
  2084. var _loop2 = function _loop2() {
  2085. var key = charProcKeys[i];
  2086. loadCharProcsPromise = loadCharProcsPromise.then(function () {
  2087. var glyphStream = charProcs.get(key);
  2088. var operatorList = new _operator_list.OperatorList();
  2089. return type3Evaluator.getOperatorList({
  2090. stream: glyphStream,
  2091. task: task,
  2092. resources: fontResources,
  2093. operatorList: operatorList
  2094. }).then(function () {
  2095. charProcOperatorList[key] = operatorList.getIR();
  2096. parentOperatorList.addDependencies(operatorList.dependencies);
  2097. }).catch(function (reason) {
  2098. (0, _util.warn)('Type3 font resource "' + key + '" is not available.');
  2099. var operatorList = new _operator_list.OperatorList();
  2100. charProcOperatorList[key] = operatorList.getIR();
  2101. });
  2102. });
  2103. };
  2104. for (var i = 0, n = charProcKeys.length; i < n; ++i) {
  2105. _loop2();
  2106. }
  2107. this.type3Loaded = loadCharProcsPromise.then(function () {
  2108. translatedFont.charProcOperatorList = charProcOperatorList;
  2109. });
  2110. return this.type3Loaded;
  2111. }
  2112. };
  2113. return TranslatedFont;
  2114. }();
  2115. var StateManager = function StateManagerClosure() {
  2116. function StateManager(initialState) {
  2117. this.state = initialState;
  2118. this.stateStack = [];
  2119. }
  2120. StateManager.prototype = {
  2121. save: function save() {
  2122. var old = this.state;
  2123. this.stateStack.push(this.state);
  2124. this.state = old.clone();
  2125. },
  2126. restore: function restore() {
  2127. var prev = this.stateStack.pop();
  2128. if (prev) {
  2129. this.state = prev;
  2130. }
  2131. },
  2132. transform: function transform(args) {
  2133. this.state.ctm = _util.Util.transform(this.state.ctm, args);
  2134. }
  2135. };
  2136. return StateManager;
  2137. }();
  2138. var TextState = function TextStateClosure() {
  2139. function TextState() {
  2140. this.ctm = new Float32Array(_util.IDENTITY_MATRIX);
  2141. this.fontName = null;
  2142. this.fontSize = 0;
  2143. this.font = null;
  2144. this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
  2145. this.textMatrix = _util.IDENTITY_MATRIX.slice();
  2146. this.textLineMatrix = _util.IDENTITY_MATRIX.slice();
  2147. this.charSpacing = 0;
  2148. this.wordSpacing = 0;
  2149. this.leading = 0;
  2150. this.textHScale = 1;
  2151. this.textRise = 0;
  2152. }
  2153. TextState.prototype = {
  2154. setTextMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {
  2155. var m = this.textMatrix;
  2156. m[0] = a;
  2157. m[1] = b;
  2158. m[2] = c;
  2159. m[3] = d;
  2160. m[4] = e;
  2161. m[5] = f;
  2162. },
  2163. setTextLineMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {
  2164. var m = this.textLineMatrix;
  2165. m[0] = a;
  2166. m[1] = b;
  2167. m[2] = c;
  2168. m[3] = d;
  2169. m[4] = e;
  2170. m[5] = f;
  2171. },
  2172. translateTextMatrix: function TextState_translateTextMatrix(x, y) {
  2173. var m = this.textMatrix;
  2174. m[4] = m[0] * x + m[2] * y + m[4];
  2175. m[5] = m[1] * x + m[3] * y + m[5];
  2176. },
  2177. translateTextLineMatrix: function TextState_translateTextMatrix(x, y) {
  2178. var m = this.textLineMatrix;
  2179. m[4] = m[0] * x + m[2] * y + m[4];
  2180. m[5] = m[1] * x + m[3] * y + m[5];
  2181. },
  2182. calcTextLineMatrixAdvance: function TextState_calcTextLineMatrixAdvance(a, b, c, d, e, f) {
  2183. var font = this.font;
  2184. if (!font) {
  2185. return null;
  2186. }
  2187. var m = this.textLineMatrix;
  2188. if (!(a === m[0] && b === m[1] && c === m[2] && d === m[3])) {
  2189. return null;
  2190. }
  2191. var txDiff = e - m[4],
  2192. tyDiff = f - m[5];
  2193. if (font.vertical && txDiff !== 0 || !font.vertical && tyDiff !== 0) {
  2194. return null;
  2195. }
  2196. var tx,
  2197. ty,
  2198. denominator = a * d - b * c;
  2199. if (font.vertical) {
  2200. tx = -tyDiff * c / denominator;
  2201. ty = tyDiff * a / denominator;
  2202. } else {
  2203. tx = txDiff * d / denominator;
  2204. ty = -txDiff * b / denominator;
  2205. }
  2206. return {
  2207. width: tx,
  2208. height: ty,
  2209. value: font.vertical ? ty : tx
  2210. };
  2211. },
  2212. calcRenderMatrix: function TextState_calcRendeMatrix(ctm) {
  2213. var tsm = [this.fontSize * this.textHScale, 0, 0, this.fontSize, 0, this.textRise];
  2214. return _util.Util.transform(ctm, _util.Util.transform(this.textMatrix, tsm));
  2215. },
  2216. carriageReturn: function TextState_carriageReturn() {
  2217. this.translateTextLineMatrix(0, -this.leading);
  2218. this.textMatrix = this.textLineMatrix.slice();
  2219. },
  2220. clone: function TextState_clone() {
  2221. var clone = Object.create(this);
  2222. clone.textMatrix = this.textMatrix.slice();
  2223. clone.textLineMatrix = this.textLineMatrix.slice();
  2224. clone.fontMatrix = this.fontMatrix.slice();
  2225. return clone;
  2226. }
  2227. };
  2228. return TextState;
  2229. }();
  2230. var EvalState = function EvalStateClosure() {
  2231. function EvalState() {
  2232. this.ctm = new Float32Array(_util.IDENTITY_MATRIX);
  2233. this.font = null;
  2234. this.textRenderingMode = _util.TextRenderingMode.FILL;
  2235. this.fillColorSpace = _colorspace.ColorSpace.singletons.gray;
  2236. this.strokeColorSpace = _colorspace.ColorSpace.singletons.gray;
  2237. }
  2238. EvalState.prototype = {
  2239. clone: function CanvasExtraState_clone() {
  2240. return Object.create(this);
  2241. }
  2242. };
  2243. return EvalState;
  2244. }();
  2245. var EvaluatorPreprocessor = function EvaluatorPreprocessorClosure() {
  2246. var getOPMap = (0, _util.getLookupTableFactory)(function (t) {
  2247. t['w'] = {
  2248. id: _util.OPS.setLineWidth,
  2249. numArgs: 1,
  2250. variableArgs: false
  2251. };
  2252. t['J'] = {
  2253. id: _util.OPS.setLineCap,
  2254. numArgs: 1,
  2255. variableArgs: false
  2256. };
  2257. t['j'] = {
  2258. id: _util.OPS.setLineJoin,
  2259. numArgs: 1,
  2260. variableArgs: false
  2261. };
  2262. t['M'] = {
  2263. id: _util.OPS.setMiterLimit,
  2264. numArgs: 1,
  2265. variableArgs: false
  2266. };
  2267. t['d'] = {
  2268. id: _util.OPS.setDash,
  2269. numArgs: 2,
  2270. variableArgs: false
  2271. };
  2272. t['ri'] = {
  2273. id: _util.OPS.setRenderingIntent,
  2274. numArgs: 1,
  2275. variableArgs: false
  2276. };
  2277. t['i'] = {
  2278. id: _util.OPS.setFlatness,
  2279. numArgs: 1,
  2280. variableArgs: false
  2281. };
  2282. t['gs'] = {
  2283. id: _util.OPS.setGState,
  2284. numArgs: 1,
  2285. variableArgs: false
  2286. };
  2287. t['q'] = {
  2288. id: _util.OPS.save,
  2289. numArgs: 0,
  2290. variableArgs: false
  2291. };
  2292. t['Q'] = {
  2293. id: _util.OPS.restore,
  2294. numArgs: 0,
  2295. variableArgs: false
  2296. };
  2297. t['cm'] = {
  2298. id: _util.OPS.transform,
  2299. numArgs: 6,
  2300. variableArgs: false
  2301. };
  2302. t['m'] = {
  2303. id: _util.OPS.moveTo,
  2304. numArgs: 2,
  2305. variableArgs: false
  2306. };
  2307. t['l'] = {
  2308. id: _util.OPS.lineTo,
  2309. numArgs: 2,
  2310. variableArgs: false
  2311. };
  2312. t['c'] = {
  2313. id: _util.OPS.curveTo,
  2314. numArgs: 6,
  2315. variableArgs: false
  2316. };
  2317. t['v'] = {
  2318. id: _util.OPS.curveTo2,
  2319. numArgs: 4,
  2320. variableArgs: false
  2321. };
  2322. t['y'] = {
  2323. id: _util.OPS.curveTo3,
  2324. numArgs: 4,
  2325. variableArgs: false
  2326. };
  2327. t['h'] = {
  2328. id: _util.OPS.closePath,
  2329. numArgs: 0,
  2330. variableArgs: false
  2331. };
  2332. t['re'] = {
  2333. id: _util.OPS.rectangle,
  2334. numArgs: 4,
  2335. variableArgs: false
  2336. };
  2337. t['S'] = {
  2338. id: _util.OPS.stroke,
  2339. numArgs: 0,
  2340. variableArgs: false
  2341. };
  2342. t['s'] = {
  2343. id: _util.OPS.closeStroke,
  2344. numArgs: 0,
  2345. variableArgs: false
  2346. };
  2347. t['f'] = {
  2348. id: _util.OPS.fill,
  2349. numArgs: 0,
  2350. variableArgs: false
  2351. };
  2352. t['F'] = {
  2353. id: _util.OPS.fill,
  2354. numArgs: 0,
  2355. variableArgs: false
  2356. };
  2357. t['f*'] = {
  2358. id: _util.OPS.eoFill,
  2359. numArgs: 0,
  2360. variableArgs: false
  2361. };
  2362. t['B'] = {
  2363. id: _util.OPS.fillStroke,
  2364. numArgs: 0,
  2365. variableArgs: false
  2366. };
  2367. t['B*'] = {
  2368. id: _util.OPS.eoFillStroke,
  2369. numArgs: 0,
  2370. variableArgs: false
  2371. };
  2372. t['b'] = {
  2373. id: _util.OPS.closeFillStroke,
  2374. numArgs: 0,
  2375. variableArgs: false
  2376. };
  2377. t['b*'] = {
  2378. id: _util.OPS.closeEOFillStroke,
  2379. numArgs: 0,
  2380. variableArgs: false
  2381. };
  2382. t['n'] = {
  2383. id: _util.OPS.endPath,
  2384. numArgs: 0,
  2385. variableArgs: false
  2386. };
  2387. t['W'] = {
  2388. id: _util.OPS.clip,
  2389. numArgs: 0,
  2390. variableArgs: false
  2391. };
  2392. t['W*'] = {
  2393. id: _util.OPS.eoClip,
  2394. numArgs: 0,
  2395. variableArgs: false
  2396. };
  2397. t['BT'] = {
  2398. id: _util.OPS.beginText,
  2399. numArgs: 0,
  2400. variableArgs: false
  2401. };
  2402. t['ET'] = {
  2403. id: _util.OPS.endText,
  2404. numArgs: 0,
  2405. variableArgs: false
  2406. };
  2407. t['Tc'] = {
  2408. id: _util.OPS.setCharSpacing,
  2409. numArgs: 1,
  2410. variableArgs: false
  2411. };
  2412. t['Tw'] = {
  2413. id: _util.OPS.setWordSpacing,
  2414. numArgs: 1,
  2415. variableArgs: false
  2416. };
  2417. t['Tz'] = {
  2418. id: _util.OPS.setHScale,
  2419. numArgs: 1,
  2420. variableArgs: false
  2421. };
  2422. t['TL'] = {
  2423. id: _util.OPS.setLeading,
  2424. numArgs: 1,
  2425. variableArgs: false
  2426. };
  2427. t['Tf'] = {
  2428. id: _util.OPS.setFont,
  2429. numArgs: 2,
  2430. variableArgs: false
  2431. };
  2432. t['Tr'] = {
  2433. id: _util.OPS.setTextRenderingMode,
  2434. numArgs: 1,
  2435. variableArgs: false
  2436. };
  2437. t['Ts'] = {
  2438. id: _util.OPS.setTextRise,
  2439. numArgs: 1,
  2440. variableArgs: false
  2441. };
  2442. t['Td'] = {
  2443. id: _util.OPS.moveText,
  2444. numArgs: 2,
  2445. variableArgs: false
  2446. };
  2447. t['TD'] = {
  2448. id: _util.OPS.setLeadingMoveText,
  2449. numArgs: 2,
  2450. variableArgs: false
  2451. };
  2452. t['Tm'] = {
  2453. id: _util.OPS.setTextMatrix,
  2454. numArgs: 6,
  2455. variableArgs: false
  2456. };
  2457. t['T*'] = {
  2458. id: _util.OPS.nextLine,
  2459. numArgs: 0,
  2460. variableArgs: false
  2461. };
  2462. t['Tj'] = {
  2463. id: _util.OPS.showText,
  2464. numArgs: 1,
  2465. variableArgs: false
  2466. };
  2467. t['TJ'] = {
  2468. id: _util.OPS.showSpacedText,
  2469. numArgs: 1,
  2470. variableArgs: false
  2471. };
  2472. t['\''] = {
  2473. id: _util.OPS.nextLineShowText,
  2474. numArgs: 1,
  2475. variableArgs: false
  2476. };
  2477. t['"'] = {
  2478. id: _util.OPS.nextLineSetSpacingShowText,
  2479. numArgs: 3,
  2480. variableArgs: false
  2481. };
  2482. t['d0'] = {
  2483. id: _util.OPS.setCharWidth,
  2484. numArgs: 2,
  2485. variableArgs: false
  2486. };
  2487. t['d1'] = {
  2488. id: _util.OPS.setCharWidthAndBounds,
  2489. numArgs: 6,
  2490. variableArgs: false
  2491. };
  2492. t['CS'] = {
  2493. id: _util.OPS.setStrokeColorSpace,
  2494. numArgs: 1,
  2495. variableArgs: false
  2496. };
  2497. t['cs'] = {
  2498. id: _util.OPS.setFillColorSpace,
  2499. numArgs: 1,
  2500. variableArgs: false
  2501. };
  2502. t['SC'] = {
  2503. id: _util.OPS.setStrokeColor,
  2504. numArgs: 4,
  2505. variableArgs: true
  2506. };
  2507. t['SCN'] = {
  2508. id: _util.OPS.setStrokeColorN,
  2509. numArgs: 33,
  2510. variableArgs: true
  2511. };
  2512. t['sc'] = {
  2513. id: _util.OPS.setFillColor,
  2514. numArgs: 4,
  2515. variableArgs: true
  2516. };
  2517. t['scn'] = {
  2518. id: _util.OPS.setFillColorN,
  2519. numArgs: 33,
  2520. variableArgs: true
  2521. };
  2522. t['G'] = {
  2523. id: _util.OPS.setStrokeGray,
  2524. numArgs: 1,
  2525. variableArgs: false
  2526. };
  2527. t['g'] = {
  2528. id: _util.OPS.setFillGray,
  2529. numArgs: 1,
  2530. variableArgs: false
  2531. };
  2532. t['RG'] = {
  2533. id: _util.OPS.setStrokeRGBColor,
  2534. numArgs: 3,
  2535. variableArgs: false
  2536. };
  2537. t['rg'] = {
  2538. id: _util.OPS.setFillRGBColor,
  2539. numArgs: 3,
  2540. variableArgs: false
  2541. };
  2542. t['K'] = {
  2543. id: _util.OPS.setStrokeCMYKColor,
  2544. numArgs: 4,
  2545. variableArgs: false
  2546. };
  2547. t['k'] = {
  2548. id: _util.OPS.setFillCMYKColor,
  2549. numArgs: 4,
  2550. variableArgs: false
  2551. };
  2552. t['sh'] = {
  2553. id: _util.OPS.shadingFill,
  2554. numArgs: 1,
  2555. variableArgs: false
  2556. };
  2557. t['BI'] = {
  2558. id: _util.OPS.beginInlineImage,
  2559. numArgs: 0,
  2560. variableArgs: false
  2561. };
  2562. t['ID'] = {
  2563. id: _util.OPS.beginImageData,
  2564. numArgs: 0,
  2565. variableArgs: false
  2566. };
  2567. t['EI'] = {
  2568. id: _util.OPS.endInlineImage,
  2569. numArgs: 1,
  2570. variableArgs: false
  2571. };
  2572. t['Do'] = {
  2573. id: _util.OPS.paintXObject,
  2574. numArgs: 1,
  2575. variableArgs: false
  2576. };
  2577. t['MP'] = {
  2578. id: _util.OPS.markPoint,
  2579. numArgs: 1,
  2580. variableArgs: false
  2581. };
  2582. t['DP'] = {
  2583. id: _util.OPS.markPointProps,
  2584. numArgs: 2,
  2585. variableArgs: false
  2586. };
  2587. t['BMC'] = {
  2588. id: _util.OPS.beginMarkedContent,
  2589. numArgs: 1,
  2590. variableArgs: false
  2591. };
  2592. t['BDC'] = {
  2593. id: _util.OPS.beginMarkedContentProps,
  2594. numArgs: 2,
  2595. variableArgs: false
  2596. };
  2597. t['EMC'] = {
  2598. id: _util.OPS.endMarkedContent,
  2599. numArgs: 0,
  2600. variableArgs: false
  2601. };
  2602. t['BX'] = {
  2603. id: _util.OPS.beginCompat,
  2604. numArgs: 0,
  2605. variableArgs: false
  2606. };
  2607. t['EX'] = {
  2608. id: _util.OPS.endCompat,
  2609. numArgs: 0,
  2610. variableArgs: false
  2611. };
  2612. t['BM'] = null;
  2613. t['BD'] = null;
  2614. t['true'] = null;
  2615. t['fa'] = null;
  2616. t['fal'] = null;
  2617. t['fals'] = null;
  2618. t['false'] = null;
  2619. t['nu'] = null;
  2620. t['nul'] = null;
  2621. t['null'] = null;
  2622. });
  2623. function EvaluatorPreprocessor(stream, xref, stateManager) {
  2624. this.opMap = getOPMap();
  2625. this.parser = new _parser.Parser(new _parser.Lexer(stream, this.opMap), false, xref);
  2626. this.stateManager = stateManager;
  2627. this.nonProcessedArgs = [];
  2628. }
  2629. EvaluatorPreprocessor.prototype = {
  2630. get savedStatesDepth() {
  2631. return this.stateManager.stateStack.length;
  2632. },
  2633. read: function EvaluatorPreprocessor_read(operation) {
  2634. var args = operation.args;
  2635. while (true) {
  2636. var obj = this.parser.getObj();
  2637. if ((0, _primitives.isCmd)(obj)) {
  2638. var cmd = obj.cmd;
  2639. var opSpec = this.opMap[cmd];
  2640. if (!opSpec) {
  2641. (0, _util.warn)('Unknown command "' + cmd + '"');
  2642. continue;
  2643. }
  2644. var fn = opSpec.id;
  2645. var numArgs = opSpec.numArgs;
  2646. var argsLength = args !== null ? args.length : 0;
  2647. if (!opSpec.variableArgs) {
  2648. if (argsLength !== numArgs) {
  2649. var nonProcessedArgs = this.nonProcessedArgs;
  2650. while (argsLength > numArgs) {
  2651. nonProcessedArgs.push(args.shift());
  2652. argsLength--;
  2653. }
  2654. while (argsLength < numArgs && nonProcessedArgs.length !== 0) {
  2655. if (args === null) {
  2656. args = [];
  2657. }
  2658. args.unshift(nonProcessedArgs.pop());
  2659. argsLength++;
  2660. }
  2661. }
  2662. if (argsLength < numArgs) {
  2663. (0, _util.warn)('Skipping command ' + fn + ': expected ' + numArgs + ' args, but received ' + argsLength + ' args.');
  2664. if (args !== null) {
  2665. args.length = 0;
  2666. }
  2667. continue;
  2668. }
  2669. } else if (argsLength > numArgs) {
  2670. (0, _util.info)('Command ' + fn + ': expected [0,' + numArgs + '] args, but received ' + argsLength + ' args.');
  2671. }
  2672. this.preprocessCommand(fn, args);
  2673. operation.fn = fn;
  2674. operation.args = args;
  2675. return true;
  2676. }
  2677. if ((0, _primitives.isEOF)(obj)) {
  2678. return false;
  2679. }
  2680. if (obj !== null) {
  2681. if (args === null) {
  2682. args = [];
  2683. }
  2684. args.push(obj);
  2685. if (args.length > 33) {
  2686. throw new _util.FormatError('Too many arguments');
  2687. }
  2688. }
  2689. }
  2690. },
  2691. preprocessCommand: function EvaluatorPreprocessor_preprocessCommand(fn, args) {
  2692. switch (fn | 0) {
  2693. case _util.OPS.save:
  2694. this.stateManager.save();
  2695. break;
  2696. case _util.OPS.restore:
  2697. this.stateManager.restore();
  2698. break;
  2699. case _util.OPS.transform:
  2700. this.stateManager.transform(args);
  2701. break;
  2702. }
  2703. }
  2704. };
  2705. return EvaluatorPreprocessor;
  2706. }();
  2707. exports.PartialEvaluator = PartialEvaluator;