2
0

evaluator.js 124 KB

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