evaluator.js 119 KB

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