pdf.js 421 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568
  1. /* Copyright 2012 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. (function (root, factory) {
  16. 'use strict';
  17. if (typeof define === 'function' && define.amd) {
  18. define('pdfjs-dist/build/pdf', ['exports'], factory);
  19. } else if (typeof exports !== 'undefined') {
  20. factory(exports);
  21. } else {
  22. factory(root['pdfjsDistBuildPdf'] = {});
  23. }
  24. }(this, function (exports) {
  25. // Use strict in our context only - users might not want it
  26. 'use strict';
  27. var pdfjsVersion = '1.6.250';
  28. var pdfjsBuild = '960e344';
  29. var pdfjsFilePath = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : null;
  30. var pdfjsLibs = {};
  31. (function pdfjsWrapper() {
  32. (function (root, factory) {
  33. factory(root.pdfjsSharedUtil = {});
  34. }(this, function (exports) {
  35. var globalScope = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : this;
  36. var FONT_IDENTITY_MATRIX = [
  37. 0.001,
  38. 0,
  39. 0,
  40. 0.001,
  41. 0,
  42. 0
  43. ];
  44. var TextRenderingMode = {
  45. FILL: 0,
  46. STROKE: 1,
  47. FILL_STROKE: 2,
  48. INVISIBLE: 3,
  49. FILL_ADD_TO_PATH: 4,
  50. STROKE_ADD_TO_PATH: 5,
  51. FILL_STROKE_ADD_TO_PATH: 6,
  52. ADD_TO_PATH: 7,
  53. FILL_STROKE_MASK: 3,
  54. ADD_TO_PATH_FLAG: 4
  55. };
  56. var ImageKind = {
  57. GRAYSCALE_1BPP: 1,
  58. RGB_24BPP: 2,
  59. RGBA_32BPP: 3
  60. };
  61. var AnnotationType = {
  62. TEXT: 1,
  63. LINK: 2,
  64. FREETEXT: 3,
  65. LINE: 4,
  66. SQUARE: 5,
  67. CIRCLE: 6,
  68. POLYGON: 7,
  69. POLYLINE: 8,
  70. HIGHLIGHT: 9,
  71. UNDERLINE: 10,
  72. SQUIGGLY: 11,
  73. STRIKEOUT: 12,
  74. STAMP: 13,
  75. CARET: 14,
  76. INK: 15,
  77. POPUP: 16,
  78. FILEATTACHMENT: 17,
  79. SOUND: 18,
  80. MOVIE: 19,
  81. WIDGET: 20,
  82. SCREEN: 21,
  83. PRINTERMARK: 22,
  84. TRAPNET: 23,
  85. WATERMARK: 24,
  86. THREED: 25,
  87. REDACT: 26
  88. };
  89. var AnnotationFlag = {
  90. INVISIBLE: 0x01,
  91. HIDDEN: 0x02,
  92. PRINT: 0x04,
  93. NOZOOM: 0x08,
  94. NOROTATE: 0x10,
  95. NOVIEW: 0x20,
  96. READONLY: 0x40,
  97. LOCKED: 0x80,
  98. TOGGLENOVIEW: 0x100,
  99. LOCKEDCONTENTS: 0x200
  100. };
  101. var AnnotationFieldFlag = {
  102. READONLY: 0x0000001,
  103. REQUIRED: 0x0000002,
  104. NOEXPORT: 0x0000004,
  105. MULTILINE: 0x0001000,
  106. PASSWORD: 0x0002000,
  107. NOTOGGLETOOFF: 0x0004000,
  108. RADIO: 0x0008000,
  109. PUSHBUTTON: 0x0010000,
  110. COMBO: 0x0020000,
  111. EDIT: 0x0040000,
  112. SORT: 0x0080000,
  113. FILESELECT: 0x0100000,
  114. MULTISELECT: 0x0200000,
  115. DONOTSPELLCHECK: 0x0400000,
  116. DONOTSCROLL: 0x0800000,
  117. COMB: 0x1000000,
  118. RICHTEXT: 0x2000000,
  119. RADIOSINUNISON: 0x2000000,
  120. COMMITONSELCHANGE: 0x4000000
  121. };
  122. var AnnotationBorderStyleType = {
  123. SOLID: 1,
  124. DASHED: 2,
  125. BEVELED: 3,
  126. INSET: 4,
  127. UNDERLINE: 5
  128. };
  129. var StreamType = {
  130. UNKNOWN: 0,
  131. FLATE: 1,
  132. LZW: 2,
  133. DCT: 3,
  134. JPX: 4,
  135. JBIG: 5,
  136. A85: 6,
  137. AHX: 7,
  138. CCF: 8,
  139. RL: 9
  140. };
  141. var FontType = {
  142. UNKNOWN: 0,
  143. TYPE1: 1,
  144. TYPE1C: 2,
  145. CIDFONTTYPE0: 3,
  146. CIDFONTTYPE0C: 4,
  147. TRUETYPE: 5,
  148. CIDFONTTYPE2: 6,
  149. TYPE3: 7,
  150. OPENTYPE: 8,
  151. TYPE0: 9,
  152. MMTYPE1: 10
  153. };
  154. var VERBOSITY_LEVELS = {
  155. errors: 0,
  156. warnings: 1,
  157. infos: 5
  158. };
  159. // All the possible operations for an operator list.
  160. var OPS = {
  161. // Intentionally start from 1 so it is easy to spot bad operators that will be
  162. // 0's.
  163. dependency: 1,
  164. setLineWidth: 2,
  165. setLineCap: 3,
  166. setLineJoin: 4,
  167. setMiterLimit: 5,
  168. setDash: 6,
  169. setRenderingIntent: 7,
  170. setFlatness: 8,
  171. setGState: 9,
  172. save: 10,
  173. restore: 11,
  174. transform: 12,
  175. moveTo: 13,
  176. lineTo: 14,
  177. curveTo: 15,
  178. curveTo2: 16,
  179. curveTo3: 17,
  180. closePath: 18,
  181. rectangle: 19,
  182. stroke: 20,
  183. closeStroke: 21,
  184. fill: 22,
  185. eoFill: 23,
  186. fillStroke: 24,
  187. eoFillStroke: 25,
  188. closeFillStroke: 26,
  189. closeEOFillStroke: 27,
  190. endPath: 28,
  191. clip: 29,
  192. eoClip: 30,
  193. beginText: 31,
  194. endText: 32,
  195. setCharSpacing: 33,
  196. setWordSpacing: 34,
  197. setHScale: 35,
  198. setLeading: 36,
  199. setFont: 37,
  200. setTextRenderingMode: 38,
  201. setTextRise: 39,
  202. moveText: 40,
  203. setLeadingMoveText: 41,
  204. setTextMatrix: 42,
  205. nextLine: 43,
  206. showText: 44,
  207. showSpacedText: 45,
  208. nextLineShowText: 46,
  209. nextLineSetSpacingShowText: 47,
  210. setCharWidth: 48,
  211. setCharWidthAndBounds: 49,
  212. setStrokeColorSpace: 50,
  213. setFillColorSpace: 51,
  214. setStrokeColor: 52,
  215. setStrokeColorN: 53,
  216. setFillColor: 54,
  217. setFillColorN: 55,
  218. setStrokeGray: 56,
  219. setFillGray: 57,
  220. setStrokeRGBColor: 58,
  221. setFillRGBColor: 59,
  222. setStrokeCMYKColor: 60,
  223. setFillCMYKColor: 61,
  224. shadingFill: 62,
  225. beginInlineImage: 63,
  226. beginImageData: 64,
  227. endInlineImage: 65,
  228. paintXObject: 66,
  229. markPoint: 67,
  230. markPointProps: 68,
  231. beginMarkedContent: 69,
  232. beginMarkedContentProps: 70,
  233. endMarkedContent: 71,
  234. beginCompat: 72,
  235. endCompat: 73,
  236. paintFormXObjectBegin: 74,
  237. paintFormXObjectEnd: 75,
  238. beginGroup: 76,
  239. endGroup: 77,
  240. beginAnnotations: 78,
  241. endAnnotations: 79,
  242. beginAnnotation: 80,
  243. endAnnotation: 81,
  244. paintJpegXObject: 82,
  245. paintImageMaskXObject: 83,
  246. paintImageMaskXObjectGroup: 84,
  247. paintImageXObject: 85,
  248. paintInlineImageXObject: 86,
  249. paintInlineImageXObjectGroup: 87,
  250. paintImageXObjectRepeat: 88,
  251. paintImageMaskXObjectRepeat: 89,
  252. paintSolidColorImageMask: 90,
  253. constructPath: 91
  254. };
  255. var verbosity = VERBOSITY_LEVELS.warnings;
  256. function setVerbosityLevel(level) {
  257. verbosity = level;
  258. }
  259. function getVerbosityLevel() {
  260. return verbosity;
  261. }
  262. // A notice for devs. These are good for things that are helpful to devs, such
  263. // as warning that Workers were disabled, which is important to devs but not
  264. // end users.
  265. function info(msg) {
  266. if (verbosity >= VERBOSITY_LEVELS.infos) {
  267. console.log('Info: ' + msg);
  268. }
  269. }
  270. // Non-fatal warnings.
  271. function warn(msg) {
  272. if (verbosity >= VERBOSITY_LEVELS.warnings) {
  273. console.log('Warning: ' + msg);
  274. }
  275. }
  276. // Deprecated API function -- display regardless of the PDFJS.verbosity setting.
  277. function deprecated(details) {
  278. console.log('Deprecated API usage: ' + details);
  279. }
  280. // Fatal errors that should trigger the fallback UI and halt execution by
  281. // throwing an exception.
  282. function error(msg) {
  283. if (verbosity >= VERBOSITY_LEVELS.errors) {
  284. console.log('Error: ' + msg);
  285. console.log(backtrace());
  286. }
  287. throw new Error(msg);
  288. }
  289. function backtrace() {
  290. try {
  291. throw new Error();
  292. } catch (e) {
  293. return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
  294. }
  295. }
  296. function assert(cond, msg) {
  297. if (!cond) {
  298. error(msg);
  299. }
  300. }
  301. var UNSUPPORTED_FEATURES = {
  302. unknown: 'unknown',
  303. forms: 'forms',
  304. javaScript: 'javaScript',
  305. smask: 'smask',
  306. shadingPattern: 'shadingPattern',
  307. font: 'font'
  308. };
  309. // Checks if URLs have the same origin. For non-HTTP based URLs, returns false.
  310. function isSameOrigin(baseUrl, otherUrl) {
  311. try {
  312. var base = new URL(baseUrl);
  313. if (!base.origin || base.origin === 'null') {
  314. return false;
  315. }
  316. } // non-HTTP url
  317. catch (e) {
  318. return false;
  319. }
  320. var other = new URL(otherUrl, base);
  321. return base.origin === other.origin;
  322. }
  323. // Validates if URL is safe and allowed, e.g. to avoid XSS.
  324. function isValidUrl(url, allowRelative) {
  325. if (!url || typeof url !== 'string') {
  326. return false;
  327. }
  328. // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
  329. // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  330. var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
  331. if (!protocol) {
  332. return allowRelative;
  333. }
  334. protocol = protocol[0].toLowerCase();
  335. switch (protocol) {
  336. case 'http':
  337. case 'https':
  338. case 'ftp':
  339. case 'mailto':
  340. case 'tel':
  341. return true;
  342. default:
  343. return false;
  344. }
  345. }
  346. function shadow(obj, prop, value) {
  347. Object.defineProperty(obj, prop, {
  348. value: value,
  349. enumerable: true,
  350. configurable: true,
  351. writable: false
  352. });
  353. return value;
  354. }
  355. function getLookupTableFactory(initializer) {
  356. var lookup;
  357. return function () {
  358. if (initializer) {
  359. lookup = Object.create(null);
  360. initializer(lookup);
  361. initializer = null;
  362. }
  363. return lookup;
  364. };
  365. }
  366. var PasswordResponses = {
  367. NEED_PASSWORD: 1,
  368. INCORRECT_PASSWORD: 2
  369. };
  370. var PasswordException = function PasswordExceptionClosure() {
  371. function PasswordException(msg, code) {
  372. this.name = 'PasswordException';
  373. this.message = msg;
  374. this.code = code;
  375. }
  376. PasswordException.prototype = new Error();
  377. PasswordException.constructor = PasswordException;
  378. return PasswordException;
  379. }();
  380. var UnknownErrorException = function UnknownErrorExceptionClosure() {
  381. function UnknownErrorException(msg, details) {
  382. this.name = 'UnknownErrorException';
  383. this.message = msg;
  384. this.details = details;
  385. }
  386. UnknownErrorException.prototype = new Error();
  387. UnknownErrorException.constructor = UnknownErrorException;
  388. return UnknownErrorException;
  389. }();
  390. var InvalidPDFException = function InvalidPDFExceptionClosure() {
  391. function InvalidPDFException(msg) {
  392. this.name = 'InvalidPDFException';
  393. this.message = msg;
  394. }
  395. InvalidPDFException.prototype = new Error();
  396. InvalidPDFException.constructor = InvalidPDFException;
  397. return InvalidPDFException;
  398. }();
  399. var MissingPDFException = function MissingPDFExceptionClosure() {
  400. function MissingPDFException(msg) {
  401. this.name = 'MissingPDFException';
  402. this.message = msg;
  403. }
  404. MissingPDFException.prototype = new Error();
  405. MissingPDFException.constructor = MissingPDFException;
  406. return MissingPDFException;
  407. }();
  408. var UnexpectedResponseException = function UnexpectedResponseExceptionClosure() {
  409. function UnexpectedResponseException(msg, status) {
  410. this.name = 'UnexpectedResponseException';
  411. this.message = msg;
  412. this.status = status;
  413. }
  414. UnexpectedResponseException.prototype = new Error();
  415. UnexpectedResponseException.constructor = UnexpectedResponseException;
  416. return UnexpectedResponseException;
  417. }();
  418. var NotImplementedException = function NotImplementedExceptionClosure() {
  419. function NotImplementedException(msg) {
  420. this.message = msg;
  421. }
  422. NotImplementedException.prototype = new Error();
  423. NotImplementedException.prototype.name = 'NotImplementedException';
  424. NotImplementedException.constructor = NotImplementedException;
  425. return NotImplementedException;
  426. }();
  427. var MissingDataException = function MissingDataExceptionClosure() {
  428. function MissingDataException(begin, end) {
  429. this.begin = begin;
  430. this.end = end;
  431. this.message = 'Missing data [' + begin + ', ' + end + ')';
  432. }
  433. MissingDataException.prototype = new Error();
  434. MissingDataException.prototype.name = 'MissingDataException';
  435. MissingDataException.constructor = MissingDataException;
  436. return MissingDataException;
  437. }();
  438. var XRefParseException = function XRefParseExceptionClosure() {
  439. function XRefParseException(msg) {
  440. this.message = msg;
  441. }
  442. XRefParseException.prototype = new Error();
  443. XRefParseException.prototype.name = 'XRefParseException';
  444. XRefParseException.constructor = XRefParseException;
  445. return XRefParseException;
  446. }();
  447. var NullCharactersRegExp = /\x00/g;
  448. function removeNullCharacters(str) {
  449. if (typeof str !== 'string') {
  450. warn('The argument for removeNullCharacters must be a string.');
  451. return str;
  452. }
  453. return str.replace(NullCharactersRegExp, '');
  454. }
  455. function bytesToString(bytes) {
  456. assert(bytes !== null && typeof bytes === 'object' && bytes.length !== undefined, 'Invalid argument for bytesToString');
  457. var length = bytes.length;
  458. var MAX_ARGUMENT_COUNT = 8192;
  459. if (length < MAX_ARGUMENT_COUNT) {
  460. return String.fromCharCode.apply(null, bytes);
  461. }
  462. var strBuf = [];
  463. for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
  464. var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
  465. var chunk = bytes.subarray(i, chunkEnd);
  466. strBuf.push(String.fromCharCode.apply(null, chunk));
  467. }
  468. return strBuf.join('');
  469. }
  470. function stringToBytes(str) {
  471. assert(typeof str === 'string', 'Invalid argument for stringToBytes');
  472. var length = str.length;
  473. var bytes = new Uint8Array(length);
  474. for (var i = 0; i < length; ++i) {
  475. bytes[i] = str.charCodeAt(i) & 0xFF;
  476. }
  477. return bytes;
  478. }
  479. /**
  480. * Gets length of the array (Array, Uint8Array, or string) in bytes.
  481. * @param {Array|Uint8Array|string} arr
  482. * @returns {number}
  483. */
  484. function arrayByteLength(arr) {
  485. if (arr.length !== undefined) {
  486. return arr.length;
  487. }
  488. assert(arr.byteLength !== undefined);
  489. return arr.byteLength;
  490. }
  491. /**
  492. * Combines array items (arrays) into single Uint8Array object.
  493. * @param {Array} arr - the array of the arrays (Array, Uint8Array, or string).
  494. * @returns {Uint8Array}
  495. */
  496. function arraysToBytes(arr) {
  497. // Shortcut: if first and only item is Uint8Array, return it.
  498. if (arr.length === 1 && arr[0] instanceof Uint8Array) {
  499. return arr[0];
  500. }
  501. var resultLength = 0;
  502. var i, ii = arr.length;
  503. var item, itemLength;
  504. for (i = 0; i < ii; i++) {
  505. item = arr[i];
  506. itemLength = arrayByteLength(item);
  507. resultLength += itemLength;
  508. }
  509. var pos = 0;
  510. var data = new Uint8Array(resultLength);
  511. for (i = 0; i < ii; i++) {
  512. item = arr[i];
  513. if (!(item instanceof Uint8Array)) {
  514. if (typeof item === 'string') {
  515. item = stringToBytes(item);
  516. } else {
  517. item = new Uint8Array(item);
  518. }
  519. }
  520. itemLength = item.byteLength;
  521. data.set(item, pos);
  522. pos += itemLength;
  523. }
  524. return data;
  525. }
  526. function string32(value) {
  527. return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
  528. }
  529. function log2(x) {
  530. var n = 1, i = 0;
  531. while (x > n) {
  532. n <<= 1;
  533. i++;
  534. }
  535. return i;
  536. }
  537. function readInt8(data, start) {
  538. return data[start] << 24 >> 24;
  539. }
  540. function readUint16(data, offset) {
  541. return data[offset] << 8 | data[offset + 1];
  542. }
  543. function readUint32(data, offset) {
  544. return (data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]) >>> 0;
  545. }
  546. // Lazy test the endianness of the platform
  547. // NOTE: This will be 'true' for simulated TypedArrays
  548. function isLittleEndian() {
  549. var buffer8 = new Uint8Array(2);
  550. buffer8[0] = 1;
  551. var buffer16 = new Uint16Array(buffer8.buffer);
  552. return buffer16[0] === 1;
  553. }
  554. // Checks if it's possible to eval JS expressions.
  555. function isEvalSupported() {
  556. try {
  557. new Function('');
  558. return true;
  559. } catch (e) {
  560. return false;
  561. }
  562. }
  563. var Uint32ArrayView = function Uint32ArrayViewClosure() {
  564. function Uint32ArrayView(buffer, length) {
  565. this.buffer = buffer;
  566. this.byteLength = buffer.length;
  567. this.length = length === undefined ? this.byteLength >> 2 : length;
  568. ensureUint32ArrayViewProps(this.length);
  569. }
  570. Uint32ArrayView.prototype = Object.create(null);
  571. var uint32ArrayViewSetters = 0;
  572. function createUint32ArrayProp(index) {
  573. return {
  574. get: function () {
  575. var buffer = this.buffer, offset = index << 2;
  576. return (buffer[offset] | buffer[offset + 1] << 8 | buffer[offset + 2] << 16 | buffer[offset + 3] << 24) >>> 0;
  577. },
  578. set: function (value) {
  579. var buffer = this.buffer, offset = index << 2;
  580. buffer[offset] = value & 255;
  581. buffer[offset + 1] = value >> 8 & 255;
  582. buffer[offset + 2] = value >> 16 & 255;
  583. buffer[offset + 3] = value >>> 24 & 255;
  584. }
  585. };
  586. }
  587. function ensureUint32ArrayViewProps(length) {
  588. while (uint32ArrayViewSetters < length) {
  589. Object.defineProperty(Uint32ArrayView.prototype, uint32ArrayViewSetters, createUint32ArrayProp(uint32ArrayViewSetters));
  590. uint32ArrayViewSetters++;
  591. }
  592. }
  593. return Uint32ArrayView;
  594. }();
  595. exports.Uint32ArrayView = Uint32ArrayView;
  596. var IDENTITY_MATRIX = [
  597. 1,
  598. 0,
  599. 0,
  600. 1,
  601. 0,
  602. 0
  603. ];
  604. var Util = function UtilClosure() {
  605. function Util() {
  606. }
  607. var rgbBuf = [
  608. 'rgb(',
  609. 0,
  610. ',',
  611. 0,
  612. ',',
  613. 0,
  614. ')'
  615. ];
  616. // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
  617. // creating many intermediate strings.
  618. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
  619. rgbBuf[1] = r;
  620. rgbBuf[3] = g;
  621. rgbBuf[5] = b;
  622. return rgbBuf.join('');
  623. };
  624. // Concatenates two transformation matrices together and returns the result.
  625. Util.transform = function Util_transform(m1, m2) {
  626. return [
  627. m1[0] * m2[0] + m1[2] * m2[1],
  628. m1[1] * m2[0] + m1[3] * m2[1],
  629. m1[0] * m2[2] + m1[2] * m2[3],
  630. m1[1] * m2[2] + m1[3] * m2[3],
  631. m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
  632. m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
  633. ];
  634. };
  635. // For 2d affine transforms
  636. Util.applyTransform = function Util_applyTransform(p, m) {
  637. var xt = p[0] * m[0] + p[1] * m[2] + m[4];
  638. var yt = p[0] * m[1] + p[1] * m[3] + m[5];
  639. return [
  640. xt,
  641. yt
  642. ];
  643. };
  644. Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
  645. var d = m[0] * m[3] - m[1] * m[2];
  646. var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
  647. var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
  648. return [
  649. xt,
  650. yt
  651. ];
  652. };
  653. // Applies the transform to the rectangle and finds the minimum axially
  654. // aligned bounding box.
  655. Util.getAxialAlignedBoundingBox = function Util_getAxialAlignedBoundingBox(r, m) {
  656. var p1 = Util.applyTransform(r, m);
  657. var p2 = Util.applyTransform(r.slice(2, 4), m);
  658. var p3 = Util.applyTransform([
  659. r[0],
  660. r[3]
  661. ], m);
  662. var p4 = Util.applyTransform([
  663. r[2],
  664. r[1]
  665. ], m);
  666. return [
  667. Math.min(p1[0], p2[0], p3[0], p4[0]),
  668. Math.min(p1[1], p2[1], p3[1], p4[1]),
  669. Math.max(p1[0], p2[0], p3[0], p4[0]),
  670. Math.max(p1[1], p2[1], p3[1], p4[1])
  671. ];
  672. };
  673. Util.inverseTransform = function Util_inverseTransform(m) {
  674. var d = m[0] * m[3] - m[1] * m[2];
  675. return [
  676. m[3] / d,
  677. -m[1] / d,
  678. -m[2] / d,
  679. m[0] / d,
  680. (m[2] * m[5] - m[4] * m[3]) / d,
  681. (m[4] * m[1] - m[5] * m[0]) / d
  682. ];
  683. };
  684. // Apply a generic 3d matrix M on a 3-vector v:
  685. // | a b c | | X |
  686. // | d e f | x | Y |
  687. // | g h i | | Z |
  688. // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
  689. // with v as [X,Y,Z]
  690. Util.apply3dTransform = function Util_apply3dTransform(m, v) {
  691. return [
  692. m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
  693. m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
  694. m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
  695. ];
  696. };
  697. // This calculation uses Singular Value Decomposition.
  698. // The SVD can be represented with formula A = USV. We are interested in the
  699. // matrix S here because it represents the scale values.
  700. Util.singularValueDecompose2dScale = function Util_singularValueDecompose2dScale(m) {
  701. var transpose = [
  702. m[0],
  703. m[2],
  704. m[1],
  705. m[3]
  706. ];
  707. // Multiply matrix m with its transpose.
  708. var a = m[0] * transpose[0] + m[1] * transpose[2];
  709. var b = m[0] * transpose[1] + m[1] * transpose[3];
  710. var c = m[2] * transpose[0] + m[3] * transpose[2];
  711. var d = m[2] * transpose[1] + m[3] * transpose[3];
  712. // Solve the second degree polynomial to get roots.
  713. var first = (a + d) / 2;
  714. var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
  715. var sx = first + second || 1;
  716. var sy = first - second || 1;
  717. // Scale values are the square roots of the eigenvalues.
  718. return [
  719. Math.sqrt(sx),
  720. Math.sqrt(sy)
  721. ];
  722. };
  723. // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
  724. // For coordinate systems whose origin lies in the bottom-left, this
  725. // means normalization to (BL,TR) ordering. For systems with origin in the
  726. // top-left, this means (TL,BR) ordering.
  727. Util.normalizeRect = function Util_normalizeRect(rect) {
  728. var r = rect.slice(0);
  729. // clone rect
  730. if (rect[0] > rect[2]) {
  731. r[0] = rect[2];
  732. r[2] = rect[0];
  733. }
  734. if (rect[1] > rect[3]) {
  735. r[1] = rect[3];
  736. r[3] = rect[1];
  737. }
  738. return r;
  739. };
  740. // Returns a rectangle [x1, y1, x2, y2] corresponding to the
  741. // intersection of rect1 and rect2. If no intersection, returns 'false'
  742. // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
  743. Util.intersect = function Util_intersect(rect1, rect2) {
  744. function compare(a, b) {
  745. return a - b;
  746. }
  747. // Order points along the axes
  748. var orderedX = [
  749. rect1[0],
  750. rect1[2],
  751. rect2[0],
  752. rect2[2]
  753. ].sort(compare), orderedY = [
  754. rect1[1],
  755. rect1[3],
  756. rect2[1],
  757. rect2[3]
  758. ].sort(compare), result = [];
  759. rect1 = Util.normalizeRect(rect1);
  760. rect2 = Util.normalizeRect(rect2);
  761. // X: first and second points belong to different rectangles?
  762. if (orderedX[0] === rect1[0] && orderedX[1] === rect2[0] || orderedX[0] === rect2[0] && orderedX[1] === rect1[0]) {
  763. // Intersection must be between second and third points
  764. result[0] = orderedX[1];
  765. result[2] = orderedX[2];
  766. } else {
  767. return false;
  768. }
  769. // Y: first and second points belong to different rectangles?
  770. if (orderedY[0] === rect1[1] && orderedY[1] === rect2[1] || orderedY[0] === rect2[1] && orderedY[1] === rect1[1]) {
  771. // Intersection must be between second and third points
  772. result[1] = orderedY[1];
  773. result[3] = orderedY[2];
  774. } else {
  775. return false;
  776. }
  777. return result;
  778. };
  779. Util.sign = function Util_sign(num) {
  780. return num < 0 ? -1 : 1;
  781. };
  782. var ROMAN_NUMBER_MAP = [
  783. '',
  784. 'C',
  785. 'CC',
  786. 'CCC',
  787. 'CD',
  788. 'D',
  789. 'DC',
  790. 'DCC',
  791. 'DCCC',
  792. 'CM',
  793. '',
  794. 'X',
  795. 'XX',
  796. 'XXX',
  797. 'XL',
  798. 'L',
  799. 'LX',
  800. 'LXX',
  801. 'LXXX',
  802. 'XC',
  803. '',
  804. 'I',
  805. 'II',
  806. 'III',
  807. 'IV',
  808. 'V',
  809. 'VI',
  810. 'VII',
  811. 'VIII',
  812. 'IX'
  813. ];
  814. /**
  815. * Converts positive integers to (upper case) Roman numerals.
  816. * @param {integer} number - The number that should be converted.
  817. * @param {boolean} lowerCase - Indicates if the result should be converted
  818. * to lower case letters. The default is false.
  819. * @return {string} The resulting Roman number.
  820. */
  821. Util.toRoman = function Util_toRoman(number, lowerCase) {
  822. assert(isInt(number) && number > 0, 'The number should be a positive integer.');
  823. var pos, romanBuf = [];
  824. // Thousands
  825. while (number >= 1000) {
  826. number -= 1000;
  827. romanBuf.push('M');
  828. }
  829. // Hundreds
  830. pos = number / 100 | 0;
  831. number %= 100;
  832. romanBuf.push(ROMAN_NUMBER_MAP[pos]);
  833. // Tens
  834. pos = number / 10 | 0;
  835. number %= 10;
  836. romanBuf.push(ROMAN_NUMBER_MAP[10 + pos]);
  837. // Ones
  838. romanBuf.push(ROMAN_NUMBER_MAP[20 + number]);
  839. var romanStr = romanBuf.join('');
  840. return lowerCase ? romanStr.toLowerCase() : romanStr;
  841. };
  842. Util.appendToArray = function Util_appendToArray(arr1, arr2) {
  843. Array.prototype.push.apply(arr1, arr2);
  844. };
  845. Util.prependToArray = function Util_prependToArray(arr1, arr2) {
  846. Array.prototype.unshift.apply(arr1, arr2);
  847. };
  848. Util.extendObj = function extendObj(obj1, obj2) {
  849. for (var key in obj2) {
  850. obj1[key] = obj2[key];
  851. }
  852. };
  853. Util.getInheritableProperty = function Util_getInheritableProperty(dict, name, getArray) {
  854. while (dict && !dict.has(name)) {
  855. dict = dict.get('Parent');
  856. }
  857. if (!dict) {
  858. return null;
  859. }
  860. return getArray ? dict.getArray(name) : dict.get(name);
  861. };
  862. Util.inherit = function Util_inherit(sub, base, prototype) {
  863. sub.prototype = Object.create(base.prototype);
  864. sub.prototype.constructor = sub;
  865. for (var prop in prototype) {
  866. sub.prototype[prop] = prototype[prop];
  867. }
  868. };
  869. Util.loadScript = function Util_loadScript(src, callback) {
  870. var script = document.createElement('script');
  871. var loaded = false;
  872. script.setAttribute('src', src);
  873. if (callback) {
  874. script.onload = function () {
  875. if (!loaded) {
  876. callback();
  877. }
  878. loaded = true;
  879. };
  880. }
  881. document.getElementsByTagName('head')[0].appendChild(script);
  882. };
  883. return Util;
  884. }();
  885. /**
  886. * PDF page viewport created based on scale, rotation and offset.
  887. * @class
  888. * @alias PageViewport
  889. */
  890. var PageViewport = function PageViewportClosure() {
  891. /**
  892. * @constructor
  893. * @private
  894. * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
  895. * @param scale {number} scale of the viewport.
  896. * @param rotation {number} rotations of the viewport in degrees.
  897. * @param offsetX {number} offset X
  898. * @param offsetY {number} offset Y
  899. * @param dontFlip {boolean} if true, axis Y will not be flipped.
  900. */
  901. function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
  902. this.viewBox = viewBox;
  903. this.scale = scale;
  904. this.rotation = rotation;
  905. this.offsetX = offsetX;
  906. this.offsetY = offsetY;
  907. // creating transform to convert pdf coordinate system to the normal
  908. // canvas like coordinates taking in account scale and rotation
  909. var centerX = (viewBox[2] + viewBox[0]) / 2;
  910. var centerY = (viewBox[3] + viewBox[1]) / 2;
  911. var rotateA, rotateB, rotateC, rotateD;
  912. rotation = rotation % 360;
  913. rotation = rotation < 0 ? rotation + 360 : rotation;
  914. switch (rotation) {
  915. case 180:
  916. rotateA = -1;
  917. rotateB = 0;
  918. rotateC = 0;
  919. rotateD = 1;
  920. break;
  921. case 90:
  922. rotateA = 0;
  923. rotateB = 1;
  924. rotateC = 1;
  925. rotateD = 0;
  926. break;
  927. case 270:
  928. rotateA = 0;
  929. rotateB = -1;
  930. rotateC = -1;
  931. rotateD = 0;
  932. break;
  933. //case 0:
  934. default:
  935. rotateA = 1;
  936. rotateB = 0;
  937. rotateC = 0;
  938. rotateD = -1;
  939. break;
  940. }
  941. if (dontFlip) {
  942. rotateC = -rotateC;
  943. rotateD = -rotateD;
  944. }
  945. var offsetCanvasX, offsetCanvasY;
  946. var width, height;
  947. if (rotateA === 0) {
  948. offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
  949. offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
  950. width = Math.abs(viewBox[3] - viewBox[1]) * scale;
  951. height = Math.abs(viewBox[2] - viewBox[0]) * scale;
  952. } else {
  953. offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
  954. offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
  955. width = Math.abs(viewBox[2] - viewBox[0]) * scale;
  956. height = Math.abs(viewBox[3] - viewBox[1]) * scale;
  957. }
  958. // creating transform for the following operations:
  959. // translate(-centerX, -centerY), rotate and flip vertically,
  960. // scale, and translate(offsetCanvasX, offsetCanvasY)
  961. this.transform = [
  962. rotateA * scale,
  963. rotateB * scale,
  964. rotateC * scale,
  965. rotateD * scale,
  966. offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
  967. offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
  968. ];
  969. this.width = width;
  970. this.height = height;
  971. this.fontScale = scale;
  972. }
  973. PageViewport.prototype = /** @lends PageViewport.prototype */
  974. {
  975. /**
  976. * Clones viewport with additional properties.
  977. * @param args {Object} (optional) If specified, may contain the 'scale' or
  978. * 'rotation' properties to override the corresponding properties in
  979. * the cloned viewport.
  980. * @returns {PageViewport} Cloned viewport.
  981. */
  982. clone: function PageViewPort_clone(args) {
  983. args = args || {};
  984. var scale = 'scale' in args ? args.scale : this.scale;
  985. var rotation = 'rotation' in args ? args.rotation : this.rotation;
  986. return new PageViewport(this.viewBox.slice(), scale, rotation, this.offsetX, this.offsetY, args.dontFlip);
  987. },
  988. /**
  989. * Converts PDF point to the viewport coordinates. For examples, useful for
  990. * converting PDF location into canvas pixel coordinates.
  991. * @param x {number} X coordinate.
  992. * @param y {number} Y coordinate.
  993. * @returns {Object} Object that contains 'x' and 'y' properties of the
  994. * point in the viewport coordinate space.
  995. * @see {@link convertToPdfPoint}
  996. * @see {@link convertToViewportRectangle}
  997. */
  998. convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
  999. return Util.applyTransform([
  1000. x,
  1001. y
  1002. ], this.transform);
  1003. },
  1004. /**
  1005. * Converts PDF rectangle to the viewport coordinates.
  1006. * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
  1007. * @returns {Array} Contains corresponding coordinates of the rectangle
  1008. * in the viewport coordinate space.
  1009. * @see {@link convertToViewportPoint}
  1010. */
  1011. convertToViewportRectangle: function PageViewport_convertToViewportRectangle(rect) {
  1012. var tl = Util.applyTransform([
  1013. rect[0],
  1014. rect[1]
  1015. ], this.transform);
  1016. var br = Util.applyTransform([
  1017. rect[2],
  1018. rect[3]
  1019. ], this.transform);
  1020. return [
  1021. tl[0],
  1022. tl[1],
  1023. br[0],
  1024. br[1]
  1025. ];
  1026. },
  1027. /**
  1028. * Converts viewport coordinates to the PDF location. For examples, useful
  1029. * for converting canvas pixel location into PDF one.
  1030. * @param x {number} X coordinate.
  1031. * @param y {number} Y coordinate.
  1032. * @returns {Object} Object that contains 'x' and 'y' properties of the
  1033. * point in the PDF coordinate space.
  1034. * @see {@link convertToViewportPoint}
  1035. */
  1036. convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
  1037. return Util.applyInverseTransform([
  1038. x,
  1039. y
  1040. ], this.transform);
  1041. }
  1042. };
  1043. return PageViewport;
  1044. }();
  1045. var PDFStringTranslateTable = [
  1046. 0,
  1047. 0,
  1048. 0,
  1049. 0,
  1050. 0,
  1051. 0,
  1052. 0,
  1053. 0,
  1054. 0,
  1055. 0,
  1056. 0,
  1057. 0,
  1058. 0,
  1059. 0,
  1060. 0,
  1061. 0,
  1062. 0,
  1063. 0,
  1064. 0,
  1065. 0,
  1066. 0,
  1067. 0,
  1068. 0,
  1069. 0,
  1070. 0x2D8,
  1071. 0x2C7,
  1072. 0x2C6,
  1073. 0x2D9,
  1074. 0x2DD,
  1075. 0x2DB,
  1076. 0x2DA,
  1077. 0x2DC,
  1078. 0,
  1079. 0,
  1080. 0,
  1081. 0,
  1082. 0,
  1083. 0,
  1084. 0,
  1085. 0,
  1086. 0,
  1087. 0,
  1088. 0,
  1089. 0,
  1090. 0,
  1091. 0,
  1092. 0,
  1093. 0,
  1094. 0,
  1095. 0,
  1096. 0,
  1097. 0,
  1098. 0,
  1099. 0,
  1100. 0,
  1101. 0,
  1102. 0,
  1103. 0,
  1104. 0,
  1105. 0,
  1106. 0,
  1107. 0,
  1108. 0,
  1109. 0,
  1110. 0,
  1111. 0,
  1112. 0,
  1113. 0,
  1114. 0,
  1115. 0,
  1116. 0,
  1117. 0,
  1118. 0,
  1119. 0,
  1120. 0,
  1121. 0,
  1122. 0,
  1123. 0,
  1124. 0,
  1125. 0,
  1126. 0,
  1127. 0,
  1128. 0,
  1129. 0,
  1130. 0,
  1131. 0,
  1132. 0,
  1133. 0,
  1134. 0,
  1135. 0,
  1136. 0,
  1137. 0,
  1138. 0,
  1139. 0,
  1140. 0,
  1141. 0,
  1142. 0,
  1143. 0,
  1144. 0,
  1145. 0,
  1146. 0,
  1147. 0,
  1148. 0,
  1149. 0,
  1150. 0,
  1151. 0,
  1152. 0,
  1153. 0,
  1154. 0,
  1155. 0,
  1156. 0,
  1157. 0,
  1158. 0,
  1159. 0,
  1160. 0,
  1161. 0,
  1162. 0,
  1163. 0,
  1164. 0,
  1165. 0,
  1166. 0,
  1167. 0,
  1168. 0,
  1169. 0,
  1170. 0,
  1171. 0,
  1172. 0,
  1173. 0,
  1174. 0x2022,
  1175. 0x2020,
  1176. 0x2021,
  1177. 0x2026,
  1178. 0x2014,
  1179. 0x2013,
  1180. 0x192,
  1181. 0x2044,
  1182. 0x2039,
  1183. 0x203A,
  1184. 0x2212,
  1185. 0x2030,
  1186. 0x201E,
  1187. 0x201C,
  1188. 0x201D,
  1189. 0x2018,
  1190. 0x2019,
  1191. 0x201A,
  1192. 0x2122,
  1193. 0xFB01,
  1194. 0xFB02,
  1195. 0x141,
  1196. 0x152,
  1197. 0x160,
  1198. 0x178,
  1199. 0x17D,
  1200. 0x131,
  1201. 0x142,
  1202. 0x153,
  1203. 0x161,
  1204. 0x17E,
  1205. 0,
  1206. 0x20AC
  1207. ];
  1208. function stringToPDFString(str) {
  1209. var i, n = str.length, strBuf = [];
  1210. if (str[0] === '\xFE' && str[1] === '\xFF') {
  1211. // UTF16BE BOM
  1212. for (i = 2; i < n; i += 2) {
  1213. strBuf.push(String.fromCharCode(str.charCodeAt(i) << 8 | str.charCodeAt(i + 1)));
  1214. }
  1215. } else {
  1216. for (i = 0; i < n; ++i) {
  1217. var code = PDFStringTranslateTable[str.charCodeAt(i)];
  1218. strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
  1219. }
  1220. }
  1221. return strBuf.join('');
  1222. }
  1223. function stringToUTF8String(str) {
  1224. return decodeURIComponent(escape(str));
  1225. }
  1226. function utf8StringToString(str) {
  1227. return unescape(encodeURIComponent(str));
  1228. }
  1229. function isEmptyObj(obj) {
  1230. for (var key in obj) {
  1231. return false;
  1232. }
  1233. return true;
  1234. }
  1235. function isBool(v) {
  1236. return typeof v === 'boolean';
  1237. }
  1238. function isInt(v) {
  1239. return typeof v === 'number' && (v | 0) === v;
  1240. }
  1241. function isNum(v) {
  1242. return typeof v === 'number';
  1243. }
  1244. function isString(v) {
  1245. return typeof v === 'string';
  1246. }
  1247. function isArray(v) {
  1248. return v instanceof Array;
  1249. }
  1250. function isArrayBuffer(v) {
  1251. return typeof v === 'object' && v !== null && v.byteLength !== undefined;
  1252. }
  1253. // Checks if ch is one of the following characters: SPACE, TAB, CR or LF.
  1254. function isSpace(ch) {
  1255. return ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A;
  1256. }
  1257. /**
  1258. * Promise Capability object.
  1259. *
  1260. * @typedef {Object} PromiseCapability
  1261. * @property {Promise} promise - A promise object.
  1262. * @property {function} resolve - Fulfills the promise.
  1263. * @property {function} reject - Rejects the promise.
  1264. */
  1265. /**
  1266. * Creates a promise capability object.
  1267. * @alias createPromiseCapability
  1268. *
  1269. * @return {PromiseCapability} A capability object contains:
  1270. * - a Promise, resolve and reject methods.
  1271. */
  1272. function createPromiseCapability() {
  1273. var capability = {};
  1274. capability.promise = new Promise(function (resolve, reject) {
  1275. capability.resolve = resolve;
  1276. capability.reject = reject;
  1277. });
  1278. return capability;
  1279. }
  1280. /**
  1281. * Polyfill for Promises:
  1282. * The following promise implementation tries to generally implement the
  1283. * Promise/A+ spec. Some notable differences from other promise libraries are:
  1284. * - There currently isn't a separate deferred and promise object.
  1285. * - Unhandled rejections eventually show an error if they aren't handled.
  1286. *
  1287. * Based off of the work in:
  1288. * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
  1289. */
  1290. (function PromiseClosure() {
  1291. if (globalScope.Promise) {
  1292. // Promises existing in the DOM/Worker, checking presence of all/resolve
  1293. if (typeof globalScope.Promise.all !== 'function') {
  1294. globalScope.Promise.all = function (iterable) {
  1295. var count = 0, results = [], resolve, reject;
  1296. var promise = new globalScope.Promise(function (resolve_, reject_) {
  1297. resolve = resolve_;
  1298. reject = reject_;
  1299. });
  1300. iterable.forEach(function (p, i) {
  1301. count++;
  1302. p.then(function (result) {
  1303. results[i] = result;
  1304. count--;
  1305. if (count === 0) {
  1306. resolve(results);
  1307. }
  1308. }, reject);
  1309. });
  1310. if (count === 0) {
  1311. resolve(results);
  1312. }
  1313. return promise;
  1314. };
  1315. }
  1316. if (typeof globalScope.Promise.resolve !== 'function') {
  1317. globalScope.Promise.resolve = function (value) {
  1318. return new globalScope.Promise(function (resolve) {
  1319. resolve(value);
  1320. });
  1321. };
  1322. }
  1323. if (typeof globalScope.Promise.reject !== 'function') {
  1324. globalScope.Promise.reject = function (reason) {
  1325. return new globalScope.Promise(function (resolve, reject) {
  1326. reject(reason);
  1327. });
  1328. };
  1329. }
  1330. if (typeof globalScope.Promise.prototype.catch !== 'function') {
  1331. globalScope.Promise.prototype.catch = function (onReject) {
  1332. return globalScope.Promise.prototype.then(undefined, onReject);
  1333. };
  1334. }
  1335. return;
  1336. }
  1337. var STATUS_PENDING = 0;
  1338. var STATUS_RESOLVED = 1;
  1339. var STATUS_REJECTED = 2;
  1340. // In an attempt to avoid silent exceptions, unhandled rejections are
  1341. // tracked and if they aren't handled in a certain amount of time an
  1342. // error is logged.
  1343. var REJECTION_TIMEOUT = 500;
  1344. var HandlerManager = {
  1345. handlers: [],
  1346. running: false,
  1347. unhandledRejections: [],
  1348. pendingRejectionCheck: false,
  1349. scheduleHandlers: function scheduleHandlers(promise) {
  1350. if (promise._status === STATUS_PENDING) {
  1351. return;
  1352. }
  1353. this.handlers = this.handlers.concat(promise._handlers);
  1354. promise._handlers = [];
  1355. if (this.running) {
  1356. return;
  1357. }
  1358. this.running = true;
  1359. setTimeout(this.runHandlers.bind(this), 0);
  1360. },
  1361. runHandlers: function runHandlers() {
  1362. var RUN_TIMEOUT = 1;
  1363. // ms
  1364. var timeoutAt = Date.now() + RUN_TIMEOUT;
  1365. while (this.handlers.length > 0) {
  1366. var handler = this.handlers.shift();
  1367. var nextStatus = handler.thisPromise._status;
  1368. var nextValue = handler.thisPromise._value;
  1369. try {
  1370. if (nextStatus === STATUS_RESOLVED) {
  1371. if (typeof handler.onResolve === 'function') {
  1372. nextValue = handler.onResolve(nextValue);
  1373. }
  1374. } else if (typeof handler.onReject === 'function') {
  1375. nextValue = handler.onReject(nextValue);
  1376. nextStatus = STATUS_RESOLVED;
  1377. if (handler.thisPromise._unhandledRejection) {
  1378. this.removeUnhandeledRejection(handler.thisPromise);
  1379. }
  1380. }
  1381. } catch (ex) {
  1382. nextStatus = STATUS_REJECTED;
  1383. nextValue = ex;
  1384. }
  1385. handler.nextPromise._updateStatus(nextStatus, nextValue);
  1386. if (Date.now() >= timeoutAt) {
  1387. break;
  1388. }
  1389. }
  1390. if (this.handlers.length > 0) {
  1391. setTimeout(this.runHandlers.bind(this), 0);
  1392. return;
  1393. }
  1394. this.running = false;
  1395. },
  1396. addUnhandledRejection: function addUnhandledRejection(promise) {
  1397. this.unhandledRejections.push({
  1398. promise: promise,
  1399. time: Date.now()
  1400. });
  1401. this.scheduleRejectionCheck();
  1402. },
  1403. removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
  1404. promise._unhandledRejection = false;
  1405. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1406. if (this.unhandledRejections[i].promise === promise) {
  1407. this.unhandledRejections.splice(i);
  1408. i--;
  1409. }
  1410. }
  1411. },
  1412. scheduleRejectionCheck: function scheduleRejectionCheck() {
  1413. if (this.pendingRejectionCheck) {
  1414. return;
  1415. }
  1416. this.pendingRejectionCheck = true;
  1417. setTimeout(function rejectionCheck() {
  1418. this.pendingRejectionCheck = false;
  1419. var now = Date.now();
  1420. for (var i = 0; i < this.unhandledRejections.length; i++) {
  1421. if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
  1422. var unhandled = this.unhandledRejections[i].promise._value;
  1423. var msg = 'Unhandled rejection: ' + unhandled;
  1424. if (unhandled.stack) {
  1425. msg += '\n' + unhandled.stack;
  1426. }
  1427. warn(msg);
  1428. this.unhandledRejections.splice(i);
  1429. i--;
  1430. }
  1431. }
  1432. if (this.unhandledRejections.length) {
  1433. this.scheduleRejectionCheck();
  1434. }
  1435. }.bind(this), REJECTION_TIMEOUT);
  1436. }
  1437. };
  1438. var Promise = function Promise(resolver) {
  1439. this._status = STATUS_PENDING;
  1440. this._handlers = [];
  1441. try {
  1442. resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
  1443. } catch (e) {
  1444. this._reject(e);
  1445. }
  1446. };
  1447. /**
  1448. * Builds a promise that is resolved when all the passed in promises are
  1449. * resolved.
  1450. * @param {array} promises array of data and/or promises to wait for.
  1451. * @return {Promise} New dependent promise.
  1452. */
  1453. Promise.all = function Promise_all(promises) {
  1454. var resolveAll, rejectAll;
  1455. var deferred = new Promise(function (resolve, reject) {
  1456. resolveAll = resolve;
  1457. rejectAll = reject;
  1458. });
  1459. var unresolved = promises.length;
  1460. var results = [];
  1461. if (unresolved === 0) {
  1462. resolveAll(results);
  1463. return deferred;
  1464. }
  1465. function reject(reason) {
  1466. if (deferred._status === STATUS_REJECTED) {
  1467. return;
  1468. }
  1469. results = [];
  1470. rejectAll(reason);
  1471. }
  1472. for (var i = 0, ii = promises.length; i < ii; ++i) {
  1473. var promise = promises[i];
  1474. var resolve = function (i) {
  1475. return function (value) {
  1476. if (deferred._status === STATUS_REJECTED) {
  1477. return;
  1478. }
  1479. results[i] = value;
  1480. unresolved--;
  1481. if (unresolved === 0) {
  1482. resolveAll(results);
  1483. }
  1484. };
  1485. }(i);
  1486. if (Promise.isPromise(promise)) {
  1487. promise.then(resolve, reject);
  1488. } else {
  1489. resolve(promise);
  1490. }
  1491. }
  1492. return deferred;
  1493. };
  1494. /**
  1495. * Checks if the value is likely a promise (has a 'then' function).
  1496. * @return {boolean} true if value is thenable
  1497. */
  1498. Promise.isPromise = function Promise_isPromise(value) {
  1499. return value && typeof value.then === 'function';
  1500. };
  1501. /**
  1502. * Creates resolved promise
  1503. * @param value resolve value
  1504. * @returns {Promise}
  1505. */
  1506. Promise.resolve = function Promise_resolve(value) {
  1507. return new Promise(function (resolve) {
  1508. resolve(value);
  1509. });
  1510. };
  1511. /**
  1512. * Creates rejected promise
  1513. * @param reason rejection value
  1514. * @returns {Promise}
  1515. */
  1516. Promise.reject = function Promise_reject(reason) {
  1517. return new Promise(function (resolve, reject) {
  1518. reject(reason);
  1519. });
  1520. };
  1521. Promise.prototype = {
  1522. _status: null,
  1523. _value: null,
  1524. _handlers: null,
  1525. _unhandledRejection: null,
  1526. _updateStatus: function Promise__updateStatus(status, value) {
  1527. if (this._status === STATUS_RESOLVED || this._status === STATUS_REJECTED) {
  1528. return;
  1529. }
  1530. if (status === STATUS_RESOLVED && Promise.isPromise(value)) {
  1531. value.then(this._updateStatus.bind(this, STATUS_RESOLVED), this._updateStatus.bind(this, STATUS_REJECTED));
  1532. return;
  1533. }
  1534. this._status = status;
  1535. this._value = value;
  1536. if (status === STATUS_REJECTED && this._handlers.length === 0) {
  1537. this._unhandledRejection = true;
  1538. HandlerManager.addUnhandledRejection(this);
  1539. }
  1540. HandlerManager.scheduleHandlers(this);
  1541. },
  1542. _resolve: function Promise_resolve(value) {
  1543. this._updateStatus(STATUS_RESOLVED, value);
  1544. },
  1545. _reject: function Promise_reject(reason) {
  1546. this._updateStatus(STATUS_REJECTED, reason);
  1547. },
  1548. then: function Promise_then(onResolve, onReject) {
  1549. var nextPromise = new Promise(function (resolve, reject) {
  1550. this.resolve = resolve;
  1551. this.reject = reject;
  1552. });
  1553. this._handlers.push({
  1554. thisPromise: this,
  1555. onResolve: onResolve,
  1556. onReject: onReject,
  1557. nextPromise: nextPromise
  1558. });
  1559. HandlerManager.scheduleHandlers(this);
  1560. return nextPromise;
  1561. },
  1562. catch: function Promise_catch(onReject) {
  1563. return this.then(undefined, onReject);
  1564. }
  1565. };
  1566. globalScope.Promise = Promise;
  1567. }());
  1568. (function WeakMapClosure() {
  1569. if (globalScope.WeakMap) {
  1570. return;
  1571. }
  1572. var id = 0;
  1573. function WeakMap() {
  1574. this.id = '$weakmap' + id++;
  1575. }
  1576. WeakMap.prototype = {
  1577. has: function (obj) {
  1578. return !!Object.getOwnPropertyDescriptor(obj, this.id);
  1579. },
  1580. get: function (obj, defaultValue) {
  1581. return this.has(obj) ? obj[this.id] : defaultValue;
  1582. },
  1583. set: function (obj, value) {
  1584. Object.defineProperty(obj, this.id, {
  1585. value: value,
  1586. enumerable: false,
  1587. configurable: true
  1588. });
  1589. },
  1590. delete: function (obj) {
  1591. delete obj[this.id];
  1592. }
  1593. };
  1594. globalScope.WeakMap = WeakMap;
  1595. }());
  1596. var StatTimer = function StatTimerClosure() {
  1597. function rpad(str, pad, length) {
  1598. while (str.length < length) {
  1599. str += pad;
  1600. }
  1601. return str;
  1602. }
  1603. function StatTimer() {
  1604. this.started = Object.create(null);
  1605. this.times = [];
  1606. this.enabled = true;
  1607. }
  1608. StatTimer.prototype = {
  1609. time: function StatTimer_time(name) {
  1610. if (!this.enabled) {
  1611. return;
  1612. }
  1613. if (name in this.started) {
  1614. warn('Timer is already running for ' + name);
  1615. }
  1616. this.started[name] = Date.now();
  1617. },
  1618. timeEnd: function StatTimer_timeEnd(name) {
  1619. if (!this.enabled) {
  1620. return;
  1621. }
  1622. if (!(name in this.started)) {
  1623. warn('Timer has not been started for ' + name);
  1624. }
  1625. this.times.push({
  1626. 'name': name,
  1627. 'start': this.started[name],
  1628. 'end': Date.now()
  1629. });
  1630. // Remove timer from started so it can be called again.
  1631. delete this.started[name];
  1632. },
  1633. toString: function StatTimer_toString() {
  1634. var i, ii;
  1635. var times = this.times;
  1636. var out = '';
  1637. // Find the longest name for padding purposes.
  1638. var longest = 0;
  1639. for (i = 0, ii = times.length; i < ii; ++i) {
  1640. var name = times[i]['name'];
  1641. if (name.length > longest) {
  1642. longest = name.length;
  1643. }
  1644. }
  1645. for (i = 0, ii = times.length; i < ii; ++i) {
  1646. var span = times[i];
  1647. var duration = span.end - span.start;
  1648. out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
  1649. }
  1650. return out;
  1651. }
  1652. };
  1653. return StatTimer;
  1654. }();
  1655. var createBlob = function createBlob(data, contentType) {
  1656. if (typeof Blob !== 'undefined') {
  1657. return new Blob([data], { type: contentType });
  1658. }
  1659. warn('The "Blob" constructor is not supported.');
  1660. };
  1661. var createObjectURL = function createObjectURLClosure() {
  1662. // Blob/createObjectURL is not available, falling back to data schema.
  1663. var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1664. return function createObjectURL(data, contentType, forceDataSchema) {
  1665. if (!forceDataSchema && typeof URL !== 'undefined' && URL.createObjectURL) {
  1666. var blob = createBlob(data, contentType);
  1667. return URL.createObjectURL(blob);
  1668. }
  1669. var buffer = 'data:' + contentType + ';base64,';
  1670. for (var i = 0, ii = data.length; i < ii; i += 3) {
  1671. var b1 = data[i] & 0xFF;
  1672. var b2 = data[i + 1] & 0xFF;
  1673. var b3 = data[i + 2] & 0xFF;
  1674. var d1 = b1 >> 2, d2 = (b1 & 3) << 4 | b2 >> 4;
  1675. var d3 = i + 1 < ii ? (b2 & 0xF) << 2 | b3 >> 6 : 64;
  1676. var d4 = i + 2 < ii ? b3 & 0x3F : 64;
  1677. buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
  1678. }
  1679. return buffer;
  1680. };
  1681. }();
  1682. function MessageHandler(sourceName, targetName, comObj) {
  1683. this.sourceName = sourceName;
  1684. this.targetName = targetName;
  1685. this.comObj = comObj;
  1686. this.callbackIndex = 1;
  1687. this.postMessageTransfers = true;
  1688. var callbacksCapabilities = this.callbacksCapabilities = Object.create(null);
  1689. var ah = this.actionHandler = Object.create(null);
  1690. this._onComObjOnMessage = function messageHandlerComObjOnMessage(event) {
  1691. var data = event.data;
  1692. if (data.targetName !== this.sourceName) {
  1693. return;
  1694. }
  1695. if (data.isReply) {
  1696. var callbackId = data.callbackId;
  1697. if (data.callbackId in callbacksCapabilities) {
  1698. var callback = callbacksCapabilities[callbackId];
  1699. delete callbacksCapabilities[callbackId];
  1700. if ('error' in data) {
  1701. callback.reject(data.error);
  1702. } else {
  1703. callback.resolve(data.data);
  1704. }
  1705. } else {
  1706. error('Cannot resolve callback ' + callbackId);
  1707. }
  1708. } else if (data.action in ah) {
  1709. var action = ah[data.action];
  1710. if (data.callbackId) {
  1711. var sourceName = this.sourceName;
  1712. var targetName = data.sourceName;
  1713. Promise.resolve().then(function () {
  1714. return action[0].call(action[1], data.data);
  1715. }).then(function (result) {
  1716. comObj.postMessage({
  1717. sourceName: sourceName,
  1718. targetName: targetName,
  1719. isReply: true,
  1720. callbackId: data.callbackId,
  1721. data: result
  1722. });
  1723. }, function (reason) {
  1724. if (reason instanceof Error) {
  1725. // Serialize error to avoid "DataCloneError"
  1726. reason = reason + '';
  1727. }
  1728. comObj.postMessage({
  1729. sourceName: sourceName,
  1730. targetName: targetName,
  1731. isReply: true,
  1732. callbackId: data.callbackId,
  1733. error: reason
  1734. });
  1735. });
  1736. } else {
  1737. action[0].call(action[1], data.data);
  1738. }
  1739. } else {
  1740. error('Unknown action from worker: ' + data.action);
  1741. }
  1742. }.bind(this);
  1743. comObj.addEventListener('message', this._onComObjOnMessage);
  1744. }
  1745. MessageHandler.prototype = {
  1746. on: function messageHandlerOn(actionName, handler, scope) {
  1747. var ah = this.actionHandler;
  1748. if (ah[actionName]) {
  1749. error('There is already an actionName called "' + actionName + '"');
  1750. }
  1751. ah[actionName] = [
  1752. handler,
  1753. scope
  1754. ];
  1755. },
  1756. /**
  1757. * Sends a message to the comObj to invoke the action with the supplied data.
  1758. * @param {String} actionName Action to call.
  1759. * @param {JSON} data JSON data to send.
  1760. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
  1761. */
  1762. send: function messageHandlerSend(actionName, data, transfers) {
  1763. var message = {
  1764. sourceName: this.sourceName,
  1765. targetName: this.targetName,
  1766. action: actionName,
  1767. data: data
  1768. };
  1769. this.postMessage(message, transfers);
  1770. },
  1771. /**
  1772. * Sends a message to the comObj to invoke the action with the supplied data.
  1773. * Expects that other side will callback with the response.
  1774. * @param {String} actionName Action to call.
  1775. * @param {JSON} data JSON data to send.
  1776. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
  1777. * @returns {Promise} Promise to be resolved with response data.
  1778. */
  1779. sendWithPromise: function messageHandlerSendWithPromise(actionName, data, transfers) {
  1780. var callbackId = this.callbackIndex++;
  1781. var message = {
  1782. sourceName: this.sourceName,
  1783. targetName: this.targetName,
  1784. action: actionName,
  1785. data: data,
  1786. callbackId: callbackId
  1787. };
  1788. var capability = createPromiseCapability();
  1789. this.callbacksCapabilities[callbackId] = capability;
  1790. try {
  1791. this.postMessage(message, transfers);
  1792. } catch (e) {
  1793. capability.reject(e);
  1794. }
  1795. return capability.promise;
  1796. },
  1797. /**
  1798. * Sends raw message to the comObj.
  1799. * @private
  1800. * @param message {Object} Raw message.
  1801. * @param transfers List of transfers/ArrayBuffers, or undefined.
  1802. */
  1803. postMessage: function (message, transfers) {
  1804. if (transfers && this.postMessageTransfers) {
  1805. this.comObj.postMessage(message, transfers);
  1806. } else {
  1807. this.comObj.postMessage(message);
  1808. }
  1809. },
  1810. destroy: function () {
  1811. this.comObj.removeEventListener('message', this._onComObjOnMessage);
  1812. }
  1813. };
  1814. function loadJpegStream(id, imageUrl, objs) {
  1815. var img = new Image();
  1816. img.onload = function loadJpegStream_onloadClosure() {
  1817. objs.resolve(id, img);
  1818. };
  1819. img.onerror = function loadJpegStream_onerrorClosure() {
  1820. objs.resolve(id, null);
  1821. warn('Error during JPEG image loading');
  1822. };
  1823. img.src = imageUrl;
  1824. }
  1825. // Polyfill from https://github.com/Polymer/URL
  1826. /* Any copyright is dedicated to the Public Domain.
  1827. * http://creativecommons.org/publicdomain/zero/1.0/ */
  1828. (function checkURLConstructor(scope) {
  1829. // feature detect for URL constructor
  1830. var hasWorkingUrl = false;
  1831. try {
  1832. if (typeof URL === 'function' && typeof URL.prototype === 'object' && 'origin' in URL.prototype) {
  1833. var u = new URL('b', 'http://a');
  1834. u.pathname = 'c%20d';
  1835. hasWorkingUrl = u.href === 'http://a/c%20d';
  1836. }
  1837. } catch (e) {
  1838. }
  1839. if (hasWorkingUrl) {
  1840. return;
  1841. }
  1842. var relative = Object.create(null);
  1843. relative['ftp'] = 21;
  1844. relative['file'] = 0;
  1845. relative['gopher'] = 70;
  1846. relative['http'] = 80;
  1847. relative['https'] = 443;
  1848. relative['ws'] = 80;
  1849. relative['wss'] = 443;
  1850. var relativePathDotMapping = Object.create(null);
  1851. relativePathDotMapping['%2e'] = '.';
  1852. relativePathDotMapping['.%2e'] = '..';
  1853. relativePathDotMapping['%2e.'] = '..';
  1854. relativePathDotMapping['%2e%2e'] = '..';
  1855. function isRelativeScheme(scheme) {
  1856. return relative[scheme] !== undefined;
  1857. }
  1858. function invalid() {
  1859. clear.call(this);
  1860. this._isInvalid = true;
  1861. }
  1862. function IDNAToASCII(h) {
  1863. if ('' === h) {
  1864. invalid.call(this);
  1865. }
  1866. // XXX
  1867. return h.toLowerCase();
  1868. }
  1869. function percentEscape(c) {
  1870. var unicode = c.charCodeAt(0);
  1871. if (unicode > 0x20 && unicode < 0x7F && // " # < > ? `
  1872. [
  1873. 0x22,
  1874. 0x23,
  1875. 0x3C,
  1876. 0x3E,
  1877. 0x3F,
  1878. 0x60
  1879. ].indexOf(unicode) === -1) {
  1880. return c;
  1881. }
  1882. return encodeURIComponent(c);
  1883. }
  1884. function percentEscapeQuery(c) {
  1885. // XXX This actually needs to encode c using encoding and then
  1886. // convert the bytes one-by-one.
  1887. var unicode = c.charCodeAt(0);
  1888. if (unicode > 0x20 && unicode < 0x7F && // " # < > ` (do not escape '?')
  1889. [
  1890. 0x22,
  1891. 0x23,
  1892. 0x3C,
  1893. 0x3E,
  1894. 0x60
  1895. ].indexOf(unicode) === -1) {
  1896. return c;
  1897. }
  1898. return encodeURIComponent(c);
  1899. }
  1900. var EOF, ALPHA = /[a-zA-Z]/, ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/;
  1901. function parse(input, stateOverride, base) {
  1902. function err(message) {
  1903. errors.push(message);
  1904. }
  1905. var state = stateOverride || 'scheme start', cursor = 0, buffer = '', seenAt = false, seenBracket = false, errors = [];
  1906. loop:
  1907. while ((input[cursor - 1] !== EOF || cursor === 0) && !this._isInvalid) {
  1908. var c = input[cursor];
  1909. switch (state) {
  1910. case 'scheme start':
  1911. if (c && ALPHA.test(c)) {
  1912. buffer += c.toLowerCase();
  1913. // ASCII-safe
  1914. state = 'scheme';
  1915. } else if (!stateOverride) {
  1916. buffer = '';
  1917. state = 'no scheme';
  1918. continue;
  1919. } else {
  1920. err('Invalid scheme.');
  1921. break loop;
  1922. }
  1923. break;
  1924. case 'scheme':
  1925. if (c && ALPHANUMERIC.test(c)) {
  1926. buffer += c.toLowerCase();
  1927. } else // ASCII-safe
  1928. if (':' === c) {
  1929. this._scheme = buffer;
  1930. buffer = '';
  1931. if (stateOverride) {
  1932. break loop;
  1933. }
  1934. if (isRelativeScheme(this._scheme)) {
  1935. this._isRelative = true;
  1936. }
  1937. if ('file' === this._scheme) {
  1938. state = 'relative';
  1939. } else if (this._isRelative && base && base._scheme === this._scheme) {
  1940. state = 'relative or authority';
  1941. } else if (this._isRelative) {
  1942. state = 'authority first slash';
  1943. } else {
  1944. state = 'scheme data';
  1945. }
  1946. } else if (!stateOverride) {
  1947. buffer = '';
  1948. cursor = 0;
  1949. state = 'no scheme';
  1950. continue;
  1951. } else if (EOF === c) {
  1952. break loop;
  1953. } else {
  1954. err('Code point not allowed in scheme: ' + c);
  1955. break loop;
  1956. }
  1957. break;
  1958. case 'scheme data':
  1959. if ('?' === c) {
  1960. this._query = '?';
  1961. state = 'query';
  1962. } else if ('#' === c) {
  1963. this._fragment = '#';
  1964. state = 'fragment';
  1965. } else {
  1966. // XXX error handling
  1967. if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  1968. this._schemeData += percentEscape(c);
  1969. }
  1970. }
  1971. break;
  1972. case 'no scheme':
  1973. if (!base || !isRelativeScheme(base._scheme)) {
  1974. err('Missing scheme.');
  1975. invalid.call(this);
  1976. } else {
  1977. state = 'relative';
  1978. continue;
  1979. }
  1980. break;
  1981. case 'relative or authority':
  1982. if ('/' === c && '/' === input[cursor + 1]) {
  1983. state = 'authority ignore slashes';
  1984. } else {
  1985. err('Expected /, got: ' + c);
  1986. state = 'relative';
  1987. continue;
  1988. }
  1989. break;
  1990. case 'relative':
  1991. this._isRelative = true;
  1992. if ('file' !== this._scheme) {
  1993. this._scheme = base._scheme;
  1994. }
  1995. if (EOF === c) {
  1996. this._host = base._host;
  1997. this._port = base._port;
  1998. this._path = base._path.slice();
  1999. this._query = base._query;
  2000. this._username = base._username;
  2001. this._password = base._password;
  2002. break loop;
  2003. } else if ('/' === c || '\\' === c) {
  2004. if ('\\' === c) {
  2005. err('\\ is an invalid code point.');
  2006. }
  2007. state = 'relative slash';
  2008. } else if ('?' === c) {
  2009. this._host = base._host;
  2010. this._port = base._port;
  2011. this._path = base._path.slice();
  2012. this._query = '?';
  2013. this._username = base._username;
  2014. this._password = base._password;
  2015. state = 'query';
  2016. } else if ('#' === c) {
  2017. this._host = base._host;
  2018. this._port = base._port;
  2019. this._path = base._path.slice();
  2020. this._query = base._query;
  2021. this._fragment = '#';
  2022. this._username = base._username;
  2023. this._password = base._password;
  2024. state = 'fragment';
  2025. } else {
  2026. var nextC = input[cursor + 1];
  2027. var nextNextC = input[cursor + 2];
  2028. if ('file' !== this._scheme || !ALPHA.test(c) || nextC !== ':' && nextC !== '|' || EOF !== nextNextC && '/' !== nextNextC && '\\' !== nextNextC && '?' !== nextNextC && '#' !== nextNextC) {
  2029. this._host = base._host;
  2030. this._port = base._port;
  2031. this._username = base._username;
  2032. this._password = base._password;
  2033. this._path = base._path.slice();
  2034. this._path.pop();
  2035. }
  2036. state = 'relative path';
  2037. continue;
  2038. }
  2039. break;
  2040. case 'relative slash':
  2041. if ('/' === c || '\\' === c) {
  2042. if ('\\' === c) {
  2043. err('\\ is an invalid code point.');
  2044. }
  2045. if ('file' === this._scheme) {
  2046. state = 'file host';
  2047. } else {
  2048. state = 'authority ignore slashes';
  2049. }
  2050. } else {
  2051. if ('file' !== this._scheme) {
  2052. this._host = base._host;
  2053. this._port = base._port;
  2054. this._username = base._username;
  2055. this._password = base._password;
  2056. }
  2057. state = 'relative path';
  2058. continue;
  2059. }
  2060. break;
  2061. case 'authority first slash':
  2062. if ('/' === c) {
  2063. state = 'authority second slash';
  2064. } else {
  2065. err('Expected \'/\', got: ' + c);
  2066. state = 'authority ignore slashes';
  2067. continue;
  2068. }
  2069. break;
  2070. case 'authority second slash':
  2071. state = 'authority ignore slashes';
  2072. if ('/' !== c) {
  2073. err('Expected \'/\', got: ' + c);
  2074. continue;
  2075. }
  2076. break;
  2077. case 'authority ignore slashes':
  2078. if ('/' !== c && '\\' !== c) {
  2079. state = 'authority';
  2080. continue;
  2081. } else {
  2082. err('Expected authority, got: ' + c);
  2083. }
  2084. break;
  2085. case 'authority':
  2086. if ('@' === c) {
  2087. if (seenAt) {
  2088. err('@ already seen.');
  2089. buffer += '%40';
  2090. }
  2091. seenAt = true;
  2092. for (var i = 0; i < buffer.length; i++) {
  2093. var cp = buffer[i];
  2094. if ('\t' === cp || '\n' === cp || '\r' === cp) {
  2095. err('Invalid whitespace in authority.');
  2096. continue;
  2097. }
  2098. // XXX check URL code points
  2099. if (':' === cp && null === this._password) {
  2100. this._password = '';
  2101. continue;
  2102. }
  2103. var tempC = percentEscape(cp);
  2104. if (null !== this._password) {
  2105. this._password += tempC;
  2106. } else {
  2107. this._username += tempC;
  2108. }
  2109. }
  2110. buffer = '';
  2111. } else if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c) {
  2112. cursor -= buffer.length;
  2113. buffer = '';
  2114. state = 'host';
  2115. continue;
  2116. } else {
  2117. buffer += c;
  2118. }
  2119. break;
  2120. case 'file host':
  2121. if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c) {
  2122. if (buffer.length === 2 && ALPHA.test(buffer[0]) && (buffer[1] === ':' || buffer[1] === '|')) {
  2123. state = 'relative path';
  2124. } else if (buffer.length === 0) {
  2125. state = 'relative path start';
  2126. } else {
  2127. this._host = IDNAToASCII.call(this, buffer);
  2128. buffer = '';
  2129. state = 'relative path start';
  2130. }
  2131. continue;
  2132. } else if ('\t' === c || '\n' === c || '\r' === c) {
  2133. err('Invalid whitespace in file host.');
  2134. } else {
  2135. buffer += c;
  2136. }
  2137. break;
  2138. case 'host':
  2139. case 'hostname':
  2140. if (':' === c && !seenBracket) {
  2141. // XXX host parsing
  2142. this._host = IDNAToASCII.call(this, buffer);
  2143. buffer = '';
  2144. state = 'port';
  2145. if ('hostname' === stateOverride) {
  2146. break loop;
  2147. }
  2148. } else if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c) {
  2149. this._host = IDNAToASCII.call(this, buffer);
  2150. buffer = '';
  2151. state = 'relative path start';
  2152. if (stateOverride) {
  2153. break loop;
  2154. }
  2155. continue;
  2156. } else if ('\t' !== c && '\n' !== c && '\r' !== c) {
  2157. if ('[' === c) {
  2158. seenBracket = true;
  2159. } else if (']' === c) {
  2160. seenBracket = false;
  2161. }
  2162. buffer += c;
  2163. } else {
  2164. err('Invalid code point in host/hostname: ' + c);
  2165. }
  2166. break;
  2167. case 'port':
  2168. if (/[0-9]/.test(c)) {
  2169. buffer += c;
  2170. } else if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c || stateOverride) {
  2171. if ('' !== buffer) {
  2172. var temp = parseInt(buffer, 10);
  2173. if (temp !== relative[this._scheme]) {
  2174. this._port = temp + '';
  2175. }
  2176. buffer = '';
  2177. }
  2178. if (stateOverride) {
  2179. break loop;
  2180. }
  2181. state = 'relative path start';
  2182. continue;
  2183. } else if ('\t' === c || '\n' === c || '\r' === c) {
  2184. err('Invalid code point in port: ' + c);
  2185. } else {
  2186. invalid.call(this);
  2187. }
  2188. break;
  2189. case 'relative path start':
  2190. if ('\\' === c) {
  2191. err('\'\\\' not allowed in path.');
  2192. }
  2193. state = 'relative path';
  2194. if ('/' !== c && '\\' !== c) {
  2195. continue;
  2196. }
  2197. break;
  2198. case 'relative path':
  2199. if (EOF === c || '/' === c || '\\' === c || !stateOverride && ('?' === c || '#' === c)) {
  2200. if ('\\' === c) {
  2201. err('\\ not allowed in relative path.');
  2202. }
  2203. var tmp;
  2204. if (tmp = relativePathDotMapping[buffer.toLowerCase()]) {
  2205. buffer = tmp;
  2206. }
  2207. if ('..' === buffer) {
  2208. this._path.pop();
  2209. if ('/' !== c && '\\' !== c) {
  2210. this._path.push('');
  2211. }
  2212. } else if ('.' === buffer && '/' !== c && '\\' !== c) {
  2213. this._path.push('');
  2214. } else if ('.' !== buffer) {
  2215. if ('file' === this._scheme && this._path.length === 0 && buffer.length === 2 && ALPHA.test(buffer[0]) && buffer[1] === '|') {
  2216. buffer = buffer[0] + ':';
  2217. }
  2218. this._path.push(buffer);
  2219. }
  2220. buffer = '';
  2221. if ('?' === c) {
  2222. this._query = '?';
  2223. state = 'query';
  2224. } else if ('#' === c) {
  2225. this._fragment = '#';
  2226. state = 'fragment';
  2227. }
  2228. } else if ('\t' !== c && '\n' !== c && '\r' !== c) {
  2229. buffer += percentEscape(c);
  2230. }
  2231. break;
  2232. case 'query':
  2233. if (!stateOverride && '#' === c) {
  2234. this._fragment = '#';
  2235. state = 'fragment';
  2236. } else if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  2237. this._query += percentEscapeQuery(c);
  2238. }
  2239. break;
  2240. case 'fragment':
  2241. if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) {
  2242. this._fragment += c;
  2243. }
  2244. break;
  2245. }
  2246. cursor++;
  2247. }
  2248. }
  2249. function clear() {
  2250. this._scheme = '';
  2251. this._schemeData = '';
  2252. this._username = '';
  2253. this._password = null;
  2254. this._host = '';
  2255. this._port = '';
  2256. this._path = [];
  2257. this._query = '';
  2258. this._fragment = '';
  2259. this._isInvalid = false;
  2260. this._isRelative = false;
  2261. }
  2262. // Does not process domain names or IP addresses.
  2263. // Does not handle encoding for the query parameter.
  2264. function JURL(url, base)
  2265. /* , encoding */
  2266. {
  2267. if (base !== undefined && !(base instanceof JURL)) {
  2268. base = new JURL(String(base));
  2269. }
  2270. this._url = url;
  2271. clear.call(this);
  2272. var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, '');
  2273. // encoding = encoding || 'utf-8'
  2274. parse.call(this, input, null, base);
  2275. }
  2276. JURL.prototype = {
  2277. toString: function () {
  2278. return this.href;
  2279. },
  2280. get href() {
  2281. if (this._isInvalid) {
  2282. return this._url;
  2283. }
  2284. var authority = '';
  2285. if ('' !== this._username || null !== this._password) {
  2286. authority = this._username + (null !== this._password ? ':' + this._password : '') + '@';
  2287. }
  2288. return this.protocol + (this._isRelative ? '//' + authority + this.host : '') + this.pathname + this._query + this._fragment;
  2289. },
  2290. set href(href) {
  2291. clear.call(this);
  2292. parse.call(this, href);
  2293. },
  2294. get protocol() {
  2295. return this._scheme + ':';
  2296. },
  2297. set protocol(protocol) {
  2298. if (this._isInvalid) {
  2299. return;
  2300. }
  2301. parse.call(this, protocol + ':', 'scheme start');
  2302. },
  2303. get host() {
  2304. return this._isInvalid ? '' : this._port ? this._host + ':' + this._port : this._host;
  2305. },
  2306. set host(host) {
  2307. if (this._isInvalid || !this._isRelative) {
  2308. return;
  2309. }
  2310. parse.call(this, host, 'host');
  2311. },
  2312. get hostname() {
  2313. return this._host;
  2314. },
  2315. set hostname(hostname) {
  2316. if (this._isInvalid || !this._isRelative) {
  2317. return;
  2318. }
  2319. parse.call(this, hostname, 'hostname');
  2320. },
  2321. get port() {
  2322. return this._port;
  2323. },
  2324. set port(port) {
  2325. if (this._isInvalid || !this._isRelative) {
  2326. return;
  2327. }
  2328. parse.call(this, port, 'port');
  2329. },
  2330. get pathname() {
  2331. return this._isInvalid ? '' : this._isRelative ? '/' + this._path.join('/') : this._schemeData;
  2332. },
  2333. set pathname(pathname) {
  2334. if (this._isInvalid || !this._isRelative) {
  2335. return;
  2336. }
  2337. this._path = [];
  2338. parse.call(this, pathname, 'relative path start');
  2339. },
  2340. get search() {
  2341. return this._isInvalid || !this._query || '?' === this._query ? '' : this._query;
  2342. },
  2343. set search(search) {
  2344. if (this._isInvalid || !this._isRelative) {
  2345. return;
  2346. }
  2347. this._query = '?';
  2348. if ('?' === search[0]) {
  2349. search = search.slice(1);
  2350. }
  2351. parse.call(this, search, 'query');
  2352. },
  2353. get hash() {
  2354. return this._isInvalid || !this._fragment || '#' === this._fragment ? '' : this._fragment;
  2355. },
  2356. set hash(hash) {
  2357. if (this._isInvalid) {
  2358. return;
  2359. }
  2360. this._fragment = '#';
  2361. if ('#' === hash[0]) {
  2362. hash = hash.slice(1);
  2363. }
  2364. parse.call(this, hash, 'fragment');
  2365. },
  2366. get origin() {
  2367. var host;
  2368. if (this._isInvalid || !this._scheme) {
  2369. return '';
  2370. }
  2371. // javascript: Gecko returns String(""), WebKit/Blink String("null")
  2372. // Gecko throws error for "data://"
  2373. // data: Gecko returns "", Blink returns "data://", WebKit returns "null"
  2374. // Gecko returns String("") for file: mailto:
  2375. // WebKit/Blink returns String("SCHEME://") for file: mailto:
  2376. switch (this._scheme) {
  2377. case 'data':
  2378. case 'file':
  2379. case 'javascript':
  2380. case 'mailto':
  2381. return 'null';
  2382. }
  2383. host = this.host;
  2384. if (!host) {
  2385. return '';
  2386. }
  2387. return this._scheme + '://' + host;
  2388. }
  2389. };
  2390. // Copy over the static methods
  2391. var OriginalURL = scope.URL;
  2392. if (OriginalURL) {
  2393. JURL.createObjectURL = function (blob) {
  2394. // IE extension allows a second optional options argument.
  2395. // http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx
  2396. return OriginalURL.createObjectURL.apply(OriginalURL, arguments);
  2397. };
  2398. JURL.revokeObjectURL = function (url) {
  2399. OriginalURL.revokeObjectURL(url);
  2400. };
  2401. }
  2402. scope.URL = JURL;
  2403. }(globalScope));
  2404. exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
  2405. exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
  2406. exports.OPS = OPS;
  2407. exports.VERBOSITY_LEVELS = VERBOSITY_LEVELS;
  2408. exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
  2409. exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
  2410. exports.AnnotationFieldFlag = AnnotationFieldFlag;
  2411. exports.AnnotationFlag = AnnotationFlag;
  2412. exports.AnnotationType = AnnotationType;
  2413. exports.FontType = FontType;
  2414. exports.ImageKind = ImageKind;
  2415. exports.InvalidPDFException = InvalidPDFException;
  2416. exports.MessageHandler = MessageHandler;
  2417. exports.MissingDataException = MissingDataException;
  2418. exports.MissingPDFException = MissingPDFException;
  2419. exports.NotImplementedException = NotImplementedException;
  2420. exports.PageViewport = PageViewport;
  2421. exports.PasswordException = PasswordException;
  2422. exports.PasswordResponses = PasswordResponses;
  2423. exports.StatTimer = StatTimer;
  2424. exports.StreamType = StreamType;
  2425. exports.TextRenderingMode = TextRenderingMode;
  2426. exports.UnexpectedResponseException = UnexpectedResponseException;
  2427. exports.UnknownErrorException = UnknownErrorException;
  2428. exports.Util = Util;
  2429. exports.XRefParseException = XRefParseException;
  2430. exports.arrayByteLength = arrayByteLength;
  2431. exports.arraysToBytes = arraysToBytes;
  2432. exports.assert = assert;
  2433. exports.bytesToString = bytesToString;
  2434. exports.createBlob = createBlob;
  2435. exports.createPromiseCapability = createPromiseCapability;
  2436. exports.createObjectURL = createObjectURL;
  2437. exports.deprecated = deprecated;
  2438. exports.error = error;
  2439. exports.getLookupTableFactory = getLookupTableFactory;
  2440. exports.getVerbosityLevel = getVerbosityLevel;
  2441. exports.globalScope = globalScope;
  2442. exports.info = info;
  2443. exports.isArray = isArray;
  2444. exports.isArrayBuffer = isArrayBuffer;
  2445. exports.isBool = isBool;
  2446. exports.isEmptyObj = isEmptyObj;
  2447. exports.isInt = isInt;
  2448. exports.isNum = isNum;
  2449. exports.isString = isString;
  2450. exports.isSpace = isSpace;
  2451. exports.isSameOrigin = isSameOrigin;
  2452. exports.isValidUrl = isValidUrl;
  2453. exports.isLittleEndian = isLittleEndian;
  2454. exports.isEvalSupported = isEvalSupported;
  2455. exports.loadJpegStream = loadJpegStream;
  2456. exports.log2 = log2;
  2457. exports.readInt8 = readInt8;
  2458. exports.readUint16 = readUint16;
  2459. exports.readUint32 = readUint32;
  2460. exports.removeNullCharacters = removeNullCharacters;
  2461. exports.setVerbosityLevel = setVerbosityLevel;
  2462. exports.shadow = shadow;
  2463. exports.string32 = string32;
  2464. exports.stringToBytes = stringToBytes;
  2465. exports.stringToPDFString = stringToPDFString;
  2466. exports.stringToUTF8String = stringToUTF8String;
  2467. exports.utf8StringToString = utf8StringToString;
  2468. exports.warn = warn;
  2469. }));
  2470. (function (root, factory) {
  2471. factory(root.pdfjsDisplayDOMUtils = {}, root.pdfjsSharedUtil);
  2472. }(this, function (exports, sharedUtil) {
  2473. var removeNullCharacters = sharedUtil.removeNullCharacters;
  2474. var warn = sharedUtil.warn;
  2475. /**
  2476. * Optimised CSS custom property getter/setter.
  2477. * @class
  2478. */
  2479. var CustomStyle = function CustomStyleClosure() {
  2480. // As noted on: http://www.zachstronaut.com/posts/2009/02/17/
  2481. // animate-css-transforms-firefox-webkit.html
  2482. // in some versions of IE9 it is critical that ms appear in this list
  2483. // before Moz
  2484. var prefixes = [
  2485. 'ms',
  2486. 'Moz',
  2487. 'Webkit',
  2488. 'O'
  2489. ];
  2490. var _cache = Object.create(null);
  2491. function CustomStyle() {
  2492. }
  2493. CustomStyle.getProp = function get(propName, element) {
  2494. // check cache only when no element is given
  2495. if (arguments.length === 1 && typeof _cache[propName] === 'string') {
  2496. return _cache[propName];
  2497. }
  2498. element = element || document.documentElement;
  2499. var style = element.style, prefixed, uPropName;
  2500. // test standard property first
  2501. if (typeof style[propName] === 'string') {
  2502. return _cache[propName] = propName;
  2503. }
  2504. // capitalize
  2505. uPropName = propName.charAt(0).toUpperCase() + propName.slice(1);
  2506. // test vendor specific properties
  2507. for (var i = 0, l = prefixes.length; i < l; i++) {
  2508. prefixed = prefixes[i] + uPropName;
  2509. if (typeof style[prefixed] === 'string') {
  2510. return _cache[propName] = prefixed;
  2511. }
  2512. }
  2513. //if all fails then set to undefined
  2514. return _cache[propName] = 'undefined';
  2515. };
  2516. CustomStyle.setProp = function set(propName, element, str) {
  2517. var prop = this.getProp(propName);
  2518. if (prop !== 'undefined') {
  2519. element.style[prop] = str;
  2520. }
  2521. };
  2522. return CustomStyle;
  2523. }();
  2524. var hasCanvasTypedArrays;
  2525. hasCanvasTypedArrays = function hasCanvasTypedArrays() {
  2526. var canvas = document.createElement('canvas');
  2527. canvas.width = canvas.height = 1;
  2528. var ctx = canvas.getContext('2d');
  2529. var imageData = ctx.createImageData(1, 1);
  2530. return typeof imageData.data.buffer !== 'undefined';
  2531. };
  2532. var LinkTarget = {
  2533. NONE: 0,
  2534. // Default value.
  2535. SELF: 1,
  2536. BLANK: 2,
  2537. PARENT: 3,
  2538. TOP: 4
  2539. };
  2540. var LinkTargetStringMap = [
  2541. '',
  2542. '_self',
  2543. '_blank',
  2544. '_parent',
  2545. '_top'
  2546. ];
  2547. /**
  2548. * @typedef ExternalLinkParameters
  2549. * @typedef {Object} ExternalLinkParameters
  2550. * @property {string} url - An absolute URL.
  2551. * @property {LinkTarget} target - The link target.
  2552. * @property {string} rel - The link relationship.
  2553. */
  2554. /**
  2555. * Adds various attributes (href, title, target, rel) to hyperlinks.
  2556. * @param {HTMLLinkElement} link - The link element.
  2557. * @param {ExternalLinkParameters} params
  2558. */
  2559. function addLinkAttributes(link, params) {
  2560. var url = params && params.url;
  2561. link.href = link.title = url ? removeNullCharacters(url) : '';
  2562. if (url) {
  2563. var target = params.target;
  2564. if (typeof target === 'undefined') {
  2565. target = getDefaultSetting('externalLinkTarget');
  2566. }
  2567. link.target = LinkTargetStringMap[target];
  2568. var rel = params.rel;
  2569. if (typeof rel === 'undefined') {
  2570. rel = getDefaultSetting('externalLinkRel');
  2571. }
  2572. link.rel = rel;
  2573. }
  2574. }
  2575. // Gets the file name from a given URL.
  2576. function getFilenameFromUrl(url) {
  2577. var anchor = url.indexOf('#');
  2578. var query = url.indexOf('?');
  2579. var end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
  2580. return url.substring(url.lastIndexOf('/', end) + 1, end);
  2581. }
  2582. function getDefaultSetting(id) {
  2583. // The list of the settings and their default is maintained for backward
  2584. // compatibility and shall not be extended or modified. See also global.js.
  2585. var globalSettings = sharedUtil.globalScope.PDFJS;
  2586. switch (id) {
  2587. case 'pdfBug':
  2588. return globalSettings ? globalSettings.pdfBug : false;
  2589. case 'disableAutoFetch':
  2590. return globalSettings ? globalSettings.disableAutoFetch : false;
  2591. case 'disableStream':
  2592. return globalSettings ? globalSettings.disableStream : false;
  2593. case 'disableRange':
  2594. return globalSettings ? globalSettings.disableRange : false;
  2595. case 'disableFontFace':
  2596. return globalSettings ? globalSettings.disableFontFace : false;
  2597. case 'disableCreateObjectURL':
  2598. return globalSettings ? globalSettings.disableCreateObjectURL : false;
  2599. case 'disableWebGL':
  2600. return globalSettings ? globalSettings.disableWebGL : true;
  2601. case 'cMapUrl':
  2602. return globalSettings ? globalSettings.cMapUrl : null;
  2603. case 'cMapPacked':
  2604. return globalSettings ? globalSettings.cMapPacked : false;
  2605. case 'postMessageTransfers':
  2606. return globalSettings ? globalSettings.postMessageTransfers : true;
  2607. case 'workerSrc':
  2608. return globalSettings ? globalSettings.workerSrc : null;
  2609. case 'disableWorker':
  2610. return globalSettings ? globalSettings.disableWorker : false;
  2611. case 'maxImageSize':
  2612. return globalSettings ? globalSettings.maxImageSize : -1;
  2613. case 'imageResourcesPath':
  2614. return globalSettings ? globalSettings.imageResourcesPath : '';
  2615. case 'isEvalSupported':
  2616. return globalSettings ? globalSettings.isEvalSupported : true;
  2617. case 'externalLinkTarget':
  2618. if (!globalSettings) {
  2619. return LinkTarget.NONE;
  2620. }
  2621. switch (globalSettings.externalLinkTarget) {
  2622. case LinkTarget.NONE:
  2623. case LinkTarget.SELF:
  2624. case LinkTarget.BLANK:
  2625. case LinkTarget.PARENT:
  2626. case LinkTarget.TOP:
  2627. return globalSettings.externalLinkTarget;
  2628. }
  2629. warn('PDFJS.externalLinkTarget is invalid: ' + globalSettings.externalLinkTarget);
  2630. // Reset the external link target, to suppress further warnings.
  2631. globalSettings.externalLinkTarget = LinkTarget.NONE;
  2632. return LinkTarget.NONE;
  2633. case 'externalLinkRel':
  2634. return globalSettings ? globalSettings.externalLinkRel : 'noreferrer';
  2635. case 'enableStats':
  2636. return !!(globalSettings && globalSettings.enableStats);
  2637. default:
  2638. throw new Error('Unknown default setting: ' + id);
  2639. }
  2640. }
  2641. function isExternalLinkTargetSet() {
  2642. var externalLinkTarget = getDefaultSetting('externalLinkTarget');
  2643. switch (externalLinkTarget) {
  2644. case LinkTarget.NONE:
  2645. return false;
  2646. case LinkTarget.SELF:
  2647. case LinkTarget.BLANK:
  2648. case LinkTarget.PARENT:
  2649. case LinkTarget.TOP:
  2650. return true;
  2651. }
  2652. }
  2653. exports.CustomStyle = CustomStyle;
  2654. exports.addLinkAttributes = addLinkAttributes;
  2655. exports.isExternalLinkTargetSet = isExternalLinkTargetSet;
  2656. exports.getFilenameFromUrl = getFilenameFromUrl;
  2657. exports.LinkTarget = LinkTarget;
  2658. exports.hasCanvasTypedArrays = hasCanvasTypedArrays;
  2659. exports.getDefaultSetting = getDefaultSetting;
  2660. }));
  2661. (function (root, factory) {
  2662. factory(root.pdfjsDisplayFontLoader = {}, root.pdfjsSharedUtil);
  2663. }(this, function (exports, sharedUtil) {
  2664. var assert = sharedUtil.assert;
  2665. var bytesToString = sharedUtil.bytesToString;
  2666. var string32 = sharedUtil.string32;
  2667. var shadow = sharedUtil.shadow;
  2668. var warn = sharedUtil.warn;
  2669. function FontLoader(docId) {
  2670. this.docId = docId;
  2671. this.styleElement = null;
  2672. this.nativeFontFaces = [];
  2673. this.loadTestFontId = 0;
  2674. this.loadingContext = {
  2675. requests: [],
  2676. nextRequestId: 0
  2677. };
  2678. }
  2679. FontLoader.prototype = {
  2680. insertRule: function fontLoaderInsertRule(rule) {
  2681. var styleElement = this.styleElement;
  2682. if (!styleElement) {
  2683. styleElement = this.styleElement = document.createElement('style');
  2684. styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId;
  2685. document.documentElement.getElementsByTagName('head')[0].appendChild(styleElement);
  2686. }
  2687. var styleSheet = styleElement.sheet;
  2688. styleSheet.insertRule(rule, styleSheet.cssRules.length);
  2689. },
  2690. clear: function fontLoaderClear() {
  2691. var styleElement = this.styleElement;
  2692. if (styleElement) {
  2693. styleElement.parentNode.removeChild(styleElement);
  2694. styleElement = this.styleElement = null;
  2695. }
  2696. this.nativeFontFaces.forEach(function (nativeFontFace) {
  2697. document.fonts.delete(nativeFontFace);
  2698. });
  2699. this.nativeFontFaces.length = 0;
  2700. }
  2701. };
  2702. var getLoadTestFont = function () {
  2703. // This is a CFF font with 1 glyph for '.' that fills its entire width and
  2704. // height.
  2705. return atob('T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' + 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' + 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' + 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' + 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' + 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' + 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' + 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' + 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' + 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' + 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' + 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' + 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' + 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' + 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' + 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' + 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' + 'ABAAAAAAAAAAAD6AAAAAAAAA==');
  2706. };
  2707. Object.defineProperty(FontLoader.prototype, 'loadTestFont', {
  2708. get: function () {
  2709. return shadow(this, 'loadTestFont', getLoadTestFont());
  2710. },
  2711. configurable: true
  2712. });
  2713. FontLoader.prototype.addNativeFontFace = function fontLoader_addNativeFontFace(nativeFontFace) {
  2714. this.nativeFontFaces.push(nativeFontFace);
  2715. document.fonts.add(nativeFontFace);
  2716. };
  2717. FontLoader.prototype.bind = function fontLoaderBind(fonts, callback) {
  2718. var rules = [];
  2719. var fontsToLoad = [];
  2720. var fontLoadPromises = [];
  2721. var getNativeFontPromise = function (nativeFontFace) {
  2722. // Return a promise that is always fulfilled, even when the font fails to
  2723. // load.
  2724. return nativeFontFace.loaded.catch(function (e) {
  2725. warn('Failed to load font "' + nativeFontFace.family + '": ' + e);
  2726. });
  2727. };
  2728. // Firefox Font Loading API does not work with mozPrintCallback --
  2729. // disabling it in this case.
  2730. var isFontLoadingAPISupported = FontLoader.isFontLoadingAPISupported && !FontLoader.isSyncFontLoadingSupported;
  2731. for (var i = 0, ii = fonts.length; i < ii; i++) {
  2732. var font = fonts[i];
  2733. // Add the font to the DOM only once or skip if the font
  2734. // is already loaded.
  2735. if (font.attached || font.loading === false) {
  2736. continue;
  2737. }
  2738. font.attached = true;
  2739. if (isFontLoadingAPISupported) {
  2740. var nativeFontFace = font.createNativeFontFace();
  2741. if (nativeFontFace) {
  2742. this.addNativeFontFace(nativeFontFace);
  2743. fontLoadPromises.push(getNativeFontPromise(nativeFontFace));
  2744. }
  2745. } else {
  2746. var rule = font.createFontFaceRule();
  2747. if (rule) {
  2748. this.insertRule(rule);
  2749. rules.push(rule);
  2750. fontsToLoad.push(font);
  2751. }
  2752. }
  2753. }
  2754. var request = this.queueLoadingCallback(callback);
  2755. if (isFontLoadingAPISupported) {
  2756. Promise.all(fontLoadPromises).then(function () {
  2757. request.complete();
  2758. });
  2759. } else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) {
  2760. this.prepareFontLoadEvent(rules, fontsToLoad, request);
  2761. } else {
  2762. request.complete();
  2763. }
  2764. };
  2765. FontLoader.prototype.queueLoadingCallback = function FontLoader_queueLoadingCallback(callback) {
  2766. function LoadLoader_completeRequest() {
  2767. assert(!request.end, 'completeRequest() cannot be called twice');
  2768. request.end = Date.now();
  2769. // sending all completed requests in order how they were queued
  2770. while (context.requests.length > 0 && context.requests[0].end) {
  2771. var otherRequest = context.requests.shift();
  2772. setTimeout(otherRequest.callback, 0);
  2773. }
  2774. }
  2775. var context = this.loadingContext;
  2776. var requestId = 'pdfjs-font-loading-' + context.nextRequestId++;
  2777. var request = {
  2778. id: requestId,
  2779. complete: LoadLoader_completeRequest,
  2780. callback: callback,
  2781. started: Date.now()
  2782. };
  2783. context.requests.push(request);
  2784. return request;
  2785. };
  2786. FontLoader.prototype.prepareFontLoadEvent = function fontLoaderPrepareFontLoadEvent(rules, fonts, request) {
  2787. /** Hack begin */
  2788. // There's currently no event when a font has finished downloading so the
  2789. // following code is a dirty hack to 'guess' when a font is
  2790. // ready. It's assumed fonts are loaded in order, so add a known test
  2791. // font after the desired fonts and then test for the loading of that
  2792. // test font.
  2793. function int32(data, offset) {
  2794. return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
  2795. }
  2796. function spliceString(s, offset, remove, insert) {
  2797. var chunk1 = s.substr(0, offset);
  2798. var chunk2 = s.substr(offset + remove);
  2799. return chunk1 + insert + chunk2;
  2800. }
  2801. var i, ii;
  2802. var canvas = document.createElement('canvas');
  2803. canvas.width = 1;
  2804. canvas.height = 1;
  2805. var ctx = canvas.getContext('2d');
  2806. var called = 0;
  2807. function isFontReady(name, callback) {
  2808. called++;
  2809. // With setTimeout clamping this gives the font ~100ms to load.
  2810. if (called > 30) {
  2811. warn('Load test font never loaded.');
  2812. callback();
  2813. return;
  2814. }
  2815. ctx.font = '30px ' + name;
  2816. ctx.fillText('.', 0, 20);
  2817. var imageData = ctx.getImageData(0, 0, 1, 1);
  2818. if (imageData.data[3] > 0) {
  2819. callback();
  2820. return;
  2821. }
  2822. setTimeout(isFontReady.bind(null, name, callback));
  2823. }
  2824. var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++;
  2825. // Chromium seems to cache fonts based on a hash of the actual font data,
  2826. // so the font must be modified for each load test else it will appear to
  2827. // be loaded already.
  2828. // TODO: This could maybe be made faster by avoiding the btoa of the full
  2829. // font by splitting it in chunks before hand and padding the font id.
  2830. var data = this.loadTestFont;
  2831. var COMMENT_OFFSET = 976;
  2832. // has to be on 4 byte boundary (for checksum)
  2833. data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
  2834. // CFF checksum is important for IE, adjusting it
  2835. var CFF_CHECKSUM_OFFSET = 16;
  2836. var XXXX_VALUE = 0x58585858;
  2837. // the "comment" filled with 'X'
  2838. var checksum = int32(data, CFF_CHECKSUM_OFFSET);
  2839. for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
  2840. checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
  2841. }
  2842. if (i < loadTestFontId.length) {
  2843. // align to 4 bytes boundary
  2844. checksum = checksum - XXXX_VALUE + int32(loadTestFontId + 'XXX', i) | 0;
  2845. }
  2846. data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum));
  2847. var url = 'url(data:font/opentype;base64,' + btoa(data) + ');';
  2848. var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' + url + '}';
  2849. this.insertRule(rule);
  2850. var names = [];
  2851. for (i = 0, ii = fonts.length; i < ii; i++) {
  2852. names.push(fonts[i].loadedName);
  2853. }
  2854. names.push(loadTestFontId);
  2855. var div = document.createElement('div');
  2856. div.setAttribute('style', 'visibility: hidden;' + 'width: 10px; height: 10px;' + 'position: absolute; top: 0px; left: 0px;');
  2857. for (i = 0, ii = names.length; i < ii; ++i) {
  2858. var span = document.createElement('span');
  2859. span.textContent = 'Hi';
  2860. span.style.fontFamily = names[i];
  2861. div.appendChild(span);
  2862. }
  2863. document.body.appendChild(div);
  2864. isFontReady(loadTestFontId, function () {
  2865. document.body.removeChild(div);
  2866. request.complete();
  2867. });
  2868. };
  2869. FontLoader.isFontLoadingAPISupported = typeof document !== 'undefined' && !!document.fonts;
  2870. var isSyncFontLoadingSupported = function isSyncFontLoadingSupported() {
  2871. if (typeof navigator === 'undefined') {
  2872. // node.js - we can pretend sync font loading is supported.
  2873. return true;
  2874. }
  2875. var supported = false;
  2876. // User agent string sniffing is bad, but there is no reliable way to tell
  2877. // if font is fully loaded and ready to be used with canvas.
  2878. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
  2879. if (m && m[1] >= 14) {
  2880. supported = true;
  2881. }
  2882. // TODO other browsers
  2883. return supported;
  2884. };
  2885. Object.defineProperty(FontLoader, 'isSyncFontLoadingSupported', {
  2886. get: function () {
  2887. return shadow(FontLoader, 'isSyncFontLoadingSupported', isSyncFontLoadingSupported());
  2888. },
  2889. enumerable: true,
  2890. configurable: true
  2891. });
  2892. var IsEvalSupportedCached = {
  2893. get value() {
  2894. return shadow(this, 'value', sharedUtil.isEvalSupported());
  2895. }
  2896. };
  2897. var FontFaceObject = function FontFaceObjectClosure() {
  2898. function FontFaceObject(translatedData, options) {
  2899. this.compiledGlyphs = Object.create(null);
  2900. // importing translated data
  2901. for (var i in translatedData) {
  2902. this[i] = translatedData[i];
  2903. }
  2904. this.options = options;
  2905. }
  2906. FontFaceObject.prototype = {
  2907. createNativeFontFace: function FontFaceObject_createNativeFontFace() {
  2908. if (!this.data) {
  2909. return null;
  2910. }
  2911. if (this.options.disableFontFace) {
  2912. this.disableFontFace = true;
  2913. return null;
  2914. }
  2915. var nativeFontFace = new FontFace(this.loadedName, this.data, {});
  2916. if (this.options.fontRegistry) {
  2917. this.options.fontRegistry.registerFont(this);
  2918. }
  2919. return nativeFontFace;
  2920. },
  2921. createFontFaceRule: function FontFaceObject_createFontFaceRule() {
  2922. if (!this.data) {
  2923. return null;
  2924. }
  2925. if (this.options.disableFontFace) {
  2926. this.disableFontFace = true;
  2927. return null;
  2928. }
  2929. var data = bytesToString(new Uint8Array(this.data));
  2930. var fontName = this.loadedName;
  2931. // Add the font-face rule to the document
  2932. var url = 'url(data:' + this.mimetype + ';base64,' + btoa(data) + ');';
  2933. var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}';
  2934. if (this.options.fontRegistry) {
  2935. this.options.fontRegistry.registerFont(this, url);
  2936. }
  2937. return rule;
  2938. },
  2939. getPathGenerator: function FontFaceObject_getPathGenerator(objs, character) {
  2940. if (!(character in this.compiledGlyphs)) {
  2941. var cmds = objs.get(this.loadedName + '_path_' + character);
  2942. var current, i, len;
  2943. // If we can, compile cmds into JS for MAXIMUM SPEED
  2944. if (this.options.isEvalSupported && IsEvalSupportedCached.value) {
  2945. var args, js = '';
  2946. for (i = 0, len = cmds.length; i < len; i++) {
  2947. current = cmds[i];
  2948. if (current.args !== undefined) {
  2949. args = current.args.join(',');
  2950. } else {
  2951. args = '';
  2952. }
  2953. js += 'c.' + current.cmd + '(' + args + ');\n';
  2954. }
  2955. this.compiledGlyphs[character] = new Function('c', 'size', js);
  2956. } else {
  2957. // But fall back on using Function.prototype.apply() if we're
  2958. // blocked from using eval() for whatever reason (like CSP policies)
  2959. this.compiledGlyphs[character] = function (c, size) {
  2960. for (i = 0, len = cmds.length; i < len; i++) {
  2961. current = cmds[i];
  2962. if (current.cmd === 'scale') {
  2963. current.args = [
  2964. size,
  2965. -size
  2966. ];
  2967. }
  2968. c[current.cmd].apply(c, current.args);
  2969. }
  2970. };
  2971. }
  2972. }
  2973. return this.compiledGlyphs[character];
  2974. }
  2975. };
  2976. return FontFaceObject;
  2977. }();
  2978. exports.FontFaceObject = FontFaceObject;
  2979. exports.FontLoader = FontLoader;
  2980. }));
  2981. (function (root, factory) {
  2982. factory(root.pdfjsDisplayMetadata = {}, root.pdfjsSharedUtil);
  2983. }(this, function (exports, sharedUtil) {
  2984. var error = sharedUtil.error;
  2985. function fixMetadata(meta) {
  2986. return meta.replace(/>\\376\\377([^<]+)/g, function (all, codes) {
  2987. var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g, function (code, d1, d2, d3) {
  2988. return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1);
  2989. });
  2990. var chars = '';
  2991. for (var i = 0; i < bytes.length; i += 2) {
  2992. var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1);
  2993. chars += code >= 32 && code < 127 && code !== 60 && code !== 62 && code !== 38 && false ? String.fromCharCode(code) : '&#x' + (0x10000 + code).toString(16).substring(1) + ';';
  2994. }
  2995. return '>' + chars;
  2996. });
  2997. }
  2998. function Metadata(meta) {
  2999. if (typeof meta === 'string') {
  3000. // Ghostscript produces invalid metadata
  3001. meta = fixMetadata(meta);
  3002. var parser = new DOMParser();
  3003. meta = parser.parseFromString(meta, 'application/xml');
  3004. } else if (!(meta instanceof Document)) {
  3005. error('Metadata: Invalid metadata object');
  3006. }
  3007. this.metaDocument = meta;
  3008. this.metadata = Object.create(null);
  3009. this.parse();
  3010. }
  3011. Metadata.prototype = {
  3012. parse: function Metadata_parse() {
  3013. var doc = this.metaDocument;
  3014. var rdf = doc.documentElement;
  3015. if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  3016. // Wrapped in <xmpmeta>
  3017. rdf = rdf.firstChild;
  3018. while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') {
  3019. rdf = rdf.nextSibling;
  3020. }
  3021. }
  3022. var nodeName = rdf ? rdf.nodeName.toLowerCase() : null;
  3023. if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) {
  3024. return;
  3025. }
  3026. var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength;
  3027. for (i = 0, length = children.length; i < length; i++) {
  3028. desc = children[i];
  3029. if (desc.nodeName.toLowerCase() !== 'rdf:description') {
  3030. continue;
  3031. }
  3032. for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) {
  3033. if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') {
  3034. entry = desc.childNodes[ii];
  3035. name = entry.nodeName.toLowerCase();
  3036. this.metadata[name] = entry.textContent.trim();
  3037. }
  3038. }
  3039. }
  3040. },
  3041. get: function Metadata_get(name) {
  3042. return this.metadata[name] || null;
  3043. },
  3044. has: function Metadata_has(name) {
  3045. return typeof this.metadata[name] !== 'undefined';
  3046. }
  3047. };
  3048. exports.Metadata = Metadata;
  3049. }));
  3050. (function (root, factory) {
  3051. factory(root.pdfjsDisplaySVG = {}, root.pdfjsSharedUtil);
  3052. }(this, function (exports, sharedUtil) {
  3053. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  3054. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  3055. var ImageKind = sharedUtil.ImageKind;
  3056. var OPS = sharedUtil.OPS;
  3057. var Util = sharedUtil.Util;
  3058. var isNum = sharedUtil.isNum;
  3059. var isArray = sharedUtil.isArray;
  3060. var warn = sharedUtil.warn;
  3061. var createObjectURL = sharedUtil.createObjectURL;
  3062. var SVG_DEFAULTS = {
  3063. fontStyle: 'normal',
  3064. fontWeight: 'normal',
  3065. fillColor: '#000000'
  3066. };
  3067. var convertImgDataToPng = function convertImgDataToPngClosure() {
  3068. var PNG_HEADER = new Uint8Array([
  3069. 0x89,
  3070. 0x50,
  3071. 0x4e,
  3072. 0x47,
  3073. 0x0d,
  3074. 0x0a,
  3075. 0x1a,
  3076. 0x0a
  3077. ]);
  3078. var CHUNK_WRAPPER_SIZE = 12;
  3079. var crcTable = new Int32Array(256);
  3080. for (var i = 0; i < 256; i++) {
  3081. var c = i;
  3082. for (var h = 0; h < 8; h++) {
  3083. if (c & 1) {
  3084. c = 0xedB88320 ^ c >> 1 & 0x7fffffff;
  3085. } else {
  3086. c = c >> 1 & 0x7fffffff;
  3087. }
  3088. }
  3089. crcTable[i] = c;
  3090. }
  3091. function crc32(data, start, end) {
  3092. var crc = -1;
  3093. for (var i = start; i < end; i++) {
  3094. var a = (crc ^ data[i]) & 0xff;
  3095. var b = crcTable[a];
  3096. crc = crc >>> 8 ^ b;
  3097. }
  3098. return crc ^ -1;
  3099. }
  3100. function writePngChunk(type, body, data, offset) {
  3101. var p = offset;
  3102. var len = body.length;
  3103. data[p] = len >> 24 & 0xff;
  3104. data[p + 1] = len >> 16 & 0xff;
  3105. data[p + 2] = len >> 8 & 0xff;
  3106. data[p + 3] = len & 0xff;
  3107. p += 4;
  3108. data[p] = type.charCodeAt(0) & 0xff;
  3109. data[p + 1] = type.charCodeAt(1) & 0xff;
  3110. data[p + 2] = type.charCodeAt(2) & 0xff;
  3111. data[p + 3] = type.charCodeAt(3) & 0xff;
  3112. p += 4;
  3113. data.set(body, p);
  3114. p += body.length;
  3115. var crc = crc32(data, offset + 4, p);
  3116. data[p] = crc >> 24 & 0xff;
  3117. data[p + 1] = crc >> 16 & 0xff;
  3118. data[p + 2] = crc >> 8 & 0xff;
  3119. data[p + 3] = crc & 0xff;
  3120. }
  3121. function adler32(data, start, end) {
  3122. var a = 1;
  3123. var b = 0;
  3124. for (var i = start; i < end; ++i) {
  3125. a = (a + (data[i] & 0xff)) % 65521;
  3126. b = (b + a) % 65521;
  3127. }
  3128. return b << 16 | a;
  3129. }
  3130. function encode(imgData, kind, forceDataSchema) {
  3131. var width = imgData.width;
  3132. var height = imgData.height;
  3133. var bitDepth, colorType, lineSize;
  3134. var bytes = imgData.data;
  3135. switch (kind) {
  3136. case ImageKind.GRAYSCALE_1BPP:
  3137. colorType = 0;
  3138. bitDepth = 1;
  3139. lineSize = width + 7 >> 3;
  3140. break;
  3141. case ImageKind.RGB_24BPP:
  3142. colorType = 2;
  3143. bitDepth = 8;
  3144. lineSize = width * 3;
  3145. break;
  3146. case ImageKind.RGBA_32BPP:
  3147. colorType = 6;
  3148. bitDepth = 8;
  3149. lineSize = width * 4;
  3150. break;
  3151. default:
  3152. throw new Error('invalid format');
  3153. }
  3154. // prefix every row with predictor 0
  3155. var literals = new Uint8Array((1 + lineSize) * height);
  3156. var offsetLiterals = 0, offsetBytes = 0;
  3157. var y, i;
  3158. for (y = 0; y < height; ++y) {
  3159. literals[offsetLiterals++] = 0;
  3160. // no prediction
  3161. literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals);
  3162. offsetBytes += lineSize;
  3163. offsetLiterals += lineSize;
  3164. }
  3165. if (kind === ImageKind.GRAYSCALE_1BPP) {
  3166. // inverting for B/W
  3167. offsetLiterals = 0;
  3168. for (y = 0; y < height; y++) {
  3169. offsetLiterals++;
  3170. // skipping predictor
  3171. for (i = 0; i < lineSize; i++) {
  3172. literals[offsetLiterals++] ^= 0xFF;
  3173. }
  3174. }
  3175. }
  3176. var ihdr = new Uint8Array([
  3177. width >> 24 & 0xff,
  3178. width >> 16 & 0xff,
  3179. width >> 8 & 0xff,
  3180. width & 0xff,
  3181. height >> 24 & 0xff,
  3182. height >> 16 & 0xff,
  3183. height >> 8 & 0xff,
  3184. height & 0xff,
  3185. bitDepth,
  3186. // bit depth
  3187. colorType,
  3188. // color type
  3189. 0x00,
  3190. // compression method
  3191. 0x00,
  3192. // filter method
  3193. 0x00
  3194. ]);
  3195. // interlace method
  3196. var len = literals.length;
  3197. var maxBlockLength = 0xFFFF;
  3198. var deflateBlocks = Math.ceil(len / maxBlockLength);
  3199. var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
  3200. var pi = 0;
  3201. idat[pi++] = 0x78;
  3202. // compression method and flags
  3203. idat[pi++] = 0x9c;
  3204. // flags
  3205. var pos = 0;
  3206. while (len > maxBlockLength) {
  3207. // writing non-final DEFLATE blocks type 0 and length of 65535
  3208. idat[pi++] = 0x00;
  3209. idat[pi++] = 0xff;
  3210. idat[pi++] = 0xff;
  3211. idat[pi++] = 0x00;
  3212. idat[pi++] = 0x00;
  3213. idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
  3214. pi += maxBlockLength;
  3215. pos += maxBlockLength;
  3216. len -= maxBlockLength;
  3217. }
  3218. // writing non-final DEFLATE blocks type 0
  3219. idat[pi++] = 0x01;
  3220. idat[pi++] = len & 0xff;
  3221. idat[pi++] = len >> 8 & 0xff;
  3222. idat[pi++] = ~len & 0xffff & 0xff;
  3223. idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
  3224. idat.set(literals.subarray(pos), pi);
  3225. pi += literals.length - pos;
  3226. var adler = adler32(literals, 0, literals.length);
  3227. // checksum
  3228. idat[pi++] = adler >> 24 & 0xff;
  3229. idat[pi++] = adler >> 16 & 0xff;
  3230. idat[pi++] = adler >> 8 & 0xff;
  3231. idat[pi++] = adler & 0xff;
  3232. // PNG will consists: header, IHDR+data, IDAT+data, and IEND.
  3233. var pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length;
  3234. var data = new Uint8Array(pngLength);
  3235. var offset = 0;
  3236. data.set(PNG_HEADER, offset);
  3237. offset += PNG_HEADER.length;
  3238. writePngChunk('IHDR', ihdr, data, offset);
  3239. offset += CHUNK_WRAPPER_SIZE + ihdr.length;
  3240. writePngChunk('IDATA', idat, data, offset);
  3241. offset += CHUNK_WRAPPER_SIZE + idat.length;
  3242. writePngChunk('IEND', new Uint8Array(0), data, offset);
  3243. return createObjectURL(data, 'image/png', forceDataSchema);
  3244. }
  3245. return function convertImgDataToPng(imgData, forceDataSchema) {
  3246. var kind = imgData.kind === undefined ? ImageKind.GRAYSCALE_1BPP : imgData.kind;
  3247. return encode(imgData, kind, forceDataSchema);
  3248. };
  3249. }();
  3250. var SVGExtraState = function SVGExtraStateClosure() {
  3251. function SVGExtraState() {
  3252. this.fontSizeScale = 1;
  3253. this.fontWeight = SVG_DEFAULTS.fontWeight;
  3254. this.fontSize = 0;
  3255. this.textMatrix = IDENTITY_MATRIX;
  3256. this.fontMatrix = FONT_IDENTITY_MATRIX;
  3257. this.leading = 0;
  3258. // Current point (in user coordinates)
  3259. this.x = 0;
  3260. this.y = 0;
  3261. // Start of text line (in text coordinates)
  3262. this.lineX = 0;
  3263. this.lineY = 0;
  3264. // Character and word spacing
  3265. this.charSpacing = 0;
  3266. this.wordSpacing = 0;
  3267. this.textHScale = 1;
  3268. this.textRise = 0;
  3269. // Default foreground and background colors
  3270. this.fillColor = SVG_DEFAULTS.fillColor;
  3271. this.strokeColor = '#000000';
  3272. this.fillAlpha = 1;
  3273. this.strokeAlpha = 1;
  3274. this.lineWidth = 1;
  3275. this.lineJoin = '';
  3276. this.lineCap = '';
  3277. this.miterLimit = 0;
  3278. this.dashArray = [];
  3279. this.dashPhase = 0;
  3280. this.dependencies = [];
  3281. // Clipping
  3282. this.clipId = '';
  3283. this.pendingClip = false;
  3284. this.maskId = '';
  3285. }
  3286. SVGExtraState.prototype = {
  3287. clone: function SVGExtraState_clone() {
  3288. return Object.create(this);
  3289. },
  3290. setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) {
  3291. this.x = x;
  3292. this.y = y;
  3293. }
  3294. };
  3295. return SVGExtraState;
  3296. }();
  3297. var SVGGraphics = function SVGGraphicsClosure() {
  3298. function createScratchSVG(width, height) {
  3299. var NS = 'http://www.w3.org/2000/svg';
  3300. var svg = document.createElementNS(NS, 'svg:svg');
  3301. svg.setAttributeNS(null, 'version', '1.1');
  3302. svg.setAttributeNS(null, 'width', width + 'px');
  3303. svg.setAttributeNS(null, 'height', height + 'px');
  3304. svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);
  3305. return svg;
  3306. }
  3307. function opListToTree(opList) {
  3308. var opTree = [];
  3309. var tmp = [];
  3310. var opListLen = opList.length;
  3311. for (var x = 0; x < opListLen; x++) {
  3312. if (opList[x].fn === 'save') {
  3313. opTree.push({
  3314. 'fnId': 92,
  3315. 'fn': 'group',
  3316. 'items': []
  3317. });
  3318. tmp.push(opTree);
  3319. opTree = opTree[opTree.length - 1].items;
  3320. continue;
  3321. }
  3322. if (opList[x].fn === 'restore') {
  3323. opTree = tmp.pop();
  3324. } else {
  3325. opTree.push(opList[x]);
  3326. }
  3327. }
  3328. return opTree;
  3329. }
  3330. /**
  3331. * Formats float number.
  3332. * @param value {number} number to format.
  3333. * @returns {string}
  3334. */
  3335. function pf(value) {
  3336. if (value === (value | 0)) {
  3337. // integer number
  3338. return value.toString();
  3339. }
  3340. var s = value.toFixed(10);
  3341. var i = s.length - 1;
  3342. if (s[i] !== '0') {
  3343. return s;
  3344. }
  3345. // removing trailing zeros
  3346. do {
  3347. i--;
  3348. } while (s[i] === '0');
  3349. return s.substr(0, s[i] === '.' ? i : i + 1);
  3350. }
  3351. /**
  3352. * Formats transform matrix. The standard rotation, scale and translate
  3353. * matrices are replaced by their shorter forms, and for identity matrix
  3354. * returns empty string to save the memory.
  3355. * @param m {Array} matrix to format.
  3356. * @returns {string}
  3357. */
  3358. function pm(m) {
  3359. if (m[4] === 0 && m[5] === 0) {
  3360. if (m[1] === 0 && m[2] === 0) {
  3361. if (m[0] === 1 && m[3] === 1) {
  3362. return '';
  3363. }
  3364. return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')';
  3365. }
  3366. if (m[0] === m[3] && m[1] === -m[2]) {
  3367. var a = Math.acos(m[0]) * 180 / Math.PI;
  3368. return 'rotate(' + pf(a) + ')';
  3369. }
  3370. } else {
  3371. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  3372. return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3373. }
  3374. }
  3375. return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' + pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3376. }
  3377. function SVGGraphics(commonObjs, objs, forceDataSchema) {
  3378. this.current = new SVGExtraState();
  3379. this.transformMatrix = IDENTITY_MATRIX;
  3380. // Graphics state matrix
  3381. this.transformStack = [];
  3382. this.extraStack = [];
  3383. this.commonObjs = commonObjs;
  3384. this.objs = objs;
  3385. this.pendingEOFill = false;
  3386. this.embedFonts = false;
  3387. this.embeddedFonts = Object.create(null);
  3388. this.cssStyle = null;
  3389. this.forceDataSchema = !!forceDataSchema;
  3390. }
  3391. var NS = 'http://www.w3.org/2000/svg';
  3392. var XML_NS = 'http://www.w3.org/XML/1998/namespace';
  3393. var XLINK_NS = 'http://www.w3.org/1999/xlink';
  3394. var LINE_CAP_STYLES = [
  3395. 'butt',
  3396. 'round',
  3397. 'square'
  3398. ];
  3399. var LINE_JOIN_STYLES = [
  3400. 'miter',
  3401. 'round',
  3402. 'bevel'
  3403. ];
  3404. var clipCount = 0;
  3405. var maskCount = 0;
  3406. SVGGraphics.prototype = {
  3407. save: function SVGGraphics_save() {
  3408. this.transformStack.push(this.transformMatrix);
  3409. var old = this.current;
  3410. this.extraStack.push(old);
  3411. this.current = old.clone();
  3412. },
  3413. restore: function SVGGraphics_restore() {
  3414. this.transformMatrix = this.transformStack.pop();
  3415. this.current = this.extraStack.pop();
  3416. this.tgrp = document.createElementNS(NS, 'svg:g');
  3417. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3418. this.pgrp.appendChild(this.tgrp);
  3419. },
  3420. group: function SVGGraphics_group(items) {
  3421. this.save();
  3422. this.executeOpTree(items);
  3423. this.restore();
  3424. },
  3425. loadDependencies: function SVGGraphics_loadDependencies(operatorList) {
  3426. var fnArray = operatorList.fnArray;
  3427. var fnArrayLen = fnArray.length;
  3428. var argsArray = operatorList.argsArray;
  3429. var self = this;
  3430. for (var i = 0; i < fnArrayLen; i++) {
  3431. if (OPS.dependency === fnArray[i]) {
  3432. var deps = argsArray[i];
  3433. for (var n = 0, nn = deps.length; n < nn; n++) {
  3434. var obj = deps[n];
  3435. var common = obj.substring(0, 2) === 'g_';
  3436. var promise;
  3437. if (common) {
  3438. promise = new Promise(function (resolve) {
  3439. self.commonObjs.get(obj, resolve);
  3440. });
  3441. } else {
  3442. promise = new Promise(function (resolve) {
  3443. self.objs.get(obj, resolve);
  3444. });
  3445. }
  3446. this.current.dependencies.push(promise);
  3447. }
  3448. }
  3449. }
  3450. return Promise.all(this.current.dependencies);
  3451. },
  3452. transform: function SVGGraphics_transform(a, b, c, d, e, f) {
  3453. var transformMatrix = [
  3454. a,
  3455. b,
  3456. c,
  3457. d,
  3458. e,
  3459. f
  3460. ];
  3461. this.transformMatrix = Util.transform(this.transformMatrix, transformMatrix);
  3462. this.tgrp = document.createElementNS(NS, 'svg:g');
  3463. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3464. },
  3465. getSVG: function SVGGraphics_getSVG(operatorList, viewport) {
  3466. this.svg = createScratchSVG(viewport.width, viewport.height);
  3467. this.viewport = viewport;
  3468. return this.loadDependencies(operatorList).then(function () {
  3469. this.transformMatrix = IDENTITY_MATRIX;
  3470. this.pgrp = document.createElementNS(NS, 'svg:g');
  3471. // Parent group
  3472. this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform));
  3473. this.tgrp = document.createElementNS(NS, 'svg:g');
  3474. // Transform group
  3475. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3476. this.defs = document.createElementNS(NS, 'svg:defs');
  3477. this.pgrp.appendChild(this.defs);
  3478. this.pgrp.appendChild(this.tgrp);
  3479. this.svg.appendChild(this.pgrp);
  3480. var opTree = this.convertOpList(operatorList);
  3481. this.executeOpTree(opTree);
  3482. return this.svg;
  3483. }.bind(this));
  3484. },
  3485. convertOpList: function SVGGraphics_convertOpList(operatorList) {
  3486. var argsArray = operatorList.argsArray;
  3487. var fnArray = operatorList.fnArray;
  3488. var fnArrayLen = fnArray.length;
  3489. var REVOPS = [];
  3490. var opList = [];
  3491. for (var op in OPS) {
  3492. REVOPS[OPS[op]] = op;
  3493. }
  3494. for (var x = 0; x < fnArrayLen; x++) {
  3495. var fnId = fnArray[x];
  3496. opList.push({
  3497. 'fnId': fnId,
  3498. 'fn': REVOPS[fnId],
  3499. 'args': argsArray[x]
  3500. });
  3501. }
  3502. return opListToTree(opList);
  3503. },
  3504. executeOpTree: function SVGGraphics_executeOpTree(opTree) {
  3505. var opTreeLen = opTree.length;
  3506. for (var x = 0; x < opTreeLen; x++) {
  3507. var fn = opTree[x].fn;
  3508. var fnId = opTree[x].fnId;
  3509. var args = opTree[x].args;
  3510. switch (fnId | 0) {
  3511. case OPS.beginText:
  3512. this.beginText();
  3513. break;
  3514. case OPS.setLeading:
  3515. this.setLeading(args);
  3516. break;
  3517. case OPS.setLeadingMoveText:
  3518. this.setLeadingMoveText(args[0], args[1]);
  3519. break;
  3520. case OPS.setFont:
  3521. this.setFont(args);
  3522. break;
  3523. case OPS.showText:
  3524. this.showText(args[0]);
  3525. break;
  3526. case OPS.showSpacedText:
  3527. this.showText(args[0]);
  3528. break;
  3529. case OPS.endText:
  3530. this.endText();
  3531. break;
  3532. case OPS.moveText:
  3533. this.moveText(args[0], args[1]);
  3534. break;
  3535. case OPS.setCharSpacing:
  3536. this.setCharSpacing(args[0]);
  3537. break;
  3538. case OPS.setWordSpacing:
  3539. this.setWordSpacing(args[0]);
  3540. break;
  3541. case OPS.setHScale:
  3542. this.setHScale(args[0]);
  3543. break;
  3544. case OPS.setTextMatrix:
  3545. this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  3546. break;
  3547. case OPS.setLineWidth:
  3548. this.setLineWidth(args[0]);
  3549. break;
  3550. case OPS.setLineJoin:
  3551. this.setLineJoin(args[0]);
  3552. break;
  3553. case OPS.setLineCap:
  3554. this.setLineCap(args[0]);
  3555. break;
  3556. case OPS.setMiterLimit:
  3557. this.setMiterLimit(args[0]);
  3558. break;
  3559. case OPS.setFillRGBColor:
  3560. this.setFillRGBColor(args[0], args[1], args[2]);
  3561. break;
  3562. case OPS.setStrokeRGBColor:
  3563. this.setStrokeRGBColor(args[0], args[1], args[2]);
  3564. break;
  3565. case OPS.setDash:
  3566. this.setDash(args[0], args[1]);
  3567. break;
  3568. case OPS.setGState:
  3569. this.setGState(args[0]);
  3570. break;
  3571. case OPS.fill:
  3572. this.fill();
  3573. break;
  3574. case OPS.eoFill:
  3575. this.eoFill();
  3576. break;
  3577. case OPS.stroke:
  3578. this.stroke();
  3579. break;
  3580. case OPS.fillStroke:
  3581. this.fillStroke();
  3582. break;
  3583. case OPS.eoFillStroke:
  3584. this.eoFillStroke();
  3585. break;
  3586. case OPS.clip:
  3587. this.clip('nonzero');
  3588. break;
  3589. case OPS.eoClip:
  3590. this.clip('evenodd');
  3591. break;
  3592. case OPS.paintSolidColorImageMask:
  3593. this.paintSolidColorImageMask();
  3594. break;
  3595. case OPS.paintJpegXObject:
  3596. this.paintJpegXObject(args[0], args[1], args[2]);
  3597. break;
  3598. case OPS.paintImageXObject:
  3599. this.paintImageXObject(args[0]);
  3600. break;
  3601. case OPS.paintInlineImageXObject:
  3602. this.paintInlineImageXObject(args[0]);
  3603. break;
  3604. case OPS.paintImageMaskXObject:
  3605. this.paintImageMaskXObject(args[0]);
  3606. break;
  3607. case OPS.paintFormXObjectBegin:
  3608. this.paintFormXObjectBegin(args[0], args[1]);
  3609. break;
  3610. case OPS.paintFormXObjectEnd:
  3611. this.paintFormXObjectEnd();
  3612. break;
  3613. case OPS.closePath:
  3614. this.closePath();
  3615. break;
  3616. case OPS.closeStroke:
  3617. this.closeStroke();
  3618. break;
  3619. case OPS.closeFillStroke:
  3620. this.closeFillStroke();
  3621. break;
  3622. case OPS.nextLine:
  3623. this.nextLine();
  3624. break;
  3625. case OPS.transform:
  3626. this.transform(args[0], args[1], args[2], args[3], args[4], args[5]);
  3627. break;
  3628. case OPS.constructPath:
  3629. this.constructPath(args[0], args[1]);
  3630. break;
  3631. case OPS.endPath:
  3632. this.endPath();
  3633. break;
  3634. case 92:
  3635. this.group(opTree[x].items);
  3636. break;
  3637. default:
  3638. warn('Unimplemented method ' + fn);
  3639. break;
  3640. }
  3641. }
  3642. },
  3643. setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) {
  3644. this.current.wordSpacing = wordSpacing;
  3645. },
  3646. setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) {
  3647. this.current.charSpacing = charSpacing;
  3648. },
  3649. nextLine: function SVGGraphics_nextLine() {
  3650. this.moveText(0, this.current.leading);
  3651. },
  3652. setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) {
  3653. var current = this.current;
  3654. this.current.textMatrix = this.current.lineMatrix = [
  3655. a,
  3656. b,
  3657. c,
  3658. d,
  3659. e,
  3660. f
  3661. ];
  3662. this.current.x = this.current.lineX = 0;
  3663. this.current.y = this.current.lineY = 0;
  3664. current.xcoords = [];
  3665. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3666. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3667. current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px');
  3668. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3669. current.txtElement = document.createElementNS(NS, 'svg:text');
  3670. current.txtElement.appendChild(current.tspan);
  3671. },
  3672. beginText: function SVGGraphics_beginText() {
  3673. this.current.x = this.current.lineX = 0;
  3674. this.current.y = this.current.lineY = 0;
  3675. this.current.textMatrix = IDENTITY_MATRIX;
  3676. this.current.lineMatrix = IDENTITY_MATRIX;
  3677. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3678. this.current.txtElement = document.createElementNS(NS, 'svg:text');
  3679. this.current.txtgrp = document.createElementNS(NS, 'svg:g');
  3680. this.current.xcoords = [];
  3681. },
  3682. moveText: function SVGGraphics_moveText(x, y) {
  3683. var current = this.current;
  3684. this.current.x = this.current.lineX += x;
  3685. this.current.y = this.current.lineY += y;
  3686. current.xcoords = [];
  3687. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3688. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3689. current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px');
  3690. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3691. },
  3692. showText: function SVGGraphics_showText(glyphs) {
  3693. var current = this.current;
  3694. var font = current.font;
  3695. var fontSize = current.fontSize;
  3696. if (fontSize === 0) {
  3697. return;
  3698. }
  3699. var charSpacing = current.charSpacing;
  3700. var wordSpacing = current.wordSpacing;
  3701. var fontDirection = current.fontDirection;
  3702. var textHScale = current.textHScale * fontDirection;
  3703. var glyphsLength = glyphs.length;
  3704. var vertical = font.vertical;
  3705. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  3706. var x = 0, i;
  3707. for (i = 0; i < glyphsLength; ++i) {
  3708. var glyph = glyphs[i];
  3709. if (glyph === null) {
  3710. // word break
  3711. x += fontDirection * wordSpacing;
  3712. continue;
  3713. } else if (isNum(glyph)) {
  3714. x += -glyph * fontSize * 0.001;
  3715. continue;
  3716. }
  3717. current.xcoords.push(current.x + x * textHScale);
  3718. var width = glyph.width;
  3719. var character = glyph.fontChar;
  3720. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  3721. x += charWidth;
  3722. current.tspan.textContent += character;
  3723. }
  3724. if (vertical) {
  3725. current.y -= x * textHScale;
  3726. } else {
  3727. current.x += x * textHScale;
  3728. }
  3729. current.tspan.setAttributeNS(null, 'x', current.xcoords.map(pf).join(' '));
  3730. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3731. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3732. current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px');
  3733. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  3734. current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);
  3735. }
  3736. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  3737. current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);
  3738. }
  3739. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  3740. current.tspan.setAttributeNS(null, 'fill', current.fillColor);
  3741. }
  3742. current.txtElement.setAttributeNS(null, 'transform', pm(current.textMatrix) + ' scale(1, -1)');
  3743. current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
  3744. current.txtElement.appendChild(current.tspan);
  3745. current.txtgrp.appendChild(current.txtElement);
  3746. this.tgrp.appendChild(current.txtElement);
  3747. },
  3748. setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) {
  3749. this.setLeading(-y);
  3750. this.moveText(x, y);
  3751. },
  3752. addFontStyle: function SVGGraphics_addFontStyle(fontObj) {
  3753. if (!this.cssStyle) {
  3754. this.cssStyle = document.createElementNS(NS, 'svg:style');
  3755. this.cssStyle.setAttributeNS(null, 'type', 'text/css');
  3756. this.defs.appendChild(this.cssStyle);
  3757. }
  3758. var url = createObjectURL(fontObj.data, fontObj.mimetype, this.forceDataSchema);
  3759. this.cssStyle.textContent += '@font-face { font-family: "' + fontObj.loadedName + '";' + ' src: url(' + url + '); }\n';
  3760. },
  3761. setFont: function SVGGraphics_setFont(details) {
  3762. var current = this.current;
  3763. var fontObj = this.commonObjs.get(details[0]);
  3764. var size = details[1];
  3765. this.current.font = fontObj;
  3766. if (this.embedFonts && fontObj.data && !this.embeddedFonts[fontObj.loadedName]) {
  3767. this.addFontStyle(fontObj);
  3768. this.embeddedFonts[fontObj.loadedName] = fontObj;
  3769. }
  3770. current.fontMatrix = fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX;
  3771. var bold = fontObj.black ? fontObj.bold ? 'bolder' : 'bold' : fontObj.bold ? 'bold' : 'normal';
  3772. var italic = fontObj.italic ? 'italic' : 'normal';
  3773. if (size < 0) {
  3774. size = -size;
  3775. current.fontDirection = -1;
  3776. } else {
  3777. current.fontDirection = 1;
  3778. }
  3779. current.fontSize = size;
  3780. current.fontFamily = fontObj.loadedName;
  3781. current.fontWeight = bold;
  3782. current.fontStyle = italic;
  3783. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3784. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3785. current.xcoords = [];
  3786. },
  3787. endText: function SVGGraphics_endText() {
  3788. if (this.current.pendingClip) {
  3789. this.cgrp.appendChild(this.tgrp);
  3790. this.pgrp.appendChild(this.cgrp);
  3791. } else {
  3792. this.pgrp.appendChild(this.tgrp);
  3793. }
  3794. this.tgrp = document.createElementNS(NS, 'svg:g');
  3795. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3796. },
  3797. // Path properties
  3798. setLineWidth: function SVGGraphics_setLineWidth(width) {
  3799. this.current.lineWidth = width;
  3800. },
  3801. setLineCap: function SVGGraphics_setLineCap(style) {
  3802. this.current.lineCap = LINE_CAP_STYLES[style];
  3803. },
  3804. setLineJoin: function SVGGraphics_setLineJoin(style) {
  3805. this.current.lineJoin = LINE_JOIN_STYLES[style];
  3806. },
  3807. setMiterLimit: function SVGGraphics_setMiterLimit(limit) {
  3808. this.current.miterLimit = limit;
  3809. },
  3810. setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) {
  3811. var color = Util.makeCssRgb(r, g, b);
  3812. this.current.strokeColor = color;
  3813. },
  3814. setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) {
  3815. var color = Util.makeCssRgb(r, g, b);
  3816. this.current.fillColor = color;
  3817. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3818. this.current.xcoords = [];
  3819. },
  3820. setDash: function SVGGraphics_setDash(dashArray, dashPhase) {
  3821. this.current.dashArray = dashArray;
  3822. this.current.dashPhase = dashPhase;
  3823. },
  3824. constructPath: function SVGGraphics_constructPath(ops, args) {
  3825. var current = this.current;
  3826. var x = current.x, y = current.y;
  3827. current.path = document.createElementNS(NS, 'svg:path');
  3828. var d = [];
  3829. var opLength = ops.length;
  3830. for (var i = 0, j = 0; i < opLength; i++) {
  3831. switch (ops[i] | 0) {
  3832. case OPS.rectangle:
  3833. x = args[j++];
  3834. y = args[j++];
  3835. var width = args[j++];
  3836. var height = args[j++];
  3837. var xw = x + width;
  3838. var yh = y + height;
  3839. d.push('M', pf(x), pf(y), 'L', pf(xw), pf(y), 'L', pf(xw), pf(yh), 'L', pf(x), pf(yh), 'Z');
  3840. break;
  3841. case OPS.moveTo:
  3842. x = args[j++];
  3843. y = args[j++];
  3844. d.push('M', pf(x), pf(y));
  3845. break;
  3846. case OPS.lineTo:
  3847. x = args[j++];
  3848. y = args[j++];
  3849. d.push('L', pf(x), pf(y));
  3850. break;
  3851. case OPS.curveTo:
  3852. x = args[j + 4];
  3853. y = args[j + 5];
  3854. d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y));
  3855. j += 6;
  3856. break;
  3857. case OPS.curveTo2:
  3858. x = args[j + 2];
  3859. y = args[j + 3];
  3860. d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]));
  3861. j += 4;
  3862. break;
  3863. case OPS.curveTo3:
  3864. x = args[j + 2];
  3865. y = args[j + 3];
  3866. d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y));
  3867. j += 4;
  3868. break;
  3869. case OPS.closePath:
  3870. d.push('Z');
  3871. break;
  3872. }
  3873. }
  3874. current.path.setAttributeNS(null, 'd', d.join(' '));
  3875. current.path.setAttributeNS(null, 'stroke-miterlimit', pf(current.miterLimit));
  3876. current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap);
  3877. current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);
  3878. current.path.setAttributeNS(null, 'stroke-width', pf(current.lineWidth) + 'px');
  3879. current.path.setAttributeNS(null, 'stroke-dasharray', current.dashArray.map(pf).join(' '));
  3880. current.path.setAttributeNS(null, 'stroke-dashoffset', pf(current.dashPhase) + 'px');
  3881. current.path.setAttributeNS(null, 'fill', 'none');
  3882. this.tgrp.appendChild(current.path);
  3883. if (current.pendingClip) {
  3884. this.cgrp.appendChild(this.tgrp);
  3885. this.pgrp.appendChild(this.cgrp);
  3886. } else {
  3887. this.pgrp.appendChild(this.tgrp);
  3888. }
  3889. // Saving a reference in current.element so that it can be addressed
  3890. // in 'fill' and 'stroke'
  3891. current.element = current.path;
  3892. current.setCurrentPoint(x, y);
  3893. },
  3894. endPath: function SVGGraphics_endPath() {
  3895. var current = this.current;
  3896. if (current.pendingClip) {
  3897. this.cgrp.appendChild(this.tgrp);
  3898. this.pgrp.appendChild(this.cgrp);
  3899. } else {
  3900. this.pgrp.appendChild(this.tgrp);
  3901. }
  3902. this.tgrp = document.createElementNS(NS, 'svg:g');
  3903. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3904. },
  3905. clip: function SVGGraphics_clip(type) {
  3906. var current = this.current;
  3907. // Add current path to clipping path
  3908. current.clipId = 'clippath' + clipCount;
  3909. clipCount++;
  3910. this.clippath = document.createElementNS(NS, 'svg:clipPath');
  3911. this.clippath.setAttributeNS(null, 'id', current.clipId);
  3912. var clipElement = current.element.cloneNode();
  3913. if (type === 'evenodd') {
  3914. clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');
  3915. } else {
  3916. clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');
  3917. }
  3918. this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3919. this.clippath.appendChild(clipElement);
  3920. this.defs.appendChild(this.clippath);
  3921. // Create a new group with that attribute
  3922. current.pendingClip = true;
  3923. this.cgrp = document.createElementNS(NS, 'svg:g');
  3924. this.cgrp.setAttributeNS(null, 'clip-path', 'url(#' + current.clipId + ')');
  3925. this.pgrp.appendChild(this.cgrp);
  3926. },
  3927. closePath: function SVGGraphics_closePath() {
  3928. var current = this.current;
  3929. var d = current.path.getAttributeNS(null, 'd');
  3930. d += 'Z';
  3931. current.path.setAttributeNS(null, 'd', d);
  3932. },
  3933. setLeading: function SVGGraphics_setLeading(leading) {
  3934. this.current.leading = -leading;
  3935. },
  3936. setTextRise: function SVGGraphics_setTextRise(textRise) {
  3937. this.current.textRise = textRise;
  3938. },
  3939. setHScale: function SVGGraphics_setHScale(scale) {
  3940. this.current.textHScale = scale / 100;
  3941. },
  3942. setGState: function SVGGraphics_setGState(states) {
  3943. for (var i = 0, ii = states.length; i < ii; i++) {
  3944. var state = states[i];
  3945. var key = state[0];
  3946. var value = state[1];
  3947. switch (key) {
  3948. case 'LW':
  3949. this.setLineWidth(value);
  3950. break;
  3951. case 'LC':
  3952. this.setLineCap(value);
  3953. break;
  3954. case 'LJ':
  3955. this.setLineJoin(value);
  3956. break;
  3957. case 'ML':
  3958. this.setMiterLimit(value);
  3959. break;
  3960. case 'D':
  3961. this.setDash(value[0], value[1]);
  3962. break;
  3963. case 'RI':
  3964. break;
  3965. case 'FL':
  3966. break;
  3967. case 'Font':
  3968. this.setFont(value);
  3969. break;
  3970. case 'CA':
  3971. break;
  3972. case 'ca':
  3973. break;
  3974. case 'BM':
  3975. break;
  3976. case 'SMask':
  3977. break;
  3978. }
  3979. }
  3980. },
  3981. fill: function SVGGraphics_fill() {
  3982. var current = this.current;
  3983. current.element.setAttributeNS(null, 'fill', current.fillColor);
  3984. },
  3985. stroke: function SVGGraphics_stroke() {
  3986. var current = this.current;
  3987. current.element.setAttributeNS(null, 'stroke', current.strokeColor);
  3988. current.element.setAttributeNS(null, 'fill', 'none');
  3989. },
  3990. eoFill: function SVGGraphics_eoFill() {
  3991. var current = this.current;
  3992. current.element.setAttributeNS(null, 'fill', current.fillColor);
  3993. current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  3994. },
  3995. fillStroke: function SVGGraphics_fillStroke() {
  3996. // Order is important since stroke wants fill to be none.
  3997. // First stroke, then if fill needed, it will be overwritten.
  3998. this.stroke();
  3999. this.fill();
  4000. },
  4001. eoFillStroke: function SVGGraphics_eoFillStroke() {
  4002. this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  4003. this.fillStroke();
  4004. },
  4005. closeStroke: function SVGGraphics_closeStroke() {
  4006. this.closePath();
  4007. this.stroke();
  4008. },
  4009. closeFillStroke: function SVGGraphics_closeFillStroke() {
  4010. this.closePath();
  4011. this.fillStroke();
  4012. },
  4013. paintSolidColorImageMask: function SVGGraphics_paintSolidColorImageMask() {
  4014. var current = this.current;
  4015. var rect = document.createElementNS(NS, 'svg:rect');
  4016. rect.setAttributeNS(null, 'x', '0');
  4017. rect.setAttributeNS(null, 'y', '0');
  4018. rect.setAttributeNS(null, 'width', '1px');
  4019. rect.setAttributeNS(null, 'height', '1px');
  4020. rect.setAttributeNS(null, 'fill', current.fillColor);
  4021. this.tgrp.appendChild(rect);
  4022. },
  4023. paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) {
  4024. var current = this.current;
  4025. var imgObj = this.objs.get(objId);
  4026. var imgEl = document.createElementNS(NS, 'svg:image');
  4027. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);
  4028. imgEl.setAttributeNS(null, 'width', imgObj.width + 'px');
  4029. imgEl.setAttributeNS(null, 'height', imgObj.height + 'px');
  4030. imgEl.setAttributeNS(null, 'x', '0');
  4031. imgEl.setAttributeNS(null, 'y', pf(-h));
  4032. imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')');
  4033. this.tgrp.appendChild(imgEl);
  4034. if (current.pendingClip) {
  4035. this.cgrp.appendChild(this.tgrp);
  4036. this.pgrp.appendChild(this.cgrp);
  4037. } else {
  4038. this.pgrp.appendChild(this.tgrp);
  4039. }
  4040. },
  4041. paintImageXObject: function SVGGraphics_paintImageXObject(objId) {
  4042. var imgData = this.objs.get(objId);
  4043. if (!imgData) {
  4044. warn('Dependent image isn\'t ready yet');
  4045. return;
  4046. }
  4047. this.paintInlineImageXObject(imgData);
  4048. },
  4049. paintInlineImageXObject: function SVGGraphics_paintInlineImageXObject(imgData, mask) {
  4050. var current = this.current;
  4051. var width = imgData.width;
  4052. var height = imgData.height;
  4053. var imgSrc = convertImgDataToPng(imgData, this.forceDataSchema);
  4054. var cliprect = document.createElementNS(NS, 'svg:rect');
  4055. cliprect.setAttributeNS(null, 'x', '0');
  4056. cliprect.setAttributeNS(null, 'y', '0');
  4057. cliprect.setAttributeNS(null, 'width', pf(width));
  4058. cliprect.setAttributeNS(null, 'height', pf(height));
  4059. current.element = cliprect;
  4060. this.clip('nonzero');
  4061. var imgEl = document.createElementNS(NS, 'svg:image');
  4062. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);
  4063. imgEl.setAttributeNS(null, 'x', '0');
  4064. imgEl.setAttributeNS(null, 'y', pf(-height));
  4065. imgEl.setAttributeNS(null, 'width', pf(width) + 'px');
  4066. imgEl.setAttributeNS(null, 'height', pf(height) + 'px');
  4067. imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / width) + ' ' + pf(-1 / height) + ')');
  4068. if (mask) {
  4069. mask.appendChild(imgEl);
  4070. } else {
  4071. this.tgrp.appendChild(imgEl);
  4072. }
  4073. if (current.pendingClip) {
  4074. this.cgrp.appendChild(this.tgrp);
  4075. this.pgrp.appendChild(this.cgrp);
  4076. } else {
  4077. this.pgrp.appendChild(this.tgrp);
  4078. }
  4079. },
  4080. paintImageMaskXObject: function SVGGraphics_paintImageMaskXObject(imgData) {
  4081. var current = this.current;
  4082. var width = imgData.width;
  4083. var height = imgData.height;
  4084. var fillColor = current.fillColor;
  4085. current.maskId = 'mask' + maskCount++;
  4086. var mask = document.createElementNS(NS, 'svg:mask');
  4087. mask.setAttributeNS(null, 'id', current.maskId);
  4088. var rect = document.createElementNS(NS, 'svg:rect');
  4089. rect.setAttributeNS(null, 'x', '0');
  4090. rect.setAttributeNS(null, 'y', '0');
  4091. rect.setAttributeNS(null, 'width', pf(width));
  4092. rect.setAttributeNS(null, 'height', pf(height));
  4093. rect.setAttributeNS(null, 'fill', fillColor);
  4094. rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId + ')');
  4095. this.defs.appendChild(mask);
  4096. this.tgrp.appendChild(rect);
  4097. this.paintInlineImageXObject(imgData, mask);
  4098. },
  4099. paintFormXObjectBegin: function SVGGraphics_paintFormXObjectBegin(matrix, bbox) {
  4100. this.save();
  4101. if (isArray(matrix) && matrix.length === 6) {
  4102. this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
  4103. }
  4104. if (isArray(bbox) && bbox.length === 4) {
  4105. var width = bbox[2] - bbox[0];
  4106. var height = bbox[3] - bbox[1];
  4107. var cliprect = document.createElementNS(NS, 'svg:rect');
  4108. cliprect.setAttributeNS(null, 'x', bbox[0]);
  4109. cliprect.setAttributeNS(null, 'y', bbox[1]);
  4110. cliprect.setAttributeNS(null, 'width', pf(width));
  4111. cliprect.setAttributeNS(null, 'height', pf(height));
  4112. this.current.element = cliprect;
  4113. this.clip('nonzero');
  4114. this.endPath();
  4115. }
  4116. },
  4117. paintFormXObjectEnd: function SVGGraphics_paintFormXObjectEnd() {
  4118. this.restore();
  4119. }
  4120. };
  4121. return SVGGraphics;
  4122. }();
  4123. exports.SVGGraphics = SVGGraphics;
  4124. }));
  4125. (function (root, factory) {
  4126. factory(root.pdfjsDisplayAnnotationLayer = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils);
  4127. }(this, function (exports, sharedUtil, displayDOMUtils) {
  4128. var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType;
  4129. var AnnotationType = sharedUtil.AnnotationType;
  4130. var Util = sharedUtil.Util;
  4131. var addLinkAttributes = displayDOMUtils.addLinkAttributes;
  4132. var LinkTarget = displayDOMUtils.LinkTarget;
  4133. var getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  4134. var warn = sharedUtil.warn;
  4135. var CustomStyle = displayDOMUtils.CustomStyle;
  4136. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  4137. /**
  4138. * @typedef {Object} AnnotationElementParameters
  4139. * @property {Object} data
  4140. * @property {HTMLDivElement} layer
  4141. * @property {PDFPage} page
  4142. * @property {PageViewport} viewport
  4143. * @property {IPDFLinkService} linkService
  4144. * @property {DownloadManager} downloadManager
  4145. * @property {string} imageResourcesPath
  4146. * @property {boolean} renderInteractiveForms
  4147. */
  4148. /**
  4149. * @class
  4150. * @alias AnnotationElementFactory
  4151. */
  4152. function AnnotationElementFactory() {
  4153. }
  4154. AnnotationElementFactory.prototype = /** @lends AnnotationElementFactory.prototype */
  4155. {
  4156. /**
  4157. * @param {AnnotationElementParameters} parameters
  4158. * @returns {AnnotationElement}
  4159. */
  4160. create: function AnnotationElementFactory_create(parameters) {
  4161. var subtype = parameters.data.annotationType;
  4162. switch (subtype) {
  4163. case AnnotationType.LINK:
  4164. return new LinkAnnotationElement(parameters);
  4165. case AnnotationType.TEXT:
  4166. return new TextAnnotationElement(parameters);
  4167. case AnnotationType.WIDGET:
  4168. var fieldType = parameters.data.fieldType;
  4169. switch (fieldType) {
  4170. case 'Tx':
  4171. return new TextWidgetAnnotationElement(parameters);
  4172. case 'Ch':
  4173. return new ChoiceWidgetAnnotationElement(parameters);
  4174. }
  4175. return new WidgetAnnotationElement(parameters);
  4176. case AnnotationType.POPUP:
  4177. return new PopupAnnotationElement(parameters);
  4178. case AnnotationType.HIGHLIGHT:
  4179. return new HighlightAnnotationElement(parameters);
  4180. case AnnotationType.UNDERLINE:
  4181. return new UnderlineAnnotationElement(parameters);
  4182. case AnnotationType.SQUIGGLY:
  4183. return new SquigglyAnnotationElement(parameters);
  4184. case AnnotationType.STRIKEOUT:
  4185. return new StrikeOutAnnotationElement(parameters);
  4186. case AnnotationType.FILEATTACHMENT:
  4187. return new FileAttachmentAnnotationElement(parameters);
  4188. default:
  4189. return new AnnotationElement(parameters);
  4190. }
  4191. }
  4192. };
  4193. /**
  4194. * @class
  4195. * @alias AnnotationElement
  4196. */
  4197. var AnnotationElement = function AnnotationElementClosure() {
  4198. function AnnotationElement(parameters, isRenderable) {
  4199. this.isRenderable = isRenderable || false;
  4200. this.data = parameters.data;
  4201. this.layer = parameters.layer;
  4202. this.page = parameters.page;
  4203. this.viewport = parameters.viewport;
  4204. this.linkService = parameters.linkService;
  4205. this.downloadManager = parameters.downloadManager;
  4206. this.imageResourcesPath = parameters.imageResourcesPath;
  4207. this.renderInteractiveForms = parameters.renderInteractiveForms;
  4208. if (isRenderable) {
  4209. this.container = this._createContainer();
  4210. }
  4211. }
  4212. AnnotationElement.prototype = /** @lends AnnotationElement.prototype */
  4213. {
  4214. /**
  4215. * Create an empty container for the annotation's HTML element.
  4216. *
  4217. * @private
  4218. * @memberof AnnotationElement
  4219. * @returns {HTMLSectionElement}
  4220. */
  4221. _createContainer: function AnnotationElement_createContainer() {
  4222. var data = this.data, page = this.page, viewport = this.viewport;
  4223. var container = document.createElement('section');
  4224. var width = data.rect[2] - data.rect[0];
  4225. var height = data.rect[3] - data.rect[1];
  4226. container.setAttribute('data-annotation-id', data.id);
  4227. // Do *not* modify `data.rect`, since that will corrupt the annotation
  4228. // position on subsequent calls to `_createContainer` (see issue 6804).
  4229. var rect = Util.normalizeRect([
  4230. data.rect[0],
  4231. page.view[3] - data.rect[1] + page.view[1],
  4232. data.rect[2],
  4233. page.view[3] - data.rect[3] + page.view[1]
  4234. ]);
  4235. CustomStyle.setProp('transform', container, 'matrix(' + viewport.transform.join(',') + ')');
  4236. CustomStyle.setProp('transformOrigin', container, -rect[0] + 'px ' + -rect[1] + 'px');
  4237. if (data.borderStyle.width > 0) {
  4238. container.style.borderWidth = data.borderStyle.width + 'px';
  4239. if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) {
  4240. // Underline styles only have a bottom border, so we do not need
  4241. // to adjust for all borders. This yields a similar result as
  4242. // Adobe Acrobat/Reader.
  4243. width = width - 2 * data.borderStyle.width;
  4244. height = height - 2 * data.borderStyle.width;
  4245. }
  4246. var horizontalRadius = data.borderStyle.horizontalCornerRadius;
  4247. var verticalRadius = data.borderStyle.verticalCornerRadius;
  4248. if (horizontalRadius > 0 || verticalRadius > 0) {
  4249. var radius = horizontalRadius + 'px / ' + verticalRadius + 'px';
  4250. CustomStyle.setProp('borderRadius', container, radius);
  4251. }
  4252. switch (data.borderStyle.style) {
  4253. case AnnotationBorderStyleType.SOLID:
  4254. container.style.borderStyle = 'solid';
  4255. break;
  4256. case AnnotationBorderStyleType.DASHED:
  4257. container.style.borderStyle = 'dashed';
  4258. break;
  4259. case AnnotationBorderStyleType.BEVELED:
  4260. warn('Unimplemented border style: beveled');
  4261. break;
  4262. case AnnotationBorderStyleType.INSET:
  4263. warn('Unimplemented border style: inset');
  4264. break;
  4265. case AnnotationBorderStyleType.UNDERLINE:
  4266. container.style.borderBottomStyle = 'solid';
  4267. break;
  4268. default:
  4269. break;
  4270. }
  4271. if (data.color) {
  4272. container.style.borderColor = Util.makeCssRgb(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0);
  4273. } else {
  4274. // Transparent (invisible) border, so do not draw it at all.
  4275. container.style.borderWidth = 0;
  4276. }
  4277. }
  4278. container.style.left = rect[0] + 'px';
  4279. container.style.top = rect[1] + 'px';
  4280. container.style.width = width + 'px';
  4281. container.style.height = height + 'px';
  4282. return container;
  4283. },
  4284. /**
  4285. * Create a popup for the annotation's HTML element. This is used for
  4286. * annotations that do not have a Popup entry in the dictionary, but
  4287. * are of a type that works with popups (such as Highlight annotations).
  4288. *
  4289. * @private
  4290. * @param {HTMLSectionElement} container
  4291. * @param {HTMLDivElement|HTMLImageElement|null} trigger
  4292. * @param {Object} data
  4293. * @memberof AnnotationElement
  4294. */
  4295. _createPopup: function AnnotationElement_createPopup(container, trigger, data) {
  4296. // If no trigger element is specified, create it.
  4297. if (!trigger) {
  4298. trigger = document.createElement('div');
  4299. trigger.style.height = container.style.height;
  4300. trigger.style.width = container.style.width;
  4301. container.appendChild(trigger);
  4302. }
  4303. var popupElement = new PopupElement({
  4304. container: container,
  4305. trigger: trigger,
  4306. color: data.color,
  4307. title: data.title,
  4308. contents: data.contents,
  4309. hideWrapper: true
  4310. });
  4311. var popup = popupElement.render();
  4312. // Position the popup next to the annotation's container.
  4313. popup.style.left = container.style.width;
  4314. container.appendChild(popup);
  4315. },
  4316. /**
  4317. * Render the annotation's HTML element in the empty container.
  4318. *
  4319. * @public
  4320. * @memberof AnnotationElement
  4321. */
  4322. render: function AnnotationElement_render() {
  4323. throw new Error('Abstract method AnnotationElement.render called');
  4324. }
  4325. };
  4326. return AnnotationElement;
  4327. }();
  4328. /**
  4329. * @class
  4330. * @alias LinkAnnotationElement
  4331. */
  4332. var LinkAnnotationElement = function LinkAnnotationElementClosure() {
  4333. function LinkAnnotationElement(parameters) {
  4334. AnnotationElement.call(this, parameters, true);
  4335. }
  4336. Util.inherit(LinkAnnotationElement, AnnotationElement, {
  4337. /**
  4338. * Render the link annotation's HTML element in the empty container.
  4339. *
  4340. * @public
  4341. * @memberof LinkAnnotationElement
  4342. * @returns {HTMLSectionElement}
  4343. */
  4344. render: function LinkAnnotationElement_render() {
  4345. this.container.className = 'linkAnnotation';
  4346. var link = document.createElement('a');
  4347. addLinkAttributes(link, {
  4348. url: this.data.url,
  4349. target: this.data.newWindow ? LinkTarget.BLANK : undefined
  4350. });
  4351. if (!this.data.url) {
  4352. if (this.data.action) {
  4353. this._bindNamedAction(link, this.data.action);
  4354. } else {
  4355. this._bindLink(link, this.data.dest || null);
  4356. }
  4357. }
  4358. this.container.appendChild(link);
  4359. return this.container;
  4360. },
  4361. /**
  4362. * Bind internal links to the link element.
  4363. *
  4364. * @private
  4365. * @param {Object} link
  4366. * @param {Object} destination
  4367. * @memberof LinkAnnotationElement
  4368. */
  4369. _bindLink: function LinkAnnotationElement_bindLink(link, destination) {
  4370. var self = this;
  4371. link.href = this.linkService.getDestinationHash(destination);
  4372. link.onclick = function () {
  4373. if (destination) {
  4374. self.linkService.navigateTo(destination);
  4375. }
  4376. return false;
  4377. };
  4378. if (destination) {
  4379. link.className = 'internalLink';
  4380. }
  4381. },
  4382. /**
  4383. * Bind named actions to the link element.
  4384. *
  4385. * @private
  4386. * @param {Object} link
  4387. * @param {Object} action
  4388. * @memberof LinkAnnotationElement
  4389. */
  4390. _bindNamedAction: function LinkAnnotationElement_bindNamedAction(link, action) {
  4391. var self = this;
  4392. link.href = this.linkService.getAnchorUrl('');
  4393. link.onclick = function () {
  4394. self.linkService.executeNamedAction(action);
  4395. return false;
  4396. };
  4397. link.className = 'internalLink';
  4398. }
  4399. });
  4400. return LinkAnnotationElement;
  4401. }();
  4402. /**
  4403. * @class
  4404. * @alias TextAnnotationElement
  4405. */
  4406. var TextAnnotationElement = function TextAnnotationElementClosure() {
  4407. function TextAnnotationElement(parameters) {
  4408. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4409. AnnotationElement.call(this, parameters, isRenderable);
  4410. }
  4411. Util.inherit(TextAnnotationElement, AnnotationElement, {
  4412. /**
  4413. * Render the text annotation's HTML element in the empty container.
  4414. *
  4415. * @public
  4416. * @memberof TextAnnotationElement
  4417. * @returns {HTMLSectionElement}
  4418. */
  4419. render: function TextAnnotationElement_render() {
  4420. this.container.className = 'textAnnotation';
  4421. var image = document.createElement('img');
  4422. image.style.height = this.container.style.height;
  4423. image.style.width = this.container.style.width;
  4424. image.src = this.imageResourcesPath + 'annotation-' + this.data.name.toLowerCase() + '.svg';
  4425. image.alt = '[{{type}} Annotation]';
  4426. image.dataset.l10nId = 'text_annotation_type';
  4427. image.dataset.l10nArgs = JSON.stringify({ type: this.data.name });
  4428. if (!this.data.hasPopup) {
  4429. this._createPopup(this.container, image, this.data);
  4430. }
  4431. this.container.appendChild(image);
  4432. return this.container;
  4433. }
  4434. });
  4435. return TextAnnotationElement;
  4436. }();
  4437. /**
  4438. * @class
  4439. * @alias WidgetAnnotationElement
  4440. */
  4441. var WidgetAnnotationElement = function WidgetAnnotationElementClosure() {
  4442. function WidgetAnnotationElement(parameters, isRenderable) {
  4443. AnnotationElement.call(this, parameters, isRenderable);
  4444. }
  4445. Util.inherit(WidgetAnnotationElement, AnnotationElement, {
  4446. /**
  4447. * Render the widget annotation's HTML element in the empty container.
  4448. *
  4449. * @public
  4450. * @memberof WidgetAnnotationElement
  4451. * @returns {HTMLSectionElement}
  4452. */
  4453. render: function WidgetAnnotationElement_render() {
  4454. // Show only the container for unsupported field types.
  4455. return this.container;
  4456. }
  4457. });
  4458. return WidgetAnnotationElement;
  4459. }();
  4460. /**
  4461. * @class
  4462. * @alias TextWidgetAnnotationElement
  4463. */
  4464. var TextWidgetAnnotationElement = function TextWidgetAnnotationElementClosure() {
  4465. var TEXT_ALIGNMENT = [
  4466. 'left',
  4467. 'center',
  4468. 'right'
  4469. ];
  4470. function TextWidgetAnnotationElement(parameters) {
  4471. var isRenderable = parameters.renderInteractiveForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
  4472. WidgetAnnotationElement.call(this, parameters, isRenderable);
  4473. }
  4474. Util.inherit(TextWidgetAnnotationElement, WidgetAnnotationElement, {
  4475. /**
  4476. * Render the text widget annotation's HTML element in the empty container.
  4477. *
  4478. * @public
  4479. * @memberof TextWidgetAnnotationElement
  4480. * @returns {HTMLSectionElement}
  4481. */
  4482. render: function TextWidgetAnnotationElement_render() {
  4483. this.container.className = 'textWidgetAnnotation';
  4484. var element = null;
  4485. if (this.renderInteractiveForms) {
  4486. // NOTE: We cannot set the values using `element.value` below, since it
  4487. // prevents the AnnotationLayer rasterizer in `test/driver.js`
  4488. // from parsing the elements correctly for the reference tests.
  4489. if (this.data.multiLine) {
  4490. element = document.createElement('textarea');
  4491. element.textContent = this.data.fieldValue;
  4492. } else {
  4493. element = document.createElement('input');
  4494. element.type = 'text';
  4495. element.setAttribute('value', this.data.fieldValue);
  4496. }
  4497. element.disabled = this.data.readOnly;
  4498. if (this.data.maxLen !== null) {
  4499. element.maxLength = this.data.maxLen;
  4500. }
  4501. if (this.data.comb) {
  4502. var fieldWidth = this.data.rect[2] - this.data.rect[0];
  4503. var combWidth = fieldWidth / this.data.maxLen;
  4504. element.classList.add('comb');
  4505. element.style.letterSpacing = 'calc(' + combWidth + 'px - 1ch)';
  4506. }
  4507. } else {
  4508. element = document.createElement('div');
  4509. element.textContent = this.data.fieldValue;
  4510. element.style.verticalAlign = 'middle';
  4511. element.style.display = 'table-cell';
  4512. var font = null;
  4513. if (this.data.fontRefName) {
  4514. font = this.page.commonObjs.getData(this.data.fontRefName);
  4515. }
  4516. this._setTextStyle(element, font);
  4517. }
  4518. if (this.data.textAlignment !== null) {
  4519. element.style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  4520. }
  4521. this.container.appendChild(element);
  4522. return this.container;
  4523. },
  4524. /**
  4525. * Apply text styles to the text in the element.
  4526. *
  4527. * @private
  4528. * @param {HTMLDivElement} element
  4529. * @param {Object} font
  4530. * @memberof TextWidgetAnnotationElement
  4531. */
  4532. _setTextStyle: function TextWidgetAnnotationElement_setTextStyle(element, font) {
  4533. // TODO: This duplicates some of the logic in CanvasGraphics.setFont().
  4534. var style = element.style;
  4535. style.fontSize = this.data.fontSize + 'px';
  4536. style.direction = this.data.fontDirection < 0 ? 'rtl' : 'ltr';
  4537. if (!font) {
  4538. return;
  4539. }
  4540. style.fontWeight = font.black ? font.bold ? '900' : 'bold' : font.bold ? 'bold' : 'normal';
  4541. style.fontStyle = font.italic ? 'italic' : 'normal';
  4542. // Use a reasonable default font if the font doesn't specify a fallback.
  4543. var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : '';
  4544. var fallbackName = font.fallbackName || 'Helvetica, sans-serif';
  4545. style.fontFamily = fontFamily + fallbackName;
  4546. }
  4547. });
  4548. return TextWidgetAnnotationElement;
  4549. }();
  4550. /**
  4551. * @class
  4552. * @alias ChoiceWidgetAnnotationElement
  4553. */
  4554. var ChoiceWidgetAnnotationElement = function ChoiceWidgetAnnotationElementClosure() {
  4555. function ChoiceWidgetAnnotationElement(parameters) {
  4556. WidgetAnnotationElement.call(this, parameters, parameters.renderInteractiveForms);
  4557. }
  4558. Util.inherit(ChoiceWidgetAnnotationElement, WidgetAnnotationElement, {
  4559. /**
  4560. * Render the choice widget annotation's HTML element in the empty
  4561. * container.
  4562. *
  4563. * @public
  4564. * @memberof ChoiceWidgetAnnotationElement
  4565. * @returns {HTMLSectionElement}
  4566. */
  4567. render: function ChoiceWidgetAnnotationElement_render() {
  4568. this.container.className = 'choiceWidgetAnnotation';
  4569. var selectElement = document.createElement('select');
  4570. selectElement.disabled = this.data.readOnly;
  4571. if (!this.data.combo) {
  4572. // List boxes have a size and (optionally) multiple selection.
  4573. selectElement.size = this.data.options.length;
  4574. if (this.data.multiSelect) {
  4575. selectElement.multiple = true;
  4576. }
  4577. }
  4578. // Insert the options into the choice field.
  4579. for (var i = 0, ii = this.data.options.length; i < ii; i++) {
  4580. var option = this.data.options[i];
  4581. var optionElement = document.createElement('option');
  4582. optionElement.textContent = option.displayValue;
  4583. optionElement.value = option.exportValue;
  4584. if (this.data.fieldValue.indexOf(option.displayValue) >= 0) {
  4585. optionElement.setAttribute('selected', true);
  4586. }
  4587. selectElement.appendChild(optionElement);
  4588. }
  4589. this.container.appendChild(selectElement);
  4590. return this.container;
  4591. }
  4592. });
  4593. return ChoiceWidgetAnnotationElement;
  4594. }();
  4595. /**
  4596. * @class
  4597. * @alias PopupAnnotationElement
  4598. */
  4599. var PopupAnnotationElement = function PopupAnnotationElementClosure() {
  4600. function PopupAnnotationElement(parameters) {
  4601. var isRenderable = !!(parameters.data.title || parameters.data.contents);
  4602. AnnotationElement.call(this, parameters, isRenderable);
  4603. }
  4604. Util.inherit(PopupAnnotationElement, AnnotationElement, {
  4605. /**
  4606. * Render the popup annotation's HTML element in the empty container.
  4607. *
  4608. * @public
  4609. * @memberof PopupAnnotationElement
  4610. * @returns {HTMLSectionElement}
  4611. */
  4612. render: function PopupAnnotationElement_render() {
  4613. this.container.className = 'popupAnnotation';
  4614. var selector = '[data-annotation-id="' + this.data.parentId + '"]';
  4615. var parentElement = this.layer.querySelector(selector);
  4616. if (!parentElement) {
  4617. return this.container;
  4618. }
  4619. var popup = new PopupElement({
  4620. container: this.container,
  4621. trigger: parentElement,
  4622. color: this.data.color,
  4623. title: this.data.title,
  4624. contents: this.data.contents
  4625. });
  4626. // Position the popup next to the parent annotation's container.
  4627. // PDF viewers ignore a popup annotation's rectangle.
  4628. var parentLeft = parseFloat(parentElement.style.left);
  4629. var parentWidth = parseFloat(parentElement.style.width);
  4630. CustomStyle.setProp('transformOrigin', this.container, -(parentLeft + parentWidth) + 'px -' + parentElement.style.top);
  4631. this.container.style.left = parentLeft + parentWidth + 'px';
  4632. this.container.appendChild(popup.render());
  4633. return this.container;
  4634. }
  4635. });
  4636. return PopupAnnotationElement;
  4637. }();
  4638. /**
  4639. * @class
  4640. * @alias PopupElement
  4641. */
  4642. var PopupElement = function PopupElementClosure() {
  4643. var BACKGROUND_ENLIGHT = 0.7;
  4644. function PopupElement(parameters) {
  4645. this.container = parameters.container;
  4646. this.trigger = parameters.trigger;
  4647. this.color = parameters.color;
  4648. this.title = parameters.title;
  4649. this.contents = parameters.contents;
  4650. this.hideWrapper = parameters.hideWrapper || false;
  4651. this.pinned = false;
  4652. }
  4653. PopupElement.prototype = /** @lends PopupElement.prototype */
  4654. {
  4655. /**
  4656. * Render the popup's HTML element.
  4657. *
  4658. * @public
  4659. * @memberof PopupElement
  4660. * @returns {HTMLSectionElement}
  4661. */
  4662. render: function PopupElement_render() {
  4663. var wrapper = document.createElement('div');
  4664. wrapper.className = 'popupWrapper';
  4665. // For Popup annotations we hide the entire section because it contains
  4666. // only the popup. However, for Text annotations without a separate Popup
  4667. // annotation, we cannot hide the entire container as the image would
  4668. // disappear too. In that special case, hiding the wrapper suffices.
  4669. this.hideElement = this.hideWrapper ? wrapper : this.container;
  4670. this.hideElement.setAttribute('hidden', true);
  4671. var popup = document.createElement('div');
  4672. popup.className = 'popup';
  4673. var color = this.color;
  4674. if (color) {
  4675. // Enlighten the color.
  4676. var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  4677. var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  4678. var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  4679. popup.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0);
  4680. }
  4681. var contents = this._formatContents(this.contents);
  4682. var title = document.createElement('h1');
  4683. title.textContent = this.title;
  4684. // Attach the event listeners to the trigger element.
  4685. this.trigger.addEventListener('click', this._toggle.bind(this));
  4686. this.trigger.addEventListener('mouseover', this._show.bind(this, false));
  4687. this.trigger.addEventListener('mouseout', this._hide.bind(this, false));
  4688. popup.addEventListener('click', this._hide.bind(this, true));
  4689. popup.appendChild(title);
  4690. popup.appendChild(contents);
  4691. wrapper.appendChild(popup);
  4692. return wrapper;
  4693. },
  4694. /**
  4695. * Format the contents of the popup by adding newlines where necessary.
  4696. *
  4697. * @private
  4698. * @param {string} contents
  4699. * @memberof PopupElement
  4700. * @returns {HTMLParagraphElement}
  4701. */
  4702. _formatContents: function PopupElement_formatContents(contents) {
  4703. var p = document.createElement('p');
  4704. var lines = contents.split(/(?:\r\n?|\n)/);
  4705. for (var i = 0, ii = lines.length; i < ii; ++i) {
  4706. var line = lines[i];
  4707. p.appendChild(document.createTextNode(line));
  4708. if (i < ii - 1) {
  4709. p.appendChild(document.createElement('br'));
  4710. }
  4711. }
  4712. return p;
  4713. },
  4714. /**
  4715. * Toggle the visibility of the popup.
  4716. *
  4717. * @private
  4718. * @memberof PopupElement
  4719. */
  4720. _toggle: function PopupElement_toggle() {
  4721. if (this.pinned) {
  4722. this._hide(true);
  4723. } else {
  4724. this._show(true);
  4725. }
  4726. },
  4727. /**
  4728. * Show the popup.
  4729. *
  4730. * @private
  4731. * @param {boolean} pin
  4732. * @memberof PopupElement
  4733. */
  4734. _show: function PopupElement_show(pin) {
  4735. if (pin) {
  4736. this.pinned = true;
  4737. }
  4738. if (this.hideElement.hasAttribute('hidden')) {
  4739. this.hideElement.removeAttribute('hidden');
  4740. this.container.style.zIndex += 1;
  4741. }
  4742. },
  4743. /**
  4744. * Hide the popup.
  4745. *
  4746. * @private
  4747. * @param {boolean} unpin
  4748. * @memberof PopupElement
  4749. */
  4750. _hide: function PopupElement_hide(unpin) {
  4751. if (unpin) {
  4752. this.pinned = false;
  4753. }
  4754. if (!this.hideElement.hasAttribute('hidden') && !this.pinned) {
  4755. this.hideElement.setAttribute('hidden', true);
  4756. this.container.style.zIndex -= 1;
  4757. }
  4758. }
  4759. };
  4760. return PopupElement;
  4761. }();
  4762. /**
  4763. * @class
  4764. * @alias HighlightAnnotationElement
  4765. */
  4766. var HighlightAnnotationElement = function HighlightAnnotationElementClosure() {
  4767. function HighlightAnnotationElement(parameters) {
  4768. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4769. AnnotationElement.call(this, parameters, isRenderable);
  4770. }
  4771. Util.inherit(HighlightAnnotationElement, AnnotationElement, {
  4772. /**
  4773. * Render the highlight annotation's HTML element in the empty container.
  4774. *
  4775. * @public
  4776. * @memberof HighlightAnnotationElement
  4777. * @returns {HTMLSectionElement}
  4778. */
  4779. render: function HighlightAnnotationElement_render() {
  4780. this.container.className = 'highlightAnnotation';
  4781. if (!this.data.hasPopup) {
  4782. this._createPopup(this.container, null, this.data);
  4783. }
  4784. return this.container;
  4785. }
  4786. });
  4787. return HighlightAnnotationElement;
  4788. }();
  4789. /**
  4790. * @class
  4791. * @alias UnderlineAnnotationElement
  4792. */
  4793. var UnderlineAnnotationElement = function UnderlineAnnotationElementClosure() {
  4794. function UnderlineAnnotationElement(parameters) {
  4795. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4796. AnnotationElement.call(this, parameters, isRenderable);
  4797. }
  4798. Util.inherit(UnderlineAnnotationElement, AnnotationElement, {
  4799. /**
  4800. * Render the underline annotation's HTML element in the empty container.
  4801. *
  4802. * @public
  4803. * @memberof UnderlineAnnotationElement
  4804. * @returns {HTMLSectionElement}
  4805. */
  4806. render: function UnderlineAnnotationElement_render() {
  4807. this.container.className = 'underlineAnnotation';
  4808. if (!this.data.hasPopup) {
  4809. this._createPopup(this.container, null, this.data);
  4810. }
  4811. return this.container;
  4812. }
  4813. });
  4814. return UnderlineAnnotationElement;
  4815. }();
  4816. /**
  4817. * @class
  4818. * @alias SquigglyAnnotationElement
  4819. */
  4820. var SquigglyAnnotationElement = function SquigglyAnnotationElementClosure() {
  4821. function SquigglyAnnotationElement(parameters) {
  4822. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4823. AnnotationElement.call(this, parameters, isRenderable);
  4824. }
  4825. Util.inherit(SquigglyAnnotationElement, AnnotationElement, {
  4826. /**
  4827. * Render the squiggly annotation's HTML element in the empty container.
  4828. *
  4829. * @public
  4830. * @memberof SquigglyAnnotationElement
  4831. * @returns {HTMLSectionElement}
  4832. */
  4833. render: function SquigglyAnnotationElement_render() {
  4834. this.container.className = 'squigglyAnnotation';
  4835. if (!this.data.hasPopup) {
  4836. this._createPopup(this.container, null, this.data);
  4837. }
  4838. return this.container;
  4839. }
  4840. });
  4841. return SquigglyAnnotationElement;
  4842. }();
  4843. /**
  4844. * @class
  4845. * @alias StrikeOutAnnotationElement
  4846. */
  4847. var StrikeOutAnnotationElement = function StrikeOutAnnotationElementClosure() {
  4848. function StrikeOutAnnotationElement(parameters) {
  4849. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4850. AnnotationElement.call(this, parameters, isRenderable);
  4851. }
  4852. Util.inherit(StrikeOutAnnotationElement, AnnotationElement, {
  4853. /**
  4854. * Render the strikeout annotation's HTML element in the empty container.
  4855. *
  4856. * @public
  4857. * @memberof StrikeOutAnnotationElement
  4858. * @returns {HTMLSectionElement}
  4859. */
  4860. render: function StrikeOutAnnotationElement_render() {
  4861. this.container.className = 'strikeoutAnnotation';
  4862. if (!this.data.hasPopup) {
  4863. this._createPopup(this.container, null, this.data);
  4864. }
  4865. return this.container;
  4866. }
  4867. });
  4868. return StrikeOutAnnotationElement;
  4869. }();
  4870. /**
  4871. * @class
  4872. * @alias FileAttachmentAnnotationElement
  4873. */
  4874. var FileAttachmentAnnotationElement = function FileAttachmentAnnotationElementClosure() {
  4875. function FileAttachmentAnnotationElement(parameters) {
  4876. AnnotationElement.call(this, parameters, true);
  4877. this.filename = getFilenameFromUrl(parameters.data.file.filename);
  4878. this.content = parameters.data.file.content;
  4879. }
  4880. Util.inherit(FileAttachmentAnnotationElement, AnnotationElement, {
  4881. /**
  4882. * Render the file attachment annotation's HTML element in the empty
  4883. * container.
  4884. *
  4885. * @public
  4886. * @memberof FileAttachmentAnnotationElement
  4887. * @returns {HTMLSectionElement}
  4888. */
  4889. render: function FileAttachmentAnnotationElement_render() {
  4890. this.container.className = 'fileAttachmentAnnotation';
  4891. var trigger = document.createElement('div');
  4892. trigger.style.height = this.container.style.height;
  4893. trigger.style.width = this.container.style.width;
  4894. trigger.addEventListener('dblclick', this._download.bind(this));
  4895. if (!this.data.hasPopup && (this.data.title || this.data.contents)) {
  4896. this._createPopup(this.container, trigger, this.data);
  4897. }
  4898. this.container.appendChild(trigger);
  4899. return this.container;
  4900. },
  4901. /**
  4902. * Download the file attachment associated with this annotation.
  4903. *
  4904. * @private
  4905. * @memberof FileAttachmentAnnotationElement
  4906. */
  4907. _download: function FileAttachmentAnnotationElement_download() {
  4908. if (!this.downloadManager) {
  4909. warn('Download cannot be started due to unavailable download manager');
  4910. return;
  4911. }
  4912. this.downloadManager.downloadData(this.content, this.filename, '');
  4913. }
  4914. });
  4915. return FileAttachmentAnnotationElement;
  4916. }();
  4917. /**
  4918. * @typedef {Object} AnnotationLayerParameters
  4919. * @property {PageViewport} viewport
  4920. * @property {HTMLDivElement} div
  4921. * @property {Array} annotations
  4922. * @property {PDFPage} page
  4923. * @property {IPDFLinkService} linkService
  4924. * @property {string} imageResourcesPath
  4925. * @property {boolean} renderInteractiveForms
  4926. */
  4927. /**
  4928. * @class
  4929. * @alias AnnotationLayer
  4930. */
  4931. var AnnotationLayer = function AnnotationLayerClosure() {
  4932. return {
  4933. /**
  4934. * Render a new annotation layer with all annotation elements.
  4935. *
  4936. * @public
  4937. * @param {AnnotationLayerParameters} parameters
  4938. * @memberof AnnotationLayer
  4939. */
  4940. render: function AnnotationLayer_render(parameters) {
  4941. var annotationElementFactory = new AnnotationElementFactory();
  4942. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4943. var data = parameters.annotations[i];
  4944. if (!data) {
  4945. continue;
  4946. }
  4947. var properties = {
  4948. data: data,
  4949. layer: parameters.div,
  4950. page: parameters.page,
  4951. viewport: parameters.viewport,
  4952. linkService: parameters.linkService,
  4953. downloadManager: parameters.downloadManager,
  4954. imageResourcesPath: parameters.imageResourcesPath || getDefaultSetting('imageResourcesPath'),
  4955. renderInteractiveForms: parameters.renderInteractiveForms || false
  4956. };
  4957. var element = annotationElementFactory.create(properties);
  4958. if (element.isRenderable) {
  4959. parameters.div.appendChild(element.render());
  4960. }
  4961. }
  4962. },
  4963. /**
  4964. * Update the annotation elements on existing annotation layer.
  4965. *
  4966. * @public
  4967. * @param {AnnotationLayerParameters} parameters
  4968. * @memberof AnnotationLayer
  4969. */
  4970. update: function AnnotationLayer_update(parameters) {
  4971. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4972. var data = parameters.annotations[i];
  4973. var element = parameters.div.querySelector('[data-annotation-id="' + data.id + '"]');
  4974. if (element) {
  4975. CustomStyle.setProp('transform', element, 'matrix(' + parameters.viewport.transform.join(',') + ')');
  4976. }
  4977. }
  4978. parameters.div.removeAttribute('hidden');
  4979. }
  4980. };
  4981. }();
  4982. exports.AnnotationLayer = AnnotationLayer;
  4983. }));
  4984. (function (root, factory) {
  4985. factory(root.pdfjsDisplayTextLayer = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils);
  4986. }(this, function (exports, sharedUtil, displayDOMUtils) {
  4987. var Util = sharedUtil.Util;
  4988. var createPromiseCapability = sharedUtil.createPromiseCapability;
  4989. var CustomStyle = displayDOMUtils.CustomStyle;
  4990. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  4991. /**
  4992. * Text layer render parameters.
  4993. *
  4994. * @typedef {Object} TextLayerRenderParameters
  4995. * @property {TextContent} textContent - Text content to render (the object is
  4996. * returned by the page's getTextContent() method).
  4997. * @property {HTMLElement} container - HTML element that will contain text runs.
  4998. * @property {PageViewport} viewport - The target viewport to properly
  4999. * layout the text runs.
  5000. * @property {Array} textDivs - (optional) HTML elements that are correspond
  5001. * the text items of the textContent input. This is output and shall be
  5002. * initially be set to empty array.
  5003. * @property {number} timeout - (optional) Delay in milliseconds before
  5004. * rendering of the text runs occurs.
  5005. * @property {boolean} enhanceTextSelection - (optional) Whether to turn on the
  5006. * text selection enhancement.
  5007. */
  5008. var renderTextLayer = function renderTextLayerClosure() {
  5009. var MAX_TEXT_DIVS_TO_RENDER = 100000;
  5010. var NonWhitespaceRegexp = /\S/;
  5011. function isAllWhitespace(str) {
  5012. return !NonWhitespaceRegexp.test(str);
  5013. }
  5014. // Text layers may contain many thousand div's, and using `styleBuf` avoids
  5015. // creating many intermediate strings when building their 'style' properties.
  5016. var styleBuf = [
  5017. 'left: ',
  5018. 0,
  5019. 'px; top: ',
  5020. 0,
  5021. 'px; font-size: ',
  5022. 0,
  5023. 'px; font-family: ',
  5024. '',
  5025. ';'
  5026. ];
  5027. function appendText(task, geom, styles) {
  5028. // Initialize all used properties to keep the caches monomorphic.
  5029. var textDiv = document.createElement('div');
  5030. var textDivProperties = {
  5031. style: null,
  5032. angle: 0,
  5033. canvasWidth: 0,
  5034. isWhitespace: false,
  5035. originalTransform: null,
  5036. paddingBottom: 0,
  5037. paddingLeft: 0,
  5038. paddingRight: 0,
  5039. paddingTop: 0,
  5040. scale: 1
  5041. };
  5042. task._textDivs.push(textDiv);
  5043. if (isAllWhitespace(geom.str)) {
  5044. textDivProperties.isWhitespace = true;
  5045. task._textDivProperties.set(textDiv, textDivProperties);
  5046. return;
  5047. }
  5048. var tx = Util.transform(task._viewport.transform, geom.transform);
  5049. var angle = Math.atan2(tx[1], tx[0]);
  5050. var style = styles[geom.fontName];
  5051. if (style.vertical) {
  5052. angle += Math.PI / 2;
  5053. }
  5054. var fontHeight = Math.sqrt(tx[2] * tx[2] + tx[3] * tx[3]);
  5055. var fontAscent = fontHeight;
  5056. if (style.ascent) {
  5057. fontAscent = style.ascent * fontAscent;
  5058. } else if (style.descent) {
  5059. fontAscent = (1 + style.descent) * fontAscent;
  5060. }
  5061. var left;
  5062. var top;
  5063. if (angle === 0) {
  5064. left = tx[4];
  5065. top = tx[5] - fontAscent;
  5066. } else {
  5067. left = tx[4] + fontAscent * Math.sin(angle);
  5068. top = tx[5] - fontAscent * Math.cos(angle);
  5069. }
  5070. styleBuf[1] = left;
  5071. styleBuf[3] = top;
  5072. styleBuf[5] = fontHeight;
  5073. styleBuf[7] = style.fontFamily;
  5074. textDivProperties.style = styleBuf.join('');
  5075. textDiv.setAttribute('style', textDivProperties.style);
  5076. textDiv.textContent = geom.str;
  5077. // |fontName| is only used by the Font Inspector. This test will succeed
  5078. // when e.g. the Font Inspector is off but the Stepper is on, but it's
  5079. // not worth the effort to do a more accurate test. We only use `dataset`
  5080. // here to make the font name available for the debugger.
  5081. if (getDefaultSetting('pdfBug')) {
  5082. textDiv.dataset.fontName = geom.fontName;
  5083. }
  5084. if (angle !== 0) {
  5085. textDivProperties.angle = angle * (180 / Math.PI);
  5086. }
  5087. // We don't bother scaling single-char text divs, because it has very
  5088. // little effect on text highlighting. This makes scrolling on docs with
  5089. // lots of such divs a lot faster.
  5090. if (geom.str.length > 1) {
  5091. if (style.vertical) {
  5092. textDivProperties.canvasWidth = geom.height * task._viewport.scale;
  5093. } else {
  5094. textDivProperties.canvasWidth = geom.width * task._viewport.scale;
  5095. }
  5096. }
  5097. task._textDivProperties.set(textDiv, textDivProperties);
  5098. if (task._enhanceTextSelection) {
  5099. var angleCos = 1, angleSin = 0;
  5100. if (angle !== 0) {
  5101. angleCos = Math.cos(angle);
  5102. angleSin = Math.sin(angle);
  5103. }
  5104. var divWidth = (style.vertical ? geom.height : geom.width) * task._viewport.scale;
  5105. var divHeight = fontHeight;
  5106. var m, b;
  5107. if (angle !== 0) {
  5108. m = [
  5109. angleCos,
  5110. angleSin,
  5111. -angleSin,
  5112. angleCos,
  5113. left,
  5114. top
  5115. ];
  5116. b = Util.getAxialAlignedBoundingBox([
  5117. 0,
  5118. 0,
  5119. divWidth,
  5120. divHeight
  5121. ], m);
  5122. } else {
  5123. b = [
  5124. left,
  5125. top,
  5126. left + divWidth,
  5127. top + divHeight
  5128. ];
  5129. }
  5130. task._bounds.push({
  5131. left: b[0],
  5132. top: b[1],
  5133. right: b[2],
  5134. bottom: b[3],
  5135. div: textDiv,
  5136. size: [
  5137. divWidth,
  5138. divHeight
  5139. ],
  5140. m: m
  5141. });
  5142. }
  5143. }
  5144. function render(task) {
  5145. if (task._canceled) {
  5146. return;
  5147. }
  5148. var textLayerFrag = task._container;
  5149. var textDivs = task._textDivs;
  5150. var capability = task._capability;
  5151. var textDivsLength = textDivs.length;
  5152. // No point in rendering many divs as it would make the browser
  5153. // unusable even after the divs are rendered.
  5154. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  5155. task._renderingDone = true;
  5156. capability.resolve();
  5157. return;
  5158. }
  5159. var canvas = document.createElement('canvas');
  5160. canvas.mozOpaque = true;
  5161. var ctx = canvas.getContext('2d', { alpha: false });
  5162. var lastFontSize;
  5163. var lastFontFamily;
  5164. for (var i = 0; i < textDivsLength; i++) {
  5165. var textDiv = textDivs[i];
  5166. var textDivProperties = task._textDivProperties.get(textDiv);
  5167. if (textDivProperties.isWhitespace) {
  5168. continue;
  5169. }
  5170. var fontSize = textDiv.style.fontSize;
  5171. var fontFamily = textDiv.style.fontFamily;
  5172. // Only build font string and set to context if different from last.
  5173. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {
  5174. ctx.font = fontSize + ' ' + fontFamily;
  5175. lastFontSize = fontSize;
  5176. lastFontFamily = fontFamily;
  5177. }
  5178. var width = ctx.measureText(textDiv.textContent).width;
  5179. textLayerFrag.appendChild(textDiv);
  5180. var transform = '';
  5181. if (textDivProperties.canvasWidth !== 0 && width > 0) {
  5182. textDivProperties.scale = textDivProperties.canvasWidth / width;
  5183. transform = 'scaleX(' + textDivProperties.scale + ')';
  5184. }
  5185. if (textDivProperties.angle !== 0) {
  5186. transform = 'rotate(' + textDivProperties.angle + 'deg) ' + transform;
  5187. }
  5188. if (transform !== '') {
  5189. textDivProperties.originalTransform = transform;
  5190. CustomStyle.setProp('transform', textDiv, transform);
  5191. }
  5192. task._textDivProperties.set(textDiv, textDivProperties);
  5193. }
  5194. task._renderingDone = true;
  5195. capability.resolve();
  5196. }
  5197. function expand(task) {
  5198. var bounds = task._bounds;
  5199. var viewport = task._viewport;
  5200. var expanded = expandBounds(viewport.width, viewport.height, bounds);
  5201. for (var i = 0; i < expanded.length; i++) {
  5202. var div = bounds[i].div;
  5203. var divProperties = task._textDivProperties.get(div);
  5204. if (divProperties.angle === 0) {
  5205. divProperties.paddingLeft = bounds[i].left - expanded[i].left;
  5206. divProperties.paddingTop = bounds[i].top - expanded[i].top;
  5207. divProperties.paddingRight = expanded[i].right - bounds[i].right;
  5208. divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom;
  5209. task._textDivProperties.set(div, divProperties);
  5210. continue;
  5211. }
  5212. // Box is rotated -- trying to find padding so rotated div will not
  5213. // exceed its expanded bounds.
  5214. var e = expanded[i], b = bounds[i];
  5215. var m = b.m, c = m[0], s = m[1];
  5216. // Finding intersections with expanded box.
  5217. var points = [
  5218. [
  5219. 0,
  5220. 0
  5221. ],
  5222. [
  5223. 0,
  5224. b.size[1]
  5225. ],
  5226. [
  5227. b.size[0],
  5228. 0
  5229. ],
  5230. b.size
  5231. ];
  5232. var ts = new Float64Array(64);
  5233. points.forEach(function (p, i) {
  5234. var t = Util.applyTransform(p, m);
  5235. ts[i + 0] = c && (e.left - t[0]) / c;
  5236. ts[i + 4] = s && (e.top - t[1]) / s;
  5237. ts[i + 8] = c && (e.right - t[0]) / c;
  5238. ts[i + 12] = s && (e.bottom - t[1]) / s;
  5239. ts[i + 16] = s && (e.left - t[0]) / -s;
  5240. ts[i + 20] = c && (e.top - t[1]) / c;
  5241. ts[i + 24] = s && (e.right - t[0]) / -s;
  5242. ts[i + 28] = c && (e.bottom - t[1]) / c;
  5243. ts[i + 32] = c && (e.left - t[0]) / -c;
  5244. ts[i + 36] = s && (e.top - t[1]) / -s;
  5245. ts[i + 40] = c && (e.right - t[0]) / -c;
  5246. ts[i + 44] = s && (e.bottom - t[1]) / -s;
  5247. ts[i + 48] = s && (e.left - t[0]) / s;
  5248. ts[i + 52] = c && (e.top - t[1]) / -c;
  5249. ts[i + 56] = s && (e.right - t[0]) / s;
  5250. ts[i + 60] = c && (e.bottom - t[1]) / -c;
  5251. });
  5252. var findPositiveMin = function (ts, offset, count) {
  5253. var result = 0;
  5254. for (var i = 0; i < count; i++) {
  5255. var t = ts[offset++];
  5256. if (t > 0) {
  5257. result = result ? Math.min(t, result) : t;
  5258. }
  5259. }
  5260. return result;
  5261. };
  5262. // Not based on math, but to simplify calculations, using cos and sin
  5263. // absolute values to not exceed the box (it can but insignificantly).
  5264. var boxScale = 1 + Math.min(Math.abs(c), Math.abs(s));
  5265. divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale;
  5266. divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale;
  5267. divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale;
  5268. divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale;
  5269. task._textDivProperties.set(div, divProperties);
  5270. }
  5271. }
  5272. function expandBounds(width, height, boxes) {
  5273. var bounds = boxes.map(function (box, i) {
  5274. return {
  5275. x1: box.left,
  5276. y1: box.top,
  5277. x2: box.right,
  5278. y2: box.bottom,
  5279. index: i,
  5280. x1New: undefined,
  5281. x2New: undefined
  5282. };
  5283. });
  5284. expandBoundsLTR(width, bounds);
  5285. var expanded = new Array(boxes.length);
  5286. bounds.forEach(function (b) {
  5287. var i = b.index;
  5288. expanded[i] = {
  5289. left: b.x1New,
  5290. top: 0,
  5291. right: b.x2New,
  5292. bottom: 0
  5293. };
  5294. });
  5295. // Rotating on 90 degrees and extending extended boxes. Reusing the bounds
  5296. // array and objects.
  5297. boxes.map(function (box, i) {
  5298. var e = expanded[i], b = bounds[i];
  5299. b.x1 = box.top;
  5300. b.y1 = width - e.right;
  5301. b.x2 = box.bottom;
  5302. b.y2 = width - e.left;
  5303. b.index = i;
  5304. b.x1New = undefined;
  5305. b.x2New = undefined;
  5306. });
  5307. expandBoundsLTR(height, bounds);
  5308. bounds.forEach(function (b) {
  5309. var i = b.index;
  5310. expanded[i].top = b.x1New;
  5311. expanded[i].bottom = b.x2New;
  5312. });
  5313. return expanded;
  5314. }
  5315. function expandBoundsLTR(width, bounds) {
  5316. // Sorting by x1 coordinate and walk by the bounds in the same order.
  5317. bounds.sort(function (a, b) {
  5318. return a.x1 - b.x1 || a.index - b.index;
  5319. });
  5320. // First we see on the horizon is a fake boundary.
  5321. var fakeBoundary = {
  5322. x1: -Infinity,
  5323. y1: -Infinity,
  5324. x2: 0,
  5325. y2: Infinity,
  5326. index: -1,
  5327. x1New: 0,
  5328. x2New: 0
  5329. };
  5330. var horizon = [{
  5331. start: -Infinity,
  5332. end: Infinity,
  5333. boundary: fakeBoundary
  5334. }];
  5335. bounds.forEach(function (boundary) {
  5336. // Searching for the affected part of horizon.
  5337. // TODO red-black tree or simple binary search
  5338. var i = 0;
  5339. while (i < horizon.length && horizon[i].end <= boundary.y1) {
  5340. i++;
  5341. }
  5342. var j = horizon.length - 1;
  5343. while (j >= 0 && horizon[j].start >= boundary.y2) {
  5344. j--;
  5345. }
  5346. var horizonPart, affectedBoundary;
  5347. var q, k, maxXNew = -Infinity;
  5348. for (q = i; q <= j; q++) {
  5349. horizonPart = horizon[q];
  5350. affectedBoundary = horizonPart.boundary;
  5351. var xNew;
  5352. if (affectedBoundary.x2 > boundary.x1) {
  5353. // In the middle of the previous element, new x shall be at the
  5354. // boundary start. Extending if further if the affected bondary
  5355. // placed on top of the current one.
  5356. xNew = affectedBoundary.index > boundary.index ? affectedBoundary.x1New : boundary.x1;
  5357. } else if (affectedBoundary.x2New === undefined) {
  5358. // We have some space in between, new x in middle will be a fair
  5359. // choice.
  5360. xNew = (affectedBoundary.x2 + boundary.x1) / 2;
  5361. } else {
  5362. // Affected boundary has x2new set, using it as new x.
  5363. xNew = affectedBoundary.x2New;
  5364. }
  5365. if (xNew > maxXNew) {
  5366. maxXNew = xNew;
  5367. }
  5368. }
  5369. // Set new x1 for current boundary.
  5370. boundary.x1New = maxXNew;
  5371. // Adjusts new x2 for the affected boundaries.
  5372. for (q = i; q <= j; q++) {
  5373. horizonPart = horizon[q];
  5374. affectedBoundary = horizonPart.boundary;
  5375. if (affectedBoundary.x2New === undefined) {
  5376. // Was not set yet, choosing new x if possible.
  5377. if (affectedBoundary.x2 > boundary.x1) {
  5378. // Current and affected boundaries intersect. If affected boundary
  5379. // is placed on top of the current, shrinking the affected.
  5380. if (affectedBoundary.index > boundary.index) {
  5381. affectedBoundary.x2New = affectedBoundary.x2;
  5382. }
  5383. } else {
  5384. affectedBoundary.x2New = maxXNew;
  5385. }
  5386. } else if (affectedBoundary.x2New > maxXNew) {
  5387. // Affected boundary is touching new x, pushing it back.
  5388. affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2);
  5389. }
  5390. }
  5391. // Fixing the horizon.
  5392. var changedHorizon = [], lastBoundary = null;
  5393. for (q = i; q <= j; q++) {
  5394. horizonPart = horizon[q];
  5395. affectedBoundary = horizonPart.boundary;
  5396. // Checking which boundary will be visible.
  5397. var useBoundary = affectedBoundary.x2 > boundary.x2 ? affectedBoundary : boundary;
  5398. if (lastBoundary === useBoundary) {
  5399. // Merging with previous.
  5400. changedHorizon[changedHorizon.length - 1].end = horizonPart.end;
  5401. } else {
  5402. changedHorizon.push({
  5403. start: horizonPart.start,
  5404. end: horizonPart.end,
  5405. boundary: useBoundary
  5406. });
  5407. lastBoundary = useBoundary;
  5408. }
  5409. }
  5410. if (horizon[i].start < boundary.y1) {
  5411. changedHorizon[0].start = boundary.y1;
  5412. changedHorizon.unshift({
  5413. start: horizon[i].start,
  5414. end: boundary.y1,
  5415. boundary: horizon[i].boundary
  5416. });
  5417. }
  5418. if (boundary.y2 < horizon[j].end) {
  5419. changedHorizon[changedHorizon.length - 1].end = boundary.y2;
  5420. changedHorizon.push({
  5421. start: boundary.y2,
  5422. end: horizon[j].end,
  5423. boundary: horizon[j].boundary
  5424. });
  5425. }
  5426. // Set x2 new of boundary that is no longer visible (see overlapping case
  5427. // above).
  5428. // TODO more efficient, e.g. via reference counting.
  5429. for (q = i; q <= j; q++) {
  5430. horizonPart = horizon[q];
  5431. affectedBoundary = horizonPart.boundary;
  5432. if (affectedBoundary.x2New !== undefined) {
  5433. continue;
  5434. }
  5435. var used = false;
  5436. for (k = i - 1; !used && k >= 0 && horizon[k].start >= affectedBoundary.y1; k--) {
  5437. used = horizon[k].boundary === affectedBoundary;
  5438. }
  5439. for (k = j + 1; !used && k < horizon.length && horizon[k].end <= affectedBoundary.y2; k++) {
  5440. used = horizon[k].boundary === affectedBoundary;
  5441. }
  5442. for (k = 0; !used && k < changedHorizon.length; k++) {
  5443. used = changedHorizon[k].boundary === affectedBoundary;
  5444. }
  5445. if (!used) {
  5446. affectedBoundary.x2New = maxXNew;
  5447. }
  5448. }
  5449. Array.prototype.splice.apply(horizon, [
  5450. i,
  5451. j - i + 1
  5452. ].concat(changedHorizon));
  5453. });
  5454. // Set new x2 for all unset boundaries.
  5455. horizon.forEach(function (horizonPart) {
  5456. var affectedBoundary = horizonPart.boundary;
  5457. if (affectedBoundary.x2New === undefined) {
  5458. affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);
  5459. }
  5460. });
  5461. }
  5462. /**
  5463. * Text layer rendering task.
  5464. *
  5465. * @param {TextContent} textContent
  5466. * @param {HTMLElement} container
  5467. * @param {PageViewport} viewport
  5468. * @param {Array} textDivs
  5469. * @param {boolean} enhanceTextSelection
  5470. * @private
  5471. */
  5472. function TextLayerRenderTask(textContent, container, viewport, textDivs, enhanceTextSelection) {
  5473. this._textContent = textContent;
  5474. this._container = container;
  5475. this._viewport = viewport;
  5476. this._textDivs = textDivs || [];
  5477. this._textDivProperties = new WeakMap();
  5478. this._renderingDone = false;
  5479. this._canceled = false;
  5480. this._capability = createPromiseCapability();
  5481. this._renderTimer = null;
  5482. this._bounds = [];
  5483. this._enhanceTextSelection = !!enhanceTextSelection;
  5484. }
  5485. TextLayerRenderTask.prototype = {
  5486. get promise() {
  5487. return this._capability.promise;
  5488. },
  5489. cancel: function TextLayer_cancel() {
  5490. this._canceled = true;
  5491. if (this._renderTimer !== null) {
  5492. clearTimeout(this._renderTimer);
  5493. this._renderTimer = null;
  5494. }
  5495. this._capability.reject('canceled');
  5496. },
  5497. _render: function TextLayer_render(timeout) {
  5498. var textItems = this._textContent.items;
  5499. var textStyles = this._textContent.styles;
  5500. for (var i = 0, len = textItems.length; i < len; i++) {
  5501. appendText(this, textItems[i], textStyles);
  5502. }
  5503. if (!timeout) {
  5504. // Render right away
  5505. render(this);
  5506. } else {
  5507. // Schedule
  5508. var self = this;
  5509. this._renderTimer = setTimeout(function () {
  5510. render(self);
  5511. self._renderTimer = null;
  5512. }, timeout);
  5513. }
  5514. },
  5515. expandTextDivs: function TextLayer_expandTextDivs(expandDivs) {
  5516. if (!this._enhanceTextSelection || !this._renderingDone) {
  5517. return;
  5518. }
  5519. if (this._bounds !== null) {
  5520. expand(this);
  5521. this._bounds = null;
  5522. }
  5523. for (var i = 0, ii = this._textDivs.length; i < ii; i++) {
  5524. var div = this._textDivs[i];
  5525. var divProperties = this._textDivProperties.get(div);
  5526. if (divProperties.isWhitespace) {
  5527. continue;
  5528. }
  5529. if (expandDivs) {
  5530. var transform = '', padding = '';
  5531. if (divProperties.scale !== 1) {
  5532. transform = 'scaleX(' + divProperties.scale + ')';
  5533. }
  5534. if (divProperties.angle !== 0) {
  5535. transform = 'rotate(' + divProperties.angle + 'deg) ' + transform;
  5536. }
  5537. if (divProperties.paddingLeft !== 0) {
  5538. padding += ' padding-left: ' + divProperties.paddingLeft / divProperties.scale + 'px;';
  5539. transform += ' translateX(' + -divProperties.paddingLeft / divProperties.scale + 'px)';
  5540. }
  5541. if (divProperties.paddingTop !== 0) {
  5542. padding += ' padding-top: ' + divProperties.paddingTop + 'px;';
  5543. transform += ' translateY(' + -divProperties.paddingTop + 'px)';
  5544. }
  5545. if (divProperties.paddingRight !== 0) {
  5546. padding += ' padding-right: ' + divProperties.paddingRight / divProperties.scale + 'px;';
  5547. }
  5548. if (divProperties.paddingBottom !== 0) {
  5549. padding += ' padding-bottom: ' + divProperties.paddingBottom + 'px;';
  5550. }
  5551. if (padding !== '') {
  5552. div.setAttribute('style', divProperties.style + padding);
  5553. }
  5554. if (transform !== '') {
  5555. CustomStyle.setProp('transform', div, transform);
  5556. }
  5557. } else {
  5558. div.style.padding = 0;
  5559. CustomStyle.setProp('transform', div, divProperties.originalTransform || '');
  5560. }
  5561. }
  5562. }
  5563. };
  5564. /**
  5565. * Starts rendering of the text layer.
  5566. *
  5567. * @param {TextLayerRenderParameters} renderParameters
  5568. * @returns {TextLayerRenderTask}
  5569. */
  5570. function renderTextLayer(renderParameters) {
  5571. var task = new TextLayerRenderTask(renderParameters.textContent, renderParameters.container, renderParameters.viewport, renderParameters.textDivs, renderParameters.enhanceTextSelection);
  5572. task._render(renderParameters.timeout);
  5573. return task;
  5574. }
  5575. return renderTextLayer;
  5576. }();
  5577. exports.renderTextLayer = renderTextLayer;
  5578. }));
  5579. (function (root, factory) {
  5580. factory(root.pdfjsDisplayWebGL = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils);
  5581. }(this, function (exports, sharedUtil, displayDOMUtils) {
  5582. var shadow = sharedUtil.shadow;
  5583. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  5584. var WebGLUtils = function WebGLUtilsClosure() {
  5585. function loadShader(gl, code, shaderType) {
  5586. var shader = gl.createShader(shaderType);
  5587. gl.shaderSource(shader, code);
  5588. gl.compileShader(shader);
  5589. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  5590. if (!compiled) {
  5591. var errorMsg = gl.getShaderInfoLog(shader);
  5592. throw new Error('Error during shader compilation: ' + errorMsg);
  5593. }
  5594. return shader;
  5595. }
  5596. function createVertexShader(gl, code) {
  5597. return loadShader(gl, code, gl.VERTEX_SHADER);
  5598. }
  5599. function createFragmentShader(gl, code) {
  5600. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  5601. }
  5602. function createProgram(gl, shaders) {
  5603. var program = gl.createProgram();
  5604. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  5605. gl.attachShader(program, shaders[i]);
  5606. }
  5607. gl.linkProgram(program);
  5608. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  5609. if (!linked) {
  5610. var errorMsg = gl.getProgramInfoLog(program);
  5611. throw new Error('Error during program linking: ' + errorMsg);
  5612. }
  5613. return program;
  5614. }
  5615. function createTexture(gl, image, textureId) {
  5616. gl.activeTexture(textureId);
  5617. var texture = gl.createTexture();
  5618. gl.bindTexture(gl.TEXTURE_2D, texture);
  5619. // Set the parameters so we can render any size image.
  5620. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5621. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5622. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  5623. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  5624. // Upload the image into the texture.
  5625. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  5626. return texture;
  5627. }
  5628. var currentGL, currentCanvas;
  5629. function generateGL() {
  5630. if (currentGL) {
  5631. return;
  5632. }
  5633. currentCanvas = document.createElement('canvas');
  5634. currentGL = currentCanvas.getContext('webgl', { premultipliedalpha: false });
  5635. }
  5636. var smaskVertexShaderCode = '\
  5637. attribute vec2 a_position; \
  5638. attribute vec2 a_texCoord; \
  5639. \
  5640. uniform vec2 u_resolution; \
  5641. \
  5642. varying vec2 v_texCoord; \
  5643. \
  5644. void main() { \
  5645. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  5646. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5647. \
  5648. v_texCoord = a_texCoord; \
  5649. } ';
  5650. var smaskFragmentShaderCode = '\
  5651. precision mediump float; \
  5652. \
  5653. uniform vec4 u_backdrop; \
  5654. uniform int u_subtype; \
  5655. uniform sampler2D u_image; \
  5656. uniform sampler2D u_mask; \
  5657. \
  5658. varying vec2 v_texCoord; \
  5659. \
  5660. void main() { \
  5661. vec4 imageColor = texture2D(u_image, v_texCoord); \
  5662. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  5663. if (u_backdrop.a > 0.0) { \
  5664. maskColor.rgb = maskColor.rgb * maskColor.a + \
  5665. u_backdrop.rgb * (1.0 - maskColor.a); \
  5666. } \
  5667. float lum; \
  5668. if (u_subtype == 0) { \
  5669. lum = maskColor.a; \
  5670. } else { \
  5671. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  5672. maskColor.b * 0.11; \
  5673. } \
  5674. imageColor.a *= lum; \
  5675. imageColor.rgb *= imageColor.a; \
  5676. gl_FragColor = imageColor; \
  5677. } ';
  5678. var smaskCache = null;
  5679. function initSmaskGL() {
  5680. var canvas, gl;
  5681. generateGL();
  5682. canvas = currentCanvas;
  5683. currentCanvas = null;
  5684. gl = currentGL;
  5685. currentGL = null;
  5686. // setup a GLSL program
  5687. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  5688. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  5689. var program = createProgram(gl, [
  5690. vertexShader,
  5691. fragmentShader
  5692. ]);
  5693. gl.useProgram(program);
  5694. var cache = {};
  5695. cache.gl = gl;
  5696. cache.canvas = canvas;
  5697. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5698. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5699. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  5700. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  5701. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  5702. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  5703. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  5704. // provide texture coordinates for the rectangle.
  5705. var texCoordBuffer = gl.createBuffer();
  5706. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  5707. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5708. 0.0,
  5709. 0.0,
  5710. 1.0,
  5711. 0.0,
  5712. 0.0,
  5713. 1.0,
  5714. 0.0,
  5715. 1.0,
  5716. 1.0,
  5717. 0.0,
  5718. 1.0,
  5719. 1.0
  5720. ]), gl.STATIC_DRAW);
  5721. gl.enableVertexAttribArray(texCoordLocation);
  5722. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  5723. gl.uniform1i(texLayerLocation, 0);
  5724. gl.uniform1i(texMaskLocation, 1);
  5725. smaskCache = cache;
  5726. }
  5727. function composeSMask(layer, mask, properties) {
  5728. var width = layer.width, height = layer.height;
  5729. if (!smaskCache) {
  5730. initSmaskGL();
  5731. }
  5732. var cache = smaskCache, canvas = cache.canvas, gl = cache.gl;
  5733. canvas.width = width;
  5734. canvas.height = height;
  5735. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5736. gl.uniform2f(cache.resolutionLocation, width, height);
  5737. if (properties.backdrop) {
  5738. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0], properties.backdrop[1], properties.backdrop[2], 1);
  5739. } else {
  5740. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  5741. }
  5742. gl.uniform1i(cache.subtypeLocation, properties.subtype === 'Luminosity' ? 1 : 0);
  5743. // Create a textures
  5744. var texture = createTexture(gl, layer, gl.TEXTURE0);
  5745. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  5746. // Create a buffer and put a single clipspace rectangle in
  5747. // it (2 triangles)
  5748. var buffer = gl.createBuffer();
  5749. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  5750. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5751. 0,
  5752. 0,
  5753. width,
  5754. 0,
  5755. 0,
  5756. height,
  5757. 0,
  5758. height,
  5759. width,
  5760. 0,
  5761. width,
  5762. height
  5763. ]), gl.STATIC_DRAW);
  5764. gl.enableVertexAttribArray(cache.positionLocation);
  5765. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5766. // draw
  5767. gl.clearColor(0, 0, 0, 0);
  5768. gl.enable(gl.BLEND);
  5769. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  5770. gl.clear(gl.COLOR_BUFFER_BIT);
  5771. gl.drawArrays(gl.TRIANGLES, 0, 6);
  5772. gl.flush();
  5773. gl.deleteTexture(texture);
  5774. gl.deleteTexture(maskTexture);
  5775. gl.deleteBuffer(buffer);
  5776. return canvas;
  5777. }
  5778. var figuresVertexShaderCode = '\
  5779. attribute vec2 a_position; \
  5780. attribute vec3 a_color; \
  5781. \
  5782. uniform vec2 u_resolution; \
  5783. uniform vec2 u_scale; \
  5784. uniform vec2 u_offset; \
  5785. \
  5786. varying vec4 v_color; \
  5787. \
  5788. void main() { \
  5789. vec2 position = (a_position + u_offset) * u_scale; \
  5790. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  5791. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5792. \
  5793. v_color = vec4(a_color / 255.0, 1.0); \
  5794. } ';
  5795. var figuresFragmentShaderCode = '\
  5796. precision mediump float; \
  5797. \
  5798. varying vec4 v_color; \
  5799. \
  5800. void main() { \
  5801. gl_FragColor = v_color; \
  5802. } ';
  5803. var figuresCache = null;
  5804. function initFiguresGL() {
  5805. var canvas, gl;
  5806. generateGL();
  5807. canvas = currentCanvas;
  5808. currentCanvas = null;
  5809. gl = currentGL;
  5810. currentGL = null;
  5811. // setup a GLSL program
  5812. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  5813. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  5814. var program = createProgram(gl, [
  5815. vertexShader,
  5816. fragmentShader
  5817. ]);
  5818. gl.useProgram(program);
  5819. var cache = {};
  5820. cache.gl = gl;
  5821. cache.canvas = canvas;
  5822. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5823. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  5824. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  5825. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5826. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  5827. figuresCache = cache;
  5828. }
  5829. function drawFigures(width, height, backgroundColor, figures, context) {
  5830. if (!figuresCache) {
  5831. initFiguresGL();
  5832. }
  5833. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  5834. canvas.width = width;
  5835. canvas.height = height;
  5836. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5837. gl.uniform2f(cache.resolutionLocation, width, height);
  5838. // count triangle points
  5839. var count = 0;
  5840. var i, ii, rows;
  5841. for (i = 0, ii = figures.length; i < ii; i++) {
  5842. switch (figures[i].type) {
  5843. case 'lattice':
  5844. rows = figures[i].coords.length / figures[i].verticesPerRow | 0;
  5845. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  5846. break;
  5847. case 'triangles':
  5848. count += figures[i].coords.length;
  5849. break;
  5850. }
  5851. }
  5852. // transfer data
  5853. var coords = new Float32Array(count * 2);
  5854. var colors = new Uint8Array(count * 3);
  5855. var coordsMap = context.coords, colorsMap = context.colors;
  5856. var pIndex = 0, cIndex = 0;
  5857. for (i = 0, ii = figures.length; i < ii; i++) {
  5858. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  5859. switch (figure.type) {
  5860. case 'lattice':
  5861. var cols = figure.verticesPerRow;
  5862. rows = ps.length / cols | 0;
  5863. for (var row = 1; row < rows; row++) {
  5864. var offset = row * cols + 1;
  5865. for (var col = 1; col < cols; col++, offset++) {
  5866. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  5867. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  5868. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  5869. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  5870. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  5871. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  5872. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  5873. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  5874. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  5875. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  5876. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  5877. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  5878. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  5879. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  5880. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  5881. coords[pIndex + 6] = coords[pIndex + 2];
  5882. coords[pIndex + 7] = coords[pIndex + 3];
  5883. coords[pIndex + 8] = coords[pIndex + 4];
  5884. coords[pIndex + 9] = coords[pIndex + 5];
  5885. coords[pIndex + 10] = coordsMap[ps[offset]];
  5886. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  5887. colors[cIndex + 9] = colors[cIndex + 3];
  5888. colors[cIndex + 10] = colors[cIndex + 4];
  5889. colors[cIndex + 11] = colors[cIndex + 5];
  5890. colors[cIndex + 12] = colors[cIndex + 6];
  5891. colors[cIndex + 13] = colors[cIndex + 7];
  5892. colors[cIndex + 14] = colors[cIndex + 8];
  5893. colors[cIndex + 15] = colorsMap[cs[offset]];
  5894. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  5895. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  5896. pIndex += 12;
  5897. cIndex += 18;
  5898. }
  5899. }
  5900. break;
  5901. case 'triangles':
  5902. for (var j = 0, jj = ps.length; j < jj; j++) {
  5903. coords[pIndex] = coordsMap[ps[j]];
  5904. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  5905. colors[cIndex] = colorsMap[cs[j]];
  5906. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  5907. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  5908. pIndex += 2;
  5909. cIndex += 3;
  5910. }
  5911. break;
  5912. }
  5913. }
  5914. // draw
  5915. if (backgroundColor) {
  5916. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255, backgroundColor[2] / 255, 1.0);
  5917. } else {
  5918. gl.clearColor(0, 0, 0, 0);
  5919. }
  5920. gl.clear(gl.COLOR_BUFFER_BIT);
  5921. var coordsBuffer = gl.createBuffer();
  5922. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  5923. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  5924. gl.enableVertexAttribArray(cache.positionLocation);
  5925. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5926. var colorsBuffer = gl.createBuffer();
  5927. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  5928. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  5929. gl.enableVertexAttribArray(cache.colorLocation);
  5930. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false, 0, 0);
  5931. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  5932. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  5933. gl.drawArrays(gl.TRIANGLES, 0, count);
  5934. gl.flush();
  5935. gl.deleteBuffer(coordsBuffer);
  5936. gl.deleteBuffer(colorsBuffer);
  5937. return canvas;
  5938. }
  5939. function cleanup() {
  5940. if (smaskCache && smaskCache.canvas) {
  5941. smaskCache.canvas.width = 0;
  5942. smaskCache.canvas.height = 0;
  5943. }
  5944. if (figuresCache && figuresCache.canvas) {
  5945. figuresCache.canvas.width = 0;
  5946. figuresCache.canvas.height = 0;
  5947. }
  5948. smaskCache = null;
  5949. figuresCache = null;
  5950. }
  5951. return {
  5952. get isEnabled() {
  5953. if (getDefaultSetting('disableWebGL')) {
  5954. return false;
  5955. }
  5956. var enabled = false;
  5957. try {
  5958. generateGL();
  5959. enabled = !!currentGL;
  5960. } catch (e) {
  5961. }
  5962. return shadow(this, 'isEnabled', enabled);
  5963. },
  5964. composeSMask: composeSMask,
  5965. drawFigures: drawFigures,
  5966. clear: cleanup
  5967. };
  5968. }();
  5969. exports.WebGLUtils = WebGLUtils;
  5970. }));
  5971. (function (root, factory) {
  5972. factory(root.pdfjsDisplayPatternHelper = {}, root.pdfjsSharedUtil, root.pdfjsDisplayWebGL);
  5973. }(this, function (exports, sharedUtil, displayWebGL) {
  5974. var Util = sharedUtil.Util;
  5975. var info = sharedUtil.info;
  5976. var isArray = sharedUtil.isArray;
  5977. var error = sharedUtil.error;
  5978. var WebGLUtils = displayWebGL.WebGLUtils;
  5979. var ShadingIRs = {};
  5980. ShadingIRs.RadialAxial = {
  5981. fromIR: function RadialAxial_fromIR(raw) {
  5982. var type = raw[1];
  5983. var colorStops = raw[2];
  5984. var p0 = raw[3];
  5985. var p1 = raw[4];
  5986. var r0 = raw[5];
  5987. var r1 = raw[6];
  5988. return {
  5989. type: 'Pattern',
  5990. getPattern: function RadialAxial_getPattern(ctx) {
  5991. var grad;
  5992. if (type === 'axial') {
  5993. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  5994. } else if (type === 'radial') {
  5995. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  5996. }
  5997. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  5998. var c = colorStops[i];
  5999. grad.addColorStop(c[0], c[1]);
  6000. }
  6001. return grad;
  6002. }
  6003. };
  6004. }
  6005. };
  6006. var createMeshCanvas = function createMeshCanvasClosure() {
  6007. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  6008. // Very basic Gouraud-shaded triangle rasterization algorithm.
  6009. var coords = context.coords, colors = context.colors;
  6010. var bytes = data.data, rowSize = data.width * 4;
  6011. var tmp;
  6012. if (coords[p1 + 1] > coords[p2 + 1]) {
  6013. tmp = p1;
  6014. p1 = p2;
  6015. p2 = tmp;
  6016. tmp = c1;
  6017. c1 = c2;
  6018. c2 = tmp;
  6019. }
  6020. if (coords[p2 + 1] > coords[p3 + 1]) {
  6021. tmp = p2;
  6022. p2 = p3;
  6023. p3 = tmp;
  6024. tmp = c2;
  6025. c2 = c3;
  6026. c3 = tmp;
  6027. }
  6028. if (coords[p1 + 1] > coords[p2 + 1]) {
  6029. tmp = p1;
  6030. p1 = p2;
  6031. p2 = tmp;
  6032. tmp = c1;
  6033. c1 = c2;
  6034. c2 = tmp;
  6035. }
  6036. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  6037. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  6038. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  6039. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  6040. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  6041. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  6042. if (y1 >= y3) {
  6043. return;
  6044. }
  6045. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  6046. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  6047. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  6048. var minY = Math.round(y1), maxY = Math.round(y3);
  6049. var xa, car, cag, cab;
  6050. var xb, cbr, cbg, cbb;
  6051. var k;
  6052. for (var y = minY; y <= maxY; y++) {
  6053. if (y < y2) {
  6054. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  6055. xa = x1 - (x1 - x2) * k;
  6056. car = c1r - (c1r - c2r) * k;
  6057. cag = c1g - (c1g - c2g) * k;
  6058. cab = c1b - (c1b - c2b) * k;
  6059. } else {
  6060. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  6061. xa = x2 - (x2 - x3) * k;
  6062. car = c2r - (c2r - c3r) * k;
  6063. cag = c2g - (c2g - c3g) * k;
  6064. cab = c2b - (c2b - c3b) * k;
  6065. }
  6066. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  6067. xb = x1 - (x1 - x3) * k;
  6068. cbr = c1r - (c1r - c3r) * k;
  6069. cbg = c1g - (c1g - c3g) * k;
  6070. cbb = c1b - (c1b - c3b) * k;
  6071. var x1_ = Math.round(Math.min(xa, xb));
  6072. var x2_ = Math.round(Math.max(xa, xb));
  6073. var j = rowSize * y + x1_ * 4;
  6074. for (var x = x1_; x <= x2_; x++) {
  6075. k = (xa - x) / (xa - xb);
  6076. k = k < 0 ? 0 : k > 1 ? 1 : k;
  6077. bytes[j++] = car - (car - cbr) * k | 0;
  6078. bytes[j++] = cag - (cag - cbg) * k | 0;
  6079. bytes[j++] = cab - (cab - cbb) * k | 0;
  6080. bytes[j++] = 255;
  6081. }
  6082. }
  6083. }
  6084. function drawFigure(data, figure, context) {
  6085. var ps = figure.coords;
  6086. var cs = figure.colors;
  6087. var i, ii;
  6088. switch (figure.type) {
  6089. case 'lattice':
  6090. var verticesPerRow = figure.verticesPerRow;
  6091. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  6092. var cols = verticesPerRow - 1;
  6093. for (i = 0; i < rows; i++) {
  6094. var q = i * verticesPerRow;
  6095. for (var j = 0; j < cols; j++, q++) {
  6096. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  6097. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  6098. }
  6099. }
  6100. break;
  6101. case 'triangles':
  6102. for (i = 0, ii = ps.length; i < ii; i += 3) {
  6103. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  6104. }
  6105. break;
  6106. default:
  6107. error('illigal figure');
  6108. break;
  6109. }
  6110. }
  6111. function createMeshCanvas(bounds, combinesScale, coords, colors, figures, backgroundColor, cachedCanvases) {
  6112. // we will increase scale on some weird factor to let antialiasing take
  6113. // care of "rough" edges
  6114. var EXPECTED_SCALE = 1.1;
  6115. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  6116. var MAX_PATTERN_SIZE = 3000;
  6117. // 10in @ 300dpi shall be enough
  6118. // We need to keep transparent border around our pattern for fill():
  6119. // createPattern with 'no-repeat' will bleed edges across entire area.
  6120. var BORDER_SIZE = 2;
  6121. var offsetX = Math.floor(bounds[0]);
  6122. var offsetY = Math.floor(bounds[1]);
  6123. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  6124. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  6125. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  6126. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  6127. var scaleX = boundsWidth / width;
  6128. var scaleY = boundsHeight / height;
  6129. var context = {
  6130. coords: coords,
  6131. colors: colors,
  6132. offsetX: -offsetX,
  6133. offsetY: -offsetY,
  6134. scaleX: 1 / scaleX,
  6135. scaleY: 1 / scaleY
  6136. };
  6137. var paddedWidth = width + BORDER_SIZE * 2;
  6138. var paddedHeight = height + BORDER_SIZE * 2;
  6139. var canvas, tmpCanvas, i, ii;
  6140. if (WebGLUtils.isEnabled) {
  6141. canvas = WebGLUtils.drawFigures(width, height, backgroundColor, figures, context);
  6142. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  6143. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight, false);
  6144. tmpCanvas.context.drawImage(canvas, BORDER_SIZE, BORDER_SIZE);
  6145. canvas = tmpCanvas.canvas;
  6146. } else {
  6147. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight, false);
  6148. var tmpCtx = tmpCanvas.context;
  6149. var data = tmpCtx.createImageData(width, height);
  6150. if (backgroundColor) {
  6151. var bytes = data.data;
  6152. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  6153. bytes[i] = backgroundColor[0];
  6154. bytes[i + 1] = backgroundColor[1];
  6155. bytes[i + 2] = backgroundColor[2];
  6156. bytes[i + 3] = 255;
  6157. }
  6158. }
  6159. for (i = 0; i < figures.length; i++) {
  6160. drawFigure(data, figures[i], context);
  6161. }
  6162. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  6163. canvas = tmpCanvas.canvas;
  6164. }
  6165. return {
  6166. canvas: canvas,
  6167. offsetX: offsetX - BORDER_SIZE * scaleX,
  6168. offsetY: offsetY - BORDER_SIZE * scaleY,
  6169. scaleX: scaleX,
  6170. scaleY: scaleY
  6171. };
  6172. }
  6173. return createMeshCanvas;
  6174. }();
  6175. ShadingIRs.Mesh = {
  6176. fromIR: function Mesh_fromIR(raw) {
  6177. //var type = raw[1];
  6178. var coords = raw[2];
  6179. var colors = raw[3];
  6180. var figures = raw[4];
  6181. var bounds = raw[5];
  6182. var matrix = raw[6];
  6183. //var bbox = raw[7];
  6184. var background = raw[8];
  6185. return {
  6186. type: 'Pattern',
  6187. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  6188. var scale;
  6189. if (shadingFill) {
  6190. scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  6191. } else {
  6192. // Obtain scale from matrix and current transformation matrix.
  6193. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  6194. if (matrix) {
  6195. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  6196. scale = [
  6197. scale[0] * matrixScale[0],
  6198. scale[1] * matrixScale[1]
  6199. ];
  6200. }
  6201. }
  6202. // Rasterizing on the main thread since sending/queue large canvases
  6203. // might cause OOM.
  6204. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords, colors, figures, shadingFill ? null : background, owner.cachedCanvases);
  6205. if (!shadingFill) {
  6206. ctx.setTransform.apply(ctx, owner.baseTransform);
  6207. if (matrix) {
  6208. ctx.transform.apply(ctx, matrix);
  6209. }
  6210. }
  6211. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  6212. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  6213. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  6214. }
  6215. };
  6216. }
  6217. };
  6218. ShadingIRs.Dummy = {
  6219. fromIR: function Dummy_fromIR() {
  6220. return {
  6221. type: 'Pattern',
  6222. getPattern: function Dummy_fromIR_getPattern() {
  6223. return 'hotpink';
  6224. }
  6225. };
  6226. }
  6227. };
  6228. function getShadingPatternFromIR(raw) {
  6229. var shadingIR = ShadingIRs[raw[0]];
  6230. if (!shadingIR) {
  6231. error('Unknown IR type: ' + raw[0]);
  6232. }
  6233. return shadingIR.fromIR(raw);
  6234. }
  6235. var TilingPattern = function TilingPatternClosure() {
  6236. var PaintType = {
  6237. COLORED: 1,
  6238. UNCOLORED: 2
  6239. };
  6240. var MAX_PATTERN_SIZE = 3000;
  6241. // 10in @ 300dpi shall be enough
  6242. function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  6243. this.operatorList = IR[2];
  6244. this.matrix = IR[3] || [
  6245. 1,
  6246. 0,
  6247. 0,
  6248. 1,
  6249. 0,
  6250. 0
  6251. ];
  6252. this.bbox = IR[4];
  6253. this.xstep = IR[5];
  6254. this.ystep = IR[6];
  6255. this.paintType = IR[7];
  6256. this.tilingType = IR[8];
  6257. this.color = color;
  6258. this.canvasGraphicsFactory = canvasGraphicsFactory;
  6259. this.baseTransform = baseTransform;
  6260. this.type = 'Pattern';
  6261. this.ctx = ctx;
  6262. }
  6263. TilingPattern.prototype = {
  6264. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  6265. var operatorList = this.operatorList;
  6266. var bbox = this.bbox;
  6267. var xstep = this.xstep;
  6268. var ystep = this.ystep;
  6269. var paintType = this.paintType;
  6270. var tilingType = this.tilingType;
  6271. var color = this.color;
  6272. var canvasGraphicsFactory = this.canvasGraphicsFactory;
  6273. info('TilingType: ' + tilingType);
  6274. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  6275. var topLeft = [
  6276. x0,
  6277. y0
  6278. ];
  6279. // we want the canvas to be as large as the step size
  6280. var botRight = [
  6281. x0 + xstep,
  6282. y0 + ystep
  6283. ];
  6284. var width = botRight[0] - topLeft[0];
  6285. var height = botRight[1] - topLeft[1];
  6286. // Obtain scale from matrix and current transformation matrix.
  6287. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  6288. var curMatrixScale = Util.singularValueDecompose2dScale(this.baseTransform);
  6289. var combinedScale = [
  6290. matrixScale[0] * curMatrixScale[0],
  6291. matrixScale[1] * curMatrixScale[1]
  6292. ];
  6293. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  6294. // Use width and height values that are as close as possible to the end
  6295. // result when the pattern is used. Too low value makes the pattern look
  6296. // blurry. Too large value makes it look too crispy.
  6297. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])), MAX_PATTERN_SIZE);
  6298. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])), MAX_PATTERN_SIZE);
  6299. var tmpCanvas = owner.cachedCanvases.getCanvas('pattern', width, height, true);
  6300. var tmpCtx = tmpCanvas.context;
  6301. var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  6302. graphics.groupLevel = owner.groupLevel;
  6303. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  6304. this.setScale(width, height, xstep, ystep);
  6305. this.transformToScale(graphics);
  6306. // transform coordinates to pattern space
  6307. var tmpTranslate = [
  6308. 1,
  6309. 0,
  6310. 0,
  6311. 1,
  6312. -topLeft[0],
  6313. -topLeft[1]
  6314. ];
  6315. graphics.transform.apply(graphics, tmpTranslate);
  6316. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  6317. graphics.executeOperatorList(operatorList);
  6318. return tmpCanvas.canvas;
  6319. },
  6320. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  6321. this.scale = [
  6322. width / xstep,
  6323. height / ystep
  6324. ];
  6325. },
  6326. transformToScale: function TilingPattern_transformToScale(graphics) {
  6327. var scale = this.scale;
  6328. var tmpScale = [
  6329. scale[0],
  6330. 0,
  6331. 0,
  6332. scale[1],
  6333. 0,
  6334. 0
  6335. ];
  6336. graphics.transform.apply(graphics, tmpScale);
  6337. },
  6338. scaleToContext: function TilingPattern_scaleToContext() {
  6339. var scale = this.scale;
  6340. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  6341. },
  6342. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  6343. if (bbox && isArray(bbox) && bbox.length === 4) {
  6344. var bboxWidth = x1 - x0;
  6345. var bboxHeight = y1 - y0;
  6346. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  6347. graphics.clip();
  6348. graphics.endPath();
  6349. }
  6350. },
  6351. setFillAndStrokeStyleToContext: function setFillAndStrokeStyleToContext(context, paintType, color) {
  6352. switch (paintType) {
  6353. case PaintType.COLORED:
  6354. var ctx = this.ctx;
  6355. context.fillStyle = ctx.fillStyle;
  6356. context.strokeStyle = ctx.strokeStyle;
  6357. break;
  6358. case PaintType.UNCOLORED:
  6359. var cssColor = Util.makeCssRgb(color[0], color[1], color[2]);
  6360. context.fillStyle = cssColor;
  6361. context.strokeStyle = cssColor;
  6362. break;
  6363. default:
  6364. error('Unsupported paint type: ' + paintType);
  6365. }
  6366. },
  6367. getPattern: function TilingPattern_getPattern(ctx, owner) {
  6368. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  6369. ctx = this.ctx;
  6370. ctx.setTransform.apply(ctx, this.baseTransform);
  6371. ctx.transform.apply(ctx, this.matrix);
  6372. this.scaleToContext();
  6373. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  6374. }
  6375. };
  6376. return TilingPattern;
  6377. }();
  6378. exports.getShadingPatternFromIR = getShadingPatternFromIR;
  6379. exports.TilingPattern = TilingPattern;
  6380. }));
  6381. (function (root, factory) {
  6382. factory(root.pdfjsDisplayCanvas = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils, root.pdfjsDisplayPatternHelper, root.pdfjsDisplayWebGL);
  6383. }(this, function (exports, sharedUtil, displayDOMUtils, displayPatternHelper, displayWebGL) {
  6384. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  6385. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  6386. var ImageKind = sharedUtil.ImageKind;
  6387. var OPS = sharedUtil.OPS;
  6388. var TextRenderingMode = sharedUtil.TextRenderingMode;
  6389. var Uint32ArrayView = sharedUtil.Uint32ArrayView;
  6390. var Util = sharedUtil.Util;
  6391. var assert = sharedUtil.assert;
  6392. var info = sharedUtil.info;
  6393. var isNum = sharedUtil.isNum;
  6394. var isArray = sharedUtil.isArray;
  6395. var isLittleEndian = sharedUtil.isLittleEndian;
  6396. var error = sharedUtil.error;
  6397. var shadow = sharedUtil.shadow;
  6398. var warn = sharedUtil.warn;
  6399. var TilingPattern = displayPatternHelper.TilingPattern;
  6400. var getShadingPatternFromIR = displayPatternHelper.getShadingPatternFromIR;
  6401. var WebGLUtils = displayWebGL.WebGLUtils;
  6402. var hasCanvasTypedArrays = displayDOMUtils.hasCanvasTypedArrays;
  6403. // <canvas> contexts store most of the state we need natively.
  6404. // However, PDF needs a bit more state, which we store here.
  6405. // Minimal font size that would be used during canvas fillText operations.
  6406. var MIN_FONT_SIZE = 16;
  6407. // Maximum font size that would be used during canvas fillText operations.
  6408. var MAX_FONT_SIZE = 100;
  6409. var MAX_GROUP_SIZE = 4096;
  6410. // Heuristic value used when enforcing minimum line widths.
  6411. var MIN_WIDTH_FACTOR = 0.65;
  6412. var COMPILE_TYPE3_GLYPHS = true;
  6413. var MAX_SIZE_TO_COMPILE = 1000;
  6414. var FULL_CHUNK_HEIGHT = 16;
  6415. var HasCanvasTypedArraysCached = {
  6416. get value() {
  6417. return shadow(HasCanvasTypedArraysCached, 'value', hasCanvasTypedArrays());
  6418. }
  6419. };
  6420. var IsLittleEndianCached = {
  6421. get value() {
  6422. return shadow(IsLittleEndianCached, 'value', isLittleEndian());
  6423. }
  6424. };
  6425. function createScratchCanvas(width, height) {
  6426. var canvas = document.createElement('canvas');
  6427. canvas.width = width;
  6428. canvas.height = height;
  6429. return canvas;
  6430. }
  6431. function addContextCurrentTransform(ctx) {
  6432. // If the context doesn't expose a `mozCurrentTransform`, add a JS based one.
  6433. if (!ctx.mozCurrentTransform) {
  6434. ctx._originalSave = ctx.save;
  6435. ctx._originalRestore = ctx.restore;
  6436. ctx._originalRotate = ctx.rotate;
  6437. ctx._originalScale = ctx.scale;
  6438. ctx._originalTranslate = ctx.translate;
  6439. ctx._originalTransform = ctx.transform;
  6440. ctx._originalSetTransform = ctx.setTransform;
  6441. ctx._transformMatrix = ctx._transformMatrix || [
  6442. 1,
  6443. 0,
  6444. 0,
  6445. 1,
  6446. 0,
  6447. 0
  6448. ];
  6449. ctx._transformStack = [];
  6450. Object.defineProperty(ctx, 'mozCurrentTransform', {
  6451. get: function getCurrentTransform() {
  6452. return this._transformMatrix;
  6453. }
  6454. });
  6455. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  6456. get: function getCurrentTransformInverse() {
  6457. // Calculation done using WolframAlpha:
  6458. // http://www.wolframalpha.com/input/?
  6459. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  6460. var m = this._transformMatrix;
  6461. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  6462. var ad_bc = a * d - b * c;
  6463. var bc_ad = b * c - a * d;
  6464. return [
  6465. d / ad_bc,
  6466. b / bc_ad,
  6467. c / bc_ad,
  6468. a / ad_bc,
  6469. (d * e - c * f) / bc_ad,
  6470. (b * e - a * f) / ad_bc
  6471. ];
  6472. }
  6473. });
  6474. ctx.save = function ctxSave() {
  6475. var old = this._transformMatrix;
  6476. this._transformStack.push(old);
  6477. this._transformMatrix = old.slice(0, 6);
  6478. this._originalSave();
  6479. };
  6480. ctx.restore = function ctxRestore() {
  6481. var prev = this._transformStack.pop();
  6482. if (prev) {
  6483. this._transformMatrix = prev;
  6484. this._originalRestore();
  6485. }
  6486. };
  6487. ctx.translate = function ctxTranslate(x, y) {
  6488. var m = this._transformMatrix;
  6489. m[4] = m[0] * x + m[2] * y + m[4];
  6490. m[5] = m[1] * x + m[3] * y + m[5];
  6491. this._originalTranslate(x, y);
  6492. };
  6493. ctx.scale = function ctxScale(x, y) {
  6494. var m = this._transformMatrix;
  6495. m[0] = m[0] * x;
  6496. m[1] = m[1] * x;
  6497. m[2] = m[2] * y;
  6498. m[3] = m[3] * y;
  6499. this._originalScale(x, y);
  6500. };
  6501. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  6502. var m = this._transformMatrix;
  6503. this._transformMatrix = [
  6504. m[0] * a + m[2] * b,
  6505. m[1] * a + m[3] * b,
  6506. m[0] * c + m[2] * d,
  6507. m[1] * c + m[3] * d,
  6508. m[0] * e + m[2] * f + m[4],
  6509. m[1] * e + m[3] * f + m[5]
  6510. ];
  6511. ctx._originalTransform(a, b, c, d, e, f);
  6512. };
  6513. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  6514. this._transformMatrix = [
  6515. a,
  6516. b,
  6517. c,
  6518. d,
  6519. e,
  6520. f
  6521. ];
  6522. ctx._originalSetTransform(a, b, c, d, e, f);
  6523. };
  6524. ctx.rotate = function ctxRotate(angle) {
  6525. var cosValue = Math.cos(angle);
  6526. var sinValue = Math.sin(angle);
  6527. var m = this._transformMatrix;
  6528. this._transformMatrix = [
  6529. m[0] * cosValue + m[2] * sinValue,
  6530. m[1] * cosValue + m[3] * sinValue,
  6531. m[0] * -sinValue + m[2] * cosValue,
  6532. m[1] * -sinValue + m[3] * cosValue,
  6533. m[4],
  6534. m[5]
  6535. ];
  6536. this._originalRotate(angle);
  6537. };
  6538. }
  6539. }
  6540. var CachedCanvases = function CachedCanvasesClosure() {
  6541. function CachedCanvases() {
  6542. this.cache = Object.create(null);
  6543. }
  6544. CachedCanvases.prototype = {
  6545. getCanvas: function CachedCanvases_getCanvas(id, width, height, trackTransform) {
  6546. var canvasEntry;
  6547. if (this.cache[id] !== undefined) {
  6548. canvasEntry = this.cache[id];
  6549. canvasEntry.canvas.width = width;
  6550. canvasEntry.canvas.height = height;
  6551. // reset canvas transform for emulated mozCurrentTransform, if needed
  6552. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  6553. } else {
  6554. var canvas = createScratchCanvas(width, height);
  6555. var ctx = canvas.getContext('2d');
  6556. if (trackTransform) {
  6557. addContextCurrentTransform(ctx);
  6558. }
  6559. this.cache[id] = canvasEntry = {
  6560. canvas: canvas,
  6561. context: ctx
  6562. };
  6563. }
  6564. return canvasEntry;
  6565. },
  6566. clear: function () {
  6567. for (var id in this.cache) {
  6568. var canvasEntry = this.cache[id];
  6569. // Zeroing the width and height causes Firefox to release graphics
  6570. // resources immediately, which can greatly reduce memory consumption.
  6571. canvasEntry.canvas.width = 0;
  6572. canvasEntry.canvas.height = 0;
  6573. delete this.cache[id];
  6574. }
  6575. }
  6576. };
  6577. return CachedCanvases;
  6578. }();
  6579. function compileType3Glyph(imgData) {
  6580. var POINT_TO_PROCESS_LIMIT = 1000;
  6581. var width = imgData.width, height = imgData.height;
  6582. var i, j, j0, width1 = width + 1;
  6583. var points = new Uint8Array(width1 * (height + 1));
  6584. var POINT_TYPES = new Uint8Array([
  6585. 0,
  6586. 2,
  6587. 4,
  6588. 0,
  6589. 1,
  6590. 0,
  6591. 5,
  6592. 4,
  6593. 8,
  6594. 10,
  6595. 0,
  6596. 8,
  6597. 0,
  6598. 2,
  6599. 1,
  6600. 0
  6601. ]);
  6602. // decodes bit-packed mask data
  6603. var lineSize = width + 7 & ~7, data0 = imgData.data;
  6604. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  6605. for (i = 0, ii = data0.length; i < ii; i++) {
  6606. var mask = 128, elem = data0[i];
  6607. while (mask > 0) {
  6608. data[pos++] = elem & mask ? 0 : 255;
  6609. mask >>= 1;
  6610. }
  6611. }
  6612. // finding iteresting points: every point is located between mask pixels,
  6613. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  6614. // will have flags assigned based on neighboring mask pixels:
  6615. // 4 | 8
  6616. // --P--
  6617. // 2 | 1
  6618. // We are interested only in points with the flags:
  6619. // - outside corners: 1, 2, 4, 8;
  6620. // - inside corners: 7, 11, 13, 14;
  6621. // - and, intersections: 5, 10.
  6622. var count = 0;
  6623. pos = 0;
  6624. if (data[pos] !== 0) {
  6625. points[0] = 1;
  6626. ++count;
  6627. }
  6628. for (j = 1; j < width; j++) {
  6629. if (data[pos] !== data[pos + 1]) {
  6630. points[j] = data[pos] ? 2 : 1;
  6631. ++count;
  6632. }
  6633. pos++;
  6634. }
  6635. if (data[pos] !== 0) {
  6636. points[j] = 2;
  6637. ++count;
  6638. }
  6639. for (i = 1; i < height; i++) {
  6640. pos = i * lineSize;
  6641. j0 = i * width1;
  6642. if (data[pos - lineSize] !== data[pos]) {
  6643. points[j0] = data[pos] ? 1 : 8;
  6644. ++count;
  6645. }
  6646. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  6647. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  6648. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  6649. for (j = 1; j < width; j++) {
  6650. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
  6651. if (POINT_TYPES[sum]) {
  6652. points[j0 + j] = POINT_TYPES[sum];
  6653. ++count;
  6654. }
  6655. pos++;
  6656. }
  6657. if (data[pos - lineSize] !== data[pos]) {
  6658. points[j0 + j] = data[pos] ? 2 : 4;
  6659. ++count;
  6660. }
  6661. if (count > POINT_TO_PROCESS_LIMIT) {
  6662. return null;
  6663. }
  6664. }
  6665. pos = lineSize * (height - 1);
  6666. j0 = i * width1;
  6667. if (data[pos] !== 0) {
  6668. points[j0] = 8;
  6669. ++count;
  6670. }
  6671. for (j = 1; j < width; j++) {
  6672. if (data[pos] !== data[pos + 1]) {
  6673. points[j0 + j] = data[pos] ? 4 : 8;
  6674. ++count;
  6675. }
  6676. pos++;
  6677. }
  6678. if (data[pos] !== 0) {
  6679. points[j0 + j] = 4;
  6680. ++count;
  6681. }
  6682. if (count > POINT_TO_PROCESS_LIMIT) {
  6683. return null;
  6684. }
  6685. // building outlines
  6686. var steps = new Int32Array([
  6687. 0,
  6688. width1,
  6689. -1,
  6690. 0,
  6691. -width1,
  6692. 0,
  6693. 0,
  6694. 0,
  6695. 1
  6696. ]);
  6697. var outlines = [];
  6698. for (i = 0; count && i <= height; i++) {
  6699. var p = i * width1;
  6700. var end = p + width;
  6701. while (p < end && !points[p]) {
  6702. p++;
  6703. }
  6704. if (p === end) {
  6705. continue;
  6706. }
  6707. var coords = [
  6708. p % width1,
  6709. i
  6710. ];
  6711. var type = points[p], p0 = p, pp;
  6712. do {
  6713. var step = steps[type];
  6714. do {
  6715. p += step;
  6716. } while (!points[p]);
  6717. pp = points[p];
  6718. if (pp !== 5 && pp !== 10) {
  6719. // set new direction
  6720. type = pp;
  6721. // delete mark
  6722. points[p] = 0;
  6723. } else {
  6724. // type is 5 or 10, ie, a crossing
  6725. // set new direction
  6726. type = pp & 0x33 * type >> 4;
  6727. // set new type for "future hit"
  6728. points[p] &= type >> 2 | type << 2;
  6729. }
  6730. coords.push(p % width1);
  6731. coords.push(p / width1 | 0);
  6732. --count;
  6733. } while (p0 !== p);
  6734. outlines.push(coords);
  6735. --i;
  6736. }
  6737. var drawOutline = function (c) {
  6738. c.save();
  6739. // the path shall be painted in [0..1]x[0..1] space
  6740. c.scale(1 / width, -1 / height);
  6741. c.translate(0, -height);
  6742. c.beginPath();
  6743. for (var i = 0, ii = outlines.length; i < ii; i++) {
  6744. var o = outlines[i];
  6745. c.moveTo(o[0], o[1]);
  6746. for (var j = 2, jj = o.length; j < jj; j += 2) {
  6747. c.lineTo(o[j], o[j + 1]);
  6748. }
  6749. }
  6750. c.fill();
  6751. c.beginPath();
  6752. c.restore();
  6753. };
  6754. return drawOutline;
  6755. }
  6756. var CanvasExtraState = function CanvasExtraStateClosure() {
  6757. function CanvasExtraState(old) {
  6758. // Are soft masks and alpha values shapes or opacities?
  6759. this.alphaIsShape = false;
  6760. this.fontSize = 0;
  6761. this.fontSizeScale = 1;
  6762. this.textMatrix = IDENTITY_MATRIX;
  6763. this.textMatrixScale = 1;
  6764. this.fontMatrix = FONT_IDENTITY_MATRIX;
  6765. this.leading = 0;
  6766. // Current point (in user coordinates)
  6767. this.x = 0;
  6768. this.y = 0;
  6769. // Start of text line (in text coordinates)
  6770. this.lineX = 0;
  6771. this.lineY = 0;
  6772. // Character and word spacing
  6773. this.charSpacing = 0;
  6774. this.wordSpacing = 0;
  6775. this.textHScale = 1;
  6776. this.textRenderingMode = TextRenderingMode.FILL;
  6777. this.textRise = 0;
  6778. // Default fore and background colors
  6779. this.fillColor = '#000000';
  6780. this.strokeColor = '#000000';
  6781. this.patternFill = false;
  6782. // Note: fill alpha applies to all non-stroking operations
  6783. this.fillAlpha = 1;
  6784. this.strokeAlpha = 1;
  6785. this.lineWidth = 1;
  6786. this.activeSMask = null;
  6787. this.resumeSMaskCtx = null;
  6788. // nonclonable field (see the save method below)
  6789. this.old = old;
  6790. }
  6791. CanvasExtraState.prototype = {
  6792. clone: function CanvasExtraState_clone() {
  6793. return Object.create(this);
  6794. },
  6795. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  6796. this.x = x;
  6797. this.y = y;
  6798. }
  6799. };
  6800. return CanvasExtraState;
  6801. }();
  6802. var CanvasGraphics = function CanvasGraphicsClosure() {
  6803. // Defines the time the executeOperatorList is going to be executing
  6804. // before it stops and shedules a continue of execution.
  6805. var EXECUTION_TIME = 15;
  6806. // Defines the number of steps before checking the execution time
  6807. var EXECUTION_STEPS = 10;
  6808. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  6809. this.ctx = canvasCtx;
  6810. this.current = new CanvasExtraState();
  6811. this.stateStack = [];
  6812. this.pendingClip = null;
  6813. this.pendingEOFill = false;
  6814. this.res = null;
  6815. this.xobjs = null;
  6816. this.commonObjs = commonObjs;
  6817. this.objs = objs;
  6818. this.imageLayer = imageLayer;
  6819. this.groupStack = [];
  6820. this.processingType3 = null;
  6821. // Patterns are painted relative to the initial page/form transform, see pdf
  6822. // spec 8.7.2 NOTE 1.
  6823. this.baseTransform = null;
  6824. this.baseTransformStack = [];
  6825. this.groupLevel = 0;
  6826. this.smaskStack = [];
  6827. this.smaskCounter = 0;
  6828. this.tempSMask = null;
  6829. this.cachedCanvases = new CachedCanvases();
  6830. if (canvasCtx) {
  6831. // NOTE: if mozCurrentTransform is polyfilled, then the current state of
  6832. // the transformation must already be set in canvasCtx._transformMatrix.
  6833. addContextCurrentTransform(canvasCtx);
  6834. }
  6835. this.cachedGetSinglePixelWidth = null;
  6836. }
  6837. function putBinaryImageData(ctx, imgData) {
  6838. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  6839. ctx.putImageData(imgData, 0, 0);
  6840. return;
  6841. }
  6842. // Put the image data to the canvas in chunks, rather than putting the
  6843. // whole image at once. This saves JS memory, because the ImageData object
  6844. // is smaller. It also possibly saves C++ memory within the implementation
  6845. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  6846. // the data passed to putImageData()). |n| shouldn't be too small, however,
  6847. // because too many putImageData() calls will slow things down.
  6848. //
  6849. // Note: as written, if the last chunk is partial, the putImageData() call
  6850. // will (conceptually) put pixels past the bounds of the canvas. But
  6851. // that's ok; any such pixels are ignored.
  6852. var height = imgData.height, width = imgData.width;
  6853. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6854. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6855. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6856. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6857. var srcPos = 0, destPos;
  6858. var src = imgData.data;
  6859. var dest = chunkImgData.data;
  6860. var i, j, thisChunkHeight, elemsInThisChunk;
  6861. // There are multiple forms in which the pixel data can be passed, and
  6862. // imgData.kind tells us which one this is.
  6863. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  6864. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  6865. var srcLength = src.byteLength;
  6866. var dest32 = HasCanvasTypedArraysCached.value ? new Uint32Array(dest.buffer) : new Uint32ArrayView(dest);
  6867. var dest32DataLength = dest32.length;
  6868. var fullSrcDiff = width + 7 >> 3;
  6869. var white = 0xFFFFFFFF;
  6870. var black = IsLittleEndianCached.value || !HasCanvasTypedArraysCached.value ? 0xFF000000 : 0x000000FF;
  6871. for (i = 0; i < totalChunks; i++) {
  6872. thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6873. destPos = 0;
  6874. for (j = 0; j < thisChunkHeight; j++) {
  6875. var srcDiff = srcLength - srcPos;
  6876. var k = 0;
  6877. var kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
  6878. var kEndUnrolled = kEnd & ~7;
  6879. var mask = 0;
  6880. var srcByte = 0;
  6881. for (; k < kEndUnrolled; k += 8) {
  6882. srcByte = src[srcPos++];
  6883. dest32[destPos++] = srcByte & 128 ? white : black;
  6884. dest32[destPos++] = srcByte & 64 ? white : black;
  6885. dest32[destPos++] = srcByte & 32 ? white : black;
  6886. dest32[destPos++] = srcByte & 16 ? white : black;
  6887. dest32[destPos++] = srcByte & 8 ? white : black;
  6888. dest32[destPos++] = srcByte & 4 ? white : black;
  6889. dest32[destPos++] = srcByte & 2 ? white : black;
  6890. dest32[destPos++] = srcByte & 1 ? white : black;
  6891. }
  6892. for (; k < kEnd; k++) {
  6893. if (mask === 0) {
  6894. srcByte = src[srcPos++];
  6895. mask = 128;
  6896. }
  6897. dest32[destPos++] = srcByte & mask ? white : black;
  6898. mask >>= 1;
  6899. }
  6900. }
  6901. // We ran out of input. Make all remaining pixels transparent.
  6902. while (destPos < dest32DataLength) {
  6903. dest32[destPos++] = 0;
  6904. }
  6905. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6906. }
  6907. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  6908. // RGBA, 32-bits per pixel.
  6909. j = 0;
  6910. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  6911. for (i = 0; i < fullChunks; i++) {
  6912. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6913. srcPos += elemsInThisChunk;
  6914. ctx.putImageData(chunkImgData, 0, j);
  6915. j += FULL_CHUNK_HEIGHT;
  6916. }
  6917. if (i < totalChunks) {
  6918. elemsInThisChunk = width * partialChunkHeight * 4;
  6919. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6920. ctx.putImageData(chunkImgData, 0, j);
  6921. }
  6922. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  6923. // RGB, 24-bits per pixel.
  6924. thisChunkHeight = FULL_CHUNK_HEIGHT;
  6925. elemsInThisChunk = width * thisChunkHeight;
  6926. for (i = 0; i < totalChunks; i++) {
  6927. if (i >= fullChunks) {
  6928. thisChunkHeight = partialChunkHeight;
  6929. elemsInThisChunk = width * thisChunkHeight;
  6930. }
  6931. destPos = 0;
  6932. for (j = elemsInThisChunk; j--;) {
  6933. dest[destPos++] = src[srcPos++];
  6934. dest[destPos++] = src[srcPos++];
  6935. dest[destPos++] = src[srcPos++];
  6936. dest[destPos++] = 255;
  6937. }
  6938. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6939. }
  6940. } else {
  6941. error('bad image kind: ' + imgData.kind);
  6942. }
  6943. }
  6944. function putBinaryImageMask(ctx, imgData) {
  6945. var height = imgData.height, width = imgData.width;
  6946. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6947. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6948. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6949. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6950. var srcPos = 0;
  6951. var src = imgData.data;
  6952. var dest = chunkImgData.data;
  6953. for (var i = 0; i < totalChunks; i++) {
  6954. var thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6955. // Expand the mask so it can be used by the canvas. Any required
  6956. // inversion has already been handled.
  6957. var destPos = 3;
  6958. // alpha component offset
  6959. for (var j = 0; j < thisChunkHeight; j++) {
  6960. var mask = 0;
  6961. for (var k = 0; k < width; k++) {
  6962. if (!mask) {
  6963. var elem = src[srcPos++];
  6964. mask = 128;
  6965. }
  6966. dest[destPos] = elem & mask ? 0 : 255;
  6967. destPos += 4;
  6968. mask >>= 1;
  6969. }
  6970. }
  6971. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6972. }
  6973. }
  6974. function copyCtxState(sourceCtx, destCtx) {
  6975. var properties = [
  6976. 'strokeStyle',
  6977. 'fillStyle',
  6978. 'fillRule',
  6979. 'globalAlpha',
  6980. 'lineWidth',
  6981. 'lineCap',
  6982. 'lineJoin',
  6983. 'miterLimit',
  6984. 'globalCompositeOperation',
  6985. 'font'
  6986. ];
  6987. for (var i = 0, ii = properties.length; i < ii; i++) {
  6988. var property = properties[i];
  6989. if (sourceCtx[property] !== undefined) {
  6990. destCtx[property] = sourceCtx[property];
  6991. }
  6992. }
  6993. if (sourceCtx.setLineDash !== undefined) {
  6994. destCtx.setLineDash(sourceCtx.getLineDash());
  6995. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  6996. }
  6997. }
  6998. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  6999. var length = bytes.length;
  7000. for (var i = 3; i < length; i += 4) {
  7001. var alpha = bytes[i];
  7002. if (alpha === 0) {
  7003. bytes[i - 3] = r0;
  7004. bytes[i - 2] = g0;
  7005. bytes[i - 1] = b0;
  7006. } else if (alpha < 255) {
  7007. var alpha_ = 255 - alpha;
  7008. bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
  7009. bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
  7010. bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
  7011. }
  7012. }
  7013. }
  7014. function composeSMaskAlpha(maskData, layerData, transferMap) {
  7015. var length = maskData.length;
  7016. var scale = 1 / 255;
  7017. for (var i = 3; i < length; i += 4) {
  7018. var alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  7019. layerData[i] = layerData[i] * alpha * scale | 0;
  7020. }
  7021. }
  7022. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  7023. var length = maskData.length;
  7024. for (var i = 3; i < length; i += 4) {
  7025. var y = maskData[i - 3] * 77 + // * 0.3 / 255 * 0x10000
  7026. maskData[i - 2] * 152 + // * 0.59 ....
  7027. maskData[i - 1] * 28;
  7028. // * 0.11 ....
  7029. layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
  7030. }
  7031. }
  7032. function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap) {
  7033. var hasBackdrop = !!backdrop;
  7034. var r0 = hasBackdrop ? backdrop[0] : 0;
  7035. var g0 = hasBackdrop ? backdrop[1] : 0;
  7036. var b0 = hasBackdrop ? backdrop[2] : 0;
  7037. var composeFn;
  7038. if (subtype === 'Luminosity') {
  7039. composeFn = composeSMaskLuminosity;
  7040. } else {
  7041. composeFn = composeSMaskAlpha;
  7042. }
  7043. // processing image in chunks to save memory
  7044. var PIXELS_TO_PROCESS = 1048576;
  7045. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  7046. for (var row = 0; row < height; row += chunkSize) {
  7047. var chunkHeight = Math.min(chunkSize, height - row);
  7048. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  7049. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  7050. if (hasBackdrop) {
  7051. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  7052. }
  7053. composeFn(maskData.data, layerData.data, transferMap);
  7054. maskCtx.putImageData(layerData, 0, row);
  7055. }
  7056. }
  7057. function composeSMask(ctx, smask, layerCtx) {
  7058. var mask = smask.canvas;
  7059. var maskCtx = smask.context;
  7060. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY);
  7061. var backdrop = smask.backdrop || null;
  7062. if (!smask.transferMap && WebGLUtils.isEnabled) {
  7063. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask, {
  7064. subtype: smask.subtype,
  7065. backdrop: backdrop
  7066. });
  7067. ctx.setTransform(1, 0, 0, 1, 0, 0);
  7068. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  7069. return;
  7070. }
  7071. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, backdrop, smask.transferMap);
  7072. ctx.drawImage(mask, 0, 0);
  7073. }
  7074. var LINE_CAP_STYLES = [
  7075. 'butt',
  7076. 'round',
  7077. 'square'
  7078. ];
  7079. var LINE_JOIN_STYLES = [
  7080. 'miter',
  7081. 'round',
  7082. 'bevel'
  7083. ];
  7084. var NORMAL_CLIP = {};
  7085. var EO_CLIP = {};
  7086. CanvasGraphics.prototype = {
  7087. beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport, transparency) {
  7088. // For pdfs that use blend modes we have to clear the canvas else certain
  7089. // blend modes can look wrong since we'd be blending with a white
  7090. // backdrop. The problem with a transparent backdrop though is we then
  7091. // don't get sub pixel anti aliasing on text, creating temporary
  7092. // transparent canvas when we have blend modes.
  7093. var width = this.ctx.canvas.width;
  7094. var height = this.ctx.canvas.height;
  7095. this.ctx.save();
  7096. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  7097. this.ctx.fillRect(0, 0, width, height);
  7098. this.ctx.restore();
  7099. if (transparency) {
  7100. var transparentCanvas = this.cachedCanvases.getCanvas('transparent', width, height, true);
  7101. this.compositeCtx = this.ctx;
  7102. this.transparentCanvas = transparentCanvas.canvas;
  7103. this.ctx = transparentCanvas.context;
  7104. this.ctx.save();
  7105. // The transform can be applied before rendering, transferring it to
  7106. // the new canvas.
  7107. this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform);
  7108. }
  7109. this.ctx.save();
  7110. if (transform) {
  7111. this.ctx.transform.apply(this.ctx, transform);
  7112. }
  7113. this.ctx.transform.apply(this.ctx, viewport.transform);
  7114. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  7115. if (this.imageLayer) {
  7116. this.imageLayer.beginLayout();
  7117. }
  7118. },
  7119. executeOperatorList: function CanvasGraphics_executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  7120. var argsArray = operatorList.argsArray;
  7121. var fnArray = operatorList.fnArray;
  7122. var i = executionStartIdx || 0;
  7123. var argsArrayLen = argsArray.length;
  7124. // Sometimes the OperatorList to execute is empty.
  7125. if (argsArrayLen === i) {
  7126. return i;
  7127. }
  7128. var chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === 'function';
  7129. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  7130. var steps = 0;
  7131. var commonObjs = this.commonObjs;
  7132. var objs = this.objs;
  7133. var fnId;
  7134. while (true) {
  7135. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  7136. stepper.breakIt(i, continueCallback);
  7137. return i;
  7138. }
  7139. fnId = fnArray[i];
  7140. if (fnId !== OPS.dependency) {
  7141. this[fnId].apply(this, argsArray[i]);
  7142. } else {
  7143. var deps = argsArray[i];
  7144. for (var n = 0, nn = deps.length; n < nn; n++) {
  7145. var depObjId = deps[n];
  7146. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  7147. var objsPool = common ? commonObjs : objs;
  7148. // If the promise isn't resolved yet, add the continueCallback
  7149. // to the promise and bail out.
  7150. if (!objsPool.isResolved(depObjId)) {
  7151. objsPool.get(depObjId, continueCallback);
  7152. return i;
  7153. }
  7154. }
  7155. }
  7156. i++;
  7157. // If the entire operatorList was executed, stop as were done.
  7158. if (i === argsArrayLen) {
  7159. return i;
  7160. }
  7161. // If the execution took longer then a certain amount of time and
  7162. // `continueCallback` is specified, interrupt the execution.
  7163. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  7164. if (Date.now() > endTime) {
  7165. continueCallback();
  7166. return i;
  7167. }
  7168. steps = 0;
  7169. }
  7170. }
  7171. },
  7172. // If the operatorList isn't executed completely yet OR the execution
  7173. // time was short enough, do another execution round.
  7174. endDrawing: function CanvasGraphics_endDrawing() {
  7175. // Finishing all opened operations such as SMask group painting.
  7176. if (this.current.activeSMask !== null) {
  7177. this.endSMaskGroup();
  7178. }
  7179. this.ctx.restore();
  7180. if (this.transparentCanvas) {
  7181. this.ctx = this.compositeCtx;
  7182. this.ctx.save();
  7183. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  7184. // Avoid apply transform twice
  7185. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  7186. this.ctx.restore();
  7187. this.transparentCanvas = null;
  7188. }
  7189. this.cachedCanvases.clear();
  7190. WebGLUtils.clear();
  7191. if (this.imageLayer) {
  7192. this.imageLayer.endLayout();
  7193. }
  7194. },
  7195. // Graphics state
  7196. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  7197. this.current.lineWidth = width;
  7198. this.ctx.lineWidth = width;
  7199. },
  7200. setLineCap: function CanvasGraphics_setLineCap(style) {
  7201. this.ctx.lineCap = LINE_CAP_STYLES[style];
  7202. },
  7203. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  7204. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  7205. },
  7206. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  7207. this.ctx.miterLimit = limit;
  7208. },
  7209. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  7210. var ctx = this.ctx;
  7211. if (ctx.setLineDash !== undefined) {
  7212. ctx.setLineDash(dashArray);
  7213. ctx.lineDashOffset = dashPhase;
  7214. }
  7215. },
  7216. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  7217. },
  7218. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  7219. },
  7220. setGState: function CanvasGraphics_setGState(states) {
  7221. for (var i = 0, ii = states.length; i < ii; i++) {
  7222. var state = states[i];
  7223. var key = state[0];
  7224. var value = state[1];
  7225. switch (key) {
  7226. case 'LW':
  7227. this.setLineWidth(value);
  7228. break;
  7229. case 'LC':
  7230. this.setLineCap(value);
  7231. break;
  7232. case 'LJ':
  7233. this.setLineJoin(value);
  7234. break;
  7235. case 'ML':
  7236. this.setMiterLimit(value);
  7237. break;
  7238. case 'D':
  7239. this.setDash(value[0], value[1]);
  7240. break;
  7241. case 'RI':
  7242. this.setRenderingIntent(value);
  7243. break;
  7244. case 'FL':
  7245. this.setFlatness(value);
  7246. break;
  7247. case 'Font':
  7248. this.setFont(value[0], value[1]);
  7249. break;
  7250. case 'CA':
  7251. this.current.strokeAlpha = state[1];
  7252. break;
  7253. case 'ca':
  7254. this.current.fillAlpha = state[1];
  7255. this.ctx.globalAlpha = state[1];
  7256. break;
  7257. case 'BM':
  7258. if (value && value.name && value.name !== 'Normal') {
  7259. var mode = value.name.replace(/([A-Z])/g, function (c) {
  7260. return '-' + c.toLowerCase();
  7261. }).substring(1);
  7262. this.ctx.globalCompositeOperation = mode;
  7263. if (this.ctx.globalCompositeOperation !== mode) {
  7264. warn('globalCompositeOperation "' + mode + '" is not supported');
  7265. }
  7266. } else {
  7267. this.ctx.globalCompositeOperation = 'source-over';
  7268. }
  7269. break;
  7270. case 'SMask':
  7271. if (this.current.activeSMask) {
  7272. // If SMask is currrenly used, it needs to be suspended or
  7273. // finished. Suspend only makes sense when at least one save()
  7274. // was performed and state needs to be reverted on restore().
  7275. if (this.stateStack.length > 0 && this.stateStack[this.stateStack.length - 1].activeSMask === this.current.activeSMask) {
  7276. this.suspendSMaskGroup();
  7277. } else {
  7278. this.endSMaskGroup();
  7279. }
  7280. }
  7281. this.current.activeSMask = value ? this.tempSMask : null;
  7282. if (this.current.activeSMask) {
  7283. this.beginSMaskGroup();
  7284. }
  7285. this.tempSMask = null;
  7286. break;
  7287. }
  7288. }
  7289. },
  7290. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  7291. var activeSMask = this.current.activeSMask;
  7292. var drawnWidth = activeSMask.canvas.width;
  7293. var drawnHeight = activeSMask.canvas.height;
  7294. var cacheId = 'smaskGroupAt' + this.groupLevel;
  7295. var scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  7296. var currentCtx = this.ctx;
  7297. var currentTransform = currentCtx.mozCurrentTransform;
  7298. this.ctx.save();
  7299. var groupCtx = scratchCanvas.context;
  7300. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  7301. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  7302. groupCtx.transform.apply(groupCtx, currentTransform);
  7303. activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse;
  7304. copyCtxState(currentCtx, groupCtx);
  7305. this.ctx = groupCtx;
  7306. this.setGState([
  7307. [
  7308. 'BM',
  7309. 'Normal'
  7310. ],
  7311. [
  7312. 'ca',
  7313. 1
  7314. ],
  7315. [
  7316. 'CA',
  7317. 1
  7318. ]
  7319. ]);
  7320. this.groupStack.push(currentCtx);
  7321. this.groupLevel++;
  7322. },
  7323. suspendSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  7324. // Similar to endSMaskGroup, the intermediate canvas has to be composed
  7325. // and future ctx state restored.
  7326. var groupCtx = this.ctx;
  7327. this.groupLevel--;
  7328. this.ctx = this.groupStack.pop();
  7329. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  7330. this.ctx.restore();
  7331. this.ctx.save();
  7332. // save is needed since SMask will be resumed.
  7333. copyCtxState(groupCtx, this.ctx);
  7334. // Saving state for resuming.
  7335. this.current.resumeSMaskCtx = groupCtx;
  7336. // Transform was changed in the SMask canvas, reflecting this change on
  7337. // this.ctx.
  7338. var deltaTransform = Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
  7339. this.ctx.transform.apply(this.ctx, deltaTransform);
  7340. // SMask was composed, the results at the groupCtx can be cleared.
  7341. groupCtx.save();
  7342. groupCtx.setTransform(1, 0, 0, 1, 0, 0);
  7343. groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height);
  7344. groupCtx.restore();
  7345. },
  7346. resumeSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  7347. // Resuming state saved by suspendSMaskGroup. We don't need to restore
  7348. // any groupCtx state since restore() command (the only caller) will do
  7349. // that for us. See also beginSMaskGroup.
  7350. var groupCtx = this.current.resumeSMaskCtx;
  7351. var currentCtx = this.ctx;
  7352. this.ctx = groupCtx;
  7353. this.groupStack.push(currentCtx);
  7354. this.groupLevel++;
  7355. },
  7356. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  7357. var groupCtx = this.ctx;
  7358. this.groupLevel--;
  7359. this.ctx = this.groupStack.pop();
  7360. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  7361. this.ctx.restore();
  7362. copyCtxState(groupCtx, this.ctx);
  7363. // Transform was changed in the SMask canvas, reflecting this change on
  7364. // this.ctx.
  7365. var deltaTransform = Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
  7366. this.ctx.transform.apply(this.ctx, deltaTransform);
  7367. },
  7368. save: function CanvasGraphics_save() {
  7369. this.ctx.save();
  7370. var old = this.current;
  7371. this.stateStack.push(old);
  7372. this.current = old.clone();
  7373. this.current.resumeSMaskCtx = null;
  7374. },
  7375. restore: function CanvasGraphics_restore() {
  7376. // SMask was suspended, we just need to resume it.
  7377. if (this.current.resumeSMaskCtx) {
  7378. this.resumeSMaskGroup();
  7379. }
  7380. // SMask has to be finished once there is no states that are using the
  7381. // same SMask.
  7382. if (this.current.activeSMask !== null && (this.stateStack.length === 0 || this.stateStack[this.stateStack.length - 1].activeSMask !== this.current.activeSMask)) {
  7383. this.endSMaskGroup();
  7384. }
  7385. if (this.stateStack.length !== 0) {
  7386. this.current = this.stateStack.pop();
  7387. this.ctx.restore();
  7388. // Ensure that the clipping path is reset (fixes issue6413.pdf).
  7389. this.pendingClip = null;
  7390. this.cachedGetSinglePixelWidth = null;
  7391. }
  7392. },
  7393. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  7394. this.ctx.transform(a, b, c, d, e, f);
  7395. this.cachedGetSinglePixelWidth = null;
  7396. },
  7397. // Path
  7398. constructPath: function CanvasGraphics_constructPath(ops, args) {
  7399. var ctx = this.ctx;
  7400. var current = this.current;
  7401. var x = current.x, y = current.y;
  7402. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  7403. switch (ops[i] | 0) {
  7404. case OPS.rectangle:
  7405. x = args[j++];
  7406. y = args[j++];
  7407. var width = args[j++];
  7408. var height = args[j++];
  7409. if (width === 0) {
  7410. width = this.getSinglePixelWidth();
  7411. }
  7412. if (height === 0) {
  7413. height = this.getSinglePixelWidth();
  7414. }
  7415. var xw = x + width;
  7416. var yh = y + height;
  7417. this.ctx.moveTo(x, y);
  7418. this.ctx.lineTo(xw, y);
  7419. this.ctx.lineTo(xw, yh);
  7420. this.ctx.lineTo(x, yh);
  7421. this.ctx.lineTo(x, y);
  7422. this.ctx.closePath();
  7423. break;
  7424. case OPS.moveTo:
  7425. x = args[j++];
  7426. y = args[j++];
  7427. ctx.moveTo(x, y);
  7428. break;
  7429. case OPS.lineTo:
  7430. x = args[j++];
  7431. y = args[j++];
  7432. ctx.lineTo(x, y);
  7433. break;
  7434. case OPS.curveTo:
  7435. x = args[j + 4];
  7436. y = args[j + 5];
  7437. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
  7438. j += 6;
  7439. break;
  7440. case OPS.curveTo2:
  7441. ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
  7442. x = args[j + 2];
  7443. y = args[j + 3];
  7444. j += 4;
  7445. break;
  7446. case OPS.curveTo3:
  7447. x = args[j + 2];
  7448. y = args[j + 3];
  7449. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  7450. j += 4;
  7451. break;
  7452. case OPS.closePath:
  7453. ctx.closePath();
  7454. break;
  7455. }
  7456. }
  7457. current.setCurrentPoint(x, y);
  7458. },
  7459. closePath: function CanvasGraphics_closePath() {
  7460. this.ctx.closePath();
  7461. },
  7462. stroke: function CanvasGraphics_stroke(consumePath) {
  7463. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  7464. var ctx = this.ctx;
  7465. var strokeColor = this.current.strokeColor;
  7466. // Prevent drawing too thin lines by enforcing a minimum line width.
  7467. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR, this.current.lineWidth);
  7468. // For stroke we want to temporarily change the global alpha to the
  7469. // stroking alpha.
  7470. ctx.globalAlpha = this.current.strokeAlpha;
  7471. if (strokeColor && strokeColor.hasOwnProperty('type') && strokeColor.type === 'Pattern') {
  7472. // for patterns, we transform to pattern space, calculate
  7473. // the pattern, call stroke, and restore to user space
  7474. ctx.save();
  7475. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  7476. ctx.stroke();
  7477. ctx.restore();
  7478. } else {
  7479. ctx.stroke();
  7480. }
  7481. if (consumePath) {
  7482. this.consumePath();
  7483. }
  7484. // Restore the global alpha to the fill alpha
  7485. ctx.globalAlpha = this.current.fillAlpha;
  7486. },
  7487. closeStroke: function CanvasGraphics_closeStroke() {
  7488. this.closePath();
  7489. this.stroke();
  7490. },
  7491. fill: function CanvasGraphics_fill(consumePath) {
  7492. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  7493. var ctx = this.ctx;
  7494. var fillColor = this.current.fillColor;
  7495. var isPatternFill = this.current.patternFill;
  7496. var needRestore = false;
  7497. if (isPatternFill) {
  7498. ctx.save();
  7499. if (this.baseTransform) {
  7500. ctx.setTransform.apply(ctx, this.baseTransform);
  7501. }
  7502. ctx.fillStyle = fillColor.getPattern(ctx, this);
  7503. needRestore = true;
  7504. }
  7505. if (this.pendingEOFill) {
  7506. if (ctx.mozFillRule !== undefined) {
  7507. ctx.mozFillRule = 'evenodd';
  7508. ctx.fill();
  7509. ctx.mozFillRule = 'nonzero';
  7510. } else {
  7511. ctx.fill('evenodd');
  7512. }
  7513. this.pendingEOFill = false;
  7514. } else {
  7515. ctx.fill();
  7516. }
  7517. if (needRestore) {
  7518. ctx.restore();
  7519. }
  7520. if (consumePath) {
  7521. this.consumePath();
  7522. }
  7523. },
  7524. eoFill: function CanvasGraphics_eoFill() {
  7525. this.pendingEOFill = true;
  7526. this.fill();
  7527. },
  7528. fillStroke: function CanvasGraphics_fillStroke() {
  7529. this.fill(false);
  7530. this.stroke(false);
  7531. this.consumePath();
  7532. },
  7533. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  7534. this.pendingEOFill = true;
  7535. this.fillStroke();
  7536. },
  7537. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  7538. this.closePath();
  7539. this.fillStroke();
  7540. },
  7541. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  7542. this.pendingEOFill = true;
  7543. this.closePath();
  7544. this.fillStroke();
  7545. },
  7546. endPath: function CanvasGraphics_endPath() {
  7547. this.consumePath();
  7548. },
  7549. // Clipping
  7550. clip: function CanvasGraphics_clip() {
  7551. this.pendingClip = NORMAL_CLIP;
  7552. },
  7553. eoClip: function CanvasGraphics_eoClip() {
  7554. this.pendingClip = EO_CLIP;
  7555. },
  7556. // Text
  7557. beginText: function CanvasGraphics_beginText() {
  7558. this.current.textMatrix = IDENTITY_MATRIX;
  7559. this.current.textMatrixScale = 1;
  7560. this.current.x = this.current.lineX = 0;
  7561. this.current.y = this.current.lineY = 0;
  7562. },
  7563. endText: function CanvasGraphics_endText() {
  7564. var paths = this.pendingTextPaths;
  7565. var ctx = this.ctx;
  7566. if (paths === undefined) {
  7567. ctx.beginPath();
  7568. return;
  7569. }
  7570. ctx.save();
  7571. ctx.beginPath();
  7572. for (var i = 0; i < paths.length; i++) {
  7573. var path = paths[i];
  7574. ctx.setTransform.apply(ctx, path.transform);
  7575. ctx.translate(path.x, path.y);
  7576. path.addToPath(ctx, path.fontSize);
  7577. }
  7578. ctx.restore();
  7579. ctx.clip();
  7580. ctx.beginPath();
  7581. delete this.pendingTextPaths;
  7582. },
  7583. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  7584. this.current.charSpacing = spacing;
  7585. },
  7586. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  7587. this.current.wordSpacing = spacing;
  7588. },
  7589. setHScale: function CanvasGraphics_setHScale(scale) {
  7590. this.current.textHScale = scale / 100;
  7591. },
  7592. setLeading: function CanvasGraphics_setLeading(leading) {
  7593. this.current.leading = -leading;
  7594. },
  7595. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  7596. var fontObj = this.commonObjs.get(fontRefName);
  7597. var current = this.current;
  7598. if (!fontObj) {
  7599. error('Can\'t find font for ' + fontRefName);
  7600. }
  7601. current.fontMatrix = fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX;
  7602. // A valid matrix needs all main diagonal elements to be non-zero
  7603. // This also ensures we bypass FF bugzilla bug #719844.
  7604. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  7605. warn('Invalid font matrix for font ' + fontRefName);
  7606. }
  7607. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  7608. // and in some docs this can be negative (inverted x-y axes).
  7609. if (size < 0) {
  7610. size = -size;
  7611. current.fontDirection = -1;
  7612. } else {
  7613. current.fontDirection = 1;
  7614. }
  7615. this.current.font = fontObj;
  7616. this.current.fontSize = size;
  7617. if (fontObj.isType3Font) {
  7618. return;
  7619. }
  7620. // we don't need ctx.font for Type3 fonts
  7621. var name = fontObj.loadedName || 'sans-serif';
  7622. var bold = fontObj.black ? fontObj.bold ? '900' : 'bold' : fontObj.bold ? 'bold' : 'normal';
  7623. var italic = fontObj.italic ? 'italic' : 'normal';
  7624. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  7625. // Some font backends cannot handle fonts below certain size.
  7626. // Keeping the font at minimal size and using the fontSizeScale to change
  7627. // the current transformation matrix before the fillText/strokeText.
  7628. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  7629. var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE : size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
  7630. this.current.fontSizeScale = size / browserFontSize;
  7631. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  7632. this.ctx.font = rule;
  7633. },
  7634. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  7635. this.current.textRenderingMode = mode;
  7636. },
  7637. setTextRise: function CanvasGraphics_setTextRise(rise) {
  7638. this.current.textRise = rise;
  7639. },
  7640. moveText: function CanvasGraphics_moveText(x, y) {
  7641. this.current.x = this.current.lineX += x;
  7642. this.current.y = this.current.lineY += y;
  7643. },
  7644. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  7645. this.setLeading(-y);
  7646. this.moveText(x, y);
  7647. },
  7648. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  7649. this.current.textMatrix = [
  7650. a,
  7651. b,
  7652. c,
  7653. d,
  7654. e,
  7655. f
  7656. ];
  7657. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  7658. this.current.x = this.current.lineX = 0;
  7659. this.current.y = this.current.lineY = 0;
  7660. },
  7661. nextLine: function CanvasGraphics_nextLine() {
  7662. this.moveText(0, this.current.leading);
  7663. },
  7664. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  7665. var ctx = this.ctx;
  7666. var current = this.current;
  7667. var font = current.font;
  7668. var textRenderingMode = current.textRenderingMode;
  7669. var fontSize = current.fontSize / current.fontSizeScale;
  7670. var fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
  7671. var isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG);
  7672. var addToPath;
  7673. if (font.disableFontFace || isAddToPathSet) {
  7674. addToPath = font.getPathGenerator(this.commonObjs, character);
  7675. }
  7676. if (font.disableFontFace) {
  7677. ctx.save();
  7678. ctx.translate(x, y);
  7679. ctx.beginPath();
  7680. addToPath(ctx, fontSize);
  7681. if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7682. ctx.fill();
  7683. }
  7684. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7685. ctx.stroke();
  7686. }
  7687. ctx.restore();
  7688. } else {
  7689. if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7690. ctx.fillText(character, x, y);
  7691. }
  7692. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7693. ctx.strokeText(character, x, y);
  7694. }
  7695. }
  7696. if (isAddToPathSet) {
  7697. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  7698. paths.push({
  7699. transform: ctx.mozCurrentTransform,
  7700. x: x,
  7701. y: y,
  7702. fontSize: fontSize,
  7703. addToPath: addToPath
  7704. });
  7705. }
  7706. },
  7707. get isFontSubpixelAAEnabled() {
  7708. // Checks if anti-aliasing is enabled when scaled text is painted.
  7709. // On Windows GDI scaled fonts looks bad.
  7710. var ctx = document.createElement('canvas').getContext('2d');
  7711. ctx.scale(1.5, 1);
  7712. ctx.fillText('I', 0, 10);
  7713. var data = ctx.getImageData(0, 0, 10, 10).data;
  7714. var enabled = false;
  7715. for (var i = 3; i < data.length; i += 4) {
  7716. if (data[i] > 0 && data[i] < 255) {
  7717. enabled = true;
  7718. break;
  7719. }
  7720. }
  7721. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  7722. },
  7723. showText: function CanvasGraphics_showText(glyphs) {
  7724. var current = this.current;
  7725. var font = current.font;
  7726. if (font.isType3Font) {
  7727. return this.showType3Text(glyphs);
  7728. }
  7729. var fontSize = current.fontSize;
  7730. if (fontSize === 0) {
  7731. return;
  7732. }
  7733. var ctx = this.ctx;
  7734. var fontSizeScale = current.fontSizeScale;
  7735. var charSpacing = current.charSpacing;
  7736. var wordSpacing = current.wordSpacing;
  7737. var fontDirection = current.fontDirection;
  7738. var textHScale = current.textHScale * fontDirection;
  7739. var glyphsLength = glyphs.length;
  7740. var vertical = font.vertical;
  7741. var spacingDir = vertical ? 1 : -1;
  7742. var defaultVMetrics = font.defaultVMetrics;
  7743. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  7744. var simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace;
  7745. ctx.save();
  7746. ctx.transform.apply(ctx, current.textMatrix);
  7747. ctx.translate(current.x, current.y + current.textRise);
  7748. if (current.patternFill) {
  7749. // TODO: Some shading patterns are not applied correctly to text,
  7750. // e.g. issues 3988 and 5432, and ShowText-ShadingPattern.pdf.
  7751. ctx.fillStyle = current.fillColor.getPattern(ctx, this);
  7752. }
  7753. if (fontDirection > 0) {
  7754. ctx.scale(textHScale, -1);
  7755. } else {
  7756. ctx.scale(textHScale, 1);
  7757. }
  7758. var lineWidth = current.lineWidth;
  7759. var scale = current.textMatrixScale;
  7760. if (scale === 0 || lineWidth === 0) {
  7761. var fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
  7762. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7763. this.cachedGetSinglePixelWidth = null;
  7764. lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
  7765. }
  7766. } else {
  7767. lineWidth /= scale;
  7768. }
  7769. if (fontSizeScale !== 1.0) {
  7770. ctx.scale(fontSizeScale, fontSizeScale);
  7771. lineWidth /= fontSizeScale;
  7772. }
  7773. ctx.lineWidth = lineWidth;
  7774. var x = 0, i;
  7775. for (i = 0; i < glyphsLength; ++i) {
  7776. var glyph = glyphs[i];
  7777. if (isNum(glyph)) {
  7778. x += spacingDir * glyph * fontSize / 1000;
  7779. continue;
  7780. }
  7781. var restoreNeeded = false;
  7782. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7783. var character = glyph.fontChar;
  7784. var accent = glyph.accent;
  7785. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  7786. var width = glyph.width;
  7787. if (vertical) {
  7788. var vmetric, vx, vy;
  7789. vmetric = glyph.vmetric || defaultVMetrics;
  7790. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  7791. vx = -vx * widthAdvanceScale;
  7792. vy = vmetric[2] * widthAdvanceScale;
  7793. width = vmetric ? -vmetric[0] : width;
  7794. scaledX = vx / fontSizeScale;
  7795. scaledY = (x + vy) / fontSizeScale;
  7796. } else {
  7797. scaledX = x / fontSizeScale;
  7798. scaledY = 0;
  7799. }
  7800. if (font.remeasure && width > 0) {
  7801. // Some standard fonts may not have the exact width: rescale per
  7802. // character if measured width is greater than expected glyph width
  7803. // and subpixel-aa is enabled, otherwise just center the glyph.
  7804. var measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  7805. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  7806. var characterScaleX = width / measuredWidth;
  7807. restoreNeeded = true;
  7808. ctx.save();
  7809. ctx.scale(characterScaleX, 1);
  7810. scaledX /= characterScaleX;
  7811. } else if (width !== measuredWidth) {
  7812. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  7813. }
  7814. }
  7815. // Only attempt to draw the glyph if it is actually in the embedded font
  7816. // file or if there isn't a font file so the fallback font is shown.
  7817. if (glyph.isInFont || font.missingFile) {
  7818. if (simpleFillText && !accent) {
  7819. // common case
  7820. ctx.fillText(character, scaledX, scaledY);
  7821. } else {
  7822. this.paintChar(character, scaledX, scaledY);
  7823. if (accent) {
  7824. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  7825. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  7826. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  7827. }
  7828. }
  7829. }
  7830. var charWidth = width * widthAdvanceScale + spacing * fontDirection;
  7831. x += charWidth;
  7832. if (restoreNeeded) {
  7833. ctx.restore();
  7834. }
  7835. }
  7836. if (vertical) {
  7837. current.y -= x * textHScale;
  7838. } else {
  7839. current.x += x * textHScale;
  7840. }
  7841. ctx.restore();
  7842. },
  7843. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  7844. // Type3 fonts - each glyph is a "mini-PDF"
  7845. var ctx = this.ctx;
  7846. var current = this.current;
  7847. var font = current.font;
  7848. var fontSize = current.fontSize;
  7849. var fontDirection = current.fontDirection;
  7850. var spacingDir = font.vertical ? 1 : -1;
  7851. var charSpacing = current.charSpacing;
  7852. var wordSpacing = current.wordSpacing;
  7853. var textHScale = current.textHScale * fontDirection;
  7854. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  7855. var glyphsLength = glyphs.length;
  7856. var isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE;
  7857. var i, glyph, width, spacingLength;
  7858. if (isTextInvisible || fontSize === 0) {
  7859. return;
  7860. }
  7861. this.cachedGetSinglePixelWidth = null;
  7862. ctx.save();
  7863. ctx.transform.apply(ctx, current.textMatrix);
  7864. ctx.translate(current.x, current.y);
  7865. ctx.scale(textHScale, fontDirection);
  7866. for (i = 0; i < glyphsLength; ++i) {
  7867. glyph = glyphs[i];
  7868. if (isNum(glyph)) {
  7869. spacingLength = spacingDir * glyph * fontSize / 1000;
  7870. this.ctx.translate(spacingLength, 0);
  7871. current.x += spacingLength * textHScale;
  7872. continue;
  7873. }
  7874. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7875. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  7876. if (!operatorList) {
  7877. warn('Type3 character \"' + glyph.operatorListId + '\" is not available');
  7878. continue;
  7879. }
  7880. this.processingType3 = glyph;
  7881. this.save();
  7882. ctx.scale(fontSize, fontSize);
  7883. ctx.transform.apply(ctx, fontMatrix);
  7884. this.executeOperatorList(operatorList);
  7885. this.restore();
  7886. var transformed = Util.applyTransform([
  7887. glyph.width,
  7888. 0
  7889. ], fontMatrix);
  7890. width = transformed[0] * fontSize + spacing;
  7891. ctx.translate(width, 0);
  7892. current.x += width * textHScale;
  7893. }
  7894. ctx.restore();
  7895. this.processingType3 = null;
  7896. },
  7897. // Type3 fonts
  7898. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  7899. },
  7900. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  7901. // TODO According to the spec we're also suppose to ignore any operators
  7902. // that set color or include images while processing this type3 font.
  7903. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  7904. this.clip();
  7905. this.endPath();
  7906. },
  7907. // Color
  7908. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  7909. var pattern;
  7910. if (IR[0] === 'TilingPattern') {
  7911. var color = IR[1];
  7912. var baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice();
  7913. var self = this;
  7914. var canvasGraphicsFactory = {
  7915. createCanvasGraphics: function (ctx) {
  7916. return new CanvasGraphics(ctx, self.commonObjs, self.objs);
  7917. }
  7918. };
  7919. pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
  7920. } else {
  7921. pattern = getShadingPatternFromIR(IR);
  7922. }
  7923. return pattern;
  7924. },
  7925. setStrokeColorN: function CanvasGraphics_setStrokeColorN()
  7926. /*...*/
  7927. {
  7928. this.current.strokeColor = this.getColorN_Pattern(arguments);
  7929. },
  7930. setFillColorN: function CanvasGraphics_setFillColorN()
  7931. /*...*/
  7932. {
  7933. this.current.fillColor = this.getColorN_Pattern(arguments);
  7934. this.current.patternFill = true;
  7935. },
  7936. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  7937. var color = Util.makeCssRgb(r, g, b);
  7938. this.ctx.strokeStyle = color;
  7939. this.current.strokeColor = color;
  7940. },
  7941. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  7942. var color = Util.makeCssRgb(r, g, b);
  7943. this.ctx.fillStyle = color;
  7944. this.current.fillColor = color;
  7945. this.current.patternFill = false;
  7946. },
  7947. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  7948. var ctx = this.ctx;
  7949. this.save();
  7950. var pattern = getShadingPatternFromIR(patternIR);
  7951. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  7952. var inv = ctx.mozCurrentTransformInverse;
  7953. if (inv) {
  7954. var canvas = ctx.canvas;
  7955. var width = canvas.width;
  7956. var height = canvas.height;
  7957. var bl = Util.applyTransform([
  7958. 0,
  7959. 0
  7960. ], inv);
  7961. var br = Util.applyTransform([
  7962. 0,
  7963. height
  7964. ], inv);
  7965. var ul = Util.applyTransform([
  7966. width,
  7967. 0
  7968. ], inv);
  7969. var ur = Util.applyTransform([
  7970. width,
  7971. height
  7972. ], inv);
  7973. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  7974. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  7975. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  7976. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  7977. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  7978. } else {
  7979. // HACK to draw the gradient onto an infinite rectangle.
  7980. // PDF gradients are drawn across the entire image while
  7981. // Canvas only allows gradients to be drawn in a rectangle
  7982. // The following bug should allow us to remove this.
  7983. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  7984. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  7985. }
  7986. this.restore();
  7987. },
  7988. // Images
  7989. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  7990. error('Should not call beginInlineImage');
  7991. },
  7992. beginImageData: function CanvasGraphics_beginImageData() {
  7993. error('Should not call beginImageData');
  7994. },
  7995. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix, bbox) {
  7996. this.save();
  7997. this.baseTransformStack.push(this.baseTransform);
  7998. if (isArray(matrix) && 6 === matrix.length) {
  7999. this.transform.apply(this, matrix);
  8000. }
  8001. this.baseTransform = this.ctx.mozCurrentTransform;
  8002. if (isArray(bbox) && 4 === bbox.length) {
  8003. var width = bbox[2] - bbox[0];
  8004. var height = bbox[3] - bbox[1];
  8005. this.ctx.rect(bbox[0], bbox[1], width, height);
  8006. this.clip();
  8007. this.endPath();
  8008. }
  8009. },
  8010. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  8011. this.restore();
  8012. this.baseTransform = this.baseTransformStack.pop();
  8013. },
  8014. beginGroup: function CanvasGraphics_beginGroup(group) {
  8015. this.save();
  8016. var currentCtx = this.ctx;
  8017. // TODO non-isolated groups - according to Rik at adobe non-isolated
  8018. // group results aren't usually that different and they even have tools
  8019. // that ignore this setting. Notes from Rik on implementing:
  8020. // - When you encounter an transparency group, create a new canvas with
  8021. // the dimensions of the bbox
  8022. // - copy the content from the previous canvas to the new canvas
  8023. // - draw as usual
  8024. // - remove the backdrop alpha:
  8025. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  8026. // value of your transparency group and 'alphaBackdrop' the alpha of the
  8027. // backdrop
  8028. // - remove background color:
  8029. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  8030. if (!group.isolated) {
  8031. info('TODO: Support non-isolated groups.');
  8032. }
  8033. // TODO knockout - supposedly possible with the clever use of compositing
  8034. // modes.
  8035. if (group.knockout) {
  8036. warn('Knockout groups not supported.');
  8037. }
  8038. var currentTransform = currentCtx.mozCurrentTransform;
  8039. if (group.matrix) {
  8040. currentCtx.transform.apply(currentCtx, group.matrix);
  8041. }
  8042. assert(group.bbox, 'Bounding box is required.');
  8043. // Based on the current transform figure out how big the bounding box
  8044. // will actually be.
  8045. var bounds = Util.getAxialAlignedBoundingBox(group.bbox, currentCtx.mozCurrentTransform);
  8046. // Clip the bounding box to the current canvas.
  8047. var canvasBounds = [
  8048. 0,
  8049. 0,
  8050. currentCtx.canvas.width,
  8051. currentCtx.canvas.height
  8052. ];
  8053. bounds = Util.intersect(bounds, canvasBounds) || [
  8054. 0,
  8055. 0,
  8056. 0,
  8057. 0
  8058. ];
  8059. // Use ceil in case we're between sizes so we don't create canvas that is
  8060. // too small and make the canvas at least 1x1 pixels.
  8061. var offsetX = Math.floor(bounds[0]);
  8062. var offsetY = Math.floor(bounds[1]);
  8063. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  8064. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  8065. var scaleX = 1, scaleY = 1;
  8066. if (drawnWidth > MAX_GROUP_SIZE) {
  8067. scaleX = drawnWidth / MAX_GROUP_SIZE;
  8068. drawnWidth = MAX_GROUP_SIZE;
  8069. }
  8070. if (drawnHeight > MAX_GROUP_SIZE) {
  8071. scaleY = drawnHeight / MAX_GROUP_SIZE;
  8072. drawnHeight = MAX_GROUP_SIZE;
  8073. }
  8074. var cacheId = 'groupAt' + this.groupLevel;
  8075. if (group.smask) {
  8076. // Using two cache entries is case if masks are used one after another.
  8077. cacheId += '_smask_' + this.smaskCounter++ % 2;
  8078. }
  8079. var scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  8080. var groupCtx = scratchCanvas.context;
  8081. // Since we created a new canvas that is just the size of the bounding box
  8082. // we have to translate the group ctx.
  8083. groupCtx.scale(1 / scaleX, 1 / scaleY);
  8084. groupCtx.translate(-offsetX, -offsetY);
  8085. groupCtx.transform.apply(groupCtx, currentTransform);
  8086. if (group.smask) {
  8087. // Saving state and cached mask to be used in setGState.
  8088. this.smaskStack.push({
  8089. canvas: scratchCanvas.canvas,
  8090. context: groupCtx,
  8091. offsetX: offsetX,
  8092. offsetY: offsetY,
  8093. scaleX: scaleX,
  8094. scaleY: scaleY,
  8095. subtype: group.smask.subtype,
  8096. backdrop: group.smask.backdrop,
  8097. transferMap: group.smask.transferMap || null,
  8098. startTransformInverse: null
  8099. });
  8100. } else
  8101. // used during suspend operation
  8102. {
  8103. // Setup the current ctx so when the group is popped we draw it at the
  8104. // right location.
  8105. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  8106. currentCtx.translate(offsetX, offsetY);
  8107. currentCtx.scale(scaleX, scaleY);
  8108. }
  8109. // The transparency group inherits all off the current graphics state
  8110. // except the blend mode, soft mask, and alpha constants.
  8111. copyCtxState(currentCtx, groupCtx);
  8112. this.ctx = groupCtx;
  8113. this.setGState([
  8114. [
  8115. 'BM',
  8116. 'Normal'
  8117. ],
  8118. [
  8119. 'ca',
  8120. 1
  8121. ],
  8122. [
  8123. 'CA',
  8124. 1
  8125. ]
  8126. ]);
  8127. this.groupStack.push(currentCtx);
  8128. this.groupLevel++;
  8129. // Reseting mask state, masks will be applied on restore of the group.
  8130. this.current.activeSMask = null;
  8131. },
  8132. endGroup: function CanvasGraphics_endGroup(group) {
  8133. this.groupLevel--;
  8134. var groupCtx = this.ctx;
  8135. this.ctx = this.groupStack.pop();
  8136. // Turn off image smoothing to avoid sub pixel interpolation which can
  8137. // look kind of blurry for some pdfs.
  8138. if (this.ctx.imageSmoothingEnabled !== undefined) {
  8139. this.ctx.imageSmoothingEnabled = false;
  8140. } else {
  8141. this.ctx.mozImageSmoothingEnabled = false;
  8142. }
  8143. if (group.smask) {
  8144. this.tempSMask = this.smaskStack.pop();
  8145. } else {
  8146. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  8147. }
  8148. this.restore();
  8149. },
  8150. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  8151. this.save();
  8152. this.current = new CanvasExtraState();
  8153. if (this.baseTransform) {
  8154. this.ctx.setTransform.apply(this.ctx, this.baseTransform);
  8155. }
  8156. },
  8157. endAnnotations: function CanvasGraphics_endAnnotations() {
  8158. this.restore();
  8159. },
  8160. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform, matrix) {
  8161. this.save();
  8162. if (isArray(rect) && 4 === rect.length) {
  8163. var width = rect[2] - rect[0];
  8164. var height = rect[3] - rect[1];
  8165. this.ctx.rect(rect[0], rect[1], width, height);
  8166. this.clip();
  8167. this.endPath();
  8168. }
  8169. this.transform.apply(this, transform);
  8170. this.transform.apply(this, matrix);
  8171. },
  8172. endAnnotation: function CanvasGraphics_endAnnotation() {
  8173. this.restore();
  8174. },
  8175. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  8176. var domImage = this.objs.get(objId);
  8177. if (!domImage) {
  8178. warn('Dependent image isn\'t ready yet');
  8179. return;
  8180. }
  8181. this.save();
  8182. var ctx = this.ctx;
  8183. // scale the image to the unit square
  8184. ctx.scale(1 / w, -1 / h);
  8185. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height, 0, -h, w, h);
  8186. if (this.imageLayer) {
  8187. var currentTransform = ctx.mozCurrentTransformInverse;
  8188. var position = this.getCanvasPosition(0, 0);
  8189. this.imageLayer.appendImage({
  8190. objId: objId,
  8191. left: position[0],
  8192. top: position[1],
  8193. width: w / currentTransform[0],
  8194. height: h / currentTransform[3]
  8195. });
  8196. }
  8197. this.restore();
  8198. },
  8199. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  8200. var ctx = this.ctx;
  8201. var width = img.width, height = img.height;
  8202. var fillColor = this.current.fillColor;
  8203. var isPatternFill = this.current.patternFill;
  8204. var glyph = this.processingType3;
  8205. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  8206. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  8207. glyph.compiled = compileType3Glyph({
  8208. data: img.data,
  8209. width: width,
  8210. height: height
  8211. });
  8212. } else {
  8213. glyph.compiled = null;
  8214. }
  8215. }
  8216. if (glyph && glyph.compiled) {
  8217. glyph.compiled(ctx);
  8218. return;
  8219. }
  8220. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height);
  8221. var maskCtx = maskCanvas.context;
  8222. maskCtx.save();
  8223. putBinaryImageMask(maskCtx, img);
  8224. maskCtx.globalCompositeOperation = 'source-in';
  8225. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  8226. maskCtx.fillRect(0, 0, width, height);
  8227. maskCtx.restore();
  8228. this.paintInlineImageXObject(maskCanvas.canvas);
  8229. },
  8230. paintImageMaskXObjectRepeat: function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX, scaleY, positions) {
  8231. var width = imgData.width;
  8232. var height = imgData.height;
  8233. var fillColor = this.current.fillColor;
  8234. var isPatternFill = this.current.patternFill;
  8235. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height);
  8236. var maskCtx = maskCanvas.context;
  8237. maskCtx.save();
  8238. putBinaryImageMask(maskCtx, imgData);
  8239. maskCtx.globalCompositeOperation = 'source-in';
  8240. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  8241. maskCtx.fillRect(0, 0, width, height);
  8242. maskCtx.restore();
  8243. var ctx = this.ctx;
  8244. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  8245. ctx.save();
  8246. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  8247. ctx.scale(1, -1);
  8248. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  8249. ctx.restore();
  8250. }
  8251. },
  8252. paintImageMaskXObjectGroup: function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  8253. var ctx = this.ctx;
  8254. var fillColor = this.current.fillColor;
  8255. var isPatternFill = this.current.patternFill;
  8256. for (var i = 0, ii = images.length; i < ii; i++) {
  8257. var image = images[i];
  8258. var width = image.width, height = image.height;
  8259. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height);
  8260. var maskCtx = maskCanvas.context;
  8261. maskCtx.save();
  8262. putBinaryImageMask(maskCtx, image);
  8263. maskCtx.globalCompositeOperation = 'source-in';
  8264. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  8265. maskCtx.fillRect(0, 0, width, height);
  8266. maskCtx.restore();
  8267. ctx.save();
  8268. ctx.transform.apply(ctx, image.transform);
  8269. ctx.scale(1, -1);
  8270. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  8271. ctx.restore();
  8272. }
  8273. },
  8274. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  8275. var imgData = this.objs.get(objId);
  8276. if (!imgData) {
  8277. warn('Dependent image isn\'t ready yet');
  8278. return;
  8279. }
  8280. this.paintInlineImageXObject(imgData);
  8281. },
  8282. paintImageXObjectRepeat: function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  8283. var imgData = this.objs.get(objId);
  8284. if (!imgData) {
  8285. warn('Dependent image isn\'t ready yet');
  8286. return;
  8287. }
  8288. var width = imgData.width;
  8289. var height = imgData.height;
  8290. var map = [];
  8291. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  8292. map.push({
  8293. transform: [
  8294. scaleX,
  8295. 0,
  8296. 0,
  8297. scaleY,
  8298. positions[i],
  8299. positions[i + 1]
  8300. ],
  8301. x: 0,
  8302. y: 0,
  8303. w: width,
  8304. h: height
  8305. });
  8306. }
  8307. this.paintInlineImageXObjectGroup(imgData, map);
  8308. },
  8309. paintInlineImageXObject: function CanvasGraphics_paintInlineImageXObject(imgData) {
  8310. var width = imgData.width;
  8311. var height = imgData.height;
  8312. var ctx = this.ctx;
  8313. this.save();
  8314. // scale the image to the unit square
  8315. ctx.scale(1 / width, -1 / height);
  8316. var currentTransform = ctx.mozCurrentTransformInverse;
  8317. var a = currentTransform[0], b = currentTransform[1];
  8318. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  8319. var c = currentTransform[2], d = currentTransform[3];
  8320. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  8321. var imgToPaint, tmpCanvas;
  8322. // instanceof HTMLElement does not work in jsdom node.js module
  8323. if (imgData instanceof HTMLElement || !imgData.data) {
  8324. imgToPaint = imgData;
  8325. } else {
  8326. tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', width, height);
  8327. var tmpCtx = tmpCanvas.context;
  8328. putBinaryImageData(tmpCtx, imgData);
  8329. imgToPaint = tmpCanvas.canvas;
  8330. }
  8331. var paintWidth = width, paintHeight = height;
  8332. var tmpCanvasId = 'prescale1';
  8333. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  8334. // pixels during drawImage operation, painting on the temporary canvas(es)
  8335. // that are twice smaller in size
  8336. while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
  8337. var newWidth = paintWidth, newHeight = paintHeight;
  8338. if (widthScale > 2 && paintWidth > 1) {
  8339. newWidth = Math.ceil(paintWidth / 2);
  8340. widthScale /= paintWidth / newWidth;
  8341. }
  8342. if (heightScale > 2 && paintHeight > 1) {
  8343. newHeight = Math.ceil(paintHeight / 2);
  8344. heightScale /= paintHeight / newHeight;
  8345. }
  8346. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  8347. tmpCtx = tmpCanvas.context;
  8348. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  8349. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
  8350. imgToPaint = tmpCanvas.canvas;
  8351. paintWidth = newWidth;
  8352. paintHeight = newHeight;
  8353. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  8354. }
  8355. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, -height, width, height);
  8356. if (this.imageLayer) {
  8357. var position = this.getCanvasPosition(0, -height);
  8358. this.imageLayer.appendImage({
  8359. imgData: imgData,
  8360. left: position[0],
  8361. top: position[1],
  8362. width: width / currentTransform[0],
  8363. height: height / currentTransform[3]
  8364. });
  8365. }
  8366. this.restore();
  8367. },
  8368. paintInlineImageXObjectGroup: function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  8369. var ctx = this.ctx;
  8370. var w = imgData.width;
  8371. var h = imgData.height;
  8372. var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h);
  8373. var tmpCtx = tmpCanvas.context;
  8374. putBinaryImageData(tmpCtx, imgData);
  8375. for (var i = 0, ii = map.length; i < ii; i++) {
  8376. var entry = map[i];
  8377. ctx.save();
  8378. ctx.transform.apply(ctx, entry.transform);
  8379. ctx.scale(1, -1);
  8380. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  8381. if (this.imageLayer) {
  8382. var position = this.getCanvasPosition(entry.x, entry.y);
  8383. this.imageLayer.appendImage({
  8384. imgData: imgData,
  8385. left: position[0],
  8386. top: position[1],
  8387. width: w,
  8388. height: h
  8389. });
  8390. }
  8391. ctx.restore();
  8392. }
  8393. },
  8394. paintSolidColorImageMask: function CanvasGraphics_paintSolidColorImageMask() {
  8395. this.ctx.fillRect(0, 0, 1, 1);
  8396. },
  8397. paintXObject: function CanvasGraphics_paintXObject() {
  8398. warn('Unsupported \'paintXObject\' command.');
  8399. },
  8400. // Marked content
  8401. markPoint: function CanvasGraphics_markPoint(tag) {
  8402. },
  8403. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  8404. },
  8405. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  8406. },
  8407. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(tag, properties) {
  8408. },
  8409. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  8410. },
  8411. // Compatibility
  8412. beginCompat: function CanvasGraphics_beginCompat() {
  8413. },
  8414. endCompat: function CanvasGraphics_endCompat() {
  8415. },
  8416. // Helper functions
  8417. consumePath: function CanvasGraphics_consumePath() {
  8418. var ctx = this.ctx;
  8419. if (this.pendingClip) {
  8420. if (this.pendingClip === EO_CLIP) {
  8421. if (ctx.mozFillRule !== undefined) {
  8422. ctx.mozFillRule = 'evenodd';
  8423. ctx.clip();
  8424. ctx.mozFillRule = 'nonzero';
  8425. } else {
  8426. ctx.clip('evenodd');
  8427. }
  8428. } else {
  8429. ctx.clip();
  8430. }
  8431. this.pendingClip = null;
  8432. }
  8433. ctx.beginPath();
  8434. },
  8435. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  8436. if (this.cachedGetSinglePixelWidth === null) {
  8437. // NOTE: The `save` and `restore` commands used below is a workaround
  8438. // that is necessary in order to prevent `mozCurrentTransformInverse`
  8439. // from intermittently returning incorrect values in Firefox, see:
  8440. // https://github.com/mozilla/pdf.js/issues/7188.
  8441. this.ctx.save();
  8442. var inverse = this.ctx.mozCurrentTransformInverse;
  8443. this.ctx.restore();
  8444. // max of the current horizontal and vertical scale
  8445. this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(inverse[0] * inverse[0] + inverse[1] * inverse[1], inverse[2] * inverse[2] + inverse[3] * inverse[3]));
  8446. }
  8447. return this.cachedGetSinglePixelWidth;
  8448. },
  8449. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  8450. var transform = this.ctx.mozCurrentTransform;
  8451. return [
  8452. transform[0] * x + transform[2] * y + transform[4],
  8453. transform[1] * x + transform[3] * y + transform[5]
  8454. ];
  8455. }
  8456. };
  8457. for (var op in OPS) {
  8458. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  8459. }
  8460. return CanvasGraphics;
  8461. }();
  8462. exports.CanvasGraphics = CanvasGraphics;
  8463. exports.createScratchCanvas = createScratchCanvas;
  8464. }));
  8465. (function (root, factory) {
  8466. factory(root.pdfjsDisplayAPI = {}, root.pdfjsSharedUtil, root.pdfjsDisplayFontLoader, root.pdfjsDisplayCanvas, root.pdfjsDisplayMetadata, root.pdfjsDisplayDOMUtils);
  8467. }(this, function (exports, sharedUtil, displayFontLoader, displayCanvas, displayMetadata, displayDOMUtils, amdRequire) {
  8468. var InvalidPDFException = sharedUtil.InvalidPDFException;
  8469. var MessageHandler = sharedUtil.MessageHandler;
  8470. var MissingPDFException = sharedUtil.MissingPDFException;
  8471. var PageViewport = sharedUtil.PageViewport;
  8472. var PasswordResponses = sharedUtil.PasswordResponses;
  8473. var PasswordException = sharedUtil.PasswordException;
  8474. var StatTimer = sharedUtil.StatTimer;
  8475. var UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  8476. var UnknownErrorException = sharedUtil.UnknownErrorException;
  8477. var Util = sharedUtil.Util;
  8478. var createPromiseCapability = sharedUtil.createPromiseCapability;
  8479. var error = sharedUtil.error;
  8480. var deprecated = sharedUtil.deprecated;
  8481. var getVerbosityLevel = sharedUtil.getVerbosityLevel;
  8482. var info = sharedUtil.info;
  8483. var isInt = sharedUtil.isInt;
  8484. var isArray = sharedUtil.isArray;
  8485. var isArrayBuffer = sharedUtil.isArrayBuffer;
  8486. var isSameOrigin = sharedUtil.isSameOrigin;
  8487. var loadJpegStream = sharedUtil.loadJpegStream;
  8488. var stringToBytes = sharedUtil.stringToBytes;
  8489. var globalScope = sharedUtil.globalScope;
  8490. var warn = sharedUtil.warn;
  8491. var FontFaceObject = displayFontLoader.FontFaceObject;
  8492. var FontLoader = displayFontLoader.FontLoader;
  8493. var CanvasGraphics = displayCanvas.CanvasGraphics;
  8494. var createScratchCanvas = displayCanvas.createScratchCanvas;
  8495. var Metadata = displayMetadata.Metadata;
  8496. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  8497. var DEFAULT_RANGE_CHUNK_SIZE = 65536;
  8498. // 2^16 = 65536
  8499. var isWorkerDisabled = false;
  8500. var workerSrc;
  8501. var isPostMessageTransfersDisabled = false;
  8502. var fakeWorkerFilesLoader = null;
  8503. var useRequireEnsure = false;
  8504. // For GENERIC build we need add support of different fake file loaders
  8505. // for different frameworks.
  8506. if (typeof window === 'undefined') {
  8507. // node.js - disable worker and set require.ensure.
  8508. isWorkerDisabled = true;
  8509. if (typeof require.ensure === 'undefined') {
  8510. require.ensure = require('node-ensure');
  8511. }
  8512. useRequireEnsure = true;
  8513. }
  8514. if (typeof __webpack_require__ !== 'undefined') {
  8515. useRequireEnsure = true;
  8516. }
  8517. if (typeof requirejs !== 'undefined' && requirejs.toUrl) {
  8518. workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js');
  8519. }
  8520. var dynamicLoaderSupported = typeof requirejs !== 'undefined' && requirejs.load;
  8521. fakeWorkerFilesLoader = useRequireEnsure ? function (callback) {
  8522. require.ensure([], function () {
  8523. var worker = require('./pdf.worker.js');
  8524. callback(worker.WorkerMessageHandler);
  8525. });
  8526. } : dynamicLoaderSupported ? function (callback) {
  8527. requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) {
  8528. callback(worker.WorkerMessageHandler);
  8529. });
  8530. } : null;
  8531. /**
  8532. * Document initialization / loading parameters object.
  8533. *
  8534. * @typedef {Object} DocumentInitParameters
  8535. * @property {string} url - The URL of the PDF.
  8536. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays
  8537. * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,
  8538. * use atob() to convert it to a binary string first.
  8539. * @property {Object} httpHeaders - Basic authentication headers.
  8540. * @property {boolean} withCredentials - Indicates whether or not cross-site
  8541. * Access-Control requests should be made using credentials such as cookies
  8542. * or authorization headers. The default is false.
  8543. * @property {string} password - For decrypting password-protected PDFs.
  8544. * @property {TypedArray} initialData - A typed array with the first portion or
  8545. * all of the pdf data. Used by the extension since some data is already
  8546. * loaded before the switch to range requests.
  8547. * @property {number} length - The PDF file length. It's used for progress
  8548. * reports and range requests operations.
  8549. * @property {PDFDataRangeTransport} range
  8550. * @property {number} rangeChunkSize - Optional parameter to specify
  8551. * maximum number of bytes fetched per range request. The default value is
  8552. * 2^16 = 65536.
  8553. * @property {PDFWorker} worker - The worker that will be used for the loading
  8554. * and parsing of the PDF data.
  8555. */
  8556. /**
  8557. * @typedef {Object} PDFDocumentStats
  8558. * @property {Array} streamTypes - Used stream types in the document (an item
  8559. * is set to true if specific stream ID was used in the document).
  8560. * @property {Array} fontTypes - Used font type in the document (an item is set
  8561. * to true if specific font ID was used in the document).
  8562. */
  8563. /**
  8564. * This is the main entry point for loading a PDF and interacting with it.
  8565. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  8566. * is used, which means it must follow the same origin rules that any XHR does
  8567. * e.g. No cross domain requests without CORS.
  8568. *
  8569. * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src
  8570. * Can be a url to where a PDF is located, a typed array (Uint8Array)
  8571. * already populated with data or parameter object.
  8572. *
  8573. * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used
  8574. * if you want to manually serve range requests for data in the PDF.
  8575. *
  8576. * @param {function} passwordCallback (deprecated) It is used to request a
  8577. * password if wrong or no password was provided. The callback receives two
  8578. * parameters: function that needs to be called with new password and reason
  8579. * (see {PasswordResponses}).
  8580. *
  8581. * @param {function} progressCallback (deprecated) It is used to be able to
  8582. * monitor the loading progress of the PDF file (necessary to implement e.g.
  8583. * a loading bar). The callback receives an {Object} with the properties:
  8584. * {number} loaded and {number} total.
  8585. *
  8586. * @return {PDFDocumentLoadingTask}
  8587. */
  8588. function getDocument(src, pdfDataRangeTransport, passwordCallback, progressCallback) {
  8589. var task = new PDFDocumentLoadingTask();
  8590. // Support of the obsolete arguments (for compatibility with API v1.0)
  8591. if (arguments.length > 1) {
  8592. deprecated('getDocument is called with pdfDataRangeTransport, ' + 'passwordCallback or progressCallback argument');
  8593. }
  8594. if (pdfDataRangeTransport) {
  8595. if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) {
  8596. // Not a PDFDataRangeTransport instance, trying to add missing properties.
  8597. pdfDataRangeTransport = Object.create(pdfDataRangeTransport);
  8598. pdfDataRangeTransport.length = src.length;
  8599. pdfDataRangeTransport.initialData = src.initialData;
  8600. if (!pdfDataRangeTransport.abort) {
  8601. pdfDataRangeTransport.abort = function () {
  8602. };
  8603. }
  8604. }
  8605. src = Object.create(src);
  8606. src.range = pdfDataRangeTransport;
  8607. }
  8608. task.onPassword = passwordCallback || null;
  8609. task.onProgress = progressCallback || null;
  8610. var source;
  8611. if (typeof src === 'string') {
  8612. source = { url: src };
  8613. } else if (isArrayBuffer(src)) {
  8614. source = { data: src };
  8615. } else if (src instanceof PDFDataRangeTransport) {
  8616. source = { range: src };
  8617. } else {
  8618. if (typeof src !== 'object') {
  8619. error('Invalid parameter in getDocument, need either Uint8Array, ' + 'string or a parameter object');
  8620. }
  8621. if (!src.url && !src.data && !src.range) {
  8622. error('Invalid parameter object: need either .data, .range or .url');
  8623. }
  8624. source = src;
  8625. }
  8626. var params = {};
  8627. var rangeTransport = null;
  8628. var worker = null;
  8629. for (var key in source) {
  8630. if (key === 'url' && typeof window !== 'undefined') {
  8631. // The full path is required in the 'url' field.
  8632. params[key] = new URL(source[key], window.location).href;
  8633. continue;
  8634. } else if (key === 'range') {
  8635. rangeTransport = source[key];
  8636. continue;
  8637. } else if (key === 'worker') {
  8638. worker = source[key];
  8639. continue;
  8640. } else if (key === 'data' && !(source[key] instanceof Uint8Array)) {
  8641. // Converting string or array-like data to Uint8Array.
  8642. var pdfBytes = source[key];
  8643. if (typeof pdfBytes === 'string') {
  8644. params[key] = stringToBytes(pdfBytes);
  8645. } else if (typeof pdfBytes === 'object' && pdfBytes !== null && !isNaN(pdfBytes.length)) {
  8646. params[key] = new Uint8Array(pdfBytes);
  8647. } else if (isArrayBuffer(pdfBytes)) {
  8648. params[key] = new Uint8Array(pdfBytes);
  8649. } else {
  8650. error('Invalid PDF binary data: either typed array, string or ' + 'array-like object is expected in the data property.');
  8651. }
  8652. continue;
  8653. }
  8654. params[key] = source[key];
  8655. }
  8656. params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
  8657. if (!worker) {
  8658. // Worker was not provided -- creating and owning our own.
  8659. worker = new PDFWorker();
  8660. task._worker = worker;
  8661. }
  8662. var docId = task.docId;
  8663. worker.promise.then(function () {
  8664. if (task.destroyed) {
  8665. throw new Error('Loading aborted');
  8666. }
  8667. return _fetchDocument(worker, params, rangeTransport, docId).then(function (workerId) {
  8668. if (task.destroyed) {
  8669. throw new Error('Loading aborted');
  8670. }
  8671. var messageHandler = new MessageHandler(docId, workerId, worker.port);
  8672. var transport = new WorkerTransport(messageHandler, task, rangeTransport);
  8673. task._transport = transport;
  8674. messageHandler.send('Ready', null);
  8675. });
  8676. }).catch(task._capability.reject);
  8677. return task;
  8678. }
  8679. /**
  8680. * Starts fetching of specified PDF document/data.
  8681. * @param {PDFWorker} worker
  8682. * @param {Object} source
  8683. * @param {PDFDataRangeTransport} pdfDataRangeTransport
  8684. * @param {string} docId Unique document id, used as MessageHandler id.
  8685. * @returns {Promise} The promise, which is resolved when worker id of
  8686. * MessageHandler is known.
  8687. * @private
  8688. */
  8689. function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
  8690. if (worker.destroyed) {
  8691. return Promise.reject(new Error('Worker was destroyed'));
  8692. }
  8693. source.disableAutoFetch = getDefaultSetting('disableAutoFetch');
  8694. source.disableStream = getDefaultSetting('disableStream');
  8695. source.chunkedViewerLoading = !!pdfDataRangeTransport;
  8696. if (pdfDataRangeTransport) {
  8697. source.length = pdfDataRangeTransport.length;
  8698. source.initialData = pdfDataRangeTransport.initialData;
  8699. }
  8700. return worker.messageHandler.sendWithPromise('GetDocRequest', {
  8701. docId: docId,
  8702. source: source,
  8703. disableRange: getDefaultSetting('disableRange'),
  8704. maxImageSize: getDefaultSetting('maxImageSize'),
  8705. cMapUrl: getDefaultSetting('cMapUrl'),
  8706. cMapPacked: getDefaultSetting('cMapPacked'),
  8707. disableFontFace: getDefaultSetting('disableFontFace'),
  8708. disableCreateObjectURL: getDefaultSetting('disableCreateObjectURL'),
  8709. postMessageTransfers: getDefaultSetting('postMessageTransfers') && !isPostMessageTransfersDisabled
  8710. }).then(function (workerId) {
  8711. if (worker.destroyed) {
  8712. throw new Error('Worker was destroyed');
  8713. }
  8714. return workerId;
  8715. });
  8716. }
  8717. /**
  8718. * PDF document loading operation.
  8719. * @class
  8720. * @alias PDFDocumentLoadingTask
  8721. */
  8722. var PDFDocumentLoadingTask = function PDFDocumentLoadingTaskClosure() {
  8723. var nextDocumentId = 0;
  8724. /** @constructs PDFDocumentLoadingTask */
  8725. function PDFDocumentLoadingTask() {
  8726. this._capability = createPromiseCapability();
  8727. this._transport = null;
  8728. this._worker = null;
  8729. /**
  8730. * Unique document loading task id -- used in MessageHandlers.
  8731. * @type {string}
  8732. */
  8733. this.docId = 'd' + nextDocumentId++;
  8734. /**
  8735. * Shows if loading task is destroyed.
  8736. * @type {boolean}
  8737. */
  8738. this.destroyed = false;
  8739. /**
  8740. * Callback to request a password if wrong or no password was provided.
  8741. * The callback receives two parameters: function that needs to be called
  8742. * with new password and reason (see {PasswordResponses}).
  8743. */
  8744. this.onPassword = null;
  8745. /**
  8746. * Callback to be able to monitor the loading progress of the PDF file
  8747. * (necessary to implement e.g. a loading bar). The callback receives
  8748. * an {Object} with the properties: {number} loaded and {number} total.
  8749. */
  8750. this.onProgress = null;
  8751. /**
  8752. * Callback to when unsupported feature is used. The callback receives
  8753. * an {UNSUPPORTED_FEATURES} argument.
  8754. */
  8755. this.onUnsupportedFeature = null;
  8756. }
  8757. PDFDocumentLoadingTask.prototype = /** @lends PDFDocumentLoadingTask.prototype */
  8758. {
  8759. /**
  8760. * @return {Promise}
  8761. */
  8762. get promise() {
  8763. return this._capability.promise;
  8764. },
  8765. /**
  8766. * Aborts all network requests and destroys worker.
  8767. * @return {Promise} A promise that is resolved after destruction activity
  8768. * is completed.
  8769. */
  8770. destroy: function () {
  8771. this.destroyed = true;
  8772. var transportDestroyed = !this._transport ? Promise.resolve() : this._transport.destroy();
  8773. return transportDestroyed.then(function () {
  8774. this._transport = null;
  8775. if (this._worker) {
  8776. this._worker.destroy();
  8777. this._worker = null;
  8778. }
  8779. }.bind(this));
  8780. },
  8781. /**
  8782. * Registers callbacks to indicate the document loading completion.
  8783. *
  8784. * @param {function} onFulfilled The callback for the loading completion.
  8785. * @param {function} onRejected The callback for the loading failure.
  8786. * @return {Promise} A promise that is resolved after the onFulfilled or
  8787. * onRejected callback.
  8788. */
  8789. then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) {
  8790. return this.promise.then.apply(this.promise, arguments);
  8791. }
  8792. };
  8793. return PDFDocumentLoadingTask;
  8794. }();
  8795. /**
  8796. * Abstract class to support range requests file loading.
  8797. * @class
  8798. * @alias PDFDataRangeTransport
  8799. * @param {number} length
  8800. * @param {Uint8Array} initialData
  8801. */
  8802. var PDFDataRangeTransport = function pdfDataRangeTransportClosure() {
  8803. function PDFDataRangeTransport(length, initialData) {
  8804. this.length = length;
  8805. this.initialData = initialData;
  8806. this._rangeListeners = [];
  8807. this._progressListeners = [];
  8808. this._progressiveReadListeners = [];
  8809. this._readyCapability = createPromiseCapability();
  8810. }
  8811. PDFDataRangeTransport.prototype = /** @lends PDFDataRangeTransport.prototype */
  8812. {
  8813. addRangeListener: function PDFDataRangeTransport_addRangeListener(listener) {
  8814. this._rangeListeners.push(listener);
  8815. },
  8816. addProgressListener: function PDFDataRangeTransport_addProgressListener(listener) {
  8817. this._progressListeners.push(listener);
  8818. },
  8819. addProgressiveReadListener: function PDFDataRangeTransport_addProgressiveReadListener(listener) {
  8820. this._progressiveReadListeners.push(listener);
  8821. },
  8822. onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {
  8823. var listeners = this._rangeListeners;
  8824. for (var i = 0, n = listeners.length; i < n; ++i) {
  8825. listeners[i](begin, chunk);
  8826. }
  8827. },
  8828. onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {
  8829. this._readyCapability.promise.then(function () {
  8830. var listeners = this._progressListeners;
  8831. for (var i = 0, n = listeners.length; i < n; ++i) {
  8832. listeners[i](loaded);
  8833. }
  8834. }.bind(this));
  8835. },
  8836. onDataProgressiveRead: function PDFDataRangeTransport_onDataProgress(chunk) {
  8837. this._readyCapability.promise.then(function () {
  8838. var listeners = this._progressiveReadListeners;
  8839. for (var i = 0, n = listeners.length; i < n; ++i) {
  8840. listeners[i](chunk);
  8841. }
  8842. }.bind(this));
  8843. },
  8844. transportReady: function PDFDataRangeTransport_transportReady() {
  8845. this._readyCapability.resolve();
  8846. },
  8847. requestDataRange: function PDFDataRangeTransport_requestDataRange(begin, end) {
  8848. throw new Error('Abstract method PDFDataRangeTransport.requestDataRange');
  8849. },
  8850. abort: function PDFDataRangeTransport_abort() {
  8851. }
  8852. };
  8853. return PDFDataRangeTransport;
  8854. }();
  8855. /**
  8856. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  8857. * properties that can be read synchronously.
  8858. * @class
  8859. * @alias PDFDocumentProxy
  8860. */
  8861. var PDFDocumentProxy = function PDFDocumentProxyClosure() {
  8862. function PDFDocumentProxy(pdfInfo, transport, loadingTask) {
  8863. this.pdfInfo = pdfInfo;
  8864. this.transport = transport;
  8865. this.loadingTask = loadingTask;
  8866. }
  8867. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */
  8868. {
  8869. /**
  8870. * @return {number} Total number of pages the PDF contains.
  8871. */
  8872. get numPages() {
  8873. return this.pdfInfo.numPages;
  8874. },
  8875. /**
  8876. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  8877. * unique.
  8878. */
  8879. get fingerprint() {
  8880. return this.pdfInfo.fingerprint;
  8881. },
  8882. /**
  8883. * @param {number} pageNumber The page number to get. The first page is 1.
  8884. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  8885. * object.
  8886. */
  8887. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  8888. return this.transport.getPage(pageNumber);
  8889. },
  8890. /**
  8891. * @param {{num: number, gen: number}} ref The page reference. Must have
  8892. * the 'num' and 'gen' properties.
  8893. * @return {Promise} A promise that is resolved with the page index that is
  8894. * associated with the reference.
  8895. */
  8896. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  8897. return this.transport.getPageIndex(ref);
  8898. },
  8899. /**
  8900. * @return {Promise} A promise that is resolved with a lookup table for
  8901. * mapping named destinations to reference numbers.
  8902. *
  8903. * This can be slow for large documents: use getDestination instead
  8904. */
  8905. getDestinations: function PDFDocumentProxy_getDestinations() {
  8906. return this.transport.getDestinations();
  8907. },
  8908. /**
  8909. * @param {string} id The named destination to get.
  8910. * @return {Promise} A promise that is resolved with all information
  8911. * of the given named destination.
  8912. */
  8913. getDestination: function PDFDocumentProxy_getDestination(id) {
  8914. return this.transport.getDestination(id);
  8915. },
  8916. /**
  8917. * @return {Promise} A promise that is resolved with:
  8918. * an Array containing the pageLabels that correspond to the pageIndexes,
  8919. * or `null` when no pageLabels are present in the PDF file.
  8920. */
  8921. getPageLabels: function PDFDocumentProxy_getPageLabels() {
  8922. return this.transport.getPageLabels();
  8923. },
  8924. /**
  8925. * @return {Promise} A promise that is resolved with a lookup table for
  8926. * mapping named attachments to their content.
  8927. */
  8928. getAttachments: function PDFDocumentProxy_getAttachments() {
  8929. return this.transport.getAttachments();
  8930. },
  8931. /**
  8932. * @return {Promise} A promise that is resolved with an array of all the
  8933. * JavaScript strings in the name tree.
  8934. */
  8935. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  8936. return this.transport.getJavaScript();
  8937. },
  8938. /**
  8939. * @return {Promise} A promise that is resolved with an {Array} that is a
  8940. * tree outline (if it has one) of the PDF. The tree is in the format of:
  8941. * [
  8942. * {
  8943. * title: string,
  8944. * bold: boolean,
  8945. * italic: boolean,
  8946. * color: rgb Uint8Array,
  8947. * dest: dest obj,
  8948. * url: string,
  8949. * items: array of more items like this
  8950. * },
  8951. * ...
  8952. * ].
  8953. */
  8954. getOutline: function PDFDocumentProxy_getOutline() {
  8955. return this.transport.getOutline();
  8956. },
  8957. /**
  8958. * @return {Promise} A promise that is resolved with an {Object} that has
  8959. * info and metadata properties. Info is an {Object} filled with anything
  8960. * available in the information dictionary and similarly metadata is a
  8961. * {Metadata} object with information from the metadata section of the PDF.
  8962. */
  8963. getMetadata: function PDFDocumentProxy_getMetadata() {
  8964. return this.transport.getMetadata();
  8965. },
  8966. /**
  8967. * @return {Promise} A promise that is resolved with a TypedArray that has
  8968. * the raw data from the PDF.
  8969. */
  8970. getData: function PDFDocumentProxy_getData() {
  8971. return this.transport.getData();
  8972. },
  8973. /**
  8974. * @return {Promise} A promise that is resolved when the document's data
  8975. * is loaded. It is resolved with an {Object} that contains the length
  8976. * property that indicates size of the PDF data in bytes.
  8977. */
  8978. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  8979. return this.transport.downloadInfoCapability.promise;
  8980. },
  8981. /**
  8982. * @return {Promise} A promise this is resolved with current stats about
  8983. * document structures (see {@link PDFDocumentStats}).
  8984. */
  8985. getStats: function PDFDocumentProxy_getStats() {
  8986. return this.transport.getStats();
  8987. },
  8988. /**
  8989. * Cleans up resources allocated by the document, e.g. created @font-face.
  8990. */
  8991. cleanup: function PDFDocumentProxy_cleanup() {
  8992. this.transport.startCleanup();
  8993. },
  8994. /**
  8995. * Destroys current document instance and terminates worker.
  8996. */
  8997. destroy: function PDFDocumentProxy_destroy() {
  8998. return this.loadingTask.destroy();
  8999. }
  9000. };
  9001. return PDFDocumentProxy;
  9002. }();
  9003. /**
  9004. * Page getTextContent parameters.
  9005. *
  9006. * @typedef {Object} getTextContentParameters
  9007. * @property {boolean} normalizeWhitespace - replaces all occurrences of
  9008. * whitespace with standard spaces (0x20). The default value is `false`.
  9009. * @property {boolean} disableCombineTextItems - do not attempt to combine
  9010. * same line {@link TextItem}'s. The default value is `false`.
  9011. */
  9012. /**
  9013. * Page text content.
  9014. *
  9015. * @typedef {Object} TextContent
  9016. * @property {array} items - array of {@link TextItem}
  9017. * @property {Object} styles - {@link TextStyles} objects, indexed by font name.
  9018. */
  9019. /**
  9020. * Page text content part.
  9021. *
  9022. * @typedef {Object} TextItem
  9023. * @property {string} str - text content.
  9024. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  9025. * @property {array} transform - transformation matrix.
  9026. * @property {number} width - width in device space.
  9027. * @property {number} height - height in device space.
  9028. * @property {string} fontName - font name used by pdf.js for converted font.
  9029. */
  9030. /**
  9031. * Text style.
  9032. *
  9033. * @typedef {Object} TextStyle
  9034. * @property {number} ascent - font ascent.
  9035. * @property {number} descent - font descent.
  9036. * @property {boolean} vertical - text is in vertical mode.
  9037. * @property {string} fontFamily - possible font family
  9038. */
  9039. /**
  9040. * Page annotation parameters.
  9041. *
  9042. * @typedef {Object} GetAnnotationsParameters
  9043. * @property {string} intent - Determines the annotations that will be fetched,
  9044. * can be either 'display' (viewable annotations) or 'print'
  9045. * (printable annotations).
  9046. * If the parameter is omitted, all annotations are fetched.
  9047. */
  9048. /**
  9049. * Page render parameters.
  9050. *
  9051. * @typedef {Object} RenderParameters
  9052. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  9053. * @property {PageViewport} viewport - Rendering viewport obtained by
  9054. * calling of PDFPage.getViewport method.
  9055. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  9056. * (default value is 'display').
  9057. * @property {boolean} renderInteractiveForms - (optional) Whether or not
  9058. * interactive form elements are rendered in the display
  9059. * layer. If so, we do not render them on canvas as well.
  9060. * @property {Array} transform - (optional) Additional transform, applied
  9061. * just before viewport transform.
  9062. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  9063. * endLayout and appendImage functions.
  9064. * @property {function} continueCallback - (deprecated) A function that will be
  9065. * called each time the rendering is paused. To continue
  9066. * rendering call the function that is the first argument
  9067. * to the callback.
  9068. */
  9069. /**
  9070. * PDF page operator list.
  9071. *
  9072. * @typedef {Object} PDFOperatorList
  9073. * @property {Array} fnArray - Array containing the operator functions.
  9074. * @property {Array} argsArray - Array containing the arguments of the
  9075. * functions.
  9076. */
  9077. /**
  9078. * Proxy to a PDFPage in the worker thread.
  9079. * @class
  9080. * @alias PDFPageProxy
  9081. */
  9082. var PDFPageProxy = function PDFPageProxyClosure() {
  9083. function PDFPageProxy(pageIndex, pageInfo, transport) {
  9084. this.pageIndex = pageIndex;
  9085. this.pageInfo = pageInfo;
  9086. this.transport = transport;
  9087. this.stats = new StatTimer();
  9088. this.stats.enabled = getDefaultSetting('enableStats');
  9089. this.commonObjs = transport.commonObjs;
  9090. this.objs = new PDFObjects();
  9091. this.cleanupAfterRender = false;
  9092. this.pendingCleanup = false;
  9093. this.intentStates = Object.create(null);
  9094. this.destroyed = false;
  9095. }
  9096. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */
  9097. {
  9098. /**
  9099. * @return {number} Page number of the page. First page is 1.
  9100. */
  9101. get pageNumber() {
  9102. return this.pageIndex + 1;
  9103. },
  9104. /**
  9105. * @return {number} The number of degrees the page is rotated clockwise.
  9106. */
  9107. get rotate() {
  9108. return this.pageInfo.rotate;
  9109. },
  9110. /**
  9111. * @return {Object} The reference that points to this page. It has 'num' and
  9112. * 'gen' properties.
  9113. */
  9114. get ref() {
  9115. return this.pageInfo.ref;
  9116. },
  9117. /**
  9118. * @return {Array} An array of the visible portion of the PDF page in the
  9119. * user space units - [x1, y1, x2, y2].
  9120. */
  9121. get view() {
  9122. return this.pageInfo.view;
  9123. },
  9124. /**
  9125. * @param {number} scale The desired scale of the viewport.
  9126. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  9127. * defaults to the page rotation.
  9128. * @return {PageViewport} Contains 'width' and 'height' properties
  9129. * along with transforms required for rendering.
  9130. */
  9131. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  9132. if (arguments.length < 2) {
  9133. rotate = this.rotate;
  9134. }
  9135. return new PageViewport(this.view, scale, rotate, 0, 0);
  9136. },
  9137. /**
  9138. * @param {GetAnnotationsParameters} params - Annotation parameters.
  9139. * @return {Promise} A promise that is resolved with an {Array} of the
  9140. * annotation objects.
  9141. */
  9142. getAnnotations: function PDFPageProxy_getAnnotations(params) {
  9143. var intent = params && params.intent || null;
  9144. if (!this.annotationsPromise || this.annotationsIntent !== intent) {
  9145. this.annotationsPromise = this.transport.getAnnotations(this.pageIndex, intent);
  9146. this.annotationsIntent = intent;
  9147. }
  9148. return this.annotationsPromise;
  9149. },
  9150. /**
  9151. * Begins the process of rendering a page to the desired context.
  9152. * @param {RenderParameters} params Page render parameters.
  9153. * @return {RenderTask} An object that contains the promise, which
  9154. * is resolved when the page finishes rendering.
  9155. */
  9156. render: function PDFPageProxy_render(params) {
  9157. var stats = this.stats;
  9158. stats.time('Overall');
  9159. // If there was a pending destroy cancel it so no cleanup happens during
  9160. // this call to render.
  9161. this.pendingCleanup = false;
  9162. var renderingIntent = params.intent === 'print' ? 'print' : 'display';
  9163. var renderInteractiveForms = params.renderInteractiveForms === true ? true : /* Default */
  9164. false;
  9165. if (!this.intentStates[renderingIntent]) {
  9166. this.intentStates[renderingIntent] = Object.create(null);
  9167. }
  9168. var intentState = this.intentStates[renderingIntent];
  9169. // If there's no displayReadyCapability yet, then the operatorList
  9170. // was never requested before. Make the request and create the promise.
  9171. if (!intentState.displayReadyCapability) {
  9172. intentState.receivingOperatorList = true;
  9173. intentState.displayReadyCapability = createPromiseCapability();
  9174. intentState.operatorList = {
  9175. fnArray: [],
  9176. argsArray: [],
  9177. lastChunk: false
  9178. };
  9179. this.stats.time('Page Request');
  9180. this.transport.messageHandler.send('RenderPageRequest', {
  9181. pageIndex: this.pageNumber - 1,
  9182. intent: renderingIntent,
  9183. renderInteractiveForms: renderInteractiveForms
  9184. });
  9185. }
  9186. var internalRenderTask = new InternalRenderTask(complete, params, this.objs, this.commonObjs, intentState.operatorList, this.pageNumber);
  9187. internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print';
  9188. if (!intentState.renderTasks) {
  9189. intentState.renderTasks = [];
  9190. }
  9191. intentState.renderTasks.push(internalRenderTask);
  9192. var renderTask = internalRenderTask.task;
  9193. // Obsolete parameter support
  9194. if (params.continueCallback) {
  9195. deprecated('render is used with continueCallback parameter');
  9196. renderTask.onContinue = params.continueCallback;
  9197. }
  9198. var self = this;
  9199. intentState.displayReadyCapability.promise.then(function pageDisplayReadyPromise(transparency) {
  9200. if (self.pendingCleanup) {
  9201. complete();
  9202. return;
  9203. }
  9204. stats.time('Rendering');
  9205. internalRenderTask.initializeGraphics(transparency);
  9206. internalRenderTask.operatorListChanged();
  9207. }, function pageDisplayReadPromiseError(reason) {
  9208. complete(reason);
  9209. });
  9210. function complete(error) {
  9211. var i = intentState.renderTasks.indexOf(internalRenderTask);
  9212. if (i >= 0) {
  9213. intentState.renderTasks.splice(i, 1);
  9214. }
  9215. if (self.cleanupAfterRender) {
  9216. self.pendingCleanup = true;
  9217. }
  9218. self._tryCleanup();
  9219. if (error) {
  9220. internalRenderTask.capability.reject(error);
  9221. } else {
  9222. internalRenderTask.capability.resolve();
  9223. }
  9224. stats.timeEnd('Rendering');
  9225. stats.timeEnd('Overall');
  9226. }
  9227. return renderTask;
  9228. },
  9229. /**
  9230. * @return {Promise} A promise resolved with an {@link PDFOperatorList}
  9231. * object that represents page's operator list.
  9232. */
  9233. getOperatorList: function PDFPageProxy_getOperatorList() {
  9234. function operatorListChanged() {
  9235. if (intentState.operatorList.lastChunk) {
  9236. intentState.opListReadCapability.resolve(intentState.operatorList);
  9237. var i = intentState.renderTasks.indexOf(opListTask);
  9238. if (i >= 0) {
  9239. intentState.renderTasks.splice(i, 1);
  9240. }
  9241. }
  9242. }
  9243. var renderingIntent = 'oplist';
  9244. if (!this.intentStates[renderingIntent]) {
  9245. this.intentStates[renderingIntent] = Object.create(null);
  9246. }
  9247. var intentState = this.intentStates[renderingIntent];
  9248. var opListTask;
  9249. if (!intentState.opListReadCapability) {
  9250. opListTask = {};
  9251. opListTask.operatorListChanged = operatorListChanged;
  9252. intentState.receivingOperatorList = true;
  9253. intentState.opListReadCapability = createPromiseCapability();
  9254. intentState.renderTasks = [];
  9255. intentState.renderTasks.push(opListTask);
  9256. intentState.operatorList = {
  9257. fnArray: [],
  9258. argsArray: [],
  9259. lastChunk: false
  9260. };
  9261. this.transport.messageHandler.send('RenderPageRequest', {
  9262. pageIndex: this.pageIndex,
  9263. intent: renderingIntent
  9264. });
  9265. }
  9266. return intentState.opListReadCapability.promise;
  9267. },
  9268. /**
  9269. * @param {getTextContentParameters} params - getTextContent parameters.
  9270. * @return {Promise} That is resolved a {@link TextContent}
  9271. * object that represent the page text content.
  9272. */
  9273. getTextContent: function PDFPageProxy_getTextContent(params) {
  9274. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  9275. pageIndex: this.pageNumber - 1,
  9276. normalizeWhitespace: params && params.normalizeWhitespace === true ? true : /* Default */
  9277. false,
  9278. combineTextItems: params && params.disableCombineTextItems === true ? false : /* Default */
  9279. true
  9280. });
  9281. },
  9282. /**
  9283. * Destroys page object.
  9284. */
  9285. _destroy: function PDFPageProxy_destroy() {
  9286. this.destroyed = true;
  9287. this.transport.pageCache[this.pageIndex] = null;
  9288. var waitOn = [];
  9289. Object.keys(this.intentStates).forEach(function (intent) {
  9290. if (intent === 'oplist') {
  9291. // Avoid errors below, since the renderTasks are just stubs.
  9292. return;
  9293. }
  9294. var intentState = this.intentStates[intent];
  9295. intentState.renderTasks.forEach(function (renderTask) {
  9296. var renderCompleted = renderTask.capability.promise.catch(function () {
  9297. });
  9298. // ignoring failures
  9299. waitOn.push(renderCompleted);
  9300. renderTask.cancel();
  9301. });
  9302. }, this);
  9303. this.objs.clear();
  9304. this.annotationsPromise = null;
  9305. this.pendingCleanup = false;
  9306. return Promise.all(waitOn);
  9307. },
  9308. /**
  9309. * Cleans up resources allocated by the page. (deprecated)
  9310. */
  9311. destroy: function () {
  9312. deprecated('page destroy method, use cleanup() instead');
  9313. this.cleanup();
  9314. },
  9315. /**
  9316. * Cleans up resources allocated by the page.
  9317. */
  9318. cleanup: function PDFPageProxy_cleanup() {
  9319. this.pendingCleanup = true;
  9320. this._tryCleanup();
  9321. },
  9322. /**
  9323. * For internal use only. Attempts to clean up if rendering is in a state
  9324. * where that's possible.
  9325. * @ignore
  9326. */
  9327. _tryCleanup: function PDFPageProxy_tryCleanup() {
  9328. if (!this.pendingCleanup || Object.keys(this.intentStates).some(function (intent) {
  9329. var intentState = this.intentStates[intent];
  9330. return intentState.renderTasks.length !== 0 || intentState.receivingOperatorList;
  9331. }, this)) {
  9332. return;
  9333. }
  9334. Object.keys(this.intentStates).forEach(function (intent) {
  9335. delete this.intentStates[intent];
  9336. }, this);
  9337. this.objs.clear();
  9338. this.annotationsPromise = null;
  9339. this.pendingCleanup = false;
  9340. },
  9341. /**
  9342. * For internal use only.
  9343. * @ignore
  9344. */
  9345. _startRenderPage: function PDFPageProxy_startRenderPage(transparency, intent) {
  9346. var intentState = this.intentStates[intent];
  9347. // TODO Refactor RenderPageRequest to separate rendering
  9348. // and operator list logic
  9349. if (intentState.displayReadyCapability) {
  9350. intentState.displayReadyCapability.resolve(transparency);
  9351. }
  9352. },
  9353. /**
  9354. * For internal use only.
  9355. * @ignore
  9356. */
  9357. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk, intent) {
  9358. var intentState = this.intentStates[intent];
  9359. var i, ii;
  9360. // Add the new chunk to the current operator list.
  9361. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  9362. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  9363. intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
  9364. }
  9365. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  9366. // Notify all the rendering tasks there are more operators to be consumed.
  9367. for (i = 0; i < intentState.renderTasks.length; i++) {
  9368. intentState.renderTasks[i].operatorListChanged();
  9369. }
  9370. if (operatorListChunk.lastChunk) {
  9371. intentState.receivingOperatorList = false;
  9372. this._tryCleanup();
  9373. }
  9374. }
  9375. };
  9376. return PDFPageProxy;
  9377. }();
  9378. /**
  9379. * PDF.js web worker abstraction, it controls instantiation of PDF documents and
  9380. * WorkerTransport for them. If creation of a web worker is not possible,
  9381. * a "fake" worker will be used instead.
  9382. * @class
  9383. */
  9384. var PDFWorker = function PDFWorkerClosure() {
  9385. var nextFakeWorkerId = 0;
  9386. function getWorkerSrc() {
  9387. if (typeof workerSrc !== 'undefined') {
  9388. return workerSrc;
  9389. }
  9390. if (getDefaultSetting('workerSrc')) {
  9391. return getDefaultSetting('workerSrc');
  9392. }
  9393. if (pdfjsFilePath) {
  9394. return pdfjsFilePath.replace(/\.js$/i, '.worker.js');
  9395. }
  9396. error('No PDFJS.workerSrc specified');
  9397. }
  9398. var fakeWorkerFilesLoadedCapability;
  9399. // Loads worker code into main thread.
  9400. function setupFakeWorkerGlobal() {
  9401. var WorkerMessageHandler;
  9402. if (fakeWorkerFilesLoadedCapability) {
  9403. return fakeWorkerFilesLoadedCapability.promise;
  9404. }
  9405. fakeWorkerFilesLoadedCapability = createPromiseCapability();
  9406. var loader = fakeWorkerFilesLoader || function (callback) {
  9407. Util.loadScript(getWorkerSrc(), function () {
  9408. callback(window.pdfjsDistBuildPdfWorker.WorkerMessageHandler);
  9409. });
  9410. };
  9411. loader(fakeWorkerFilesLoadedCapability.resolve);
  9412. return fakeWorkerFilesLoadedCapability.promise;
  9413. }
  9414. function FakeWorkerPort(defer) {
  9415. this._listeners = [];
  9416. this._defer = defer;
  9417. this._deferred = Promise.resolve(undefined);
  9418. }
  9419. FakeWorkerPort.prototype = {
  9420. postMessage: function (obj, transfers) {
  9421. function cloneValue(value) {
  9422. // Trying to perform a structured clone close to the spec, including
  9423. // transfers.
  9424. if (typeof value !== 'object' || value === null) {
  9425. return value;
  9426. }
  9427. if (cloned.has(value)) {
  9428. // already cloned the object
  9429. return cloned.get(value);
  9430. }
  9431. var result;
  9432. var buffer;
  9433. if ((buffer = value.buffer) && isArrayBuffer(buffer)) {
  9434. // We found object with ArrayBuffer (typed array).
  9435. var transferable = transfers && transfers.indexOf(buffer) >= 0;
  9436. if (value === buffer) {
  9437. // Special case when we are faking typed arrays in compatibility.js.
  9438. result = value;
  9439. } else if (transferable) {
  9440. result = new value.constructor(buffer, value.byteOffset, value.byteLength);
  9441. } else {
  9442. result = new value.constructor(value);
  9443. }
  9444. cloned.set(value, result);
  9445. return result;
  9446. }
  9447. result = isArray(value) ? [] : {};
  9448. cloned.set(value, result);
  9449. // adding to cache now for cyclic references
  9450. // Cloning all value and object properties, however ignoring properties
  9451. // defined via getter.
  9452. for (var i in value) {
  9453. var desc, p = value;
  9454. while (!(desc = Object.getOwnPropertyDescriptor(p, i))) {
  9455. p = Object.getPrototypeOf(p);
  9456. }
  9457. if (typeof desc.value === 'undefined' || typeof desc.value === 'function') {
  9458. continue;
  9459. }
  9460. result[i] = cloneValue(desc.value);
  9461. }
  9462. return result;
  9463. }
  9464. if (!this._defer) {
  9465. this._listeners.forEach(function (listener) {
  9466. listener.call(this, { data: obj });
  9467. }, this);
  9468. return;
  9469. }
  9470. var cloned = new WeakMap();
  9471. var e = { data: cloneValue(obj) };
  9472. this._deferred.then(function () {
  9473. this._listeners.forEach(function (listener) {
  9474. listener.call(this, e);
  9475. }, this);
  9476. }.bind(this));
  9477. },
  9478. addEventListener: function (name, listener) {
  9479. this._listeners.push(listener);
  9480. },
  9481. removeEventListener: function (name, listener) {
  9482. var i = this._listeners.indexOf(listener);
  9483. this._listeners.splice(i, 1);
  9484. },
  9485. terminate: function () {
  9486. this._listeners = [];
  9487. }
  9488. };
  9489. function createCDNWrapper(url) {
  9490. // We will rely on blob URL's property to specify origin.
  9491. // We want this function to fail in case if createObjectURL or Blob do not
  9492. // exist or fail for some reason -- our Worker creation will fail anyway.
  9493. var wrapper = 'importScripts(\'' + url + '\');';
  9494. return URL.createObjectURL(new Blob([wrapper]));
  9495. }
  9496. function PDFWorker(name) {
  9497. this.name = name;
  9498. this.destroyed = false;
  9499. this._readyCapability = createPromiseCapability();
  9500. this._port = null;
  9501. this._webWorker = null;
  9502. this._messageHandler = null;
  9503. this._initialize();
  9504. }
  9505. PDFWorker.prototype = /** @lends PDFWorker.prototype */
  9506. {
  9507. get promise() {
  9508. return this._readyCapability.promise;
  9509. },
  9510. get port() {
  9511. return this._port;
  9512. },
  9513. get messageHandler() {
  9514. return this._messageHandler;
  9515. },
  9516. _initialize: function PDFWorker_initialize() {
  9517. // If worker support isn't disabled explicit and the browser has worker
  9518. // support, create a new web worker and test if it/the browser fulfills
  9519. // all requirements to run parts of pdf.js in a web worker.
  9520. // Right now, the requirement is, that an Uint8Array is still an
  9521. // Uint8Array as it arrives on the worker. (Chrome added this with v.15.)
  9522. if (!isWorkerDisabled && !getDefaultSetting('disableWorker') && typeof Worker !== 'undefined') {
  9523. var workerSrc = getWorkerSrc();
  9524. try {
  9525. // Wraps workerSrc path into blob URL, if the former does not belong
  9526. // to the same origin.
  9527. if (!isSameOrigin(window.location.href, workerSrc)) {
  9528. workerSrc = createCDNWrapper(new URL(workerSrc, window.location).href);
  9529. }
  9530. // Some versions of FF can't create a worker on localhost, see:
  9531. // https://bugzilla.mozilla.org/show_bug.cgi?id=683280
  9532. var worker = new Worker(workerSrc);
  9533. var messageHandler = new MessageHandler('main', 'worker', worker);
  9534. var terminateEarly = function () {
  9535. worker.removeEventListener('error', onWorkerError);
  9536. messageHandler.destroy();
  9537. worker.terminate();
  9538. if (this.destroyed) {
  9539. this._readyCapability.reject(new Error('Worker was destroyed'));
  9540. } else {
  9541. // Fall back to fake worker if the termination is caused by an
  9542. // error (e.g. NetworkError / SecurityError).
  9543. this._setupFakeWorker();
  9544. }
  9545. }.bind(this);
  9546. var onWorkerError = function (event) {
  9547. if (!this._webWorker) {
  9548. // Worker failed to initialize due to an error. Clean up and fall
  9549. // back to the fake worker.
  9550. terminateEarly();
  9551. }
  9552. }.bind(this);
  9553. worker.addEventListener('error', onWorkerError);
  9554. messageHandler.on('test', function PDFWorker_test(data) {
  9555. worker.removeEventListener('error', onWorkerError);
  9556. if (this.destroyed) {
  9557. terminateEarly();
  9558. return;
  9559. }
  9560. // worker was destroyed
  9561. var supportTypedArray = data && data.supportTypedArray;
  9562. if (supportTypedArray) {
  9563. this._messageHandler = messageHandler;
  9564. this._port = worker;
  9565. this._webWorker = worker;
  9566. if (!data.supportTransfers) {
  9567. isPostMessageTransfersDisabled = true;
  9568. }
  9569. this._readyCapability.resolve();
  9570. // Send global setting, e.g. verbosity level.
  9571. messageHandler.send('configure', { verbosity: getVerbosityLevel() });
  9572. } else {
  9573. this._setupFakeWorker();
  9574. messageHandler.destroy();
  9575. worker.terminate();
  9576. }
  9577. }.bind(this));
  9578. messageHandler.on('console_log', function (data) {
  9579. console.log.apply(console, data);
  9580. });
  9581. messageHandler.on('console_error', function (data) {
  9582. console.error.apply(console, data);
  9583. });
  9584. messageHandler.on('ready', function (data) {
  9585. worker.removeEventListener('error', onWorkerError);
  9586. if (this.destroyed) {
  9587. terminateEarly();
  9588. return;
  9589. }
  9590. // worker was destroyed
  9591. try {
  9592. sendTest();
  9593. } catch (e) {
  9594. // We need fallback to a faked worker.
  9595. this._setupFakeWorker();
  9596. }
  9597. }.bind(this));
  9598. var sendTest = function () {
  9599. var postMessageTransfers = getDefaultSetting('postMessageTransfers') && !isPostMessageTransfersDisabled;
  9600. var testObj = new Uint8Array([postMessageTransfers ? 255 : 0]);
  9601. // Some versions of Opera throw a DATA_CLONE_ERR on serializing the
  9602. // typed array. Also, checking if we can use transfers.
  9603. try {
  9604. messageHandler.send('test', testObj, [testObj.buffer]);
  9605. } catch (ex) {
  9606. info('Cannot use postMessage transfers');
  9607. testObj[0] = 0;
  9608. messageHandler.send('test', testObj);
  9609. }
  9610. };
  9611. // It might take time for worker to initialize (especially when AMD
  9612. // loader is used). We will try to send test immediately, and then
  9613. // when 'ready' message will arrive. The worker shall process only
  9614. // first received 'test'.
  9615. sendTest();
  9616. return;
  9617. } catch (e) {
  9618. info('The worker has been disabled.');
  9619. }
  9620. }
  9621. // Either workers are disabled, not supported or have thrown an exception.
  9622. // Thus, we fallback to a faked worker.
  9623. this._setupFakeWorker();
  9624. },
  9625. _setupFakeWorker: function PDFWorker_setupFakeWorker() {
  9626. if (!isWorkerDisabled && !getDefaultSetting('disableWorker')) {
  9627. warn('Setting up fake worker.');
  9628. isWorkerDisabled = true;
  9629. }
  9630. setupFakeWorkerGlobal().then(function (WorkerMessageHandler) {
  9631. if (this.destroyed) {
  9632. this._readyCapability.reject(new Error('Worker was destroyed'));
  9633. return;
  9634. }
  9635. // We cannot turn on proper fake port simulation (this includes
  9636. // structured cloning) when typed arrays are not supported. Relying
  9637. // on a chance that messages will be sent in proper order.
  9638. var isTypedArraysPresent = Uint8Array !== Float32Array;
  9639. var port = new FakeWorkerPort(isTypedArraysPresent);
  9640. this._port = port;
  9641. // All fake workers use the same port, making id unique.
  9642. var id = 'fake' + nextFakeWorkerId++;
  9643. // If the main thread is our worker, setup the handling for the
  9644. // messages -- the main thread sends to it self.
  9645. var workerHandler = new MessageHandler(id + '_worker', id, port);
  9646. WorkerMessageHandler.setup(workerHandler, port);
  9647. var messageHandler = new MessageHandler(id, id + '_worker', port);
  9648. this._messageHandler = messageHandler;
  9649. this._readyCapability.resolve();
  9650. }.bind(this));
  9651. },
  9652. /**
  9653. * Destroys the worker instance.
  9654. */
  9655. destroy: function PDFWorker_destroy() {
  9656. this.destroyed = true;
  9657. if (this._webWorker) {
  9658. // We need to terminate only web worker created resource.
  9659. this._webWorker.terminate();
  9660. this._webWorker = null;
  9661. }
  9662. this._port = null;
  9663. if (this._messageHandler) {
  9664. this._messageHandler.destroy();
  9665. this._messageHandler = null;
  9666. }
  9667. }
  9668. };
  9669. return PDFWorker;
  9670. }();
  9671. /**
  9672. * For internal use only.
  9673. * @ignore
  9674. */
  9675. var WorkerTransport = function WorkerTransportClosure() {
  9676. function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) {
  9677. this.messageHandler = messageHandler;
  9678. this.loadingTask = loadingTask;
  9679. this.pdfDataRangeTransport = pdfDataRangeTransport;
  9680. this.commonObjs = new PDFObjects();
  9681. this.fontLoader = new FontLoader(loadingTask.docId);
  9682. this.destroyed = false;
  9683. this.destroyCapability = null;
  9684. this.pageCache = [];
  9685. this.pagePromises = [];
  9686. this.downloadInfoCapability = createPromiseCapability();
  9687. this.setupMessageHandler();
  9688. }
  9689. WorkerTransport.prototype = {
  9690. destroy: function WorkerTransport_destroy() {
  9691. if (this.destroyCapability) {
  9692. return this.destroyCapability.promise;
  9693. }
  9694. this.destroyed = true;
  9695. this.destroyCapability = createPromiseCapability();
  9696. var waitOn = [];
  9697. // We need to wait for all renderings to be completed, e.g.
  9698. // timeout/rAF can take a long time.
  9699. this.pageCache.forEach(function (page) {
  9700. if (page) {
  9701. waitOn.push(page._destroy());
  9702. }
  9703. });
  9704. this.pageCache = [];
  9705. this.pagePromises = [];
  9706. var self = this;
  9707. // We also need to wait for the worker to finish its long running tasks.
  9708. var terminated = this.messageHandler.sendWithPromise('Terminate', null);
  9709. waitOn.push(terminated);
  9710. Promise.all(waitOn).then(function () {
  9711. self.fontLoader.clear();
  9712. if (self.pdfDataRangeTransport) {
  9713. self.pdfDataRangeTransport.abort();
  9714. self.pdfDataRangeTransport = null;
  9715. }
  9716. if (self.messageHandler) {
  9717. self.messageHandler.destroy();
  9718. self.messageHandler = null;
  9719. }
  9720. self.destroyCapability.resolve();
  9721. }, this.destroyCapability.reject);
  9722. return this.destroyCapability.promise;
  9723. },
  9724. setupMessageHandler: function WorkerTransport_setupMessageHandler() {
  9725. var messageHandler = this.messageHandler;
  9726. function updatePassword(password) {
  9727. messageHandler.send('UpdatePassword', password);
  9728. }
  9729. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  9730. if (pdfDataRangeTransport) {
  9731. pdfDataRangeTransport.addRangeListener(function (begin, chunk) {
  9732. messageHandler.send('OnDataRange', {
  9733. begin: begin,
  9734. chunk: chunk
  9735. });
  9736. });
  9737. pdfDataRangeTransport.addProgressListener(function (loaded) {
  9738. messageHandler.send('OnDataProgress', { loaded: loaded });
  9739. });
  9740. pdfDataRangeTransport.addProgressiveReadListener(function (chunk) {
  9741. messageHandler.send('OnDataRange', { chunk: chunk });
  9742. });
  9743. messageHandler.on('RequestDataRange', function transportDataRange(data) {
  9744. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  9745. }, this);
  9746. }
  9747. messageHandler.on('GetDoc', function transportDoc(data) {
  9748. var pdfInfo = data.pdfInfo;
  9749. this.numPages = data.pdfInfo.numPages;
  9750. var loadingTask = this.loadingTask;
  9751. var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask);
  9752. this.pdfDocument = pdfDocument;
  9753. loadingTask._capability.resolve(pdfDocument);
  9754. }, this);
  9755. messageHandler.on('NeedPassword', function transportNeedPassword(exception) {
  9756. var loadingTask = this.loadingTask;
  9757. if (loadingTask.onPassword) {
  9758. return loadingTask.onPassword(updatePassword, PasswordResponses.NEED_PASSWORD);
  9759. }
  9760. loadingTask._capability.reject(new PasswordException(exception.message, exception.code));
  9761. }, this);
  9762. messageHandler.on('IncorrectPassword', function transportIncorrectPassword(exception) {
  9763. var loadingTask = this.loadingTask;
  9764. if (loadingTask.onPassword) {
  9765. return loadingTask.onPassword(updatePassword, PasswordResponses.INCORRECT_PASSWORD);
  9766. }
  9767. loadingTask._capability.reject(new PasswordException(exception.message, exception.code));
  9768. }, this);
  9769. messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
  9770. this.loadingTask._capability.reject(new InvalidPDFException(exception.message));
  9771. }, this);
  9772. messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
  9773. this.loadingTask._capability.reject(new MissingPDFException(exception.message));
  9774. }, this);
  9775. messageHandler.on('UnexpectedResponse', function transportUnexpectedResponse(exception) {
  9776. this.loadingTask._capability.reject(new UnexpectedResponseException(exception.message, exception.status));
  9777. }, this);
  9778. messageHandler.on('UnknownError', function transportUnknownError(exception) {
  9779. this.loadingTask._capability.reject(new UnknownErrorException(exception.message, exception.details));
  9780. }, this);
  9781. messageHandler.on('DataLoaded', function transportPage(data) {
  9782. this.downloadInfoCapability.resolve(data);
  9783. }, this);
  9784. messageHandler.on('PDFManagerReady', function transportPage(data) {
  9785. if (this.pdfDataRangeTransport) {
  9786. this.pdfDataRangeTransport.transportReady();
  9787. }
  9788. }, this);
  9789. messageHandler.on('StartRenderPage', function transportRender(data) {
  9790. if (this.destroyed) {
  9791. return;
  9792. }
  9793. // Ignore any pending requests if the worker was terminated.
  9794. var page = this.pageCache[data.pageIndex];
  9795. page.stats.timeEnd('Page Request');
  9796. page._startRenderPage(data.transparency, data.intent);
  9797. }, this);
  9798. messageHandler.on('RenderPageChunk', function transportRender(data) {
  9799. if (this.destroyed) {
  9800. return;
  9801. }
  9802. // Ignore any pending requests if the worker was terminated.
  9803. var page = this.pageCache[data.pageIndex];
  9804. page._renderPageChunk(data.operatorList, data.intent);
  9805. }, this);
  9806. messageHandler.on('commonobj', function transportObj(data) {
  9807. if (this.destroyed) {
  9808. return;
  9809. }
  9810. // Ignore any pending requests if the worker was terminated.
  9811. var id = data[0];
  9812. var type = data[1];
  9813. if (this.commonObjs.hasData(id)) {
  9814. return;
  9815. }
  9816. switch (type) {
  9817. case 'Font':
  9818. var exportedData = data[2];
  9819. if ('error' in exportedData) {
  9820. var exportedError = exportedData.error;
  9821. warn('Error during font loading: ' + exportedError);
  9822. this.commonObjs.resolve(id, exportedError);
  9823. break;
  9824. }
  9825. var fontRegistry = null;
  9826. if (getDefaultSetting('pdfBug') && globalScope.FontInspector && globalScope['FontInspector'].enabled) {
  9827. fontRegistry = {
  9828. registerFont: function (font, url) {
  9829. globalScope['FontInspector'].fontAdded(font, url);
  9830. }
  9831. };
  9832. }
  9833. var font = new FontFaceObject(exportedData, {
  9834. isEvalSuported: getDefaultSetting('isEvalSupported'),
  9835. disableFontFace: getDefaultSetting('disableFontFace'),
  9836. fontRegistry: fontRegistry
  9837. });
  9838. this.fontLoader.bind([font], function fontReady(fontObjs) {
  9839. this.commonObjs.resolve(id, font);
  9840. }.bind(this));
  9841. break;
  9842. case 'FontPath':
  9843. this.commonObjs.resolve(id, data[2]);
  9844. break;
  9845. default:
  9846. error('Got unknown common object type ' + type);
  9847. }
  9848. }, this);
  9849. messageHandler.on('obj', function transportObj(data) {
  9850. if (this.destroyed) {
  9851. return;
  9852. }
  9853. // Ignore any pending requests if the worker was terminated.
  9854. var id = data[0];
  9855. var pageIndex = data[1];
  9856. var type = data[2];
  9857. var pageProxy = this.pageCache[pageIndex];
  9858. var imageData;
  9859. if (pageProxy.objs.hasData(id)) {
  9860. return;
  9861. }
  9862. switch (type) {
  9863. case 'JpegStream':
  9864. imageData = data[3];
  9865. loadJpegStream(id, imageData, pageProxy.objs);
  9866. break;
  9867. case 'Image':
  9868. imageData = data[3];
  9869. pageProxy.objs.resolve(id, imageData);
  9870. // heuristics that will allow not to store large data
  9871. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  9872. if (imageData && 'data' in imageData && imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  9873. pageProxy.cleanupAfterRender = true;
  9874. }
  9875. break;
  9876. default:
  9877. error('Got unknown object type ' + type);
  9878. }
  9879. }, this);
  9880. messageHandler.on('DocProgress', function transportDocProgress(data) {
  9881. if (this.destroyed) {
  9882. return;
  9883. }
  9884. // Ignore any pending requests if the worker was terminated.
  9885. var loadingTask = this.loadingTask;
  9886. if (loadingTask.onProgress) {
  9887. loadingTask.onProgress({
  9888. loaded: data.loaded,
  9889. total: data.total
  9890. });
  9891. }
  9892. }, this);
  9893. messageHandler.on('PageError', function transportError(data) {
  9894. if (this.destroyed) {
  9895. return;
  9896. }
  9897. // Ignore any pending requests if the worker was terminated.
  9898. var page = this.pageCache[data.pageNum - 1];
  9899. var intentState = page.intentStates[data.intent];
  9900. if (intentState.displayReadyCapability) {
  9901. intentState.displayReadyCapability.reject(data.error);
  9902. } else {
  9903. error(data.error);
  9904. }
  9905. if (intentState.operatorList) {
  9906. // Mark operator list as complete.
  9907. intentState.operatorList.lastChunk = true;
  9908. for (var i = 0; i < intentState.renderTasks.length; i++) {
  9909. intentState.renderTasks[i].operatorListChanged();
  9910. }
  9911. }
  9912. }, this);
  9913. messageHandler.on('UnsupportedFeature', function transportUnsupportedFeature(data) {
  9914. if (this.destroyed) {
  9915. return;
  9916. }
  9917. // Ignore any pending requests if the worker was terminated.
  9918. var featureId = data.featureId;
  9919. var loadingTask = this.loadingTask;
  9920. if (loadingTask.onUnsupportedFeature) {
  9921. loadingTask.onUnsupportedFeature(featureId);
  9922. }
  9923. _UnsupportedManager.notify(featureId);
  9924. }, this);
  9925. messageHandler.on('JpegDecode', function (data) {
  9926. if (this.destroyed) {
  9927. return Promise.reject(new Error('Worker was destroyed'));
  9928. }
  9929. var imageUrl = data[0];
  9930. var components = data[1];
  9931. if (components !== 3 && components !== 1) {
  9932. return Promise.reject(new Error('Only 3 components or 1 component can be returned'));
  9933. }
  9934. return new Promise(function (resolve, reject) {
  9935. var img = new Image();
  9936. img.onload = function () {
  9937. var width = img.width;
  9938. var height = img.height;
  9939. var size = width * height;
  9940. var rgbaLength = size * 4;
  9941. var buf = new Uint8Array(size * components);
  9942. var tmpCanvas = createScratchCanvas(width, height);
  9943. var tmpCtx = tmpCanvas.getContext('2d');
  9944. tmpCtx.drawImage(img, 0, 0);
  9945. var data = tmpCtx.getImageData(0, 0, width, height).data;
  9946. var i, j;
  9947. if (components === 3) {
  9948. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  9949. buf[j] = data[i];
  9950. buf[j + 1] = data[i + 1];
  9951. buf[j + 2] = data[i + 2];
  9952. }
  9953. } else if (components === 1) {
  9954. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  9955. buf[j] = data[i];
  9956. }
  9957. }
  9958. resolve({
  9959. data: buf,
  9960. width: width,
  9961. height: height
  9962. });
  9963. };
  9964. img.onerror = function () {
  9965. reject(new Error('JpegDecode failed to load image'));
  9966. };
  9967. img.src = imageUrl;
  9968. });
  9969. }, this);
  9970. },
  9971. getData: function WorkerTransport_getData() {
  9972. return this.messageHandler.sendWithPromise('GetData', null);
  9973. },
  9974. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  9975. if (!isInt(pageNumber) || pageNumber <= 0 || pageNumber > this.numPages) {
  9976. return Promise.reject(new Error('Invalid page request'));
  9977. }
  9978. var pageIndex = pageNumber - 1;
  9979. if (pageIndex in this.pagePromises) {
  9980. return this.pagePromises[pageIndex];
  9981. }
  9982. var promise = this.messageHandler.sendWithPromise('GetPage', { pageIndex: pageIndex }).then(function (pageInfo) {
  9983. if (this.destroyed) {
  9984. throw new Error('Transport destroyed');
  9985. }
  9986. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  9987. this.pageCache[pageIndex] = page;
  9988. return page;
  9989. }.bind(this));
  9990. this.pagePromises[pageIndex] = promise;
  9991. return promise;
  9992. },
  9993. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  9994. return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref }).catch(function (reason) {
  9995. return Promise.reject(new Error(reason));
  9996. });
  9997. },
  9998. getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) {
  9999. return this.messageHandler.sendWithPromise('GetAnnotations', {
  10000. pageIndex: pageIndex,
  10001. intent: intent
  10002. });
  10003. },
  10004. getDestinations: function WorkerTransport_getDestinations() {
  10005. return this.messageHandler.sendWithPromise('GetDestinations', null);
  10006. },
  10007. getDestination: function WorkerTransport_getDestination(id) {
  10008. return this.messageHandler.sendWithPromise('GetDestination', { id: id });
  10009. },
  10010. getPageLabels: function WorkerTransport_getPageLabels() {
  10011. return this.messageHandler.sendWithPromise('GetPageLabels', null);
  10012. },
  10013. getAttachments: function WorkerTransport_getAttachments() {
  10014. return this.messageHandler.sendWithPromise('GetAttachments', null);
  10015. },
  10016. getJavaScript: function WorkerTransport_getJavaScript() {
  10017. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  10018. },
  10019. getOutline: function WorkerTransport_getOutline() {
  10020. return this.messageHandler.sendWithPromise('GetOutline', null);
  10021. },
  10022. getMetadata: function WorkerTransport_getMetadata() {
  10023. return this.messageHandler.sendWithPromise('GetMetadata', null).then(function transportMetadata(results) {
  10024. return {
  10025. info: results[0],
  10026. metadata: results[1] ? new Metadata(results[1]) : null
  10027. };
  10028. });
  10029. },
  10030. getStats: function WorkerTransport_getStats() {
  10031. return this.messageHandler.sendWithPromise('GetStats', null);
  10032. },
  10033. startCleanup: function WorkerTransport_startCleanup() {
  10034. this.messageHandler.sendWithPromise('Cleanup', null).then(function endCleanup() {
  10035. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  10036. var page = this.pageCache[i];
  10037. if (page) {
  10038. page.cleanup();
  10039. }
  10040. }
  10041. this.commonObjs.clear();
  10042. this.fontLoader.clear();
  10043. }.bind(this));
  10044. }
  10045. };
  10046. return WorkerTransport;
  10047. }();
  10048. /**
  10049. * A PDF document and page is built of many objects. E.g. there are objects
  10050. * for fonts, images, rendering code and such. These objects might get processed
  10051. * inside of a worker. The `PDFObjects` implements some basic functions to
  10052. * manage these objects.
  10053. * @ignore
  10054. */
  10055. var PDFObjects = function PDFObjectsClosure() {
  10056. function PDFObjects() {
  10057. this.objs = Object.create(null);
  10058. }
  10059. PDFObjects.prototype = {
  10060. /**
  10061. * Internal function.
  10062. * Ensures there is an object defined for `objId`.
  10063. */
  10064. ensureObj: function PDFObjects_ensureObj(objId) {
  10065. if (this.objs[objId]) {
  10066. return this.objs[objId];
  10067. }
  10068. var obj = {
  10069. capability: createPromiseCapability(),
  10070. data: null,
  10071. resolved: false
  10072. };
  10073. this.objs[objId] = obj;
  10074. return obj;
  10075. },
  10076. /**
  10077. * If called *without* callback, this returns the data of `objId` but the
  10078. * object needs to be resolved. If it isn't, this function throws.
  10079. *
  10080. * If called *with* a callback, the callback is called with the data of the
  10081. * object once the object is resolved. That means, if you call this
  10082. * function and the object is already resolved, the callback gets called
  10083. * right away.
  10084. */
  10085. get: function PDFObjects_get(objId, callback) {
  10086. // If there is a callback, then the get can be async and the object is
  10087. // not required to be resolved right now
  10088. if (callback) {
  10089. this.ensureObj(objId).capability.promise.then(callback);
  10090. return null;
  10091. }
  10092. // If there isn't a callback, the user expects to get the resolved data
  10093. // directly.
  10094. var obj = this.objs[objId];
  10095. // If there isn't an object yet or the object isn't resolved, then the
  10096. // data isn't ready yet!
  10097. if (!obj || !obj.resolved) {
  10098. error('Requesting object that isn\'t resolved yet ' + objId);
  10099. }
  10100. return obj.data;
  10101. },
  10102. /**
  10103. * Resolves the object `objId` with optional `data`.
  10104. */
  10105. resolve: function PDFObjects_resolve(objId, data) {
  10106. var obj = this.ensureObj(objId);
  10107. obj.resolved = true;
  10108. obj.data = data;
  10109. obj.capability.resolve(data);
  10110. },
  10111. isResolved: function PDFObjects_isResolved(objId) {
  10112. var objs = this.objs;
  10113. if (!objs[objId]) {
  10114. return false;
  10115. } else {
  10116. return objs[objId].resolved;
  10117. }
  10118. },
  10119. hasData: function PDFObjects_hasData(objId) {
  10120. return this.isResolved(objId);
  10121. },
  10122. /**
  10123. * Returns the data of `objId` if object exists, null otherwise.
  10124. */
  10125. getData: function PDFObjects_getData(objId) {
  10126. var objs = this.objs;
  10127. if (!objs[objId] || !objs[objId].resolved) {
  10128. return null;
  10129. } else {
  10130. return objs[objId].data;
  10131. }
  10132. },
  10133. clear: function PDFObjects_clear() {
  10134. this.objs = Object.create(null);
  10135. }
  10136. };
  10137. return PDFObjects;
  10138. }();
  10139. /**
  10140. * Allows controlling of the rendering tasks.
  10141. * @class
  10142. * @alias RenderTask
  10143. */
  10144. var RenderTask = function RenderTaskClosure() {
  10145. function RenderTask(internalRenderTask) {
  10146. this._internalRenderTask = internalRenderTask;
  10147. /**
  10148. * Callback for incremental rendering -- a function that will be called
  10149. * each time the rendering is paused. To continue rendering call the
  10150. * function that is the first argument to the callback.
  10151. * @type {function}
  10152. */
  10153. this.onContinue = null;
  10154. }
  10155. RenderTask.prototype = /** @lends RenderTask.prototype */
  10156. {
  10157. /**
  10158. * Promise for rendering task completion.
  10159. * @return {Promise}
  10160. */
  10161. get promise() {
  10162. return this._internalRenderTask.capability.promise;
  10163. },
  10164. /**
  10165. * Cancels the rendering task. If the task is currently rendering it will
  10166. * not be cancelled until graphics pauses with a timeout. The promise that
  10167. * this object extends will resolved when cancelled.
  10168. */
  10169. cancel: function RenderTask_cancel() {
  10170. this._internalRenderTask.cancel();
  10171. },
  10172. /**
  10173. * Registers callbacks to indicate the rendering task completion.
  10174. *
  10175. * @param {function} onFulfilled The callback for the rendering completion.
  10176. * @param {function} onRejected The callback for the rendering failure.
  10177. * @return {Promise} A promise that is resolved after the onFulfilled or
  10178. * onRejected callback.
  10179. */
  10180. then: function RenderTask_then(onFulfilled, onRejected) {
  10181. return this.promise.then.apply(this.promise, arguments);
  10182. }
  10183. };
  10184. return RenderTask;
  10185. }();
  10186. /**
  10187. * For internal use only.
  10188. * @ignore
  10189. */
  10190. var InternalRenderTask = function InternalRenderTaskClosure() {
  10191. function InternalRenderTask(callback, params, objs, commonObjs, operatorList, pageNumber) {
  10192. this.callback = callback;
  10193. this.params = params;
  10194. this.objs = objs;
  10195. this.commonObjs = commonObjs;
  10196. this.operatorListIdx = null;
  10197. this.operatorList = operatorList;
  10198. this.pageNumber = pageNumber;
  10199. this.running = false;
  10200. this.graphicsReadyCallback = null;
  10201. this.graphicsReady = false;
  10202. this.useRequestAnimationFrame = false;
  10203. this.cancelled = false;
  10204. this.capability = createPromiseCapability();
  10205. this.task = new RenderTask(this);
  10206. // caching this-bound methods
  10207. this._continueBound = this._continue.bind(this);
  10208. this._scheduleNextBound = this._scheduleNext.bind(this);
  10209. this._nextBound = this._next.bind(this);
  10210. }
  10211. InternalRenderTask.prototype = {
  10212. initializeGraphics: function InternalRenderTask_initializeGraphics(transparency) {
  10213. if (this.cancelled) {
  10214. return;
  10215. }
  10216. if (getDefaultSetting('pdfBug') && globalScope.StepperManager && globalScope.StepperManager.enabled) {
  10217. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  10218. this.stepper.init(this.operatorList);
  10219. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  10220. }
  10221. var params = this.params;
  10222. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs, this.objs, params.imageLayer);
  10223. this.gfx.beginDrawing(params.transform, params.viewport, transparency);
  10224. this.operatorListIdx = 0;
  10225. this.graphicsReady = true;
  10226. if (this.graphicsReadyCallback) {
  10227. this.graphicsReadyCallback();
  10228. }
  10229. },
  10230. cancel: function InternalRenderTask_cancel() {
  10231. this.running = false;
  10232. this.cancelled = true;
  10233. this.callback('cancelled');
  10234. },
  10235. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  10236. if (!this.graphicsReady) {
  10237. if (!this.graphicsReadyCallback) {
  10238. this.graphicsReadyCallback = this._continueBound;
  10239. }
  10240. return;
  10241. }
  10242. if (this.stepper) {
  10243. this.stepper.updateOperatorList(this.operatorList);
  10244. }
  10245. if (this.running) {
  10246. return;
  10247. }
  10248. this._continue();
  10249. },
  10250. _continue: function InternalRenderTask__continue() {
  10251. this.running = true;
  10252. if (this.cancelled) {
  10253. return;
  10254. }
  10255. if (this.task.onContinue) {
  10256. this.task.onContinue.call(this.task, this._scheduleNextBound);
  10257. } else {
  10258. this._scheduleNext();
  10259. }
  10260. },
  10261. _scheduleNext: function InternalRenderTask__scheduleNext() {
  10262. if (this.useRequestAnimationFrame && typeof window !== 'undefined') {
  10263. window.requestAnimationFrame(this._nextBound);
  10264. } else {
  10265. Promise.resolve(undefined).then(this._nextBound);
  10266. }
  10267. },
  10268. _next: function InternalRenderTask__next() {
  10269. if (this.cancelled) {
  10270. return;
  10271. }
  10272. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
  10273. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  10274. this.running = false;
  10275. if (this.operatorList.lastChunk) {
  10276. this.gfx.endDrawing();
  10277. this.callback();
  10278. }
  10279. }
  10280. }
  10281. };
  10282. return InternalRenderTask;
  10283. }();
  10284. /**
  10285. * (Deprecated) Global observer of unsupported feature usages. Use
  10286. * onUnsupportedFeature callback of the {PDFDocumentLoadingTask} instance.
  10287. */
  10288. var _UnsupportedManager = function UnsupportedManagerClosure() {
  10289. var listeners = [];
  10290. return {
  10291. listen: function (cb) {
  10292. deprecated('Global UnsupportedManager.listen is used: ' + ' use PDFDocumentLoadingTask.onUnsupportedFeature instead');
  10293. listeners.push(cb);
  10294. },
  10295. notify: function (featureId) {
  10296. for (var i = 0, ii = listeners.length; i < ii; i++) {
  10297. listeners[i](featureId);
  10298. }
  10299. }
  10300. };
  10301. }();
  10302. if (typeof pdfjsVersion !== 'undefined') {
  10303. exports.version = pdfjsVersion;
  10304. }
  10305. if (typeof pdfjsBuild !== 'undefined') {
  10306. exports.build = pdfjsBuild;
  10307. }
  10308. exports.getDocument = getDocument;
  10309. exports.PDFDataRangeTransport = PDFDataRangeTransport;
  10310. exports.PDFWorker = PDFWorker;
  10311. exports.PDFDocumentProxy = PDFDocumentProxy;
  10312. exports.PDFPageProxy = PDFPageProxy;
  10313. exports._UnsupportedManager = _UnsupportedManager;
  10314. }));
  10315. (function (root, factory) {
  10316. factory(root.pdfjsDisplayGlobal = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils, root.pdfjsDisplayAPI, root.pdfjsDisplayAnnotationLayer, root.pdfjsDisplayTextLayer, root.pdfjsDisplayMetadata, root.pdfjsDisplaySVG);
  10317. }(this, function (exports, sharedUtil, displayDOMUtils, displayAPI, displayAnnotationLayer, displayTextLayer, displayMetadata, displaySVG) {
  10318. var globalScope = sharedUtil.globalScope;
  10319. var deprecated = sharedUtil.deprecated;
  10320. var warn = sharedUtil.warn;
  10321. var LinkTarget = displayDOMUtils.LinkTarget;
  10322. var isWorker = typeof window === 'undefined';
  10323. // The global PDFJS object is now deprecated and will not be supported in
  10324. // the future. The members below are maintained for backward compatibility
  10325. // and shall not be extended or modified. If the global.js is included as
  10326. // a module, we will create a global PDFJS object instance or use existing.
  10327. if (!globalScope.PDFJS) {
  10328. globalScope.PDFJS = {};
  10329. }
  10330. var PDFJS = globalScope.PDFJS;
  10331. if (typeof pdfjsVersion !== 'undefined') {
  10332. PDFJS.version = pdfjsVersion;
  10333. }
  10334. if (typeof pdfjsBuild !== 'undefined') {
  10335. PDFJS.build = pdfjsBuild;
  10336. }
  10337. PDFJS.pdfBug = false;
  10338. if (PDFJS.verbosity !== undefined) {
  10339. sharedUtil.setVerbosityLevel(PDFJS.verbosity);
  10340. }
  10341. delete PDFJS.verbosity;
  10342. Object.defineProperty(PDFJS, 'verbosity', {
  10343. get: function () {
  10344. return sharedUtil.getVerbosityLevel();
  10345. },
  10346. set: function (level) {
  10347. sharedUtil.setVerbosityLevel(level);
  10348. },
  10349. enumerable: true,
  10350. configurable: true
  10351. });
  10352. PDFJS.VERBOSITY_LEVELS = sharedUtil.VERBOSITY_LEVELS;
  10353. PDFJS.OPS = sharedUtil.OPS;
  10354. PDFJS.UNSUPPORTED_FEATURES = sharedUtil.UNSUPPORTED_FEATURES;
  10355. PDFJS.isValidUrl = sharedUtil.isValidUrl;
  10356. PDFJS.shadow = sharedUtil.shadow;
  10357. PDFJS.createBlob = sharedUtil.createBlob;
  10358. PDFJS.createObjectURL = function PDFJS_createObjectURL(data, contentType) {
  10359. return sharedUtil.createObjectURL(data, contentType, PDFJS.disableCreateObjectURL);
  10360. };
  10361. Object.defineProperty(PDFJS, 'isLittleEndian', {
  10362. configurable: true,
  10363. get: function PDFJS_isLittleEndian() {
  10364. var value = sharedUtil.isLittleEndian();
  10365. return sharedUtil.shadow(PDFJS, 'isLittleEndian', value);
  10366. }
  10367. });
  10368. PDFJS.removeNullCharacters = sharedUtil.removeNullCharacters;
  10369. PDFJS.PasswordResponses = sharedUtil.PasswordResponses;
  10370. PDFJS.PasswordException = sharedUtil.PasswordException;
  10371. PDFJS.UnknownErrorException = sharedUtil.UnknownErrorException;
  10372. PDFJS.InvalidPDFException = sharedUtil.InvalidPDFException;
  10373. PDFJS.MissingPDFException = sharedUtil.MissingPDFException;
  10374. PDFJS.UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  10375. PDFJS.Util = sharedUtil.Util;
  10376. PDFJS.PageViewport = sharedUtil.PageViewport;
  10377. PDFJS.createPromiseCapability = sharedUtil.createPromiseCapability;
  10378. /**
  10379. * The maximum allowed image size in total pixels e.g. width * height. Images
  10380. * above this value will not be drawn. Use -1 for no limit.
  10381. * @var {number}
  10382. */
  10383. PDFJS.maxImageSize = PDFJS.maxImageSize === undefined ? -1 : PDFJS.maxImageSize;
  10384. /**
  10385. * The url of where the predefined Adobe CMaps are located. Include trailing
  10386. * slash.
  10387. * @var {string}
  10388. */
  10389. PDFJS.cMapUrl = PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl;
  10390. /**
  10391. * Specifies if CMaps are binary packed.
  10392. * @var {boolean}
  10393. */
  10394. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  10395. /**
  10396. * By default fonts are converted to OpenType fonts and loaded via font face
  10397. * rules. If disabled, the font will be rendered using a built in font
  10398. * renderer that constructs the glyphs with primitive path commands.
  10399. * @var {boolean}
  10400. */
  10401. PDFJS.disableFontFace = PDFJS.disableFontFace === undefined ? false : PDFJS.disableFontFace;
  10402. /**
  10403. * Path for image resources, mainly for annotation icons. Include trailing
  10404. * slash.
  10405. * @var {string}
  10406. */
  10407. PDFJS.imageResourcesPath = PDFJS.imageResourcesPath === undefined ? '' : PDFJS.imageResourcesPath;
  10408. /**
  10409. * Disable the web worker and run all code on the main thread. This will
  10410. * happen automatically if the browser doesn't support workers or sending
  10411. * typed arrays to workers.
  10412. * @var {boolean}
  10413. */
  10414. PDFJS.disableWorker = PDFJS.disableWorker === undefined ? false : PDFJS.disableWorker;
  10415. /**
  10416. * Path and filename of the worker file. Required when the worker is enabled
  10417. * in development mode. If unspecified in the production build, the worker
  10418. * will be loaded based on the location of the pdf.js file. It is recommended
  10419. * that the workerSrc is set in a custom application to prevent issues caused
  10420. * by third-party frameworks and libraries.
  10421. * @var {string}
  10422. */
  10423. PDFJS.workerSrc = PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc;
  10424. /**
  10425. * Disable range request loading of PDF files. When enabled and if the server
  10426. * supports partial content requests then the PDF will be fetched in chunks.
  10427. * Enabled (false) by default.
  10428. * @var {boolean}
  10429. */
  10430. PDFJS.disableRange = PDFJS.disableRange === undefined ? false : PDFJS.disableRange;
  10431. /**
  10432. * Disable streaming of PDF file data. By default PDF.js attempts to load PDF
  10433. * in chunks. This default behavior can be disabled.
  10434. * @var {boolean}
  10435. */
  10436. PDFJS.disableStream = PDFJS.disableStream === undefined ? false : PDFJS.disableStream;
  10437. /**
  10438. * Disable pre-fetching of PDF file data. When range requests are enabled
  10439. * PDF.js will automatically keep fetching more data even if it isn't needed
  10440. * to display the current page. This default behavior can be disabled.
  10441. *
  10442. * NOTE: It is also necessary to disable streaming, see above,
  10443. * in order for disabling of pre-fetching to work correctly.
  10444. * @var {boolean}
  10445. */
  10446. PDFJS.disableAutoFetch = PDFJS.disableAutoFetch === undefined ? false : PDFJS.disableAutoFetch;
  10447. /**
  10448. * Enables special hooks for debugging PDF.js.
  10449. * @var {boolean}
  10450. */
  10451. PDFJS.pdfBug = PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug;
  10452. /**
  10453. * Enables transfer usage in postMessage for ArrayBuffers.
  10454. * @var {boolean}
  10455. */
  10456. PDFJS.postMessageTransfers = PDFJS.postMessageTransfers === undefined ? true : PDFJS.postMessageTransfers;
  10457. /**
  10458. * Disables URL.createObjectURL usage.
  10459. * @var {boolean}
  10460. */
  10461. PDFJS.disableCreateObjectURL = PDFJS.disableCreateObjectURL === undefined ? false : PDFJS.disableCreateObjectURL;
  10462. /**
  10463. * Disables WebGL usage.
  10464. * @var {boolean}
  10465. */
  10466. PDFJS.disableWebGL = PDFJS.disableWebGL === undefined ? true : PDFJS.disableWebGL;
  10467. /**
  10468. * Specifies the |target| attribute for external links.
  10469. * The constants from PDFJS.LinkTarget should be used:
  10470. * - NONE [default]
  10471. * - SELF
  10472. * - BLANK
  10473. * - PARENT
  10474. * - TOP
  10475. * @var {number}
  10476. */
  10477. PDFJS.externalLinkTarget = PDFJS.externalLinkTarget === undefined ? LinkTarget.NONE : PDFJS.externalLinkTarget;
  10478. /**
  10479. * Specifies the |rel| attribute for external links. Defaults to stripping
  10480. * the referrer.
  10481. * @var {string}
  10482. */
  10483. PDFJS.externalLinkRel = PDFJS.externalLinkRel === undefined ? 'noreferrer' : PDFJS.externalLinkRel;
  10484. /**
  10485. * Determines if we can eval strings as JS. Primarily used to improve
  10486. * performance for font rendering.
  10487. * @var {boolean}
  10488. */
  10489. PDFJS.isEvalSupported = PDFJS.isEvalSupported === undefined ? true : PDFJS.isEvalSupported;
  10490. var savedOpenExternalLinksInNewWindow = PDFJS.openExternalLinksInNewWindow;
  10491. delete PDFJS.openExternalLinksInNewWindow;
  10492. Object.defineProperty(PDFJS, 'openExternalLinksInNewWindow', {
  10493. get: function () {
  10494. return PDFJS.externalLinkTarget === LinkTarget.BLANK;
  10495. },
  10496. set: function (value) {
  10497. if (value) {
  10498. deprecated('PDFJS.openExternalLinksInNewWindow, please use ' + '"PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.');
  10499. }
  10500. if (PDFJS.externalLinkTarget !== LinkTarget.NONE) {
  10501. warn('PDFJS.externalLinkTarget is already initialized');
  10502. return;
  10503. }
  10504. PDFJS.externalLinkTarget = value ? LinkTarget.BLANK : LinkTarget.NONE;
  10505. },
  10506. enumerable: true,
  10507. configurable: true
  10508. });
  10509. if (savedOpenExternalLinksInNewWindow) {
  10510. /**
  10511. * (Deprecated) Opens external links in a new window if enabled.
  10512. * The default behavior opens external links in the PDF.js window.
  10513. *
  10514. * NOTE: This property has been deprecated, please use
  10515. * `PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK` instead.
  10516. * @var {boolean}
  10517. */
  10518. PDFJS.openExternalLinksInNewWindow = savedOpenExternalLinksInNewWindow;
  10519. }
  10520. PDFJS.getDocument = displayAPI.getDocument;
  10521. PDFJS.PDFDataRangeTransport = displayAPI.PDFDataRangeTransport;
  10522. PDFJS.PDFWorker = displayAPI.PDFWorker;
  10523. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  10524. configurable: true,
  10525. get: function PDFJS_hasCanvasTypedArrays() {
  10526. var value = displayDOMUtils.hasCanvasTypedArrays();
  10527. return sharedUtil.shadow(PDFJS, 'hasCanvasTypedArrays', value);
  10528. }
  10529. });
  10530. PDFJS.CustomStyle = displayDOMUtils.CustomStyle;
  10531. PDFJS.LinkTarget = LinkTarget;
  10532. PDFJS.addLinkAttributes = displayDOMUtils.addLinkAttributes;
  10533. PDFJS.getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  10534. PDFJS.isExternalLinkTargetSet = displayDOMUtils.isExternalLinkTargetSet;
  10535. PDFJS.AnnotationLayer = displayAnnotationLayer.AnnotationLayer;
  10536. PDFJS.renderTextLayer = displayTextLayer.renderTextLayer;
  10537. PDFJS.Metadata = displayMetadata.Metadata;
  10538. PDFJS.SVGGraphics = displaySVG.SVGGraphics;
  10539. PDFJS.UnsupportedManager = displayAPI._UnsupportedManager;
  10540. exports.globalScope = globalScope;
  10541. exports.isWorker = isWorker;
  10542. exports.PDFJS = globalScope.PDFJS;
  10543. }));
  10544. }.call(pdfjsLibs));
  10545. exports.PDFJS = pdfjsLibs.pdfjsDisplayGlobal.PDFJS;
  10546. exports.build = pdfjsLibs.pdfjsDisplayAPI.build;
  10547. exports.version = pdfjsLibs.pdfjsDisplayAPI.version;
  10548. exports.getDocument = pdfjsLibs.pdfjsDisplayAPI.getDocument;
  10549. exports.PDFDataRangeTransport = pdfjsLibs.pdfjsDisplayAPI.PDFDataRangeTransport;
  10550. exports.PDFWorker = pdfjsLibs.pdfjsDisplayAPI.PDFWorker;
  10551. exports.renderTextLayer = pdfjsLibs.pdfjsDisplayTextLayer.renderTextLayer;
  10552. exports.AnnotationLayer = pdfjsLibs.pdfjsDisplayAnnotationLayer.AnnotationLayer;
  10553. exports.CustomStyle = pdfjsLibs.pdfjsDisplayDOMUtils.CustomStyle;
  10554. exports.PasswordResponses = pdfjsLibs.pdfjsSharedUtil.PasswordResponses;
  10555. exports.InvalidPDFException = pdfjsLibs.pdfjsSharedUtil.InvalidPDFException;
  10556. exports.MissingPDFException = pdfjsLibs.pdfjsSharedUtil.MissingPDFException;
  10557. exports.SVGGraphics = pdfjsLibs.pdfjsDisplaySVG.SVGGraphics;
  10558. exports.UnexpectedResponseException = pdfjsLibs.pdfjsSharedUtil.UnexpectedResponseException;
  10559. exports.OPS = pdfjsLibs.pdfjsSharedUtil.OPS;
  10560. exports.UNSUPPORTED_FEATURES = pdfjsLibs.pdfjsSharedUtil.UNSUPPORTED_FEATURES;
  10561. exports.isValidUrl = pdfjsLibs.pdfjsSharedUtil.isValidUrl;
  10562. exports.createObjectURL = pdfjsLibs.pdfjsSharedUtil.createObjectURL;
  10563. exports.removeNullCharacters = pdfjsLibs.pdfjsSharedUtil.removeNullCharacters;
  10564. exports.shadow = pdfjsLibs.pdfjsSharedUtil.shadow;
  10565. exports.createBlob = pdfjsLibs.pdfjsSharedUtil.createBlob;
  10566. exports.getFilenameFromUrl = pdfjsLibs.pdfjsDisplayDOMUtils.getFilenameFromUrl;
  10567. exports.addLinkAttributes = pdfjsLibs.pdfjsDisplayDOMUtils.addLinkAttributes;
  10568. }));