2
0

evaluator.js 107 KB

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