evaluator.js 106 KB

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