pdf.js 420 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538
  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.254';
  28. var pdfjsBuild = '273d2de';
  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 opListToTree(opList) {
  3299. var opTree = [];
  3300. var tmp = [];
  3301. var opListLen = opList.length;
  3302. for (var x = 0; x < opListLen; x++) {
  3303. if (opList[x].fn === 'save') {
  3304. opTree.push({
  3305. 'fnId': 92,
  3306. 'fn': 'group',
  3307. 'items': []
  3308. });
  3309. tmp.push(opTree);
  3310. opTree = opTree[opTree.length - 1].items;
  3311. continue;
  3312. }
  3313. if (opList[x].fn === 'restore') {
  3314. opTree = tmp.pop();
  3315. } else {
  3316. opTree.push(opList[x]);
  3317. }
  3318. }
  3319. return opTree;
  3320. }
  3321. /**
  3322. * Formats float number.
  3323. * @param value {number} number to format.
  3324. * @returns {string}
  3325. */
  3326. function pf(value) {
  3327. if (value === (value | 0)) {
  3328. // integer number
  3329. return value.toString();
  3330. }
  3331. var s = value.toFixed(10);
  3332. var i = s.length - 1;
  3333. if (s[i] !== '0') {
  3334. return s;
  3335. }
  3336. // removing trailing zeros
  3337. do {
  3338. i--;
  3339. } while (s[i] === '0');
  3340. return s.substr(0, s[i] === '.' ? i : i + 1);
  3341. }
  3342. /**
  3343. * Formats transform matrix. The standard rotation, scale and translate
  3344. * matrices are replaced by their shorter forms, and for identity matrix
  3345. * returns empty string to save the memory.
  3346. * @param m {Array} matrix to format.
  3347. * @returns {string}
  3348. */
  3349. function pm(m) {
  3350. if (m[4] === 0 && m[5] === 0) {
  3351. if (m[1] === 0 && m[2] === 0) {
  3352. if (m[0] === 1 && m[3] === 1) {
  3353. return '';
  3354. }
  3355. return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')';
  3356. }
  3357. if (m[0] === m[3] && m[1] === -m[2]) {
  3358. var a = Math.acos(m[0]) * 180 / Math.PI;
  3359. return 'rotate(' + pf(a) + ')';
  3360. }
  3361. } else {
  3362. if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
  3363. return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3364. }
  3365. }
  3366. return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' + pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')';
  3367. }
  3368. function SVGGraphics(commonObjs, objs, forceDataSchema) {
  3369. this.current = new SVGExtraState();
  3370. this.transformMatrix = IDENTITY_MATRIX;
  3371. // Graphics state matrix
  3372. this.transformStack = [];
  3373. this.extraStack = [];
  3374. this.commonObjs = commonObjs;
  3375. this.objs = objs;
  3376. this.pendingEOFill = false;
  3377. this.embedFonts = false;
  3378. this.embeddedFonts = Object.create(null);
  3379. this.cssStyle = null;
  3380. this.forceDataSchema = !!forceDataSchema;
  3381. }
  3382. var NS = 'http://www.w3.org/2000/svg';
  3383. var XML_NS = 'http://www.w3.org/XML/1998/namespace';
  3384. var XLINK_NS = 'http://www.w3.org/1999/xlink';
  3385. var LINE_CAP_STYLES = [
  3386. 'butt',
  3387. 'round',
  3388. 'square'
  3389. ];
  3390. var LINE_JOIN_STYLES = [
  3391. 'miter',
  3392. 'round',
  3393. 'bevel'
  3394. ];
  3395. var clipCount = 0;
  3396. var maskCount = 0;
  3397. SVGGraphics.prototype = {
  3398. save: function SVGGraphics_save() {
  3399. this.transformStack.push(this.transformMatrix);
  3400. var old = this.current;
  3401. this.extraStack.push(old);
  3402. this.current = old.clone();
  3403. },
  3404. restore: function SVGGraphics_restore() {
  3405. this.transformMatrix = this.transformStack.pop();
  3406. this.current = this.extraStack.pop();
  3407. this.tgrp = null;
  3408. },
  3409. group: function SVGGraphics_group(items) {
  3410. this.save();
  3411. this.executeOpTree(items);
  3412. this.restore();
  3413. },
  3414. loadDependencies: function SVGGraphics_loadDependencies(operatorList) {
  3415. var fnArray = operatorList.fnArray;
  3416. var fnArrayLen = fnArray.length;
  3417. var argsArray = operatorList.argsArray;
  3418. var self = this;
  3419. for (var i = 0; i < fnArrayLen; i++) {
  3420. if (OPS.dependency === fnArray[i]) {
  3421. var deps = argsArray[i];
  3422. for (var n = 0, nn = deps.length; n < nn; n++) {
  3423. var obj = deps[n];
  3424. var common = obj.substring(0, 2) === 'g_';
  3425. var promise;
  3426. if (common) {
  3427. promise = new Promise(function (resolve) {
  3428. self.commonObjs.get(obj, resolve);
  3429. });
  3430. } else {
  3431. promise = new Promise(function (resolve) {
  3432. self.objs.get(obj, resolve);
  3433. });
  3434. }
  3435. this.current.dependencies.push(promise);
  3436. }
  3437. }
  3438. }
  3439. return Promise.all(this.current.dependencies);
  3440. },
  3441. transform: function SVGGraphics_transform(a, b, c, d, e, f) {
  3442. var transformMatrix = [
  3443. a,
  3444. b,
  3445. c,
  3446. d,
  3447. e,
  3448. f
  3449. ];
  3450. this.transformMatrix = Util.transform(this.transformMatrix, transformMatrix);
  3451. this.tgrp = null;
  3452. },
  3453. getSVG: function SVGGraphics_getSVG(operatorList, viewport) {
  3454. this.viewport = viewport;
  3455. var svgElement = this._initialize(viewport);
  3456. return this.loadDependencies(operatorList).then(function () {
  3457. this.transformMatrix = IDENTITY_MATRIX;
  3458. var opTree = this.convertOpList(operatorList);
  3459. this.executeOpTree(opTree);
  3460. return svgElement;
  3461. }.bind(this));
  3462. },
  3463. convertOpList: function SVGGraphics_convertOpList(operatorList) {
  3464. var argsArray = operatorList.argsArray;
  3465. var fnArray = operatorList.fnArray;
  3466. var fnArrayLen = fnArray.length;
  3467. var REVOPS = [];
  3468. var opList = [];
  3469. for (var op in OPS) {
  3470. REVOPS[OPS[op]] = op;
  3471. }
  3472. for (var x = 0; x < fnArrayLen; x++) {
  3473. var fnId = fnArray[x];
  3474. opList.push({
  3475. 'fnId': fnId,
  3476. 'fn': REVOPS[fnId],
  3477. 'args': argsArray[x]
  3478. });
  3479. }
  3480. return opListToTree(opList);
  3481. },
  3482. executeOpTree: function SVGGraphics_executeOpTree(opTree) {
  3483. var opTreeLen = opTree.length;
  3484. for (var x = 0; x < opTreeLen; x++) {
  3485. var fn = opTree[x].fn;
  3486. var fnId = opTree[x].fnId;
  3487. var args = opTree[x].args;
  3488. switch (fnId | 0) {
  3489. case OPS.beginText:
  3490. this.beginText();
  3491. break;
  3492. case OPS.setLeading:
  3493. this.setLeading(args);
  3494. break;
  3495. case OPS.setLeadingMoveText:
  3496. this.setLeadingMoveText(args[0], args[1]);
  3497. break;
  3498. case OPS.setFont:
  3499. this.setFont(args);
  3500. break;
  3501. case OPS.showText:
  3502. this.showText(args[0]);
  3503. break;
  3504. case OPS.showSpacedText:
  3505. this.showText(args[0]);
  3506. break;
  3507. case OPS.endText:
  3508. this.endText();
  3509. break;
  3510. case OPS.moveText:
  3511. this.moveText(args[0], args[1]);
  3512. break;
  3513. case OPS.setCharSpacing:
  3514. this.setCharSpacing(args[0]);
  3515. break;
  3516. case OPS.setWordSpacing:
  3517. this.setWordSpacing(args[0]);
  3518. break;
  3519. case OPS.setHScale:
  3520. this.setHScale(args[0]);
  3521. break;
  3522. case OPS.setTextMatrix:
  3523. this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
  3524. break;
  3525. case OPS.setLineWidth:
  3526. this.setLineWidth(args[0]);
  3527. break;
  3528. case OPS.setLineJoin:
  3529. this.setLineJoin(args[0]);
  3530. break;
  3531. case OPS.setLineCap:
  3532. this.setLineCap(args[0]);
  3533. break;
  3534. case OPS.setMiterLimit:
  3535. this.setMiterLimit(args[0]);
  3536. break;
  3537. case OPS.setFillRGBColor:
  3538. this.setFillRGBColor(args[0], args[1], args[2]);
  3539. break;
  3540. case OPS.setStrokeRGBColor:
  3541. this.setStrokeRGBColor(args[0], args[1], args[2]);
  3542. break;
  3543. case OPS.setDash:
  3544. this.setDash(args[0], args[1]);
  3545. break;
  3546. case OPS.setGState:
  3547. this.setGState(args[0]);
  3548. break;
  3549. case OPS.fill:
  3550. this.fill();
  3551. break;
  3552. case OPS.eoFill:
  3553. this.eoFill();
  3554. break;
  3555. case OPS.stroke:
  3556. this.stroke();
  3557. break;
  3558. case OPS.fillStroke:
  3559. this.fillStroke();
  3560. break;
  3561. case OPS.eoFillStroke:
  3562. this.eoFillStroke();
  3563. break;
  3564. case OPS.clip:
  3565. this.clip('nonzero');
  3566. break;
  3567. case OPS.eoClip:
  3568. this.clip('evenodd');
  3569. break;
  3570. case OPS.paintSolidColorImageMask:
  3571. this.paintSolidColorImageMask();
  3572. break;
  3573. case OPS.paintJpegXObject:
  3574. this.paintJpegXObject(args[0], args[1], args[2]);
  3575. break;
  3576. case OPS.paintImageXObject:
  3577. this.paintImageXObject(args[0]);
  3578. break;
  3579. case OPS.paintInlineImageXObject:
  3580. this.paintInlineImageXObject(args[0]);
  3581. break;
  3582. case OPS.paintImageMaskXObject:
  3583. this.paintImageMaskXObject(args[0]);
  3584. break;
  3585. case OPS.paintFormXObjectBegin:
  3586. this.paintFormXObjectBegin(args[0], args[1]);
  3587. break;
  3588. case OPS.paintFormXObjectEnd:
  3589. this.paintFormXObjectEnd();
  3590. break;
  3591. case OPS.closePath:
  3592. this.closePath();
  3593. break;
  3594. case OPS.closeStroke:
  3595. this.closeStroke();
  3596. break;
  3597. case OPS.closeFillStroke:
  3598. this.closeFillStroke();
  3599. break;
  3600. case OPS.nextLine:
  3601. this.nextLine();
  3602. break;
  3603. case OPS.transform:
  3604. this.transform(args[0], args[1], args[2], args[3], args[4], args[5]);
  3605. break;
  3606. case OPS.constructPath:
  3607. this.constructPath(args[0], args[1]);
  3608. break;
  3609. case OPS.endPath:
  3610. this.endPath();
  3611. break;
  3612. case 92:
  3613. this.group(opTree[x].items);
  3614. break;
  3615. default:
  3616. warn('Unimplemented operator ' + fn);
  3617. break;
  3618. }
  3619. }
  3620. },
  3621. setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) {
  3622. this.current.wordSpacing = wordSpacing;
  3623. },
  3624. setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) {
  3625. this.current.charSpacing = charSpacing;
  3626. },
  3627. nextLine: function SVGGraphics_nextLine() {
  3628. this.moveText(0, this.current.leading);
  3629. },
  3630. setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) {
  3631. var current = this.current;
  3632. this.current.textMatrix = this.current.lineMatrix = [
  3633. a,
  3634. b,
  3635. c,
  3636. d,
  3637. e,
  3638. f
  3639. ];
  3640. this.current.x = this.current.lineX = 0;
  3641. this.current.y = this.current.lineY = 0;
  3642. current.xcoords = [];
  3643. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3644. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3645. current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px');
  3646. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3647. current.txtElement = document.createElementNS(NS, 'svg:text');
  3648. current.txtElement.appendChild(current.tspan);
  3649. },
  3650. beginText: function SVGGraphics_beginText() {
  3651. this.current.x = this.current.lineX = 0;
  3652. this.current.y = this.current.lineY = 0;
  3653. this.current.textMatrix = IDENTITY_MATRIX;
  3654. this.current.lineMatrix = IDENTITY_MATRIX;
  3655. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3656. this.current.txtElement = document.createElementNS(NS, 'svg:text');
  3657. this.current.txtgrp = document.createElementNS(NS, 'svg:g');
  3658. this.current.xcoords = [];
  3659. },
  3660. moveText: function SVGGraphics_moveText(x, y) {
  3661. var current = this.current;
  3662. this.current.x = this.current.lineX += x;
  3663. this.current.y = this.current.lineY += y;
  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. },
  3670. showText: function SVGGraphics_showText(glyphs) {
  3671. var current = this.current;
  3672. var font = current.font;
  3673. var fontSize = current.fontSize;
  3674. if (fontSize === 0) {
  3675. return;
  3676. }
  3677. var charSpacing = current.charSpacing;
  3678. var wordSpacing = current.wordSpacing;
  3679. var fontDirection = current.fontDirection;
  3680. var textHScale = current.textHScale * fontDirection;
  3681. var glyphsLength = glyphs.length;
  3682. var vertical = font.vertical;
  3683. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  3684. var x = 0, i;
  3685. for (i = 0; i < glyphsLength; ++i) {
  3686. var glyph = glyphs[i];
  3687. if (glyph === null) {
  3688. // word break
  3689. x += fontDirection * wordSpacing;
  3690. continue;
  3691. } else if (isNum(glyph)) {
  3692. x += -glyph * fontSize * 0.001;
  3693. continue;
  3694. }
  3695. current.xcoords.push(current.x + x * textHScale);
  3696. var width = glyph.width;
  3697. var character = glyph.fontChar;
  3698. var charWidth = width * widthAdvanceScale + charSpacing * fontDirection;
  3699. x += charWidth;
  3700. current.tspan.textContent += character;
  3701. }
  3702. if (vertical) {
  3703. current.y -= x * textHScale;
  3704. } else {
  3705. current.x += x * textHScale;
  3706. }
  3707. current.tspan.setAttributeNS(null, 'x', current.xcoords.map(pf).join(' '));
  3708. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3709. current.tspan.setAttributeNS(null, 'font-family', current.fontFamily);
  3710. current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px');
  3711. if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
  3712. current.tspan.setAttributeNS(null, 'font-style', current.fontStyle);
  3713. }
  3714. if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
  3715. current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight);
  3716. }
  3717. if (current.fillColor !== SVG_DEFAULTS.fillColor) {
  3718. current.tspan.setAttributeNS(null, 'fill', current.fillColor);
  3719. }
  3720. current.txtElement.setAttributeNS(null, 'transform', pm(current.textMatrix) + ' scale(1, -1)');
  3721. current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve');
  3722. current.txtElement.appendChild(current.tspan);
  3723. current.txtgrp.appendChild(current.txtElement);
  3724. this._ensureTransformGroup().appendChild(current.txtElement);
  3725. },
  3726. setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) {
  3727. this.setLeading(-y);
  3728. this.moveText(x, y);
  3729. },
  3730. addFontStyle: function SVGGraphics_addFontStyle(fontObj) {
  3731. if (!this.cssStyle) {
  3732. this.cssStyle = document.createElementNS(NS, 'svg:style');
  3733. this.cssStyle.setAttributeNS(null, 'type', 'text/css');
  3734. this.defs.appendChild(this.cssStyle);
  3735. }
  3736. var url = createObjectURL(fontObj.data, fontObj.mimetype, this.forceDataSchema);
  3737. this.cssStyle.textContent += '@font-face { font-family: "' + fontObj.loadedName + '";' + ' src: url(' + url + '); }\n';
  3738. },
  3739. setFont: function SVGGraphics_setFont(details) {
  3740. var current = this.current;
  3741. var fontObj = this.commonObjs.get(details[0]);
  3742. var size = details[1];
  3743. this.current.font = fontObj;
  3744. if (this.embedFonts && fontObj.data && !this.embeddedFonts[fontObj.loadedName]) {
  3745. this.addFontStyle(fontObj);
  3746. this.embeddedFonts[fontObj.loadedName] = fontObj;
  3747. }
  3748. current.fontMatrix = fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX;
  3749. var bold = fontObj.black ? fontObj.bold ? 'bolder' : 'bold' : fontObj.bold ? 'bold' : 'normal';
  3750. var italic = fontObj.italic ? 'italic' : 'normal';
  3751. if (size < 0) {
  3752. size = -size;
  3753. current.fontDirection = -1;
  3754. } else {
  3755. current.fontDirection = 1;
  3756. }
  3757. current.fontSize = size;
  3758. current.fontFamily = fontObj.loadedName;
  3759. current.fontWeight = bold;
  3760. current.fontStyle = italic;
  3761. current.tspan = document.createElementNS(NS, 'svg:tspan');
  3762. current.tspan.setAttributeNS(null, 'y', pf(-current.y));
  3763. current.xcoords = [];
  3764. },
  3765. endText: function SVGGraphics_endText() {
  3766. },
  3767. // Path properties
  3768. setLineWidth: function SVGGraphics_setLineWidth(width) {
  3769. this.current.lineWidth = width;
  3770. },
  3771. setLineCap: function SVGGraphics_setLineCap(style) {
  3772. this.current.lineCap = LINE_CAP_STYLES[style];
  3773. },
  3774. setLineJoin: function SVGGraphics_setLineJoin(style) {
  3775. this.current.lineJoin = LINE_JOIN_STYLES[style];
  3776. },
  3777. setMiterLimit: function SVGGraphics_setMiterLimit(limit) {
  3778. this.current.miterLimit = limit;
  3779. },
  3780. setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) {
  3781. var color = Util.makeCssRgb(r, g, b);
  3782. this.current.strokeColor = color;
  3783. },
  3784. setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) {
  3785. var color = Util.makeCssRgb(r, g, b);
  3786. this.current.fillColor = color;
  3787. this.current.tspan = document.createElementNS(NS, 'svg:tspan');
  3788. this.current.xcoords = [];
  3789. },
  3790. setDash: function SVGGraphics_setDash(dashArray, dashPhase) {
  3791. this.current.dashArray = dashArray;
  3792. this.current.dashPhase = dashPhase;
  3793. },
  3794. constructPath: function SVGGraphics_constructPath(ops, args) {
  3795. var current = this.current;
  3796. var x = current.x, y = current.y;
  3797. current.path = document.createElementNS(NS, 'svg:path');
  3798. var d = [];
  3799. var opLength = ops.length;
  3800. for (var i = 0, j = 0; i < opLength; i++) {
  3801. switch (ops[i] | 0) {
  3802. case OPS.rectangle:
  3803. x = args[j++];
  3804. y = args[j++];
  3805. var width = args[j++];
  3806. var height = args[j++];
  3807. var xw = x + width;
  3808. var yh = y + height;
  3809. d.push('M', pf(x), pf(y), 'L', pf(xw), pf(y), 'L', pf(xw), pf(yh), 'L', pf(x), pf(yh), 'Z');
  3810. break;
  3811. case OPS.moveTo:
  3812. x = args[j++];
  3813. y = args[j++];
  3814. d.push('M', pf(x), pf(y));
  3815. break;
  3816. case OPS.lineTo:
  3817. x = args[j++];
  3818. y = args[j++];
  3819. d.push('L', pf(x), pf(y));
  3820. break;
  3821. case OPS.curveTo:
  3822. x = args[j + 4];
  3823. y = args[j + 5];
  3824. d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y));
  3825. j += 6;
  3826. break;
  3827. case OPS.curveTo2:
  3828. x = args[j + 2];
  3829. y = args[j + 3];
  3830. d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]));
  3831. j += 4;
  3832. break;
  3833. case OPS.curveTo3:
  3834. x = args[j + 2];
  3835. y = args[j + 3];
  3836. d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y));
  3837. j += 4;
  3838. break;
  3839. case OPS.closePath:
  3840. d.push('Z');
  3841. break;
  3842. }
  3843. }
  3844. current.path.setAttributeNS(null, 'd', d.join(' '));
  3845. current.path.setAttributeNS(null, 'stroke-miterlimit', pf(current.miterLimit));
  3846. current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap);
  3847. current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin);
  3848. current.path.setAttributeNS(null, 'stroke-width', pf(current.lineWidth) + 'px');
  3849. current.path.setAttributeNS(null, 'stroke-dasharray', current.dashArray.map(pf).join(' '));
  3850. current.path.setAttributeNS(null, 'stroke-dashoffset', pf(current.dashPhase) + 'px');
  3851. current.path.setAttributeNS(null, 'fill', 'none');
  3852. this._ensureTransformGroup().appendChild(current.path);
  3853. // Saving a reference in current.element so that it can be addressed
  3854. // in 'fill' and 'stroke'
  3855. current.element = current.path;
  3856. current.setCurrentPoint(x, y);
  3857. },
  3858. endPath: function SVGGraphics_endPath() {
  3859. },
  3860. clip: function SVGGraphics_clip(type) {
  3861. var current = this.current;
  3862. // Add current path to clipping path
  3863. current.clipId = 'clippath' + clipCount;
  3864. clipCount++;
  3865. this.clippath = document.createElementNS(NS, 'svg:clipPath');
  3866. this.clippath.setAttributeNS(null, 'id', current.clipId);
  3867. var clipElement = current.element.cloneNode();
  3868. if (type === 'evenodd') {
  3869. clipElement.setAttributeNS(null, 'clip-rule', 'evenodd');
  3870. } else {
  3871. clipElement.setAttributeNS(null, 'clip-rule', 'nonzero');
  3872. }
  3873. this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  3874. this.clippath.appendChild(clipElement);
  3875. this.defs.appendChild(this.clippath);
  3876. // Create a clipping group that references the clipping path.
  3877. current.pendingClip = true;
  3878. this.cgrp = document.createElementNS(NS, 'svg:g');
  3879. this.cgrp.setAttributeNS(null, 'clip-path', 'url(#' + current.clipId + ')');
  3880. this.svg.appendChild(this.cgrp);
  3881. },
  3882. closePath: function SVGGraphics_closePath() {
  3883. var current = this.current;
  3884. var d = current.path.getAttributeNS(null, 'd');
  3885. d += 'Z';
  3886. current.path.setAttributeNS(null, 'd', d);
  3887. },
  3888. setLeading: function SVGGraphics_setLeading(leading) {
  3889. this.current.leading = -leading;
  3890. },
  3891. setTextRise: function SVGGraphics_setTextRise(textRise) {
  3892. this.current.textRise = textRise;
  3893. },
  3894. setHScale: function SVGGraphics_setHScale(scale) {
  3895. this.current.textHScale = scale / 100;
  3896. },
  3897. setGState: function SVGGraphics_setGState(states) {
  3898. for (var i = 0, ii = states.length; i < ii; i++) {
  3899. var state = states[i];
  3900. var key = state[0];
  3901. var value = state[1];
  3902. switch (key) {
  3903. case 'LW':
  3904. this.setLineWidth(value);
  3905. break;
  3906. case 'LC':
  3907. this.setLineCap(value);
  3908. break;
  3909. case 'LJ':
  3910. this.setLineJoin(value);
  3911. break;
  3912. case 'ML':
  3913. this.setMiterLimit(value);
  3914. break;
  3915. case 'D':
  3916. this.setDash(value[0], value[1]);
  3917. break;
  3918. case 'Font':
  3919. this.setFont(value);
  3920. break;
  3921. default:
  3922. warn('Unimplemented graphic state ' + key);
  3923. break;
  3924. }
  3925. }
  3926. },
  3927. fill: function SVGGraphics_fill() {
  3928. var current = this.current;
  3929. current.element.setAttributeNS(null, 'fill', current.fillColor);
  3930. },
  3931. stroke: function SVGGraphics_stroke() {
  3932. var current = this.current;
  3933. current.element.setAttributeNS(null, 'stroke', current.strokeColor);
  3934. current.element.setAttributeNS(null, 'fill', 'none');
  3935. },
  3936. eoFill: function SVGGraphics_eoFill() {
  3937. var current = this.current;
  3938. current.element.setAttributeNS(null, 'fill', current.fillColor);
  3939. current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  3940. },
  3941. fillStroke: function SVGGraphics_fillStroke() {
  3942. // Order is important since stroke wants fill to be none.
  3943. // First stroke, then if fill needed, it will be overwritten.
  3944. this.stroke();
  3945. this.fill();
  3946. },
  3947. eoFillStroke: function SVGGraphics_eoFillStroke() {
  3948. this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd');
  3949. this.fillStroke();
  3950. },
  3951. closeStroke: function SVGGraphics_closeStroke() {
  3952. this.closePath();
  3953. this.stroke();
  3954. },
  3955. closeFillStroke: function SVGGraphics_closeFillStroke() {
  3956. this.closePath();
  3957. this.fillStroke();
  3958. },
  3959. paintSolidColorImageMask: function SVGGraphics_paintSolidColorImageMask() {
  3960. var current = this.current;
  3961. var rect = document.createElementNS(NS, 'svg:rect');
  3962. rect.setAttributeNS(null, 'x', '0');
  3963. rect.setAttributeNS(null, 'y', '0');
  3964. rect.setAttributeNS(null, 'width', '1px');
  3965. rect.setAttributeNS(null, 'height', '1px');
  3966. rect.setAttributeNS(null, 'fill', current.fillColor);
  3967. this._ensureTransformGroup().appendChild(rect);
  3968. },
  3969. paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) {
  3970. var imgObj = this.objs.get(objId);
  3971. var imgEl = document.createElementNS(NS, 'svg:image');
  3972. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src);
  3973. imgEl.setAttributeNS(null, 'width', imgObj.width + 'px');
  3974. imgEl.setAttributeNS(null, 'height', imgObj.height + 'px');
  3975. imgEl.setAttributeNS(null, 'x', '0');
  3976. imgEl.setAttributeNS(null, 'y', pf(-h));
  3977. imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')');
  3978. this._ensureTransformGroup().appendChild(imgEl);
  3979. },
  3980. paintImageXObject: function SVGGraphics_paintImageXObject(objId) {
  3981. var imgData = this.objs.get(objId);
  3982. if (!imgData) {
  3983. warn('Dependent image isn\'t ready yet');
  3984. return;
  3985. }
  3986. this.paintInlineImageXObject(imgData);
  3987. },
  3988. paintInlineImageXObject: function SVGGraphics_paintInlineImageXObject(imgData, mask) {
  3989. var width = imgData.width;
  3990. var height = imgData.height;
  3991. var imgSrc = convertImgDataToPng(imgData, this.forceDataSchema);
  3992. var cliprect = document.createElementNS(NS, 'svg:rect');
  3993. cliprect.setAttributeNS(null, 'x', '0');
  3994. cliprect.setAttributeNS(null, 'y', '0');
  3995. cliprect.setAttributeNS(null, 'width', pf(width));
  3996. cliprect.setAttributeNS(null, 'height', pf(height));
  3997. this.current.element = cliprect;
  3998. this.clip('nonzero');
  3999. var imgEl = document.createElementNS(NS, 'svg:image');
  4000. imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc);
  4001. imgEl.setAttributeNS(null, 'x', '0');
  4002. imgEl.setAttributeNS(null, 'y', pf(-height));
  4003. imgEl.setAttributeNS(null, 'width', pf(width) + 'px');
  4004. imgEl.setAttributeNS(null, 'height', pf(height) + 'px');
  4005. imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / width) + ' ' + pf(-1 / height) + ')');
  4006. if (mask) {
  4007. mask.appendChild(imgEl);
  4008. } else {
  4009. this._ensureTransformGroup().appendChild(imgEl);
  4010. }
  4011. },
  4012. paintImageMaskXObject: function SVGGraphics_paintImageMaskXObject(imgData) {
  4013. var current = this.current;
  4014. var width = imgData.width;
  4015. var height = imgData.height;
  4016. var fillColor = current.fillColor;
  4017. current.maskId = 'mask' + maskCount++;
  4018. var mask = document.createElementNS(NS, 'svg:mask');
  4019. mask.setAttributeNS(null, 'id', current.maskId);
  4020. var rect = document.createElementNS(NS, 'svg:rect');
  4021. rect.setAttributeNS(null, 'x', '0');
  4022. rect.setAttributeNS(null, 'y', '0');
  4023. rect.setAttributeNS(null, 'width', pf(width));
  4024. rect.setAttributeNS(null, 'height', pf(height));
  4025. rect.setAttributeNS(null, 'fill', fillColor);
  4026. rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId + ')');
  4027. this.defs.appendChild(mask);
  4028. this._ensureTransformGroup().appendChild(rect);
  4029. this.paintInlineImageXObject(imgData, mask);
  4030. },
  4031. paintFormXObjectBegin: function SVGGraphics_paintFormXObjectBegin(matrix, bbox) {
  4032. if (isArray(matrix) && matrix.length === 6) {
  4033. this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
  4034. }
  4035. if (isArray(bbox) && bbox.length === 4) {
  4036. var width = bbox[2] - bbox[0];
  4037. var height = bbox[3] - bbox[1];
  4038. var cliprect = document.createElementNS(NS, 'svg:rect');
  4039. cliprect.setAttributeNS(null, 'x', bbox[0]);
  4040. cliprect.setAttributeNS(null, 'y', bbox[1]);
  4041. cliprect.setAttributeNS(null, 'width', pf(width));
  4042. cliprect.setAttributeNS(null, 'height', pf(height));
  4043. this.current.element = cliprect;
  4044. this.clip('nonzero');
  4045. this.endPath();
  4046. }
  4047. },
  4048. paintFormXObjectEnd: function SVGGraphics_paintFormXObjectEnd() {
  4049. },
  4050. /**
  4051. * @private
  4052. */
  4053. _initialize: function SVGGraphics_initialize(viewport) {
  4054. // Create the SVG element.
  4055. var svg = document.createElementNS(NS, 'svg:svg');
  4056. svg.setAttributeNS(null, 'version', '1.1');
  4057. svg.setAttributeNS(null, 'width', viewport.width + 'px');
  4058. svg.setAttributeNS(null, 'height', viewport.height + 'px');
  4059. svg.setAttributeNS(null, 'viewBox', '0 0 ' + viewport.width + ' ' + viewport.height);
  4060. // Create the definitions element.
  4061. var definitions = document.createElementNS(NS, 'svg:defs');
  4062. svg.appendChild(definitions);
  4063. this.defs = definitions;
  4064. // Create the root group element, which acts a container for all other
  4065. // groups and applies the viewport transform.
  4066. var rootGroup = document.createElementNS(NS, 'svg:g');
  4067. rootGroup.setAttributeNS(null, 'transform', pm(viewport.transform));
  4068. svg.appendChild(rootGroup);
  4069. // For the construction of the SVG image we are only interested in the
  4070. // root group, so we expose it as the entry point of the SVG image for
  4071. // the other code in this class.
  4072. this.svg = rootGroup;
  4073. return svg;
  4074. },
  4075. /**
  4076. * @private
  4077. */
  4078. _ensureTransformGroup: function SVGGraphics_ensureTransformGroup() {
  4079. if (!this.tgrp) {
  4080. this.tgrp = document.createElementNS(NS, 'svg:g');
  4081. this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix));
  4082. if (this.current.pendingClip) {
  4083. this.cgrp.appendChild(this.tgrp);
  4084. } else {
  4085. this.svg.appendChild(this.tgrp);
  4086. }
  4087. }
  4088. return this.tgrp;
  4089. }
  4090. };
  4091. return SVGGraphics;
  4092. }();
  4093. exports.SVGGraphics = SVGGraphics;
  4094. }));
  4095. (function (root, factory) {
  4096. factory(root.pdfjsDisplayAnnotationLayer = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils);
  4097. }(this, function (exports, sharedUtil, displayDOMUtils) {
  4098. var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType;
  4099. var AnnotationType = sharedUtil.AnnotationType;
  4100. var Util = sharedUtil.Util;
  4101. var addLinkAttributes = displayDOMUtils.addLinkAttributes;
  4102. var LinkTarget = displayDOMUtils.LinkTarget;
  4103. var getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  4104. var warn = sharedUtil.warn;
  4105. var CustomStyle = displayDOMUtils.CustomStyle;
  4106. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  4107. /**
  4108. * @typedef {Object} AnnotationElementParameters
  4109. * @property {Object} data
  4110. * @property {HTMLDivElement} layer
  4111. * @property {PDFPage} page
  4112. * @property {PageViewport} viewport
  4113. * @property {IPDFLinkService} linkService
  4114. * @property {DownloadManager} downloadManager
  4115. * @property {string} imageResourcesPath
  4116. * @property {boolean} renderInteractiveForms
  4117. */
  4118. /**
  4119. * @class
  4120. * @alias AnnotationElementFactory
  4121. */
  4122. function AnnotationElementFactory() {
  4123. }
  4124. AnnotationElementFactory.prototype = /** @lends AnnotationElementFactory.prototype */
  4125. {
  4126. /**
  4127. * @param {AnnotationElementParameters} parameters
  4128. * @returns {AnnotationElement}
  4129. */
  4130. create: function AnnotationElementFactory_create(parameters) {
  4131. var subtype = parameters.data.annotationType;
  4132. switch (subtype) {
  4133. case AnnotationType.LINK:
  4134. return new LinkAnnotationElement(parameters);
  4135. case AnnotationType.TEXT:
  4136. return new TextAnnotationElement(parameters);
  4137. case AnnotationType.WIDGET:
  4138. var fieldType = parameters.data.fieldType;
  4139. switch (fieldType) {
  4140. case 'Tx':
  4141. return new TextWidgetAnnotationElement(parameters);
  4142. case 'Ch':
  4143. return new ChoiceWidgetAnnotationElement(parameters);
  4144. }
  4145. return new WidgetAnnotationElement(parameters);
  4146. case AnnotationType.POPUP:
  4147. return new PopupAnnotationElement(parameters);
  4148. case AnnotationType.HIGHLIGHT:
  4149. return new HighlightAnnotationElement(parameters);
  4150. case AnnotationType.UNDERLINE:
  4151. return new UnderlineAnnotationElement(parameters);
  4152. case AnnotationType.SQUIGGLY:
  4153. return new SquigglyAnnotationElement(parameters);
  4154. case AnnotationType.STRIKEOUT:
  4155. return new StrikeOutAnnotationElement(parameters);
  4156. case AnnotationType.FILEATTACHMENT:
  4157. return new FileAttachmentAnnotationElement(parameters);
  4158. default:
  4159. return new AnnotationElement(parameters);
  4160. }
  4161. }
  4162. };
  4163. /**
  4164. * @class
  4165. * @alias AnnotationElement
  4166. */
  4167. var AnnotationElement = function AnnotationElementClosure() {
  4168. function AnnotationElement(parameters, isRenderable) {
  4169. this.isRenderable = isRenderable || false;
  4170. this.data = parameters.data;
  4171. this.layer = parameters.layer;
  4172. this.page = parameters.page;
  4173. this.viewport = parameters.viewport;
  4174. this.linkService = parameters.linkService;
  4175. this.downloadManager = parameters.downloadManager;
  4176. this.imageResourcesPath = parameters.imageResourcesPath;
  4177. this.renderInteractiveForms = parameters.renderInteractiveForms;
  4178. if (isRenderable) {
  4179. this.container = this._createContainer();
  4180. }
  4181. }
  4182. AnnotationElement.prototype = /** @lends AnnotationElement.prototype */
  4183. {
  4184. /**
  4185. * Create an empty container for the annotation's HTML element.
  4186. *
  4187. * @private
  4188. * @memberof AnnotationElement
  4189. * @returns {HTMLSectionElement}
  4190. */
  4191. _createContainer: function AnnotationElement_createContainer() {
  4192. var data = this.data, page = this.page, viewport = this.viewport;
  4193. var container = document.createElement('section');
  4194. var width = data.rect[2] - data.rect[0];
  4195. var height = data.rect[3] - data.rect[1];
  4196. container.setAttribute('data-annotation-id', data.id);
  4197. // Do *not* modify `data.rect`, since that will corrupt the annotation
  4198. // position on subsequent calls to `_createContainer` (see issue 6804).
  4199. var rect = Util.normalizeRect([
  4200. data.rect[0],
  4201. page.view[3] - data.rect[1] + page.view[1],
  4202. data.rect[2],
  4203. page.view[3] - data.rect[3] + page.view[1]
  4204. ]);
  4205. CustomStyle.setProp('transform', container, 'matrix(' + viewport.transform.join(',') + ')');
  4206. CustomStyle.setProp('transformOrigin', container, -rect[0] + 'px ' + -rect[1] + 'px');
  4207. if (data.borderStyle.width > 0) {
  4208. container.style.borderWidth = data.borderStyle.width + 'px';
  4209. if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) {
  4210. // Underline styles only have a bottom border, so we do not need
  4211. // to adjust for all borders. This yields a similar result as
  4212. // Adobe Acrobat/Reader.
  4213. width = width - 2 * data.borderStyle.width;
  4214. height = height - 2 * data.borderStyle.width;
  4215. }
  4216. var horizontalRadius = data.borderStyle.horizontalCornerRadius;
  4217. var verticalRadius = data.borderStyle.verticalCornerRadius;
  4218. if (horizontalRadius > 0 || verticalRadius > 0) {
  4219. var radius = horizontalRadius + 'px / ' + verticalRadius + 'px';
  4220. CustomStyle.setProp('borderRadius', container, radius);
  4221. }
  4222. switch (data.borderStyle.style) {
  4223. case AnnotationBorderStyleType.SOLID:
  4224. container.style.borderStyle = 'solid';
  4225. break;
  4226. case AnnotationBorderStyleType.DASHED:
  4227. container.style.borderStyle = 'dashed';
  4228. break;
  4229. case AnnotationBorderStyleType.BEVELED:
  4230. warn('Unimplemented border style: beveled');
  4231. break;
  4232. case AnnotationBorderStyleType.INSET:
  4233. warn('Unimplemented border style: inset');
  4234. break;
  4235. case AnnotationBorderStyleType.UNDERLINE:
  4236. container.style.borderBottomStyle = 'solid';
  4237. break;
  4238. default:
  4239. break;
  4240. }
  4241. if (data.color) {
  4242. container.style.borderColor = Util.makeCssRgb(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0);
  4243. } else {
  4244. // Transparent (invisible) border, so do not draw it at all.
  4245. container.style.borderWidth = 0;
  4246. }
  4247. }
  4248. container.style.left = rect[0] + 'px';
  4249. container.style.top = rect[1] + 'px';
  4250. container.style.width = width + 'px';
  4251. container.style.height = height + 'px';
  4252. return container;
  4253. },
  4254. /**
  4255. * Create a popup for the annotation's HTML element. This is used for
  4256. * annotations that do not have a Popup entry in the dictionary, but
  4257. * are of a type that works with popups (such as Highlight annotations).
  4258. *
  4259. * @private
  4260. * @param {HTMLSectionElement} container
  4261. * @param {HTMLDivElement|HTMLImageElement|null} trigger
  4262. * @param {Object} data
  4263. * @memberof AnnotationElement
  4264. */
  4265. _createPopup: function AnnotationElement_createPopup(container, trigger, data) {
  4266. // If no trigger element is specified, create it.
  4267. if (!trigger) {
  4268. trigger = document.createElement('div');
  4269. trigger.style.height = container.style.height;
  4270. trigger.style.width = container.style.width;
  4271. container.appendChild(trigger);
  4272. }
  4273. var popupElement = new PopupElement({
  4274. container: container,
  4275. trigger: trigger,
  4276. color: data.color,
  4277. title: data.title,
  4278. contents: data.contents,
  4279. hideWrapper: true
  4280. });
  4281. var popup = popupElement.render();
  4282. // Position the popup next to the annotation's container.
  4283. popup.style.left = container.style.width;
  4284. container.appendChild(popup);
  4285. },
  4286. /**
  4287. * Render the annotation's HTML element in the empty container.
  4288. *
  4289. * @public
  4290. * @memberof AnnotationElement
  4291. */
  4292. render: function AnnotationElement_render() {
  4293. throw new Error('Abstract method AnnotationElement.render called');
  4294. }
  4295. };
  4296. return AnnotationElement;
  4297. }();
  4298. /**
  4299. * @class
  4300. * @alias LinkAnnotationElement
  4301. */
  4302. var LinkAnnotationElement = function LinkAnnotationElementClosure() {
  4303. function LinkAnnotationElement(parameters) {
  4304. AnnotationElement.call(this, parameters, true);
  4305. }
  4306. Util.inherit(LinkAnnotationElement, AnnotationElement, {
  4307. /**
  4308. * Render the link annotation's HTML element in the empty container.
  4309. *
  4310. * @public
  4311. * @memberof LinkAnnotationElement
  4312. * @returns {HTMLSectionElement}
  4313. */
  4314. render: function LinkAnnotationElement_render() {
  4315. this.container.className = 'linkAnnotation';
  4316. var link = document.createElement('a');
  4317. addLinkAttributes(link, {
  4318. url: this.data.url,
  4319. target: this.data.newWindow ? LinkTarget.BLANK : undefined
  4320. });
  4321. if (!this.data.url) {
  4322. if (this.data.action) {
  4323. this._bindNamedAction(link, this.data.action);
  4324. } else {
  4325. this._bindLink(link, this.data.dest || null);
  4326. }
  4327. }
  4328. this.container.appendChild(link);
  4329. return this.container;
  4330. },
  4331. /**
  4332. * Bind internal links to the link element.
  4333. *
  4334. * @private
  4335. * @param {Object} link
  4336. * @param {Object} destination
  4337. * @memberof LinkAnnotationElement
  4338. */
  4339. _bindLink: function LinkAnnotationElement_bindLink(link, destination) {
  4340. var self = this;
  4341. link.href = this.linkService.getDestinationHash(destination);
  4342. link.onclick = function () {
  4343. if (destination) {
  4344. self.linkService.navigateTo(destination);
  4345. }
  4346. return false;
  4347. };
  4348. if (destination) {
  4349. link.className = 'internalLink';
  4350. }
  4351. },
  4352. /**
  4353. * Bind named actions to the link element.
  4354. *
  4355. * @private
  4356. * @param {Object} link
  4357. * @param {Object} action
  4358. * @memberof LinkAnnotationElement
  4359. */
  4360. _bindNamedAction: function LinkAnnotationElement_bindNamedAction(link, action) {
  4361. var self = this;
  4362. link.href = this.linkService.getAnchorUrl('');
  4363. link.onclick = function () {
  4364. self.linkService.executeNamedAction(action);
  4365. return false;
  4366. };
  4367. link.className = 'internalLink';
  4368. }
  4369. });
  4370. return LinkAnnotationElement;
  4371. }();
  4372. /**
  4373. * @class
  4374. * @alias TextAnnotationElement
  4375. */
  4376. var TextAnnotationElement = function TextAnnotationElementClosure() {
  4377. function TextAnnotationElement(parameters) {
  4378. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4379. AnnotationElement.call(this, parameters, isRenderable);
  4380. }
  4381. Util.inherit(TextAnnotationElement, AnnotationElement, {
  4382. /**
  4383. * Render the text annotation's HTML element in the empty container.
  4384. *
  4385. * @public
  4386. * @memberof TextAnnotationElement
  4387. * @returns {HTMLSectionElement}
  4388. */
  4389. render: function TextAnnotationElement_render() {
  4390. this.container.className = 'textAnnotation';
  4391. var image = document.createElement('img');
  4392. image.style.height = this.container.style.height;
  4393. image.style.width = this.container.style.width;
  4394. image.src = this.imageResourcesPath + 'annotation-' + this.data.name.toLowerCase() + '.svg';
  4395. image.alt = '[{{type}} Annotation]';
  4396. image.dataset.l10nId = 'text_annotation_type';
  4397. image.dataset.l10nArgs = JSON.stringify({ type: this.data.name });
  4398. if (!this.data.hasPopup) {
  4399. this._createPopup(this.container, image, this.data);
  4400. }
  4401. this.container.appendChild(image);
  4402. return this.container;
  4403. }
  4404. });
  4405. return TextAnnotationElement;
  4406. }();
  4407. /**
  4408. * @class
  4409. * @alias WidgetAnnotationElement
  4410. */
  4411. var WidgetAnnotationElement = function WidgetAnnotationElementClosure() {
  4412. function WidgetAnnotationElement(parameters, isRenderable) {
  4413. AnnotationElement.call(this, parameters, isRenderable);
  4414. }
  4415. Util.inherit(WidgetAnnotationElement, AnnotationElement, {
  4416. /**
  4417. * Render the widget annotation's HTML element in the empty container.
  4418. *
  4419. * @public
  4420. * @memberof WidgetAnnotationElement
  4421. * @returns {HTMLSectionElement}
  4422. */
  4423. render: function WidgetAnnotationElement_render() {
  4424. // Show only the container for unsupported field types.
  4425. return this.container;
  4426. }
  4427. });
  4428. return WidgetAnnotationElement;
  4429. }();
  4430. /**
  4431. * @class
  4432. * @alias TextWidgetAnnotationElement
  4433. */
  4434. var TextWidgetAnnotationElement = function TextWidgetAnnotationElementClosure() {
  4435. var TEXT_ALIGNMENT = [
  4436. 'left',
  4437. 'center',
  4438. 'right'
  4439. ];
  4440. function TextWidgetAnnotationElement(parameters) {
  4441. var isRenderable = parameters.renderInteractiveForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
  4442. WidgetAnnotationElement.call(this, parameters, isRenderable);
  4443. }
  4444. Util.inherit(TextWidgetAnnotationElement, WidgetAnnotationElement, {
  4445. /**
  4446. * Render the text widget annotation's HTML element in the empty container.
  4447. *
  4448. * @public
  4449. * @memberof TextWidgetAnnotationElement
  4450. * @returns {HTMLSectionElement}
  4451. */
  4452. render: function TextWidgetAnnotationElement_render() {
  4453. this.container.className = 'textWidgetAnnotation';
  4454. var element = null;
  4455. if (this.renderInteractiveForms) {
  4456. // NOTE: We cannot set the values using `element.value` below, since it
  4457. // prevents the AnnotationLayer rasterizer in `test/driver.js`
  4458. // from parsing the elements correctly for the reference tests.
  4459. if (this.data.multiLine) {
  4460. element = document.createElement('textarea');
  4461. element.textContent = this.data.fieldValue;
  4462. } else {
  4463. element = document.createElement('input');
  4464. element.type = 'text';
  4465. element.setAttribute('value', this.data.fieldValue);
  4466. }
  4467. element.disabled = this.data.readOnly;
  4468. if (this.data.maxLen !== null) {
  4469. element.maxLength = this.data.maxLen;
  4470. }
  4471. if (this.data.comb) {
  4472. var fieldWidth = this.data.rect[2] - this.data.rect[0];
  4473. var combWidth = fieldWidth / this.data.maxLen;
  4474. element.classList.add('comb');
  4475. element.style.letterSpacing = 'calc(' + combWidth + 'px - 1ch)';
  4476. }
  4477. } else {
  4478. element = document.createElement('div');
  4479. element.textContent = this.data.fieldValue;
  4480. element.style.verticalAlign = 'middle';
  4481. element.style.display = 'table-cell';
  4482. var font = null;
  4483. if (this.data.fontRefName) {
  4484. font = this.page.commonObjs.getData(this.data.fontRefName);
  4485. }
  4486. this._setTextStyle(element, font);
  4487. }
  4488. if (this.data.textAlignment !== null) {
  4489. element.style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
  4490. }
  4491. this.container.appendChild(element);
  4492. return this.container;
  4493. },
  4494. /**
  4495. * Apply text styles to the text in the element.
  4496. *
  4497. * @private
  4498. * @param {HTMLDivElement} element
  4499. * @param {Object} font
  4500. * @memberof TextWidgetAnnotationElement
  4501. */
  4502. _setTextStyle: function TextWidgetAnnotationElement_setTextStyle(element, font) {
  4503. // TODO: This duplicates some of the logic in CanvasGraphics.setFont().
  4504. var style = element.style;
  4505. style.fontSize = this.data.fontSize + 'px';
  4506. style.direction = this.data.fontDirection < 0 ? 'rtl' : 'ltr';
  4507. if (!font) {
  4508. return;
  4509. }
  4510. style.fontWeight = font.black ? font.bold ? '900' : 'bold' : font.bold ? 'bold' : 'normal';
  4511. style.fontStyle = font.italic ? 'italic' : 'normal';
  4512. // Use a reasonable default font if the font doesn't specify a fallback.
  4513. var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : '';
  4514. var fallbackName = font.fallbackName || 'Helvetica, sans-serif';
  4515. style.fontFamily = fontFamily + fallbackName;
  4516. }
  4517. });
  4518. return TextWidgetAnnotationElement;
  4519. }();
  4520. /**
  4521. * @class
  4522. * @alias ChoiceWidgetAnnotationElement
  4523. */
  4524. var ChoiceWidgetAnnotationElement = function ChoiceWidgetAnnotationElementClosure() {
  4525. function ChoiceWidgetAnnotationElement(parameters) {
  4526. WidgetAnnotationElement.call(this, parameters, parameters.renderInteractiveForms);
  4527. }
  4528. Util.inherit(ChoiceWidgetAnnotationElement, WidgetAnnotationElement, {
  4529. /**
  4530. * Render the choice widget annotation's HTML element in the empty
  4531. * container.
  4532. *
  4533. * @public
  4534. * @memberof ChoiceWidgetAnnotationElement
  4535. * @returns {HTMLSectionElement}
  4536. */
  4537. render: function ChoiceWidgetAnnotationElement_render() {
  4538. this.container.className = 'choiceWidgetAnnotation';
  4539. var selectElement = document.createElement('select');
  4540. selectElement.disabled = this.data.readOnly;
  4541. if (!this.data.combo) {
  4542. // List boxes have a size and (optionally) multiple selection.
  4543. selectElement.size = this.data.options.length;
  4544. if (this.data.multiSelect) {
  4545. selectElement.multiple = true;
  4546. }
  4547. }
  4548. // Insert the options into the choice field.
  4549. for (var i = 0, ii = this.data.options.length; i < ii; i++) {
  4550. var option = this.data.options[i];
  4551. var optionElement = document.createElement('option');
  4552. optionElement.textContent = option.displayValue;
  4553. optionElement.value = option.exportValue;
  4554. if (this.data.fieldValue.indexOf(option.displayValue) >= 0) {
  4555. optionElement.setAttribute('selected', true);
  4556. }
  4557. selectElement.appendChild(optionElement);
  4558. }
  4559. this.container.appendChild(selectElement);
  4560. return this.container;
  4561. }
  4562. });
  4563. return ChoiceWidgetAnnotationElement;
  4564. }();
  4565. /**
  4566. * @class
  4567. * @alias PopupAnnotationElement
  4568. */
  4569. var PopupAnnotationElement = function PopupAnnotationElementClosure() {
  4570. function PopupAnnotationElement(parameters) {
  4571. var isRenderable = !!(parameters.data.title || parameters.data.contents);
  4572. AnnotationElement.call(this, parameters, isRenderable);
  4573. }
  4574. Util.inherit(PopupAnnotationElement, AnnotationElement, {
  4575. /**
  4576. * Render the popup annotation's HTML element in the empty container.
  4577. *
  4578. * @public
  4579. * @memberof PopupAnnotationElement
  4580. * @returns {HTMLSectionElement}
  4581. */
  4582. render: function PopupAnnotationElement_render() {
  4583. this.container.className = 'popupAnnotation';
  4584. var selector = '[data-annotation-id="' + this.data.parentId + '"]';
  4585. var parentElement = this.layer.querySelector(selector);
  4586. if (!parentElement) {
  4587. return this.container;
  4588. }
  4589. var popup = new PopupElement({
  4590. container: this.container,
  4591. trigger: parentElement,
  4592. color: this.data.color,
  4593. title: this.data.title,
  4594. contents: this.data.contents
  4595. });
  4596. // Position the popup next to the parent annotation's container.
  4597. // PDF viewers ignore a popup annotation's rectangle.
  4598. var parentLeft = parseFloat(parentElement.style.left);
  4599. var parentWidth = parseFloat(parentElement.style.width);
  4600. CustomStyle.setProp('transformOrigin', this.container, -(parentLeft + parentWidth) + 'px -' + parentElement.style.top);
  4601. this.container.style.left = parentLeft + parentWidth + 'px';
  4602. this.container.appendChild(popup.render());
  4603. return this.container;
  4604. }
  4605. });
  4606. return PopupAnnotationElement;
  4607. }();
  4608. /**
  4609. * @class
  4610. * @alias PopupElement
  4611. */
  4612. var PopupElement = function PopupElementClosure() {
  4613. var BACKGROUND_ENLIGHT = 0.7;
  4614. function PopupElement(parameters) {
  4615. this.container = parameters.container;
  4616. this.trigger = parameters.trigger;
  4617. this.color = parameters.color;
  4618. this.title = parameters.title;
  4619. this.contents = parameters.contents;
  4620. this.hideWrapper = parameters.hideWrapper || false;
  4621. this.pinned = false;
  4622. }
  4623. PopupElement.prototype = /** @lends PopupElement.prototype */
  4624. {
  4625. /**
  4626. * Render the popup's HTML element.
  4627. *
  4628. * @public
  4629. * @memberof PopupElement
  4630. * @returns {HTMLSectionElement}
  4631. */
  4632. render: function PopupElement_render() {
  4633. var wrapper = document.createElement('div');
  4634. wrapper.className = 'popupWrapper';
  4635. // For Popup annotations we hide the entire section because it contains
  4636. // only the popup. However, for Text annotations without a separate Popup
  4637. // annotation, we cannot hide the entire container as the image would
  4638. // disappear too. In that special case, hiding the wrapper suffices.
  4639. this.hideElement = this.hideWrapper ? wrapper : this.container;
  4640. this.hideElement.setAttribute('hidden', true);
  4641. var popup = document.createElement('div');
  4642. popup.className = 'popup';
  4643. var color = this.color;
  4644. if (color) {
  4645. // Enlighten the color.
  4646. var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
  4647. var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
  4648. var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
  4649. popup.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0);
  4650. }
  4651. var contents = this._formatContents(this.contents);
  4652. var title = document.createElement('h1');
  4653. title.textContent = this.title;
  4654. // Attach the event listeners to the trigger element.
  4655. this.trigger.addEventListener('click', this._toggle.bind(this));
  4656. this.trigger.addEventListener('mouseover', this._show.bind(this, false));
  4657. this.trigger.addEventListener('mouseout', this._hide.bind(this, false));
  4658. popup.addEventListener('click', this._hide.bind(this, true));
  4659. popup.appendChild(title);
  4660. popup.appendChild(contents);
  4661. wrapper.appendChild(popup);
  4662. return wrapper;
  4663. },
  4664. /**
  4665. * Format the contents of the popup by adding newlines where necessary.
  4666. *
  4667. * @private
  4668. * @param {string} contents
  4669. * @memberof PopupElement
  4670. * @returns {HTMLParagraphElement}
  4671. */
  4672. _formatContents: function PopupElement_formatContents(contents) {
  4673. var p = document.createElement('p');
  4674. var lines = contents.split(/(?:\r\n?|\n)/);
  4675. for (var i = 0, ii = lines.length; i < ii; ++i) {
  4676. var line = lines[i];
  4677. p.appendChild(document.createTextNode(line));
  4678. if (i < ii - 1) {
  4679. p.appendChild(document.createElement('br'));
  4680. }
  4681. }
  4682. return p;
  4683. },
  4684. /**
  4685. * Toggle the visibility of the popup.
  4686. *
  4687. * @private
  4688. * @memberof PopupElement
  4689. */
  4690. _toggle: function PopupElement_toggle() {
  4691. if (this.pinned) {
  4692. this._hide(true);
  4693. } else {
  4694. this._show(true);
  4695. }
  4696. },
  4697. /**
  4698. * Show the popup.
  4699. *
  4700. * @private
  4701. * @param {boolean} pin
  4702. * @memberof PopupElement
  4703. */
  4704. _show: function PopupElement_show(pin) {
  4705. if (pin) {
  4706. this.pinned = true;
  4707. }
  4708. if (this.hideElement.hasAttribute('hidden')) {
  4709. this.hideElement.removeAttribute('hidden');
  4710. this.container.style.zIndex += 1;
  4711. }
  4712. },
  4713. /**
  4714. * Hide the popup.
  4715. *
  4716. * @private
  4717. * @param {boolean} unpin
  4718. * @memberof PopupElement
  4719. */
  4720. _hide: function PopupElement_hide(unpin) {
  4721. if (unpin) {
  4722. this.pinned = false;
  4723. }
  4724. if (!this.hideElement.hasAttribute('hidden') && !this.pinned) {
  4725. this.hideElement.setAttribute('hidden', true);
  4726. this.container.style.zIndex -= 1;
  4727. }
  4728. }
  4729. };
  4730. return PopupElement;
  4731. }();
  4732. /**
  4733. * @class
  4734. * @alias HighlightAnnotationElement
  4735. */
  4736. var HighlightAnnotationElement = function HighlightAnnotationElementClosure() {
  4737. function HighlightAnnotationElement(parameters) {
  4738. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4739. AnnotationElement.call(this, parameters, isRenderable);
  4740. }
  4741. Util.inherit(HighlightAnnotationElement, AnnotationElement, {
  4742. /**
  4743. * Render the highlight annotation's HTML element in the empty container.
  4744. *
  4745. * @public
  4746. * @memberof HighlightAnnotationElement
  4747. * @returns {HTMLSectionElement}
  4748. */
  4749. render: function HighlightAnnotationElement_render() {
  4750. this.container.className = 'highlightAnnotation';
  4751. if (!this.data.hasPopup) {
  4752. this._createPopup(this.container, null, this.data);
  4753. }
  4754. return this.container;
  4755. }
  4756. });
  4757. return HighlightAnnotationElement;
  4758. }();
  4759. /**
  4760. * @class
  4761. * @alias UnderlineAnnotationElement
  4762. */
  4763. var UnderlineAnnotationElement = function UnderlineAnnotationElementClosure() {
  4764. function UnderlineAnnotationElement(parameters) {
  4765. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4766. AnnotationElement.call(this, parameters, isRenderable);
  4767. }
  4768. Util.inherit(UnderlineAnnotationElement, AnnotationElement, {
  4769. /**
  4770. * Render the underline annotation's HTML element in the empty container.
  4771. *
  4772. * @public
  4773. * @memberof UnderlineAnnotationElement
  4774. * @returns {HTMLSectionElement}
  4775. */
  4776. render: function UnderlineAnnotationElement_render() {
  4777. this.container.className = 'underlineAnnotation';
  4778. if (!this.data.hasPopup) {
  4779. this._createPopup(this.container, null, this.data);
  4780. }
  4781. return this.container;
  4782. }
  4783. });
  4784. return UnderlineAnnotationElement;
  4785. }();
  4786. /**
  4787. * @class
  4788. * @alias SquigglyAnnotationElement
  4789. */
  4790. var SquigglyAnnotationElement = function SquigglyAnnotationElementClosure() {
  4791. function SquigglyAnnotationElement(parameters) {
  4792. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4793. AnnotationElement.call(this, parameters, isRenderable);
  4794. }
  4795. Util.inherit(SquigglyAnnotationElement, AnnotationElement, {
  4796. /**
  4797. * Render the squiggly annotation's HTML element in the empty container.
  4798. *
  4799. * @public
  4800. * @memberof SquigglyAnnotationElement
  4801. * @returns {HTMLSectionElement}
  4802. */
  4803. render: function SquigglyAnnotationElement_render() {
  4804. this.container.className = 'squigglyAnnotation';
  4805. if (!this.data.hasPopup) {
  4806. this._createPopup(this.container, null, this.data);
  4807. }
  4808. return this.container;
  4809. }
  4810. });
  4811. return SquigglyAnnotationElement;
  4812. }();
  4813. /**
  4814. * @class
  4815. * @alias StrikeOutAnnotationElement
  4816. */
  4817. var StrikeOutAnnotationElement = function StrikeOutAnnotationElementClosure() {
  4818. function StrikeOutAnnotationElement(parameters) {
  4819. var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
  4820. AnnotationElement.call(this, parameters, isRenderable);
  4821. }
  4822. Util.inherit(StrikeOutAnnotationElement, AnnotationElement, {
  4823. /**
  4824. * Render the strikeout annotation's HTML element in the empty container.
  4825. *
  4826. * @public
  4827. * @memberof StrikeOutAnnotationElement
  4828. * @returns {HTMLSectionElement}
  4829. */
  4830. render: function StrikeOutAnnotationElement_render() {
  4831. this.container.className = 'strikeoutAnnotation';
  4832. if (!this.data.hasPopup) {
  4833. this._createPopup(this.container, null, this.data);
  4834. }
  4835. return this.container;
  4836. }
  4837. });
  4838. return StrikeOutAnnotationElement;
  4839. }();
  4840. /**
  4841. * @class
  4842. * @alias FileAttachmentAnnotationElement
  4843. */
  4844. var FileAttachmentAnnotationElement = function FileAttachmentAnnotationElementClosure() {
  4845. function FileAttachmentAnnotationElement(parameters) {
  4846. AnnotationElement.call(this, parameters, true);
  4847. this.filename = getFilenameFromUrl(parameters.data.file.filename);
  4848. this.content = parameters.data.file.content;
  4849. }
  4850. Util.inherit(FileAttachmentAnnotationElement, AnnotationElement, {
  4851. /**
  4852. * Render the file attachment annotation's HTML element in the empty
  4853. * container.
  4854. *
  4855. * @public
  4856. * @memberof FileAttachmentAnnotationElement
  4857. * @returns {HTMLSectionElement}
  4858. */
  4859. render: function FileAttachmentAnnotationElement_render() {
  4860. this.container.className = 'fileAttachmentAnnotation';
  4861. var trigger = document.createElement('div');
  4862. trigger.style.height = this.container.style.height;
  4863. trigger.style.width = this.container.style.width;
  4864. trigger.addEventListener('dblclick', this._download.bind(this));
  4865. if (!this.data.hasPopup && (this.data.title || this.data.contents)) {
  4866. this._createPopup(this.container, trigger, this.data);
  4867. }
  4868. this.container.appendChild(trigger);
  4869. return this.container;
  4870. },
  4871. /**
  4872. * Download the file attachment associated with this annotation.
  4873. *
  4874. * @private
  4875. * @memberof FileAttachmentAnnotationElement
  4876. */
  4877. _download: function FileAttachmentAnnotationElement_download() {
  4878. if (!this.downloadManager) {
  4879. warn('Download cannot be started due to unavailable download manager');
  4880. return;
  4881. }
  4882. this.downloadManager.downloadData(this.content, this.filename, '');
  4883. }
  4884. });
  4885. return FileAttachmentAnnotationElement;
  4886. }();
  4887. /**
  4888. * @typedef {Object} AnnotationLayerParameters
  4889. * @property {PageViewport} viewport
  4890. * @property {HTMLDivElement} div
  4891. * @property {Array} annotations
  4892. * @property {PDFPage} page
  4893. * @property {IPDFLinkService} linkService
  4894. * @property {string} imageResourcesPath
  4895. * @property {boolean} renderInteractiveForms
  4896. */
  4897. /**
  4898. * @class
  4899. * @alias AnnotationLayer
  4900. */
  4901. var AnnotationLayer = function AnnotationLayerClosure() {
  4902. return {
  4903. /**
  4904. * Render a new annotation layer with all annotation elements.
  4905. *
  4906. * @public
  4907. * @param {AnnotationLayerParameters} parameters
  4908. * @memberof AnnotationLayer
  4909. */
  4910. render: function AnnotationLayer_render(parameters) {
  4911. var annotationElementFactory = new AnnotationElementFactory();
  4912. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4913. var data = parameters.annotations[i];
  4914. if (!data) {
  4915. continue;
  4916. }
  4917. var properties = {
  4918. data: data,
  4919. layer: parameters.div,
  4920. page: parameters.page,
  4921. viewport: parameters.viewport,
  4922. linkService: parameters.linkService,
  4923. downloadManager: parameters.downloadManager,
  4924. imageResourcesPath: parameters.imageResourcesPath || getDefaultSetting('imageResourcesPath'),
  4925. renderInteractiveForms: parameters.renderInteractiveForms || false
  4926. };
  4927. var element = annotationElementFactory.create(properties);
  4928. if (element.isRenderable) {
  4929. parameters.div.appendChild(element.render());
  4930. }
  4931. }
  4932. },
  4933. /**
  4934. * Update the annotation elements on existing annotation layer.
  4935. *
  4936. * @public
  4937. * @param {AnnotationLayerParameters} parameters
  4938. * @memberof AnnotationLayer
  4939. */
  4940. update: function AnnotationLayer_update(parameters) {
  4941. for (var i = 0, ii = parameters.annotations.length; i < ii; i++) {
  4942. var data = parameters.annotations[i];
  4943. var element = parameters.div.querySelector('[data-annotation-id="' + data.id + '"]');
  4944. if (element) {
  4945. CustomStyle.setProp('transform', element, 'matrix(' + parameters.viewport.transform.join(',') + ')');
  4946. }
  4947. }
  4948. parameters.div.removeAttribute('hidden');
  4949. }
  4950. };
  4951. }();
  4952. exports.AnnotationLayer = AnnotationLayer;
  4953. }));
  4954. (function (root, factory) {
  4955. factory(root.pdfjsDisplayTextLayer = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils);
  4956. }(this, function (exports, sharedUtil, displayDOMUtils) {
  4957. var Util = sharedUtil.Util;
  4958. var createPromiseCapability = sharedUtil.createPromiseCapability;
  4959. var CustomStyle = displayDOMUtils.CustomStyle;
  4960. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  4961. /**
  4962. * Text layer render parameters.
  4963. *
  4964. * @typedef {Object} TextLayerRenderParameters
  4965. * @property {TextContent} textContent - Text content to render (the object is
  4966. * returned by the page's getTextContent() method).
  4967. * @property {HTMLElement} container - HTML element that will contain text runs.
  4968. * @property {PageViewport} viewport - The target viewport to properly
  4969. * layout the text runs.
  4970. * @property {Array} textDivs - (optional) HTML elements that are correspond
  4971. * the text items of the textContent input. This is output and shall be
  4972. * initially be set to empty array.
  4973. * @property {number} timeout - (optional) Delay in milliseconds before
  4974. * rendering of the text runs occurs.
  4975. * @property {boolean} enhanceTextSelection - (optional) Whether to turn on the
  4976. * text selection enhancement.
  4977. */
  4978. var renderTextLayer = function renderTextLayerClosure() {
  4979. var MAX_TEXT_DIVS_TO_RENDER = 100000;
  4980. var NonWhitespaceRegexp = /\S/;
  4981. function isAllWhitespace(str) {
  4982. return !NonWhitespaceRegexp.test(str);
  4983. }
  4984. // Text layers may contain many thousand div's, and using `styleBuf` avoids
  4985. // creating many intermediate strings when building their 'style' properties.
  4986. var styleBuf = [
  4987. 'left: ',
  4988. 0,
  4989. 'px; top: ',
  4990. 0,
  4991. 'px; font-size: ',
  4992. 0,
  4993. 'px; font-family: ',
  4994. '',
  4995. ';'
  4996. ];
  4997. function appendText(task, geom, styles) {
  4998. // Initialize all used properties to keep the caches monomorphic.
  4999. var textDiv = document.createElement('div');
  5000. var textDivProperties = {
  5001. style: null,
  5002. angle: 0,
  5003. canvasWidth: 0,
  5004. isWhitespace: false,
  5005. originalTransform: null,
  5006. paddingBottom: 0,
  5007. paddingLeft: 0,
  5008. paddingRight: 0,
  5009. paddingTop: 0,
  5010. scale: 1
  5011. };
  5012. task._textDivs.push(textDiv);
  5013. if (isAllWhitespace(geom.str)) {
  5014. textDivProperties.isWhitespace = true;
  5015. task._textDivProperties.set(textDiv, textDivProperties);
  5016. return;
  5017. }
  5018. var tx = Util.transform(task._viewport.transform, geom.transform);
  5019. var angle = Math.atan2(tx[1], tx[0]);
  5020. var style = styles[geom.fontName];
  5021. if (style.vertical) {
  5022. angle += Math.PI / 2;
  5023. }
  5024. var fontHeight = Math.sqrt(tx[2] * tx[2] + tx[3] * tx[3]);
  5025. var fontAscent = fontHeight;
  5026. if (style.ascent) {
  5027. fontAscent = style.ascent * fontAscent;
  5028. } else if (style.descent) {
  5029. fontAscent = (1 + style.descent) * fontAscent;
  5030. }
  5031. var left;
  5032. var top;
  5033. if (angle === 0) {
  5034. left = tx[4];
  5035. top = tx[5] - fontAscent;
  5036. } else {
  5037. left = tx[4] + fontAscent * Math.sin(angle);
  5038. top = tx[5] - fontAscent * Math.cos(angle);
  5039. }
  5040. styleBuf[1] = left;
  5041. styleBuf[3] = top;
  5042. styleBuf[5] = fontHeight;
  5043. styleBuf[7] = style.fontFamily;
  5044. textDivProperties.style = styleBuf.join('');
  5045. textDiv.setAttribute('style', textDivProperties.style);
  5046. textDiv.textContent = geom.str;
  5047. // |fontName| is only used by the Font Inspector. This test will succeed
  5048. // when e.g. the Font Inspector is off but the Stepper is on, but it's
  5049. // not worth the effort to do a more accurate test. We only use `dataset`
  5050. // here to make the font name available for the debugger.
  5051. if (getDefaultSetting('pdfBug')) {
  5052. textDiv.dataset.fontName = geom.fontName;
  5053. }
  5054. if (angle !== 0) {
  5055. textDivProperties.angle = angle * (180 / Math.PI);
  5056. }
  5057. // We don't bother scaling single-char text divs, because it has very
  5058. // little effect on text highlighting. This makes scrolling on docs with
  5059. // lots of such divs a lot faster.
  5060. if (geom.str.length > 1) {
  5061. if (style.vertical) {
  5062. textDivProperties.canvasWidth = geom.height * task._viewport.scale;
  5063. } else {
  5064. textDivProperties.canvasWidth = geom.width * task._viewport.scale;
  5065. }
  5066. }
  5067. task._textDivProperties.set(textDiv, textDivProperties);
  5068. if (task._enhanceTextSelection) {
  5069. var angleCos = 1, angleSin = 0;
  5070. if (angle !== 0) {
  5071. angleCos = Math.cos(angle);
  5072. angleSin = Math.sin(angle);
  5073. }
  5074. var divWidth = (style.vertical ? geom.height : geom.width) * task._viewport.scale;
  5075. var divHeight = fontHeight;
  5076. var m, b;
  5077. if (angle !== 0) {
  5078. m = [
  5079. angleCos,
  5080. angleSin,
  5081. -angleSin,
  5082. angleCos,
  5083. left,
  5084. top
  5085. ];
  5086. b = Util.getAxialAlignedBoundingBox([
  5087. 0,
  5088. 0,
  5089. divWidth,
  5090. divHeight
  5091. ], m);
  5092. } else {
  5093. b = [
  5094. left,
  5095. top,
  5096. left + divWidth,
  5097. top + divHeight
  5098. ];
  5099. }
  5100. task._bounds.push({
  5101. left: b[0],
  5102. top: b[1],
  5103. right: b[2],
  5104. bottom: b[3],
  5105. div: textDiv,
  5106. size: [
  5107. divWidth,
  5108. divHeight
  5109. ],
  5110. m: m
  5111. });
  5112. }
  5113. }
  5114. function render(task) {
  5115. if (task._canceled) {
  5116. return;
  5117. }
  5118. var textLayerFrag = task._container;
  5119. var textDivs = task._textDivs;
  5120. var capability = task._capability;
  5121. var textDivsLength = textDivs.length;
  5122. // No point in rendering many divs as it would make the browser
  5123. // unusable even after the divs are rendered.
  5124. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
  5125. task._renderingDone = true;
  5126. capability.resolve();
  5127. return;
  5128. }
  5129. var canvas = document.createElement('canvas');
  5130. canvas.mozOpaque = true;
  5131. var ctx = canvas.getContext('2d', { alpha: false });
  5132. var lastFontSize;
  5133. var lastFontFamily;
  5134. for (var i = 0; i < textDivsLength; i++) {
  5135. var textDiv = textDivs[i];
  5136. var textDivProperties = task._textDivProperties.get(textDiv);
  5137. if (textDivProperties.isWhitespace) {
  5138. continue;
  5139. }
  5140. var fontSize = textDiv.style.fontSize;
  5141. var fontFamily = textDiv.style.fontFamily;
  5142. // Only build font string and set to context if different from last.
  5143. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) {
  5144. ctx.font = fontSize + ' ' + fontFamily;
  5145. lastFontSize = fontSize;
  5146. lastFontFamily = fontFamily;
  5147. }
  5148. var width = ctx.measureText(textDiv.textContent).width;
  5149. textLayerFrag.appendChild(textDiv);
  5150. var transform = '';
  5151. if (textDivProperties.canvasWidth !== 0 && width > 0) {
  5152. textDivProperties.scale = textDivProperties.canvasWidth / width;
  5153. transform = 'scaleX(' + textDivProperties.scale + ')';
  5154. }
  5155. if (textDivProperties.angle !== 0) {
  5156. transform = 'rotate(' + textDivProperties.angle + 'deg) ' + transform;
  5157. }
  5158. if (transform !== '') {
  5159. textDivProperties.originalTransform = transform;
  5160. CustomStyle.setProp('transform', textDiv, transform);
  5161. }
  5162. task._textDivProperties.set(textDiv, textDivProperties);
  5163. }
  5164. task._renderingDone = true;
  5165. capability.resolve();
  5166. }
  5167. function expand(task) {
  5168. var bounds = task._bounds;
  5169. var viewport = task._viewport;
  5170. var expanded = expandBounds(viewport.width, viewport.height, bounds);
  5171. for (var i = 0; i < expanded.length; i++) {
  5172. var div = bounds[i].div;
  5173. var divProperties = task._textDivProperties.get(div);
  5174. if (divProperties.angle === 0) {
  5175. divProperties.paddingLeft = bounds[i].left - expanded[i].left;
  5176. divProperties.paddingTop = bounds[i].top - expanded[i].top;
  5177. divProperties.paddingRight = expanded[i].right - bounds[i].right;
  5178. divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom;
  5179. task._textDivProperties.set(div, divProperties);
  5180. continue;
  5181. }
  5182. // Box is rotated -- trying to find padding so rotated div will not
  5183. // exceed its expanded bounds.
  5184. var e = expanded[i], b = bounds[i];
  5185. var m = b.m, c = m[0], s = m[1];
  5186. // Finding intersections with expanded box.
  5187. var points = [
  5188. [
  5189. 0,
  5190. 0
  5191. ],
  5192. [
  5193. 0,
  5194. b.size[1]
  5195. ],
  5196. [
  5197. b.size[0],
  5198. 0
  5199. ],
  5200. b.size
  5201. ];
  5202. var ts = new Float64Array(64);
  5203. points.forEach(function (p, i) {
  5204. var t = Util.applyTransform(p, m);
  5205. ts[i + 0] = c && (e.left - t[0]) / c;
  5206. ts[i + 4] = s && (e.top - t[1]) / s;
  5207. ts[i + 8] = c && (e.right - t[0]) / c;
  5208. ts[i + 12] = s && (e.bottom - t[1]) / s;
  5209. ts[i + 16] = s && (e.left - t[0]) / -s;
  5210. ts[i + 20] = c && (e.top - t[1]) / c;
  5211. ts[i + 24] = s && (e.right - t[0]) / -s;
  5212. ts[i + 28] = c && (e.bottom - t[1]) / c;
  5213. ts[i + 32] = c && (e.left - t[0]) / -c;
  5214. ts[i + 36] = s && (e.top - t[1]) / -s;
  5215. ts[i + 40] = c && (e.right - t[0]) / -c;
  5216. ts[i + 44] = s && (e.bottom - t[1]) / -s;
  5217. ts[i + 48] = s && (e.left - t[0]) / s;
  5218. ts[i + 52] = c && (e.top - t[1]) / -c;
  5219. ts[i + 56] = s && (e.right - t[0]) / s;
  5220. ts[i + 60] = c && (e.bottom - t[1]) / -c;
  5221. });
  5222. var findPositiveMin = function (ts, offset, count) {
  5223. var result = 0;
  5224. for (var i = 0; i < count; i++) {
  5225. var t = ts[offset++];
  5226. if (t > 0) {
  5227. result = result ? Math.min(t, result) : t;
  5228. }
  5229. }
  5230. return result;
  5231. };
  5232. // Not based on math, but to simplify calculations, using cos and sin
  5233. // absolute values to not exceed the box (it can but insignificantly).
  5234. var boxScale = 1 + Math.min(Math.abs(c), Math.abs(s));
  5235. divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale;
  5236. divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale;
  5237. divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale;
  5238. divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale;
  5239. task._textDivProperties.set(div, divProperties);
  5240. }
  5241. }
  5242. function expandBounds(width, height, boxes) {
  5243. var bounds = boxes.map(function (box, i) {
  5244. return {
  5245. x1: box.left,
  5246. y1: box.top,
  5247. x2: box.right,
  5248. y2: box.bottom,
  5249. index: i,
  5250. x1New: undefined,
  5251. x2New: undefined
  5252. };
  5253. });
  5254. expandBoundsLTR(width, bounds);
  5255. var expanded = new Array(boxes.length);
  5256. bounds.forEach(function (b) {
  5257. var i = b.index;
  5258. expanded[i] = {
  5259. left: b.x1New,
  5260. top: 0,
  5261. right: b.x2New,
  5262. bottom: 0
  5263. };
  5264. });
  5265. // Rotating on 90 degrees and extending extended boxes. Reusing the bounds
  5266. // array and objects.
  5267. boxes.map(function (box, i) {
  5268. var e = expanded[i], b = bounds[i];
  5269. b.x1 = box.top;
  5270. b.y1 = width - e.right;
  5271. b.x2 = box.bottom;
  5272. b.y2 = width - e.left;
  5273. b.index = i;
  5274. b.x1New = undefined;
  5275. b.x2New = undefined;
  5276. });
  5277. expandBoundsLTR(height, bounds);
  5278. bounds.forEach(function (b) {
  5279. var i = b.index;
  5280. expanded[i].top = b.x1New;
  5281. expanded[i].bottom = b.x2New;
  5282. });
  5283. return expanded;
  5284. }
  5285. function expandBoundsLTR(width, bounds) {
  5286. // Sorting by x1 coordinate and walk by the bounds in the same order.
  5287. bounds.sort(function (a, b) {
  5288. return a.x1 - b.x1 || a.index - b.index;
  5289. });
  5290. // First we see on the horizon is a fake boundary.
  5291. var fakeBoundary = {
  5292. x1: -Infinity,
  5293. y1: -Infinity,
  5294. x2: 0,
  5295. y2: Infinity,
  5296. index: -1,
  5297. x1New: 0,
  5298. x2New: 0
  5299. };
  5300. var horizon = [{
  5301. start: -Infinity,
  5302. end: Infinity,
  5303. boundary: fakeBoundary
  5304. }];
  5305. bounds.forEach(function (boundary) {
  5306. // Searching for the affected part of horizon.
  5307. // TODO red-black tree or simple binary search
  5308. var i = 0;
  5309. while (i < horizon.length && horizon[i].end <= boundary.y1) {
  5310. i++;
  5311. }
  5312. var j = horizon.length - 1;
  5313. while (j >= 0 && horizon[j].start >= boundary.y2) {
  5314. j--;
  5315. }
  5316. var horizonPart, affectedBoundary;
  5317. var q, k, maxXNew = -Infinity;
  5318. for (q = i; q <= j; q++) {
  5319. horizonPart = horizon[q];
  5320. affectedBoundary = horizonPart.boundary;
  5321. var xNew;
  5322. if (affectedBoundary.x2 > boundary.x1) {
  5323. // In the middle of the previous element, new x shall be at the
  5324. // boundary start. Extending if further if the affected bondary
  5325. // placed on top of the current one.
  5326. xNew = affectedBoundary.index > boundary.index ? affectedBoundary.x1New : boundary.x1;
  5327. } else if (affectedBoundary.x2New === undefined) {
  5328. // We have some space in between, new x in middle will be a fair
  5329. // choice.
  5330. xNew = (affectedBoundary.x2 + boundary.x1) / 2;
  5331. } else {
  5332. // Affected boundary has x2new set, using it as new x.
  5333. xNew = affectedBoundary.x2New;
  5334. }
  5335. if (xNew > maxXNew) {
  5336. maxXNew = xNew;
  5337. }
  5338. }
  5339. // Set new x1 for current boundary.
  5340. boundary.x1New = maxXNew;
  5341. // Adjusts new x2 for the affected boundaries.
  5342. for (q = i; q <= j; q++) {
  5343. horizonPart = horizon[q];
  5344. affectedBoundary = horizonPart.boundary;
  5345. if (affectedBoundary.x2New === undefined) {
  5346. // Was not set yet, choosing new x if possible.
  5347. if (affectedBoundary.x2 > boundary.x1) {
  5348. // Current and affected boundaries intersect. If affected boundary
  5349. // is placed on top of the current, shrinking the affected.
  5350. if (affectedBoundary.index > boundary.index) {
  5351. affectedBoundary.x2New = affectedBoundary.x2;
  5352. }
  5353. } else {
  5354. affectedBoundary.x2New = maxXNew;
  5355. }
  5356. } else if (affectedBoundary.x2New > maxXNew) {
  5357. // Affected boundary is touching new x, pushing it back.
  5358. affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2);
  5359. }
  5360. }
  5361. // Fixing the horizon.
  5362. var changedHorizon = [], lastBoundary = null;
  5363. for (q = i; q <= j; q++) {
  5364. horizonPart = horizon[q];
  5365. affectedBoundary = horizonPart.boundary;
  5366. // Checking which boundary will be visible.
  5367. var useBoundary = affectedBoundary.x2 > boundary.x2 ? affectedBoundary : boundary;
  5368. if (lastBoundary === useBoundary) {
  5369. // Merging with previous.
  5370. changedHorizon[changedHorizon.length - 1].end = horizonPart.end;
  5371. } else {
  5372. changedHorizon.push({
  5373. start: horizonPart.start,
  5374. end: horizonPart.end,
  5375. boundary: useBoundary
  5376. });
  5377. lastBoundary = useBoundary;
  5378. }
  5379. }
  5380. if (horizon[i].start < boundary.y1) {
  5381. changedHorizon[0].start = boundary.y1;
  5382. changedHorizon.unshift({
  5383. start: horizon[i].start,
  5384. end: boundary.y1,
  5385. boundary: horizon[i].boundary
  5386. });
  5387. }
  5388. if (boundary.y2 < horizon[j].end) {
  5389. changedHorizon[changedHorizon.length - 1].end = boundary.y2;
  5390. changedHorizon.push({
  5391. start: boundary.y2,
  5392. end: horizon[j].end,
  5393. boundary: horizon[j].boundary
  5394. });
  5395. }
  5396. // Set x2 new of boundary that is no longer visible (see overlapping case
  5397. // above).
  5398. // TODO more efficient, e.g. via reference counting.
  5399. for (q = i; q <= j; q++) {
  5400. horizonPart = horizon[q];
  5401. affectedBoundary = horizonPart.boundary;
  5402. if (affectedBoundary.x2New !== undefined) {
  5403. continue;
  5404. }
  5405. var used = false;
  5406. for (k = i - 1; !used && k >= 0 && horizon[k].start >= affectedBoundary.y1; k--) {
  5407. used = horizon[k].boundary === affectedBoundary;
  5408. }
  5409. for (k = j + 1; !used && k < horizon.length && horizon[k].end <= affectedBoundary.y2; k++) {
  5410. used = horizon[k].boundary === affectedBoundary;
  5411. }
  5412. for (k = 0; !used && k < changedHorizon.length; k++) {
  5413. used = changedHorizon[k].boundary === affectedBoundary;
  5414. }
  5415. if (!used) {
  5416. affectedBoundary.x2New = maxXNew;
  5417. }
  5418. }
  5419. Array.prototype.splice.apply(horizon, [
  5420. i,
  5421. j - i + 1
  5422. ].concat(changedHorizon));
  5423. });
  5424. // Set new x2 for all unset boundaries.
  5425. horizon.forEach(function (horizonPart) {
  5426. var affectedBoundary = horizonPart.boundary;
  5427. if (affectedBoundary.x2New === undefined) {
  5428. affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);
  5429. }
  5430. });
  5431. }
  5432. /**
  5433. * Text layer rendering task.
  5434. *
  5435. * @param {TextContent} textContent
  5436. * @param {HTMLElement} container
  5437. * @param {PageViewport} viewport
  5438. * @param {Array} textDivs
  5439. * @param {boolean} enhanceTextSelection
  5440. * @private
  5441. */
  5442. function TextLayerRenderTask(textContent, container, viewport, textDivs, enhanceTextSelection) {
  5443. this._textContent = textContent;
  5444. this._container = container;
  5445. this._viewport = viewport;
  5446. this._textDivs = textDivs || [];
  5447. this._textDivProperties = new WeakMap();
  5448. this._renderingDone = false;
  5449. this._canceled = false;
  5450. this._capability = createPromiseCapability();
  5451. this._renderTimer = null;
  5452. this._bounds = [];
  5453. this._enhanceTextSelection = !!enhanceTextSelection;
  5454. }
  5455. TextLayerRenderTask.prototype = {
  5456. get promise() {
  5457. return this._capability.promise;
  5458. },
  5459. cancel: function TextLayer_cancel() {
  5460. this._canceled = true;
  5461. if (this._renderTimer !== null) {
  5462. clearTimeout(this._renderTimer);
  5463. this._renderTimer = null;
  5464. }
  5465. this._capability.reject('canceled');
  5466. },
  5467. _render: function TextLayer_render(timeout) {
  5468. var textItems = this._textContent.items;
  5469. var textStyles = this._textContent.styles;
  5470. for (var i = 0, len = textItems.length; i < len; i++) {
  5471. appendText(this, textItems[i], textStyles);
  5472. }
  5473. if (!timeout) {
  5474. // Render right away
  5475. render(this);
  5476. } else {
  5477. // Schedule
  5478. var self = this;
  5479. this._renderTimer = setTimeout(function () {
  5480. render(self);
  5481. self._renderTimer = null;
  5482. }, timeout);
  5483. }
  5484. },
  5485. expandTextDivs: function TextLayer_expandTextDivs(expandDivs) {
  5486. if (!this._enhanceTextSelection || !this._renderingDone) {
  5487. return;
  5488. }
  5489. if (this._bounds !== null) {
  5490. expand(this);
  5491. this._bounds = null;
  5492. }
  5493. for (var i = 0, ii = this._textDivs.length; i < ii; i++) {
  5494. var div = this._textDivs[i];
  5495. var divProperties = this._textDivProperties.get(div);
  5496. if (divProperties.isWhitespace) {
  5497. continue;
  5498. }
  5499. if (expandDivs) {
  5500. var transform = '', padding = '';
  5501. if (divProperties.scale !== 1) {
  5502. transform = 'scaleX(' + divProperties.scale + ')';
  5503. }
  5504. if (divProperties.angle !== 0) {
  5505. transform = 'rotate(' + divProperties.angle + 'deg) ' + transform;
  5506. }
  5507. if (divProperties.paddingLeft !== 0) {
  5508. padding += ' padding-left: ' + divProperties.paddingLeft / divProperties.scale + 'px;';
  5509. transform += ' translateX(' + -divProperties.paddingLeft / divProperties.scale + 'px)';
  5510. }
  5511. if (divProperties.paddingTop !== 0) {
  5512. padding += ' padding-top: ' + divProperties.paddingTop + 'px;';
  5513. transform += ' translateY(' + -divProperties.paddingTop + 'px)';
  5514. }
  5515. if (divProperties.paddingRight !== 0) {
  5516. padding += ' padding-right: ' + divProperties.paddingRight / divProperties.scale + 'px;';
  5517. }
  5518. if (divProperties.paddingBottom !== 0) {
  5519. padding += ' padding-bottom: ' + divProperties.paddingBottom + 'px;';
  5520. }
  5521. if (padding !== '') {
  5522. div.setAttribute('style', divProperties.style + padding);
  5523. }
  5524. if (transform !== '') {
  5525. CustomStyle.setProp('transform', div, transform);
  5526. }
  5527. } else {
  5528. div.style.padding = 0;
  5529. CustomStyle.setProp('transform', div, divProperties.originalTransform || '');
  5530. }
  5531. }
  5532. }
  5533. };
  5534. /**
  5535. * Starts rendering of the text layer.
  5536. *
  5537. * @param {TextLayerRenderParameters} renderParameters
  5538. * @returns {TextLayerRenderTask}
  5539. */
  5540. function renderTextLayer(renderParameters) {
  5541. var task = new TextLayerRenderTask(renderParameters.textContent, renderParameters.container, renderParameters.viewport, renderParameters.textDivs, renderParameters.enhanceTextSelection);
  5542. task._render(renderParameters.timeout);
  5543. return task;
  5544. }
  5545. return renderTextLayer;
  5546. }();
  5547. exports.renderTextLayer = renderTextLayer;
  5548. }));
  5549. (function (root, factory) {
  5550. factory(root.pdfjsDisplayWebGL = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils);
  5551. }(this, function (exports, sharedUtil, displayDOMUtils) {
  5552. var shadow = sharedUtil.shadow;
  5553. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  5554. var WebGLUtils = function WebGLUtilsClosure() {
  5555. function loadShader(gl, code, shaderType) {
  5556. var shader = gl.createShader(shaderType);
  5557. gl.shaderSource(shader, code);
  5558. gl.compileShader(shader);
  5559. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  5560. if (!compiled) {
  5561. var errorMsg = gl.getShaderInfoLog(shader);
  5562. throw new Error('Error during shader compilation: ' + errorMsg);
  5563. }
  5564. return shader;
  5565. }
  5566. function createVertexShader(gl, code) {
  5567. return loadShader(gl, code, gl.VERTEX_SHADER);
  5568. }
  5569. function createFragmentShader(gl, code) {
  5570. return loadShader(gl, code, gl.FRAGMENT_SHADER);
  5571. }
  5572. function createProgram(gl, shaders) {
  5573. var program = gl.createProgram();
  5574. for (var i = 0, ii = shaders.length; i < ii; ++i) {
  5575. gl.attachShader(program, shaders[i]);
  5576. }
  5577. gl.linkProgram(program);
  5578. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  5579. if (!linked) {
  5580. var errorMsg = gl.getProgramInfoLog(program);
  5581. throw new Error('Error during program linking: ' + errorMsg);
  5582. }
  5583. return program;
  5584. }
  5585. function createTexture(gl, image, textureId) {
  5586. gl.activeTexture(textureId);
  5587. var texture = gl.createTexture();
  5588. gl.bindTexture(gl.TEXTURE_2D, texture);
  5589. // Set the parameters so we can render any size image.
  5590. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5591. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5592. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  5593. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  5594. // Upload the image into the texture.
  5595. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
  5596. return texture;
  5597. }
  5598. var currentGL, currentCanvas;
  5599. function generateGL() {
  5600. if (currentGL) {
  5601. return;
  5602. }
  5603. currentCanvas = document.createElement('canvas');
  5604. currentGL = currentCanvas.getContext('webgl', { premultipliedalpha: false });
  5605. }
  5606. var smaskVertexShaderCode = '\
  5607. attribute vec2 a_position; \
  5608. attribute vec2 a_texCoord; \
  5609. \
  5610. uniform vec2 u_resolution; \
  5611. \
  5612. varying vec2 v_texCoord; \
  5613. \
  5614. void main() { \
  5615. vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \
  5616. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5617. \
  5618. v_texCoord = a_texCoord; \
  5619. } ';
  5620. var smaskFragmentShaderCode = '\
  5621. precision mediump float; \
  5622. \
  5623. uniform vec4 u_backdrop; \
  5624. uniform int u_subtype; \
  5625. uniform sampler2D u_image; \
  5626. uniform sampler2D u_mask; \
  5627. \
  5628. varying vec2 v_texCoord; \
  5629. \
  5630. void main() { \
  5631. vec4 imageColor = texture2D(u_image, v_texCoord); \
  5632. vec4 maskColor = texture2D(u_mask, v_texCoord); \
  5633. if (u_backdrop.a > 0.0) { \
  5634. maskColor.rgb = maskColor.rgb * maskColor.a + \
  5635. u_backdrop.rgb * (1.0 - maskColor.a); \
  5636. } \
  5637. float lum; \
  5638. if (u_subtype == 0) { \
  5639. lum = maskColor.a; \
  5640. } else { \
  5641. lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \
  5642. maskColor.b * 0.11; \
  5643. } \
  5644. imageColor.a *= lum; \
  5645. imageColor.rgb *= imageColor.a; \
  5646. gl_FragColor = imageColor; \
  5647. } ';
  5648. var smaskCache = null;
  5649. function initSmaskGL() {
  5650. var canvas, gl;
  5651. generateGL();
  5652. canvas = currentCanvas;
  5653. currentCanvas = null;
  5654. gl = currentGL;
  5655. currentGL = null;
  5656. // setup a GLSL program
  5657. var vertexShader = createVertexShader(gl, smaskVertexShaderCode);
  5658. var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode);
  5659. var program = createProgram(gl, [
  5660. vertexShader,
  5661. fragmentShader
  5662. ]);
  5663. gl.useProgram(program);
  5664. var cache = {};
  5665. cache.gl = gl;
  5666. cache.canvas = canvas;
  5667. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5668. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5669. cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop');
  5670. cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype');
  5671. var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord');
  5672. var texLayerLocation = gl.getUniformLocation(program, 'u_image');
  5673. var texMaskLocation = gl.getUniformLocation(program, 'u_mask');
  5674. // provide texture coordinates for the rectangle.
  5675. var texCoordBuffer = gl.createBuffer();
  5676. gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
  5677. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5678. 0.0,
  5679. 0.0,
  5680. 1.0,
  5681. 0.0,
  5682. 0.0,
  5683. 1.0,
  5684. 0.0,
  5685. 1.0,
  5686. 1.0,
  5687. 0.0,
  5688. 1.0,
  5689. 1.0
  5690. ]), gl.STATIC_DRAW);
  5691. gl.enableVertexAttribArray(texCoordLocation);
  5692. gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0);
  5693. gl.uniform1i(texLayerLocation, 0);
  5694. gl.uniform1i(texMaskLocation, 1);
  5695. smaskCache = cache;
  5696. }
  5697. function composeSMask(layer, mask, properties) {
  5698. var width = layer.width, height = layer.height;
  5699. if (!smaskCache) {
  5700. initSmaskGL();
  5701. }
  5702. var cache = smaskCache, canvas = cache.canvas, gl = cache.gl;
  5703. canvas.width = width;
  5704. canvas.height = height;
  5705. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5706. gl.uniform2f(cache.resolutionLocation, width, height);
  5707. if (properties.backdrop) {
  5708. gl.uniform4f(cache.resolutionLocation, properties.backdrop[0], properties.backdrop[1], properties.backdrop[2], 1);
  5709. } else {
  5710. gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0);
  5711. }
  5712. gl.uniform1i(cache.subtypeLocation, properties.subtype === 'Luminosity' ? 1 : 0);
  5713. // Create a textures
  5714. var texture = createTexture(gl, layer, gl.TEXTURE0);
  5715. var maskTexture = createTexture(gl, mask, gl.TEXTURE1);
  5716. // Create a buffer and put a single clipspace rectangle in
  5717. // it (2 triangles)
  5718. var buffer = gl.createBuffer();
  5719. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  5720. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  5721. 0,
  5722. 0,
  5723. width,
  5724. 0,
  5725. 0,
  5726. height,
  5727. 0,
  5728. height,
  5729. width,
  5730. 0,
  5731. width,
  5732. height
  5733. ]), gl.STATIC_DRAW);
  5734. gl.enableVertexAttribArray(cache.positionLocation);
  5735. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5736. // draw
  5737. gl.clearColor(0, 0, 0, 0);
  5738. gl.enable(gl.BLEND);
  5739. gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  5740. gl.clear(gl.COLOR_BUFFER_BIT);
  5741. gl.drawArrays(gl.TRIANGLES, 0, 6);
  5742. gl.flush();
  5743. gl.deleteTexture(texture);
  5744. gl.deleteTexture(maskTexture);
  5745. gl.deleteBuffer(buffer);
  5746. return canvas;
  5747. }
  5748. var figuresVertexShaderCode = '\
  5749. attribute vec2 a_position; \
  5750. attribute vec3 a_color; \
  5751. \
  5752. uniform vec2 u_resolution; \
  5753. uniform vec2 u_scale; \
  5754. uniform vec2 u_offset; \
  5755. \
  5756. varying vec4 v_color; \
  5757. \
  5758. void main() { \
  5759. vec2 position = (a_position + u_offset) * u_scale; \
  5760. vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \
  5761. gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \
  5762. \
  5763. v_color = vec4(a_color / 255.0, 1.0); \
  5764. } ';
  5765. var figuresFragmentShaderCode = '\
  5766. precision mediump float; \
  5767. \
  5768. varying vec4 v_color; \
  5769. \
  5770. void main() { \
  5771. gl_FragColor = v_color; \
  5772. } ';
  5773. var figuresCache = null;
  5774. function initFiguresGL() {
  5775. var canvas, gl;
  5776. generateGL();
  5777. canvas = currentCanvas;
  5778. currentCanvas = null;
  5779. gl = currentGL;
  5780. currentGL = null;
  5781. // setup a GLSL program
  5782. var vertexShader = createVertexShader(gl, figuresVertexShaderCode);
  5783. var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode);
  5784. var program = createProgram(gl, [
  5785. vertexShader,
  5786. fragmentShader
  5787. ]);
  5788. gl.useProgram(program);
  5789. var cache = {};
  5790. cache.gl = gl;
  5791. cache.canvas = canvas;
  5792. cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution');
  5793. cache.scaleLocation = gl.getUniformLocation(program, 'u_scale');
  5794. cache.offsetLocation = gl.getUniformLocation(program, 'u_offset');
  5795. cache.positionLocation = gl.getAttribLocation(program, 'a_position');
  5796. cache.colorLocation = gl.getAttribLocation(program, 'a_color');
  5797. figuresCache = cache;
  5798. }
  5799. function drawFigures(width, height, backgroundColor, figures, context) {
  5800. if (!figuresCache) {
  5801. initFiguresGL();
  5802. }
  5803. var cache = figuresCache, canvas = cache.canvas, gl = cache.gl;
  5804. canvas.width = width;
  5805. canvas.height = height;
  5806. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  5807. gl.uniform2f(cache.resolutionLocation, width, height);
  5808. // count triangle points
  5809. var count = 0;
  5810. var i, ii, rows;
  5811. for (i = 0, ii = figures.length; i < ii; i++) {
  5812. switch (figures[i].type) {
  5813. case 'lattice':
  5814. rows = figures[i].coords.length / figures[i].verticesPerRow | 0;
  5815. count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6;
  5816. break;
  5817. case 'triangles':
  5818. count += figures[i].coords.length;
  5819. break;
  5820. }
  5821. }
  5822. // transfer data
  5823. var coords = new Float32Array(count * 2);
  5824. var colors = new Uint8Array(count * 3);
  5825. var coordsMap = context.coords, colorsMap = context.colors;
  5826. var pIndex = 0, cIndex = 0;
  5827. for (i = 0, ii = figures.length; i < ii; i++) {
  5828. var figure = figures[i], ps = figure.coords, cs = figure.colors;
  5829. switch (figure.type) {
  5830. case 'lattice':
  5831. var cols = figure.verticesPerRow;
  5832. rows = ps.length / cols | 0;
  5833. for (var row = 1; row < rows; row++) {
  5834. var offset = row * cols + 1;
  5835. for (var col = 1; col < cols; col++, offset++) {
  5836. coords[pIndex] = coordsMap[ps[offset - cols - 1]];
  5837. coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1];
  5838. coords[pIndex + 2] = coordsMap[ps[offset - cols]];
  5839. coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1];
  5840. coords[pIndex + 4] = coordsMap[ps[offset - 1]];
  5841. coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1];
  5842. colors[cIndex] = colorsMap[cs[offset - cols - 1]];
  5843. colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1];
  5844. colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2];
  5845. colors[cIndex + 3] = colorsMap[cs[offset - cols]];
  5846. colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1];
  5847. colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2];
  5848. colors[cIndex + 6] = colorsMap[cs[offset - 1]];
  5849. colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1];
  5850. colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2];
  5851. coords[pIndex + 6] = coords[pIndex + 2];
  5852. coords[pIndex + 7] = coords[pIndex + 3];
  5853. coords[pIndex + 8] = coords[pIndex + 4];
  5854. coords[pIndex + 9] = coords[pIndex + 5];
  5855. coords[pIndex + 10] = coordsMap[ps[offset]];
  5856. coords[pIndex + 11] = coordsMap[ps[offset] + 1];
  5857. colors[cIndex + 9] = colors[cIndex + 3];
  5858. colors[cIndex + 10] = colors[cIndex + 4];
  5859. colors[cIndex + 11] = colors[cIndex + 5];
  5860. colors[cIndex + 12] = colors[cIndex + 6];
  5861. colors[cIndex + 13] = colors[cIndex + 7];
  5862. colors[cIndex + 14] = colors[cIndex + 8];
  5863. colors[cIndex + 15] = colorsMap[cs[offset]];
  5864. colors[cIndex + 16] = colorsMap[cs[offset] + 1];
  5865. colors[cIndex + 17] = colorsMap[cs[offset] + 2];
  5866. pIndex += 12;
  5867. cIndex += 18;
  5868. }
  5869. }
  5870. break;
  5871. case 'triangles':
  5872. for (var j = 0, jj = ps.length; j < jj; j++) {
  5873. coords[pIndex] = coordsMap[ps[j]];
  5874. coords[pIndex + 1] = coordsMap[ps[j] + 1];
  5875. colors[cIndex] = colorsMap[cs[j]];
  5876. colors[cIndex + 1] = colorsMap[cs[j] + 1];
  5877. colors[cIndex + 2] = colorsMap[cs[j] + 2];
  5878. pIndex += 2;
  5879. cIndex += 3;
  5880. }
  5881. break;
  5882. }
  5883. }
  5884. // draw
  5885. if (backgroundColor) {
  5886. gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255, backgroundColor[2] / 255, 1.0);
  5887. } else {
  5888. gl.clearColor(0, 0, 0, 0);
  5889. }
  5890. gl.clear(gl.COLOR_BUFFER_BIT);
  5891. var coordsBuffer = gl.createBuffer();
  5892. gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer);
  5893. gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW);
  5894. gl.enableVertexAttribArray(cache.positionLocation);
  5895. gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0);
  5896. var colorsBuffer = gl.createBuffer();
  5897. gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer);
  5898. gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
  5899. gl.enableVertexAttribArray(cache.colorLocation);
  5900. gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false, 0, 0);
  5901. gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY);
  5902. gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY);
  5903. gl.drawArrays(gl.TRIANGLES, 0, count);
  5904. gl.flush();
  5905. gl.deleteBuffer(coordsBuffer);
  5906. gl.deleteBuffer(colorsBuffer);
  5907. return canvas;
  5908. }
  5909. function cleanup() {
  5910. if (smaskCache && smaskCache.canvas) {
  5911. smaskCache.canvas.width = 0;
  5912. smaskCache.canvas.height = 0;
  5913. }
  5914. if (figuresCache && figuresCache.canvas) {
  5915. figuresCache.canvas.width = 0;
  5916. figuresCache.canvas.height = 0;
  5917. }
  5918. smaskCache = null;
  5919. figuresCache = null;
  5920. }
  5921. return {
  5922. get isEnabled() {
  5923. if (getDefaultSetting('disableWebGL')) {
  5924. return false;
  5925. }
  5926. var enabled = false;
  5927. try {
  5928. generateGL();
  5929. enabled = !!currentGL;
  5930. } catch (e) {
  5931. }
  5932. return shadow(this, 'isEnabled', enabled);
  5933. },
  5934. composeSMask: composeSMask,
  5935. drawFigures: drawFigures,
  5936. clear: cleanup
  5937. };
  5938. }();
  5939. exports.WebGLUtils = WebGLUtils;
  5940. }));
  5941. (function (root, factory) {
  5942. factory(root.pdfjsDisplayPatternHelper = {}, root.pdfjsSharedUtil, root.pdfjsDisplayWebGL);
  5943. }(this, function (exports, sharedUtil, displayWebGL) {
  5944. var Util = sharedUtil.Util;
  5945. var info = sharedUtil.info;
  5946. var isArray = sharedUtil.isArray;
  5947. var error = sharedUtil.error;
  5948. var WebGLUtils = displayWebGL.WebGLUtils;
  5949. var ShadingIRs = {};
  5950. ShadingIRs.RadialAxial = {
  5951. fromIR: function RadialAxial_fromIR(raw) {
  5952. var type = raw[1];
  5953. var colorStops = raw[2];
  5954. var p0 = raw[3];
  5955. var p1 = raw[4];
  5956. var r0 = raw[5];
  5957. var r1 = raw[6];
  5958. return {
  5959. type: 'Pattern',
  5960. getPattern: function RadialAxial_getPattern(ctx) {
  5961. var grad;
  5962. if (type === 'axial') {
  5963. grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]);
  5964. } else if (type === 'radial') {
  5965. grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1);
  5966. }
  5967. for (var i = 0, ii = colorStops.length; i < ii; ++i) {
  5968. var c = colorStops[i];
  5969. grad.addColorStop(c[0], c[1]);
  5970. }
  5971. return grad;
  5972. }
  5973. };
  5974. }
  5975. };
  5976. var createMeshCanvas = function createMeshCanvasClosure() {
  5977. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  5978. // Very basic Gouraud-shaded triangle rasterization algorithm.
  5979. var coords = context.coords, colors = context.colors;
  5980. var bytes = data.data, rowSize = data.width * 4;
  5981. var tmp;
  5982. if (coords[p1 + 1] > coords[p2 + 1]) {
  5983. tmp = p1;
  5984. p1 = p2;
  5985. p2 = tmp;
  5986. tmp = c1;
  5987. c1 = c2;
  5988. c2 = tmp;
  5989. }
  5990. if (coords[p2 + 1] > coords[p3 + 1]) {
  5991. tmp = p2;
  5992. p2 = p3;
  5993. p3 = tmp;
  5994. tmp = c2;
  5995. c2 = c3;
  5996. c3 = tmp;
  5997. }
  5998. if (coords[p1 + 1] > coords[p2 + 1]) {
  5999. tmp = p1;
  6000. p1 = p2;
  6001. p2 = tmp;
  6002. tmp = c1;
  6003. c1 = c2;
  6004. c2 = tmp;
  6005. }
  6006. var x1 = (coords[p1] + context.offsetX) * context.scaleX;
  6007. var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  6008. var x2 = (coords[p2] + context.offsetX) * context.scaleX;
  6009. var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  6010. var x3 = (coords[p3] + context.offsetX) * context.scaleX;
  6011. var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  6012. if (y1 >= y3) {
  6013. return;
  6014. }
  6015. var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2];
  6016. var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2];
  6017. var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2];
  6018. var minY = Math.round(y1), maxY = Math.round(y3);
  6019. var xa, car, cag, cab;
  6020. var xb, cbr, cbg, cbb;
  6021. var k;
  6022. for (var y = minY; y <= maxY; y++) {
  6023. if (y < y2) {
  6024. k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2);
  6025. xa = x1 - (x1 - x2) * k;
  6026. car = c1r - (c1r - c2r) * k;
  6027. cag = c1g - (c1g - c2g) * k;
  6028. cab = c1b - (c1b - c2b) * k;
  6029. } else {
  6030. k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3);
  6031. xa = x2 - (x2 - x3) * k;
  6032. car = c2r - (c2r - c3r) * k;
  6033. cag = c2g - (c2g - c3g) * k;
  6034. cab = c2b - (c2b - c3b) * k;
  6035. }
  6036. k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3);
  6037. xb = x1 - (x1 - x3) * k;
  6038. cbr = c1r - (c1r - c3r) * k;
  6039. cbg = c1g - (c1g - c3g) * k;
  6040. cbb = c1b - (c1b - c3b) * k;
  6041. var x1_ = Math.round(Math.min(xa, xb));
  6042. var x2_ = Math.round(Math.max(xa, xb));
  6043. var j = rowSize * y + x1_ * 4;
  6044. for (var x = x1_; x <= x2_; x++) {
  6045. k = (xa - x) / (xa - xb);
  6046. k = k < 0 ? 0 : k > 1 ? 1 : k;
  6047. bytes[j++] = car - (car - cbr) * k | 0;
  6048. bytes[j++] = cag - (cag - cbg) * k | 0;
  6049. bytes[j++] = cab - (cab - cbb) * k | 0;
  6050. bytes[j++] = 255;
  6051. }
  6052. }
  6053. }
  6054. function drawFigure(data, figure, context) {
  6055. var ps = figure.coords;
  6056. var cs = figure.colors;
  6057. var i, ii;
  6058. switch (figure.type) {
  6059. case 'lattice':
  6060. var verticesPerRow = figure.verticesPerRow;
  6061. var rows = Math.floor(ps.length / verticesPerRow) - 1;
  6062. var cols = verticesPerRow - 1;
  6063. for (i = 0; i < rows; i++) {
  6064. var q = i * verticesPerRow;
  6065. for (var j = 0; j < cols; j++, q++) {
  6066. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  6067. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  6068. }
  6069. }
  6070. break;
  6071. case 'triangles':
  6072. for (i = 0, ii = ps.length; i < ii; i += 3) {
  6073. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  6074. }
  6075. break;
  6076. default:
  6077. error('illigal figure');
  6078. break;
  6079. }
  6080. }
  6081. function createMeshCanvas(bounds, combinesScale, coords, colors, figures, backgroundColor, cachedCanvases) {
  6082. // we will increase scale on some weird factor to let antialiasing take
  6083. // care of "rough" edges
  6084. var EXPECTED_SCALE = 1.1;
  6085. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  6086. var MAX_PATTERN_SIZE = 3000;
  6087. // 10in @ 300dpi shall be enough
  6088. // We need to keep transparent border around our pattern for fill():
  6089. // createPattern with 'no-repeat' will bleed edges across entire area.
  6090. var BORDER_SIZE = 2;
  6091. var offsetX = Math.floor(bounds[0]);
  6092. var offsetY = Math.floor(bounds[1]);
  6093. var boundsWidth = Math.ceil(bounds[2]) - offsetX;
  6094. var boundsHeight = Math.ceil(bounds[3]) - offsetY;
  6095. var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  6096. var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  6097. var scaleX = boundsWidth / width;
  6098. var scaleY = boundsHeight / height;
  6099. var context = {
  6100. coords: coords,
  6101. colors: colors,
  6102. offsetX: -offsetX,
  6103. offsetY: -offsetY,
  6104. scaleX: 1 / scaleX,
  6105. scaleY: 1 / scaleY
  6106. };
  6107. var paddedWidth = width + BORDER_SIZE * 2;
  6108. var paddedHeight = height + BORDER_SIZE * 2;
  6109. var canvas, tmpCanvas, i, ii;
  6110. if (WebGLUtils.isEnabled) {
  6111. canvas = WebGLUtils.drawFigures(width, height, backgroundColor, figures, context);
  6112. // https://bugzilla.mozilla.org/show_bug.cgi?id=972126
  6113. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight, false);
  6114. tmpCanvas.context.drawImage(canvas, BORDER_SIZE, BORDER_SIZE);
  6115. canvas = tmpCanvas.canvas;
  6116. } else {
  6117. tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight, false);
  6118. var tmpCtx = tmpCanvas.context;
  6119. var data = tmpCtx.createImageData(width, height);
  6120. if (backgroundColor) {
  6121. var bytes = data.data;
  6122. for (i = 0, ii = bytes.length; i < ii; i += 4) {
  6123. bytes[i] = backgroundColor[0];
  6124. bytes[i + 1] = backgroundColor[1];
  6125. bytes[i + 2] = backgroundColor[2];
  6126. bytes[i + 3] = 255;
  6127. }
  6128. }
  6129. for (i = 0; i < figures.length; i++) {
  6130. drawFigure(data, figures[i], context);
  6131. }
  6132. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  6133. canvas = tmpCanvas.canvas;
  6134. }
  6135. return {
  6136. canvas: canvas,
  6137. offsetX: offsetX - BORDER_SIZE * scaleX,
  6138. offsetY: offsetY - BORDER_SIZE * scaleY,
  6139. scaleX: scaleX,
  6140. scaleY: scaleY
  6141. };
  6142. }
  6143. return createMeshCanvas;
  6144. }();
  6145. ShadingIRs.Mesh = {
  6146. fromIR: function Mesh_fromIR(raw) {
  6147. //var type = raw[1];
  6148. var coords = raw[2];
  6149. var colors = raw[3];
  6150. var figures = raw[4];
  6151. var bounds = raw[5];
  6152. var matrix = raw[6];
  6153. //var bbox = raw[7];
  6154. var background = raw[8];
  6155. return {
  6156. type: 'Pattern',
  6157. getPattern: function Mesh_getPattern(ctx, owner, shadingFill) {
  6158. var scale;
  6159. if (shadingFill) {
  6160. scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  6161. } else {
  6162. // Obtain scale from matrix and current transformation matrix.
  6163. scale = Util.singularValueDecompose2dScale(owner.baseTransform);
  6164. if (matrix) {
  6165. var matrixScale = Util.singularValueDecompose2dScale(matrix);
  6166. scale = [
  6167. scale[0] * matrixScale[0],
  6168. scale[1] * matrixScale[1]
  6169. ];
  6170. }
  6171. }
  6172. // Rasterizing on the main thread since sending/queue large canvases
  6173. // might cause OOM.
  6174. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords, colors, figures, shadingFill ? null : background, owner.cachedCanvases);
  6175. if (!shadingFill) {
  6176. ctx.setTransform.apply(ctx, owner.baseTransform);
  6177. if (matrix) {
  6178. ctx.transform.apply(ctx, matrix);
  6179. }
  6180. }
  6181. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  6182. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  6183. return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat');
  6184. }
  6185. };
  6186. }
  6187. };
  6188. ShadingIRs.Dummy = {
  6189. fromIR: function Dummy_fromIR() {
  6190. return {
  6191. type: 'Pattern',
  6192. getPattern: function Dummy_fromIR_getPattern() {
  6193. return 'hotpink';
  6194. }
  6195. };
  6196. }
  6197. };
  6198. function getShadingPatternFromIR(raw) {
  6199. var shadingIR = ShadingIRs[raw[0]];
  6200. if (!shadingIR) {
  6201. error('Unknown IR type: ' + raw[0]);
  6202. }
  6203. return shadingIR.fromIR(raw);
  6204. }
  6205. var TilingPattern = function TilingPatternClosure() {
  6206. var PaintType = {
  6207. COLORED: 1,
  6208. UNCOLORED: 2
  6209. };
  6210. var MAX_PATTERN_SIZE = 3000;
  6211. // 10in @ 300dpi shall be enough
  6212. function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  6213. this.operatorList = IR[2];
  6214. this.matrix = IR[3] || [
  6215. 1,
  6216. 0,
  6217. 0,
  6218. 1,
  6219. 0,
  6220. 0
  6221. ];
  6222. this.bbox = IR[4];
  6223. this.xstep = IR[5];
  6224. this.ystep = IR[6];
  6225. this.paintType = IR[7];
  6226. this.tilingType = IR[8];
  6227. this.color = color;
  6228. this.canvasGraphicsFactory = canvasGraphicsFactory;
  6229. this.baseTransform = baseTransform;
  6230. this.type = 'Pattern';
  6231. this.ctx = ctx;
  6232. }
  6233. TilingPattern.prototype = {
  6234. createPatternCanvas: function TilinPattern_createPatternCanvas(owner) {
  6235. var operatorList = this.operatorList;
  6236. var bbox = this.bbox;
  6237. var xstep = this.xstep;
  6238. var ystep = this.ystep;
  6239. var paintType = this.paintType;
  6240. var tilingType = this.tilingType;
  6241. var color = this.color;
  6242. var canvasGraphicsFactory = this.canvasGraphicsFactory;
  6243. info('TilingType: ' + tilingType);
  6244. var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3];
  6245. var topLeft = [
  6246. x0,
  6247. y0
  6248. ];
  6249. // we want the canvas to be as large as the step size
  6250. var botRight = [
  6251. x0 + xstep,
  6252. y0 + ystep
  6253. ];
  6254. var width = botRight[0] - topLeft[0];
  6255. var height = botRight[1] - topLeft[1];
  6256. // Obtain scale from matrix and current transformation matrix.
  6257. var matrixScale = Util.singularValueDecompose2dScale(this.matrix);
  6258. var curMatrixScale = Util.singularValueDecompose2dScale(this.baseTransform);
  6259. var combinedScale = [
  6260. matrixScale[0] * curMatrixScale[0],
  6261. matrixScale[1] * curMatrixScale[1]
  6262. ];
  6263. // MAX_PATTERN_SIZE is used to avoid OOM situation.
  6264. // Use width and height values that are as close as possible to the end
  6265. // result when the pattern is used. Too low value makes the pattern look
  6266. // blurry. Too large value makes it look too crispy.
  6267. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])), MAX_PATTERN_SIZE);
  6268. height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])), MAX_PATTERN_SIZE);
  6269. var tmpCanvas = owner.cachedCanvases.getCanvas('pattern', width, height, true);
  6270. var tmpCtx = tmpCanvas.context;
  6271. var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  6272. graphics.groupLevel = owner.groupLevel;
  6273. this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color);
  6274. this.setScale(width, height, xstep, ystep);
  6275. this.transformToScale(graphics);
  6276. // transform coordinates to pattern space
  6277. var tmpTranslate = [
  6278. 1,
  6279. 0,
  6280. 0,
  6281. 1,
  6282. -topLeft[0],
  6283. -topLeft[1]
  6284. ];
  6285. graphics.transform.apply(graphics, tmpTranslate);
  6286. this.clipBbox(graphics, bbox, x0, y0, x1, y1);
  6287. graphics.executeOperatorList(operatorList);
  6288. return tmpCanvas.canvas;
  6289. },
  6290. setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
  6291. this.scale = [
  6292. width / xstep,
  6293. height / ystep
  6294. ];
  6295. },
  6296. transformToScale: function TilingPattern_transformToScale(graphics) {
  6297. var scale = this.scale;
  6298. var tmpScale = [
  6299. scale[0],
  6300. 0,
  6301. 0,
  6302. scale[1],
  6303. 0,
  6304. 0
  6305. ];
  6306. graphics.transform.apply(graphics, tmpScale);
  6307. },
  6308. scaleToContext: function TilingPattern_scaleToContext() {
  6309. var scale = this.scale;
  6310. this.ctx.scale(1 / scale[0], 1 / scale[1]);
  6311. },
  6312. clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
  6313. if (bbox && isArray(bbox) && bbox.length === 4) {
  6314. var bboxWidth = x1 - x0;
  6315. var bboxHeight = y1 - y0;
  6316. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  6317. graphics.clip();
  6318. graphics.endPath();
  6319. }
  6320. },
  6321. setFillAndStrokeStyleToContext: function setFillAndStrokeStyleToContext(context, paintType, color) {
  6322. switch (paintType) {
  6323. case PaintType.COLORED:
  6324. var ctx = this.ctx;
  6325. context.fillStyle = ctx.fillStyle;
  6326. context.strokeStyle = ctx.strokeStyle;
  6327. break;
  6328. case PaintType.UNCOLORED:
  6329. var cssColor = Util.makeCssRgb(color[0], color[1], color[2]);
  6330. context.fillStyle = cssColor;
  6331. context.strokeStyle = cssColor;
  6332. break;
  6333. default:
  6334. error('Unsupported paint type: ' + paintType);
  6335. }
  6336. },
  6337. getPattern: function TilingPattern_getPattern(ctx, owner) {
  6338. var temporaryPatternCanvas = this.createPatternCanvas(owner);
  6339. ctx = this.ctx;
  6340. ctx.setTransform.apply(ctx, this.baseTransform);
  6341. ctx.transform.apply(ctx, this.matrix);
  6342. this.scaleToContext();
  6343. return ctx.createPattern(temporaryPatternCanvas, 'repeat');
  6344. }
  6345. };
  6346. return TilingPattern;
  6347. }();
  6348. exports.getShadingPatternFromIR = getShadingPatternFromIR;
  6349. exports.TilingPattern = TilingPattern;
  6350. }));
  6351. (function (root, factory) {
  6352. factory(root.pdfjsDisplayCanvas = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils, root.pdfjsDisplayPatternHelper, root.pdfjsDisplayWebGL);
  6353. }(this, function (exports, sharedUtil, displayDOMUtils, displayPatternHelper, displayWebGL) {
  6354. var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
  6355. var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
  6356. var ImageKind = sharedUtil.ImageKind;
  6357. var OPS = sharedUtil.OPS;
  6358. var TextRenderingMode = sharedUtil.TextRenderingMode;
  6359. var Uint32ArrayView = sharedUtil.Uint32ArrayView;
  6360. var Util = sharedUtil.Util;
  6361. var assert = sharedUtil.assert;
  6362. var info = sharedUtil.info;
  6363. var isNum = sharedUtil.isNum;
  6364. var isArray = sharedUtil.isArray;
  6365. var isLittleEndian = sharedUtil.isLittleEndian;
  6366. var error = sharedUtil.error;
  6367. var shadow = sharedUtil.shadow;
  6368. var warn = sharedUtil.warn;
  6369. var TilingPattern = displayPatternHelper.TilingPattern;
  6370. var getShadingPatternFromIR = displayPatternHelper.getShadingPatternFromIR;
  6371. var WebGLUtils = displayWebGL.WebGLUtils;
  6372. var hasCanvasTypedArrays = displayDOMUtils.hasCanvasTypedArrays;
  6373. // <canvas> contexts store most of the state we need natively.
  6374. // However, PDF needs a bit more state, which we store here.
  6375. // Minimal font size that would be used during canvas fillText operations.
  6376. var MIN_FONT_SIZE = 16;
  6377. // Maximum font size that would be used during canvas fillText operations.
  6378. var MAX_FONT_SIZE = 100;
  6379. var MAX_GROUP_SIZE = 4096;
  6380. // Heuristic value used when enforcing minimum line widths.
  6381. var MIN_WIDTH_FACTOR = 0.65;
  6382. var COMPILE_TYPE3_GLYPHS = true;
  6383. var MAX_SIZE_TO_COMPILE = 1000;
  6384. var FULL_CHUNK_HEIGHT = 16;
  6385. var HasCanvasTypedArraysCached = {
  6386. get value() {
  6387. return shadow(HasCanvasTypedArraysCached, 'value', hasCanvasTypedArrays());
  6388. }
  6389. };
  6390. var IsLittleEndianCached = {
  6391. get value() {
  6392. return shadow(IsLittleEndianCached, 'value', isLittleEndian());
  6393. }
  6394. };
  6395. function createScratchCanvas(width, height) {
  6396. var canvas = document.createElement('canvas');
  6397. canvas.width = width;
  6398. canvas.height = height;
  6399. return canvas;
  6400. }
  6401. function addContextCurrentTransform(ctx) {
  6402. // If the context doesn't expose a `mozCurrentTransform`, add a JS based one.
  6403. if (!ctx.mozCurrentTransform) {
  6404. ctx._originalSave = ctx.save;
  6405. ctx._originalRestore = ctx.restore;
  6406. ctx._originalRotate = ctx.rotate;
  6407. ctx._originalScale = ctx.scale;
  6408. ctx._originalTranslate = ctx.translate;
  6409. ctx._originalTransform = ctx.transform;
  6410. ctx._originalSetTransform = ctx.setTransform;
  6411. ctx._transformMatrix = ctx._transformMatrix || [
  6412. 1,
  6413. 0,
  6414. 0,
  6415. 1,
  6416. 0,
  6417. 0
  6418. ];
  6419. ctx._transformStack = [];
  6420. Object.defineProperty(ctx, 'mozCurrentTransform', {
  6421. get: function getCurrentTransform() {
  6422. return this._transformMatrix;
  6423. }
  6424. });
  6425. Object.defineProperty(ctx, 'mozCurrentTransformInverse', {
  6426. get: function getCurrentTransformInverse() {
  6427. // Calculation done using WolframAlpha:
  6428. // http://www.wolframalpha.com/input/?
  6429. // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}}
  6430. var m = this._transformMatrix;
  6431. var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5];
  6432. var ad_bc = a * d - b * c;
  6433. var bc_ad = b * c - a * d;
  6434. return [
  6435. d / ad_bc,
  6436. b / bc_ad,
  6437. c / bc_ad,
  6438. a / ad_bc,
  6439. (d * e - c * f) / bc_ad,
  6440. (b * e - a * f) / ad_bc
  6441. ];
  6442. }
  6443. });
  6444. ctx.save = function ctxSave() {
  6445. var old = this._transformMatrix;
  6446. this._transformStack.push(old);
  6447. this._transformMatrix = old.slice(0, 6);
  6448. this._originalSave();
  6449. };
  6450. ctx.restore = function ctxRestore() {
  6451. var prev = this._transformStack.pop();
  6452. if (prev) {
  6453. this._transformMatrix = prev;
  6454. this._originalRestore();
  6455. }
  6456. };
  6457. ctx.translate = function ctxTranslate(x, y) {
  6458. var m = this._transformMatrix;
  6459. m[4] = m[0] * x + m[2] * y + m[4];
  6460. m[5] = m[1] * x + m[3] * y + m[5];
  6461. this._originalTranslate(x, y);
  6462. };
  6463. ctx.scale = function ctxScale(x, y) {
  6464. var m = this._transformMatrix;
  6465. m[0] = m[0] * x;
  6466. m[1] = m[1] * x;
  6467. m[2] = m[2] * y;
  6468. m[3] = m[3] * y;
  6469. this._originalScale(x, y);
  6470. };
  6471. ctx.transform = function ctxTransform(a, b, c, d, e, f) {
  6472. var m = this._transformMatrix;
  6473. this._transformMatrix = [
  6474. m[0] * a + m[2] * b,
  6475. m[1] * a + m[3] * b,
  6476. m[0] * c + m[2] * d,
  6477. m[1] * c + m[3] * d,
  6478. m[0] * e + m[2] * f + m[4],
  6479. m[1] * e + m[3] * f + m[5]
  6480. ];
  6481. ctx._originalTransform(a, b, c, d, e, f);
  6482. };
  6483. ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
  6484. this._transformMatrix = [
  6485. a,
  6486. b,
  6487. c,
  6488. d,
  6489. e,
  6490. f
  6491. ];
  6492. ctx._originalSetTransform(a, b, c, d, e, f);
  6493. };
  6494. ctx.rotate = function ctxRotate(angle) {
  6495. var cosValue = Math.cos(angle);
  6496. var sinValue = Math.sin(angle);
  6497. var m = this._transformMatrix;
  6498. this._transformMatrix = [
  6499. m[0] * cosValue + m[2] * sinValue,
  6500. m[1] * cosValue + m[3] * sinValue,
  6501. m[0] * -sinValue + m[2] * cosValue,
  6502. m[1] * -sinValue + m[3] * cosValue,
  6503. m[4],
  6504. m[5]
  6505. ];
  6506. this._originalRotate(angle);
  6507. };
  6508. }
  6509. }
  6510. var CachedCanvases = function CachedCanvasesClosure() {
  6511. function CachedCanvases() {
  6512. this.cache = Object.create(null);
  6513. }
  6514. CachedCanvases.prototype = {
  6515. getCanvas: function CachedCanvases_getCanvas(id, width, height, trackTransform) {
  6516. var canvasEntry;
  6517. if (this.cache[id] !== undefined) {
  6518. canvasEntry = this.cache[id];
  6519. canvasEntry.canvas.width = width;
  6520. canvasEntry.canvas.height = height;
  6521. // reset canvas transform for emulated mozCurrentTransform, if needed
  6522. canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
  6523. } else {
  6524. var canvas = createScratchCanvas(width, height);
  6525. var ctx = canvas.getContext('2d');
  6526. if (trackTransform) {
  6527. addContextCurrentTransform(ctx);
  6528. }
  6529. this.cache[id] = canvasEntry = {
  6530. canvas: canvas,
  6531. context: ctx
  6532. };
  6533. }
  6534. return canvasEntry;
  6535. },
  6536. clear: function () {
  6537. for (var id in this.cache) {
  6538. var canvasEntry = this.cache[id];
  6539. // Zeroing the width and height causes Firefox to release graphics
  6540. // resources immediately, which can greatly reduce memory consumption.
  6541. canvasEntry.canvas.width = 0;
  6542. canvasEntry.canvas.height = 0;
  6543. delete this.cache[id];
  6544. }
  6545. }
  6546. };
  6547. return CachedCanvases;
  6548. }();
  6549. function compileType3Glyph(imgData) {
  6550. var POINT_TO_PROCESS_LIMIT = 1000;
  6551. var width = imgData.width, height = imgData.height;
  6552. var i, j, j0, width1 = width + 1;
  6553. var points = new Uint8Array(width1 * (height + 1));
  6554. var POINT_TYPES = new Uint8Array([
  6555. 0,
  6556. 2,
  6557. 4,
  6558. 0,
  6559. 1,
  6560. 0,
  6561. 5,
  6562. 4,
  6563. 8,
  6564. 10,
  6565. 0,
  6566. 8,
  6567. 0,
  6568. 2,
  6569. 1,
  6570. 0
  6571. ]);
  6572. // decodes bit-packed mask data
  6573. var lineSize = width + 7 & ~7, data0 = imgData.data;
  6574. var data = new Uint8Array(lineSize * height), pos = 0, ii;
  6575. for (i = 0, ii = data0.length; i < ii; i++) {
  6576. var mask = 128, elem = data0[i];
  6577. while (mask > 0) {
  6578. data[pos++] = elem & mask ? 0 : 255;
  6579. mask >>= 1;
  6580. }
  6581. }
  6582. // finding iteresting points: every point is located between mask pixels,
  6583. // so there will be points of the (width + 1)x(height + 1) grid. Every point
  6584. // will have flags assigned based on neighboring mask pixels:
  6585. // 4 | 8
  6586. // --P--
  6587. // 2 | 1
  6588. // We are interested only in points with the flags:
  6589. // - outside corners: 1, 2, 4, 8;
  6590. // - inside corners: 7, 11, 13, 14;
  6591. // - and, intersections: 5, 10.
  6592. var count = 0;
  6593. pos = 0;
  6594. if (data[pos] !== 0) {
  6595. points[0] = 1;
  6596. ++count;
  6597. }
  6598. for (j = 1; j < width; j++) {
  6599. if (data[pos] !== data[pos + 1]) {
  6600. points[j] = data[pos] ? 2 : 1;
  6601. ++count;
  6602. }
  6603. pos++;
  6604. }
  6605. if (data[pos] !== 0) {
  6606. points[j] = 2;
  6607. ++count;
  6608. }
  6609. for (i = 1; i < height; i++) {
  6610. pos = i * lineSize;
  6611. j0 = i * width1;
  6612. if (data[pos - lineSize] !== data[pos]) {
  6613. points[j0] = data[pos] ? 1 : 8;
  6614. ++count;
  6615. }
  6616. // 'sum' is the position of the current pixel configuration in the 'TYPES'
  6617. // array (in order 8-1-2-4, so we can use '>>2' to shift the column).
  6618. var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
  6619. for (j = 1; j < width; j++) {
  6620. sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
  6621. if (POINT_TYPES[sum]) {
  6622. points[j0 + j] = POINT_TYPES[sum];
  6623. ++count;
  6624. }
  6625. pos++;
  6626. }
  6627. if (data[pos - lineSize] !== data[pos]) {
  6628. points[j0 + j] = data[pos] ? 2 : 4;
  6629. ++count;
  6630. }
  6631. if (count > POINT_TO_PROCESS_LIMIT) {
  6632. return null;
  6633. }
  6634. }
  6635. pos = lineSize * (height - 1);
  6636. j0 = i * width1;
  6637. if (data[pos] !== 0) {
  6638. points[j0] = 8;
  6639. ++count;
  6640. }
  6641. for (j = 1; j < width; j++) {
  6642. if (data[pos] !== data[pos + 1]) {
  6643. points[j0 + j] = data[pos] ? 4 : 8;
  6644. ++count;
  6645. }
  6646. pos++;
  6647. }
  6648. if (data[pos] !== 0) {
  6649. points[j0 + j] = 4;
  6650. ++count;
  6651. }
  6652. if (count > POINT_TO_PROCESS_LIMIT) {
  6653. return null;
  6654. }
  6655. // building outlines
  6656. var steps = new Int32Array([
  6657. 0,
  6658. width1,
  6659. -1,
  6660. 0,
  6661. -width1,
  6662. 0,
  6663. 0,
  6664. 0,
  6665. 1
  6666. ]);
  6667. var outlines = [];
  6668. for (i = 0; count && i <= height; i++) {
  6669. var p = i * width1;
  6670. var end = p + width;
  6671. while (p < end && !points[p]) {
  6672. p++;
  6673. }
  6674. if (p === end) {
  6675. continue;
  6676. }
  6677. var coords = [
  6678. p % width1,
  6679. i
  6680. ];
  6681. var type = points[p], p0 = p, pp;
  6682. do {
  6683. var step = steps[type];
  6684. do {
  6685. p += step;
  6686. } while (!points[p]);
  6687. pp = points[p];
  6688. if (pp !== 5 && pp !== 10) {
  6689. // set new direction
  6690. type = pp;
  6691. // delete mark
  6692. points[p] = 0;
  6693. } else {
  6694. // type is 5 or 10, ie, a crossing
  6695. // set new direction
  6696. type = pp & 0x33 * type >> 4;
  6697. // set new type for "future hit"
  6698. points[p] &= type >> 2 | type << 2;
  6699. }
  6700. coords.push(p % width1);
  6701. coords.push(p / width1 | 0);
  6702. --count;
  6703. } while (p0 !== p);
  6704. outlines.push(coords);
  6705. --i;
  6706. }
  6707. var drawOutline = function (c) {
  6708. c.save();
  6709. // the path shall be painted in [0..1]x[0..1] space
  6710. c.scale(1 / width, -1 / height);
  6711. c.translate(0, -height);
  6712. c.beginPath();
  6713. for (var i = 0, ii = outlines.length; i < ii; i++) {
  6714. var o = outlines[i];
  6715. c.moveTo(o[0], o[1]);
  6716. for (var j = 2, jj = o.length; j < jj; j += 2) {
  6717. c.lineTo(o[j], o[j + 1]);
  6718. }
  6719. }
  6720. c.fill();
  6721. c.beginPath();
  6722. c.restore();
  6723. };
  6724. return drawOutline;
  6725. }
  6726. var CanvasExtraState = function CanvasExtraStateClosure() {
  6727. function CanvasExtraState(old) {
  6728. // Are soft masks and alpha values shapes or opacities?
  6729. this.alphaIsShape = false;
  6730. this.fontSize = 0;
  6731. this.fontSizeScale = 1;
  6732. this.textMatrix = IDENTITY_MATRIX;
  6733. this.textMatrixScale = 1;
  6734. this.fontMatrix = FONT_IDENTITY_MATRIX;
  6735. this.leading = 0;
  6736. // Current point (in user coordinates)
  6737. this.x = 0;
  6738. this.y = 0;
  6739. // Start of text line (in text coordinates)
  6740. this.lineX = 0;
  6741. this.lineY = 0;
  6742. // Character and word spacing
  6743. this.charSpacing = 0;
  6744. this.wordSpacing = 0;
  6745. this.textHScale = 1;
  6746. this.textRenderingMode = TextRenderingMode.FILL;
  6747. this.textRise = 0;
  6748. // Default fore and background colors
  6749. this.fillColor = '#000000';
  6750. this.strokeColor = '#000000';
  6751. this.patternFill = false;
  6752. // Note: fill alpha applies to all non-stroking operations
  6753. this.fillAlpha = 1;
  6754. this.strokeAlpha = 1;
  6755. this.lineWidth = 1;
  6756. this.activeSMask = null;
  6757. this.resumeSMaskCtx = null;
  6758. // nonclonable field (see the save method below)
  6759. this.old = old;
  6760. }
  6761. CanvasExtraState.prototype = {
  6762. clone: function CanvasExtraState_clone() {
  6763. return Object.create(this);
  6764. },
  6765. setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) {
  6766. this.x = x;
  6767. this.y = y;
  6768. }
  6769. };
  6770. return CanvasExtraState;
  6771. }();
  6772. var CanvasGraphics = function CanvasGraphicsClosure() {
  6773. // Defines the time the executeOperatorList is going to be executing
  6774. // before it stops and shedules a continue of execution.
  6775. var EXECUTION_TIME = 15;
  6776. // Defines the number of steps before checking the execution time
  6777. var EXECUTION_STEPS = 10;
  6778. function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) {
  6779. this.ctx = canvasCtx;
  6780. this.current = new CanvasExtraState();
  6781. this.stateStack = [];
  6782. this.pendingClip = null;
  6783. this.pendingEOFill = false;
  6784. this.res = null;
  6785. this.xobjs = null;
  6786. this.commonObjs = commonObjs;
  6787. this.objs = objs;
  6788. this.imageLayer = imageLayer;
  6789. this.groupStack = [];
  6790. this.processingType3 = null;
  6791. // Patterns are painted relative to the initial page/form transform, see pdf
  6792. // spec 8.7.2 NOTE 1.
  6793. this.baseTransform = null;
  6794. this.baseTransformStack = [];
  6795. this.groupLevel = 0;
  6796. this.smaskStack = [];
  6797. this.smaskCounter = 0;
  6798. this.tempSMask = null;
  6799. this.cachedCanvases = new CachedCanvases();
  6800. if (canvasCtx) {
  6801. // NOTE: if mozCurrentTransform is polyfilled, then the current state of
  6802. // the transformation must already be set in canvasCtx._transformMatrix.
  6803. addContextCurrentTransform(canvasCtx);
  6804. }
  6805. this.cachedGetSinglePixelWidth = null;
  6806. }
  6807. function putBinaryImageData(ctx, imgData) {
  6808. if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) {
  6809. ctx.putImageData(imgData, 0, 0);
  6810. return;
  6811. }
  6812. // Put the image data to the canvas in chunks, rather than putting the
  6813. // whole image at once. This saves JS memory, because the ImageData object
  6814. // is smaller. It also possibly saves C++ memory within the implementation
  6815. // of putImageData(). (E.g. in Firefox we make two short-lived copies of
  6816. // the data passed to putImageData()). |n| shouldn't be too small, however,
  6817. // because too many putImageData() calls will slow things down.
  6818. //
  6819. // Note: as written, if the last chunk is partial, the putImageData() call
  6820. // will (conceptually) put pixels past the bounds of the canvas. But
  6821. // that's ok; any such pixels are ignored.
  6822. var height = imgData.height, width = imgData.width;
  6823. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6824. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6825. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6826. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6827. var srcPos = 0, destPos;
  6828. var src = imgData.data;
  6829. var dest = chunkImgData.data;
  6830. var i, j, thisChunkHeight, elemsInThisChunk;
  6831. // There are multiple forms in which the pixel data can be passed, and
  6832. // imgData.kind tells us which one this is.
  6833. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) {
  6834. // Grayscale, 1 bit per pixel (i.e. black-and-white).
  6835. var srcLength = src.byteLength;
  6836. var dest32 = HasCanvasTypedArraysCached.value ? new Uint32Array(dest.buffer) : new Uint32ArrayView(dest);
  6837. var dest32DataLength = dest32.length;
  6838. var fullSrcDiff = width + 7 >> 3;
  6839. var white = 0xFFFFFFFF;
  6840. var black = IsLittleEndianCached.value || !HasCanvasTypedArraysCached.value ? 0xFF000000 : 0x000000FF;
  6841. for (i = 0; i < totalChunks; i++) {
  6842. thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6843. destPos = 0;
  6844. for (j = 0; j < thisChunkHeight; j++) {
  6845. var srcDiff = srcLength - srcPos;
  6846. var k = 0;
  6847. var kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
  6848. var kEndUnrolled = kEnd & ~7;
  6849. var mask = 0;
  6850. var srcByte = 0;
  6851. for (; k < kEndUnrolled; k += 8) {
  6852. srcByte = src[srcPos++];
  6853. dest32[destPos++] = srcByte & 128 ? white : black;
  6854. dest32[destPos++] = srcByte & 64 ? white : black;
  6855. dest32[destPos++] = srcByte & 32 ? white : black;
  6856. dest32[destPos++] = srcByte & 16 ? white : black;
  6857. dest32[destPos++] = srcByte & 8 ? white : black;
  6858. dest32[destPos++] = srcByte & 4 ? white : black;
  6859. dest32[destPos++] = srcByte & 2 ? white : black;
  6860. dest32[destPos++] = srcByte & 1 ? white : black;
  6861. }
  6862. for (; k < kEnd; k++) {
  6863. if (mask === 0) {
  6864. srcByte = src[srcPos++];
  6865. mask = 128;
  6866. }
  6867. dest32[destPos++] = srcByte & mask ? white : black;
  6868. mask >>= 1;
  6869. }
  6870. }
  6871. // We ran out of input. Make all remaining pixels transparent.
  6872. while (destPos < dest32DataLength) {
  6873. dest32[destPos++] = 0;
  6874. }
  6875. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6876. }
  6877. } else if (imgData.kind === ImageKind.RGBA_32BPP) {
  6878. // RGBA, 32-bits per pixel.
  6879. j = 0;
  6880. elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
  6881. for (i = 0; i < fullChunks; i++) {
  6882. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6883. srcPos += elemsInThisChunk;
  6884. ctx.putImageData(chunkImgData, 0, j);
  6885. j += FULL_CHUNK_HEIGHT;
  6886. }
  6887. if (i < totalChunks) {
  6888. elemsInThisChunk = width * partialChunkHeight * 4;
  6889. dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
  6890. ctx.putImageData(chunkImgData, 0, j);
  6891. }
  6892. } else if (imgData.kind === ImageKind.RGB_24BPP) {
  6893. // RGB, 24-bits per pixel.
  6894. thisChunkHeight = FULL_CHUNK_HEIGHT;
  6895. elemsInThisChunk = width * thisChunkHeight;
  6896. for (i = 0; i < totalChunks; i++) {
  6897. if (i >= fullChunks) {
  6898. thisChunkHeight = partialChunkHeight;
  6899. elemsInThisChunk = width * thisChunkHeight;
  6900. }
  6901. destPos = 0;
  6902. for (j = elemsInThisChunk; j--;) {
  6903. dest[destPos++] = src[srcPos++];
  6904. dest[destPos++] = src[srcPos++];
  6905. dest[destPos++] = src[srcPos++];
  6906. dest[destPos++] = 255;
  6907. }
  6908. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6909. }
  6910. } else {
  6911. error('bad image kind: ' + imgData.kind);
  6912. }
  6913. }
  6914. function putBinaryImageMask(ctx, imgData) {
  6915. var height = imgData.height, width = imgData.width;
  6916. var partialChunkHeight = height % FULL_CHUNK_HEIGHT;
  6917. var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
  6918. var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
  6919. var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
  6920. var srcPos = 0;
  6921. var src = imgData.data;
  6922. var dest = chunkImgData.data;
  6923. for (var i = 0; i < totalChunks; i++) {
  6924. var thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
  6925. // Expand the mask so it can be used by the canvas. Any required
  6926. // inversion has already been handled.
  6927. var destPos = 3;
  6928. // alpha component offset
  6929. for (var j = 0; j < thisChunkHeight; j++) {
  6930. var mask = 0;
  6931. for (var k = 0; k < width; k++) {
  6932. if (!mask) {
  6933. var elem = src[srcPos++];
  6934. mask = 128;
  6935. }
  6936. dest[destPos] = elem & mask ? 0 : 255;
  6937. destPos += 4;
  6938. mask >>= 1;
  6939. }
  6940. }
  6941. ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
  6942. }
  6943. }
  6944. function copyCtxState(sourceCtx, destCtx) {
  6945. var properties = [
  6946. 'strokeStyle',
  6947. 'fillStyle',
  6948. 'fillRule',
  6949. 'globalAlpha',
  6950. 'lineWidth',
  6951. 'lineCap',
  6952. 'lineJoin',
  6953. 'miterLimit',
  6954. 'globalCompositeOperation',
  6955. 'font'
  6956. ];
  6957. for (var i = 0, ii = properties.length; i < ii; i++) {
  6958. var property = properties[i];
  6959. if (sourceCtx[property] !== undefined) {
  6960. destCtx[property] = sourceCtx[property];
  6961. }
  6962. }
  6963. if (sourceCtx.setLineDash !== undefined) {
  6964. destCtx.setLineDash(sourceCtx.getLineDash());
  6965. destCtx.lineDashOffset = sourceCtx.lineDashOffset;
  6966. }
  6967. }
  6968. function composeSMaskBackdrop(bytes, r0, g0, b0) {
  6969. var length = bytes.length;
  6970. for (var i = 3; i < length; i += 4) {
  6971. var alpha = bytes[i];
  6972. if (alpha === 0) {
  6973. bytes[i - 3] = r0;
  6974. bytes[i - 2] = g0;
  6975. bytes[i - 1] = b0;
  6976. } else if (alpha < 255) {
  6977. var alpha_ = 255 - alpha;
  6978. bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
  6979. bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
  6980. bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
  6981. }
  6982. }
  6983. }
  6984. function composeSMaskAlpha(maskData, layerData, transferMap) {
  6985. var length = maskData.length;
  6986. var scale = 1 / 255;
  6987. for (var i = 3; i < length; i += 4) {
  6988. var alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
  6989. layerData[i] = layerData[i] * alpha * scale | 0;
  6990. }
  6991. }
  6992. function composeSMaskLuminosity(maskData, layerData, transferMap) {
  6993. var length = maskData.length;
  6994. for (var i = 3; i < length; i += 4) {
  6995. var y = maskData[i - 3] * 77 + // * 0.3 / 255 * 0x10000
  6996. maskData[i - 2] * 152 + // * 0.59 ....
  6997. maskData[i - 1] * 28;
  6998. // * 0.11 ....
  6999. layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
  7000. }
  7001. }
  7002. function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap) {
  7003. var hasBackdrop = !!backdrop;
  7004. var r0 = hasBackdrop ? backdrop[0] : 0;
  7005. var g0 = hasBackdrop ? backdrop[1] : 0;
  7006. var b0 = hasBackdrop ? backdrop[2] : 0;
  7007. var composeFn;
  7008. if (subtype === 'Luminosity') {
  7009. composeFn = composeSMaskLuminosity;
  7010. } else {
  7011. composeFn = composeSMaskAlpha;
  7012. }
  7013. // processing image in chunks to save memory
  7014. var PIXELS_TO_PROCESS = 1048576;
  7015. var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
  7016. for (var row = 0; row < height; row += chunkSize) {
  7017. var chunkHeight = Math.min(chunkSize, height - row);
  7018. var maskData = maskCtx.getImageData(0, row, width, chunkHeight);
  7019. var layerData = layerCtx.getImageData(0, row, width, chunkHeight);
  7020. if (hasBackdrop) {
  7021. composeSMaskBackdrop(maskData.data, r0, g0, b0);
  7022. }
  7023. composeFn(maskData.data, layerData.data, transferMap);
  7024. maskCtx.putImageData(layerData, 0, row);
  7025. }
  7026. }
  7027. function composeSMask(ctx, smask, layerCtx) {
  7028. var mask = smask.canvas;
  7029. var maskCtx = smask.context;
  7030. ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY);
  7031. var backdrop = smask.backdrop || null;
  7032. if (!smask.transferMap && WebGLUtils.isEnabled) {
  7033. var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask, {
  7034. subtype: smask.subtype,
  7035. backdrop: backdrop
  7036. });
  7037. ctx.setTransform(1, 0, 0, 1, 0, 0);
  7038. ctx.drawImage(composed, smask.offsetX, smask.offsetY);
  7039. return;
  7040. }
  7041. genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, backdrop, smask.transferMap);
  7042. ctx.drawImage(mask, 0, 0);
  7043. }
  7044. var LINE_CAP_STYLES = [
  7045. 'butt',
  7046. 'round',
  7047. 'square'
  7048. ];
  7049. var LINE_JOIN_STYLES = [
  7050. 'miter',
  7051. 'round',
  7052. 'bevel'
  7053. ];
  7054. var NORMAL_CLIP = {};
  7055. var EO_CLIP = {};
  7056. CanvasGraphics.prototype = {
  7057. beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport, transparency) {
  7058. // For pdfs that use blend modes we have to clear the canvas else certain
  7059. // blend modes can look wrong since we'd be blending with a white
  7060. // backdrop. The problem with a transparent backdrop though is we then
  7061. // don't get sub pixel anti aliasing on text, creating temporary
  7062. // transparent canvas when we have blend modes.
  7063. var width = this.ctx.canvas.width;
  7064. var height = this.ctx.canvas.height;
  7065. this.ctx.save();
  7066. this.ctx.fillStyle = 'rgb(255, 255, 255)';
  7067. this.ctx.fillRect(0, 0, width, height);
  7068. this.ctx.restore();
  7069. if (transparency) {
  7070. var transparentCanvas = this.cachedCanvases.getCanvas('transparent', width, height, true);
  7071. this.compositeCtx = this.ctx;
  7072. this.transparentCanvas = transparentCanvas.canvas;
  7073. this.ctx = transparentCanvas.context;
  7074. this.ctx.save();
  7075. // The transform can be applied before rendering, transferring it to
  7076. // the new canvas.
  7077. this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform);
  7078. }
  7079. this.ctx.save();
  7080. if (transform) {
  7081. this.ctx.transform.apply(this.ctx, transform);
  7082. }
  7083. this.ctx.transform.apply(this.ctx, viewport.transform);
  7084. this.baseTransform = this.ctx.mozCurrentTransform.slice();
  7085. if (this.imageLayer) {
  7086. this.imageLayer.beginLayout();
  7087. }
  7088. },
  7089. executeOperatorList: function CanvasGraphics_executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
  7090. var argsArray = operatorList.argsArray;
  7091. var fnArray = operatorList.fnArray;
  7092. var i = executionStartIdx || 0;
  7093. var argsArrayLen = argsArray.length;
  7094. // Sometimes the OperatorList to execute is empty.
  7095. if (argsArrayLen === i) {
  7096. return i;
  7097. }
  7098. var chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === 'function';
  7099. var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
  7100. var steps = 0;
  7101. var commonObjs = this.commonObjs;
  7102. var objs = this.objs;
  7103. var fnId;
  7104. while (true) {
  7105. if (stepper !== undefined && i === stepper.nextBreakPoint) {
  7106. stepper.breakIt(i, continueCallback);
  7107. return i;
  7108. }
  7109. fnId = fnArray[i];
  7110. if (fnId !== OPS.dependency) {
  7111. this[fnId].apply(this, argsArray[i]);
  7112. } else {
  7113. var deps = argsArray[i];
  7114. for (var n = 0, nn = deps.length; n < nn; n++) {
  7115. var depObjId = deps[n];
  7116. var common = depObjId[0] === 'g' && depObjId[1] === '_';
  7117. var objsPool = common ? commonObjs : objs;
  7118. // If the promise isn't resolved yet, add the continueCallback
  7119. // to the promise and bail out.
  7120. if (!objsPool.isResolved(depObjId)) {
  7121. objsPool.get(depObjId, continueCallback);
  7122. return i;
  7123. }
  7124. }
  7125. }
  7126. i++;
  7127. // If the entire operatorList was executed, stop as were done.
  7128. if (i === argsArrayLen) {
  7129. return i;
  7130. }
  7131. // If the execution took longer then a certain amount of time and
  7132. // `continueCallback` is specified, interrupt the execution.
  7133. if (chunkOperations && ++steps > EXECUTION_STEPS) {
  7134. if (Date.now() > endTime) {
  7135. continueCallback();
  7136. return i;
  7137. }
  7138. steps = 0;
  7139. }
  7140. }
  7141. },
  7142. // If the operatorList isn't executed completely yet OR the execution
  7143. // time was short enough, do another execution round.
  7144. endDrawing: function CanvasGraphics_endDrawing() {
  7145. // Finishing all opened operations such as SMask group painting.
  7146. if (this.current.activeSMask !== null) {
  7147. this.endSMaskGroup();
  7148. }
  7149. this.ctx.restore();
  7150. if (this.transparentCanvas) {
  7151. this.ctx = this.compositeCtx;
  7152. this.ctx.save();
  7153. this.ctx.setTransform(1, 0, 0, 1, 0, 0);
  7154. // Avoid apply transform twice
  7155. this.ctx.drawImage(this.transparentCanvas, 0, 0);
  7156. this.ctx.restore();
  7157. this.transparentCanvas = null;
  7158. }
  7159. this.cachedCanvases.clear();
  7160. WebGLUtils.clear();
  7161. if (this.imageLayer) {
  7162. this.imageLayer.endLayout();
  7163. }
  7164. },
  7165. // Graphics state
  7166. setLineWidth: function CanvasGraphics_setLineWidth(width) {
  7167. this.current.lineWidth = width;
  7168. this.ctx.lineWidth = width;
  7169. },
  7170. setLineCap: function CanvasGraphics_setLineCap(style) {
  7171. this.ctx.lineCap = LINE_CAP_STYLES[style];
  7172. },
  7173. setLineJoin: function CanvasGraphics_setLineJoin(style) {
  7174. this.ctx.lineJoin = LINE_JOIN_STYLES[style];
  7175. },
  7176. setMiterLimit: function CanvasGraphics_setMiterLimit(limit) {
  7177. this.ctx.miterLimit = limit;
  7178. },
  7179. setDash: function CanvasGraphics_setDash(dashArray, dashPhase) {
  7180. var ctx = this.ctx;
  7181. if (ctx.setLineDash !== undefined) {
  7182. ctx.setLineDash(dashArray);
  7183. ctx.lineDashOffset = dashPhase;
  7184. }
  7185. },
  7186. setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {
  7187. },
  7188. setFlatness: function CanvasGraphics_setFlatness(flatness) {
  7189. },
  7190. setGState: function CanvasGraphics_setGState(states) {
  7191. for (var i = 0, ii = states.length; i < ii; i++) {
  7192. var state = states[i];
  7193. var key = state[0];
  7194. var value = state[1];
  7195. switch (key) {
  7196. case 'LW':
  7197. this.setLineWidth(value);
  7198. break;
  7199. case 'LC':
  7200. this.setLineCap(value);
  7201. break;
  7202. case 'LJ':
  7203. this.setLineJoin(value);
  7204. break;
  7205. case 'ML':
  7206. this.setMiterLimit(value);
  7207. break;
  7208. case 'D':
  7209. this.setDash(value[0], value[1]);
  7210. break;
  7211. case 'RI':
  7212. this.setRenderingIntent(value);
  7213. break;
  7214. case 'FL':
  7215. this.setFlatness(value);
  7216. break;
  7217. case 'Font':
  7218. this.setFont(value[0], value[1]);
  7219. break;
  7220. case 'CA':
  7221. this.current.strokeAlpha = state[1];
  7222. break;
  7223. case 'ca':
  7224. this.current.fillAlpha = state[1];
  7225. this.ctx.globalAlpha = state[1];
  7226. break;
  7227. case 'BM':
  7228. if (value && value.name && value.name !== 'Normal') {
  7229. var mode = value.name.replace(/([A-Z])/g, function (c) {
  7230. return '-' + c.toLowerCase();
  7231. }).substring(1);
  7232. this.ctx.globalCompositeOperation = mode;
  7233. if (this.ctx.globalCompositeOperation !== mode) {
  7234. warn('globalCompositeOperation "' + mode + '" is not supported');
  7235. }
  7236. } else {
  7237. this.ctx.globalCompositeOperation = 'source-over';
  7238. }
  7239. break;
  7240. case 'SMask':
  7241. if (this.current.activeSMask) {
  7242. // If SMask is currrenly used, it needs to be suspended or
  7243. // finished. Suspend only makes sense when at least one save()
  7244. // was performed and state needs to be reverted on restore().
  7245. if (this.stateStack.length > 0 && this.stateStack[this.stateStack.length - 1].activeSMask === this.current.activeSMask) {
  7246. this.suspendSMaskGroup();
  7247. } else {
  7248. this.endSMaskGroup();
  7249. }
  7250. }
  7251. this.current.activeSMask = value ? this.tempSMask : null;
  7252. if (this.current.activeSMask) {
  7253. this.beginSMaskGroup();
  7254. }
  7255. this.tempSMask = null;
  7256. break;
  7257. }
  7258. }
  7259. },
  7260. beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() {
  7261. var activeSMask = this.current.activeSMask;
  7262. var drawnWidth = activeSMask.canvas.width;
  7263. var drawnHeight = activeSMask.canvas.height;
  7264. var cacheId = 'smaskGroupAt' + this.groupLevel;
  7265. var scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  7266. var currentCtx = this.ctx;
  7267. var currentTransform = currentCtx.mozCurrentTransform;
  7268. this.ctx.save();
  7269. var groupCtx = scratchCanvas.context;
  7270. groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
  7271. groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
  7272. groupCtx.transform.apply(groupCtx, currentTransform);
  7273. activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse;
  7274. copyCtxState(currentCtx, groupCtx);
  7275. this.ctx = groupCtx;
  7276. this.setGState([
  7277. [
  7278. 'BM',
  7279. 'Normal'
  7280. ],
  7281. [
  7282. 'ca',
  7283. 1
  7284. ],
  7285. [
  7286. 'CA',
  7287. 1
  7288. ]
  7289. ]);
  7290. this.groupStack.push(currentCtx);
  7291. this.groupLevel++;
  7292. },
  7293. suspendSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  7294. // Similar to endSMaskGroup, the intermediate canvas has to be composed
  7295. // and future ctx state restored.
  7296. var groupCtx = this.ctx;
  7297. this.groupLevel--;
  7298. this.ctx = this.groupStack.pop();
  7299. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  7300. this.ctx.restore();
  7301. this.ctx.save();
  7302. // save is needed since SMask will be resumed.
  7303. copyCtxState(groupCtx, this.ctx);
  7304. // Saving state for resuming.
  7305. this.current.resumeSMaskCtx = groupCtx;
  7306. // Transform was changed in the SMask canvas, reflecting this change on
  7307. // this.ctx.
  7308. var deltaTransform = Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
  7309. this.ctx.transform.apply(this.ctx, deltaTransform);
  7310. // SMask was composed, the results at the groupCtx can be cleared.
  7311. groupCtx.save();
  7312. groupCtx.setTransform(1, 0, 0, 1, 0, 0);
  7313. groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height);
  7314. groupCtx.restore();
  7315. },
  7316. resumeSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  7317. // Resuming state saved by suspendSMaskGroup. We don't need to restore
  7318. // any groupCtx state since restore() command (the only caller) will do
  7319. // that for us. See also beginSMaskGroup.
  7320. var groupCtx = this.current.resumeSMaskCtx;
  7321. var currentCtx = this.ctx;
  7322. this.ctx = groupCtx;
  7323. this.groupStack.push(currentCtx);
  7324. this.groupLevel++;
  7325. },
  7326. endSMaskGroup: function CanvasGraphics_endSMaskGroup() {
  7327. var groupCtx = this.ctx;
  7328. this.groupLevel--;
  7329. this.ctx = this.groupStack.pop();
  7330. composeSMask(this.ctx, this.current.activeSMask, groupCtx);
  7331. this.ctx.restore();
  7332. copyCtxState(groupCtx, this.ctx);
  7333. // Transform was changed in the SMask canvas, reflecting this change on
  7334. // this.ctx.
  7335. var deltaTransform = Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
  7336. this.ctx.transform.apply(this.ctx, deltaTransform);
  7337. },
  7338. save: function CanvasGraphics_save() {
  7339. this.ctx.save();
  7340. var old = this.current;
  7341. this.stateStack.push(old);
  7342. this.current = old.clone();
  7343. this.current.resumeSMaskCtx = null;
  7344. },
  7345. restore: function CanvasGraphics_restore() {
  7346. // SMask was suspended, we just need to resume it.
  7347. if (this.current.resumeSMaskCtx) {
  7348. this.resumeSMaskGroup();
  7349. }
  7350. // SMask has to be finished once there is no states that are using the
  7351. // same SMask.
  7352. if (this.current.activeSMask !== null && (this.stateStack.length === 0 || this.stateStack[this.stateStack.length - 1].activeSMask !== this.current.activeSMask)) {
  7353. this.endSMaskGroup();
  7354. }
  7355. if (this.stateStack.length !== 0) {
  7356. this.current = this.stateStack.pop();
  7357. this.ctx.restore();
  7358. // Ensure that the clipping path is reset (fixes issue6413.pdf).
  7359. this.pendingClip = null;
  7360. this.cachedGetSinglePixelWidth = null;
  7361. }
  7362. },
  7363. transform: function CanvasGraphics_transform(a, b, c, d, e, f) {
  7364. this.ctx.transform(a, b, c, d, e, f);
  7365. this.cachedGetSinglePixelWidth = null;
  7366. },
  7367. // Path
  7368. constructPath: function CanvasGraphics_constructPath(ops, args) {
  7369. var ctx = this.ctx;
  7370. var current = this.current;
  7371. var x = current.x, y = current.y;
  7372. for (var i = 0, j = 0, ii = ops.length; i < ii; i++) {
  7373. switch (ops[i] | 0) {
  7374. case OPS.rectangle:
  7375. x = args[j++];
  7376. y = args[j++];
  7377. var width = args[j++];
  7378. var height = args[j++];
  7379. if (width === 0) {
  7380. width = this.getSinglePixelWidth();
  7381. }
  7382. if (height === 0) {
  7383. height = this.getSinglePixelWidth();
  7384. }
  7385. var xw = x + width;
  7386. var yh = y + height;
  7387. this.ctx.moveTo(x, y);
  7388. this.ctx.lineTo(xw, y);
  7389. this.ctx.lineTo(xw, yh);
  7390. this.ctx.lineTo(x, yh);
  7391. this.ctx.lineTo(x, y);
  7392. this.ctx.closePath();
  7393. break;
  7394. case OPS.moveTo:
  7395. x = args[j++];
  7396. y = args[j++];
  7397. ctx.moveTo(x, y);
  7398. break;
  7399. case OPS.lineTo:
  7400. x = args[j++];
  7401. y = args[j++];
  7402. ctx.lineTo(x, y);
  7403. break;
  7404. case OPS.curveTo:
  7405. x = args[j + 4];
  7406. y = args[j + 5];
  7407. ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
  7408. j += 6;
  7409. break;
  7410. case OPS.curveTo2:
  7411. ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
  7412. x = args[j + 2];
  7413. y = args[j + 3];
  7414. j += 4;
  7415. break;
  7416. case OPS.curveTo3:
  7417. x = args[j + 2];
  7418. y = args[j + 3];
  7419. ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
  7420. j += 4;
  7421. break;
  7422. case OPS.closePath:
  7423. ctx.closePath();
  7424. break;
  7425. }
  7426. }
  7427. current.setCurrentPoint(x, y);
  7428. },
  7429. closePath: function CanvasGraphics_closePath() {
  7430. this.ctx.closePath();
  7431. },
  7432. stroke: function CanvasGraphics_stroke(consumePath) {
  7433. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  7434. var ctx = this.ctx;
  7435. var strokeColor = this.current.strokeColor;
  7436. // Prevent drawing too thin lines by enforcing a minimum line width.
  7437. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR, this.current.lineWidth);
  7438. // For stroke we want to temporarily change the global alpha to the
  7439. // stroking alpha.
  7440. ctx.globalAlpha = this.current.strokeAlpha;
  7441. if (strokeColor && strokeColor.hasOwnProperty('type') && strokeColor.type === 'Pattern') {
  7442. // for patterns, we transform to pattern space, calculate
  7443. // the pattern, call stroke, and restore to user space
  7444. ctx.save();
  7445. ctx.strokeStyle = strokeColor.getPattern(ctx, this);
  7446. ctx.stroke();
  7447. ctx.restore();
  7448. } else {
  7449. ctx.stroke();
  7450. }
  7451. if (consumePath) {
  7452. this.consumePath();
  7453. }
  7454. // Restore the global alpha to the fill alpha
  7455. ctx.globalAlpha = this.current.fillAlpha;
  7456. },
  7457. closeStroke: function CanvasGraphics_closeStroke() {
  7458. this.closePath();
  7459. this.stroke();
  7460. },
  7461. fill: function CanvasGraphics_fill(consumePath) {
  7462. consumePath = typeof consumePath !== 'undefined' ? consumePath : true;
  7463. var ctx = this.ctx;
  7464. var fillColor = this.current.fillColor;
  7465. var isPatternFill = this.current.patternFill;
  7466. var needRestore = false;
  7467. if (isPatternFill) {
  7468. ctx.save();
  7469. if (this.baseTransform) {
  7470. ctx.setTransform.apply(ctx, this.baseTransform);
  7471. }
  7472. ctx.fillStyle = fillColor.getPattern(ctx, this);
  7473. needRestore = true;
  7474. }
  7475. if (this.pendingEOFill) {
  7476. if (ctx.mozFillRule !== undefined) {
  7477. ctx.mozFillRule = 'evenodd';
  7478. ctx.fill();
  7479. ctx.mozFillRule = 'nonzero';
  7480. } else {
  7481. ctx.fill('evenodd');
  7482. }
  7483. this.pendingEOFill = false;
  7484. } else {
  7485. ctx.fill();
  7486. }
  7487. if (needRestore) {
  7488. ctx.restore();
  7489. }
  7490. if (consumePath) {
  7491. this.consumePath();
  7492. }
  7493. },
  7494. eoFill: function CanvasGraphics_eoFill() {
  7495. this.pendingEOFill = true;
  7496. this.fill();
  7497. },
  7498. fillStroke: function CanvasGraphics_fillStroke() {
  7499. this.fill(false);
  7500. this.stroke(false);
  7501. this.consumePath();
  7502. },
  7503. eoFillStroke: function CanvasGraphics_eoFillStroke() {
  7504. this.pendingEOFill = true;
  7505. this.fillStroke();
  7506. },
  7507. closeFillStroke: function CanvasGraphics_closeFillStroke() {
  7508. this.closePath();
  7509. this.fillStroke();
  7510. },
  7511. closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() {
  7512. this.pendingEOFill = true;
  7513. this.closePath();
  7514. this.fillStroke();
  7515. },
  7516. endPath: function CanvasGraphics_endPath() {
  7517. this.consumePath();
  7518. },
  7519. // Clipping
  7520. clip: function CanvasGraphics_clip() {
  7521. this.pendingClip = NORMAL_CLIP;
  7522. },
  7523. eoClip: function CanvasGraphics_eoClip() {
  7524. this.pendingClip = EO_CLIP;
  7525. },
  7526. // Text
  7527. beginText: function CanvasGraphics_beginText() {
  7528. this.current.textMatrix = IDENTITY_MATRIX;
  7529. this.current.textMatrixScale = 1;
  7530. this.current.x = this.current.lineX = 0;
  7531. this.current.y = this.current.lineY = 0;
  7532. },
  7533. endText: function CanvasGraphics_endText() {
  7534. var paths = this.pendingTextPaths;
  7535. var ctx = this.ctx;
  7536. if (paths === undefined) {
  7537. ctx.beginPath();
  7538. return;
  7539. }
  7540. ctx.save();
  7541. ctx.beginPath();
  7542. for (var i = 0; i < paths.length; i++) {
  7543. var path = paths[i];
  7544. ctx.setTransform.apply(ctx, path.transform);
  7545. ctx.translate(path.x, path.y);
  7546. path.addToPath(ctx, path.fontSize);
  7547. }
  7548. ctx.restore();
  7549. ctx.clip();
  7550. ctx.beginPath();
  7551. delete this.pendingTextPaths;
  7552. },
  7553. setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) {
  7554. this.current.charSpacing = spacing;
  7555. },
  7556. setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) {
  7557. this.current.wordSpacing = spacing;
  7558. },
  7559. setHScale: function CanvasGraphics_setHScale(scale) {
  7560. this.current.textHScale = scale / 100;
  7561. },
  7562. setLeading: function CanvasGraphics_setLeading(leading) {
  7563. this.current.leading = -leading;
  7564. },
  7565. setFont: function CanvasGraphics_setFont(fontRefName, size) {
  7566. var fontObj = this.commonObjs.get(fontRefName);
  7567. var current = this.current;
  7568. if (!fontObj) {
  7569. error('Can\'t find font for ' + fontRefName);
  7570. }
  7571. current.fontMatrix = fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX;
  7572. // A valid matrix needs all main diagonal elements to be non-zero
  7573. // This also ensures we bypass FF bugzilla bug #719844.
  7574. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
  7575. warn('Invalid font matrix for font ' + fontRefName);
  7576. }
  7577. // The spec for Tf (setFont) says that 'size' specifies the font 'scale',
  7578. // and in some docs this can be negative (inverted x-y axes).
  7579. if (size < 0) {
  7580. size = -size;
  7581. current.fontDirection = -1;
  7582. } else {
  7583. current.fontDirection = 1;
  7584. }
  7585. this.current.font = fontObj;
  7586. this.current.fontSize = size;
  7587. if (fontObj.isType3Font) {
  7588. return;
  7589. }
  7590. // we don't need ctx.font for Type3 fonts
  7591. var name = fontObj.loadedName || 'sans-serif';
  7592. var bold = fontObj.black ? fontObj.bold ? '900' : 'bold' : fontObj.bold ? 'bold' : 'normal';
  7593. var italic = fontObj.italic ? 'italic' : 'normal';
  7594. var typeface = '"' + name + '", ' + fontObj.fallbackName;
  7595. // Some font backends cannot handle fonts below certain size.
  7596. // Keeping the font at minimal size and using the fontSizeScale to change
  7597. // the current transformation matrix before the fillText/strokeText.
  7598. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227
  7599. var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE : size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size;
  7600. this.current.fontSizeScale = size / browserFontSize;
  7601. var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface;
  7602. this.ctx.font = rule;
  7603. },
  7604. setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) {
  7605. this.current.textRenderingMode = mode;
  7606. },
  7607. setTextRise: function CanvasGraphics_setTextRise(rise) {
  7608. this.current.textRise = rise;
  7609. },
  7610. moveText: function CanvasGraphics_moveText(x, y) {
  7611. this.current.x = this.current.lineX += x;
  7612. this.current.y = this.current.lineY += y;
  7613. },
  7614. setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) {
  7615. this.setLeading(-y);
  7616. this.moveText(x, y);
  7617. },
  7618. setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) {
  7619. this.current.textMatrix = [
  7620. a,
  7621. b,
  7622. c,
  7623. d,
  7624. e,
  7625. f
  7626. ];
  7627. this.current.textMatrixScale = Math.sqrt(a * a + b * b);
  7628. this.current.x = this.current.lineX = 0;
  7629. this.current.y = this.current.lineY = 0;
  7630. },
  7631. nextLine: function CanvasGraphics_nextLine() {
  7632. this.moveText(0, this.current.leading);
  7633. },
  7634. paintChar: function CanvasGraphics_paintChar(character, x, y) {
  7635. var ctx = this.ctx;
  7636. var current = this.current;
  7637. var font = current.font;
  7638. var textRenderingMode = current.textRenderingMode;
  7639. var fontSize = current.fontSize / current.fontSizeScale;
  7640. var fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
  7641. var isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG);
  7642. var addToPath;
  7643. if (font.disableFontFace || isAddToPathSet) {
  7644. addToPath = font.getPathGenerator(this.commonObjs, character);
  7645. }
  7646. if (font.disableFontFace) {
  7647. ctx.save();
  7648. ctx.translate(x, y);
  7649. ctx.beginPath();
  7650. addToPath(ctx, fontSize);
  7651. if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7652. ctx.fill();
  7653. }
  7654. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7655. ctx.stroke();
  7656. }
  7657. ctx.restore();
  7658. } else {
  7659. if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7660. ctx.fillText(character, x, y);
  7661. }
  7662. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7663. ctx.strokeText(character, x, y);
  7664. }
  7665. }
  7666. if (isAddToPathSet) {
  7667. var paths = this.pendingTextPaths || (this.pendingTextPaths = []);
  7668. paths.push({
  7669. transform: ctx.mozCurrentTransform,
  7670. x: x,
  7671. y: y,
  7672. fontSize: fontSize,
  7673. addToPath: addToPath
  7674. });
  7675. }
  7676. },
  7677. get isFontSubpixelAAEnabled() {
  7678. // Checks if anti-aliasing is enabled when scaled text is painted.
  7679. // On Windows GDI scaled fonts looks bad.
  7680. var ctx = document.createElement('canvas').getContext('2d');
  7681. ctx.scale(1.5, 1);
  7682. ctx.fillText('I', 0, 10);
  7683. var data = ctx.getImageData(0, 0, 10, 10).data;
  7684. var enabled = false;
  7685. for (var i = 3; i < data.length; i += 4) {
  7686. if (data[i] > 0 && data[i] < 255) {
  7687. enabled = true;
  7688. break;
  7689. }
  7690. }
  7691. return shadow(this, 'isFontSubpixelAAEnabled', enabled);
  7692. },
  7693. showText: function CanvasGraphics_showText(glyphs) {
  7694. var current = this.current;
  7695. var font = current.font;
  7696. if (font.isType3Font) {
  7697. return this.showType3Text(glyphs);
  7698. }
  7699. var fontSize = current.fontSize;
  7700. if (fontSize === 0) {
  7701. return;
  7702. }
  7703. var ctx = this.ctx;
  7704. var fontSizeScale = current.fontSizeScale;
  7705. var charSpacing = current.charSpacing;
  7706. var wordSpacing = current.wordSpacing;
  7707. var fontDirection = current.fontDirection;
  7708. var textHScale = current.textHScale * fontDirection;
  7709. var glyphsLength = glyphs.length;
  7710. var vertical = font.vertical;
  7711. var spacingDir = vertical ? 1 : -1;
  7712. var defaultVMetrics = font.defaultVMetrics;
  7713. var widthAdvanceScale = fontSize * current.fontMatrix[0];
  7714. var simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace;
  7715. ctx.save();
  7716. ctx.transform.apply(ctx, current.textMatrix);
  7717. ctx.translate(current.x, current.y + current.textRise);
  7718. if (current.patternFill) {
  7719. // TODO: Some shading patterns are not applied correctly to text,
  7720. // e.g. issues 3988 and 5432, and ShowText-ShadingPattern.pdf.
  7721. ctx.fillStyle = current.fillColor.getPattern(ctx, this);
  7722. }
  7723. if (fontDirection > 0) {
  7724. ctx.scale(textHScale, -1);
  7725. } else {
  7726. ctx.scale(textHScale, 1);
  7727. }
  7728. var lineWidth = current.lineWidth;
  7729. var scale = current.textMatrixScale;
  7730. if (scale === 0 || lineWidth === 0) {
  7731. var fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK;
  7732. if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
  7733. this.cachedGetSinglePixelWidth = null;
  7734. lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR;
  7735. }
  7736. } else {
  7737. lineWidth /= scale;
  7738. }
  7739. if (fontSizeScale !== 1.0) {
  7740. ctx.scale(fontSizeScale, fontSizeScale);
  7741. lineWidth /= fontSizeScale;
  7742. }
  7743. ctx.lineWidth = lineWidth;
  7744. var x = 0, i;
  7745. for (i = 0; i < glyphsLength; ++i) {
  7746. var glyph = glyphs[i];
  7747. if (isNum(glyph)) {
  7748. x += spacingDir * glyph * fontSize / 1000;
  7749. continue;
  7750. }
  7751. var restoreNeeded = false;
  7752. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7753. var character = glyph.fontChar;
  7754. var accent = glyph.accent;
  7755. var scaledX, scaledY, scaledAccentX, scaledAccentY;
  7756. var width = glyph.width;
  7757. if (vertical) {
  7758. var vmetric, vx, vy;
  7759. vmetric = glyph.vmetric || defaultVMetrics;
  7760. vx = glyph.vmetric ? vmetric[1] : width * 0.5;
  7761. vx = -vx * widthAdvanceScale;
  7762. vy = vmetric[2] * widthAdvanceScale;
  7763. width = vmetric ? -vmetric[0] : width;
  7764. scaledX = vx / fontSizeScale;
  7765. scaledY = (x + vy) / fontSizeScale;
  7766. } else {
  7767. scaledX = x / fontSizeScale;
  7768. scaledY = 0;
  7769. }
  7770. if (font.remeasure && width > 0) {
  7771. // Some standard fonts may not have the exact width: rescale per
  7772. // character if measured width is greater than expected glyph width
  7773. // and subpixel-aa is enabled, otherwise just center the glyph.
  7774. var measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
  7775. if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
  7776. var characterScaleX = width / measuredWidth;
  7777. restoreNeeded = true;
  7778. ctx.save();
  7779. ctx.scale(characterScaleX, 1);
  7780. scaledX /= characterScaleX;
  7781. } else if (width !== measuredWidth) {
  7782. scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
  7783. }
  7784. }
  7785. // Only attempt to draw the glyph if it is actually in the embedded font
  7786. // file or if there isn't a font file so the fallback font is shown.
  7787. if (glyph.isInFont || font.missingFile) {
  7788. if (simpleFillText && !accent) {
  7789. // common case
  7790. ctx.fillText(character, scaledX, scaledY);
  7791. } else {
  7792. this.paintChar(character, scaledX, scaledY);
  7793. if (accent) {
  7794. scaledAccentX = scaledX + accent.offset.x / fontSizeScale;
  7795. scaledAccentY = scaledY - accent.offset.y / fontSizeScale;
  7796. this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY);
  7797. }
  7798. }
  7799. }
  7800. var charWidth = width * widthAdvanceScale + spacing * fontDirection;
  7801. x += charWidth;
  7802. if (restoreNeeded) {
  7803. ctx.restore();
  7804. }
  7805. }
  7806. if (vertical) {
  7807. current.y -= x * textHScale;
  7808. } else {
  7809. current.x += x * textHScale;
  7810. }
  7811. ctx.restore();
  7812. },
  7813. showType3Text: function CanvasGraphics_showType3Text(glyphs) {
  7814. // Type3 fonts - each glyph is a "mini-PDF"
  7815. var ctx = this.ctx;
  7816. var current = this.current;
  7817. var font = current.font;
  7818. var fontSize = current.fontSize;
  7819. var fontDirection = current.fontDirection;
  7820. var spacingDir = font.vertical ? 1 : -1;
  7821. var charSpacing = current.charSpacing;
  7822. var wordSpacing = current.wordSpacing;
  7823. var textHScale = current.textHScale * fontDirection;
  7824. var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX;
  7825. var glyphsLength = glyphs.length;
  7826. var isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE;
  7827. var i, glyph, width, spacingLength;
  7828. if (isTextInvisible || fontSize === 0) {
  7829. return;
  7830. }
  7831. this.cachedGetSinglePixelWidth = null;
  7832. ctx.save();
  7833. ctx.transform.apply(ctx, current.textMatrix);
  7834. ctx.translate(current.x, current.y);
  7835. ctx.scale(textHScale, fontDirection);
  7836. for (i = 0; i < glyphsLength; ++i) {
  7837. glyph = glyphs[i];
  7838. if (isNum(glyph)) {
  7839. spacingLength = spacingDir * glyph * fontSize / 1000;
  7840. this.ctx.translate(spacingLength, 0);
  7841. current.x += spacingLength * textHScale;
  7842. continue;
  7843. }
  7844. var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
  7845. var operatorList = font.charProcOperatorList[glyph.operatorListId];
  7846. if (!operatorList) {
  7847. warn('Type3 character \"' + glyph.operatorListId + '\" is not available');
  7848. continue;
  7849. }
  7850. this.processingType3 = glyph;
  7851. this.save();
  7852. ctx.scale(fontSize, fontSize);
  7853. ctx.transform.apply(ctx, fontMatrix);
  7854. this.executeOperatorList(operatorList);
  7855. this.restore();
  7856. var transformed = Util.applyTransform([
  7857. glyph.width,
  7858. 0
  7859. ], fontMatrix);
  7860. width = transformed[0] * fontSize + spacing;
  7861. ctx.translate(width, 0);
  7862. current.x += width * textHScale;
  7863. }
  7864. ctx.restore();
  7865. this.processingType3 = null;
  7866. },
  7867. // Type3 fonts
  7868. setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) {
  7869. },
  7870. setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
  7871. // TODO According to the spec we're also suppose to ignore any operators
  7872. // that set color or include images while processing this type3 font.
  7873. this.ctx.rect(llx, lly, urx - llx, ury - lly);
  7874. this.clip();
  7875. this.endPath();
  7876. },
  7877. // Color
  7878. getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) {
  7879. var pattern;
  7880. if (IR[0] === 'TilingPattern') {
  7881. var color = IR[1];
  7882. var baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice();
  7883. var self = this;
  7884. var canvasGraphicsFactory = {
  7885. createCanvasGraphics: function (ctx) {
  7886. return new CanvasGraphics(ctx, self.commonObjs, self.objs);
  7887. }
  7888. };
  7889. pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
  7890. } else {
  7891. pattern = getShadingPatternFromIR(IR);
  7892. }
  7893. return pattern;
  7894. },
  7895. setStrokeColorN: function CanvasGraphics_setStrokeColorN()
  7896. /*...*/
  7897. {
  7898. this.current.strokeColor = this.getColorN_Pattern(arguments);
  7899. },
  7900. setFillColorN: function CanvasGraphics_setFillColorN()
  7901. /*...*/
  7902. {
  7903. this.current.fillColor = this.getColorN_Pattern(arguments);
  7904. this.current.patternFill = true;
  7905. },
  7906. setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) {
  7907. var color = Util.makeCssRgb(r, g, b);
  7908. this.ctx.strokeStyle = color;
  7909. this.current.strokeColor = color;
  7910. },
  7911. setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) {
  7912. var color = Util.makeCssRgb(r, g, b);
  7913. this.ctx.fillStyle = color;
  7914. this.current.fillColor = color;
  7915. this.current.patternFill = false;
  7916. },
  7917. shadingFill: function CanvasGraphics_shadingFill(patternIR) {
  7918. var ctx = this.ctx;
  7919. this.save();
  7920. var pattern = getShadingPatternFromIR(patternIR);
  7921. ctx.fillStyle = pattern.getPattern(ctx, this, true);
  7922. var inv = ctx.mozCurrentTransformInverse;
  7923. if (inv) {
  7924. var canvas = ctx.canvas;
  7925. var width = canvas.width;
  7926. var height = canvas.height;
  7927. var bl = Util.applyTransform([
  7928. 0,
  7929. 0
  7930. ], inv);
  7931. var br = Util.applyTransform([
  7932. 0,
  7933. height
  7934. ], inv);
  7935. var ul = Util.applyTransform([
  7936. width,
  7937. 0
  7938. ], inv);
  7939. var ur = Util.applyTransform([
  7940. width,
  7941. height
  7942. ], inv);
  7943. var x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
  7944. var y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
  7945. var x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
  7946. var y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
  7947. this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
  7948. } else {
  7949. // HACK to draw the gradient onto an infinite rectangle.
  7950. // PDF gradients are drawn across the entire image while
  7951. // Canvas only allows gradients to be drawn in a rectangle
  7952. // The following bug should allow us to remove this.
  7953. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884
  7954. this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
  7955. }
  7956. this.restore();
  7957. },
  7958. // Images
  7959. beginInlineImage: function CanvasGraphics_beginInlineImage() {
  7960. error('Should not call beginInlineImage');
  7961. },
  7962. beginImageData: function CanvasGraphics_beginImageData() {
  7963. error('Should not call beginImageData');
  7964. },
  7965. paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix, bbox) {
  7966. this.save();
  7967. this.baseTransformStack.push(this.baseTransform);
  7968. if (isArray(matrix) && 6 === matrix.length) {
  7969. this.transform.apply(this, matrix);
  7970. }
  7971. this.baseTransform = this.ctx.mozCurrentTransform;
  7972. if (isArray(bbox) && 4 === bbox.length) {
  7973. var width = bbox[2] - bbox[0];
  7974. var height = bbox[3] - bbox[1];
  7975. this.ctx.rect(bbox[0], bbox[1], width, height);
  7976. this.clip();
  7977. this.endPath();
  7978. }
  7979. },
  7980. paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() {
  7981. this.restore();
  7982. this.baseTransform = this.baseTransformStack.pop();
  7983. },
  7984. beginGroup: function CanvasGraphics_beginGroup(group) {
  7985. this.save();
  7986. var currentCtx = this.ctx;
  7987. // TODO non-isolated groups - according to Rik at adobe non-isolated
  7988. // group results aren't usually that different and they even have tools
  7989. // that ignore this setting. Notes from Rik on implementing:
  7990. // - When you encounter an transparency group, create a new canvas with
  7991. // the dimensions of the bbox
  7992. // - copy the content from the previous canvas to the new canvas
  7993. // - draw as usual
  7994. // - remove the backdrop alpha:
  7995. // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha
  7996. // value of your transparency group and 'alphaBackdrop' the alpha of the
  7997. // backdrop
  7998. // - remove background color:
  7999. // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew)
  8000. if (!group.isolated) {
  8001. info('TODO: Support non-isolated groups.');
  8002. }
  8003. // TODO knockout - supposedly possible with the clever use of compositing
  8004. // modes.
  8005. if (group.knockout) {
  8006. warn('Knockout groups not supported.');
  8007. }
  8008. var currentTransform = currentCtx.mozCurrentTransform;
  8009. if (group.matrix) {
  8010. currentCtx.transform.apply(currentCtx, group.matrix);
  8011. }
  8012. assert(group.bbox, 'Bounding box is required.');
  8013. // Based on the current transform figure out how big the bounding box
  8014. // will actually be.
  8015. var bounds = Util.getAxialAlignedBoundingBox(group.bbox, currentCtx.mozCurrentTransform);
  8016. // Clip the bounding box to the current canvas.
  8017. var canvasBounds = [
  8018. 0,
  8019. 0,
  8020. currentCtx.canvas.width,
  8021. currentCtx.canvas.height
  8022. ];
  8023. bounds = Util.intersect(bounds, canvasBounds) || [
  8024. 0,
  8025. 0,
  8026. 0,
  8027. 0
  8028. ];
  8029. // Use ceil in case we're between sizes so we don't create canvas that is
  8030. // too small and make the canvas at least 1x1 pixels.
  8031. var offsetX = Math.floor(bounds[0]);
  8032. var offsetY = Math.floor(bounds[1]);
  8033. var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
  8034. var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
  8035. var scaleX = 1, scaleY = 1;
  8036. if (drawnWidth > MAX_GROUP_SIZE) {
  8037. scaleX = drawnWidth / MAX_GROUP_SIZE;
  8038. drawnWidth = MAX_GROUP_SIZE;
  8039. }
  8040. if (drawnHeight > MAX_GROUP_SIZE) {
  8041. scaleY = drawnHeight / MAX_GROUP_SIZE;
  8042. drawnHeight = MAX_GROUP_SIZE;
  8043. }
  8044. var cacheId = 'groupAt' + this.groupLevel;
  8045. if (group.smask) {
  8046. // Using two cache entries is case if masks are used one after another.
  8047. cacheId += '_smask_' + this.smaskCounter++ % 2;
  8048. }
  8049. var scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
  8050. var groupCtx = scratchCanvas.context;
  8051. // Since we created a new canvas that is just the size of the bounding box
  8052. // we have to translate the group ctx.
  8053. groupCtx.scale(1 / scaleX, 1 / scaleY);
  8054. groupCtx.translate(-offsetX, -offsetY);
  8055. groupCtx.transform.apply(groupCtx, currentTransform);
  8056. if (group.smask) {
  8057. // Saving state and cached mask to be used in setGState.
  8058. this.smaskStack.push({
  8059. canvas: scratchCanvas.canvas,
  8060. context: groupCtx,
  8061. offsetX: offsetX,
  8062. offsetY: offsetY,
  8063. scaleX: scaleX,
  8064. scaleY: scaleY,
  8065. subtype: group.smask.subtype,
  8066. backdrop: group.smask.backdrop,
  8067. transferMap: group.smask.transferMap || null,
  8068. startTransformInverse: null
  8069. });
  8070. } else
  8071. // used during suspend operation
  8072. {
  8073. // Setup the current ctx so when the group is popped we draw it at the
  8074. // right location.
  8075. currentCtx.setTransform(1, 0, 0, 1, 0, 0);
  8076. currentCtx.translate(offsetX, offsetY);
  8077. currentCtx.scale(scaleX, scaleY);
  8078. }
  8079. // The transparency group inherits all off the current graphics state
  8080. // except the blend mode, soft mask, and alpha constants.
  8081. copyCtxState(currentCtx, groupCtx);
  8082. this.ctx = groupCtx;
  8083. this.setGState([
  8084. [
  8085. 'BM',
  8086. 'Normal'
  8087. ],
  8088. [
  8089. 'ca',
  8090. 1
  8091. ],
  8092. [
  8093. 'CA',
  8094. 1
  8095. ]
  8096. ]);
  8097. this.groupStack.push(currentCtx);
  8098. this.groupLevel++;
  8099. // Reseting mask state, masks will be applied on restore of the group.
  8100. this.current.activeSMask = null;
  8101. },
  8102. endGroup: function CanvasGraphics_endGroup(group) {
  8103. this.groupLevel--;
  8104. var groupCtx = this.ctx;
  8105. this.ctx = this.groupStack.pop();
  8106. // Turn off image smoothing to avoid sub pixel interpolation which can
  8107. // look kind of blurry for some pdfs.
  8108. if (this.ctx.imageSmoothingEnabled !== undefined) {
  8109. this.ctx.imageSmoothingEnabled = false;
  8110. } else {
  8111. this.ctx.mozImageSmoothingEnabled = false;
  8112. }
  8113. if (group.smask) {
  8114. this.tempSMask = this.smaskStack.pop();
  8115. } else {
  8116. this.ctx.drawImage(groupCtx.canvas, 0, 0);
  8117. }
  8118. this.restore();
  8119. },
  8120. beginAnnotations: function CanvasGraphics_beginAnnotations() {
  8121. this.save();
  8122. this.current = new CanvasExtraState();
  8123. if (this.baseTransform) {
  8124. this.ctx.setTransform.apply(this.ctx, this.baseTransform);
  8125. }
  8126. },
  8127. endAnnotations: function CanvasGraphics_endAnnotations() {
  8128. this.restore();
  8129. },
  8130. beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform, matrix) {
  8131. this.save();
  8132. if (isArray(rect) && 4 === rect.length) {
  8133. var width = rect[2] - rect[0];
  8134. var height = rect[3] - rect[1];
  8135. this.ctx.rect(rect[0], rect[1], width, height);
  8136. this.clip();
  8137. this.endPath();
  8138. }
  8139. this.transform.apply(this, transform);
  8140. this.transform.apply(this, matrix);
  8141. },
  8142. endAnnotation: function CanvasGraphics_endAnnotation() {
  8143. this.restore();
  8144. },
  8145. paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
  8146. var domImage = this.objs.get(objId);
  8147. if (!domImage) {
  8148. warn('Dependent image isn\'t ready yet');
  8149. return;
  8150. }
  8151. this.save();
  8152. var ctx = this.ctx;
  8153. // scale the image to the unit square
  8154. ctx.scale(1 / w, -1 / h);
  8155. ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height, 0, -h, w, h);
  8156. if (this.imageLayer) {
  8157. var currentTransform = ctx.mozCurrentTransformInverse;
  8158. var position = this.getCanvasPosition(0, 0);
  8159. this.imageLayer.appendImage({
  8160. objId: objId,
  8161. left: position[0],
  8162. top: position[1],
  8163. width: w / currentTransform[0],
  8164. height: h / currentTransform[3]
  8165. });
  8166. }
  8167. this.restore();
  8168. },
  8169. paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) {
  8170. var ctx = this.ctx;
  8171. var width = img.width, height = img.height;
  8172. var fillColor = this.current.fillColor;
  8173. var isPatternFill = this.current.patternFill;
  8174. var glyph = this.processingType3;
  8175. if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
  8176. if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
  8177. glyph.compiled = compileType3Glyph({
  8178. data: img.data,
  8179. width: width,
  8180. height: height
  8181. });
  8182. } else {
  8183. glyph.compiled = null;
  8184. }
  8185. }
  8186. if (glyph && glyph.compiled) {
  8187. glyph.compiled(ctx);
  8188. return;
  8189. }
  8190. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height);
  8191. var maskCtx = maskCanvas.context;
  8192. maskCtx.save();
  8193. putBinaryImageMask(maskCtx, img);
  8194. maskCtx.globalCompositeOperation = 'source-in';
  8195. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  8196. maskCtx.fillRect(0, 0, width, height);
  8197. maskCtx.restore();
  8198. this.paintInlineImageXObject(maskCanvas.canvas);
  8199. },
  8200. paintImageMaskXObjectRepeat: function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX, scaleY, positions) {
  8201. var width = imgData.width;
  8202. var height = imgData.height;
  8203. var fillColor = this.current.fillColor;
  8204. var isPatternFill = this.current.patternFill;
  8205. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height);
  8206. var maskCtx = maskCanvas.context;
  8207. maskCtx.save();
  8208. putBinaryImageMask(maskCtx, imgData);
  8209. maskCtx.globalCompositeOperation = 'source-in';
  8210. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  8211. maskCtx.fillRect(0, 0, width, height);
  8212. maskCtx.restore();
  8213. var ctx = this.ctx;
  8214. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  8215. ctx.save();
  8216. ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]);
  8217. ctx.scale(1, -1);
  8218. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  8219. ctx.restore();
  8220. }
  8221. },
  8222. paintImageMaskXObjectGroup: function CanvasGraphics_paintImageMaskXObjectGroup(images) {
  8223. var ctx = this.ctx;
  8224. var fillColor = this.current.fillColor;
  8225. var isPatternFill = this.current.patternFill;
  8226. for (var i = 0, ii = images.length; i < ii; i++) {
  8227. var image = images[i];
  8228. var width = image.width, height = image.height;
  8229. var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height);
  8230. var maskCtx = maskCanvas.context;
  8231. maskCtx.save();
  8232. putBinaryImageMask(maskCtx, image);
  8233. maskCtx.globalCompositeOperation = 'source-in';
  8234. maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
  8235. maskCtx.fillRect(0, 0, width, height);
  8236. maskCtx.restore();
  8237. ctx.save();
  8238. ctx.transform.apply(ctx, image.transform);
  8239. ctx.scale(1, -1);
  8240. ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
  8241. ctx.restore();
  8242. }
  8243. },
  8244. paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
  8245. var imgData = this.objs.get(objId);
  8246. if (!imgData) {
  8247. warn('Dependent image isn\'t ready yet');
  8248. return;
  8249. }
  8250. this.paintInlineImageXObject(imgData);
  8251. },
  8252. paintImageXObjectRepeat: function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
  8253. var imgData = this.objs.get(objId);
  8254. if (!imgData) {
  8255. warn('Dependent image isn\'t ready yet');
  8256. return;
  8257. }
  8258. var width = imgData.width;
  8259. var height = imgData.height;
  8260. var map = [];
  8261. for (var i = 0, ii = positions.length; i < ii; i += 2) {
  8262. map.push({
  8263. transform: [
  8264. scaleX,
  8265. 0,
  8266. 0,
  8267. scaleY,
  8268. positions[i],
  8269. positions[i + 1]
  8270. ],
  8271. x: 0,
  8272. y: 0,
  8273. w: width,
  8274. h: height
  8275. });
  8276. }
  8277. this.paintInlineImageXObjectGroup(imgData, map);
  8278. },
  8279. paintInlineImageXObject: function CanvasGraphics_paintInlineImageXObject(imgData) {
  8280. var width = imgData.width;
  8281. var height = imgData.height;
  8282. var ctx = this.ctx;
  8283. this.save();
  8284. // scale the image to the unit square
  8285. ctx.scale(1 / width, -1 / height);
  8286. var currentTransform = ctx.mozCurrentTransformInverse;
  8287. var a = currentTransform[0], b = currentTransform[1];
  8288. var widthScale = Math.max(Math.sqrt(a * a + b * b), 1);
  8289. var c = currentTransform[2], d = currentTransform[3];
  8290. var heightScale = Math.max(Math.sqrt(c * c + d * d), 1);
  8291. var imgToPaint, tmpCanvas;
  8292. // instanceof HTMLElement does not work in jsdom node.js module
  8293. if (imgData instanceof HTMLElement || !imgData.data) {
  8294. imgToPaint = imgData;
  8295. } else {
  8296. tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', width, height);
  8297. var tmpCtx = tmpCanvas.context;
  8298. putBinaryImageData(tmpCtx, imgData);
  8299. imgToPaint = tmpCanvas.canvas;
  8300. }
  8301. var paintWidth = width, paintHeight = height;
  8302. var tmpCanvasId = 'prescale1';
  8303. // Vertial or horizontal scaling shall not be more than 2 to not loose the
  8304. // pixels during drawImage operation, painting on the temporary canvas(es)
  8305. // that are twice smaller in size
  8306. while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
  8307. var newWidth = paintWidth, newHeight = paintHeight;
  8308. if (widthScale > 2 && paintWidth > 1) {
  8309. newWidth = Math.ceil(paintWidth / 2);
  8310. widthScale /= paintWidth / newWidth;
  8311. }
  8312. if (heightScale > 2 && paintHeight > 1) {
  8313. newHeight = Math.ceil(paintHeight / 2);
  8314. heightScale /= paintHeight / newHeight;
  8315. }
  8316. tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
  8317. tmpCtx = tmpCanvas.context;
  8318. tmpCtx.clearRect(0, 0, newWidth, newHeight);
  8319. tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
  8320. imgToPaint = tmpCanvas.canvas;
  8321. paintWidth = newWidth;
  8322. paintHeight = newHeight;
  8323. tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1';
  8324. }
  8325. ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, -height, width, height);
  8326. if (this.imageLayer) {
  8327. var position = this.getCanvasPosition(0, -height);
  8328. this.imageLayer.appendImage({
  8329. imgData: imgData,
  8330. left: position[0],
  8331. top: position[1],
  8332. width: width / currentTransform[0],
  8333. height: height / currentTransform[3]
  8334. });
  8335. }
  8336. this.restore();
  8337. },
  8338. paintInlineImageXObjectGroup: function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) {
  8339. var ctx = this.ctx;
  8340. var w = imgData.width;
  8341. var h = imgData.height;
  8342. var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h);
  8343. var tmpCtx = tmpCanvas.context;
  8344. putBinaryImageData(tmpCtx, imgData);
  8345. for (var i = 0, ii = map.length; i < ii; i++) {
  8346. var entry = map[i];
  8347. ctx.save();
  8348. ctx.transform.apply(ctx, entry.transform);
  8349. ctx.scale(1, -1);
  8350. ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
  8351. if (this.imageLayer) {
  8352. var position = this.getCanvasPosition(entry.x, entry.y);
  8353. this.imageLayer.appendImage({
  8354. imgData: imgData,
  8355. left: position[0],
  8356. top: position[1],
  8357. width: w,
  8358. height: h
  8359. });
  8360. }
  8361. ctx.restore();
  8362. }
  8363. },
  8364. paintSolidColorImageMask: function CanvasGraphics_paintSolidColorImageMask() {
  8365. this.ctx.fillRect(0, 0, 1, 1);
  8366. },
  8367. paintXObject: function CanvasGraphics_paintXObject() {
  8368. warn('Unsupported \'paintXObject\' command.');
  8369. },
  8370. // Marked content
  8371. markPoint: function CanvasGraphics_markPoint(tag) {
  8372. },
  8373. markPointProps: function CanvasGraphics_markPointProps(tag, properties) {
  8374. },
  8375. beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) {
  8376. },
  8377. beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps(tag, properties) {
  8378. },
  8379. endMarkedContent: function CanvasGraphics_endMarkedContent() {
  8380. },
  8381. // Compatibility
  8382. beginCompat: function CanvasGraphics_beginCompat() {
  8383. },
  8384. endCompat: function CanvasGraphics_endCompat() {
  8385. },
  8386. // Helper functions
  8387. consumePath: function CanvasGraphics_consumePath() {
  8388. var ctx = this.ctx;
  8389. if (this.pendingClip) {
  8390. if (this.pendingClip === EO_CLIP) {
  8391. if (ctx.mozFillRule !== undefined) {
  8392. ctx.mozFillRule = 'evenodd';
  8393. ctx.clip();
  8394. ctx.mozFillRule = 'nonzero';
  8395. } else {
  8396. ctx.clip('evenodd');
  8397. }
  8398. } else {
  8399. ctx.clip();
  8400. }
  8401. this.pendingClip = null;
  8402. }
  8403. ctx.beginPath();
  8404. },
  8405. getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) {
  8406. if (this.cachedGetSinglePixelWidth === null) {
  8407. // NOTE: The `save` and `restore` commands used below is a workaround
  8408. // that is necessary in order to prevent `mozCurrentTransformInverse`
  8409. // from intermittently returning incorrect values in Firefox, see:
  8410. // https://github.com/mozilla/pdf.js/issues/7188.
  8411. this.ctx.save();
  8412. var inverse = this.ctx.mozCurrentTransformInverse;
  8413. this.ctx.restore();
  8414. // max of the current horizontal and vertical scale
  8415. this.cachedGetSinglePixelWidth = Math.sqrt(Math.max(inverse[0] * inverse[0] + inverse[1] * inverse[1], inverse[2] * inverse[2] + inverse[3] * inverse[3]));
  8416. }
  8417. return this.cachedGetSinglePixelWidth;
  8418. },
  8419. getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) {
  8420. var transform = this.ctx.mozCurrentTransform;
  8421. return [
  8422. transform[0] * x + transform[2] * y + transform[4],
  8423. transform[1] * x + transform[3] * y + transform[5]
  8424. ];
  8425. }
  8426. };
  8427. for (var op in OPS) {
  8428. CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op];
  8429. }
  8430. return CanvasGraphics;
  8431. }();
  8432. exports.CanvasGraphics = CanvasGraphics;
  8433. exports.createScratchCanvas = createScratchCanvas;
  8434. }));
  8435. (function (root, factory) {
  8436. factory(root.pdfjsDisplayAPI = {}, root.pdfjsSharedUtil, root.pdfjsDisplayFontLoader, root.pdfjsDisplayCanvas, root.pdfjsDisplayMetadata, root.pdfjsDisplayDOMUtils);
  8437. }(this, function (exports, sharedUtil, displayFontLoader, displayCanvas, displayMetadata, displayDOMUtils, amdRequire) {
  8438. var InvalidPDFException = sharedUtil.InvalidPDFException;
  8439. var MessageHandler = sharedUtil.MessageHandler;
  8440. var MissingPDFException = sharedUtil.MissingPDFException;
  8441. var PageViewport = sharedUtil.PageViewport;
  8442. var PasswordResponses = sharedUtil.PasswordResponses;
  8443. var PasswordException = sharedUtil.PasswordException;
  8444. var StatTimer = sharedUtil.StatTimer;
  8445. var UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  8446. var UnknownErrorException = sharedUtil.UnknownErrorException;
  8447. var Util = sharedUtil.Util;
  8448. var createPromiseCapability = sharedUtil.createPromiseCapability;
  8449. var error = sharedUtil.error;
  8450. var deprecated = sharedUtil.deprecated;
  8451. var getVerbosityLevel = sharedUtil.getVerbosityLevel;
  8452. var info = sharedUtil.info;
  8453. var isInt = sharedUtil.isInt;
  8454. var isArray = sharedUtil.isArray;
  8455. var isArrayBuffer = sharedUtil.isArrayBuffer;
  8456. var isSameOrigin = sharedUtil.isSameOrigin;
  8457. var loadJpegStream = sharedUtil.loadJpegStream;
  8458. var stringToBytes = sharedUtil.stringToBytes;
  8459. var globalScope = sharedUtil.globalScope;
  8460. var warn = sharedUtil.warn;
  8461. var FontFaceObject = displayFontLoader.FontFaceObject;
  8462. var FontLoader = displayFontLoader.FontLoader;
  8463. var CanvasGraphics = displayCanvas.CanvasGraphics;
  8464. var createScratchCanvas = displayCanvas.createScratchCanvas;
  8465. var Metadata = displayMetadata.Metadata;
  8466. var getDefaultSetting = displayDOMUtils.getDefaultSetting;
  8467. var DEFAULT_RANGE_CHUNK_SIZE = 65536;
  8468. // 2^16 = 65536
  8469. var isWorkerDisabled = false;
  8470. var workerSrc;
  8471. var isPostMessageTransfersDisabled = false;
  8472. var fakeWorkerFilesLoader = null;
  8473. var useRequireEnsure = false;
  8474. // For GENERIC build we need add support of different fake file loaders
  8475. // for different frameworks.
  8476. if (typeof window === 'undefined') {
  8477. // node.js - disable worker and set require.ensure.
  8478. isWorkerDisabled = true;
  8479. if (typeof require.ensure === 'undefined') {
  8480. require.ensure = require('node-ensure');
  8481. }
  8482. useRequireEnsure = true;
  8483. }
  8484. if (typeof __webpack_require__ !== 'undefined') {
  8485. useRequireEnsure = true;
  8486. }
  8487. if (typeof requirejs !== 'undefined' && requirejs.toUrl) {
  8488. workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js');
  8489. }
  8490. var dynamicLoaderSupported = typeof requirejs !== 'undefined' && requirejs.load;
  8491. fakeWorkerFilesLoader = useRequireEnsure ? function (callback) {
  8492. require.ensure([], function () {
  8493. var worker = require('./pdf.worker.js');
  8494. callback(worker.WorkerMessageHandler);
  8495. });
  8496. } : dynamicLoaderSupported ? function (callback) {
  8497. requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) {
  8498. callback(worker.WorkerMessageHandler);
  8499. });
  8500. } : null;
  8501. /**
  8502. * Document initialization / loading parameters object.
  8503. *
  8504. * @typedef {Object} DocumentInitParameters
  8505. * @property {string} url - The URL of the PDF.
  8506. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays
  8507. * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,
  8508. * use atob() to convert it to a binary string first.
  8509. * @property {Object} httpHeaders - Basic authentication headers.
  8510. * @property {boolean} withCredentials - Indicates whether or not cross-site
  8511. * Access-Control requests should be made using credentials such as cookies
  8512. * or authorization headers. The default is false.
  8513. * @property {string} password - For decrypting password-protected PDFs.
  8514. * @property {TypedArray} initialData - A typed array with the first portion or
  8515. * all of the pdf data. Used by the extension since some data is already
  8516. * loaded before the switch to range requests.
  8517. * @property {number} length - The PDF file length. It's used for progress
  8518. * reports and range requests operations.
  8519. * @property {PDFDataRangeTransport} range
  8520. * @property {number} rangeChunkSize - Optional parameter to specify
  8521. * maximum number of bytes fetched per range request. The default value is
  8522. * 2^16 = 65536.
  8523. * @property {PDFWorker} worker - The worker that will be used for the loading
  8524. * and parsing of the PDF data.
  8525. */
  8526. /**
  8527. * @typedef {Object} PDFDocumentStats
  8528. * @property {Array} streamTypes - Used stream types in the document (an item
  8529. * is set to true if specific stream ID was used in the document).
  8530. * @property {Array} fontTypes - Used font type in the document (an item is set
  8531. * to true if specific font ID was used in the document).
  8532. */
  8533. /**
  8534. * This is the main entry point for loading a PDF and interacting with it.
  8535. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
  8536. * is used, which means it must follow the same origin rules that any XHR does
  8537. * e.g. No cross domain requests without CORS.
  8538. *
  8539. * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src
  8540. * Can be a url to where a PDF is located, a typed array (Uint8Array)
  8541. * already populated with data or parameter object.
  8542. *
  8543. * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used
  8544. * if you want to manually serve range requests for data in the PDF.
  8545. *
  8546. * @param {function} passwordCallback (deprecated) It is used to request a
  8547. * password if wrong or no password was provided. The callback receives two
  8548. * parameters: function that needs to be called with new password and reason
  8549. * (see {PasswordResponses}).
  8550. *
  8551. * @param {function} progressCallback (deprecated) It is used to be able to
  8552. * monitor the loading progress of the PDF file (necessary to implement e.g.
  8553. * a loading bar). The callback receives an {Object} with the properties:
  8554. * {number} loaded and {number} total.
  8555. *
  8556. * @return {PDFDocumentLoadingTask}
  8557. */
  8558. function getDocument(src, pdfDataRangeTransport, passwordCallback, progressCallback) {
  8559. var task = new PDFDocumentLoadingTask();
  8560. // Support of the obsolete arguments (for compatibility with API v1.0)
  8561. if (arguments.length > 1) {
  8562. deprecated('getDocument is called with pdfDataRangeTransport, ' + 'passwordCallback or progressCallback argument');
  8563. }
  8564. if (pdfDataRangeTransport) {
  8565. if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) {
  8566. // Not a PDFDataRangeTransport instance, trying to add missing properties.
  8567. pdfDataRangeTransport = Object.create(pdfDataRangeTransport);
  8568. pdfDataRangeTransport.length = src.length;
  8569. pdfDataRangeTransport.initialData = src.initialData;
  8570. if (!pdfDataRangeTransport.abort) {
  8571. pdfDataRangeTransport.abort = function () {
  8572. };
  8573. }
  8574. }
  8575. src = Object.create(src);
  8576. src.range = pdfDataRangeTransport;
  8577. }
  8578. task.onPassword = passwordCallback || null;
  8579. task.onProgress = progressCallback || null;
  8580. var source;
  8581. if (typeof src === 'string') {
  8582. source = { url: src };
  8583. } else if (isArrayBuffer(src)) {
  8584. source = { data: src };
  8585. } else if (src instanceof PDFDataRangeTransport) {
  8586. source = { range: src };
  8587. } else {
  8588. if (typeof src !== 'object') {
  8589. error('Invalid parameter in getDocument, need either Uint8Array, ' + 'string or a parameter object');
  8590. }
  8591. if (!src.url && !src.data && !src.range) {
  8592. error('Invalid parameter object: need either .data, .range or .url');
  8593. }
  8594. source = src;
  8595. }
  8596. var params = {};
  8597. var rangeTransport = null;
  8598. var worker = null;
  8599. for (var key in source) {
  8600. if (key === 'url' && typeof window !== 'undefined') {
  8601. // The full path is required in the 'url' field.
  8602. params[key] = new URL(source[key], window.location).href;
  8603. continue;
  8604. } else if (key === 'range') {
  8605. rangeTransport = source[key];
  8606. continue;
  8607. } else if (key === 'worker') {
  8608. worker = source[key];
  8609. continue;
  8610. } else if (key === 'data' && !(source[key] instanceof Uint8Array)) {
  8611. // Converting string or array-like data to Uint8Array.
  8612. var pdfBytes = source[key];
  8613. if (typeof pdfBytes === 'string') {
  8614. params[key] = stringToBytes(pdfBytes);
  8615. } else if (typeof pdfBytes === 'object' && pdfBytes !== null && !isNaN(pdfBytes.length)) {
  8616. params[key] = new Uint8Array(pdfBytes);
  8617. } else if (isArrayBuffer(pdfBytes)) {
  8618. params[key] = new Uint8Array(pdfBytes);
  8619. } else {
  8620. error('Invalid PDF binary data: either typed array, string or ' + 'array-like object is expected in the data property.');
  8621. }
  8622. continue;
  8623. }
  8624. params[key] = source[key];
  8625. }
  8626. params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
  8627. if (!worker) {
  8628. // Worker was not provided -- creating and owning our own.
  8629. worker = new PDFWorker();
  8630. task._worker = worker;
  8631. }
  8632. var docId = task.docId;
  8633. worker.promise.then(function () {
  8634. if (task.destroyed) {
  8635. throw new Error('Loading aborted');
  8636. }
  8637. return _fetchDocument(worker, params, rangeTransport, docId).then(function (workerId) {
  8638. if (task.destroyed) {
  8639. throw new Error('Loading aborted');
  8640. }
  8641. var messageHandler = new MessageHandler(docId, workerId, worker.port);
  8642. var transport = new WorkerTransport(messageHandler, task, rangeTransport);
  8643. task._transport = transport;
  8644. messageHandler.send('Ready', null);
  8645. });
  8646. }).catch(task._capability.reject);
  8647. return task;
  8648. }
  8649. /**
  8650. * Starts fetching of specified PDF document/data.
  8651. * @param {PDFWorker} worker
  8652. * @param {Object} source
  8653. * @param {PDFDataRangeTransport} pdfDataRangeTransport
  8654. * @param {string} docId Unique document id, used as MessageHandler id.
  8655. * @returns {Promise} The promise, which is resolved when worker id of
  8656. * MessageHandler is known.
  8657. * @private
  8658. */
  8659. function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
  8660. if (worker.destroyed) {
  8661. return Promise.reject(new Error('Worker was destroyed'));
  8662. }
  8663. source.disableAutoFetch = getDefaultSetting('disableAutoFetch');
  8664. source.disableStream = getDefaultSetting('disableStream');
  8665. source.chunkedViewerLoading = !!pdfDataRangeTransport;
  8666. if (pdfDataRangeTransport) {
  8667. source.length = pdfDataRangeTransport.length;
  8668. source.initialData = pdfDataRangeTransport.initialData;
  8669. }
  8670. return worker.messageHandler.sendWithPromise('GetDocRequest', {
  8671. docId: docId,
  8672. source: source,
  8673. disableRange: getDefaultSetting('disableRange'),
  8674. maxImageSize: getDefaultSetting('maxImageSize'),
  8675. cMapUrl: getDefaultSetting('cMapUrl'),
  8676. cMapPacked: getDefaultSetting('cMapPacked'),
  8677. disableFontFace: getDefaultSetting('disableFontFace'),
  8678. disableCreateObjectURL: getDefaultSetting('disableCreateObjectURL'),
  8679. postMessageTransfers: getDefaultSetting('postMessageTransfers') && !isPostMessageTransfersDisabled
  8680. }).then(function (workerId) {
  8681. if (worker.destroyed) {
  8682. throw new Error('Worker was destroyed');
  8683. }
  8684. return workerId;
  8685. });
  8686. }
  8687. /**
  8688. * PDF document loading operation.
  8689. * @class
  8690. * @alias PDFDocumentLoadingTask
  8691. */
  8692. var PDFDocumentLoadingTask = function PDFDocumentLoadingTaskClosure() {
  8693. var nextDocumentId = 0;
  8694. /** @constructs PDFDocumentLoadingTask */
  8695. function PDFDocumentLoadingTask() {
  8696. this._capability = createPromiseCapability();
  8697. this._transport = null;
  8698. this._worker = null;
  8699. /**
  8700. * Unique document loading task id -- used in MessageHandlers.
  8701. * @type {string}
  8702. */
  8703. this.docId = 'd' + nextDocumentId++;
  8704. /**
  8705. * Shows if loading task is destroyed.
  8706. * @type {boolean}
  8707. */
  8708. this.destroyed = false;
  8709. /**
  8710. * Callback to request a password if wrong or no password was provided.
  8711. * The callback receives two parameters: function that needs to be called
  8712. * with new password and reason (see {PasswordResponses}).
  8713. */
  8714. this.onPassword = null;
  8715. /**
  8716. * Callback to be able to monitor the loading progress of the PDF file
  8717. * (necessary to implement e.g. a loading bar). The callback receives
  8718. * an {Object} with the properties: {number} loaded and {number} total.
  8719. */
  8720. this.onProgress = null;
  8721. /**
  8722. * Callback to when unsupported feature is used. The callback receives
  8723. * an {UNSUPPORTED_FEATURES} argument.
  8724. */
  8725. this.onUnsupportedFeature = null;
  8726. }
  8727. PDFDocumentLoadingTask.prototype = /** @lends PDFDocumentLoadingTask.prototype */
  8728. {
  8729. /**
  8730. * @return {Promise}
  8731. */
  8732. get promise() {
  8733. return this._capability.promise;
  8734. },
  8735. /**
  8736. * Aborts all network requests and destroys worker.
  8737. * @return {Promise} A promise that is resolved after destruction activity
  8738. * is completed.
  8739. */
  8740. destroy: function () {
  8741. this.destroyed = true;
  8742. var transportDestroyed = !this._transport ? Promise.resolve() : this._transport.destroy();
  8743. return transportDestroyed.then(function () {
  8744. this._transport = null;
  8745. if (this._worker) {
  8746. this._worker.destroy();
  8747. this._worker = null;
  8748. }
  8749. }.bind(this));
  8750. },
  8751. /**
  8752. * Registers callbacks to indicate the document loading completion.
  8753. *
  8754. * @param {function} onFulfilled The callback for the loading completion.
  8755. * @param {function} onRejected The callback for the loading failure.
  8756. * @return {Promise} A promise that is resolved after the onFulfilled or
  8757. * onRejected callback.
  8758. */
  8759. then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) {
  8760. return this.promise.then.apply(this.promise, arguments);
  8761. }
  8762. };
  8763. return PDFDocumentLoadingTask;
  8764. }();
  8765. /**
  8766. * Abstract class to support range requests file loading.
  8767. * @class
  8768. * @alias PDFDataRangeTransport
  8769. * @param {number} length
  8770. * @param {Uint8Array} initialData
  8771. */
  8772. var PDFDataRangeTransport = function pdfDataRangeTransportClosure() {
  8773. function PDFDataRangeTransport(length, initialData) {
  8774. this.length = length;
  8775. this.initialData = initialData;
  8776. this._rangeListeners = [];
  8777. this._progressListeners = [];
  8778. this._progressiveReadListeners = [];
  8779. this._readyCapability = createPromiseCapability();
  8780. }
  8781. PDFDataRangeTransport.prototype = /** @lends PDFDataRangeTransport.prototype */
  8782. {
  8783. addRangeListener: function PDFDataRangeTransport_addRangeListener(listener) {
  8784. this._rangeListeners.push(listener);
  8785. },
  8786. addProgressListener: function PDFDataRangeTransport_addProgressListener(listener) {
  8787. this._progressListeners.push(listener);
  8788. },
  8789. addProgressiveReadListener: function PDFDataRangeTransport_addProgressiveReadListener(listener) {
  8790. this._progressiveReadListeners.push(listener);
  8791. },
  8792. onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {
  8793. var listeners = this._rangeListeners;
  8794. for (var i = 0, n = listeners.length; i < n; ++i) {
  8795. listeners[i](begin, chunk);
  8796. }
  8797. },
  8798. onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {
  8799. this._readyCapability.promise.then(function () {
  8800. var listeners = this._progressListeners;
  8801. for (var i = 0, n = listeners.length; i < n; ++i) {
  8802. listeners[i](loaded);
  8803. }
  8804. }.bind(this));
  8805. },
  8806. onDataProgressiveRead: function PDFDataRangeTransport_onDataProgress(chunk) {
  8807. this._readyCapability.promise.then(function () {
  8808. var listeners = this._progressiveReadListeners;
  8809. for (var i = 0, n = listeners.length; i < n; ++i) {
  8810. listeners[i](chunk);
  8811. }
  8812. }.bind(this));
  8813. },
  8814. transportReady: function PDFDataRangeTransport_transportReady() {
  8815. this._readyCapability.resolve();
  8816. },
  8817. requestDataRange: function PDFDataRangeTransport_requestDataRange(begin, end) {
  8818. throw new Error('Abstract method PDFDataRangeTransport.requestDataRange');
  8819. },
  8820. abort: function PDFDataRangeTransport_abort() {
  8821. }
  8822. };
  8823. return PDFDataRangeTransport;
  8824. }();
  8825. /**
  8826. * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
  8827. * properties that can be read synchronously.
  8828. * @class
  8829. * @alias PDFDocumentProxy
  8830. */
  8831. var PDFDocumentProxy = function PDFDocumentProxyClosure() {
  8832. function PDFDocumentProxy(pdfInfo, transport, loadingTask) {
  8833. this.pdfInfo = pdfInfo;
  8834. this.transport = transport;
  8835. this.loadingTask = loadingTask;
  8836. }
  8837. PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */
  8838. {
  8839. /**
  8840. * @return {number} Total number of pages the PDF contains.
  8841. */
  8842. get numPages() {
  8843. return this.pdfInfo.numPages;
  8844. },
  8845. /**
  8846. * @return {string} A unique ID to identify a PDF. Not guaranteed to be
  8847. * unique.
  8848. */
  8849. get fingerprint() {
  8850. return this.pdfInfo.fingerprint;
  8851. },
  8852. /**
  8853. * @param {number} pageNumber The page number to get. The first page is 1.
  8854. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
  8855. * object.
  8856. */
  8857. getPage: function PDFDocumentProxy_getPage(pageNumber) {
  8858. return this.transport.getPage(pageNumber);
  8859. },
  8860. /**
  8861. * @param {{num: number, gen: number}} ref The page reference. Must have
  8862. * the 'num' and 'gen' properties.
  8863. * @return {Promise} A promise that is resolved with the page index that is
  8864. * associated with the reference.
  8865. */
  8866. getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
  8867. return this.transport.getPageIndex(ref);
  8868. },
  8869. /**
  8870. * @return {Promise} A promise that is resolved with a lookup table for
  8871. * mapping named destinations to reference numbers.
  8872. *
  8873. * This can be slow for large documents: use getDestination instead
  8874. */
  8875. getDestinations: function PDFDocumentProxy_getDestinations() {
  8876. return this.transport.getDestinations();
  8877. },
  8878. /**
  8879. * @param {string} id The named destination to get.
  8880. * @return {Promise} A promise that is resolved with all information
  8881. * of the given named destination.
  8882. */
  8883. getDestination: function PDFDocumentProxy_getDestination(id) {
  8884. return this.transport.getDestination(id);
  8885. },
  8886. /**
  8887. * @return {Promise} A promise that is resolved with:
  8888. * an Array containing the pageLabels that correspond to the pageIndexes,
  8889. * or `null` when no pageLabels are present in the PDF file.
  8890. */
  8891. getPageLabels: function PDFDocumentProxy_getPageLabels() {
  8892. return this.transport.getPageLabels();
  8893. },
  8894. /**
  8895. * @return {Promise} A promise that is resolved with a lookup table for
  8896. * mapping named attachments to their content.
  8897. */
  8898. getAttachments: function PDFDocumentProxy_getAttachments() {
  8899. return this.transport.getAttachments();
  8900. },
  8901. /**
  8902. * @return {Promise} A promise that is resolved with an array of all the
  8903. * JavaScript strings in the name tree.
  8904. */
  8905. getJavaScript: function PDFDocumentProxy_getJavaScript() {
  8906. return this.transport.getJavaScript();
  8907. },
  8908. /**
  8909. * @return {Promise} A promise that is resolved with an {Array} that is a
  8910. * tree outline (if it has one) of the PDF. The tree is in the format of:
  8911. * [
  8912. * {
  8913. * title: string,
  8914. * bold: boolean,
  8915. * italic: boolean,
  8916. * color: rgb Uint8Array,
  8917. * dest: dest obj,
  8918. * url: string,
  8919. * items: array of more items like this
  8920. * },
  8921. * ...
  8922. * ].
  8923. */
  8924. getOutline: function PDFDocumentProxy_getOutline() {
  8925. return this.transport.getOutline();
  8926. },
  8927. /**
  8928. * @return {Promise} A promise that is resolved with an {Object} that has
  8929. * info and metadata properties. Info is an {Object} filled with anything
  8930. * available in the information dictionary and similarly metadata is a
  8931. * {Metadata} object with information from the metadata section of the PDF.
  8932. */
  8933. getMetadata: function PDFDocumentProxy_getMetadata() {
  8934. return this.transport.getMetadata();
  8935. },
  8936. /**
  8937. * @return {Promise} A promise that is resolved with a TypedArray that has
  8938. * the raw data from the PDF.
  8939. */
  8940. getData: function PDFDocumentProxy_getData() {
  8941. return this.transport.getData();
  8942. },
  8943. /**
  8944. * @return {Promise} A promise that is resolved when the document's data
  8945. * is loaded. It is resolved with an {Object} that contains the length
  8946. * property that indicates size of the PDF data in bytes.
  8947. */
  8948. getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
  8949. return this.transport.downloadInfoCapability.promise;
  8950. },
  8951. /**
  8952. * @return {Promise} A promise this is resolved with current stats about
  8953. * document structures (see {@link PDFDocumentStats}).
  8954. */
  8955. getStats: function PDFDocumentProxy_getStats() {
  8956. return this.transport.getStats();
  8957. },
  8958. /**
  8959. * Cleans up resources allocated by the document, e.g. created @font-face.
  8960. */
  8961. cleanup: function PDFDocumentProxy_cleanup() {
  8962. this.transport.startCleanup();
  8963. },
  8964. /**
  8965. * Destroys current document instance and terminates worker.
  8966. */
  8967. destroy: function PDFDocumentProxy_destroy() {
  8968. return this.loadingTask.destroy();
  8969. }
  8970. };
  8971. return PDFDocumentProxy;
  8972. }();
  8973. /**
  8974. * Page getTextContent parameters.
  8975. *
  8976. * @typedef {Object} getTextContentParameters
  8977. * @property {boolean} normalizeWhitespace - replaces all occurrences of
  8978. * whitespace with standard spaces (0x20). The default value is `false`.
  8979. * @property {boolean} disableCombineTextItems - do not attempt to combine
  8980. * same line {@link TextItem}'s. The default value is `false`.
  8981. */
  8982. /**
  8983. * Page text content.
  8984. *
  8985. * @typedef {Object} TextContent
  8986. * @property {array} items - array of {@link TextItem}
  8987. * @property {Object} styles - {@link TextStyles} objects, indexed by font name.
  8988. */
  8989. /**
  8990. * Page text content part.
  8991. *
  8992. * @typedef {Object} TextItem
  8993. * @property {string} str - text content.
  8994. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
  8995. * @property {array} transform - transformation matrix.
  8996. * @property {number} width - width in device space.
  8997. * @property {number} height - height in device space.
  8998. * @property {string} fontName - font name used by pdf.js for converted font.
  8999. */
  9000. /**
  9001. * Text style.
  9002. *
  9003. * @typedef {Object} TextStyle
  9004. * @property {number} ascent - font ascent.
  9005. * @property {number} descent - font descent.
  9006. * @property {boolean} vertical - text is in vertical mode.
  9007. * @property {string} fontFamily - possible font family
  9008. */
  9009. /**
  9010. * Page annotation parameters.
  9011. *
  9012. * @typedef {Object} GetAnnotationsParameters
  9013. * @property {string} intent - Determines the annotations that will be fetched,
  9014. * can be either 'display' (viewable annotations) or 'print'
  9015. * (printable annotations).
  9016. * If the parameter is omitted, all annotations are fetched.
  9017. */
  9018. /**
  9019. * Page render parameters.
  9020. *
  9021. * @typedef {Object} RenderParameters
  9022. * @property {Object} canvasContext - A 2D context of a DOM Canvas object.
  9023. * @property {PageViewport} viewport - Rendering viewport obtained by
  9024. * calling of PDFPage.getViewport method.
  9025. * @property {string} intent - Rendering intent, can be 'display' or 'print'
  9026. * (default value is 'display').
  9027. * @property {boolean} renderInteractiveForms - (optional) Whether or not
  9028. * interactive form elements are rendered in the display
  9029. * layer. If so, we do not render them on canvas as well.
  9030. * @property {Array} transform - (optional) Additional transform, applied
  9031. * just before viewport transform.
  9032. * @property {Object} imageLayer - (optional) An object that has beginLayout,
  9033. * endLayout and appendImage functions.
  9034. * @property {function} continueCallback - (deprecated) A function that will be
  9035. * called each time the rendering is paused. To continue
  9036. * rendering call the function that is the first argument
  9037. * to the callback.
  9038. */
  9039. /**
  9040. * PDF page operator list.
  9041. *
  9042. * @typedef {Object} PDFOperatorList
  9043. * @property {Array} fnArray - Array containing the operator functions.
  9044. * @property {Array} argsArray - Array containing the arguments of the
  9045. * functions.
  9046. */
  9047. /**
  9048. * Proxy to a PDFPage in the worker thread.
  9049. * @class
  9050. * @alias PDFPageProxy
  9051. */
  9052. var PDFPageProxy = function PDFPageProxyClosure() {
  9053. function PDFPageProxy(pageIndex, pageInfo, transport) {
  9054. this.pageIndex = pageIndex;
  9055. this.pageInfo = pageInfo;
  9056. this.transport = transport;
  9057. this.stats = new StatTimer();
  9058. this.stats.enabled = getDefaultSetting('enableStats');
  9059. this.commonObjs = transport.commonObjs;
  9060. this.objs = new PDFObjects();
  9061. this.cleanupAfterRender = false;
  9062. this.pendingCleanup = false;
  9063. this.intentStates = Object.create(null);
  9064. this.destroyed = false;
  9065. }
  9066. PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */
  9067. {
  9068. /**
  9069. * @return {number} Page number of the page. First page is 1.
  9070. */
  9071. get pageNumber() {
  9072. return this.pageIndex + 1;
  9073. },
  9074. /**
  9075. * @return {number} The number of degrees the page is rotated clockwise.
  9076. */
  9077. get rotate() {
  9078. return this.pageInfo.rotate;
  9079. },
  9080. /**
  9081. * @return {Object} The reference that points to this page. It has 'num' and
  9082. * 'gen' properties.
  9083. */
  9084. get ref() {
  9085. return this.pageInfo.ref;
  9086. },
  9087. /**
  9088. * @return {Array} An array of the visible portion of the PDF page in the
  9089. * user space units - [x1, y1, x2, y2].
  9090. */
  9091. get view() {
  9092. return this.pageInfo.view;
  9093. },
  9094. /**
  9095. * @param {number} scale The desired scale of the viewport.
  9096. * @param {number} rotate Degrees to rotate the viewport. If omitted this
  9097. * defaults to the page rotation.
  9098. * @return {PageViewport} Contains 'width' and 'height' properties
  9099. * along with transforms required for rendering.
  9100. */
  9101. getViewport: function PDFPageProxy_getViewport(scale, rotate) {
  9102. if (arguments.length < 2) {
  9103. rotate = this.rotate;
  9104. }
  9105. return new PageViewport(this.view, scale, rotate, 0, 0);
  9106. },
  9107. /**
  9108. * @param {GetAnnotationsParameters} params - Annotation parameters.
  9109. * @return {Promise} A promise that is resolved with an {Array} of the
  9110. * annotation objects.
  9111. */
  9112. getAnnotations: function PDFPageProxy_getAnnotations(params) {
  9113. var intent = params && params.intent || null;
  9114. if (!this.annotationsPromise || this.annotationsIntent !== intent) {
  9115. this.annotationsPromise = this.transport.getAnnotations(this.pageIndex, intent);
  9116. this.annotationsIntent = intent;
  9117. }
  9118. return this.annotationsPromise;
  9119. },
  9120. /**
  9121. * Begins the process of rendering a page to the desired context.
  9122. * @param {RenderParameters} params Page render parameters.
  9123. * @return {RenderTask} An object that contains the promise, which
  9124. * is resolved when the page finishes rendering.
  9125. */
  9126. render: function PDFPageProxy_render(params) {
  9127. var stats = this.stats;
  9128. stats.time('Overall');
  9129. // If there was a pending destroy cancel it so no cleanup happens during
  9130. // this call to render.
  9131. this.pendingCleanup = false;
  9132. var renderingIntent = params.intent === 'print' ? 'print' : 'display';
  9133. var renderInteractiveForms = params.renderInteractiveForms === true ? true : /* Default */
  9134. false;
  9135. if (!this.intentStates[renderingIntent]) {
  9136. this.intentStates[renderingIntent] = Object.create(null);
  9137. }
  9138. var intentState = this.intentStates[renderingIntent];
  9139. // If there's no displayReadyCapability yet, then the operatorList
  9140. // was never requested before. Make the request and create the promise.
  9141. if (!intentState.displayReadyCapability) {
  9142. intentState.receivingOperatorList = true;
  9143. intentState.displayReadyCapability = createPromiseCapability();
  9144. intentState.operatorList = {
  9145. fnArray: [],
  9146. argsArray: [],
  9147. lastChunk: false
  9148. };
  9149. this.stats.time('Page Request');
  9150. this.transport.messageHandler.send('RenderPageRequest', {
  9151. pageIndex: this.pageNumber - 1,
  9152. intent: renderingIntent,
  9153. renderInteractiveForms: renderInteractiveForms
  9154. });
  9155. }
  9156. var internalRenderTask = new InternalRenderTask(complete, params, this.objs, this.commonObjs, intentState.operatorList, this.pageNumber);
  9157. internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print';
  9158. if (!intentState.renderTasks) {
  9159. intentState.renderTasks = [];
  9160. }
  9161. intentState.renderTasks.push(internalRenderTask);
  9162. var renderTask = internalRenderTask.task;
  9163. // Obsolete parameter support
  9164. if (params.continueCallback) {
  9165. deprecated('render is used with continueCallback parameter');
  9166. renderTask.onContinue = params.continueCallback;
  9167. }
  9168. var self = this;
  9169. intentState.displayReadyCapability.promise.then(function pageDisplayReadyPromise(transparency) {
  9170. if (self.pendingCleanup) {
  9171. complete();
  9172. return;
  9173. }
  9174. stats.time('Rendering');
  9175. internalRenderTask.initializeGraphics(transparency);
  9176. internalRenderTask.operatorListChanged();
  9177. }, function pageDisplayReadPromiseError(reason) {
  9178. complete(reason);
  9179. });
  9180. function complete(error) {
  9181. var i = intentState.renderTasks.indexOf(internalRenderTask);
  9182. if (i >= 0) {
  9183. intentState.renderTasks.splice(i, 1);
  9184. }
  9185. if (self.cleanupAfterRender) {
  9186. self.pendingCleanup = true;
  9187. }
  9188. self._tryCleanup();
  9189. if (error) {
  9190. internalRenderTask.capability.reject(error);
  9191. } else {
  9192. internalRenderTask.capability.resolve();
  9193. }
  9194. stats.timeEnd('Rendering');
  9195. stats.timeEnd('Overall');
  9196. }
  9197. return renderTask;
  9198. },
  9199. /**
  9200. * @return {Promise} A promise resolved with an {@link PDFOperatorList}
  9201. * object that represents page's operator list.
  9202. */
  9203. getOperatorList: function PDFPageProxy_getOperatorList() {
  9204. function operatorListChanged() {
  9205. if (intentState.operatorList.lastChunk) {
  9206. intentState.opListReadCapability.resolve(intentState.operatorList);
  9207. var i = intentState.renderTasks.indexOf(opListTask);
  9208. if (i >= 0) {
  9209. intentState.renderTasks.splice(i, 1);
  9210. }
  9211. }
  9212. }
  9213. var renderingIntent = 'oplist';
  9214. if (!this.intentStates[renderingIntent]) {
  9215. this.intentStates[renderingIntent] = Object.create(null);
  9216. }
  9217. var intentState = this.intentStates[renderingIntent];
  9218. var opListTask;
  9219. if (!intentState.opListReadCapability) {
  9220. opListTask = {};
  9221. opListTask.operatorListChanged = operatorListChanged;
  9222. intentState.receivingOperatorList = true;
  9223. intentState.opListReadCapability = createPromiseCapability();
  9224. intentState.renderTasks = [];
  9225. intentState.renderTasks.push(opListTask);
  9226. intentState.operatorList = {
  9227. fnArray: [],
  9228. argsArray: [],
  9229. lastChunk: false
  9230. };
  9231. this.transport.messageHandler.send('RenderPageRequest', {
  9232. pageIndex: this.pageIndex,
  9233. intent: renderingIntent
  9234. });
  9235. }
  9236. return intentState.opListReadCapability.promise;
  9237. },
  9238. /**
  9239. * @param {getTextContentParameters} params - getTextContent parameters.
  9240. * @return {Promise} That is resolved a {@link TextContent}
  9241. * object that represent the page text content.
  9242. */
  9243. getTextContent: function PDFPageProxy_getTextContent(params) {
  9244. return this.transport.messageHandler.sendWithPromise('GetTextContent', {
  9245. pageIndex: this.pageNumber - 1,
  9246. normalizeWhitespace: params && params.normalizeWhitespace === true ? true : /* Default */
  9247. false,
  9248. combineTextItems: params && params.disableCombineTextItems === true ? false : /* Default */
  9249. true
  9250. });
  9251. },
  9252. /**
  9253. * Destroys page object.
  9254. */
  9255. _destroy: function PDFPageProxy_destroy() {
  9256. this.destroyed = true;
  9257. this.transport.pageCache[this.pageIndex] = null;
  9258. var waitOn = [];
  9259. Object.keys(this.intentStates).forEach(function (intent) {
  9260. if (intent === 'oplist') {
  9261. // Avoid errors below, since the renderTasks are just stubs.
  9262. return;
  9263. }
  9264. var intentState = this.intentStates[intent];
  9265. intentState.renderTasks.forEach(function (renderTask) {
  9266. var renderCompleted = renderTask.capability.promise.catch(function () {
  9267. });
  9268. // ignoring failures
  9269. waitOn.push(renderCompleted);
  9270. renderTask.cancel();
  9271. });
  9272. }, this);
  9273. this.objs.clear();
  9274. this.annotationsPromise = null;
  9275. this.pendingCleanup = false;
  9276. return Promise.all(waitOn);
  9277. },
  9278. /**
  9279. * Cleans up resources allocated by the page. (deprecated)
  9280. */
  9281. destroy: function () {
  9282. deprecated('page destroy method, use cleanup() instead');
  9283. this.cleanup();
  9284. },
  9285. /**
  9286. * Cleans up resources allocated by the page.
  9287. */
  9288. cleanup: function PDFPageProxy_cleanup() {
  9289. this.pendingCleanup = true;
  9290. this._tryCleanup();
  9291. },
  9292. /**
  9293. * For internal use only. Attempts to clean up if rendering is in a state
  9294. * where that's possible.
  9295. * @ignore
  9296. */
  9297. _tryCleanup: function PDFPageProxy_tryCleanup() {
  9298. if (!this.pendingCleanup || Object.keys(this.intentStates).some(function (intent) {
  9299. var intentState = this.intentStates[intent];
  9300. return intentState.renderTasks.length !== 0 || intentState.receivingOperatorList;
  9301. }, this)) {
  9302. return;
  9303. }
  9304. Object.keys(this.intentStates).forEach(function (intent) {
  9305. delete this.intentStates[intent];
  9306. }, this);
  9307. this.objs.clear();
  9308. this.annotationsPromise = null;
  9309. this.pendingCleanup = false;
  9310. },
  9311. /**
  9312. * For internal use only.
  9313. * @ignore
  9314. */
  9315. _startRenderPage: function PDFPageProxy_startRenderPage(transparency, intent) {
  9316. var intentState = this.intentStates[intent];
  9317. // TODO Refactor RenderPageRequest to separate rendering
  9318. // and operator list logic
  9319. if (intentState.displayReadyCapability) {
  9320. intentState.displayReadyCapability.resolve(transparency);
  9321. }
  9322. },
  9323. /**
  9324. * For internal use only.
  9325. * @ignore
  9326. */
  9327. _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk, intent) {
  9328. var intentState = this.intentStates[intent];
  9329. var i, ii;
  9330. // Add the new chunk to the current operator list.
  9331. for (i = 0, ii = operatorListChunk.length; i < ii; i++) {
  9332. intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
  9333. intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
  9334. }
  9335. intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
  9336. // Notify all the rendering tasks there are more operators to be consumed.
  9337. for (i = 0; i < intentState.renderTasks.length; i++) {
  9338. intentState.renderTasks[i].operatorListChanged();
  9339. }
  9340. if (operatorListChunk.lastChunk) {
  9341. intentState.receivingOperatorList = false;
  9342. this._tryCleanup();
  9343. }
  9344. }
  9345. };
  9346. return PDFPageProxy;
  9347. }();
  9348. /**
  9349. * PDF.js web worker abstraction, it controls instantiation of PDF documents and
  9350. * WorkerTransport for them. If creation of a web worker is not possible,
  9351. * a "fake" worker will be used instead.
  9352. * @class
  9353. */
  9354. var PDFWorker = function PDFWorkerClosure() {
  9355. var nextFakeWorkerId = 0;
  9356. function getWorkerSrc() {
  9357. if (typeof workerSrc !== 'undefined') {
  9358. return workerSrc;
  9359. }
  9360. if (getDefaultSetting('workerSrc')) {
  9361. return getDefaultSetting('workerSrc');
  9362. }
  9363. if (pdfjsFilePath) {
  9364. return pdfjsFilePath.replace(/\.js$/i, '.worker.js');
  9365. }
  9366. error('No PDFJS.workerSrc specified');
  9367. }
  9368. var fakeWorkerFilesLoadedCapability;
  9369. // Loads worker code into main thread.
  9370. function setupFakeWorkerGlobal() {
  9371. var WorkerMessageHandler;
  9372. if (fakeWorkerFilesLoadedCapability) {
  9373. return fakeWorkerFilesLoadedCapability.promise;
  9374. }
  9375. fakeWorkerFilesLoadedCapability = createPromiseCapability();
  9376. var loader = fakeWorkerFilesLoader || function (callback) {
  9377. Util.loadScript(getWorkerSrc(), function () {
  9378. callback(window.pdfjsDistBuildPdfWorker.WorkerMessageHandler);
  9379. });
  9380. };
  9381. loader(fakeWorkerFilesLoadedCapability.resolve);
  9382. return fakeWorkerFilesLoadedCapability.promise;
  9383. }
  9384. function FakeWorkerPort(defer) {
  9385. this._listeners = [];
  9386. this._defer = defer;
  9387. this._deferred = Promise.resolve(undefined);
  9388. }
  9389. FakeWorkerPort.prototype = {
  9390. postMessage: function (obj, transfers) {
  9391. function cloneValue(value) {
  9392. // Trying to perform a structured clone close to the spec, including
  9393. // transfers.
  9394. if (typeof value !== 'object' || value === null) {
  9395. return value;
  9396. }
  9397. if (cloned.has(value)) {
  9398. // already cloned the object
  9399. return cloned.get(value);
  9400. }
  9401. var result;
  9402. var buffer;
  9403. if ((buffer = value.buffer) && isArrayBuffer(buffer)) {
  9404. // We found object with ArrayBuffer (typed array).
  9405. var transferable = transfers && transfers.indexOf(buffer) >= 0;
  9406. if (value === buffer) {
  9407. // Special case when we are faking typed arrays in compatibility.js.
  9408. result = value;
  9409. } else if (transferable) {
  9410. result = new value.constructor(buffer, value.byteOffset, value.byteLength);
  9411. } else {
  9412. result = new value.constructor(value);
  9413. }
  9414. cloned.set(value, result);
  9415. return result;
  9416. }
  9417. result = isArray(value) ? [] : {};
  9418. cloned.set(value, result);
  9419. // adding to cache now for cyclic references
  9420. // Cloning all value and object properties, however ignoring properties
  9421. // defined via getter.
  9422. for (var i in value) {
  9423. var desc, p = value;
  9424. while (!(desc = Object.getOwnPropertyDescriptor(p, i))) {
  9425. p = Object.getPrototypeOf(p);
  9426. }
  9427. if (typeof desc.value === 'undefined' || typeof desc.value === 'function') {
  9428. continue;
  9429. }
  9430. result[i] = cloneValue(desc.value);
  9431. }
  9432. return result;
  9433. }
  9434. if (!this._defer) {
  9435. this._listeners.forEach(function (listener) {
  9436. listener.call(this, { data: obj });
  9437. }, this);
  9438. return;
  9439. }
  9440. var cloned = new WeakMap();
  9441. var e = { data: cloneValue(obj) };
  9442. this._deferred.then(function () {
  9443. this._listeners.forEach(function (listener) {
  9444. listener.call(this, e);
  9445. }, this);
  9446. }.bind(this));
  9447. },
  9448. addEventListener: function (name, listener) {
  9449. this._listeners.push(listener);
  9450. },
  9451. removeEventListener: function (name, listener) {
  9452. var i = this._listeners.indexOf(listener);
  9453. this._listeners.splice(i, 1);
  9454. },
  9455. terminate: function () {
  9456. this._listeners = [];
  9457. }
  9458. };
  9459. function createCDNWrapper(url) {
  9460. // We will rely on blob URL's property to specify origin.
  9461. // We want this function to fail in case if createObjectURL or Blob do not
  9462. // exist or fail for some reason -- our Worker creation will fail anyway.
  9463. var wrapper = 'importScripts(\'' + url + '\');';
  9464. return URL.createObjectURL(new Blob([wrapper]));
  9465. }
  9466. function PDFWorker(name) {
  9467. this.name = name;
  9468. this.destroyed = false;
  9469. this._readyCapability = createPromiseCapability();
  9470. this._port = null;
  9471. this._webWorker = null;
  9472. this._messageHandler = null;
  9473. this._initialize();
  9474. }
  9475. PDFWorker.prototype = /** @lends PDFWorker.prototype */
  9476. {
  9477. get promise() {
  9478. return this._readyCapability.promise;
  9479. },
  9480. get port() {
  9481. return this._port;
  9482. },
  9483. get messageHandler() {
  9484. return this._messageHandler;
  9485. },
  9486. _initialize: function PDFWorker_initialize() {
  9487. // If worker support isn't disabled explicit and the browser has worker
  9488. // support, create a new web worker and test if it/the browser fulfills
  9489. // all requirements to run parts of pdf.js in a web worker.
  9490. // Right now, the requirement is, that an Uint8Array is still an
  9491. // Uint8Array as it arrives on the worker. (Chrome added this with v.15.)
  9492. if (!isWorkerDisabled && !getDefaultSetting('disableWorker') && typeof Worker !== 'undefined') {
  9493. var workerSrc = getWorkerSrc();
  9494. try {
  9495. // Wraps workerSrc path into blob URL, if the former does not belong
  9496. // to the same origin.
  9497. if (!isSameOrigin(window.location.href, workerSrc)) {
  9498. workerSrc = createCDNWrapper(new URL(workerSrc, window.location).href);
  9499. }
  9500. // Some versions of FF can't create a worker on localhost, see:
  9501. // https://bugzilla.mozilla.org/show_bug.cgi?id=683280
  9502. var worker = new Worker(workerSrc);
  9503. var messageHandler = new MessageHandler('main', 'worker', worker);
  9504. var terminateEarly = function () {
  9505. worker.removeEventListener('error', onWorkerError);
  9506. messageHandler.destroy();
  9507. worker.terminate();
  9508. if (this.destroyed) {
  9509. this._readyCapability.reject(new Error('Worker was destroyed'));
  9510. } else {
  9511. // Fall back to fake worker if the termination is caused by an
  9512. // error (e.g. NetworkError / SecurityError).
  9513. this._setupFakeWorker();
  9514. }
  9515. }.bind(this);
  9516. var onWorkerError = function (event) {
  9517. if (!this._webWorker) {
  9518. // Worker failed to initialize due to an error. Clean up and fall
  9519. // back to the fake worker.
  9520. terminateEarly();
  9521. }
  9522. }.bind(this);
  9523. worker.addEventListener('error', onWorkerError);
  9524. messageHandler.on('test', function PDFWorker_test(data) {
  9525. worker.removeEventListener('error', onWorkerError);
  9526. if (this.destroyed) {
  9527. terminateEarly();
  9528. return;
  9529. }
  9530. // worker was destroyed
  9531. var supportTypedArray = data && data.supportTypedArray;
  9532. if (supportTypedArray) {
  9533. this._messageHandler = messageHandler;
  9534. this._port = worker;
  9535. this._webWorker = worker;
  9536. if (!data.supportTransfers) {
  9537. isPostMessageTransfersDisabled = true;
  9538. }
  9539. this._readyCapability.resolve();
  9540. // Send global setting, e.g. verbosity level.
  9541. messageHandler.send('configure', { verbosity: getVerbosityLevel() });
  9542. } else {
  9543. this._setupFakeWorker();
  9544. messageHandler.destroy();
  9545. worker.terminate();
  9546. }
  9547. }.bind(this));
  9548. messageHandler.on('console_log', function (data) {
  9549. console.log.apply(console, data);
  9550. });
  9551. messageHandler.on('console_error', function (data) {
  9552. console.error.apply(console, data);
  9553. });
  9554. messageHandler.on('ready', function (data) {
  9555. worker.removeEventListener('error', onWorkerError);
  9556. if (this.destroyed) {
  9557. terminateEarly();
  9558. return;
  9559. }
  9560. // worker was destroyed
  9561. try {
  9562. sendTest();
  9563. } catch (e) {
  9564. // We need fallback to a faked worker.
  9565. this._setupFakeWorker();
  9566. }
  9567. }.bind(this));
  9568. var sendTest = function () {
  9569. var postMessageTransfers = getDefaultSetting('postMessageTransfers') && !isPostMessageTransfersDisabled;
  9570. var testObj = new Uint8Array([postMessageTransfers ? 255 : 0]);
  9571. // Some versions of Opera throw a DATA_CLONE_ERR on serializing the
  9572. // typed array. Also, checking if we can use transfers.
  9573. try {
  9574. messageHandler.send('test', testObj, [testObj.buffer]);
  9575. } catch (ex) {
  9576. info('Cannot use postMessage transfers');
  9577. testObj[0] = 0;
  9578. messageHandler.send('test', testObj);
  9579. }
  9580. };
  9581. // It might take time for worker to initialize (especially when AMD
  9582. // loader is used). We will try to send test immediately, and then
  9583. // when 'ready' message will arrive. The worker shall process only
  9584. // first received 'test'.
  9585. sendTest();
  9586. return;
  9587. } catch (e) {
  9588. info('The worker has been disabled.');
  9589. }
  9590. }
  9591. // Either workers are disabled, not supported or have thrown an exception.
  9592. // Thus, we fallback to a faked worker.
  9593. this._setupFakeWorker();
  9594. },
  9595. _setupFakeWorker: function PDFWorker_setupFakeWorker() {
  9596. if (!isWorkerDisabled && !getDefaultSetting('disableWorker')) {
  9597. warn('Setting up fake worker.');
  9598. isWorkerDisabled = true;
  9599. }
  9600. setupFakeWorkerGlobal().then(function (WorkerMessageHandler) {
  9601. if (this.destroyed) {
  9602. this._readyCapability.reject(new Error('Worker was destroyed'));
  9603. return;
  9604. }
  9605. // We cannot turn on proper fake port simulation (this includes
  9606. // structured cloning) when typed arrays are not supported. Relying
  9607. // on a chance that messages will be sent in proper order.
  9608. var isTypedArraysPresent = Uint8Array !== Float32Array;
  9609. var port = new FakeWorkerPort(isTypedArraysPresent);
  9610. this._port = port;
  9611. // All fake workers use the same port, making id unique.
  9612. var id = 'fake' + nextFakeWorkerId++;
  9613. // If the main thread is our worker, setup the handling for the
  9614. // messages -- the main thread sends to it self.
  9615. var workerHandler = new MessageHandler(id + '_worker', id, port);
  9616. WorkerMessageHandler.setup(workerHandler, port);
  9617. var messageHandler = new MessageHandler(id, id + '_worker', port);
  9618. this._messageHandler = messageHandler;
  9619. this._readyCapability.resolve();
  9620. }.bind(this));
  9621. },
  9622. /**
  9623. * Destroys the worker instance.
  9624. */
  9625. destroy: function PDFWorker_destroy() {
  9626. this.destroyed = true;
  9627. if (this._webWorker) {
  9628. // We need to terminate only web worker created resource.
  9629. this._webWorker.terminate();
  9630. this._webWorker = null;
  9631. }
  9632. this._port = null;
  9633. if (this._messageHandler) {
  9634. this._messageHandler.destroy();
  9635. this._messageHandler = null;
  9636. }
  9637. }
  9638. };
  9639. return PDFWorker;
  9640. }();
  9641. /**
  9642. * For internal use only.
  9643. * @ignore
  9644. */
  9645. var WorkerTransport = function WorkerTransportClosure() {
  9646. function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) {
  9647. this.messageHandler = messageHandler;
  9648. this.loadingTask = loadingTask;
  9649. this.pdfDataRangeTransport = pdfDataRangeTransport;
  9650. this.commonObjs = new PDFObjects();
  9651. this.fontLoader = new FontLoader(loadingTask.docId);
  9652. this.destroyed = false;
  9653. this.destroyCapability = null;
  9654. this.pageCache = [];
  9655. this.pagePromises = [];
  9656. this.downloadInfoCapability = createPromiseCapability();
  9657. this.setupMessageHandler();
  9658. }
  9659. WorkerTransport.prototype = {
  9660. destroy: function WorkerTransport_destroy() {
  9661. if (this.destroyCapability) {
  9662. return this.destroyCapability.promise;
  9663. }
  9664. this.destroyed = true;
  9665. this.destroyCapability = createPromiseCapability();
  9666. var waitOn = [];
  9667. // We need to wait for all renderings to be completed, e.g.
  9668. // timeout/rAF can take a long time.
  9669. this.pageCache.forEach(function (page) {
  9670. if (page) {
  9671. waitOn.push(page._destroy());
  9672. }
  9673. });
  9674. this.pageCache = [];
  9675. this.pagePromises = [];
  9676. var self = this;
  9677. // We also need to wait for the worker to finish its long running tasks.
  9678. var terminated = this.messageHandler.sendWithPromise('Terminate', null);
  9679. waitOn.push(terminated);
  9680. Promise.all(waitOn).then(function () {
  9681. self.fontLoader.clear();
  9682. if (self.pdfDataRangeTransport) {
  9683. self.pdfDataRangeTransport.abort();
  9684. self.pdfDataRangeTransport = null;
  9685. }
  9686. if (self.messageHandler) {
  9687. self.messageHandler.destroy();
  9688. self.messageHandler = null;
  9689. }
  9690. self.destroyCapability.resolve();
  9691. }, this.destroyCapability.reject);
  9692. return this.destroyCapability.promise;
  9693. },
  9694. setupMessageHandler: function WorkerTransport_setupMessageHandler() {
  9695. var messageHandler = this.messageHandler;
  9696. function updatePassword(password) {
  9697. messageHandler.send('UpdatePassword', password);
  9698. }
  9699. var pdfDataRangeTransport = this.pdfDataRangeTransport;
  9700. if (pdfDataRangeTransport) {
  9701. pdfDataRangeTransport.addRangeListener(function (begin, chunk) {
  9702. messageHandler.send('OnDataRange', {
  9703. begin: begin,
  9704. chunk: chunk
  9705. });
  9706. });
  9707. pdfDataRangeTransport.addProgressListener(function (loaded) {
  9708. messageHandler.send('OnDataProgress', { loaded: loaded });
  9709. });
  9710. pdfDataRangeTransport.addProgressiveReadListener(function (chunk) {
  9711. messageHandler.send('OnDataRange', { chunk: chunk });
  9712. });
  9713. messageHandler.on('RequestDataRange', function transportDataRange(data) {
  9714. pdfDataRangeTransport.requestDataRange(data.begin, data.end);
  9715. }, this);
  9716. }
  9717. messageHandler.on('GetDoc', function transportDoc(data) {
  9718. var pdfInfo = data.pdfInfo;
  9719. this.numPages = data.pdfInfo.numPages;
  9720. var loadingTask = this.loadingTask;
  9721. var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask);
  9722. this.pdfDocument = pdfDocument;
  9723. loadingTask._capability.resolve(pdfDocument);
  9724. }, this);
  9725. messageHandler.on('NeedPassword', function transportNeedPassword(exception) {
  9726. var loadingTask = this.loadingTask;
  9727. if (loadingTask.onPassword) {
  9728. return loadingTask.onPassword(updatePassword, PasswordResponses.NEED_PASSWORD);
  9729. }
  9730. loadingTask._capability.reject(new PasswordException(exception.message, exception.code));
  9731. }, this);
  9732. messageHandler.on('IncorrectPassword', function transportIncorrectPassword(exception) {
  9733. var loadingTask = this.loadingTask;
  9734. if (loadingTask.onPassword) {
  9735. return loadingTask.onPassword(updatePassword, PasswordResponses.INCORRECT_PASSWORD);
  9736. }
  9737. loadingTask._capability.reject(new PasswordException(exception.message, exception.code));
  9738. }, this);
  9739. messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) {
  9740. this.loadingTask._capability.reject(new InvalidPDFException(exception.message));
  9741. }, this);
  9742. messageHandler.on('MissingPDF', function transportMissingPDF(exception) {
  9743. this.loadingTask._capability.reject(new MissingPDFException(exception.message));
  9744. }, this);
  9745. messageHandler.on('UnexpectedResponse', function transportUnexpectedResponse(exception) {
  9746. this.loadingTask._capability.reject(new UnexpectedResponseException(exception.message, exception.status));
  9747. }, this);
  9748. messageHandler.on('UnknownError', function transportUnknownError(exception) {
  9749. this.loadingTask._capability.reject(new UnknownErrorException(exception.message, exception.details));
  9750. }, this);
  9751. messageHandler.on('DataLoaded', function transportPage(data) {
  9752. this.downloadInfoCapability.resolve(data);
  9753. }, this);
  9754. messageHandler.on('PDFManagerReady', function transportPage(data) {
  9755. if (this.pdfDataRangeTransport) {
  9756. this.pdfDataRangeTransport.transportReady();
  9757. }
  9758. }, this);
  9759. messageHandler.on('StartRenderPage', function transportRender(data) {
  9760. if (this.destroyed) {
  9761. return;
  9762. }
  9763. // Ignore any pending requests if the worker was terminated.
  9764. var page = this.pageCache[data.pageIndex];
  9765. page.stats.timeEnd('Page Request');
  9766. page._startRenderPage(data.transparency, data.intent);
  9767. }, this);
  9768. messageHandler.on('RenderPageChunk', function transportRender(data) {
  9769. if (this.destroyed) {
  9770. return;
  9771. }
  9772. // Ignore any pending requests if the worker was terminated.
  9773. var page = this.pageCache[data.pageIndex];
  9774. page._renderPageChunk(data.operatorList, data.intent);
  9775. }, this);
  9776. messageHandler.on('commonobj', function transportObj(data) {
  9777. if (this.destroyed) {
  9778. return;
  9779. }
  9780. // Ignore any pending requests if the worker was terminated.
  9781. var id = data[0];
  9782. var type = data[1];
  9783. if (this.commonObjs.hasData(id)) {
  9784. return;
  9785. }
  9786. switch (type) {
  9787. case 'Font':
  9788. var exportedData = data[2];
  9789. if ('error' in exportedData) {
  9790. var exportedError = exportedData.error;
  9791. warn('Error during font loading: ' + exportedError);
  9792. this.commonObjs.resolve(id, exportedError);
  9793. break;
  9794. }
  9795. var fontRegistry = null;
  9796. if (getDefaultSetting('pdfBug') && globalScope.FontInspector && globalScope['FontInspector'].enabled) {
  9797. fontRegistry = {
  9798. registerFont: function (font, url) {
  9799. globalScope['FontInspector'].fontAdded(font, url);
  9800. }
  9801. };
  9802. }
  9803. var font = new FontFaceObject(exportedData, {
  9804. isEvalSuported: getDefaultSetting('isEvalSupported'),
  9805. disableFontFace: getDefaultSetting('disableFontFace'),
  9806. fontRegistry: fontRegistry
  9807. });
  9808. this.fontLoader.bind([font], function fontReady(fontObjs) {
  9809. this.commonObjs.resolve(id, font);
  9810. }.bind(this));
  9811. break;
  9812. case 'FontPath':
  9813. this.commonObjs.resolve(id, data[2]);
  9814. break;
  9815. default:
  9816. error('Got unknown common object type ' + type);
  9817. }
  9818. }, this);
  9819. messageHandler.on('obj', function transportObj(data) {
  9820. if (this.destroyed) {
  9821. return;
  9822. }
  9823. // Ignore any pending requests if the worker was terminated.
  9824. var id = data[0];
  9825. var pageIndex = data[1];
  9826. var type = data[2];
  9827. var pageProxy = this.pageCache[pageIndex];
  9828. var imageData;
  9829. if (pageProxy.objs.hasData(id)) {
  9830. return;
  9831. }
  9832. switch (type) {
  9833. case 'JpegStream':
  9834. imageData = data[3];
  9835. loadJpegStream(id, imageData, pageProxy.objs);
  9836. break;
  9837. case 'Image':
  9838. imageData = data[3];
  9839. pageProxy.objs.resolve(id, imageData);
  9840. // heuristics that will allow not to store large data
  9841. var MAX_IMAGE_SIZE_TO_STORE = 8000000;
  9842. if (imageData && 'data' in imageData && imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) {
  9843. pageProxy.cleanupAfterRender = true;
  9844. }
  9845. break;
  9846. default:
  9847. error('Got unknown object type ' + type);
  9848. }
  9849. }, this);
  9850. messageHandler.on('DocProgress', function transportDocProgress(data) {
  9851. if (this.destroyed) {
  9852. return;
  9853. }
  9854. // Ignore any pending requests if the worker was terminated.
  9855. var loadingTask = this.loadingTask;
  9856. if (loadingTask.onProgress) {
  9857. loadingTask.onProgress({
  9858. loaded: data.loaded,
  9859. total: data.total
  9860. });
  9861. }
  9862. }, this);
  9863. messageHandler.on('PageError', function transportError(data) {
  9864. if (this.destroyed) {
  9865. return;
  9866. }
  9867. // Ignore any pending requests if the worker was terminated.
  9868. var page = this.pageCache[data.pageNum - 1];
  9869. var intentState = page.intentStates[data.intent];
  9870. if (intentState.displayReadyCapability) {
  9871. intentState.displayReadyCapability.reject(data.error);
  9872. } else {
  9873. error(data.error);
  9874. }
  9875. if (intentState.operatorList) {
  9876. // Mark operator list as complete.
  9877. intentState.operatorList.lastChunk = true;
  9878. for (var i = 0; i < intentState.renderTasks.length; i++) {
  9879. intentState.renderTasks[i].operatorListChanged();
  9880. }
  9881. }
  9882. }, this);
  9883. messageHandler.on('UnsupportedFeature', function transportUnsupportedFeature(data) {
  9884. if (this.destroyed) {
  9885. return;
  9886. }
  9887. // Ignore any pending requests if the worker was terminated.
  9888. var featureId = data.featureId;
  9889. var loadingTask = this.loadingTask;
  9890. if (loadingTask.onUnsupportedFeature) {
  9891. loadingTask.onUnsupportedFeature(featureId);
  9892. }
  9893. _UnsupportedManager.notify(featureId);
  9894. }, this);
  9895. messageHandler.on('JpegDecode', function (data) {
  9896. if (this.destroyed) {
  9897. return Promise.reject(new Error('Worker was destroyed'));
  9898. }
  9899. var imageUrl = data[0];
  9900. var components = data[1];
  9901. if (components !== 3 && components !== 1) {
  9902. return Promise.reject(new Error('Only 3 components or 1 component can be returned'));
  9903. }
  9904. return new Promise(function (resolve, reject) {
  9905. var img = new Image();
  9906. img.onload = function () {
  9907. var width = img.width;
  9908. var height = img.height;
  9909. var size = width * height;
  9910. var rgbaLength = size * 4;
  9911. var buf = new Uint8Array(size * components);
  9912. var tmpCanvas = createScratchCanvas(width, height);
  9913. var tmpCtx = tmpCanvas.getContext('2d');
  9914. tmpCtx.drawImage(img, 0, 0);
  9915. var data = tmpCtx.getImageData(0, 0, width, height).data;
  9916. var i, j;
  9917. if (components === 3) {
  9918. for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) {
  9919. buf[j] = data[i];
  9920. buf[j + 1] = data[i + 1];
  9921. buf[j + 2] = data[i + 2];
  9922. }
  9923. } else if (components === 1) {
  9924. for (i = 0, j = 0; i < rgbaLength; i += 4, j++) {
  9925. buf[j] = data[i];
  9926. }
  9927. }
  9928. resolve({
  9929. data: buf,
  9930. width: width,
  9931. height: height
  9932. });
  9933. };
  9934. img.onerror = function () {
  9935. reject(new Error('JpegDecode failed to load image'));
  9936. };
  9937. img.src = imageUrl;
  9938. });
  9939. }, this);
  9940. },
  9941. getData: function WorkerTransport_getData() {
  9942. return this.messageHandler.sendWithPromise('GetData', null);
  9943. },
  9944. getPage: function WorkerTransport_getPage(pageNumber, capability) {
  9945. if (!isInt(pageNumber) || pageNumber <= 0 || pageNumber > this.numPages) {
  9946. return Promise.reject(new Error('Invalid page request'));
  9947. }
  9948. var pageIndex = pageNumber - 1;
  9949. if (pageIndex in this.pagePromises) {
  9950. return this.pagePromises[pageIndex];
  9951. }
  9952. var promise = this.messageHandler.sendWithPromise('GetPage', { pageIndex: pageIndex }).then(function (pageInfo) {
  9953. if (this.destroyed) {
  9954. throw new Error('Transport destroyed');
  9955. }
  9956. var page = new PDFPageProxy(pageIndex, pageInfo, this);
  9957. this.pageCache[pageIndex] = page;
  9958. return page;
  9959. }.bind(this));
  9960. this.pagePromises[pageIndex] = promise;
  9961. return promise;
  9962. },
  9963. getPageIndex: function WorkerTransport_getPageIndexByRef(ref) {
  9964. return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref }).catch(function (reason) {
  9965. return Promise.reject(new Error(reason));
  9966. });
  9967. },
  9968. getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) {
  9969. return this.messageHandler.sendWithPromise('GetAnnotations', {
  9970. pageIndex: pageIndex,
  9971. intent: intent
  9972. });
  9973. },
  9974. getDestinations: function WorkerTransport_getDestinations() {
  9975. return this.messageHandler.sendWithPromise('GetDestinations', null);
  9976. },
  9977. getDestination: function WorkerTransport_getDestination(id) {
  9978. return this.messageHandler.sendWithPromise('GetDestination', { id: id });
  9979. },
  9980. getPageLabels: function WorkerTransport_getPageLabels() {
  9981. return this.messageHandler.sendWithPromise('GetPageLabels', null);
  9982. },
  9983. getAttachments: function WorkerTransport_getAttachments() {
  9984. return this.messageHandler.sendWithPromise('GetAttachments', null);
  9985. },
  9986. getJavaScript: function WorkerTransport_getJavaScript() {
  9987. return this.messageHandler.sendWithPromise('GetJavaScript', null);
  9988. },
  9989. getOutline: function WorkerTransport_getOutline() {
  9990. return this.messageHandler.sendWithPromise('GetOutline', null);
  9991. },
  9992. getMetadata: function WorkerTransport_getMetadata() {
  9993. return this.messageHandler.sendWithPromise('GetMetadata', null).then(function transportMetadata(results) {
  9994. return {
  9995. info: results[0],
  9996. metadata: results[1] ? new Metadata(results[1]) : null
  9997. };
  9998. });
  9999. },
  10000. getStats: function WorkerTransport_getStats() {
  10001. return this.messageHandler.sendWithPromise('GetStats', null);
  10002. },
  10003. startCleanup: function WorkerTransport_startCleanup() {
  10004. this.messageHandler.sendWithPromise('Cleanup', null).then(function endCleanup() {
  10005. for (var i = 0, ii = this.pageCache.length; i < ii; i++) {
  10006. var page = this.pageCache[i];
  10007. if (page) {
  10008. page.cleanup();
  10009. }
  10010. }
  10011. this.commonObjs.clear();
  10012. this.fontLoader.clear();
  10013. }.bind(this));
  10014. }
  10015. };
  10016. return WorkerTransport;
  10017. }();
  10018. /**
  10019. * A PDF document and page is built of many objects. E.g. there are objects
  10020. * for fonts, images, rendering code and such. These objects might get processed
  10021. * inside of a worker. The `PDFObjects` implements some basic functions to
  10022. * manage these objects.
  10023. * @ignore
  10024. */
  10025. var PDFObjects = function PDFObjectsClosure() {
  10026. function PDFObjects() {
  10027. this.objs = Object.create(null);
  10028. }
  10029. PDFObjects.prototype = {
  10030. /**
  10031. * Internal function.
  10032. * Ensures there is an object defined for `objId`.
  10033. */
  10034. ensureObj: function PDFObjects_ensureObj(objId) {
  10035. if (this.objs[objId]) {
  10036. return this.objs[objId];
  10037. }
  10038. var obj = {
  10039. capability: createPromiseCapability(),
  10040. data: null,
  10041. resolved: false
  10042. };
  10043. this.objs[objId] = obj;
  10044. return obj;
  10045. },
  10046. /**
  10047. * If called *without* callback, this returns the data of `objId` but the
  10048. * object needs to be resolved. If it isn't, this function throws.
  10049. *
  10050. * If called *with* a callback, the callback is called with the data of the
  10051. * object once the object is resolved. That means, if you call this
  10052. * function and the object is already resolved, the callback gets called
  10053. * right away.
  10054. */
  10055. get: function PDFObjects_get(objId, callback) {
  10056. // If there is a callback, then the get can be async and the object is
  10057. // not required to be resolved right now
  10058. if (callback) {
  10059. this.ensureObj(objId).capability.promise.then(callback);
  10060. return null;
  10061. }
  10062. // If there isn't a callback, the user expects to get the resolved data
  10063. // directly.
  10064. var obj = this.objs[objId];
  10065. // If there isn't an object yet or the object isn't resolved, then the
  10066. // data isn't ready yet!
  10067. if (!obj || !obj.resolved) {
  10068. error('Requesting object that isn\'t resolved yet ' + objId);
  10069. }
  10070. return obj.data;
  10071. },
  10072. /**
  10073. * Resolves the object `objId` with optional `data`.
  10074. */
  10075. resolve: function PDFObjects_resolve(objId, data) {
  10076. var obj = this.ensureObj(objId);
  10077. obj.resolved = true;
  10078. obj.data = data;
  10079. obj.capability.resolve(data);
  10080. },
  10081. isResolved: function PDFObjects_isResolved(objId) {
  10082. var objs = this.objs;
  10083. if (!objs[objId]) {
  10084. return false;
  10085. } else {
  10086. return objs[objId].resolved;
  10087. }
  10088. },
  10089. hasData: function PDFObjects_hasData(objId) {
  10090. return this.isResolved(objId);
  10091. },
  10092. /**
  10093. * Returns the data of `objId` if object exists, null otherwise.
  10094. */
  10095. getData: function PDFObjects_getData(objId) {
  10096. var objs = this.objs;
  10097. if (!objs[objId] || !objs[objId].resolved) {
  10098. return null;
  10099. } else {
  10100. return objs[objId].data;
  10101. }
  10102. },
  10103. clear: function PDFObjects_clear() {
  10104. this.objs = Object.create(null);
  10105. }
  10106. };
  10107. return PDFObjects;
  10108. }();
  10109. /**
  10110. * Allows controlling of the rendering tasks.
  10111. * @class
  10112. * @alias RenderTask
  10113. */
  10114. var RenderTask = function RenderTaskClosure() {
  10115. function RenderTask(internalRenderTask) {
  10116. this._internalRenderTask = internalRenderTask;
  10117. /**
  10118. * Callback for incremental rendering -- a function that will be called
  10119. * each time the rendering is paused. To continue rendering call the
  10120. * function that is the first argument to the callback.
  10121. * @type {function}
  10122. */
  10123. this.onContinue = null;
  10124. }
  10125. RenderTask.prototype = /** @lends RenderTask.prototype */
  10126. {
  10127. /**
  10128. * Promise for rendering task completion.
  10129. * @return {Promise}
  10130. */
  10131. get promise() {
  10132. return this._internalRenderTask.capability.promise;
  10133. },
  10134. /**
  10135. * Cancels the rendering task. If the task is currently rendering it will
  10136. * not be cancelled until graphics pauses with a timeout. The promise that
  10137. * this object extends will resolved when cancelled.
  10138. */
  10139. cancel: function RenderTask_cancel() {
  10140. this._internalRenderTask.cancel();
  10141. },
  10142. /**
  10143. * Registers callbacks to indicate the rendering task completion.
  10144. *
  10145. * @param {function} onFulfilled The callback for the rendering completion.
  10146. * @param {function} onRejected The callback for the rendering failure.
  10147. * @return {Promise} A promise that is resolved after the onFulfilled or
  10148. * onRejected callback.
  10149. */
  10150. then: function RenderTask_then(onFulfilled, onRejected) {
  10151. return this.promise.then.apply(this.promise, arguments);
  10152. }
  10153. };
  10154. return RenderTask;
  10155. }();
  10156. /**
  10157. * For internal use only.
  10158. * @ignore
  10159. */
  10160. var InternalRenderTask = function InternalRenderTaskClosure() {
  10161. function InternalRenderTask(callback, params, objs, commonObjs, operatorList, pageNumber) {
  10162. this.callback = callback;
  10163. this.params = params;
  10164. this.objs = objs;
  10165. this.commonObjs = commonObjs;
  10166. this.operatorListIdx = null;
  10167. this.operatorList = operatorList;
  10168. this.pageNumber = pageNumber;
  10169. this.running = false;
  10170. this.graphicsReadyCallback = null;
  10171. this.graphicsReady = false;
  10172. this.useRequestAnimationFrame = false;
  10173. this.cancelled = false;
  10174. this.capability = createPromiseCapability();
  10175. this.task = new RenderTask(this);
  10176. // caching this-bound methods
  10177. this._continueBound = this._continue.bind(this);
  10178. this._scheduleNextBound = this._scheduleNext.bind(this);
  10179. this._nextBound = this._next.bind(this);
  10180. }
  10181. InternalRenderTask.prototype = {
  10182. initializeGraphics: function InternalRenderTask_initializeGraphics(transparency) {
  10183. if (this.cancelled) {
  10184. return;
  10185. }
  10186. if (getDefaultSetting('pdfBug') && globalScope.StepperManager && globalScope.StepperManager.enabled) {
  10187. this.stepper = globalScope.StepperManager.create(this.pageNumber - 1);
  10188. this.stepper.init(this.operatorList);
  10189. this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
  10190. }
  10191. var params = this.params;
  10192. this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs, this.objs, params.imageLayer);
  10193. this.gfx.beginDrawing(params.transform, params.viewport, transparency);
  10194. this.operatorListIdx = 0;
  10195. this.graphicsReady = true;
  10196. if (this.graphicsReadyCallback) {
  10197. this.graphicsReadyCallback();
  10198. }
  10199. },
  10200. cancel: function InternalRenderTask_cancel() {
  10201. this.running = false;
  10202. this.cancelled = true;
  10203. this.callback('cancelled');
  10204. },
  10205. operatorListChanged: function InternalRenderTask_operatorListChanged() {
  10206. if (!this.graphicsReady) {
  10207. if (!this.graphicsReadyCallback) {
  10208. this.graphicsReadyCallback = this._continueBound;
  10209. }
  10210. return;
  10211. }
  10212. if (this.stepper) {
  10213. this.stepper.updateOperatorList(this.operatorList);
  10214. }
  10215. if (this.running) {
  10216. return;
  10217. }
  10218. this._continue();
  10219. },
  10220. _continue: function InternalRenderTask__continue() {
  10221. this.running = true;
  10222. if (this.cancelled) {
  10223. return;
  10224. }
  10225. if (this.task.onContinue) {
  10226. this.task.onContinue.call(this.task, this._scheduleNextBound);
  10227. } else {
  10228. this._scheduleNext();
  10229. }
  10230. },
  10231. _scheduleNext: function InternalRenderTask__scheduleNext() {
  10232. if (this.useRequestAnimationFrame && typeof window !== 'undefined') {
  10233. window.requestAnimationFrame(this._nextBound);
  10234. } else {
  10235. Promise.resolve(undefined).then(this._nextBound);
  10236. }
  10237. },
  10238. _next: function InternalRenderTask__next() {
  10239. if (this.cancelled) {
  10240. return;
  10241. }
  10242. this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
  10243. if (this.operatorListIdx === this.operatorList.argsArray.length) {
  10244. this.running = false;
  10245. if (this.operatorList.lastChunk) {
  10246. this.gfx.endDrawing();
  10247. this.callback();
  10248. }
  10249. }
  10250. }
  10251. };
  10252. return InternalRenderTask;
  10253. }();
  10254. /**
  10255. * (Deprecated) Global observer of unsupported feature usages. Use
  10256. * onUnsupportedFeature callback of the {PDFDocumentLoadingTask} instance.
  10257. */
  10258. var _UnsupportedManager = function UnsupportedManagerClosure() {
  10259. var listeners = [];
  10260. return {
  10261. listen: function (cb) {
  10262. deprecated('Global UnsupportedManager.listen is used: ' + ' use PDFDocumentLoadingTask.onUnsupportedFeature instead');
  10263. listeners.push(cb);
  10264. },
  10265. notify: function (featureId) {
  10266. for (var i = 0, ii = listeners.length; i < ii; i++) {
  10267. listeners[i](featureId);
  10268. }
  10269. }
  10270. };
  10271. }();
  10272. if (typeof pdfjsVersion !== 'undefined') {
  10273. exports.version = pdfjsVersion;
  10274. }
  10275. if (typeof pdfjsBuild !== 'undefined') {
  10276. exports.build = pdfjsBuild;
  10277. }
  10278. exports.getDocument = getDocument;
  10279. exports.PDFDataRangeTransport = PDFDataRangeTransport;
  10280. exports.PDFWorker = PDFWorker;
  10281. exports.PDFDocumentProxy = PDFDocumentProxy;
  10282. exports.PDFPageProxy = PDFPageProxy;
  10283. exports._UnsupportedManager = _UnsupportedManager;
  10284. }));
  10285. (function (root, factory) {
  10286. factory(root.pdfjsDisplayGlobal = {}, root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils, root.pdfjsDisplayAPI, root.pdfjsDisplayAnnotationLayer, root.pdfjsDisplayTextLayer, root.pdfjsDisplayMetadata, root.pdfjsDisplaySVG);
  10287. }(this, function (exports, sharedUtil, displayDOMUtils, displayAPI, displayAnnotationLayer, displayTextLayer, displayMetadata, displaySVG) {
  10288. var globalScope = sharedUtil.globalScope;
  10289. var deprecated = sharedUtil.deprecated;
  10290. var warn = sharedUtil.warn;
  10291. var LinkTarget = displayDOMUtils.LinkTarget;
  10292. var isWorker = typeof window === 'undefined';
  10293. // The global PDFJS object is now deprecated and will not be supported in
  10294. // the future. The members below are maintained for backward compatibility
  10295. // and shall not be extended or modified. If the global.js is included as
  10296. // a module, we will create a global PDFJS object instance or use existing.
  10297. if (!globalScope.PDFJS) {
  10298. globalScope.PDFJS = {};
  10299. }
  10300. var PDFJS = globalScope.PDFJS;
  10301. if (typeof pdfjsVersion !== 'undefined') {
  10302. PDFJS.version = pdfjsVersion;
  10303. }
  10304. if (typeof pdfjsBuild !== 'undefined') {
  10305. PDFJS.build = pdfjsBuild;
  10306. }
  10307. PDFJS.pdfBug = false;
  10308. if (PDFJS.verbosity !== undefined) {
  10309. sharedUtil.setVerbosityLevel(PDFJS.verbosity);
  10310. }
  10311. delete PDFJS.verbosity;
  10312. Object.defineProperty(PDFJS, 'verbosity', {
  10313. get: function () {
  10314. return sharedUtil.getVerbosityLevel();
  10315. },
  10316. set: function (level) {
  10317. sharedUtil.setVerbosityLevel(level);
  10318. },
  10319. enumerable: true,
  10320. configurable: true
  10321. });
  10322. PDFJS.VERBOSITY_LEVELS = sharedUtil.VERBOSITY_LEVELS;
  10323. PDFJS.OPS = sharedUtil.OPS;
  10324. PDFJS.UNSUPPORTED_FEATURES = sharedUtil.UNSUPPORTED_FEATURES;
  10325. PDFJS.isValidUrl = sharedUtil.isValidUrl;
  10326. PDFJS.shadow = sharedUtil.shadow;
  10327. PDFJS.createBlob = sharedUtil.createBlob;
  10328. PDFJS.createObjectURL = function PDFJS_createObjectURL(data, contentType) {
  10329. return sharedUtil.createObjectURL(data, contentType, PDFJS.disableCreateObjectURL);
  10330. };
  10331. Object.defineProperty(PDFJS, 'isLittleEndian', {
  10332. configurable: true,
  10333. get: function PDFJS_isLittleEndian() {
  10334. var value = sharedUtil.isLittleEndian();
  10335. return sharedUtil.shadow(PDFJS, 'isLittleEndian', value);
  10336. }
  10337. });
  10338. PDFJS.removeNullCharacters = sharedUtil.removeNullCharacters;
  10339. PDFJS.PasswordResponses = sharedUtil.PasswordResponses;
  10340. PDFJS.PasswordException = sharedUtil.PasswordException;
  10341. PDFJS.UnknownErrorException = sharedUtil.UnknownErrorException;
  10342. PDFJS.InvalidPDFException = sharedUtil.InvalidPDFException;
  10343. PDFJS.MissingPDFException = sharedUtil.MissingPDFException;
  10344. PDFJS.UnexpectedResponseException = sharedUtil.UnexpectedResponseException;
  10345. PDFJS.Util = sharedUtil.Util;
  10346. PDFJS.PageViewport = sharedUtil.PageViewport;
  10347. PDFJS.createPromiseCapability = sharedUtil.createPromiseCapability;
  10348. /**
  10349. * The maximum allowed image size in total pixels e.g. width * height. Images
  10350. * above this value will not be drawn. Use -1 for no limit.
  10351. * @var {number}
  10352. */
  10353. PDFJS.maxImageSize = PDFJS.maxImageSize === undefined ? -1 : PDFJS.maxImageSize;
  10354. /**
  10355. * The url of where the predefined Adobe CMaps are located. Include trailing
  10356. * slash.
  10357. * @var {string}
  10358. */
  10359. PDFJS.cMapUrl = PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl;
  10360. /**
  10361. * Specifies if CMaps are binary packed.
  10362. * @var {boolean}
  10363. */
  10364. PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked;
  10365. /**
  10366. * By default fonts are converted to OpenType fonts and loaded via font face
  10367. * rules. If disabled, the font will be rendered using a built in font
  10368. * renderer that constructs the glyphs with primitive path commands.
  10369. * @var {boolean}
  10370. */
  10371. PDFJS.disableFontFace = PDFJS.disableFontFace === undefined ? false : PDFJS.disableFontFace;
  10372. /**
  10373. * Path for image resources, mainly for annotation icons. Include trailing
  10374. * slash.
  10375. * @var {string}
  10376. */
  10377. PDFJS.imageResourcesPath = PDFJS.imageResourcesPath === undefined ? '' : PDFJS.imageResourcesPath;
  10378. /**
  10379. * Disable the web worker and run all code on the main thread. This will
  10380. * happen automatically if the browser doesn't support workers or sending
  10381. * typed arrays to workers.
  10382. * @var {boolean}
  10383. */
  10384. PDFJS.disableWorker = PDFJS.disableWorker === undefined ? false : PDFJS.disableWorker;
  10385. /**
  10386. * Path and filename of the worker file. Required when the worker is enabled
  10387. * in development mode. If unspecified in the production build, the worker
  10388. * will be loaded based on the location of the pdf.js file. It is recommended
  10389. * that the workerSrc is set in a custom application to prevent issues caused
  10390. * by third-party frameworks and libraries.
  10391. * @var {string}
  10392. */
  10393. PDFJS.workerSrc = PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc;
  10394. /**
  10395. * Disable range request loading of PDF files. When enabled and if the server
  10396. * supports partial content requests then the PDF will be fetched in chunks.
  10397. * Enabled (false) by default.
  10398. * @var {boolean}
  10399. */
  10400. PDFJS.disableRange = PDFJS.disableRange === undefined ? false : PDFJS.disableRange;
  10401. /**
  10402. * Disable streaming of PDF file data. By default PDF.js attempts to load PDF
  10403. * in chunks. This default behavior can be disabled.
  10404. * @var {boolean}
  10405. */
  10406. PDFJS.disableStream = PDFJS.disableStream === undefined ? false : PDFJS.disableStream;
  10407. /**
  10408. * Disable pre-fetching of PDF file data. When range requests are enabled
  10409. * PDF.js will automatically keep fetching more data even if it isn't needed
  10410. * to display the current page. This default behavior can be disabled.
  10411. *
  10412. * NOTE: It is also necessary to disable streaming, see above,
  10413. * in order for disabling of pre-fetching to work correctly.
  10414. * @var {boolean}
  10415. */
  10416. PDFJS.disableAutoFetch = PDFJS.disableAutoFetch === undefined ? false : PDFJS.disableAutoFetch;
  10417. /**
  10418. * Enables special hooks for debugging PDF.js.
  10419. * @var {boolean}
  10420. */
  10421. PDFJS.pdfBug = PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug;
  10422. /**
  10423. * Enables transfer usage in postMessage for ArrayBuffers.
  10424. * @var {boolean}
  10425. */
  10426. PDFJS.postMessageTransfers = PDFJS.postMessageTransfers === undefined ? true : PDFJS.postMessageTransfers;
  10427. /**
  10428. * Disables URL.createObjectURL usage.
  10429. * @var {boolean}
  10430. */
  10431. PDFJS.disableCreateObjectURL = PDFJS.disableCreateObjectURL === undefined ? false : PDFJS.disableCreateObjectURL;
  10432. /**
  10433. * Disables WebGL usage.
  10434. * @var {boolean}
  10435. */
  10436. PDFJS.disableWebGL = PDFJS.disableWebGL === undefined ? true : PDFJS.disableWebGL;
  10437. /**
  10438. * Specifies the |target| attribute for external links.
  10439. * The constants from PDFJS.LinkTarget should be used:
  10440. * - NONE [default]
  10441. * - SELF
  10442. * - BLANK
  10443. * - PARENT
  10444. * - TOP
  10445. * @var {number}
  10446. */
  10447. PDFJS.externalLinkTarget = PDFJS.externalLinkTarget === undefined ? LinkTarget.NONE : PDFJS.externalLinkTarget;
  10448. /**
  10449. * Specifies the |rel| attribute for external links. Defaults to stripping
  10450. * the referrer.
  10451. * @var {string}
  10452. */
  10453. PDFJS.externalLinkRel = PDFJS.externalLinkRel === undefined ? 'noreferrer' : PDFJS.externalLinkRel;
  10454. /**
  10455. * Determines if we can eval strings as JS. Primarily used to improve
  10456. * performance for font rendering.
  10457. * @var {boolean}
  10458. */
  10459. PDFJS.isEvalSupported = PDFJS.isEvalSupported === undefined ? true : PDFJS.isEvalSupported;
  10460. var savedOpenExternalLinksInNewWindow = PDFJS.openExternalLinksInNewWindow;
  10461. delete PDFJS.openExternalLinksInNewWindow;
  10462. Object.defineProperty(PDFJS, 'openExternalLinksInNewWindow', {
  10463. get: function () {
  10464. return PDFJS.externalLinkTarget === LinkTarget.BLANK;
  10465. },
  10466. set: function (value) {
  10467. if (value) {
  10468. deprecated('PDFJS.openExternalLinksInNewWindow, please use ' + '"PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.');
  10469. }
  10470. if (PDFJS.externalLinkTarget !== LinkTarget.NONE) {
  10471. warn('PDFJS.externalLinkTarget is already initialized');
  10472. return;
  10473. }
  10474. PDFJS.externalLinkTarget = value ? LinkTarget.BLANK : LinkTarget.NONE;
  10475. },
  10476. enumerable: true,
  10477. configurable: true
  10478. });
  10479. if (savedOpenExternalLinksInNewWindow) {
  10480. /**
  10481. * (Deprecated) Opens external links in a new window if enabled.
  10482. * The default behavior opens external links in the PDF.js window.
  10483. *
  10484. * NOTE: This property has been deprecated, please use
  10485. * `PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK` instead.
  10486. * @var {boolean}
  10487. */
  10488. PDFJS.openExternalLinksInNewWindow = savedOpenExternalLinksInNewWindow;
  10489. }
  10490. PDFJS.getDocument = displayAPI.getDocument;
  10491. PDFJS.PDFDataRangeTransport = displayAPI.PDFDataRangeTransport;
  10492. PDFJS.PDFWorker = displayAPI.PDFWorker;
  10493. Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
  10494. configurable: true,
  10495. get: function PDFJS_hasCanvasTypedArrays() {
  10496. var value = displayDOMUtils.hasCanvasTypedArrays();
  10497. return sharedUtil.shadow(PDFJS, 'hasCanvasTypedArrays', value);
  10498. }
  10499. });
  10500. PDFJS.CustomStyle = displayDOMUtils.CustomStyle;
  10501. PDFJS.LinkTarget = LinkTarget;
  10502. PDFJS.addLinkAttributes = displayDOMUtils.addLinkAttributes;
  10503. PDFJS.getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl;
  10504. PDFJS.isExternalLinkTargetSet = displayDOMUtils.isExternalLinkTargetSet;
  10505. PDFJS.AnnotationLayer = displayAnnotationLayer.AnnotationLayer;
  10506. PDFJS.renderTextLayer = displayTextLayer.renderTextLayer;
  10507. PDFJS.Metadata = displayMetadata.Metadata;
  10508. PDFJS.SVGGraphics = displaySVG.SVGGraphics;
  10509. PDFJS.UnsupportedManager = displayAPI._UnsupportedManager;
  10510. exports.globalScope = globalScope;
  10511. exports.isWorker = isWorker;
  10512. exports.PDFJS = globalScope.PDFJS;
  10513. }));
  10514. }.call(pdfjsLibs));
  10515. exports.PDFJS = pdfjsLibs.pdfjsDisplayGlobal.PDFJS;
  10516. exports.build = pdfjsLibs.pdfjsDisplayAPI.build;
  10517. exports.version = pdfjsLibs.pdfjsDisplayAPI.version;
  10518. exports.getDocument = pdfjsLibs.pdfjsDisplayAPI.getDocument;
  10519. exports.PDFDataRangeTransport = pdfjsLibs.pdfjsDisplayAPI.PDFDataRangeTransport;
  10520. exports.PDFWorker = pdfjsLibs.pdfjsDisplayAPI.PDFWorker;
  10521. exports.renderTextLayer = pdfjsLibs.pdfjsDisplayTextLayer.renderTextLayer;
  10522. exports.AnnotationLayer = pdfjsLibs.pdfjsDisplayAnnotationLayer.AnnotationLayer;
  10523. exports.CustomStyle = pdfjsLibs.pdfjsDisplayDOMUtils.CustomStyle;
  10524. exports.PasswordResponses = pdfjsLibs.pdfjsSharedUtil.PasswordResponses;
  10525. exports.InvalidPDFException = pdfjsLibs.pdfjsSharedUtil.InvalidPDFException;
  10526. exports.MissingPDFException = pdfjsLibs.pdfjsSharedUtil.MissingPDFException;
  10527. exports.SVGGraphics = pdfjsLibs.pdfjsDisplaySVG.SVGGraphics;
  10528. exports.UnexpectedResponseException = pdfjsLibs.pdfjsSharedUtil.UnexpectedResponseException;
  10529. exports.OPS = pdfjsLibs.pdfjsSharedUtil.OPS;
  10530. exports.UNSUPPORTED_FEATURES = pdfjsLibs.pdfjsSharedUtil.UNSUPPORTED_FEATURES;
  10531. exports.isValidUrl = pdfjsLibs.pdfjsSharedUtil.isValidUrl;
  10532. exports.createObjectURL = pdfjsLibs.pdfjsSharedUtil.createObjectURL;
  10533. exports.removeNullCharacters = pdfjsLibs.pdfjsSharedUtil.removeNullCharacters;
  10534. exports.shadow = pdfjsLibs.pdfjsSharedUtil.shadow;
  10535. exports.createBlob = pdfjsLibs.pdfjsSharedUtil.createBlob;
  10536. exports.getFilenameFromUrl = pdfjsLibs.pdfjsDisplayDOMUtils.getFilenameFromUrl;
  10537. exports.addLinkAttributes = pdfjsLibs.pdfjsDisplayDOMUtils.addLinkAttributes;
  10538. }));